hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js"; |
| 2 | import { Button } from "@/components/ui/button"; |
| 3 | import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; |
| 4 | import { cn } from "@/lib/cn"; |
| 5 | import { PAPER_CELL, PAPER_LINE, canvasPx, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke"; |
| 6 | import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file"; |
| 7 | import { useT } from "@/stores/preferences-context"; |
| 8 | |
| 9 | const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; |
| 10 | const WIDTHS = [2, 6, 14]; |
| 11 | const ZOOM_MIN = 0.25; |
| 12 | const ZOOM_MAX = 4; |
| 13 | const ZOOM_STEP = 1.25; |
| 14 | // Whitespace kept around the drawn region when exporting the bounding box. |
| 15 | const EXPORT_MARGIN = 8; |
| 16 | // Floating glass overlays that live inside the canvas, matching the bottom-right |
| 17 | // zoom control. Position/size utilities are appended per overlay via cn(). |
| 18 | const OVERLAY_CARD = "absolute z-10 flex gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-xs backdrop-blur-xs"; |
| 19 | const OVERLAY_BTN = "flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"; |
| 20 | // Per-tool canvas cursors. Pen uses the built-in crosshair; the eraser is a |
| 21 | // lucide-eraser SVG data-URI (black glyph on a white halo so it stays visible |
| 22 | // over any stroke colour), hotspot centred on the block. Pan falls back to |
| 23 | // grab/grabbing in the reactive cursor() below. |
| 24 | // Halo-under-glyph cursor: draw each lucide path once thick-white for contrast, |
| 25 | // then thin-black on top, baked into ONE svg (a cursor value list only picks the |
| 26 | // first url, it can't composite two). Hotspot is per glyph — pen at its writing |
| 27 | // tip, eraser at its centre. |
| 28 | const haloCursor = (glyph: string, hx: number, hy: number) => |
| 29 | `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke-linecap='round' stroke-linejoin='round'%3E%3Cg stroke='%23fff' stroke-width='4'%3E${glyph}%3C/g%3E%3Cg stroke='%23000' stroke-width='2'%3E${glyph}%3C/g%3E%3C/svg%3E") ${hx} ${hy}`; |
| 30 | // lucide "pencil" — nib points to bottom-left, so the hotspot rides its tip. |
| 31 | const PEN_GLYPH = |
| 32 | "%3Cpath d='M12 20h9'/%3E%3Cpath d='M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z'/%3E"; |
| 33 | const PEN_CURSOR = `${haloCursor(PEN_GLYPH, 3, 21)}, crosshair`; |
| 34 | const ERASER_GLYPH = |
| 35 | "%3Cpath d='m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21'/%3E%3Cpath d='M22 21H7'/%3E%3Cpath d='m5 11 9 9'/%3E"; |
| 36 | const ERASER_CURSOR = `${haloCursor(ERASER_GLYPH, 12, 12)}, crosshair`; |
| 37 | |
| 38 | /** |
| 39 | * Freehand drawing pad. `props.onSave` receives a PNG `File` that both displays |
| 40 | * as a normal image and carries its editable stroke JSON in a tEXt chunk, so the |
| 41 | * same File feeds every existing upload seam (`postNoteFile`, |
| 42 | * `postExamQuestionImage`) and a saved drawing can be reopened via `initialScene`. |
| 43 | * PNG/JPEG buttons additionally download a flat image straight to the device. |
| 44 | */ |
| 45 | export function DrawCanvas(props: { |
| 46 | onSave: (file: File) => void; |
| 47 | initialScene?: DrawScene | null; |
| 48 | fileName?: string; |
| 49 | pending?: boolean; |
| 50 | class?: string; |
| 51 | }) { |
| 52 | const t = useT(); |
| 53 | let canvas: HTMLCanvasElement | undefined; |
| 54 | let wrap: HTMLDivElement | undefined; |
| 55 | let current: Stroke | undefined; |
| 56 | // Live pan drag: pointer origin + pan value at grab, so the pad follows the finger. |
| 57 | let panStart: { x: number; y: number; px: number; py: number } | undefined; |
| 58 | |
| 59 | const [strokes, setStrokes] = createSignal<Stroke[]>([]); |
| 60 | const [color, setColor] = createSignal(COLORS[0]); |
| 61 | const [width, setWidth] = createSignal(WIDTHS[1]); |
| 62 | const [erasing, setErasing] = createSignal(false); |
| 63 | const [hand, setHand] = createSignal(false); |
| 64 | // Transient tool while a non-left button is held (middle = pan, right = erase), |
| 65 | // so the toolbar highlights it as if clicked and reverts on release. |
| 66 | const [override, setOverride] = createSignal<null | "pan" | "erase">(null); |
| 67 | // The pad is unbounded — strokes live in world coords; pan is the world→screen |
| 68 | // offset in CSS px so you can move around a drawing larger than the viewport. |
| 69 | const [pan, setPan] = createSignal({ x: 0, y: 0 }); |
| 70 | // Reactive flag for an in-progress pan drag, so the pan cursor flips grab→grabbing. |
| 71 | const [panning, setPanning] = createSignal(false); |
| 72 | // View-only magnification: screenCSS = world * zoom + pan. Strokes stay in world |
| 73 | // px, so stroke widths scale with the transform — never multiply them by hand. |
| 74 | const [zoom, setZoom] = createSignal(1); |
| 75 | // Notebook paper, drawn as CSS on the wrapper (never in redraw(), or the eraser |
| 76 | // would cut it). New pads default to squared grid — the look the pad is for. |
| 77 | const [bg, setBg] = createSignal<BgKind>("grid"); |
| 78 | // Which floating picker is open (pen/eraser line-thickness, or paper style). |
| 79 | // Driven by JS, not CSS :focus-within — a mouse click keeps focus on the trigger |
| 80 | // and the canvas isn't focusable to blur it, so focus-within stayed stuck open. |
| 81 | const [openMenu, setOpenMenu] = createSignal<null | "pen" | "eraser" | "paper">(null); |
| 82 | |
| 83 | const ratio = () => window.devicePixelRatio || 1; |
| 84 | const context = () => canvas?.getContext("2d") ?? null; |
| 85 | |
| 86 | // Transient override wins over the persistent tool so the toolbar reflects a held button. |
| 87 | const activeTool = (): "pen" | "erase" | "pan" => { |
| 88 | const o = override(); |
| 89 | if (o) return o; |
| 90 | if (hand()) return "pan"; |
| 91 | if (erasing()) return "erase"; |
| 92 | return "pen"; |
| 93 | }; |
| 94 | |
| 95 | // Canvas cursor mirrors the active tool: pen → crosshair, eraser → its glyph, |
| 96 | // pan → grab (grabbing mid-drag). Set inline so all three read from one place. |
| 97 | const cursor = () => { |
| 98 | const tool = activeTool(); |
| 99 | if (tool === "pan") return panning() ? "grabbing" : "grab"; |
| 100 | if (tool === "erase") return ERASER_CURSOR; |
| 101 | return PEN_CURSOR; |
| 102 | }; |
| 103 | |
| 104 | const redraw = () => { |
| 105 | const c = context(); |
| 106 | if (!c || !canvas) return; |
| 107 | const scale = ratio(); |
| 108 | // Clear the whole backing store in device pixels, then shift into world space |
| 109 | // by the pan offset so off-origin strokes render where the pan puts them. |
| 110 | c.setTransform(scale, 0, 0, scale, 0, 0); |
| 111 | c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); |
| 112 | const p = pan(); |
| 113 | const z = zoom(); |
| 114 | c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); |
| 115 | for (const stroke of strokes()) paintStroke(c, stroke); |
| 116 | if (current) paintStroke(c, current); |
| 117 | }; |
| 118 | |
| 119 | // The backing store is DPR-scaled; without this strokes land blurry and offset. |
| 120 | const resize = () => { |
| 121 | if (!canvas) return; |
| 122 | const rect = canvas.getBoundingClientRect(); |
| 123 | if (rect.width === 0 || rect.height === 0) return; |
| 124 | const scale = ratio(); |
| 125 | canvas.width = Math.round(rect.width * scale); |
| 126 | canvas.height = Math.round(rect.height * scale); |
| 127 | redraw(); |
| 128 | }; |
| 129 | |
| 130 | onMount(() => { |
| 131 | resize(); |
| 132 | const observer = new ResizeObserver(() => resize()); |
| 133 | if (wrap) observer.observe(wrap); |
| 134 | // Close any open flyout on a pointerdown outside every picker group, or Escape. |
| 135 | // The canvas isn't focusable, so nothing would otherwise dismiss it. |
| 136 | const onDocDown = (e: PointerEvent) => { |
| 137 | if (!(e.target as HTMLElement | null)?.closest("[data-draw-menu]")) setOpenMenu(null); |
| 138 | }; |
| 139 | const onKey = (e: KeyboardEvent) => { |
| 140 | if (e.key === "Escape") setOpenMenu(null); |
| 141 | }; |
| 142 | document.addEventListener("pointerdown", onDocDown); |
| 143 | document.addEventListener("keydown", onKey); |
| 144 | onCleanup(() => { |
| 145 | observer.disconnect(); |
| 146 | document.removeEventListener("pointerdown", onDocDown); |
| 147 | document.removeEventListener("keydown", onKey); |
| 148 | }); |
| 149 | }); |
| 150 | |
| 151 | // Load (or reload) an edited scene whenever the caller supplies one — including |
| 152 | // while the pad is already open. No rescale: the pad is unbounded, so rather than |
| 153 | // shrinking a big drawing to fit we keep it 1:1 and pan its content into the |
| 154 | // corner (you move around it from there). untrack keeps redraw's read of |
| 155 | // strokes() from turning this into a self-triggering loop. |
| 156 | let lastLoadedScene: DrawScene | null | undefined = Symbol("uninitialized") as any; |
| 157 | |
| 158 | createEffect(() => { |
| 159 | const scene = props.initialScene; |
| 160 | if (scene === lastLoadedScene) return; |
| 161 | lastLoadedScene = scene; |
| 162 | untrack(() => { |
| 163 | const next = scene ? scene.strokes : []; |
| 164 | setStrokes(next); |
| 165 | setBg(scene?.bg ?? "grid"); // default grid background for new/edited drawings |
| 166 | setZoom(1); // a reopened drawing starts at 100% |
| 167 | const b = strokesBounds(next); |
| 168 | setPan(b ? { x: EXPORT_MARGIN - b.x, y: EXPORT_MARGIN - b.y } : { x: 0, y: 0 }); |
| 169 | redraw(); |
| 170 | }); |
| 171 | }); |
| 172 | |
| 173 | const pointAt = (e: PointerEvent): Point => { |
| 174 | const rect = canvas!.getBoundingClientRect(); |
| 175 | const p = pan(); |
| 176 | const z = zoom(); |
| 177 | return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; |
| 178 | }; |
| 179 | |
| 180 | // Zoom around the pad center: keep the world point under the center fixed so |
| 181 | // content doesn't fly off. Clamped to [ZOOM_MIN, ZOOM_MAX]. |
| 182 | // ponytail: no pinch-zoom; buttons + wheel cover it, add 2-pointer tracking if touch users ask |
| 183 | const zoomBy = (factor: number) => { |
| 184 | if (!canvas) return; |
| 185 | const rect = canvas.getBoundingClientRect(); |
| 186 | const cx = rect.width / 2; |
| 187 | const cy = rect.height / 2; |
| 188 | const p = pan(); |
| 189 | const z0 = zoom(); |
| 190 | const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); |
| 191 | if (z1 === z0) return; |
| 192 | const wx = (cx - p.x) / z0; |
| 193 | const wy = (cy - p.y) / z0; |
| 194 | setZoom(z1); |
| 195 | setPan({ x: cx - wx * z1, y: cy - wy * z1 }); |
| 196 | redraw(); |
| 197 | }; |
| 198 | |
| 199 | // Snap back to 100% while keeping the centered content centered (no-op at 1). |
| 200 | const resetZoom = () => zoomBy(1 / zoom()); |
| 201 | |
| 202 | const drawTip = (stroke: Stroke) => { |
| 203 | const c = context(); |
| 204 | if (c) paintTip(c, stroke); |
| 205 | }; |
| 206 | |
| 207 | const startStroke = (e: PointerEvent) => { |
| 208 | if (props.pending) return; |
| 209 | e.preventDefault(); |
| 210 | canvas?.setPointerCapture(e.pointerId); |
| 211 | // Middle button (1) always pans; the hand tool pans on any button EXCEPT right, |
| 212 | // because right button always erases (see below). button is the real value only |
| 213 | // on pointerdown; -1 during move, which is why panStart/current carry the state. |
| 214 | if (e.button === 1 || (hand() && e.button !== 2)) { |
| 215 | if (e.button === 1) setOverride("pan"); // transient middle-button pan |
| 216 | const p = pan(); |
| 217 | panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; |
| 218 | setPanning(true); |
| 219 | return; |
| 220 | } |
| 221 | // Right button (2) forces an erase stroke regardless of the selected tool. |
| 222 | const eraseNow = erasing() || e.button === 2; |
| 223 | if (e.button === 2) setOverride("erase"); // transient right-button erase |
| 224 | current = { |
| 225 | color: color(), |
| 226 | width: eraseNow ? width() * 2.5 : width(), |
| 227 | erase: eraseNow, |
| 228 | points: [pointAt(e)], |
| 229 | }; |
| 230 | drawTip(current); |
| 231 | }; |
| 232 | |
| 233 | const extendStroke = (e: PointerEvent) => { |
| 234 | if (panStart) { |
| 235 | setPan({ x: panStart.px + (e.clientX - panStart.x), y: panStart.py + (e.clientY - panStart.y) }); |
| 236 | redraw(); |
| 237 | return; |
| 238 | } |
| 239 | if (!current) return; |
| 240 | current.points.push(pointAt(e)); |
| 241 | drawTip(current); |
| 242 | }; |
| 243 | |
| 244 | const endStroke = () => { |
| 245 | setOverride(null); |
| 246 | if (panStart) { |
| 247 | panStart = undefined; |
| 248 | setPanning(false); |
| 249 | return; |
| 250 | } |
| 251 | const done = current; |
| 252 | current = undefined; |
| 253 | if (!done) return; |
| 254 | setStrokes((all) => [...all, done]); |
| 255 | redraw(); // swap the live polyline for its smoothed replay |
| 256 | }; |
| 257 | |
| 258 | const undo = () => { |
| 259 | setStrokes((all) => all.slice(0, -1)); |
| 260 | redraw(); |
| 261 | }; |
| 262 | |
| 263 | const clear = () => { |
| 264 | setStrokes([]); |
| 265 | redraw(); |
| 266 | }; |
| 267 | |
| 268 | // Editing lets you clear a drawing and save the blank (persist the erase); a |
| 269 | // brand-new untouched pad has nothing to save. |
| 270 | const canSave = () => strokes().length > 0 || props.initialScene != null; |
| 271 | |
| 272 | // Render only the drawn region (not the viewport) onto an offscreen DPR-scaled |
| 273 | // canvas, and produce the matching scene with strokes shifted into that box. |
| 274 | // This is what makes the pad "infinite": export follows the content wherever it |
| 275 | // was drawn or panned to, instead of capturing what happens to be on screen. |
| 276 | const renderBounds = (): { canvas: HTMLCanvasElement; scene: DrawScene } | null => { |
| 277 | const list = strokes(); |
| 278 | const b = strokesBounds(list); |
| 279 | if (!b) return null; |
| 280 | const scale = ratio(); |
| 281 | const w = Math.ceil(b.w + EXPORT_MARGIN * 2); |
| 282 | const h = Math.ceil(b.h + EXPORT_MARGIN * 2); |
| 283 | const dx = EXPORT_MARGIN - b.x; |
| 284 | const dy = EXPORT_MARGIN - b.y; |
| 285 | const off = document.createElement("canvas"); |
| 286 | off.width = canvasPx(w, scale); |
| 287 | off.height = canvasPx(h, scale); |
| 288 | const oc = off.getContext("2d"); |
| 289 | if (!oc) return null; |
| 290 | oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale); |
| 291 | for (const s of list) paintStroke(oc, s); |
| 292 | const shifted = list.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) })); |
| 293 | // dpr rides along: the PNG is baked at this ratio, so a viewer on a different |
| 294 | // display can size the replay to the same pixels instead of its own ratio. |
| 295 | const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg(), dpr: scale }; |
| 296 | return { canvas: off, scene }; |
| 297 | }; |
| 298 | |
| 299 | const save = async () => { |
| 300 | if (!canSave()) return; |
| 301 | const name = props.fileName ?? "drawing.png"; |
| 302 | const rendered = renderBounds(); |
| 303 | if (rendered) { |
| 304 | props.onSave(await sceneToPngFile(rendered.canvas, rendered.scene, name)); |
| 305 | return; |
| 306 | } |
| 307 | // Cleared while editing an existing drawing: save a 1×1 blank to persist the erase. |
| 308 | const blank = document.createElement("canvas"); |
| 309 | blank.width = 1; |
| 310 | blank.height = 1; |
| 311 | props.onSave(await sceneToPngFile(blank, { v: 1, w: 1, h: 1, strokes: [], bg: bg() }, name)); |
| 312 | }; |
| 313 | |
| 314 | const baseName = () => (props.fileName ?? "drawing").replace(/(\.hzdraw)?\.[a-z0-9]+$/i, ""); |
| 315 | |
| 316 | const download = async (mime: string, ext: string) => { |
| 317 | const rendered = renderBounds(); |
| 318 | if (!rendered) return; |
| 319 | const blob = await canvasToImageBlob(rendered.canvas, mime, bg()); |
| 320 | if (!blob) return; |
| 321 | const url = URL.createObjectURL(blob); |
| 322 | const link = document.createElement("a"); |
| 323 | link.href = url; |
| 324 | link.download = `${baseName()}.${ext}`; |
| 325 | link.click(); |
| 326 | URL.revokeObjectURL(url); |
| 327 | }; |
| 328 | |
| 329 | // Live ruling via CSS gradients so lines pan and zoom WITH the content: world |
| 330 | // cell PAPER_CELL → PAPER_CELL*zoom on screen, a world-origin line sits at pan. |
| 331 | // (Export bakes its own ruling; the two aren't pixel-identical, and needn't be.) |
| 332 | const paperStyle = () => { |
| 333 | const kind = bg(); |
| 334 | if (kind === "none") return {}; |
| 335 | const cell = PAPER_CELL * zoom(); |
| 336 | const p = pan(); |
| 337 | if (kind === "grid") { |
| 338 | return { |
| 339 | "background-image": `linear-gradient(to right, ${PAPER_LINE} 1px, transparent 1px), linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`, |
| 340 | "background-size": `${cell}px ${cell}px`, |
| 341 | "background-position": `${p.x}px ${p.y}px`, |
| 342 | }; |
| 343 | } |
| 344 | return { |
| 345 | "background-image": `linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`, |
| 346 | "background-size": `100% ${cell}px`, |
| 347 | "background-position": `0 ${p.y}px`, |
| 348 | }; |
| 349 | }; |
| 350 | |
| 351 | const bgLabel = () => (bg() === "none" ? t("draw.bgNone") : bg() === "lines" ? t("draw.bgLines") : t("draw.bgGrid")); |
| 352 | |
| 353 | const toolClass = (active: boolean) => |
| 354 | cn( |
| 355 | "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", |
| 356 | active |
| 357 | ? "border-primary bg-primary text-primary-foreground shadow-xs" |
| 358 | : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", |
| 359 | ); |
| 360 | |
| 361 | // Line-thickness flyout shared by the pen and eraser triggers (width is one |
| 362 | // shared signal, so both open the same picker). A JSX-returning local, not a |
| 363 | // second exported component — one file, one component. Visibility is driven by |
| 364 | // openMenu() (see the pointer/click handlers on each trigger); the pt-1.5 wrapper |
| 365 | // bridges the gap so the mouse can travel trigger→flyout without pointerleave |
| 366 | // firing. z-20 sits it above the sibling islands. |
| 367 | const widthPicker = (id: "pen" | "eraser") => ( |
| 368 | <div |
| 369 | class={cn( |
| 370 | "absolute left-0 top-full z-20 pt-1.5 transition", |
| 371 | openMenu() === id ? "translate-y-0 opacity-100" : "pointer-events-none invisible translate-y-1 opacity-0", |
| 372 | )} |
| 373 | > |
| 374 | <div class={cn(OVERLAY_CARD, "static")} role="group" aria-label={t("draw.width")}> |
| 375 | <For each={WIDTHS}> |
| 376 | {(size) => ( |
| 377 | <button |
| 378 | type="button" |
| 379 | aria-pressed={width() === size} |
| 380 | title={t("draw.width")} |
| 381 | class={toolClass(width() === size)} |
| 382 | onClick={() => { |
| 383 | setWidth(size); |
| 384 | setOpenMenu(null); |
| 385 | }} |
| 386 | > |
| 387 | <span class="rounded-full bg-current" style={{ width: `${size + 2}px`, height: `${size + 2}px` }} /> |
| 388 | <span class="sr-only">{size}</span> |
| 389 | </button> |
| 390 | )} |
| 391 | </For> |
| 392 | </div> |
| 393 | </div> |
| 394 | ); |
| 395 | |
| 396 | return ( |
| 397 | <div class={cn("space-y-3", props.class)}> |
| 398 | <div ref={wrap} class="relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-120" style={paperStyle()}> |
| 399 | <canvas |
| 400 | ref={canvas} |
| 401 | class="h-full w-full touch-none" |
| 402 | style={{ cursor: cursor() }} |
| 403 | onMouseDown={(e) => { |
| 404 | // preventDefault in pointerdown does not stop the middle-click autoscroll widget. |
| 405 | if (e.button === 1) e.preventDefault(); |
| 406 | }} |
| 407 | onContextMenu={(e) => e.preventDefault()} |
| 408 | onPointerDown={startStroke} |
| 409 | onPointerMove={extendStroke} |
| 410 | onPointerUp={endStroke} |
| 411 | onPointerCancel={endStroke} |
| 412 | onWheel={(e) => { |
| 413 | e.preventDefault(); |
| 414 | zoomBy(e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP); |
| 415 | }} |
| 416 | /> |
| 417 | <Show when={strokes().length === 0 && !current}> |
| 418 | <p class="pointer-events-none absolute inset-0 flex items-center justify-center text-sm text-slate-400">{t("draw.hint")}</p> |
| 419 | </Show> |
| 420 | |
| 421 | {/* Top-left island — tools only: pen, eraser, pan. Pen and eraser each |
| 422 | reveal the shared line-thickness flyout (open on hover/tap, toggled via |
| 423 | openMenu()); pan has no flyout. */} |
| 424 | <div class={cn(OVERLAY_CARD, "left-2 top-2")}> |
| 425 | <div |
| 426 | data-draw-menu |
| 427 | class="relative" |
| 428 | onPointerEnter={(e) => { |
| 429 | if (e.pointerType !== "touch") setOpenMenu("pen"); |
| 430 | }} |
| 431 | onPointerLeave={(e) => { |
| 432 | if (e.pointerType !== "touch") setOpenMenu(null); |
| 433 | }} |
| 434 | > |
| 435 | <button |
| 436 | type="button" |
| 437 | class={toolClass(activeTool() === "pen")} |
| 438 | aria-haspopup="true" |
| 439 | aria-expanded={openMenu() === "pen"} |
| 440 | aria-pressed={activeTool() === "pen"} |
| 441 | title={t("draw.pen")} |
| 442 | onClick={() => { |
| 443 | setErasing(false); |
| 444 | setHand(false); |
| 445 | setOpenMenu((o) => (o === "pen" ? null : "pen")); |
| 446 | }} |
| 447 | > |
| 448 | <IconEdit class="h-5 w-5" /> |
| 449 | <span class="sr-only">{t("draw.pen")}</span> |
| 450 | </button> |
| 451 | {widthPicker("pen")} |
| 452 | </div> |
| 453 | <div |
| 454 | data-draw-menu |
| 455 | class="relative" |
| 456 | onPointerEnter={(e) => { |
| 457 | if (e.pointerType !== "touch") setOpenMenu("eraser"); |
| 458 | }} |
| 459 | onPointerLeave={(e) => { |
| 460 | if (e.pointerType !== "touch") setOpenMenu(null); |
| 461 | }} |
| 462 | > |
| 463 | <button |
| 464 | type="button" |
| 465 | class={toolClass(activeTool() === "erase")} |
| 466 | aria-haspopup="true" |
| 467 | aria-expanded={openMenu() === "eraser"} |
| 468 | aria-pressed={activeTool() === "erase"} |
| 469 | title={t("draw.eraser")} |
| 470 | onClick={() => { |
| 471 | setErasing(true); |
| 472 | setHand(false); |
| 473 | setOpenMenu((o) => (o === "eraser" ? null : "eraser")); |
| 474 | }} |
| 475 | > |
| 476 | <IconEraser class="h-5 w-5" /> |
| 477 | <span class="sr-only">{t("draw.eraser")}</span> |
| 478 | </button> |
| 479 | {widthPicker("eraser")} |
| 480 | </div> |
| 481 | <button type="button" class={toolClass(activeTool() === "pan")} aria-pressed={activeTool() === "pan"} title={t("draw.pan")} onClick={() => setHand(true)}> |
| 482 | <IconMove class="h-5 w-5" /> |
| 483 | <span class="sr-only">{t("draw.pan")}</span> |
| 484 | </button> |
| 485 | </div> |
| 486 | |
| 487 | {/* Top-middle island — colour swatches */} |
| 488 | <div class={cn(OVERLAY_CARD, "left-1/2 top-2 -translate-x-1/2 flex-wrap items-center")} role="group" aria-label={t("draw.color")}> |
| 489 | <For each={COLORS}> |
| 490 | {(swatch) => ( |
| 491 | <button |
| 492 | type="button" |
| 493 | aria-pressed={color() === swatch && activeTool() === "pen"} |
| 494 | title={t("draw.color")} |
| 495 | class={cn( |
| 496 | "h-9 w-9 sm:h-11 sm:w-11 rounded-lg border-2 transition-transform", |
| 497 | color() === swatch && activeTool() === "pen" ? "border-foreground scale-105" : "border-border/60 hover:scale-105", |
| 498 | )} |
| 499 | style={{ "background-color": swatch }} |
| 500 | onClick={() => { |
| 501 | setColor(swatch); |
| 502 | setErasing(false); |
| 503 | setHand(false); |
| 504 | }} |
| 505 | > |
| 506 | <span class="sr-only">{swatch}</span> |
| 507 | </button> |
| 508 | )} |
| 509 | </For> |
| 510 | </div> |
| 511 | |
| 512 | {/* Top-right island — paper selector. The trigger shows the current paper; |
| 513 | hover/tap toggles the none/lines/grid flyout via openMenu(). The card is |
| 514 | already `absolute` (its own containing block), so the flyout positions off |
| 515 | it without a `relative` wrapper. */} |
| 516 | <div |
| 517 | data-draw-menu |
| 518 | class={cn(OVERLAY_CARD, "right-2 top-2")} |
| 519 | onPointerEnter={(e) => { |
| 520 | if (e.pointerType !== "touch") setOpenMenu("paper"); |
| 521 | }} |
| 522 | onPointerLeave={(e) => { |
| 523 | if (e.pointerType !== "touch") setOpenMenu(null); |
| 524 | }} |
| 525 | > |
| 526 | <button |
| 527 | type="button" |
| 528 | class={toolClass(bg() !== "none")} |
| 529 | aria-haspopup="true" |
| 530 | aria-expanded={openMenu() === "paper"} |
| 531 | aria-pressed={bg() !== "none"} |
| 532 | title={bgLabel()} |
| 533 | onClick={() => setOpenMenu((o) => (o === "paper" ? null : "paper"))} |
| 534 | > |
| 535 | <Switch> |
| 536 | <Match when={bg() === "none"}> |
| 537 | <IconSquareOff class="h-5 w-5" /> |
| 538 | </Match> |
| 539 | <Match when={bg() === "lines"}> |
| 540 | <IconRuled class="h-5 w-5" /> |
| 541 | </Match> |
| 542 | <Match when={bg() === "grid"}> |
| 543 | <IconGrid class="h-5 w-5" /> |
| 544 | </Match> |
| 545 | </Switch> |
| 546 | <span class="sr-only">{bgLabel()}</span> |
| 547 | </button> |
| 548 | {/* Paper flyout — opens downward, right-aligned; pt-1.5 bridges the gap so |
| 549 | the mouse can travel trigger→flyout without pointerleave firing. */} |
| 550 | <div |
| 551 | class={cn( |
| 552 | "absolute right-0 top-full z-20 pt-1.5 transition", |
| 553 | openMenu() === "paper" ? "translate-y-0 opacity-100" : "pointer-events-none invisible translate-y-1 opacity-0", |
| 554 | )} |
| 555 | > |
| 556 | <div class={cn(OVERLAY_CARD, "static")} role="group" aria-label={t("draw.paper")}> |
| 557 | <button |
| 558 | type="button" |
| 559 | class={toolClass(bg() === "none")} |
| 560 | aria-pressed={bg() === "none"} |
| 561 | title={t("draw.bgNone")} |
| 562 | onClick={() => { |
| 563 | setBg("none"); |
| 564 | setOpenMenu(null); |
| 565 | }} |
| 566 | > |
| 567 | <IconSquareOff class="h-5 w-5" /> |
| 568 | <span class="sr-only">{t("draw.bgNone")}</span> |
| 569 | </button> |
| 570 | <button |
| 571 | type="button" |
| 572 | class={toolClass(bg() === "lines")} |
| 573 | aria-pressed={bg() === "lines"} |
| 574 | title={t("draw.bgLines")} |
| 575 | onClick={() => { |
| 576 | setBg("lines"); |
| 577 | setOpenMenu(null); |
| 578 | }} |
| 579 | > |
| 580 | <IconRuled class="h-5 w-5" /> |
| 581 | <span class="sr-only">{t("draw.bgLines")}</span> |
| 582 | </button> |
| 583 | <button |
| 584 | type="button" |
| 585 | class={toolClass(bg() === "grid")} |
| 586 | aria-pressed={bg() === "grid"} |
| 587 | title={t("draw.bgGrid")} |
| 588 | onClick={() => { |
| 589 | setBg("grid"); |
| 590 | setOpenMenu(null); |
| 591 | }} |
| 592 | > |
| 593 | <IconGrid class="h-5 w-5" /> |
| 594 | <span class="sr-only">{t("draw.bgGrid")}</span> |
| 595 | </button> |
| 596 | </div> |
| 597 | </div> |
| 598 | </div> |
| 599 | |
| 600 | {/* Bottom-left history */} |
| 601 | <div class={cn(OVERLAY_CARD, "bottom-2 left-2")}> |
| 602 | <button |
| 603 | type="button" |
| 604 | class={cn(OVERLAY_BTN, "rounded-md disabled:pointer-events-none disabled:opacity-40")} |
| 605 | disabled={strokes().length === 0} |
| 606 | title={t("draw.undo")} |
| 607 | onClick={undo} |
| 608 | > |
| 609 | <IconUndo class="h-5 w-5" /> |
| 610 | <span class="sr-only">{t("draw.undo")}</span> |
| 611 | </button> |
| 612 | <button |
| 613 | type="button" |
| 614 | class={cn(OVERLAY_BTN, "rounded-md disabled:pointer-events-none disabled:opacity-40")} |
| 615 | disabled={strokes().length === 0} |
| 616 | title={t("draw.clear")} |
| 617 | onClick={clear} |
| 618 | > |
| 619 | <IconTrash class="h-5 w-5" /> |
| 620 | <span class="sr-only">{t("draw.clear")}</span> |
| 621 | </button> |
| 622 | </div> |
| 623 | |
| 624 | <div class="absolute bottom-2 right-2 z-10 flex flex-col divide-y divide-border overflow-hidden rounded-lg border bg-card/90 shadow-xs backdrop-blur-xs"> |
| 625 | <button |
| 626 | type="button" |
| 627 | class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" |
| 628 | title={t("draw.zoomIn")} |
| 629 | onClick={() => zoomBy(ZOOM_STEP)} |
| 630 | > |
| 631 | <IconZoomIn class="h-5 w-5" /> |
| 632 | <span class="sr-only">{t("draw.zoomIn")}</span> |
| 633 | </button> |
| 634 | <button |
| 635 | type="button" |
| 636 | class="flex h-9 w-9 items-center justify-center font-mono text-xs tabular-nums text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" |
| 637 | title={t("draw.resetZoom")} |
| 638 | onClick={resetZoom} |
| 639 | > |
| 640 | {Math.round(zoom() * 100)}% |
| 641 | </button> |
| 642 | <button |
| 643 | type="button" |
| 644 | class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" |
| 645 | title={t("draw.zoomOut")} |
| 646 | onClick={() => zoomBy(1 / ZOOM_STEP)} |
| 647 | > |
| 648 | <IconZoomOut class="h-5 w-5" /> |
| 649 | <span class="sr-only">{t("draw.zoomOut")}</span> |
| 650 | </button> |
| 651 | </div> |
| 652 | </div> |
| 653 | |
| 654 | <div class="flex flex-wrap items-center gap-2"> |
| 655 | <Button type="button" class="h-10 px-5" disabled={props.pending || !canSave()} onClick={() => void save()}> |
| 656 | {t("draw.save")} |
| 657 | </Button> |
| 658 | <Button type="button" variant="outline" class="h-10 gap-2" disabled={strokes().length === 0} onClick={() => void download("image/png", "png")}> |
| 659 | <IconDownload class="h-4 w-4" /> |
| 660 | {t("draw.downloadPng")} |
| 661 | </Button> |
| 662 | <Button type="button" variant="outline" class="h-10 gap-2" disabled={strokes().length === 0} onClick={() => void download("image/jpeg", "jpg")}> |
| 663 | <IconDownload class="h-4 w-4" /> |
| 664 | {t("draw.downloadJpeg")} |
| 665 | </Button> |
| 666 | </div> |
| 667 | </div> |
| 668 | ); |
| 669 | } |