| 1 | // fixtures/canvas.mjs — editing a canvas slide on the stage (spec |
| 2 | // §3.1): the selected block drags by its body and resizes by eight |
| 3 | // handles, snapping to the frame's thirds and to the other blocks' |
| 4 | // edges, and the box is written once, on pointer up, as four-decimal |
| 5 | // fractions of the frame — so undo is per gesture. |
| 6 | // |
| 7 | // The maths is pure over boxes {x, y, w, h} in frame fractions |
| 8 | // (canvas.test.mjs): clamping to the frame, the guides a slide |
| 9 | // offers, snapping a moving edge to the nearest guide within one per |
| 10 | // cent, moving, resizing by handle, nudging by key. The overlay is the |
| 11 | // DOM part: one element placed over the selected block, with a drag |
| 12 | // surface and the handles, positioned from the block's own rectangle |
| 13 | // so it is right in the desktop rendering and the phone one alike. |
| 14 | // |
| 15 | // The keyboard's equivalent is the overlay itself: it is focusable and |
| 16 | // named, arrow keys nudge by half a per cent, Shift by two, Alt |
| 17 | // resizes; the inspector's Left/Top/Width/Height fields are the same |
| 18 | // numbers typed. With Ctrl or Cmd an arrow is not a nudge: Mod+Shift+ |
| 19 | // arrows move the box up and down the slide's order (box-menu.mjs). It is not a tab stop of its own: each box is |
| 20 | // (stage-focus.mjs), focus on a box goes on to its overlay, and Tab on |
| 21 | // the overlay goes on to the next box. The handles are pointer targets only (aria-hidden), |
| 22 | // 24px square so a finger finds them (touch is pointer events too). |
| 23 | // |
| 24 | // A text block is dragged by its edges — a ring inside its border — |
| 25 | // because its interior is the caret's; anything else drags by its |
| 26 | // whole body. During a drag only the block's inline style moves; the |
| 27 | // op is written on pointer up and the stage re-fetches the section. |
| 28 | import { round4 } from './layout.mjs' |
| 29 | |
| 30 | export const MIN_SIZE = 0.02 |
| 31 | export const SNAP = 0.01 |
| 32 | export const NUDGE = 0.005 |
| 33 | export const NUDGE_BIG = 0.02 |
| 34 | export const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] |
| 35 | const THIRDS = [0, 1 / 3, 2 / 3, 1] |
| 36 | const DRAG_THRESHOLD_PX = 3 |
| 37 | const NUDGE_COALESCE_MS = 300 |
| 38 | const TEXT_TYPES = ['heading', 'text', 'list', 'quote', 'code', 'table'] |
| 39 | |
| 40 | /** The box kept inside the frame, never smaller than MIN_SIZE. */ |
| 41 | export function clampBox (box) { |
| 42 | const w = Math.min(1, Math.max(MIN_SIZE, box.w)) |
| 43 | const h = Math.min(1, Math.max(MIN_SIZE, box.h)) |
| 44 | const x = Math.min(1 - w, Math.max(0, box.x)) |
| 45 | const y = Math.min(1 - h, Math.max(0, box.y)) |
| 46 | return { x, y, w, h } |
| 47 | } |
| 48 | |
| 49 | /** Four decimals each, then clamped: what an op carries. */ |
| 50 | export function fixBox (box) { |
| 51 | const c = clampBox(box) |
| 52 | return { x: round4(c.x), y: round4(c.y), w: round4(c.w), h: round4(c.h) } |
| 53 | } |
| 54 | |
| 55 | export function sameBox (a, b) { |
| 56 | return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h |
| 57 | } |
| 58 | |
| 59 | /** The guides a slide offers: the thirds of the frame and every other block's edges. */ |
| 60 | export function guides (others) { |
| 61 | const x = new Set(THIRDS) |
| 62 | const y = new Set(THIRDS) |
| 63 | for (const b of others) { |
| 64 | x.add(b.x); x.add(b.x + b.w) |
| 65 | y.add(b.y); y.add(b.y + b.h) |
| 66 | } |
| 67 | return { x: [...x], y: [...y] } |
| 68 | } |
| 69 | |
| 70 | /** The guide nearest v within tol, or null. */ |
| 71 | function nearest (v, lines, tol) { |
| 72 | let best = null |
| 73 | let dist = tol |
| 74 | for (const g of lines) { |
| 75 | const d = Math.abs(v - g) |
| 76 | if (d <= dist) { dist = d; best = g } |
| 77 | } |
| 78 | return best |
| 79 | } |
| 80 | |
| 81 | /** The whole box shifted so its nearest edge (per axis) sits on a guide within tol. */ |
| 82 | export function snapMove (box, g, tol = SNAP) { |
| 83 | const out = { ...box } |
| 84 | const left = nearest(box.x, g.x, tol) |
| 85 | const right = nearest(box.x + box.w, g.x, tol) |
| 86 | if (left !== null && (right === null || Math.abs(left - box.x) <= Math.abs(right - box.x - box.w))) out.x = left |
| 87 | else if (right !== null) out.x = right - box.w |
| 88 | const top = nearest(box.y, g.y, tol) |
| 89 | const bottom = nearest(box.y + box.h, g.y, tol) |
| 90 | if (top !== null && (bottom === null || Math.abs(top - box.y) <= Math.abs(bottom - box.y - box.h))) out.y = top |
| 91 | else if (bottom !== null) out.y = bottom - box.h |
| 92 | return out |
| 93 | } |
| 94 | |
| 95 | /** The box with only the edges handle moves snapped to a guide within tol. */ |
| 96 | export function snapResize (box, handle, g, tol = SNAP) { |
| 97 | let { x, y, w, h } = box |
| 98 | if (handle.includes('w')) { |
| 99 | const s = nearest(x, g.x, tol) |
| 100 | if (s !== null) { w += x - s; x = s } |
| 101 | } |
| 102 | if (handle.includes('e')) { |
| 103 | const s = nearest(x + w, g.x, tol) |
| 104 | if (s !== null) w = s - x |
| 105 | } |
| 106 | if (handle.includes('n')) { |
| 107 | const s = nearest(y, g.y, tol) |
| 108 | if (s !== null) { h += y - s; y = s } |
| 109 | } |
| 110 | if (handle.includes('s')) { |
| 111 | const s = nearest(y + h, g.y, tol) |
| 112 | if (s !== null) h = s - y |
| 113 | } |
| 114 | return { x, y, w, h } |
| 115 | } |
| 116 | |
| 117 | export function moveBox (box, dx, dy) { |
| 118 | return { ...box, x: box.x + dx, y: box.y + dy } |
| 119 | } |
| 120 | |
| 121 | /** The box after handle is dragged by (dx, dy): the named edges move, the opposite ones stay. */ |
| 122 | export function resizeBox (box, handle, dx, dy) { |
| 123 | let { x, y, w, h } = box |
| 124 | if (handle.includes('e')) w = Math.max(MIN_SIZE, w + dx) |
| 125 | if (handle.includes('s')) h = Math.max(MIN_SIZE, h + dy) |
| 126 | if (handle.includes('w')) { |
| 127 | const nw = Math.max(MIN_SIZE, w - dx) |
| 128 | x += w - nw |
| 129 | w = nw |
| 130 | } |
| 131 | if (handle.includes('n')) { |
| 132 | const nh = Math.max(MIN_SIZE, h - dy) |
| 133 | y += h - nh |
| 134 | h = nh |
| 135 | } |
| 136 | return { x, y, w, h } |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * The box after an arrow key: a nudge (Shift for the bigger step), or |
| 141 | * with Alt a resize of the right/bottom edge. null for any other key. |
| 142 | */ |
| 143 | export function nudge (box, key, { shift = false, alt = false } = {}) { |
| 144 | const step = shift ? NUDGE_BIG : NUDGE |
| 145 | const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[key] |
| 146 | if (!d) return null |
| 147 | const [dx, dy] = d |
| 148 | if (alt) return resizeBox(box, 'se', dx, dy) |
| 149 | return moveBox(box, dx, dy) |
| 150 | } |
| 151 | |
| 152 | /** A block element's box as fractions of its frame, from the two rectangles. */ |
| 153 | export function rectBox (frame, rect) { |
| 154 | if (!frame.width || !frame.height) return { x: 0, y: 0, w: 0, h: 0 } |
| 155 | return { |
| 156 | x: (rect.left - frame.left) / frame.width, |
| 157 | y: (rect.top - frame.top) / frame.height, |
| 158 | w: rect.width / frame.width, |
| 159 | h: rect.height / frame.height |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | function pct (f) { return (f * 100).toFixed(2) + '%' } |
| 164 | |
| 165 | /** Writes a box onto a block element's inline style — the drag preview. */ |
| 166 | export function applyBox (el, box) { |
| 167 | el.style.left = pct(box.x) |
| 168 | el.style.top = pct(box.y) |
| 169 | el.style.width = pct(box.w) |
| 170 | el.style.height = pct(box.h) |
| 171 | } |
| 172 | |
| 173 | /** |
| 174 | * Mounts the canvas editing overlay in stageEl. getSelected() is the |
| 175 | * selected block's id; onCommit(id, box) is called once per gesture |
| 176 | * with the fixed box; label names the overlay for a screen reader; |
| 177 | * onPlace() is told after every placing (the box's round button, |
| 178 | * box-menu.mjs, follows the overlay and its handles). |
| 179 | * Returns {place, destroy}: place() re-positions the overlay (after a |
| 180 | * selection change, a refresh, a resize) and hides it when the stage |
| 181 | * is not a canvas slide or nothing is selected. |
| 182 | */ |
| 183 | export function mountCanvas ({ stageEl, getSelected, onCommit, label, onPlace = () => {} }) { |
| 184 | const overlay = document.createElement('div') |
| 185 | overlay.setAttribute('slides-canvas-overlay', '') |
| 186 | overlay.setAttribute('tabindex', '-1') |
| 187 | overlay.setAttribute('role', 'group') |
| 188 | overlay.setAttribute('aria-label', label) |
| 189 | overlay.hidden = true |
| 190 | const body = document.createElement('div') |
| 191 | body.setAttribute('slides-drag', '') |
| 192 | body.dataset.surface = 'body' |
| 193 | overlay.append(body) |
| 194 | for (const side of ['n', 'e', 's', 'w']) { |
| 195 | const edge = document.createElement('div') |
| 196 | edge.setAttribute('slides-drag', '') |
| 197 | edge.dataset.surface = 'edge' |
| 198 | edge.dataset.side = side |
| 199 | overlay.append(edge) |
| 200 | } |
| 201 | for (const h of HANDLES) { |
| 202 | const el = document.createElement('div') |
| 203 | el.setAttribute('slides-handle', '') |
| 204 | el.dataset.handle = h |
| 205 | el.setAttribute('aria-hidden', 'true') |
| 206 | overlay.append(el) |
| 207 | } |
| 208 | stageEl.append(overlay) |
| 209 | |
| 210 | const section = () => stageEl.querySelector('[slides-slide][data-layout="canvas"]') |
| 211 | const selectedEl = () => { |
| 212 | const id = getSelected() |
| 213 | const s = section() |
| 214 | return id && s ? s.querySelector(`:scope > [slides-block][data-id="${CSS.escape(id)}"]`) : null |
| 215 | } |
| 216 | const frameRect = () => section().getBoundingClientRect() |
| 217 | const boxOf = el => rectBox(frameRect(), el.getBoundingClientRect()) |
| 218 | const othersBoxes = el => Array.from(section().querySelectorAll(':scope > [slides-block]')).filter(b => b !== el).map(boxOf) |
| 219 | |
| 220 | function place () { |
| 221 | // A burst of nudges is the selected box's: another box selected (by |
| 222 | // Tab, a click, the Outline, Esc) writes it now rather than letting |
| 223 | // the next box's burst take its place. |
| 224 | if (pending && pending.id !== getSelected()) flushNudge() |
| 225 | placeOverlay() |
| 226 | onPlace() |
| 227 | } |
| 228 | function placeOverlay () { |
| 229 | // A load replaces the stage's whole DOM, the overlay with it: it |
| 230 | // goes back after the section, every time. |
| 231 | if (!overlay.isConnected) stageEl.append(overlay) |
| 232 | const el = selectedEl() |
| 233 | if (!el) { |
| 234 | overlay.hidden = true |
| 235 | return |
| 236 | } |
| 237 | const stage = stageEl.getBoundingClientRect() |
| 238 | const r = el.getBoundingClientRect() |
| 239 | overlay.hidden = false |
| 240 | overlay.style.left = (r.left - stage.left + stageEl.scrollLeft) + 'px' |
| 241 | overlay.style.top = (r.top - stage.top + stageEl.scrollTop) + 'px' |
| 242 | overlay.style.width = r.width + 'px' |
| 243 | overlay.style.height = r.height + 'px' |
| 244 | overlay.dataset.text = TEXT_TYPES.includes(el.getAttribute('data-block')) ? 'true' : 'false' |
| 245 | } |
| 246 | |
| 247 | // One gesture: pointerdown on a surface or a handle, moves, up. |
| 248 | let gesture = null |
| 249 | function start (e, handle) { |
| 250 | const el = selectedEl() |
| 251 | if (!el || e.button !== 0) return |
| 252 | const frame = frameRect() |
| 253 | gesture = { el, handle, frame, startX: e.clientX, startY: e.clientY, from: boxOf(el), box: boxOf(el), moved: false, guides: guides(othersBoxes(el)), pointerId: e.pointerId } |
| 254 | overlay.setPointerCapture(e.pointerId) |
| 255 | e.preventDefault() |
| 256 | } |
| 257 | overlay.addEventListener('pointerdown', e => { |
| 258 | const handle = e.target.closest('[slides-handle]') |
| 259 | if (handle) return start(e, handle.dataset.handle) |
| 260 | if (e.target.closest('[slides-drag]')) start(e, null) |
| 261 | }) |
| 262 | overlay.addEventListener('pointermove', e => { |
| 263 | if (!gesture || e.pointerId !== gesture.pointerId) return |
| 264 | const px = e.clientX - gesture.startX |
| 265 | const py = e.clientY - gesture.startY |
| 266 | if (!gesture.moved && Math.hypot(px, py) < DRAG_THRESHOLD_PX) return |
| 267 | gesture.moved = true |
| 268 | const dx = px / gesture.frame.width |
| 269 | const dy = py / gesture.frame.height |
| 270 | let box = gesture.handle ? resizeBox(gesture.from, gesture.handle, dx, dy) : moveBox(gesture.from, dx, dy) |
| 271 | box = gesture.handle ? snapResize(box, gesture.handle, gesture.guides) : snapMove(box, gesture.guides) |
| 272 | box = clampBox(box) |
| 273 | gesture.box = box |
| 274 | applyBox(gesture.el, box) |
| 275 | place() |
| 276 | }) |
| 277 | function end (e) { |
| 278 | if (!gesture || e.pointerId !== gesture.pointerId) return |
| 279 | const g = gesture |
| 280 | gesture = null |
| 281 | if (!g.moved) return |
| 282 | const box = fixBox(g.box) |
| 283 | if (!sameBox(box, fixBox(g.from))) onCommit(g.el.getAttribute('data-id'), box) |
| 284 | } |
| 285 | overlay.addEventListener('pointerup', end) |
| 286 | overlay.addEventListener('pointercancel', end) |
| 287 | |
| 288 | // A held arrow key repeats several times a second; a mouse drag |
| 289 | // commits once, at pointerup. The keyboard gets the same shape: the |
| 290 | // box is redrawn on every keydown for instant feedback, but onCommit |
| 291 | // — a Y transaction, and past it a save-queue post — fires once, |
| 292 | // after the burst settles, not once per repeat. |
| 293 | let nudgeTimer = null |
| 294 | let pending = null |
| 295 | function flushNudge () { |
| 296 | if (!pending) return |
| 297 | clearTimeout(nudgeTimer) |
| 298 | nudgeTimer = null |
| 299 | const { id, box } = pending |
| 300 | pending = null |
| 301 | onCommit(id, box) |
| 302 | } |
| 303 | overlay.addEventListener('keydown', e => { |
| 304 | const el = selectedEl() |
| 305 | if (!el || e.ctrlKey || e.metaKey) return |
| 306 | const id = el.getAttribute('data-id') |
| 307 | if (pending && pending.id !== id) flushNudge() |
| 308 | const next = nudge(boxOf(el), e.key, { shift: e.shiftKey, alt: e.altKey }) |
| 309 | if (!next) return |
| 310 | e.preventDefault() |
| 311 | const box = fixBox(next) |
| 312 | applyBox(el, box) |
| 313 | pending = { id, box } |
| 314 | place() |
| 315 | clearTimeout(nudgeTimer) |
| 316 | nudgeTimer = setTimeout(flushNudge, NUDGE_COALESCE_MS) |
| 317 | }) |
| 318 | |
| 319 | const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => place()) : null |
| 320 | if (ro) ro.observe(stageEl) |
| 321 | |
| 322 | return { |
| 323 | place, |
| 324 | focus: () => { if (!overlay.hidden) overlay.focus() }, |
| 325 | destroy () { |
| 326 | // A resync destroys this mount before another replaces it: the |
| 327 | // last nudge in a burst is real intent and lands rather than |
| 328 | // being dropped on the floor with the timer that was carrying it. |
| 329 | flushNudge() |
| 330 | if (ro) ro.disconnect() |
| 331 | overlay.remove() |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |