Examples
Practical examples। Live demos।
कोई example चुनिए और फ़ुल-स्क्रीन में खोलिए: live preview और source code साथ-साथ।
कोई example चुनिए और फ़ुल-स्क्रीन में खोलिए: live preview और source code साथ-साथ।
image रंग बताने वाली 1024 strings का एक सादा array है। हर cell उसी से अपना रंग पढ़ता है। stroke array बदलता है और update() call करता है। stroke पूरा होने पर editor slice() से एक copy रख लेता है। undo, redo और history (वह भी एक list() है) का हर step पुराना array वापस रख देता है: न store, न immutable data।
// app.ts: the editor. The picture is one plain array of colors, and each of // its 1024 cells reads its color from that array. A stroke writes into the // array and calls update(); when it ends, history.ts keeps a copy. Undo, redo // and the history panel only put an older copy back. import "nuclo"; import { SIZE, at, blank, commit, fill, get, history, jump, line, load, mushroom, pixels, redo, undo, type Snapshot } from "./history.ts"; import { s } from "./styles.ts"; const TOOLS = [ { name: "Pencil", key: "B" }, { name: "Eraser", key: "E" }, { name: "Fill", key: "G" }, { name: "Picker", key: "I" }, ] as const; type Tool = (typeof TOOLS)[number]["name"]; const PALETTE = ["#1f2937", "#6b7280", "#d1d5db", "#ffffff", "#ef4444", "#f97316", "#facc15", "#fde68a", "#22c55e", "#15803d", "#14b8a6", "#38bdf8", "#2563eb", "#8b5cf6", "#ec4899", "#92400e"]; let tool: Tool = "Pencil"; let color = "#ef4444"; let stroke: { tool: Tool; ink: string; x: number; y: number; changed: number } | null = null; // a pencil or eraser drag // Picking a color means painting with it next: leave the eraser and the picker. function choose(c: string) { color = c; if (tool !== "Fill") tool = "Pencil"; } function replace(label: string, next: string[]) { load(next); commit(label); update(); } // The cell under the pointer, from coordinates rather than from the event // target: with pointer capture, a drag keeps reporting to the canvas, even // outside it (those cells are off the picture and paint nothing). function cellAt(e: PointerEvent, el: HTMLElement) { const r = el.getBoundingClientRect(); return [Math.floor(((e.clientX - r.left) / r.width) * SIZE), Math.floor(((e.clientY - r.top) / r.height) * SIZE)]; } function Canvas() { return div( s.canvas, { role: "img", "aria-label": `Canvas, ${SIZE} by ${SIZE} pixels` }, { onPointerDown: (e) => { if (e.button !== 0) return; const [x, y] = cellAt(e, e.currentTarget); if (tool === "Picker") { const c = get(x, y); if (c) choose(c); } else if (tool === "Fill") commit(`Fill · ${fill(x, y, color)} px`); else { e.currentTarget.setPointerCapture(e.pointerId); const ink = tool === "Eraser" ? "" : color; stroke = { tool, ink, x, y, changed: line(x, y, x, y, ink) }; } update(); }, onPointerMove: (e) => { if (!stroke) return; const [x, y] = cellAt(e, e.currentTarget); if (x === stroke.x && y === stroke.y) return; stroke.changed += line(stroke.x, stroke.y, x, y, stroke.ink); // the whole segment: fast drags skip cells stroke.x = x; stroke.y = y; update(); }, // Fires when the stroke's pointer goes up, and when the browser cancels it. onLostPointerCapture: () => { if (stroke) commit(`${stroke.tool} · ${stroke.changed} px`); stroke = null; update(); }, }, // The cells never come and go, so they are built once; only their color is read again. ...pixels.map((_, i) => div(s.cell, { style: () => ({ backgroundColor: pixels[i] }) })), ); } const ToolButton = (t: (typeof TOOLS)[number]) => button( s.tool, { class: () => cx(s.tool, tool === t.name ? s.on : null).className, "aria-pressed": () => String(tool === t.name), title: `${t.name} (${t.key})` }, t.name, kbd(t.key), { onClick: () => { tool = t.name; update(); } }, ); const Swatch = (c: string) => button(s.swatch, { style: { backgroundColor: c }, title: c, "aria-label": `Color ${c}`, class: () => cx(s.swatch, c === color ? s.picked : null).className, onClick: () => { choose(c); update(); }, }); // A snapshot never changes, so its thumbnail is drawn once, when its row mounts. const Thumb = (snap: Snapshot) => canvas(s.thumb, { width: SIZE, height: SIZE, "aria-hidden": "true" }, on("mount", (el) => { const ctx = el.getContext("2d")!; snap.pixels.forEach((c, i) => { if (c) { ctx.fillStyle = c; ctx.fillRect(i % SIZE, Math.floor(i / SIZE), 1, 1); } }); })); function Entry(snap: Snapshot) { const i = () => history.indexOf(snap); return button( s.entry, { class: () => cx(s.entry, i() === at ? s.current : i() > at ? s.future : null).className, "aria-current": () => String(i() === at) }, Thumb(snap), span(snap.label), { onClick: () => { jump(i()); update(); } }, // time travel: any snapshot, either direction ); } // Shortcuts listen on the document in the capture phase: they work wherever // the focus is, and a key handled here is defaultPrevented before the modal sees it. function shortcuts(el: HTMLElement) { const onKey = (e: KeyboardEvent) => { // Not while a source tab hides the editor, nor while typing in the color field. if (!el.offsetParent || e.altKey || e.target instanceof HTMLInputElement) return; const key = e.key.toUpperCase(); const t = TOOLS.find((t) => t.key === key); if (e.ctrlKey || e.metaKey) { if (key === "Z") (e.shiftKey ? redo : undo)(); else if (key === "Y") redo(); else return; } else if (t) tool = t.name; else return; e.preventDefault(); update(); }; document.addEventListener("keydown", onKey, true); return () => { document.removeEventListener("keydown", onKey, true); stroke = null; // a drag cut short by closing the example must not go on at the next visit }; } export function PixelEditor() { return div( s.app, on("mount", shortcuts), div( s.tools, ...TOOLS.map(ToolButton), div(s.palette, ...PALETTE.map(Swatch)), label(s.custom, input({ type: "color", value: () => color }, { onInput: (e) => { choose(e.currentTarget.value); update(); } }), "Custom"), div( s.actions, button(s.btn, "Clear", { onClick: () => replace("Clear", blank()) }), button(s.btn, "Mushroom", { title: "Start again from the mushroom", onClick: () => replace("Mushroom", mushroom()) }), ), ), div(s.stage, Canvas()), aside( s.history, div( s.head, strong("History"), button(s.btn, "Undo", { title: "Undo (Ctrl+Z)", disabled: () => at === 0, onClick: () => { undo(); update(); } }), button(s.btn, "Redo", { title: "Redo (Ctrl+Shift+Z)", disabled: () => at === history.length - 1, onClick: () => { redo(); update(); } }), ), p(s.stats, () => `${history.length} snapshots · each a plain array of ${SIZE * SIZE} strings`), // Newest first. Rows are the snapshot objects: a new step builds one row, nothing else. div(s.entries, list(() => history.slice().reverse(), Entry)), ), ); }
// history.ts: the picture and its past. The picture is a plain array of color // strings, one per pixel ("" is transparent). A snapshot is pixels.slice(), and // undo copies an older snapshot back. No store, no immutable data: old states // are just old arrays. Nothing here knows about the UI. export const SIZE = 32; const LIMIT = 100; // snapshots kept; the oldest are dropped first export interface Snapshot { label: string; pixels: string[]; } // The starter picture: one string per row, one letter per pixel. const INK: Record<string, string> = { k: "#1f2937", r: "#ef4444", w: "#ffffff", s: "#fde68a" }; const MUSHROOM = [ ".....kkkkkk.....", "...kkrrrrrrkk...", "..krwwrrrrrrrk..", ".krwwwwrrrrwwrk.", ".krwwwwrrrwwwwk.", "krrrwwrrrrwwwwrk", "krrrrrrwwrrwwrrk", "krrrrrwwwwrrrrrk", "krrrrrwwwwrrrrrk", ".kkkkkkkkkkkkkk.", "...kssssssssk...", "...kssksskssk...", "...kssksskssk...", "...kssssssssk...", "....kssssssk....", ".....kkkkkk.....", ]; export const blank = () => Array<string>(SIZE * SIZE).fill(""); export function mushroom() { const px = blank(); const edge = (SIZE - MUSHROOM.length) / 2; // the sprite is square: the same margin on every side MUSHROOM.forEach((row, y) => [...row].forEach((ch, x) => { px[(edge + y) * SIZE + edge + x] = INK[ch] ?? ""; })); return px; } export const pixels = mushroom(); export const history: Snapshot[] = [{ label: "Mushroom", pixels: pixels.slice() }]; export let at = 0; // the snapshot that `pixels` matches /** Saves the picture as a new step. A step that changed nothing is not saved. */ export function commit(label: string) { if (pixels.every((c, i) => c === history[at].pixels[i])) return; history.splice(at + 1); // a new step drops the undone ones history.push({ label, pixels: pixels.slice() }); if (history.length > LIMIT) history.shift(); at = history.length - 1; } /** Overwrites the picture in place: the array the cells read stays the same one. */ export const load = (next: string[]) => { pixels.splice(0, SIZE * SIZE, ...next); }; export function jump(i: number) { at = i; load(history[i].pixels); } export const undo = () => { if (at > 0) jump(at - 1); }; export const redo = () => { if (at < history.length - 1) jump(at + 1); }; const inside = (x: number, y: number) => x >= 0 && y >= 0 && x < SIZE && y < SIZE; export const get = (x: number, y: number) => (inside(x, y) ? pixels[y * SIZE + x] : ""); /** Paints every pixel from (x0, y0) to (x1, y1), so a fast stroke leaves no gaps. Returns how many changed. */ export function line(x0: number, y0: number, x1: number, y1: number, color: string) { const steps = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)); let changed = 0; for (let i = 0; i <= steps; i++) { const t = steps === 0 ? 0 : i / steps; const x = Math.round(x0 + (x1 - x0) * t), y = Math.round(y0 + (y1 - y0) * t); if (inside(x, y) && pixels[y * SIZE + x] !== color) { pixels[y * SIZE + x] = color; changed++; } } return changed; } /** Flood fill, with a stack instead of recursion. Returns how many pixels changed. */ export function fill(x: number, y: number, color: string) { const from = get(x, y); if (!inside(x, y) || from === color) return 0; const stack = [[x, y]]; let changed = 0; while (stack.length) { const [px, py] = stack.pop()!; if (!inside(px, py) || pixels[py * SIZE + px] !== from) continue; pixels[py * SIZE + px] = color; changed++; stack.push([px + 1, py], [px - 1, py], [px, py + 1], [px, py - 1]); } return changed; }
// styles.ts: the editor's look. The canvas is a CSS grid over a checkerboard, so a // transparent pixel ("" in the array) is simply a cell with no background. import "nuclo"; import { SIZE } from "./history.ts"; const mono = "ui-monospace, monospace"; const wide = "@media (min-width: 760px)"; // tools left, canvas, history right; stacked below const control = { height: "32px", padding: "0 10px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.8125rem", fontWeight: "600", whiteSpace: "nowrap" }; export const s = { app: css("px-app", { display: "flex", flexDirection: "column", gap: "14px", width: "100%", [wide]: { flexDirection: "row", height: "100%" } }), tools: css("px-tools", { display: "grid", gridTemplateColumns: "repeat(4, 1fr)", alignContent: "start", gap: "6px", [wide]: { gridTemplateColumns: "repeat(2, 1fr)", flexShrink: 0, width: "172px" } }), tool: css("px-tool", { ...control, display: "flex", alignItems: "center", justifyContent: "space-between", gap: "4px", hover: { backgroundColor: "var(--c-bg-secondary)" }, "& kbd": { fontFamily: mono, fontSize: "0.6875rem", fontWeight: "400", color: "var(--c-text-muted)" } }), on: css("px-on", { borderColor: "var(--c-primary)", backgroundColor: "var(--c-primary-alpha-13)", color: "var(--c-primary-ink)", hover: { backgroundColor: "var(--c-primary-alpha-19)" } }), palette: css("px-palette", { gridColumn: "1 / -1", display: "grid", gridTemplateColumns: "repeat(8, 1fr)", gap: "5px", margin: "6px 0", [wide]: { gridTemplateColumns: "repeat(4, 1fr)" } }), swatch: css("px-swatch", { aspectRatio: "1", borderRadius: "6px", border: "1px solid var(--c-border-light)" }), picked: css("px-picked", { boxShadow: "0 0 0 2px var(--c-bg-card), 0 0 0 4px var(--c-primary)" }), custom: css("px-custom", { ...control, gridColumn: "span 2", display: "flex", alignItems: "center", gap: "8px", cursor: "pointer", "& input": { width: "22px", height: "22px", padding: "0", border: "none", backgroundColor: "transparent", cursor: "pointer" } }), actions: css("px-actions", { gridColumn: "span 2", display: "flex", gap: "6px", "& button": { flex: "1 1 auto" } }), btn: css("px-btn", { ...control, hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:disabled": { opacity: "0.45", cursor: "default" } }), // Wide, the stage is a size container: the canvas takes the smaller of its width and height. stage: css("px-stage", { display: "flex", alignItems: "center", justifyContent: "center", flex: "1", minWidth: "0", [wide]: { containerType: "size" } }), canvas: css("px-canvas", { display: "grid", gridTemplateColumns: `repeat(${SIZE}, 1fr)`, gridTemplateRows: `repeat(${SIZE}, 1fr)`, width: "100%", maxWidth: "480px", aspectRatio: "1", // A checkerboard behind the transparent cells: one tile is two cells wide. backgroundImage: "conic-gradient(var(--c-bg-light) 25%, var(--c-bg) 0 50%, var(--c-bg-light) 0 75%, var(--c-bg) 0)", backgroundSize: `${200 / SIZE}% ${200 / SIZE}%`, boxShadow: "0 0 0 1px var(--c-border)", // not a border: the cell math reads the box edge to edge cursor: "crosshair", touchAction: "none", [wide]: { width: "min(100cqw, 100cqh)", maxWidth: "none" }, }), cell: css("px-cell", { hover: { boxShadow: "inset 0 0 0 1px var(--c-primary)" } }), history: css("px-history", { display: "flex", flexDirection: "column", gap: "8px", [wide]: { flexShrink: 0, width: "232px", minHeight: "0" } }), head: css("px-head", { display: "flex", alignItems: "center", gap: "6px", "& strong": { flex: "1", fontSize: "0.9375rem" } }), stats: css("px-stats", { fontFamily: mono, fontSize: "0.75rem", lineHeight: "1.4", color: "var(--c-text-muted)" }), entries: css("px-entries", { display: "flex", flexDirection: "column", gap: "2px", maxHeight: "240px", overflowY: "auto", [wide]: { flex: "1", minHeight: "0", maxHeight: "none" } }), entry: css("px-entry", { display: "flex", alignItems: "center", gap: "10px", flexShrink: 0, padding: "4px 8px 4px 4px", borderRadius: "8px", fontSize: "0.8125rem", textAlign: "left", color: "var(--c-text-dim)", hover: { backgroundColor: "var(--c-bg-secondary)" } }), current: css("px-current", { backgroundColor: "var(--c-primary-alpha-13)", color: "var(--c-primary-ink)", fontWeight: "600", hover: { backgroundColor: "var(--c-primary-alpha-13)" } }), future: css("px-future", { opacity: "0.45" }), thumb: css("px-thumb", { flexShrink: 0, width: "32px", height: "32px", borderRadius: "4px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg)", raw: { "image-rendering": "pixelated" } }), };