Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: the drags, the pinch and the menus a phone could not reach (#431)

nyblnet2473792def37
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index 828ead8a..b99adc26 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -486,6 +486,46 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
2026, from the same file. `bento.journal()` opens today's for an agent, and
`bento.journal('2026-08-06')` any day's.
+- **A finger can do the four things only a mouse could.** Reordering a block,
+ nesting a page in the tree, moving an issue card between columns and moving a
+ card on a canvas were all mouse-only: the first three are HTML5
+ drag-and-drop, which never fires from a touch, and the fourth listened for
+ `mousedown`. Two had a fallback (Move up / Move down in the block menu; tap a
+ card's status chip) and **the page tree had none** — nesting a page was
+ impossible on a phone by any route. Press and hold now starts the same drag,
+ and holding a card at the edge of a board or a list scrolls it along, since at
+ 390px only one of six columns is on screen at a time.
+
+ A finger that MOVES is still scrolling. Nothing is captured until the press
+ has been held still, so a swipe that starts on a card scrolls the page exactly
+ as it did before.
+
+- **Pinch to zoom the graph.** One finger already panned it, but zoom was on the
+ scroll wheel alone — so on a phone the one view whose whole point is a crowded
+ picture could be shoved around and never scaled. Two fingers zoom about the
+ point between them and pan at the same time; the second finger also ends the
+ one-finger drag it interrupts, so the two gestures no longer fight.
+
+- **A menu taller than the window has items nobody can reach.** Measured on a
+ 390×800 phone: Insert laid out 19 items 1000px tall, putting Table, Link to
+ the web, Image and Video or audio 253px below the screen with no gesture that
+ reaches them — the menu is positioned inside a fixed bar, so the page cannot
+ scroll to them. ⋯ lost its last five the same way. Both scroll now, and this
+ was never only a phone bug: on an 860px laptop window the last Insert item was
+ off the bottom too.
+
+- **A sideways swipe stops at the edge of what it is scrolling.** A board or a
+ wide table that runs out of content handed the rest of the gesture to the
+ browser, which on a phone is the back-navigation swipe. It ends where the
+ board does.
+
+- **A wide page stops giving away a third of a phone.** "Wide" is 80% of the
+ window, which is a sensible proportion on a desktop and 283px on a 390px
+ phone — with the block gutter's 26px that left a 257px column inside a 390px
+ screen. It takes the whole width below 850px and is unchanged above it
+ (measured at 1400px: 872px before and after). And the sharing button, alone
+ among the toolbar's controls, was 35×29 rather than the 40×40 every other one
+ gets on a touch screen.
- **Callouts, quotes and captions survive a trip through Markdown.** Four
places where the exporter and the importer disagreed with each other, each
measured by exporting one block and reading it back:
diff --git a/spaces/src/canvas.ts b/spaces/src/canvas.ts
index f4284aeb..c8f1991e 100644
--- a/spaces/src/canvas.ts
+++ b/spaces/src/canvas.ts
@@ -62,6 +62,7 @@ import { descendantsOf, newBlock } from './model.ts'
import { sanitizeInline } from './sanitize.ts'
import { t } from './i18n.ts'
import { ICONS } from './icons.ts'
+import { touchDragAsMouse } from './touch.ts'
/** The surface's shape, width ÷ height. Wide, because the first thing anyone
* draws here is a row of steps. */
@@ -428,6 +429,11 @@ function wireCard(card: HTMLElement, body: HTMLElement, hooks: CanvasHooks): voi
card.appendChild(grip)
grip.addEventListener('mousedown', (down) => startDrag(down, card, body, id, hooks))
+ // AND A FINGER DRIVES THE SAME GESTURE. The mouse choice above is right and
+ // none of its reasoning is about input hardware, so a touch is replayed as
+ // the mouse stream it already handles rather than forked into a second drag
+ // with its own clamps and its own commit. See touch.ts.
+ touchDragAsMouse(grip)
// THE KEYBOARD MOVES IT TOO. A surface reachable only by mouse is a surface
// half this app's readers cannot use, and the same clamp and the same commit
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index 4e5dae96..8e1c9a7e 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -20,6 +20,7 @@ import { Store } from './store'
import { renderPage, toneLabel, paintCode } from './render'
import { notesOnPage } from './footnotes.ts'
import { wireCanvas, placeNewCard } from './canvas.ts'
+import { enableTouchDrag } from './touch.ts'
import { CODE_LANGS, langLabel, normLang } from './highlight'
import { canonicalize, escText, sanitizeInline, textOf } from './sanitize'
import { FormatBar } from './formatbar'
@@ -564,6 +565,13 @@ export class Editor {
}, true)
}
+ // A FINGER GETS THE DRAGS A MOUSE HAD. Blocks, page rows and issue cards
+ // are all `[draggable="true"]`, and HTML5 dnd never fires from a touch —
+ // so press-and-hold replays the same dnd events those handlers already
+ // listen for. One call, delegated at the root, so anything draggable this
+ // editor grows later is covered without a second edit. See touch.ts.
+ enableTouchDrag(this.root)
+
this.paintTree()
this.paintPage()
this.syncHistoryButtons()
diff --git a/spaces/src/graph.ts b/spaces/src/graph.ts
index 9a16a07c..bff92e89 100644
--- a/spaces/src/graph.ts
+++ b/spaces/src/graph.ts
@@ -43,6 +43,7 @@
import type { SpacesDoc, SpaceIndex } from './model.ts'
import { ICONS } from './icons.ts'
import { t } from './i18n.ts'
+import { enablePinchZoom } from './touch.ts'
// ————— the graph itself ————————————————————————————————————————————————————
@@ -761,6 +762,23 @@ export function openGraphView(opts: GraphViewOpts): GraphView {
draw()
}, { passive: false })
+ // ——— two fingers ———
+ //
+ // One finger already worked: the pointer path above is pointer events, and a
+ // touch drives those. ZOOM did not — it was `wheel` alone, and a phone has no
+ // wheel, so a crowded graph could be shoved around and never scaled. Fit was
+ // the only way to change magnification and it only ever gives you one.
+ //
+ // The second finger also has to CANCEL the one-finger drag it interrupts, or
+ // the pointer path keeps panning (or worse, keeps dragging a node) underneath
+ // the pinch and the two fight over the same picture.
+ canvas.addEventListener('touchstart', (e) => { if (e.touches.length > 1) drag = null }, { passive: true })
+ enablePinchZoom(canvas, {
+ get: () => ({ scale, panX, panY }),
+ set: (s, x, y) => { scale = s; panX = x; panY = y; draw() },
+ limits: [0.12, 5],
+ })
+
fitBtn.addEventListener('click', () => { fit(); draw() })
closeBtn.addEventListener('click', () => opts.close())
diff --git a/spaces/src/render.ts b/spaces/src/render.ts
index f030fe3a..37a30051 100644
--- a/spaces/src/render.ts
+++ b/spaces/src/render.ts
@@ -988,7 +988,16 @@ export function renderPage(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): H
// 80% keeps a visible step at every size, and the 1500px cap keeps Wide from
// becoming an unreadable line on a very large screen — at which point Full is
// the thing to pick, deliberately.
- else if (width === 'wide') inner.style.maxWidth = 'min(1500px, 80%)'
+ // …WITH A FLOOR, because a proportion has nothing to be a proportion OF on a
+ // phone. 80% of a 354px page is 283px, and the 26px the gutter takes there
+ // leaves a 257px column on a 390px screen — a third of the display given to
+ // margin on the setting whose entire purpose is "room for a board or a
+ // table", and reachable in one tap ("Use this width for every page" is a
+ // per-screen preference). `max(80%, 680px)` is the same 80% wherever 80% is
+ // at least 680px (a container of 850px and up) and the whole container below
+ // that, since a max-width wider than the box does nothing. Measured at 390px:
+ // column 257 → 328, the page's left margin 79 → 26.
+ else if (width === 'wide') inner.style.maxWidth = 'min(1500px, max(80%, 680px))'
else if (doc.theme.measure) {
// AND THE DEFAULT ITSELF GROWS. 720px is ~88 characters at 16px, which is
// already at the long end — so this does not widen the line much; what it
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index d5d8cdf8..25ad58f0 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -777,7 +777,10 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset
/* A WIDE TABLE SCROLLS. The measure belongs to the document, so a six-column
table must not widen the prose column on a phone — it gets its own scroller
and the paragraph above it keeps its line length. */
-.sp-tb-wrap { overflow-x: auto; position: relative; }
+/* `overscroll-behavior-x` for the reason spelled out on `.sp-board`: a
+ sideways swipe that runs out of table must stop, not become the browser's
+ back gesture. */
+.sp-tb-wrap { overflow-x: auto; overscroll-behavior-x: contain; position: relative; }
.sp-tb {
width: 100%; border-collapse: collapse; table-layout: fixed;
font-size: 15px; line-height: 1.5;
@@ -1702,6 +1705,19 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset
.sp-mkbd { display: none; }
}
+/* WHILE A FINGER IS DRAGGING. The press that starts a touch drag is also the
+ press that arms text selection on iOS and Android, and a card whose title is
+ being selected mid-drag paints a blue smear across the gesture. touch.ts
+ clears the selection when the hold fires; this stops a new one starting. */
+body.sp-touchdrag, body.sp-touchdrag * { -webkit-user-select: none; user-select: none; }
+/* AND SCROLL SNAPPING STANDS DOWN WHILE IT LASTS. The board's
+ `scroll-snap-type: x proximity` is right for a thumb flicking between
+ columns and wrong for the 12px-per-frame creep that carries a held card
+ towards an off-screen column: each step lands inside the proximity of the
+ snap point it just left and is pulled straight back. Measured before this
+ rule, with the finger parked at the board's right edge for 1400ms:
+ scrollLeft 0 → 0. */
+body.sp-touchdrag .sp-board { scroll-snap-type: none; }
/* ————— find & replace on a small screen —————
Measured at a 575px viewport: the bar laid out 644px wide and started at
@@ -2004,6 +2020,14 @@ button.sp-prop-val:hover { background: var(--surface); border-color: var(--edge)
.sp-board {
display: flex; gap: 12px; overflow-x: auto; padding-bottom: 6px;
scroll-snap-type: x proximity;
+ /* …AND THE SWIPE STOPS AT ITS OWN EDGE. `overflow-x: auto` keeps the board's
+ columns out of the document, but by default a touch scroll that reaches
+ the end of a scroller CHAINS to its ancestors — and on a phone the
+ outermost ancestor is the browser's own back-navigation gesture. Measured
+ at 390px: the board holds 1452px of columns in a 257px box, so a reader
+ swiping through five columns hits that end on nearly every gesture.
+ Containment ends the scroll where the board does. */
+ overscroll-behavior-x: contain;
}
.sp-col {
flex: 0 0 232px; min-width: 232px; scroll-snap-align: start;
@@ -2069,7 +2093,7 @@ button.sp-issue-set:hover { background: var(--chrome-2); border-color: var(--edg
the rest as data: tabular figures, a quiet rule under the head, and no
vertical lines — a grid of boxes is a spreadsheet, and this is a list of
documents that happens to have columns. */
-.sp-view-tablewrap { overflow-x: auto; margin: 0 0 4px; }
+.sp-view-tablewrap { overflow-x: auto; overscroll-behavior-x: contain; margin: 0 0 4px; }
.sp-view-table {
border-collapse: collapse; width: 100%; font-size: 13.5px;
font-variant-numeric: tabular-nums;
diff --git a/spaces/src/touch.ts b/spaces/src/touch.ts
new file mode 100644
index 00000000..0c261820
--- /dev/null
+++ b/spaces/src/touch.ts
@@ -0,0 +1,367 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// TOUCH: the gestures a finger needs and a mouse already had.
+//
+// This file exists because three of this app's most ordinary actions were
+// reachable ONLY with a mouse, and the measurement is the argument:
+//
+// · reordering a block — `grip.draggable = true`, HTML5 dnd
+// · nesting a page in the tree — `a.draggable = true`, HTML5 dnd
+// · moving an issue card — `card.draggable = true`, HTML5 dnd
+// · moving a card on a canvas — `grip.addEventListener('mousedown', …)`
+//
+// HTML5 drag-and-drop does not exist on a touch screen. Not "is awkward" —
+// `dragstart` never fires from a finger on iOS or Android, so those three
+// gestures were not degraded on a phone, they were ABSENT. Two of them had a
+// documented fallback (Move up / Move down in the block menu; tap the status
+// chip on a card), and the page tree had none at all: nesting a page was
+// impossible on a phone, by any route.
+//
+// THE SHAPE OF THE FIX: REPLAY, DON'T REIMPLEMENT.
+//
+// The obvious version of this file is a second drag engine that knows what a
+// block, a page row and an issue card each mean. That is three copies of logic
+// that already exists and works, kept in step by hand forever. So instead the
+// touch gesture SYNTHESISES THE EVENTS THE EXISTING HANDLERS ALREADY LISTEN
+// FOR — a real `DataTransfer`, a real `dragstart` on the source, `dragover` /
+// `dragleave` on whatever is under the finger, `drop`, `dragend`. Every drop
+// rule, every "only a block drag" payload check, every `.sp-drop` /
+// `.sp-dropline` / `.sp-dropbefore` highlight in editor.ts is reached
+// unchanged and unaware. Adding a fourth draggable thing to the editor gets
+// touch support with no edit here.
+//
+// `new DataTransfer()` is what makes that honest rather than a mock: the
+// source's own `dragstart` handler calls `setData` on it, so `types` and
+// `getData` in the drop handler answer with the real payload the real gesture
+// would have carried.
+//
+// A LONG PRESS, NOT A DRAG THRESHOLD. A finger that moves is scrolling — that
+// is the whole vocabulary of a touch screen, and a page you cannot scroll
+// because you started on a card is worse than a card you cannot drag. So the
+// gesture is: press, hold HOLD_MS without moving more than SLOP, and only then
+// does the surface become a drag. Move first and the drag is cancelled and the
+// scroll is left completely alone (nothing is preventDefault-ed until the hold
+// has fired). This is the same bargain a phone's home screen makes, and it is
+// why press-and-hold is also what opens a context menu: it is the gesture that
+// means "this thing, specifically" rather than "the page".
+//
+// DESKTOP IS NOT TOUCHED. Every listener here is a `touch*` listener. A mouse
+// emits none of them, so a machine driven by a mouse runs not one line of this
+// file — which is the only reason a change this broad can be made to four
+// mouse-driven surfaces at once without a desktop regression to argue about.
+
+/** How long a finger must sit still before a press becomes a drag. */
+const HOLD_MS = 320
+/** How far it may drift in that time and still count as sitting still. */
+const SLOP = 10
+
+/** How close to a scroller's edge the finger has to be to drag the view along. */
+const EDGE = 44
+/** Pixels per frame at the very edge. Gentle: this runs at 60Hz. */
+const EDGE_SPEED = 12
+
+const point = (e: TouchEvent): Touch | null => e.touches[0] ?? e.changedTouches[0] ?? null
+
+/**
+ * Drag the view when the finger reaches the edge of what it can see.
+ *
+ * WITHOUT THIS THE BOARD DRAG IS A RIG TRICK. Measured on the built shell at
+ * 390px: the board holds six columns 232px wide in a 328px box, so exactly one
+ * column and a sliver of the next are on screen. Every drop target worth
+ * dragging to is therefore OUTSIDE the viewport, `elementFromPoint` returns
+ * null there, and a gesture that cannot reach its target is not a feature. The
+ * finger is also holding the card, so it cannot scroll the board itself.
+ *
+ * The scroller is found per frame rather than once, because a drag crosses
+ * between them — out of a board sideways, down a sidebar, down the page.
+ */
+function edgeScroll(x: number, y: number): void {
+ let el: Element | null = document.elementFromPoint(x, y)
+ while (el) {
+ const s = el as HTMLElement
+ const canX = s.scrollWidth - s.clientWidth > 2
+ const canY = s.scrollHeight - s.clientHeight > 2
+ if (canX || canY) {
+ const r = s.getBoundingClientRect()
+ if (canX) {
+ if (x < r.left + EDGE) s.scrollLeft -= EDGE_SPEED
+ else if (x > r.right - EDGE) s.scrollLeft += EDGE_SPEED
+ }
+ if (canY) {
+ if (y < r.top + EDGE) s.scrollTop -= EDGE_SPEED
+ else if (y > r.bottom - EDGE) s.scrollTop += EDGE_SPEED
+ }
+ return
+ }
+ el = s.parentElement
+ }
+ // Nothing between the finger and the root scrolls: the page itself might.
+ const root = document.scrollingElement as HTMLElement | null
+ if (!root) return
+ if (y < EDGE) root.scrollTop -= EDGE_SPEED
+ else if (y > innerHeight - EDGE) root.scrollTop += EDGE_SPEED
+}
+
+/**
+ * Give every `[draggable="true"]` inside `root` a press-and-hold drag.
+ *
+ * Returns its own teardown, so a caller that rebuilds the app can let go of it.
+ */
+export function enableTouchDrag(root: HTMLElement): () => void {
+ let src: HTMLElement | null = null
+ let data: DataTransfer | null = null
+ let over: Element | null = null
+ let hold = 0
+ let startX = 0
+ let startY = 0
+ let live = false
+ let atX = 0
+ let atY = 0
+ let creep = 0
+
+ const fire = (type: string, on: EventTarget, x: number, y: number): boolean => {
+ // A real DragEvent, carrying a real DataTransfer: the handlers downstream
+ // read `dataTransfer.types` to decide whether this drag is theirs, and a
+ // CustomEvent could not answer that question.
+ const ev = new DragEvent(type, {
+ bubbles: true, cancelable: true, composed: true,
+ clientX: x, clientY: y, dataTransfer: data,
+ })
+ return on.dispatchEvent(ev)
+ }
+
+ const cancelHold = (): void => { if (hold) { clearTimeout(hold); hold = 0 } }
+
+ /** Re-aim at whatever is under the finger now — after a move, or after the
+ * edge scroll has slid new content beneath a finger that has not moved. */
+ const aim = (): void => {
+ const under = document.elementFromPoint(atX, atY)
+ if (under !== over) {
+ if (over) fire('dragleave', over, atX, atY)
+ over = under
+ }
+ if (over) fire('dragover', over, atX, atY)
+ }
+
+ // `setInterval`, not `requestAnimationFrame`: a finger PARKED at the edge
+ // must keep scrolling, and rAF is throttled to zero in a hidden or occluded
+ // tab (CLAUDE.md's testing note — the same trap that makes an unfocused rig
+ // report "it does not animate"). A timer degrades to slow rather than to
+ // nothing, which is also what makes this measurable off a phone.
+ const stopCreep = (): void => { if (creep) { clearInterval(creep); creep = 0 } }
+ const startCreep = (): void => {
+ stopCreep()
+ creep = window.setInterval(() => {
+ if (!live) { stopCreep(); return }
+ edgeScroll(atX, atY)
+ aim()
+ }, 16)
+ }
+
+ const finish = (x: number, y: number, dropIt: boolean): void => {
+ const from = src
+ const target = over
+ src = null; over = null; live = false
+ cancelHold()
+ stopCreep()
+ document.body.classList.remove('sp-touchdrag')
+ if (!from) return
+ if (dropIt && target) fire('drop', target, x, y)
+ else if (target) fire('dragleave', target, x, y)
+ fire('dragend', from, x, y)
+ data = null
+ }
+
+ const onStart = (e: TouchEvent): void => {
+ if (e.touches.length !== 1) { finish(0, 0, false); return }
+ const t = point(e)
+ if (!t) return
+ const at = t.target instanceof Element ? t.target : null
+ const cand = at?.closest<HTMLElement>('[draggable="true"]')
+ if (!cand || !root.contains(cand)) return
+ // A button inside a draggable row is its own control — the ⋯ on a page row,
+ // the status chip on a card. Pressing one must never drag its container.
+ const btn = at?.closest('button')
+ if (btn && btn !== cand) return
+ src = cand
+ startX = atX = t.clientX
+ startY = atY = t.clientY
+ hold = window.setTimeout(() => {
+ hold = 0
+ if (!src) return
+ live = true
+ startCreep()
+ data = new DataTransfer()
+ document.body.classList.add('sp-touchdrag')
+ // The long press has already armed the OS text-selection gesture on some
+ // browsers; the drag owns the finger from here.
+ getSelection()?.removeAllRanges()
+ navigator.vibrate?.(8)
+ fire('dragstart', src, startX, startY)
+ }, HOLD_MS)
+ }
+
+ const onMove = (e: TouchEvent): void => {
+ if (!src) return
+ const t = point(e)
+ if (!t) return
+ if (!live) {
+ // Still deciding. A finger that has travelled is scrolling, and this
+ // listener has not called preventDefault, so the scroll already started
+ // and is none of our business.
+ if (Math.abs(t.clientX - startX) + Math.abs(t.clientY - startY) > SLOP) {
+ cancelHold(); src = null
+ }
+ return
+ }
+ e.preventDefault()
+ atX = t.clientX
+ atY = t.clientY
+ aim()
+ }
+
+ const onEnd = (e: TouchEvent): void => {
+ const t = point(e)
+ finish(t?.clientX ?? 0, t?.clientY ?? 0, live)
+ }
+
+ const onCancel = (): void => { finish(0, 0, false) }
+
+ // `passive: false` on the move listener because a live drag must be able to
+ // stop the page scrolling under it. touchstart stays passive: it never
+ // prevents anything, and the decision has not been made yet.
+ root.addEventListener('touchstart', onStart, { passive: true })
+ root.addEventListener('touchmove', onMove, { passive: false })
+ root.addEventListener('touchend', onEnd, { passive: true })
+ root.addEventListener('touchcancel', onCancel, { passive: true })
+
+ return () => {
+ finish(0, 0, false)
+ root.removeEventListener('touchstart', onStart)
+ root.removeEventListener('touchmove', onMove)
+ root.removeEventListener('touchend', onEnd)
+ root.removeEventListener('touchcancel', onCancel)
+ }
+}
+
+/**
+ * Let a finger drive a handle that was written for a mouse.
+ *
+ * The canvas card grip (canvas.ts) is a deliberate MOUSE drag rather than dnd:
+ * a free surface needs a continuous coordinate, and dnd reports a drop target.
+ * Its reasoning is sound and none of it is touch-specific, so rather than
+ * fork it, a touch on the handle is replayed as the mousedown/mousemove/mouseup
+ * stream it already listens for. One gesture, one implementation, one set of
+ * clamps and one commit.
+ *
+ * No long press here: a grip is an explicit handle whose only purpose is to be
+ * dragged, so there is nothing to disambiguate and nothing to wait for.
+ */
+export function touchDragAsMouse(handle: HTMLElement): void {
+ let on = false
+
+ const send = (type: string, to: EventTarget, t: Touch): void => {
+ to.dispatchEvent(new MouseEvent(type, {
+ bubbles: true, cancelable: true, composed: true,
+ clientX: t.clientX, clientY: t.clientY, button: 0,
+ }))
+ }
+
+ const move = (e: TouchEvent): void => {
+ const t = point(e)
+ if (!t || !on) return
+ e.preventDefault()
+ send('mousemove', window, t)
+ }
+
+ const end = (e: TouchEvent): void => {
+ if (!on) return
+ on = false
+ const t = point(e)
+ if (t) send('mouseup', window, t)
+ window.removeEventListener('touchmove', move)
+ window.removeEventListener('touchend', end)
+ window.removeEventListener('touchcancel', end)
+ }
+
+ handle.addEventListener('touchstart', (e: TouchEvent) => {
+ if (e.touches.length !== 1) return
+ const t = point(e)
+ if (!t) return
+ e.preventDefault()
+ on = true
+ window.addEventListener('touchmove', move, { passive: false })
+ window.addEventListener('touchend', end, { passive: true })
+ window.addEventListener('touchcancel', end, { passive: true })
+ send('mousedown', handle, t)
+ }, { passive: false })
+}
+
+/** What a pinch reports back to the surface it is zooming. */
+export interface PinchHost {
+ /** the surface's camera, right now */
+ get(): { scale: number; panX: number; panY: number }
+ /** the camera it should have; the surface redraws */
+ set(scale: number, panX: number, panY: number): void
+ /** the narrowest and widest the surface will go */
+ limits: [number, number]
+}
+
+/**
+ * Two fingers: pinch to zoom, and drag to pan.
+ *
+ * The graph could already be panned with one finger (its `pointerdown` path is
+ * pointer events, which a touch drives) — but zoom was on `wheel` alone, and a
+ * phone has no wheel. So a graph on a phone could be moved and never scaled:
+ * the one operation a crowded picture actually needs.
+ *
+ * Zoom is about the MIDPOINT of the two fingers, the same rule the wheel path
+ * uses about the cursor — the thing between your fingers is the thing you are
+ * looking at, and it should stay where it is.
+ */
+export function enablePinchZoom(el: HTMLElement, host: PinchHost): void {
+ let d0 = 0
+ let mid0 = { x: 0, y: 0 }
+ let cam0 = { scale: 1, panX: 0, panY: 0 }
+
+ const pair = (e: TouchEvent): { d: number; x: number; y: number } | null => {
+ const [a, b] = [e.touches[0], e.touches[1]]
+ if (!a || !b) return null
+ const r = el.getBoundingClientRect()
+ const dx = a.clientX - b.clientX
+ const dy = a.clientY - b.clientY
+ return {
+ d: Math.hypot(dx, dy),
+ x: (a.clientX + b.clientX) / 2 - r.left,
+ y: (a.clientY + b.clientY) / 2 - r.top,
+ }
+ }
+
+ el.addEventListener('touchstart', (e: TouchEvent) => {
+ const p = pair(e)
+ if (!p) { d0 = 0; return }
+ d0 = p.d || 1
+ mid0 = { x: p.x, y: p.y }
+ cam0 = host.get()
+ }, { passive: true })
+
+ el.addEventListener('touchmove', (e: TouchEvent) => {
+ if (!d0) return
+ const p = pair(e)
+ if (!p) return
+ e.preventDefault()
+ const [lo, hi] = host.limits
+ const next = Math.max(lo, Math.min(hi, cam0.scale * (p.d / d0)))
+ // Zoom about the starting midpoint, then follow wherever that midpoint has
+ // travelled since — so a pinch that also slides pans at the same time,
+ // which is what a hand does whether or not it means to.
+ const panX = p.x - ((mid0.x - cam0.panX) / cam0.scale) * next
+ const panY = p.y - ((mid0.y - cam0.panY) / cam0.scale) * next
+ host.set(next, panX, panY)
+ }, { passive: false })
+
+ const stop = (e: TouchEvent): void => { if (e.touches.length < 2) d0 = 0 }
+ el.addEventListener('touchend', stop, { passive: true })
+ el.addEventListener('touchcancel', stop, { passive: true })
+}