From 982f3ad78d6c24afd04c9a7981ff15ee2ca08752 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 20 Apr 2026 23:24:38 -0700 Subject: [PATCH] Moodboard: viewport state, recenter indicator, shortcut cheatsheet, canvas perf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lifts `viewport` (zoom/pan) and `canvasSize` into the moodboard store so overlays and a future minimap can read the camera without drilling refs. Adds a recenter pill in the bottom-right that appears when nothing in the current viewport intersects any content, and a translucent shortcut cheatsheet that appears after holding Ctrl/Cmd alone for 3s. New Figma-style shortcuts: V/L/T tool switches, Cmd/Ctrl+A select all, Cmd/Ctrl+G group, Cmd/Ctrl+Shift+G ungroup, Shift+1 zoom-to-fit. Consolidates all previously-duplicated rect / AABB / clamp / viewport math into `layout/geometry.ts` (removes private copies from useSelection, useViewportControls, MoodboardStore, and packCollage). Exports include `computeContentBounds`, `computeVisibleRect`, `anyContentVisible`, `fitViewportToBounds`, `panToCenterOn`, `ZOOM_MIN/MAX` — everything a future minimap overlay will need. Canvas perf pass: - Level-of-detail dotted grid (doubles effective spacing as you zoom out so dot count stays bounded; dot radius tracks screen pixels). - React.memo on ImageNode, TextNode, GroupNode, MoodboardBackground. - Stable onSelect contract (children receive (id, e) and call a single parent callback, letting memo skip children on camera/selection-only renders). - GroupNode subscribes only to its own children via useShallow, not the full nodes map. - TextNode's editingTextId selector collapsed to a per-node boolean. - MoodboardStage's transient subscription narrowed to {marquee, lassoPath} so setIsPanning / setEditingText don't churn the whole Stage. - visibleViewport memoized so marquee/lasso drags don't force the background sceneFunc to re-run. --- .../app/src/pages/PageMoodboard/Moodboard.tsx | 8 + .../PageMoodboard/MoodboardBackground.tsx | 43 +++-- .../pages/PageMoodboard/MoodboardStage.tsx | 111 ++++++----- .../src/pages/PageMoodboard/MoodboardStore.ts | 59 +++--- .../interactions/useKeyboardShortcuts.ts | 77 ++++++++ .../interactions/useSelection.ts | 37 +--- .../interactions/useShortcutCheatsheet.ts | 74 ++++++++ .../interactions/useViewportControls.ts | 43 ++--- .../pages/PageMoodboard/layout/geometry.ts | 174 ++++++++++++++++++ .../pages/PageMoodboard/layout/packCollage.ts | 15 -- .../pages/PageMoodboard/nodes/GroupNode.tsx | 46 +++-- .../pages/PageMoodboard/nodes/ImageNode.tsx | 21 ++- .../pages/PageMoodboard/nodes/TextNode.tsx | 25 ++- .../overlays/RecenterIndicator.tsx | 32 ++++ .../overlays/ShortcutCheatsheet.tsx | 76 ++++++++ .../pages/PageMoodboard/overlays/shortcuts.ts | 46 +++++ .../PageMoodboard/layout/packCollage.test.ts | 3 +- 17 files changed, 718 insertions(+), 172 deletions(-) create mode 100644 frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useKeyboardShortcuts.ts create mode 100644 frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useShortcutCheatsheet.ts create mode 100644 frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/geometry.ts create mode 100644 frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/RecenterIndicator.tsx create mode 100644 frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/ShortcutCheatsheet.tsx create mode 100644 frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/shortcuts.ts diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/Moodboard.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/Moodboard.tsx index ee924015f6..493c9143c9 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/Moodboard.tsx +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/Moodboard.tsx @@ -7,6 +7,10 @@ import { useMoodboardStore } from "./MoodboardStore"; import { useUndoRedo } from "./interactions/useUndoRedo"; import { usePasteHandler } from "./interactions/usePasteHandler"; import { useGalleryDropEvent } from "./interactions/useGalleryDropEvent"; +import { useKeyboardShortcuts } from "./interactions/useKeyboardShortcuts"; +import { useShortcutCheatsheet } from "./interactions/useShortcutCheatsheet"; +import { RecenterIndicator } from "./overlays/RecenterIndicator"; +import { ShortcutCheatsheet } from "./overlays/ShortcutCheatsheet"; export const Moodboard = () => { const containerRef = useRef(null); @@ -18,6 +22,8 @@ export const Moodboard = () => { useUndoRedo(true); usePasteHandler(true, stageRef); useGalleryDropEvent(true, stageRef); + useKeyboardShortcuts(true); + const cheatsheetVisible = useShortcutCheatsheet(); // Delete / Backspace removes the current selection. Skip when typing in // an input or while a text node is in edit mode. @@ -44,6 +50,8 @@ export const Moodboard = () => {
+ +
); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardBackground.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardBackground.tsx index c579725234..d1dbd47fb2 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardBackground.tsx +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardBackground.tsx @@ -1,3 +1,4 @@ +import { memo } from "react"; import { Shape } from "react-konva"; import Konva from "konva"; import { Rect } from "./types"; @@ -6,35 +7,53 @@ interface Props { // Visible region in stage (document) coordinates. Driven by pan/zoom. viewport: Rect; spacing: number; + zoom: number; dotColor?: string; - dotRadius?: number; + // On-screen radius in CSS pixels. Converted to stage units so dots stay + // the same visual size regardless of zoom. + dotRadiusPx?: number; } +// Minimum on-screen gap between dots before we drop to a coarser grid. +// At zoom 1× with spacing 32, dots are 32px apart; as you zoom out, the +// LOD step doubles `spacing` so density never drops below this bound. +const MIN_SCREEN_SPACING = 16; + // Vector dotted grid that follows the visible viewport. Dots stay anchored -// at fixed stage coords (multiples of `spacing`); panning reveals more, -// zooming in spaces them apart on screen. -export const MoodboardBackground = ({ +// at fixed stage coords (multiples of the effective spacing); zooming out +// coarsens the grid in powers of 2 so we never draw tens of thousands of +// arcs per frame. +const MoodboardBackgroundInner = ({ viewport, spacing, + zoom, dotColor = "rgba(255,255,255,0.18)", - dotRadius = 1.2, + dotRadiusPx = 1.2, }: Props) => { + const baseOnScreen = spacing * zoom; + const lodStep = + baseOnScreen >= MIN_SCREEN_SPACING + ? 0 + : Math.ceil(Math.log2(MIN_SCREEN_SPACING / Math.max(baseOnScreen, 1e-6))); + const effectiveSpacing = spacing * Math.pow(2, lodStep); + const radius = dotRadiusPx / Math.max(zoom, 1e-6); + return ( { - const startX = Math.floor(viewport.x / spacing) * spacing; - const startY = Math.floor(viewport.y / spacing) * spacing; + const startX = Math.floor(viewport.x / effectiveSpacing) * effectiveSpacing; + const startY = Math.floor(viewport.y / effectiveSpacing) * effectiveSpacing; const endX = viewport.x + viewport.width; const endY = viewport.y + viewport.height; ctx.fillStyle = dotColor; ctx.beginPath(); - for (let x = startX; x <= endX; x += spacing) { - for (let y = startY; y <= endY; y += spacing) { - ctx.moveTo(x + dotRadius, y); - ctx.arc(x, y, dotRadius, 0, Math.PI * 2); + for (let x = startX; x <= endX; x += effectiveSpacing) { + for (let y = startY; y <= endY; y += effectiveSpacing) { + ctx.moveTo(x + radius, y); + ctx.arc(x, y, radius, 0, Math.PI * 2); } } ctx.fill(); @@ -43,3 +62,5 @@ export const MoodboardBackground = ({ /> ); }; + +export const MoodboardBackground = memo(MoodboardBackgroundInner); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStage.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStage.tsx index da6b139e37..6965ad2a94 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStage.tsx +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStage.tsx @@ -1,6 +1,7 @@ -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo } from "react"; import Konva from "konva"; import { Stage, Layer, Rect, Line, Group, Transformer } from "react-konva"; +import { useShallow } from "zustand/react/shallow"; import { useMoodboardStore } from "./MoodboardStore"; import { MoodboardBackground } from "./MoodboardBackground"; import { ImageNode } from "./nodes/ImageNode"; @@ -10,7 +11,6 @@ import { useSelection } from "./interactions/useSelection"; import { useTransformer } from "./interactions/useTransformer"; import { useViewportControls } from "./interactions/useViewportControls"; import { stagePointerPos } from "./interactions/useStagePointer"; -import { Vec2 } from "./types"; interface Props { containerRef: React.RefObject; @@ -20,40 +20,48 @@ interface Props { export const MoodboardStage = ({ containerRef, stageRef }: Props) => { const transformerRef = useTransformer(stageRef); - const [size, setSize] = useState({ width: 800, height: 600 }); - const [zoom, setZoom] = useState(1); - const [pan, setPan] = useState({ x: 0, y: 0 }); - const zoomRef = useRef(zoom); - const panRef = useRef(pan); - zoomRef.current = zoom; - panRef.current = pan; - const nodes = useMoodboardStore((s) => s.nodes); const rootOrder = useMoodboardStore((s) => s.rootOrder); const selectedIds = useMoodboardStore((s) => s.selectedIds); const tool = useMoodboardStore((s) => s.tool); const gridSpacing = useMoodboardStore((s) => s.gridSpacing); - const transient = useMoodboardStore((s) => s.transient); + // Only subscribe to the transient fields this component actually renders + // (marquee + lasso). Skips re-renders on `editingTextId` and `isPanning` + // toggles, which don't affect Stage JSX. + const { marquee, lassoPath } = useMoodboardStore( + useShallow((s) => ({ + marquee: s.transient.marquee, + lassoPath: s.transient.lassoPath, + })), + ); + const viewport = useMoodboardStore((s) => s.viewport); + const canvasSize = useMoodboardStore((s) => s.canvasSize); const setLastDropPoint = useMoodboardStore((s) => s.setLastDropPoint); + const setCanvasSize = useMoodboardStore((s) => s.setCanvasSize); const toggleInSelection = useMoodboardStore((s) => s.toggleInSelection); const setEditingText = useMoodboardStore((s) => s.setEditingText); const addText = useMoodboardStore((s) => s.addText); + const zoom = viewport.zoom; + const pan = viewport.pan; + // Track wrapper size with ResizeObserver so the Stage fills its container. + // The size lives in the store so overlays (recenter indicator, future + // minimap) can read it without drilling refs through the tree. useEffect(() => { const el = containerRef.current; if (!el) return undefined; const updateSize = () => { - setSize({ width: el.clientWidth, height: el.clientHeight }); + setCanvasSize({ width: el.clientWidth, height: el.clientHeight }); }; updateSize(); const ro = new ResizeObserver(updateSize); ro.observe(el); return () => ro.disconnect(); - }, [containerRef]); + }, [containerRef, setCanvasSize]); useSelection(stageRef); - useViewportControls(stageRef, { zoomRef, panRef, setZoom, setPan }); + useViewportControls(stageRef); // Update lastDropPoint as the cursor moves across the stage so external // drops (uploads, paste fallbacks) land near the cursor. @@ -70,14 +78,17 @@ export const MoodboardStage = ({ containerRef, stageRef }: Props) => { }; }, [setLastDropPoint, stageRef]); - const handleNodeSelect = ( - id: string, - e: Konva.KonvaEventObject, - ) => { - const evt = e.evt as MouseEvent | TouchEvent; - const additive = "shiftKey" in evt && evt.shiftKey; - toggleInSelection(id, additive); - }; + // Stable across renders so memoized node children see an unchanged + // onSelect prop and skip re-render when only camera/selection state + // changes. Depends only on a Zustand action, which itself is stable. + const handleNodeSelect = useCallback( + (id: string, e: Konva.KonvaEventObject) => { + const evt = e.evt as MouseEvent | TouchEvent; + const additive = "shiftKey" in evt && evt.shiftKey; + toggleInSelection(id, additive); + }, + [toggleInSelection], + ); const handleStageClick = (e: Konva.KonvaEventObject) => { if (e.target !== stageRef.current) return; @@ -95,20 +106,26 @@ export const MoodboardStage = ({ containerRef, stageRef }: Props) => { // Visible region in stage coords; drives the dotted background grid so // it follows pan/zoom rather than rendering a fixed (0,0,w,h) block. - const visibleViewport = { - x: -pan.x / zoom, - y: -pan.y / zoom, - width: size.width / zoom, - height: size.height / zoom, - }; + // Memoized so transient store updates (marquee, lasso, isPanning) don't + // churn its identity and force `MoodboardBackground` to re-run sceneFunc + // every frame of a marquee drag. + const visibleViewport = useMemo( + () => ({ + x: -pan.x / zoom, + y: -pan.y / zoom, + width: canvasSize.width / zoom, + height: canvasSize.height / zoom, + }), + [pan.x, pan.y, zoom, canvasSize.width, canvasSize.height], + ); return ( { stageRef.current = s; }} - width={size.width} - height={size.height} + width={canvasSize.width} + height={canvasSize.height} x={pan.x} y={pan.y} scaleX={zoom} @@ -125,24 +142,26 @@ export const MoodboardStage = ({ containerRef, stageRef }: Props) => { height={visibleViewport.height} fill="#0f0f12" /> - + {rootOrder.map((id) => { const n = nodes[id]; if (!n) return null; const selected = selectedIds.has(id); - const onSelect = ( - e: Konva.KonvaEventObject, - ) => handleNodeSelect(id, e); + const draggable = tool === "select"; if (n.kind === "image") { return ( ); } @@ -151,9 +170,9 @@ export const MoodboardStage = ({ containerRef, stageRef }: Props) => { ); } @@ -163,7 +182,7 @@ export const MoodboardStage = ({ containerRef, stageRef }: Props) => { key={id} node={n} selected={selected} - onSelect={onSelect} + onSelect={handleNodeSelect} /> ); } @@ -233,21 +252,21 @@ export const MoodboardStage = ({ containerRef, stageRef }: Props) => { /> ); })} - {transient.marquee && ( + {marquee && ( )} - {transient.lassoPath && transient.lassoPath.length >= 2 && ( + {lassoPath && lassoPath.length >= 2 && ( [p.x, p.y])} + points={lassoPath.flatMap((p) => [p.x, p.y])} stroke="#3b82f6" strokeWidth={1 / zoom} dash={[4 / zoom, 4 / zoom]} diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStore.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStore.ts index 49365b0f2e..11d9d4d6e4 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStore.ts +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/MoodboardStore.ts @@ -11,6 +11,13 @@ import { Vec2, } from "./types"; import { useMoodboardHistoryStore } from "./MoodboardHistoryStore"; +import { + CanvasSize, + Viewport, + computeAABBById, + computeContentBounds, + fitViewportToBounds, +} from "./layout/geometry"; interface Transient { marquee: Rect | null; @@ -26,10 +33,18 @@ interface MoodboardState { tool: Tool; gridSpacing: number; lastDropPoint: Vec2; + viewport: Viewport; + canvasSize: CanvasSize; transient: Transient; setTool: (t: Tool) => void; setLastDropPoint: (p: Vec2) => void; + setZoom: (z: number) => void; + setPan: (p: Vec2) => void; + setCanvasSize: (s: CanvasSize) => void; + resetViewport: () => void; + fitToContent: (padding?: number) => void; + selectAll: () => void; addImage: ( src: string, @@ -90,6 +105,8 @@ export const useMoodboardStore = create((set, get) => ({ tool: "select", gridSpacing: 32, lastDropPoint: { x: 200, y: 200 }, + viewport: { zoom: 1, pan: { x: 0, y: 0 } }, + canvasSize: { width: 800, height: 600 }, transient: { marquee: null, lassoPath: null, @@ -99,6 +116,22 @@ export const useMoodboardStore = create((set, get) => ({ setTool: (t) => set({ tool: t }), setLastDropPoint: (p) => set({ lastDropPoint: p }), + setZoom: (z) => set((s) => ({ viewport: { ...s.viewport, zoom: z } })), + setPan: (p) => set((s) => ({ viewport: { ...s.viewport, pan: p } })), + setCanvasSize: (sz) => set({ canvasSize: sz }), + resetViewport: () => + set({ viewport: { zoom: 1, pan: { x: 0, y: 0 } } }), + fitToContent: (padding = 48) => { + const { nodes, rootOrder, canvasSize } = get(); + const bounds = computeContentBounds(nodes, rootOrder); + if (!bounds) return; + set({ viewport: fitViewportToBounds(bounds, canvasSize, padding) }); + }, + selectAll: () => { + const { rootOrder } = get(); + if (rootOrder.length === 0) return; + set({ selectedIds: new Set(rootOrder) }); + }, addImage: (src, pos, naturalW, naturalH, mediaId = null) => { get().pushHistory(); @@ -242,7 +275,7 @@ export const useMoodboardStore = create((set, get) => ({ get().pushHistory(); const groupId = uuidv4(); - const aabb = computeAABB(nodes, topLevelIds); + const aabb = computeAABBById(nodes, topLevelIds); if (!aabb) return null; const groupNode: GroupNode = { @@ -301,7 +334,7 @@ export const useMoodboardStore = create((set, get) => ({ return n && n.parentId === null; }); if (topLevelIds.length < 2) continue; - const aabb = computeAABB(newNodes, topLevelIds); + const aabb = computeAABBById(newNodes, topLevelIds); if (!aabb) continue; const groupId = uuidv4(); const groupNode: GroupNode = { @@ -440,6 +473,7 @@ export const useMoodboardStore = create((set, get) => ({ selectedIds: new Set(), tool: "select", lastDropPoint: { x: 200, y: 200 }, + viewport: { zoom: 1, pan: { x: 0, y: 0 } }, transient: { marquee: null, lassoPath: null, @@ -484,27 +518,6 @@ const stripAncestorsAndDescendants = ( return result; }; -const computeAABB = ( - nodes: Record, - ids: string[], -): Rect | null => { - if (ids.length === 0) return null; - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const id of ids) { - const n = nodes[id]; - if (!n) continue; - minX = Math.min(minX, n.x); - minY = Math.min(minY, n.y); - maxX = Math.max(maxX, n.x + n.width); - maxY = Math.max(maxY, n.y + n.height); - } - if (!isFinite(minX)) return null; - return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; -}; - // Maps a group-local point to stage-local coords using the group's transform. const applyGroupTransform = (local: Vec2, g: GroupNode): Vec2 => { const rad = (g.rotation * Math.PI) / 180; diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useKeyboardShortcuts.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useKeyboardShortcuts.ts new file mode 100644 index 0000000000..693831ecdf --- /dev/null +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useKeyboardShortcuts.ts @@ -0,0 +1,77 @@ +import { useEffect } from "react"; +import { useMoodboardStore } from "../MoodboardStore"; + +const isEditableTarget = (target: EventTarget | null): boolean => { + const el = target as HTMLElement | null; + if (!el) return false; + if (/input|textarea/i.test(el.tagName)) return true; + if (el.isContentEditable) return true; + return false; +}; + +// Figma-style shortcuts that aren't already wired elsewhere. +// Cmd+Z / Cmd+Shift+Z live in useUndoRedo; Cmd+0 + Space-pan live in +// useViewportControls; Delete / Escape live in Moodboard.tsx. +export const useKeyboardShortcuts = (active: boolean) => { + const setTool = useMoodboardStore((s) => s.setTool); + const selectAll = useMoodboardStore((s) => s.selectAll); + const group = useMoodboardStore((s) => s.group); + const ungroup = useMoodboardStore((s) => s.ungroup); + const fitToContent = useMoodboardStore((s) => s.fitToContent); + + useEffect(() => { + if (!active) return undefined; + const isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform); + + const handler = (e: KeyboardEvent) => { + if (isEditableTarget(e.target)) return; + // Skip while typing in the text-edit overlay (covered by isEditableTarget + // too, but belt-and-suspenders in case the overlay loses target focus). + if (useMoodboardStore.getState().transient.editingTextId) return; + + const mod = isMac ? e.metaKey : e.ctrlKey; + const k = e.key.toLowerCase(); + + // Modifier combos + if (mod && !e.shiftKey && k === "a") { + e.preventDefault(); + selectAll(); + return; + } + if (mod && !e.shiftKey && k === "g") { + e.preventDefault(); + group(); + return; + } + if (mod && e.shiftKey && k === "g") { + e.preventDefault(); + ungroup(); + return; + } + + // Shift-only combos + if (e.shiftKey && !mod && !e.altKey && k === "1") { + e.preventDefault(); + fitToContent(); + return; + } + + // Plain (no modifiers) tool switches — skip if any modifier is held + // so Cmd+V (paste) etc. never triggers the Text tool. + if (mod || e.shiftKey || e.altKey) return; + if (k === "v") { + e.preventDefault(); + setTool("select"); + } else if (k === "l") { + e.preventDefault(); + setTool("lasso"); + } else if (k === "t") { + e.preventDefault(); + setTool("text"); + } + }; + + document.addEventListener("keydown", handler); + return () => document.removeEventListener("keydown", handler); + }, [active, setTool, selectAll, group, ungroup, fitToContent]); +}; diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useSelection.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useSelection.ts index 5fbbf97969..02e0f2a743 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useSelection.ts +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useSelection.ts @@ -1,10 +1,11 @@ import { useEffect, useRef } from "react"; import Konva from "konva"; import { useMoodboardStore } from "../MoodboardStore"; -import { Rect, Vec2 } from "../types"; +import { Vec2 } from "../types"; import { stagePointerPos } from "./useStagePointer"; import { pointInPolygon } from "../layout/pointInPolygon"; import { polygonIntersectsRect } from "../layout/segmentsIntersect"; +import { rectCorners, rectFromPoints, rectsIntersect } from "../layout/geometry"; const MIN_DRAG = 4; // screen px before a press becomes a drag @@ -15,31 +16,6 @@ interface DragState { mode: "rect" | "lasso" | null; } -const rectFromPoints = (a: Vec2, b: Vec2): Rect => ({ - x: Math.min(a.x, b.x), - y: Math.min(a.y, b.y), - width: Math.abs(b.x - a.x), - height: Math.abs(b.y - a.y), -}); - -const aabbCorners = (n: { x: number; y: number; width: number; height: number }): Vec2[] => [ - { x: n.x, y: n.y }, - { x: n.x + n.width, y: n.y }, - { x: n.x + n.width, y: n.y + n.height }, - { x: n.x, y: n.y + n.height }, -]; - -const intersectsRect = ( - n: { x: number; y: number; width: number; height: number }, - r: Rect, -) => - !( - n.x + n.width < r.x || - n.x > r.x + r.width || - n.y + n.height < r.y || - n.y > r.y + r.height - ); - // Selection state machine for rectangle marquee (Select tool) and free-form // lasso (Lasso tool). Pan gestures (middle-mouse, spacebar+left) are owned // by `useViewportControls` and stop the event at the capture phase, so @@ -110,7 +86,12 @@ export const useSelection = ( setSelection([]); } else { const hit = candidates - .filter((n) => intersectsRect(n, rect)) + .filter((n) => + rectsIntersect( + { x: n.x, y: n.y, width: n.width, height: n.height }, + rect, + ), + ) .map((n) => n.id); setSelection(hit); } @@ -123,7 +104,7 @@ export const useSelection = ( const closed = [...path, path[0]]; const hit = candidates .filter((n) => { - const corners = aabbCorners(n); + const corners = rectCorners(n); if (corners.some((c) => pointInPolygon(c, closed))) return true; if (polygonIntersectsRect(closed, n)) return true; return false; diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useShortcutCheatsheet.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useShortcutCheatsheet.ts new file mode 100644 index 0000000000..29fe4a6d38 --- /dev/null +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useShortcutCheatsheet.ts @@ -0,0 +1,74 @@ +import { useEffect, useState } from "react"; + +const HOLD_MS = 3000; + +// Shows the cheatsheet when the user holds Ctrl (or Cmd on Mac) alone for +// HOLD_MS with no other key pressed. Any other keydown cancels the timer, +// so a real `Ctrl+C` / `Cmd+X` never trips it. Releasing the modifier hides +// the cheatsheet immediately. +export const useShortcutCheatsheet = (): boolean => { + const [visible, setVisible] = useState(false); + + useEffect(() => { + const isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform); + const modKey = isMac ? "Meta" : "Control"; + let timer: ReturnType | null = null; + let modHeld = false; + + const clearTimer = () => { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + }; + + const hide = () => { + setVisible((v) => (v ? false : v)); + }; + + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === modKey) { + // Ignore auto-repeat keydown while already held. + if (modHeld) return; + modHeld = true; + clearTimer(); + timer = setTimeout(() => { + timer = null; + setVisible(true); + }, HOLD_MS); + return; + } + // Any non-modifier key press while the modifier is held cancels the + // planned cheatsheet — the user is running a real combo. + clearTimer(); + hide(); + }; + + const onKeyUp = (e: KeyboardEvent) => { + if (e.key === modKey) { + modHeld = false; + clearTimer(); + hide(); + } + }; + + // Losing focus while holding the key should also cancel. + const onBlur = () => { + modHeld = false; + clearTimer(); + hide(); + }; + + document.addEventListener("keydown", onKeyDown); + document.addEventListener("keyup", onKeyUp); + window.addEventListener("blur", onBlur); + return () => { + document.removeEventListener("keydown", onKeyDown); + document.removeEventListener("keyup", onKeyUp); + window.removeEventListener("blur", onBlur); + clearTimer(); + }; + }, []); + + return visible; +}; diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useViewportControls.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useViewportControls.ts index b43e60870b..7b4169ad78 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useViewportControls.ts +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/interactions/useViewportControls.ts @@ -2,20 +2,9 @@ import { useEffect, useRef } from "react"; import Konva from "konva"; import { useMoodboardStore } from "../MoodboardStore"; import { Vec2 } from "../types"; +import { ZOOM_MAX, ZOOM_MIN, clamp } from "../layout/geometry"; const ZOOM_STEP = 1.1; -const MIN_ZOOM = 0.1; -const MAX_ZOOM = 8; - -interface ViewportSetters { - zoomRef: React.MutableRefObject; - panRef: React.MutableRefObject; - setZoom: (z: number) => void; - setPan: (p: Vec2) => void; -} - -const clamp = (v: number, lo: number, hi: number) => - Math.max(lo, Math.min(hi, v)); const isEditableTarget = (target: EventTarget | null): boolean => { const el = target as HTMLElement | null; @@ -26,14 +15,16 @@ const isEditableTarget = (target: EventTarget | null): boolean => { }; // Centralizes wheel-zoom and three pan gestures (drag-empty, spacebar+drag, -// middle-click drag) for the moodboard canvas. Owns no state of its own — -// reads zoom/pan from refs (live values) and writes through the provided -// setters so React state stays in sync. +// middle-click drag) for the moodboard canvas. Reads/writes viewport from +// the store directly — no more ref props, which keeps a future minimap or +// other camera-driving UI (recenter button, Shift+1 fit, etc.) able to +// co-exist with these gestures. export const useViewportControls = ( stageRef: React.RefObject, - setters: ViewportSetters, ) => { - const { zoomRef, panRef, setZoom, setPan } = setters; + const setZoom = useMoodboardStore((s) => s.setZoom); + const setPan = useMoodboardStore((s) => s.setPan); + const resetViewport = useMoodboardStore((s) => s.resetViewport); const setIsPanning = useMoodboardStore((s) => s.setIsPanning); // Track spacebar so any subsequent mousedown becomes a pan, not a select. @@ -60,10 +51,11 @@ export const useViewportControls = ( // Ignore zoom if the user is typing in the text-edit overlay or an input. if (isEditableTarget(document.activeElement)) return; e.preventDefault(); - const oldScale = zoomRef.current; + const { viewport } = useMoodboardStore.getState(); + const oldScale = viewport.zoom; const pointer = stage.getPointerPosition(); if (!pointer) return; - const stagePos = panRef.current; + const stagePos = viewport.pan; const mousePointTo = { x: (pointer.x - stagePos.x) / oldScale, y: (pointer.y - stagePos.y) / oldScale, @@ -71,8 +63,8 @@ export const useViewportControls = ( const direction = e.deltaY > 0 ? -1 : 1; const newScale = clamp( direction > 0 ? oldScale * ZOOM_STEP : oldScale / ZOOM_STEP, - MIN_ZOOM, - MAX_ZOOM, + ZOOM_MIN, + ZOOM_MAX, ); const newPan = { x: pointer.x - mousePointTo.x * newScale, @@ -86,7 +78,7 @@ export const useViewportControls = ( return () => { container.removeEventListener("wheel", handleWheel); }; - }, [stageRef, zoomRef, panRef, setZoom, setPan]); + }, [stageRef, setZoom, setPan]); // Pan gestures: middle-mouse drag, or spacebar+left-drag. Plain left // click is reserved for selection (clicking nodes, lasso, future marquee) @@ -100,7 +92,7 @@ export const useViewportControls = ( panState.current = { active: true, startScreen: { x: clientX, y: clientY }, - startPan: { ...panRef.current }, + startPan: { ...useMoodboardStore.getState().viewport.pan }, }; setIsPanning(true); container.style.cursor = "grabbing"; @@ -156,8 +148,7 @@ export const useViewportControls = ( const mod = isMac ? e.metaKey : e.ctrlKey; if (mod && e.key === "0") { e.preventDefault(); - setZoom(1); - setPan({ x: 0, y: 0 }); + resetViewport(); } }; @@ -186,5 +177,5 @@ export const useViewportControls = ( document.removeEventListener("keyup", handleKeyUp); container.style.cursor = ""; }; - }, [stageRef, panRef, setPan, setZoom, setIsPanning]); + }, [stageRef, setPan, resetViewport, setIsPanning]); }; diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/geometry.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/geometry.ts new file mode 100644 index 0000000000..7e923f0864 --- /dev/null +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/geometry.ts @@ -0,0 +1,174 @@ +import { MoodboardNode, Rect, Vec2 } from "../types"; + +export interface Viewport { + zoom: number; + pan: Vec2; +} + +export interface CanvasSize { + width: number; + height: number; +} + +// Global zoom clamps — shared by gesture handlers, fit-to-content, and any +// future minimap so the camera can never land outside a consistent range. +export const ZOOM_MIN = 0.1; +export const ZOOM_MAX = 8; + +// ---------- scalar + rect primitives ---------- + +export const clamp = (v: number, lo: number, hi: number): number => + Math.max(lo, Math.min(hi, v)); + +export const rectFromPoints = (a: Vec2, b: Vec2): Rect => ({ + x: Math.min(a.x, b.x), + y: Math.min(a.y, b.y), + width: Math.abs(b.x - a.x), + height: Math.abs(b.y - a.y), +}); + +export const rectCorners = (r: { + x: number; + y: number; + width: number; + height: number; +}): Vec2[] => [ + { x: r.x, y: r.y }, + { x: r.x + r.width, y: r.y }, + { x: r.x + r.width, y: r.y + r.height }, + { x: r.x, y: r.y + r.height }, +]; + +export const rectsIntersect = (a: Rect, b: Rect): boolean => + !( + a.x + a.width < b.x || + a.x > b.x + b.width || + a.y + a.height < b.y || + a.y > b.y + b.height + ); + +// ---------- AABB over a set of nodes ---------- + +export const computeAABB = (nodes: MoodboardNode[]): Rect | null => { + if (nodes.length === 0) return null; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const n of nodes) { + minX = Math.min(minX, n.x); + minY = Math.min(minY, n.y); + maxX = Math.max(maxX, n.x + n.width); + maxY = Math.max(maxY, n.y + n.height); + } + if (!Number.isFinite(minX)) return null; + return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; +}; + +export const computeAABBById = ( + nodes: Record, + ids: string[], +): Rect | null => { + const picked: MoodboardNode[] = []; + for (const id of ids) { + const n = nodes[id]; + if (n) picked.push(n); + } + return computeAABB(picked); +}; + +// AABB of every top-level node. Treats rotated nodes as their own +// (x, y, w, h) rect for simplicity — fine for "is content on screen?" +// checks and minimap overviews. +export const computeContentBounds = ( + nodes: Record, + rootOrder: string[], +): Rect | null => computeAABBById(nodes, rootOrder); + +// ---------- viewport math ---------- + +// Visible stage-coord rect = what the camera currently sees. +// canvas_px = pan + stage_coord * zoom, so the visible stage region maps to +// (-pan / zoom) .. (-pan / zoom + canvas / zoom). +export const computeVisibleRect = ( + viewport: Viewport, + canvas: CanvasSize, +): Rect => ({ + x: -viewport.pan.x / viewport.zoom, + y: -viewport.pan.y / viewport.zoom, + width: canvas.width / viewport.zoom, + height: canvas.height / viewport.zoom, +}); + +// True if any top-level node's AABB intersects the visible viewport. +// Used by the recenter indicator; a minimap can use this to style the +// viewport rectangle differently when off-content. +export const anyContentVisible = ( + nodes: Record, + rootOrder: string[], + viewport: Viewport, + canvas: CanvasSize, +): boolean => { + const visible = computeVisibleRect(viewport, canvas); + for (const id of rootOrder) { + const n = nodes[id]; + if (!n) continue; + if ( + rectsIntersect( + { x: n.x, y: n.y, width: n.width, height: n.height }, + visible, + ) + ) { + return true; + } + } + return false; +}; + +// Returns the viewport that frames `bounds` inside `canvas` with `padding` +// screen pixels of margin on all sides, clamped to [ZOOM_MIN, ZOOM_MAX]. +// Degenerate bounds (zero width/height) fall back to zoom=1 centered on +// the point. +export const fitViewportToBounds = ( + bounds: Rect, + canvas: CanvasSize, + padding: number, +): Viewport => { + if (bounds.width <= 0 || bounds.height <= 0) { + return { + zoom: 1, + pan: { + x: canvas.width / 2 - bounds.x, + y: canvas.height / 2 - bounds.y, + }, + }; + } + const availW = Math.max(canvas.width - 2 * padding, 1); + const availH = Math.max(canvas.height - 2 * padding, 1); + const zoom = clamp( + Math.min(availW / bounds.width, availH / bounds.height), + ZOOM_MIN, + ZOOM_MAX, + ); + const centerX = bounds.x + bounds.width / 2; + const centerY = bounds.y + bounds.height / 2; + return { + zoom, + pan: { + x: canvas.width / 2 - centerX * zoom, + y: canvas.height / 2 - centerY * zoom, + }, + }; +}; + +// Returns the pan that centers the viewport on a given stage-coord point +// at the current zoom. Handy for minimap drag-to-navigate: stage point +// under the minimap cursor → pan such that it lands in the canvas center. +export const panToCenterOn = ( + stagePoint: Vec2, + zoom: number, + canvas: CanvasSize, +): Vec2 => ({ + x: canvas.width / 2 - stagePoint.x * zoom, + y: canvas.height / 2 - stagePoint.y * zoom, +}); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/packCollage.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/packCollage.ts index 5724b2a3a3..9810d19467 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/packCollage.ts +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/layout/packCollage.ts @@ -8,21 +8,6 @@ export interface PackOptions { const DEFAULTS: PackOptions = { rowHeight: 180, gap: 8 }; -export const computeAABB = (nodes: MoodboardNode[]): Rect | null => { - if (nodes.length === 0) return null; - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const n of nodes) { - minX = Math.min(minX, n.x); - minY = Math.min(minY, n.y); - maxX = Math.max(maxX, n.x + n.width); - maxY = Math.max(maxY, n.y + n.height); - } - return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; -}; - export const computePackPatches = ( nodes: MoodboardNode[], bounds: Rect, diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/GroupNode.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/GroupNode.tsx index 2c56b965f3..1dbf6f4aee 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/GroupNode.tsx +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/GroupNode.tsx @@ -1,5 +1,7 @@ +import { memo } from "react"; import Konva from "konva"; import { Group, Rect } from "react-konva"; +import { useShallow } from "zustand/react/shallow"; import { GroupNode as GroupNodeData, MoodboardNode } from "../types"; import { useMoodboardStore } from "../MoodboardStore"; import { ImageNode } from "./ImageNode"; @@ -8,17 +10,37 @@ import { TextNode } from "./TextNode"; interface Props { node: GroupNodeData; selected: boolean; - onSelect: (e: Konva.KonvaEventObject) => void; + onSelect: ( + id: string, + e: Konva.KonvaEventObject, + ) => void; } -export const GroupNode = ({ node, selected, onSelect }: Props) => { - const nodes = useMoodboardStore((s) => s.nodes); +// Shared no-op for child renders: the group absorbs all clicks, so child +// nodes never fire `onSelect`. Using a module-level constant keeps the +// reference stable across renders, which lets the memoized child nodes +// skip work when nothing else about them changed. +const NO_OP_SELECT = () => {}; + +const GroupNodeInner = ({ node, selected, onSelect }: Props) => { const updateNode = useMoodboardStore((s) => s.updateNode); const pushHistory = useMoodboardStore((s) => s.pushHistory); - const children: MoodboardNode[] = node.childIds - .map((id) => nodes[id]) - .filter((n): n is MoodboardNode => Boolean(n)); + // Subscribe only to this group's own children, with a shallow compare on + // the returned array. Avoids re-rendering every group whenever any node + // anywhere in the board updates (which would otherwise mutate the whole + // `nodes` map reference). + const children = useMoodboardStore( + useShallow((s) => + node.childIds + .map((id) => s.nodes[id]) + .filter((n): n is MoodboardNode => Boolean(n)), + ), + ); + + const handleSelect = ( + e: Konva.KonvaEventObject, + ) => onSelect(node.id, e); return ( { height={node.height} rotation={node.rotation} draggable - onMouseDown={onSelect} - onTouchStart={onSelect} + onMouseDown={handleSelect} + onTouchStart={handleSelect} onDragStart={() => { pushHistory(); }} @@ -58,7 +80,7 @@ export const GroupNode = ({ node, selected, onSelect }: Props) => { node={child} draggable={false} selected={false} - onSelect={() => {}} + onSelect={NO_OP_SELECT} /> ); } @@ -69,7 +91,7 @@ export const GroupNode = ({ node, selected, onSelect }: Props) => { node={child} draggable={false} selected={false} - onSelect={() => {}} + onSelect={NO_OP_SELECT} /> ); } @@ -80,7 +102,7 @@ export const GroupNode = ({ node, selected, onSelect }: Props) => { key={child.id} node={child} selected={false} - onSelect={() => {}} + onSelect={NO_OP_SELECT} /> ); } @@ -89,3 +111,5 @@ export const GroupNode = ({ node, selected, onSelect }: Props) => { ); }; + +export const GroupNode = memo(GroupNodeInner); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/ImageNode.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/ImageNode.tsx index 783e089a43..2e522f2582 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/ImageNode.tsx +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/ImageNode.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { memo, useEffect, useRef, useState } from "react"; import Konva from "konva"; import { Image as KonvaImage, Rect } from "react-konva"; import { ImageNode as ImageNodeData } from "../types"; @@ -8,10 +8,15 @@ interface Props { node: ImageNodeData; draggable: boolean; selected: boolean; - onSelect: (e: Konva.KonvaEventObject) => void; + // Receives the node id so parents can pass one stable callback to every + // sibling rather than allocating a per-item closure on each render. + onSelect: ( + id: string, + e: Konva.KonvaEventObject, + ) => void; } -export const ImageNode = ({ node, draggable, selected, onSelect }: Props) => { +const ImageNodeInner = ({ node, draggable, selected, onSelect }: Props) => { const updateNode = useMoodboardStore((s) => s.updateNode); const pushHistory = useMoodboardStore((s) => s.pushHistory); const ref = useRef(null); @@ -27,6 +32,10 @@ export const ImageNode = ({ node, draggable, selected, onSelect }: Props) => { }; }, [node.src]); + const handleSelect = ( + e: Konva.KonvaEventObject, + ) => onSelect(node.id, e); + return ( <> {!img && ( @@ -53,8 +62,8 @@ export const ImageNode = ({ node, draggable, selected, onSelect }: Props) => { height={node.height} rotation={node.rotation} draggable={draggable} - onMouseDown={onSelect} - onTouchStart={onSelect} + onMouseDown={handleSelect} + onTouchStart={handleSelect} onDragStart={() => { pushHistory(); }} @@ -65,3 +74,5 @@ export const ImageNode = ({ node, draggable, selected, onSelect }: Props) => { ); }; + +export const ImageNode = memo(ImageNodeInner); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/TextNode.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/TextNode.tsx index 813fcf5fcd..090c09140a 100644 --- a/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/TextNode.tsx +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/nodes/TextNode.tsx @@ -1,3 +1,4 @@ +import { memo } from "react"; import Konva from "konva"; import { Text as KonvaText } from "react-konva"; import { TextNode as TextNodeData } from "../types"; @@ -7,15 +8,25 @@ interface Props { node: TextNodeData; draggable: boolean; selected: boolean; - onSelect: (e: Konva.KonvaEventObject) => void; + onSelect: ( + id: string, + e: Konva.KonvaEventObject, + ) => void; } -export const TextNode = ({ node, draggable, selected, onSelect }: Props) => { +const TextNodeInner = ({ node, draggable, selected, onSelect }: Props) => { const updateNode = useMoodboardStore((s) => s.updateNode); const pushHistory = useMoodboardStore((s) => s.pushHistory); const setEditingText = useMoodboardStore((s) => s.setEditingText); - const editingTextId = useMoodboardStore((s) => s.transient.editingTextId); - const isEditing = editingTextId === node.id; + // Selector compares a single id — only the TextNode whose isEditing + // actually flips will re-render when someone enters/exits text edit. + const isEditing = useMoodboardStore( + (s) => s.transient.editingTextId === node.id, + ); + + const handleSelect = ( + e: Konva.KonvaEventObject, + ) => onSelect(node.id, e); return ( { fill={node.color} padding={6} draggable={draggable} - onMouseDown={onSelect} - onTouchStart={onSelect} + onMouseDown={handleSelect} + onTouchStart={handleSelect} onDblClick={() => setEditingText(node.id)} onDblTap={() => setEditingText(node.id)} onDragStart={() => { @@ -45,3 +56,5 @@ export const TextNode = ({ node, draggable, selected, onSelect }: Props) => { /> ); }; + +export const TextNode = memo(TextNodeInner); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/RecenterIndicator.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/RecenterIndicator.tsx new file mode 100644 index 0000000000..323de51b94 --- /dev/null +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/RecenterIndicator.tsx @@ -0,0 +1,32 @@ +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { faCompress } from "@fortawesome/pro-solid-svg-icons"; +import { useMoodboardStore } from "../MoodboardStore"; +import { anyContentVisible } from "../layout/geometry"; + +// Small pill button in the bottom-right that appears when the user has +// panned or zoomed so far that no content is on screen. Clicking it calls +// `fitToContent` to frame all nodes back into view. Hidden on an empty +// board (nothing to recenter on) and whenever any node intersects the +// visible viewport. +export const RecenterIndicator = () => { + const nodes = useMoodboardStore((s) => s.nodes); + const rootOrder = useMoodboardStore((s) => s.rootOrder); + const viewport = useMoodboardStore((s) => s.viewport); + const canvasSize = useMoodboardStore((s) => s.canvasSize); + const fitToContent = useMoodboardStore((s) => s.fitToContent); + + if (rootOrder.length === 0) return null; + if (anyContentVisible(nodes, rootOrder, viewport, canvasSize)) return null; + + return ( + + ); +}; diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/ShortcutCheatsheet.tsx b/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/ShortcutCheatsheet.tsx new file mode 100644 index 0000000000..640d60d715 --- /dev/null +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/ShortcutCheatsheet.tsx @@ -0,0 +1,76 @@ +import { SHORTCUTS, ShortcutRow } from "./shortcuts"; + +interface Props { + visible: boolean; +} + +const SECTION_ORDER: ShortcutRow["section"][] = [ + "Tools", + "Selection", + "Editing", + "Viewport", + "History", +]; + +// Translucent, non-interactive overlay that lists all keyboard shortcuts. +// Shown while the user holds Ctrl/Cmd alone for 3 s (see +// `useShortcutCheatsheet.ts`). `pointer-events: none` so it never steals +// focus — the user can keep panning / zooming / typing while it's visible. +export const ShortcutCheatsheet = ({ visible }: Props) => { + if (!visible) return null; + + // Group rows by section, preserving declaration order within each. + const bySection = new Map(); + for (const row of SHORTCUTS) { + const arr = bySection.get(row.section) ?? []; + arr.push(row); + bySection.set(row.section, arr); + } + + return ( +
+
+
+ Keyboard shortcuts +
+
+ {SECTION_ORDER.map((section) => { + const rows = bySection.get(section); + if (!rows) return null; + return ( +
+
+ {section} +
+
    + {rows.map((row) => ( +
  • + {row.label} + + {row.keys.map((k, i) => ( + + ))} + +
  • + ))} +
+
+ ); + })} +
+
+
+ ); +}; + +const Key = ({ label }: { label: string }) => ( + + {label} + +); diff --git a/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/shortcuts.ts b/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/shortcuts.ts new file mode 100644 index 0000000000..cd2cea4f50 --- /dev/null +++ b/frontend/apps/artcraft/app/src/pages/PageMoodboard/overlays/shortcuts.ts @@ -0,0 +1,46 @@ +// Single source of truth for moodboard keyboard shortcuts. Consumed by +// `ShortcutCheatsheet.tsx` (rendering) and indirectly by +// `useKeyboardShortcuts.ts` (wiring). The `keys` array is the label shown +// to the user; the actual matching logic lives in the hook because some +// shortcuts are modifier-sensitive and platform-specific. + +export interface ShortcutRow { + label: string; + keys: string[]; + section: "Tools" | "Selection" | "Editing" | "Viewport" | "History"; +} + +const isMac = + typeof navigator !== "undefined" && + /Mac|iPod|iPhone|iPad/.test(navigator.platform); + +export const MOD = isMac ? "⌘" : "Ctrl"; + +export const SHORTCUTS: ShortcutRow[] = [ + // Tools + { section: "Tools", label: "Select tool", keys: ["V"] }, + { section: "Tools", label: "Lasso tool", keys: ["L"] }, + { section: "Tools", label: "Text tool", keys: ["T"] }, + + // Selection + { section: "Selection", label: "Select all", keys: [MOD, "A"] }, + { section: "Selection", label: "Clear selection", keys: ["Esc"] }, + { section: "Selection", label: "Add / remove from selection", keys: ["Shift", "Click"] }, + + // Editing + { section: "Editing", label: "Delete selection", keys: ["Delete"] }, + { section: "Editing", label: "Group selection", keys: [MOD, "G"] }, + { section: "Editing", label: "Ungroup selection", keys: [MOD, "Shift", "G"] }, + { section: "Editing", label: "Paste image", keys: [MOD, "V"] }, + + // Viewport + { section: "Viewport", label: "Pan", keys: ["Middle-click", "drag"] }, + { section: "Viewport", label: "Pan (alt)", keys: ["Space", "drag"] }, + { section: "Viewport", label: "Zoom", keys: ["Scroll"] }, + { section: "Viewport", label: "Reset zoom", keys: [MOD, "0"] }, + { section: "Viewport", label: "Zoom to fit", keys: ["Shift", "1"] }, + + // History + { section: "History", label: "Undo", keys: [MOD, "Z"] }, + { section: "History", label: "Redo", keys: [MOD, "Shift", "Z"] }, +]; diff --git a/frontend/apps/artcraft/test/app/pages/PageMoodboard/layout/packCollage.test.ts b/frontend/apps/artcraft/test/app/pages/PageMoodboard/layout/packCollage.test.ts index 6978a88568..64a2e452a1 100644 --- a/frontend/apps/artcraft/test/app/pages/PageMoodboard/layout/packCollage.test.ts +++ b/frontend/apps/artcraft/test/app/pages/PageMoodboard/layout/packCollage.test.ts @@ -1,4 +1,5 @@ -import { computeAABB, computePackPatches } from "~/pages/PageMoodboard/layout/packCollage"; +import { computeAABB } from "~/pages/PageMoodboard/layout/geometry"; +import { computePackPatches } from "~/pages/PageMoodboard/layout/packCollage"; import { MoodboardNode } from "~/pages/PageMoodboard/types"; const img = (