@kolkrabbi/kol-component 0.295.1 → 0.297.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,159 @@
1
+ import { useState } from 'react'
2
+ import { MenuCtx, useAsk, glyph } from '../molecules/AppItem.jsx'
3
+ import ContextMenu, { useContextMenu } from '../molecules/ContextMenu.jsx'
4
+ import { MenuDropdownItem } from '../molecules/MenuItem.jsx'
5
+ import Tag from '../atoms/Tag.jsx'
6
+ import Input from '../atoms/Input.jsx'
7
+ import Textarea from '../atoms/Textarea.jsx'
8
+ import IconFrame from '../atoms/IconFrame.jsx'
9
+ import Button from '../atoms/Button.jsx'
10
+ import { Tooltip } from '../utilities/Popover.jsx'
11
+ import { pickImage } from '../utilities/imageToDataUrl.js'
12
+ import SettingsPanel, { SettingsFooter } from './SettingsPanel.jsx'
13
+ import SettingsSections from './SettingsSections.jsx'
14
+
15
+ /**
16
+ * AppItemMenuProvider — One menu and one file rail. the page's ONE right-click menu and ONE file
17
+ * rail for every `app` card and row (AppItem.jsx). CatalogPage and HubHome mount it.
18
+ *
19
+ * THE FILE RAIL IS THE SETTINGS DRAWER (studio-hub review 2, § 2.1 — user: *"why is there border on the siderail? …
20
+ * rethink this entire siderail based on settings rail and based on labs rail, convention, standards, padding,
21
+ * width"*). It was a bare `Rail` with `backdrop={false}` (hence the edge) and its own section labels and buttons;
22
+ * it is now `SettingsPanel variant="rail" title="File"` — the drawer the settings gear opens, 380 wide, the scrim, no
23
+ * edge, the header row with its × — holding `SettingsSections divided`: Name (an `Input` committing through
24
+ * `verbs.rename` on Enter or blur), Tags (the chips with ×, then the add-a-tag `Input`, both through `onTags`),
25
+ * Details (one row per `{ label, value }`). The foot is `SettingsFooter` with three icon buttons in reset's control —
26
+ * download, duplicate, delete; Delete confirms through `useModal`. It lives here, an organism, because the drawer is
27
+ * one; the card and row keep reading the context from the molecule.
28
+ *
29
+ * READ AND EDIT (user 2026-10-23): the rail opens read-only — name, tags, note, details as text — and the pencil on its
30
+ * header line (Create's rename glyph, `IconFrame nav`) toggles edit mode. `note` / `onNote` arrived the same day: a plain
31
+ * description on a file, HubHome's `note` and `onNote(file, text)`.
32
+ *
33
+ * DATE · SIZE · COVER (user 2026-10-24: *"why is date and size not included in file info? same with upload image?"* ·
34
+ * *"why is edit 32px icon when others are 26px??"*): Details opens with the card's own Date and Size; in edit mode a
35
+ * Cover row offers Upload image — the DS picker, a webp data URL, handed to the file's `onCover(src)` (HubHome's
36
+ * `onCover(file, src)`); and the pencil is the rows' `sm` frame (26), as the × beside it.
37
+ */
38
+ /* the rail's body — READ MODE by default, the header's pencil opens EDIT MODE (user 2026-10-23: *"use the same edit icon
39
+ * from create? to edit mode or read mode?"*): read shows the name, the tag chips and the note as text; edit swaps in the
40
+ * Input, the chips with × over the add-a-tag Input, and the note's Textarea. Drafts are the rail's own, so what you typed
41
+ * stays while the consumer's state catches up. ONE row per field, no section label over a lone row of the same name
42
+ * (user 2026-10-23: the rail read NAME / NAME, TAGS / TAGS / ADD). */
43
+ function FileRailBody({ item, editing, onRenamed }) {
44
+ const { name, verbs, tags, details, note, onTags, onNote, mark, date, size, onCover } = item
45
+ const [draftName, setDraftName] = useState(name ?? '')
46
+ const [draftTags, setDraftTags] = useState(tags ?? [])
47
+ const [newTag, setNewTag] = useState('')
48
+ const [draftNote, setDraftNote] = useState(note ?? '')
49
+ const commitName = (v) => {
50
+ const next = (v ?? draftName).trim()
51
+ if (next && next !== name && verbs?.rename) { verbs.rename(next); onRenamed?.(next) }
52
+ }
53
+ const setTags = (next) => { setDraftTags(next); onTags?.(next) }
54
+ const addTag = (v) => {
55
+ const t = (v ?? newTag).trim()
56
+ if (t && !draftTags.includes(t)) setTags([...draftTags, t])
57
+ setNewTag('')
58
+ }
59
+ const commitNote = () => { const next = draftNote.trim(); if (next !== (note ?? '').trim()) onNote?.(next) }
60
+ const editName = editing && !!verbs?.rename
61
+ const editTags = editing && !!onTags
62
+ const editNote = editing && !!onNote
63
+ const text = (v, cls = '') => <span className={`kol-mono-12 text-body ${cls}`.trim()}>{v}</span>
64
+ /* READ MODE RIGHT-ALIGNS (user 2026-10-24: *"why is tags in the middle"*): every value — the name, the tag chips, the
65
+ * note — sits on the value column's right edge, as a text row does; in edit mode the rows fill with their controls */
66
+ const rows = [
67
+ editName
68
+ ? { label: 'Name', align: 'fill', render: () => <Input size="sm" className="w-full" value={draftName} onChange={(e) => setDraftName(e.target.value)} onCommit={commitName} aria-label="Name" /> }
69
+ : { label: 'Name', text: true, value: text(name, 'truncate') },
70
+ ...((editTags || draftTags.length > 0) ? [editTags
71
+ ? { label: 'Tags', align: 'fill', render: () => (
72
+ <div className="flex w-full flex-col gap-2">
73
+ {draftTags.length > 0 && (
74
+ <div className="flex flex-wrap gap-2">
75
+ {draftTags.map((t) => <Tag key={t} size="sm" hash={false} onRemove={() => setTags(draftTags.filter((x) => x !== t))}>{t}</Tag>)}
76
+ </div>
77
+ )}
78
+ <Input size="sm" className="w-full" placeholder="Add a tag" value={newTag} onChange={(e) => setNewTag(e.target.value)} onCommit={addTag} aria-label="Add a tag" />
79
+ </div>
80
+ ) }
81
+ : { label: 'Tags', text: true, value: (
82
+ <span className="flex flex-wrap justify-end gap-2">
83
+ {draftTags.map((t) => <Tag key={t} size="sm" hash={false}>{t}</Tag>)}
84
+ </span>
85
+ ) }] : []),
86
+ /* read mode shows the DRAFT, as the tags do — the item is a snapshot, so a note just committed would read stale */
87
+ ...((editNote || draftNote.trim()) ? [editNote
88
+ ? { label: 'Note', align: 'fill', render: () => <Textarea size="sm" rows={3} value={draftNote} onChange={(e) => setDraftNote(e.target.value)} onBlur={commitNote} placeholder="Add a note" aria-label="Note" /> }
89
+ : { label: 'Note', text: true, value: text(draftNote.trim(), 'text-right') }] : []),
90
+ /* edit mode: the cover — Upload image hands the DS picker's data URL to `onCover` (2026-10-24) */
91
+ ...((editing && onCover) ? [{ label: 'Cover', align: 'fill', render: () => (
92
+ <Button size="sm" tone="grey" onClick={async () => { const src = await pickImage(); if (src) onCover(src) }}>Upload image</Button>
93
+ ) }] : []),
94
+ ]
95
+ const sections = [
96
+ { rows },
97
+ ...((date || size || mark || details?.length) ? [{ label: 'Details', rows: [
98
+ /* the card's own date and size first (user 2026-10-24) */
99
+ ...(date ? [{ label: 'Date', text: true, value: text(date) }] : []),
100
+ ...(size ? [{ label: 'Size', text: true, value: text(size) }] : []),
101
+ /* then the mark — FXR's chrome: Chrome, Editor (`of` names the axis; `label` the value) */
102
+ ...(mark ? [{ label: mark.of ?? 'Kind', text: true, value: text(mark.label) }] : []),
103
+ ...(details ?? []).map(({ label, value }) => ({ label, text: true, value: text(value) })),
104
+ ] }] : []),
105
+ ]
106
+ return <SettingsSections sections={sections} divided />
107
+ }
108
+
109
+ /* the foot: SettingsFooter's row, three icon buttons in reset's control */
110
+ function fileRailFoot(item, ask, onClose) {
111
+ const { name, verbs, download } = item
112
+ if (!(download || verbs?.duplicate || verbs?.remove)) return undefined
113
+ const verb = (icon, label, onClick) => (
114
+ <Tooltip label={label}><IconFrame name={icon} variant="nav" size="sm" onClick={onClick} aria-label={label} /></Tooltip>
115
+ )
116
+ return (
117
+ <SettingsFooter>
118
+ {download && verb('download', 'Download', download)}
119
+ {verbs?.duplicate && verb('copy', 'Duplicate', verbs.duplicate)}
120
+ {verbs?.remove && verb('trash', 'Delete', async () => { if (await ask.remove(name, verbs)) onClose() })}
121
+ </SettingsFooter>
122
+ )
123
+ }
124
+
125
+ export default function AppItemMenuProvider({ children }) {
126
+ const menu = useContextMenu()
127
+ const ask = useAsk()
128
+ /* the file whose rail is open — a snapshot of its handlers; the rail keeps its own drafts */
129
+ const [info, setInfo] = useState(null)
130
+ const [editing, setEditing] = useState(false)
131
+ const close = () => setInfo(null)
132
+ const editable = !!(info?.verbs?.rename || info?.onTags || info?.onNote || info?.onCover)
133
+ return (
134
+ /* each open is stamped, so the rail keeps its drafts across a rename (the key no longer follows the name) and the
135
+ * foot's Delete confirm names the file as renamed, not as opened */
136
+ <MenuCtx.Provider value={{ menu, openInfo: (item) => { setEditing(false); setInfo(item && { ...item, openId: Date.now() }) } }}>
137
+ {children}
138
+ <ContextMenu menu={menu}>
139
+ {(item) => item && (
140
+ <>
141
+ {item.verbs?.rename && <MenuDropdownItem iconLeft={glyph('edit')} onClick={() => ask.rename(item.name, item.verbs)}>Rename</MenuDropdownItem>}
142
+ {item.verbs?.duplicate && <MenuDropdownItem iconLeft={glyph('copy')} onClick={item.verbs.duplicate}>Duplicate</MenuDropdownItem>}
143
+ {item.verbs?.remove && <MenuDropdownItem iconLeft={glyph('trash')} onClick={() => ask.remove(item.name, item.verbs)}>Delete</MenuDropdownItem>}
144
+ {item.menuItems}
145
+ </>
146
+ )}
147
+ </ContextMenu>
148
+ <SettingsPanel
149
+ open={!!info} variant="rail" title="File" onClose={close} footer={info ? fileRailFoot(info, ask, close) : undefined}
150
+ /* the pencil — bare, as Create's rename is; the rows' `sm` frame (26), the same box as the × beside it (user
151
+ * 2026-10-24: *"why is edit 32px icon when others are 26px??"*) */
152
+ headerActions={editable ? <IconFrame name="edit" variant="nav" size="sm" onClick={() => setEditing((v) => !v)} aria-label={editing ? 'Done editing' : 'Edit'} /> : undefined}
153
+ >
154
+ {/* `key` resets the drafts per file */}
155
+ {info && <FileRailBody key={info.openId} item={info} editing={editing} onRenamed={(name) => setInfo((i) => i && { ...i, name })} />}
156
+ </SettingsPanel>
157
+ </MenuCtx.Provider>
158
+ )
159
+ }
@@ -1,9 +1,14 @@
1
- import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react'
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
2
2
  import { CanvasZoomContext } from '../hooks/canvasZoom.js'
3
+ import { useCanvasViewport, useFps, zoomAt } from '../hooks/canvasViewport.js'
3
4
  import { Tooltip } from '../utilities/Popover.jsx'
4
5
 
5
6
  /**
6
- * Canvas — the editor's aspect-ratio stage.
7
+ * CanvasEditor — The editor's artboard. the editor's aspect-ratio stage, one of the two surfaces of the
8
+ * canvas family (2026-10-23): a FIXED frame you pan and zoom around, with rulers and guides.
9
+ * `CanvasStudio` is the other — an infinite dotted surface. Both read `useCanvasViewport`
10
+ * (hooks/canvasViewport.js): one set of gestures, one key table (`CANVAS_KEYS`), ⌘ the
11
+ * canvas's modifier. `Canvas` is this component's old name, an alias on the ledger.
7
12
  *
8
13
  * A letterboxed frame (dashed guide border + mono ratio label) that hosts its
9
14
  * children in a **fixed 1080-virtual-pixel coordinate space** and scales the
@@ -16,8 +21,9 @@ import { Tooltip } from '../utilities/Popover.jsx'
16
21
  * dividing by the live scale (frameWidth / 1080).
17
22
  *
18
23
  * Ships from this file: `CanvasZoomContext`, `CanvasFrame` (the bare scale
19
- * layer), `Canvas` (the letterbox, default export), `PanZoomViewport` (pan +
20
- * zoom + rulers + guides), `PanViewport` (pan only) and `useFps`.
24
+ * layer), `CanvasEditor` (the letterbox, default export), `PanZoomViewport` (pan +
25
+ * zoom + rulers + guides — deprecated, the engine is the hook), `PanViewport` (pan
26
+ * only — deprecated) and `useFps` (re-exported from the hook).
21
27
  *
22
28
  * Ported from kol-fxr's editor with three app-couplings dropped (per lobby
23
29
  * spec): the static `ASPECTS` table → an `aspects` prop (+ DEFAULT_ASPECTS);
@@ -40,6 +46,8 @@ import { Tooltip } from '../utilities/Popover.jsx'
40
46
  * had, so `import { CanvasZoomContext } from '@kolkrabbi/kol-component'` and
41
47
  * every existing deep import keep working. */
42
48
  export { CanvasZoomContext }
49
+ /* the fps hook lives with the engine now; the name stays here for every import that had it */
50
+ export { useFps }
43
51
 
44
52
  /* Fixed virtual canvas width — children render in this pixel space and the
45
53
  * outer rect scales to fit the viewport via CSS transform. Height is derived
@@ -168,7 +176,7 @@ export function CanvasFrame({
168
176
  }
169
177
 
170
178
  /**
171
- * Canvas — letterboxed stage (default export).
179
+ * CanvasEditor — letterboxed stage (default export).
172
180
  *
173
181
  * The OUTER wrapper letterboxes the inner `<CanvasFrame>` (rect carries the
174
182
  * optional `bgColor`, dashed border, label, and virtual-pixel scale layer).
@@ -197,7 +205,7 @@ export function CanvasFrame({
197
205
  * @param {Function} onSpaceTap fires when Space was pressed and released WITHOUT panning — a tap, not a drag. fxr binds its transport play/pause here; unset, a tap does nothing
198
206
  * @param {ReactNode} children rendered in the 1080-virtual scale layer
199
207
  */
200
- export default function Canvas({
208
+ export default function CanvasEditor({
201
209
  aspect,
202
210
  customRatio,
203
211
  aspects,
@@ -261,6 +269,7 @@ export default function Canvas({
261
269
  }
262
270
 
263
271
  /**
272
+ * @deprecated 2026-10-23 → `CanvasEditor panEnabled` (the engine is `useCanvasViewport`); kept so a consumer composing its own viewport keeps resolving.
264
273
  * PanViewport — Space + drag pan wrapper. **Pan only, no zoom.**
265
274
  *
266
275
  * Kept for a consumer composing its own viewport, and because it is what
@@ -362,11 +371,10 @@ export function PanViewport({ backdrop, children }) {
362
371
 
363
372
  /* ── Pan + zoom ────────────────────────────────────────────────────────────
364
373
  * Ported verbatim from kol-fxr `src/editor/shell/Canvas.jsx` (2026-09-03,
365
- * `editor-set-is-behind-its-source`). Two app couplings became seams: the
366
- * Space-tap `transport.toggle()` is now `onSpaceTap`, and the hardwired
367
- * `.kol-grid-bg` div is the `backdrop` node this package already took. The
368
- * clamps, the anchor math, the wheel handling and the chip layout are the
369
- * source's — fxr is the reference for this set. */
374
+ * `editor-set-is-behind-its-source`); the gestures moved into `useCanvasViewport`
375
+ * (hooks/canvasViewport.js) on 2026-10-23 so the studio surface reads the same ones.
376
+ * What stays here is the editor's: the clamps in REAL terms, the fit, the
377
+ * `kol:zoom-*` window events, the rulers, the guides and the chips. */
370
378
 
371
379
  /* The clamps are in REAL terms — screen px per frame px, `zoom × fit` (CanvasViewCommands, kol-fxr
372
380
  * 2026-10-13). They were 0.1–8 relative to the fitted frame, so a 1080 frame fitted at ~0.58 capped
@@ -381,66 +389,17 @@ function fitOf(node) {
381
389
  return w ? w / CANVAS_VIRTUAL_W : 1
382
390
  }
383
391
 
384
- const clampZoom = (z, fit) => Math.min(ZOOM_MAX_REAL / fit, Math.max(ZOOM_MIN_REAL / fit, z))
385
-
386
- /* Anchor a zoom change at a screen point (sx, sy relative to the viewport
387
- * top-left) so the content under the cursor stays put. Transform is
388
- * `translate(x,y) scale(zoom)` with origin 0,0, so screen = p*zoom + pan;
389
- * inverting for a fixed p gives the new pan below. */
390
- function zoomAt(v, factor, sx, sy, fit = 1) {
391
- const z2 = clampZoom(v.zoom * factor, fit)
392
- return {
393
- zoom: z2,
394
- x: sx - (sx - v.x) * (z2 / v.zoom),
395
- y: sy - (sy - v.y) * (z2 / v.zoom),
396
- }
397
- }
398
-
399
- /* useFps(enabled) — live framerate, measured only while `enabled` (the RAF
400
- * idles when off); returns frames per second, updated twice a second.
401
- * Exported because a consumer's own stage corner renders the same chip.
402
- *
403
- * A plain block comment on purpose: `@param` belongs to a destructured props
404
- * signature, and the props gate pairs a `/** … *\/` block with the next such
405
- * export — a JSDoc'd positional hook hands its `@param` to the component
406
- * below it, which is exactly the false positive it reported on this file. */
407
- export function useFps(enabled) {
408
- const [fps, setFps] = useState(0)
409
- useEffect(() => {
410
- if (!enabled) return
411
- let raf, frames = 0, last = performance.now()
412
- const loop = (now) => {
413
- frames++
414
- if (now - last >= 500) {
415
- setFps(Math.round((frames * 1000) / (now - last)))
416
- frames = 0
417
- last = now
418
- }
419
- raf = requestAnimationFrame(loop)
420
- }
421
- raf = requestAnimationFrame(loop)
422
- return () => cancelAnimationFrame(raf)
423
- }, [enabled])
424
- return fps
425
- }
426
-
427
- function isTypingTarget(el) {
428
- if (!el) return false
429
- const tag = el.tagName
430
- return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable
431
- }
432
-
433
392
  /**
434
- * PanZoomViewport — An infinite canvas to pan and zoom. infinite-canvas viewport (pan + zoom), and the one that
393
+ * @deprecated 2026-10-23 → `CanvasEditor panEnabled`; the pan and zoom are `useCanvasViewport`'s, shared with `CanvasStudio`. Kept so an editor composing its own stage keeps resolving.
394
+ * PanZoomViewport — An infinite canvas to pan and zoom. the editor's viewport (pan + zoom), and the one that
435
395
  * publishes `CanvasZoomContext`.
436
396
  *
437
- * Pan: hold Space + drag (cursor grab/grabbing), or two-finger trackpad
438
- * scroll. Zoom: Cmd/Ctrl + wheel or trackpad pinch, anchored at the pointer;
439
- * Cmd+0 resets, Cmd+= / Cmd+- step-zoom at the viewport center. A single
440
- * `translate() scale()` on the transform layer carries both, so a consumer's
441
- * screen→virtual math needs no zoom awareness. Pointer events on the
442
- * transform layer disable while Space is held so layer mousedowns don't fire
443
- * mid-pan. `f` toggles an fps chip beside the zoom readout. From outside: `kol:zoom-at`
397
+ * Pan: hold Space + drag (cursor grab/grabbing), middle-drag, ⌘-drag, or a plain two-finger
398
+ * scroll. Zoom: ⌘/Ctrl + wheel or a trackpad pinch, anchored at the pointer; ⌘0 resets, ⌘= / ⌘−
399
+ * step-zoom at the viewport centre (`CANVAS_KEYS`). A single `translate() scale()` on the
400
+ * transform layer carries both, so a consumer's screen→virtual math needs no zoom awareness.
401
+ * Pointer events on the transform layer disable while Space is held so layer mousedowns don't
402
+ * fire mid-pan. `F` toggles an fps chip beside the zoom readout. From outside: `kol:zoom-at`
444
403
  * { clientX, clientY, factor } · `kol:zoom-to` { scale } (real, 1 = 100%) · `kol:zoom-fit` { to:
445
404
  * 'frame' | 'width' | { x, y, w, h } } — window events. Zoom is clamped at 2%–3200% real. Touch:
446
405
  * two fingers pinch-zoom + pan; a one-finger tap fires `onSpaceTap`.
@@ -462,161 +421,20 @@ export function PanZoomViewport({
462
421
  guidesInteractive = true,
463
422
  onSpaceTap,
464
423
  }) {
465
- const containerRef = useRef(null)
466
- const [spaceHeld, setSpaceHeld] = useState(false)
467
- /* Space tap vs Space+drag: the ref records whether a pan drag consumed this
468
- * Space press (set on pan mousedown), so keyup can tell them apart. */
469
- const spacePannedRef = useRef(false)
470
- const [dragging, setDragging] = useState(false)
471
- const [view, setView] = useState({ zoom: 1, x: 0, y: 0 })
472
- const dragStart = useRef(null)
473
- const [pinching, setPinching] = useState(false)
474
- const [showFps, setShowFps] = useState(false)
475
- const fps = useFps(showFps)
476
- /* Ref mirror so the keyup listener calls the latest callback without
477
- * rebinding the window listeners on every consumer re-render. */
478
- const spaceTapRef = useRef(onSpaceTap)
479
- spaceTapRef.current = onSpaceTap
480
-
481
- /* Space toggles pan mode; Cmd+0 / Cmd+= / Cmd+- drive zoom from the
482
- * keyboard (centered on the viewport). Skipped while typing in a field. */
483
- useEffect(() => {
484
- const isInputTarget = (el) =>
485
- el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)
486
- const onKeyDown = (e) => {
487
- if (isInputTarget(e.target)) return
488
- if (e.code === 'Space') {
489
- e.preventDefault()
490
- if (!e.repeat) spacePannedRef.current = false
491
- setSpaceHeld(true)
492
- return
493
- }
494
- if (e.metaKey || e.ctrlKey) {
495
- if (e.key === '0') {
496
- e.preventDefault()
497
- setView({ zoom: 1, x: 0, y: 0 })
498
- } else if (e.key === '=' || e.key === '+') {
499
- e.preventDefault()
500
- const r = containerRef.current?.getBoundingClientRect()
501
- setView((v) => zoomAt(v, 1.2, (r?.width ?? 0) / 2, (r?.height ?? 0) / 2, fitOf(containerRef.current)))
502
- } else if (e.key === '-') {
503
- e.preventDefault()
504
- const r = containerRef.current?.getBoundingClientRect()
505
- setView((v) => zoomAt(v, 1 / 1.2, (r?.width ?? 0) / 2, (r?.height ?? 0) / 2, fitOf(containerRef.current)))
506
- }
507
- }
508
- }
509
- const onKeyUp = (e) => {
510
- if (e.code === 'Space') {
511
- setSpaceHeld(false)
512
- setDragging(false)
513
- dragStart.current = null
514
- /* No pan happened → this was a tap. fxr binds play/pause here; the
515
- * same input guard as keydown so typing a space in a field is not a
516
- * tap. Unset, a tap does nothing. */
517
- if (!spacePannedRef.current && !isInputTarget(e.target)) spaceTapRef.current?.()
518
- }
519
- }
520
- window.addEventListener('keydown', onKeyDown)
521
- window.addEventListener('keyup', onKeyUp)
522
- return () => {
523
- window.removeEventListener('keydown', onKeyDown)
524
- window.removeEventListener('keyup', onKeyUp)
525
- }
526
- }, [])
527
-
528
- useEffect(() => {
529
- if (!dragging) return
530
- const onMove = (e) => {
531
- if (!dragStart.current) return
532
- const { x: sx, y: sy } = dragStart.current
533
- setView((v) => ({ ...v, x: e.clientX - sx, y: e.clientY - sy }))
534
- }
535
- const onUp = () => {
536
- setDragging(false)
537
- dragStart.current = null
538
- }
539
- window.addEventListener('mousemove', onMove)
540
- window.addEventListener('mouseup', onUp)
541
- return () => {
542
- window.removeEventListener('mousemove', onMove)
543
- window.removeEventListener('mouseup', onUp)
544
- }
545
- }, [dragging])
546
-
547
- /* Wheel: Cmd/Ctrl+wheel or trackpad pinch (ctrlKey) → zoom at pointer;
548
- * plain two-finger scroll → pan. Native non-passive listener so we can
549
- * preventDefault the browser's page-zoom / scroll. */
550
- useEffect(() => {
551
- const node = containerRef.current
552
- if (!node) return
553
- const onWheel = (e) => {
554
- e.preventDefault()
555
- const rect = node.getBoundingClientRect()
556
- const sx = e.clientX - rect.left
557
- const sy = e.clientY - rect.top
558
- if (e.ctrlKey || e.metaKey) {
559
- setView((v) => zoomAt(v, Math.exp(-e.deltaY * 0.0015), sx, sy, fitOf(node)))
560
- } else {
561
- setView((v) => ({ ...v, x: v.x - e.deltaX, y: v.y - e.deltaY }))
562
- }
563
- }
564
- node.addEventListener('wheel', onWheel, { passive: false })
565
- return () => node.removeEventListener('wheel', onWheel)
566
- }, [])
567
-
568
- /* Touch (ViewportTouchGestures, kol-fxr 2026-10-14): two fingers pinch-zoom at their midpoint and
569
- * the midpoint's travel pans, in one gesture; the transform layer goes deaf while they are down so
570
- * a consumer's tool never sees the second finger. One finger stays the consumer's, except a TAP
571
- * (up within TAP_MS and TAP_PX, no second finger joined) fires `onSpaceTap`. Down is caught in the
572
- * capture phase on the container; move/up on window, so a finger leaving the frame still ends. */
573
- useEffect(() => {
574
- const node = containerRef.current
575
- if (!node) return
576
- const TAP_MS = 350, TAP_PX = 12
577
- const pts = new Map()
578
- let pinch = null, tap = null
579
- const pair = () => {
580
- const [a, b] = [...pts.values()]
581
- return { mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2, d: Math.hypot(a.x - b.x, a.y - b.y) || 1 }
582
- }
583
- const onDown = (e) => {
584
- if (e.pointerType !== 'touch') return
585
- pts.set(e.pointerId, { x: e.clientX, y: e.clientY })
586
- if (pts.size === 1) tap = { id: e.pointerId, t: e.timeStamp, x: e.clientX, y: e.clientY }
587
- else if (pts.size === 2) { tap = null; pinch = pair(); setPinching(true) }
588
- }
589
- const onMove = (e) => {
590
- if (!pts.has(e.pointerId)) return
591
- pts.set(e.pointerId, { x: e.clientX, y: e.clientY })
592
- if (tap && Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > TAP_PX) tap = null
593
- if (!pinch || pts.size < 2) return
594
- const prev = pinch, next = pair()
595
- pinch = next
596
- const r = node.getBoundingClientRect()
597
- const fit = fitOf(node)
598
- setView((v) => {
599
- const z = zoomAt(v, next.d / prev.d, prev.mx - r.left, prev.my - r.top, fit)
600
- return { ...z, x: z.x + next.mx - prev.mx, y: z.y + next.my - prev.my }
601
- })
602
- }
603
- const onEnd = (e) => {
604
- if (!pts.delete(e.pointerId)) return
605
- if (tap?.id === e.pointerId && e.type === 'pointerup' && e.timeStamp - tap.t < TAP_MS) spaceTapRef.current?.()
606
- if (tap?.id === e.pointerId) tap = null
607
- if (pinch && pts.size < 2) { pinch = null; setPinching(false) }
608
- }
609
- node.addEventListener('pointerdown', onDown, true)
610
- window.addEventListener('pointermove', onMove)
611
- window.addEventListener('pointerup', onEnd)
612
- window.addEventListener('pointercancel', onEnd)
613
- return () => {
614
- node.removeEventListener('pointerdown', onDown, true)
615
- window.removeEventListener('pointermove', onMove)
616
- window.removeEventListener('pointerup', onEnd)
617
- window.removeEventListener('pointercancel', onEnd)
618
- }
619
- }, [])
424
+ const containerRef = useRef(null)
425
+ const vp = useCanvasViewport({
426
+ ref: containerRef,
427
+ minZoom: ZOOM_MIN_REAL,
428
+ maxZoom: ZOOM_MAX_REAL,
429
+ fit: () => fitOf(containerRef.current),
430
+ touch: 'editor',
431
+ onSpaceTap,
432
+ })
433
+ const { view, setView, clamp, spaceHeld, pinching, cursor, showFps, fps } = vp
434
+ const setViewRef = useRef(setView)
435
+ setViewRef.current = setView
436
+ const clampRef = useRef(clamp)
437
+ clampRef.current = clamp
620
438
 
621
439
  /* A consumer's zoom TOOL announces clicks as `kol:zoom-at` (client coords +
622
440
  * factor) rather than reaching into this state — anchored zoom at the
@@ -627,7 +445,7 @@ export function PanZoomViewport({
627
445
  if (!node) return
628
446
  const { clientX, clientY, factor } = e.detail
629
447
  const rect = node.getBoundingClientRect()
630
- setView((v) => zoomAt(v, factor, clientX - rect.left, clientY - rect.top, fitOf(node)))
448
+ setViewRef.current((v) => zoomAt(v, factor, clientX - rect.left, clientY - rect.top, clampRef.current))
631
449
  }
632
450
  /* `kol:zoom-to` { scale } — a REAL scale (1 = 100%: one screen px per frame px), about the
633
451
  * viewport centre, so a consumer's 100–800% steps need not measure the fit. */
@@ -636,7 +454,7 @@ export function PanZoomViewport({
636
454
  if (!node) return
637
455
  const fit = fitOf(node)
638
456
  const r = node.getBoundingClientRect()
639
- setView((v) => zoomAt(v, e.detail.scale / (v.zoom * fit), r.width / 2, r.height / 2, fit))
457
+ setViewRef.current((v) => zoomAt(v, e.detail.scale / (v.zoom * fit), r.width / 2, r.height / 2, clampRef.current))
640
458
  }
641
459
  /* `kol:zoom-fit` { to } — `'frame'` (default) is ⌘0's opening view; `'width'` fills the
642
460
  * viewport with the frame's width, centred vertically; `{ x, y, w, h }` in frame (virtual) px
@@ -645,20 +463,20 @@ export function PanZoomViewport({
645
463
  const node = containerRef.current
646
464
  const frame = node?.querySelector('[data-canvas-frame]')
647
465
  const to = e.detail?.to ?? 'frame'
648
- if (!frame || to === 'frame') { setView({ zoom: 1, x: 0, y: 0 }); return }
466
+ if (!frame || to === 'frame') { setViewRef.current({ zoom: 1, x: 0, y: 0 }); return }
649
467
  const fit = fitOf(node)
650
468
  const cr = node.getBoundingClientRect()
651
469
  const fr = frame.getBoundingClientRect()
652
- setView((v) => {
470
+ setViewRef.current((v) => {
653
471
  /* the frame's rect at rest (zoom 1, no pan), in viewport px */
654
472
  const fx = (fr.left - cr.left - v.x) / v.zoom
655
473
  const fy = (fr.top - cr.top - v.y) / v.zoom
656
474
  const rect = to === 'width'
657
475
  ? { x: fx, y: fy, w: frame.offsetWidth, h: frame.offsetHeight }
658
476
  : { x: fx + to.x * fit, y: fy + to.y * fit, w: to.w * fit, h: to.h * fit }
659
- const zoom = clampZoom(to === 'width'
477
+ const zoom = clampRef.current(to === 'width'
660
478
  ? cr.width / rect.w
661
- : Math.min((cr.width - 2 * FIT_MARGIN) / rect.w, (cr.height - 2 * FIT_MARGIN) / rect.h), fit)
479
+ : Math.min((cr.width - 2 * FIT_MARGIN) / rect.w, (cr.height - 2 * FIT_MARGIN) / rect.h))
662
480
  return {
663
481
  zoom,
664
482
  x: cr.width / 2 - (rect.x + rect.w / 2) * zoom,
@@ -676,32 +494,6 @@ export function PanZoomViewport({
676
494
  }
677
495
  }, [])
678
496
 
679
- /* `f` toggles the fps chip (measured only while shown). Guarded against
680
- * typing targets so text fields don't flip it. */
681
- useEffect(() => {
682
- const onKey = (e) => {
683
- if (e.key !== 'f' && e.key !== 'F') return
684
- if (e.metaKey || e.ctrlKey || e.altKey) return
685
- if (isTypingTarget(e.target)) return
686
- setShowFps((v) => !v)
687
- }
688
- window.addEventListener('keydown', onKey)
689
- return () => window.removeEventListener('keydown', onKey)
690
- }, [])
691
-
692
- const onMouseDown = (e) => {
693
- if (!spaceHeld) return
694
- e.preventDefault()
695
- spacePannedRef.current = true
696
- dragStart.current = { x: e.clientX - view.x, y: e.clientY - view.y }
697
- setDragging(true)
698
- }
699
-
700
- /* Only override the cursor while actively panning (Space-held / dragging).
701
- * At rest, leave it unset so consumers above can apply their own cursor
702
- * (a tool-driven cursor) and have it visible across the backdrop AND the
703
- * canvas frame, not just the frame area. */
704
- const cursor = dragging ? 'grabbing' : spaceHeld ? 'grab' : undefined
705
497
  const atRest = view.zoom === 1 && view.x === 0 && view.y === 0
706
498
 
707
499
  return (
@@ -710,7 +502,6 @@ export function PanZoomViewport({
710
502
  ref={containerRef}
711
503
  className="relative w-full h-full overflow-hidden select-none"
712
504
  style={{ cursor, touchAction: 'none' }}
713
- onMouseDown={onMouseDown}
714
505
  >
715
506
  {/* No transition on the transform: editing chrome (selection
716
507
  wireframe, path nodes) sizes itself by 1/zoom from React state,
@@ -720,7 +511,7 @@ export function PanZoomViewport({
720
511
  <div
721
512
  className="absolute inset-0"
722
513
  style={{
723
- transform: `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`,
514
+ transform: vp.transform,
724
515
  transformOrigin: '0 0',
725
516
  pointerEvents: spaceHeld || pinching ? 'none' : 'auto',
726
517
  }}
@@ -744,7 +535,7 @@ export function PanZoomViewport({
744
535
  {showRulers && <CanvasRuler containerRef={containerRef} disabled={spaceHeld} />}
745
536
 
746
537
  {/* Zoom % + fps — matching chips. Zoom (click resets to 100% /
747
- centered) first, fps to its right, shown while `f` toggles it. */}
538
+ centered) first, fps to its right, shown while `F` toggles it. */}
748
539
  <div className="absolute bottom-3 right-3 z-[3] flex items-center gap-2">
749
540
  <Tooltip label="Reset zoom (⌘0)" asChild>
750
541
  <button