diff --git a/bun.lock b/bun.lock index f3ea0dcbd..23407d2e3 100644 --- a/bun.lock +++ b/bun.lock @@ -2659,6 +2659,7 @@ }, "devDependencies": { "@sand/harness": "workspace:*", + "playwright": "^1.64.1", }, }, "plugins/ui/chat/images": { diff --git a/package.json b/package.json index 574460b80..81a6436a5 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "bench:gate": "bun apps/bench/src/gate/main.ts", "test": "bun test --parallel=4 --timeout 60000 ./apps ./packages ./plugins", "test:upgrade": "bun test --timeout 1200000 ./plugins/host/daemon/test/upgrade/upgrade.ts", - "test:phone": "bun test --parallel --timeout 30000 ./plugins/ui/look/kit/test/gallery/gallery.ts ./plugins/ui/shell/shell/test/phone/window.ts ./plugins/ui/shell/shell/test/phone/drawers.ts ./plugins/ui/shell/shell/test/phone/keyboard.ts ./plugins/core/features/test/web/matrix.ts ./plugins/ui/chat/chat/test/web/follow.ts ./plugins/ui/chat/chat/test/web/catch-up.ts ./plugins/ui/chat/chat/test/web/draft.ts ./plugins/ui/chat/chat/test/web/early.ts ./plugins/ui/chat/chat/test/web/reply.ts ./plugins/ui/chat/chat/test/web/upload.ts ./plugins/bots/views/test/web/history.ts ./plugins/bots/views/test/web/tabs.ts ./plugins/core/server/test/web/hello.ts ./plugins/ui/shell/shell/test/web/parts.ts" + "test:phone": "bun test --parallel --timeout 30000 ./plugins/ui/look/kit/test/gallery/gallery.ts ./plugins/ui/shell/shell/test/phone/window.ts ./plugins/ui/shell/shell/test/phone/drawers.ts ./plugins/ui/shell/shell/test/phone/keyboard.ts ./plugins/core/features/test/web/matrix.ts ./plugins/ui/chat/chat/test/web/follow.ts ./plugins/ui/chat/chat/test/web/catch-up.ts ./plugins/ui/chat/chat/test/web/draft.ts ./plugins/ui/chat/chat/test/web/early.ts ./plugins/ui/chat/chat/test/web/reply.ts ./plugins/ui/chat/chat/test/web/upload.ts ./plugins/bots/views/test/web/history.ts ./plugins/bots/views/test/web/tabs.ts ./plugins/core/server/test/web/hello.ts ./plugins/ui/shell/shell/test/web/parts.ts ./plugins/ui/chat/html/test/web/zoom.ts" }, "devDependencies": { "@sand/boot": "workspace:*", diff --git a/plugins/ui/chat/html/package.json b/plugins/ui/chat/html/package.json index 6696eb6d4..3794048f7 100644 --- a/plugins/ui/chat/html/package.json +++ b/plugins/ui/chat/html/package.json @@ -38,6 +38,7 @@ "zod": "^4.6.5" }, "devDependencies": { - "@sand/harness": "workspace:*" + "@sand/harness": "workspace:*", + "playwright": "^1.64.1" } } diff --git a/plugins/ui/chat/html/src/page/integrations/index.ts b/plugins/ui/chat/html/src/page/integrations/index.ts index 60fd9e9ee..df13fbdf7 100644 --- a/plugins/ui/chat/html/src/page/integrations/index.ts +++ b/plugins/ui/chat/html/src/page/integrations/index.ts @@ -4,6 +4,7 @@ import { forwardLinks } from './links' import { reportSize } from './size' import { relaySwipes } from './swipe' import { followTheme } from './theme' +import { relayZoom } from './zoom' if (window.parent !== window) { followTheme() @@ -12,4 +13,5 @@ if (window.parent !== window) { forwardLinks() reportSize() relaySwipes() + relayZoom() } diff --git a/plugins/ui/chat/html/src/page/integrations/zoom.ts b/plugins/ui/chat/html/src/page/integrations/zoom.ts new file mode 100644 index 000000000..580fa1d5f --- /dev/null +++ b/plugins/ui/chat/html/src/page/integrations/zoom.ts @@ -0,0 +1,14 @@ +import { zoomGesture } from '@sand/ui-kit/contract' +import { listen } from '@vaakx-dev/vrui' +import { zoomable, zoomBy, zoomToggle } from '../protocol' +import { post } from './post' + +const relay = () => zoomGesture(window, { zoom: change => post(zoomBy, change), toggle: at => post(zoomToggle, { at }) }, { wheel: 'scrolls', surface: 'scaled' }) + +export const relayZoom = () => { + const stop = listen(window, 'message', ({ source, data }) => { + if (source !== window.parent || data?.method !== zoomable) return + stop() + relay() + }) +} diff --git a/plugins/ui/chat/html/src/page/protocol.ts b/plugins/ui/chat/html/src/page/protocol.ts index e067bde26..22cefc236 100644 --- a/plugins/ui/chat/html/src/page/protocol.ts +++ b/plugins/ui/chat/html/src/page/protocol.ts @@ -12,3 +12,6 @@ export const showPage = 'sand/show-page' export const swipeStart = 'sand/swipe-start' export const swipeMove = 'sand/swipe-move' export const swipeEnd = 'sand/swipe-end' +export const zoomable = 'sand/zoomable' +export const zoomBy = 'sand/zoom-by' +export const zoomToggle = 'sand/zoom-toggle' diff --git a/plugins/ui/chat/html/src/web/expand.ts b/plugins/ui/chat/html/src/web/expand.ts index f320cce1d..c9f768ab2 100644 --- a/plugins/ui/chat/html/src/web/expand.ts +++ b/plugins/ui/chat/html/src/web/expand.ts @@ -1,4 +1,5 @@ import type { SheetSpec } from '@sand/ui-shell/contract' +import type { Point, ZoomTarget } from '@sand/ui-kit/contract' import type { HtmlRenderEntry } from '../contract' import { columnWidth } from '../page/limits' import { hostPath } from '../page/protocol' @@ -6,11 +7,22 @@ import type { FrameContext } from './context' import { sandboxedFrame } from './integrations/frame' import { connectPage } from './page' +const onScreen = (frame: HTMLIFrameElement, { x, y }: Point): Point => { + const box = frame.getBoundingClientRect() + const scale = box.width / columnWidth + return { x: box.left + x * scale, y: box.top + y * scale } +} + +const zoomFrom = (frame: HTMLIFrameElement, zoom: ZoomTarget): ZoomTarget => ({ + zoom: ({ factor, from, to }) => zoom.zoom({ factor, from: onScreen(frame, from), to: onScreen(frame, to) }), + toggle: at => zoom.toggle(onScreen(frame, at)), +}) + export const expandedPage = (ctx: FrameContext, data: HtmlRenderEntry, html: string, height: number): SheetSpec => { const { kit } = ctx const zoom = kit.fitZoom({ width: columnWidth, height }) const frame = sandboxedFrame({ 'aria-label': data.title, src: hostPath, class: 'block h-full w-full border-0', onLoad: () => connection.show(html) }) - const connection = connectPage(ctx, frame, {}) + const connection = connectPage(ctx, frame, { zoom: zoomFrom(frame, zoom) }) return { label: `Full screen ${data.title}`, diff --git a/plugins/ui/chat/html/src/web/integrations/frame.ts b/plugins/ui/chat/html/src/web/integrations/frame.ts index 219cd8fb5..8c1280eaf 100644 --- a/plugins/ui/chat/html/src/web/integrations/frame.ts +++ b/plugins/ui/chat/html/src/web/integrations/frame.ts @@ -1,12 +1,40 @@ import type { Swipe, Way } from '@sand/ui-shell/contract' +import type { Point, ZoomTarget } from '@sand/ui-kit/contract' import { el, listen, type Props } from '@vaakx-dev/vrui' -import { hostContext, openImage, openLink, pressKey, shortcutKeys, showPage, sizeChanged, swipeEnd, swipeMove, swipeStart } from '../../page/protocol' +import { + hostContext, + openImage, + openLink, + pressKey, + shortcutKeys, + showPage, + sizeChanged, + swipeEnd, + swipeMove, + swipeStart, + zoomable, + zoomBy, + zoomToggle, +} from '../../page/protocol' interface Message { jsonrpc?: unknown id?: unknown method?: unknown - params?: { height?: unknown; url?: unknown; delta?: unknown; way?: unknown; velocity?: unknown; src?: unknown; name?: unknown; key?: unknown } + params?: { + height?: unknown + url?: unknown + delta?: unknown + way?: unknown + velocity?: unknown + src?: unknown + name?: unknown + key?: unknown + factor?: unknown + from?: unknown + to?: unknown + at?: unknown + } } export interface FrameEvents { @@ -15,8 +43,14 @@ export interface FrameEvents { image(src: string, name: string): void key(key: string): void swipe?(way: Way): Swipe | undefined + zoom?: ZoomTarget } +const isPoint = (value: unknown): value is Point => + typeof value === 'object' && value !== null && 'x' in value && 'y' in value && Number.isFinite(value.x) && Number.isFinite(value.y) + +const isFactor = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0 + const isWebUrl = (url: unknown): url is string => typeof url === 'string' && /^https?:\/\//i.test(url) const clickedIn = (frame: HTMLIFrameElement) => document.activeElement === frame && navigator.userActivation?.isActive !== false @@ -32,6 +66,8 @@ export const sendTheme = (frame: HTMLIFrameElement, css: string) => post(frame, export const sendKeys = (frame: HTMLIFrameElement, keys: string[]) => post(frame, { method: shortcutKeys, params: { keys } }) +export const sendZoomable = (frame: HTMLIFrameElement) => post(frame, { method: zoomable }) + const WAYS: readonly unknown[] = ['left', 'right', 'up', 'down'] satisfies Way[] const isWay = (value: unknown): value is Way => WAYS.includes(value) @@ -62,6 +98,14 @@ export const listenToFrame = (frame: HTMLIFrameElement, events: FrameEvents) => events.key(params.key) return } + if (message.method === zoomBy && isFactor(params.factor) && isPoint(params.from) && isPoint(params.to)) { + events.zoom?.zoom({ factor: params.factor, from: params.from, to: params.to }) + return + } + if (message.method === zoomToggle && isPoint(params.at)) { + events.zoom?.toggle(params.at) + return + } if (!clickedIn(frame)) return if (message.method === openLink && isWebUrl(params.url)) { events.open(params.url) diff --git a/plugins/ui/chat/html/src/web/page.ts b/plugins/ui/chat/html/src/web/page.ts index 4b343ec2e..044df5568 100644 --- a/plugins/ui/chat/html/src/web/page.ts +++ b/plugins/ui/chat/html/src/web/page.ts @@ -3,10 +3,10 @@ import { keys } from '@sand/keys/contract' import { theme, type Theme } from '@sand/ui-theme/contract' import { joinDisposers } from '@sand/util' import type { FrameContext } from './context' -import { listenToFrame, sendKeys, sendTheme, showPageIn, type FrameEvents } from './integrations/frame' +import { listenToFrame, sendKeys, sendTheme, sendZoomable, showPageIn, type FrameEvents } from './integrations/frame' import { themeCss } from './theme' -export const connectPage = (ctx: FrameContext, frame: HTMLIFrameElement, events: Pick) => { +export const connectPage = (ctx: FrameContext, frame: HTMLIFrameElement, events: Pick) => { const paint = (current: Theme | undefined) => { if (current) sendTheme(frame, themeCss(current)) } @@ -15,6 +15,7 @@ export const connectPage = (ctx: FrameContext, frame: HTMLIFrameElement, events: showPageIn(frame, html) paint(ctx.get(theme)) sendKeys(frame, ctx.get(keys)?.passthroughKeys() ?? []) + if (events.zoom) sendZoomable(frame) }, listen: () => joinDisposers( diff --git a/plugins/ui/chat/html/test/web/sandbox.ts b/plugins/ui/chat/html/test/web/sandbox.ts new file mode 100644 index 000000000..99e212af8 --- /dev/null +++ b/plugins/ui/chat/html/test/web/sandbox.ts @@ -0,0 +1,47 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const main = join(import.meta.dir, '../../../../../../apps/sand/src/main.ts') + +const sand = async (home: string, ...args: string[]) => { + const run = Bun.spawn([process.execPath, main, '--home', home, ...args], { stdout: 'pipe', stderr: 'pipe' }) + const [out, err, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]) + if (code !== 0) throw new Error(`sand ${args.join(' ')} failed: ${err || out}`) + return out +} + +const printed = (out: string, pattern: RegExp) => { + const found = out.match(pattern)?.[1]?.trim() + if (!found) throw new Error(`sand sandbox printed no ${pattern}:\n${out}`) + return found +} + +const settings = (title: string, html: string) => + [ + '[features]', + '', + '[[plugins.replay.sources]]', + 'id = "replay"', + 'models = ["script"]', + `replies = [[{ type = "call", name = "html_render", input = { title = ${JSON.stringify(title)}, html = ${JSON.stringify(html)} } }], [{ type = "text", text = "Here it is" }]]`, + '', + '[plugins.thread-titles]', + 'enabled = false', + '', + ].join('\n') + +export const startSandbox = async (title: string, html: string) => { + const home = mkdtempSync(join(tmpdir(), 'sand-html-')) + await Bun.write(join(home, 'sandbox.toml'), settings(title, html)) + const out = await sand(home, 'sandbox') + rmSync(home, { recursive: true, force: true }) + const box = printed(out, /throwaway sand \(pid \d+\) in (.+)$/m) + return { + url: printed(out, /open it paired: (\S+)/), + async stop() { + await sand(box, 'stop') + rmSync(box, { recursive: true, force: true }) + }, + } +} diff --git a/plugins/ui/chat/html/test/web/zoom.ts b/plugins/ui/chat/html/test/web/zoom.ts new file mode 100644 index 000000000..94f975f91 --- /dev/null +++ b/plugins/ui/chat/html/test/web/zoom.ts @@ -0,0 +1,174 @@ +import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test' +import { chromium, type Browser, type CDPSession, type Locator, type Page } from 'playwright' +import { startSandbox } from './sandbox' + +interface Point { + x: number + y: number +} + +const TITLE = 'Harbor tides' + +const PIER = `data:image/svg+xml,${encodeURIComponent('')}` + +const PAGE = [ + '

Tide table

', + ...Array.from({ length: 6 }, (_, row) => `

High water ${row + 1} rises over the breakwater and settles by the pier.

`), + `Pier at dawn`, +].join('') + +let sand: Awaited> +let browser: Browser +let page: Page +let hand: ReturnType + +const fingers = (cdp: CDPSession) => { + const send = (type: 'touchStart' | 'touchMove' | 'touchEnd', points: Point[]) => + cdp.send('Input.dispatchTouchEvent', { type, touchPoints: points.map((point, id) => ({ ...point, id })) }) + const stroke = async (from: Point[], to: Point[], steps = 10) => { + await send('touchStart', from) + for (let step = 1; step <= steps; step++) { + await send( + 'touchMove', + from.map((start, index) => ({ x: start.x + ((to[index]!.x - start.x) * step) / steps, y: start.y + ((to[index]!.y - start.y) * step) / steps })), + ) + await Bun.sleep(16) + } + await send('touchEnd', []) + } + const tap = async (at: Point) => { + await send('touchStart', [at]) + await send('touchEnd', []) + } + return { + pinch: (center: Point, fromGap: number, toGap: number) => + stroke( + [ + { x: center.x - fromGap / 2, y: center.y }, + { x: center.x + fromGap / 2, y: center.y }, + ], + [ + { x: center.x - toGap / 2, y: center.y }, + { x: center.x + toGap / 2, y: center.y }, + ], + ), + drag: (from: Point, to: Point) => stroke([from], [to]), + tap, + doubleTap: async (at: Point) => { + await tap(at) + await Bun.sleep(80) + await tap(at) + }, + } +} + +const pointIn = async (node: Locator, across: number, down: number): Promise => { + const box = (await node.boundingBox())! + return { x: box.x + box.width * across, y: box.y + box.height * down } +} + +const centerOf = (node: Locator) => pointIn(node, 0.5, 0.5) + +const shareOf = async (node: Locator, { x, y }: Point) => { + const box = (await node.boundingBox())! + return { across: (x - box.x) / box.width, down: (y - box.y) / box.height } +} + +const expectHeld = async (node: Locator, share: { across: number; down: number }, at: Point) => { + const now = await pointIn(node, share.across, share.down) + expect(Math.abs(now.x - at.x)).toBeLessThan(4) + expect(Math.abs(now.y - at.y)).toBeLessThan(4) +} + + +const stageOf = (frame: Locator) => + frame.evaluate(node => { + const content = node.parentElement! + const scroller = content.parentElement! + return { level: Number(content.style.zoom), left: scroller.scrollLeft } + }) + +const scaleOf = (image: Locator) => image.evaluate(node => new DOMMatrix(getComputedStyle(node).transform).a) + +const offsetOf = (image: Locator) => + image.evaluate(node => { + const matrix = new DOMMatrix(getComputedStyle(node).transform) + return { x: matrix.e, y: matrix.f } + }) + +beforeAll(async () => { + sand = await startSandbox(TITLE, PAGE) + browser = await chromium.launch() + const context = await browser.newContext({ serviceWorkers: 'block', viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, deviceScaleFactor: 2 }) + page = await context.newPage() + hand = fingers(await context.newCDPSession(page)) + await page.goto(sand.url) + await page.getByRole('textbox').first().fill('Show me the tides') + await page.getByRole('button', { name: 'Send' }).click() + await page.getByText('Here it is').first().waitFor({ timeout: 60_000 }) +}, 90_000) + +afterEach(async () => { + await page.keyboard.press('Escape') + await page.getByRole('dialog').waitFor({ state: 'detached' }) +}) + +afterAll(async () => { + await browser?.close() + await sand?.stop() +}) + +const drawerOpen = () => page.evaluate(() => (document.querySelector('nav[aria-label="Sidebar"]')?.getBoundingClientRect().right ?? 0) > innerWidth / 2) + +test('a full-screen page pinches, pans and double-taps back to fit without the shell taking the swipe', async () => { + await page.getByRole('button', { name: 'Open full screen' }).first().click() + const sheet = page.getByRole('dialog', { name: `Full screen ${TITLE}` }) + const frame = sheet.locator('iframe') + await frame.contentFrame().getByText('Tide table').waitFor() + const fitted = await stageOf(frame) + + const focus = await centerOf(frame) + const share = await shareOf(frame, focus) + await hand.pinch(focus, 60, 240) + await expectHeld(frame, share, focus) + const pinched = await stageOf(frame) + expect(pinched.level).toBeGreaterThan(fitted.level * 2) + expect(await sheet.getByTitle('Fit to screen').innerText()).toMatch(/%$/) + + await hand.drag({ x: 300, y: 500 }, { x: 120, y: 500 }) + const panned = await stageOf(frame) + expect(panned.left).toBeGreaterThan(pinched.left + 100) + + await hand.drag({ x: 40, y: 500 }, { x: 300, y: 500 }) + expect((await stageOf(frame)).left).toBeLessThan(panned.left - 100) + expect(await sheet.isVisible()).toBe(true) + expect(await drawerOpen()).toBe(false) + + await hand.doubleTap(await centerOf(sheet)) + expect(await stageOf(frame)).toMatchObject({ level: fitted.level }) + expect(await sheet.getByTitle('Fit to screen').innerText()).toBe('Fit') +}, 60_000) + +test('an image opened from a page pinches, pans and double-taps back to fit without flipping or closing', async () => { + await hand.tap(await centerOf(page.locator(`iframe[aria-label="${TITLE}"]`).contentFrame().getByRole('img', { name: 'Pier at dawn' }))) + const viewer = page.getByRole('dialog', { name: 'Image viewer' }) + const image = viewer.locator('img') + await image.waitFor() + + const focus = await pointIn(image, 0.3, 0.6) + const share = await shareOf(image, focus) + await hand.pinch(focus, 40, 200) + expect(await scaleOf(image)).toBeGreaterThan(3) + await expectHeld(image, share, focus) + + const before = await offsetOf(image) + await hand.drag(await centerOf(viewer), { x: 60, y: 300 }) + const after = await offsetOf(image) + expect(after.x).toBeLessThan(before.x - 50) + expect(await viewer.isVisible()).toBe(true) + expect(await drawerOpen()).toBe(false) + + await hand.doubleTap(await centerOf(image)) + expect(await scaleOf(image)).toBe(1) + expect(await offsetOf(image)).toEqual({ x: 0, y: 0 }) +}, 60_000) diff --git a/plugins/ui/chat/images/src/web/viewer/view/dialog.ts b/plugins/ui/chat/images/src/web/viewer/view/dialog.ts index 26663e93a..7273505f1 100644 --- a/plugins/ui/chat/images/src/web/viewer/view/dialog.ts +++ b/plugins/ui/chat/images/src/web/viewer/view/dialog.ts @@ -47,7 +47,7 @@ export const viewerDialog = (kit: Kit, model: ViewerModel, draw: Draw): SheetSpe dynamicChild(model.current, index => { const shown = model.images[index] if (!shown) return null - return div({ class: 'flex min-h-0 flex-1 flex-col' }, viewerStage(shown, draw, zoom, by => go(() => model.step(by)), close)) + return div({ class: 'flex min-h-0 flex-1 flex-col' }, viewerStage({ kit, shown, draw, zoom, flip: by => go(() => model.step(by)), close })) }), many && flipButton(kit, 'left', 'Previous (←)', model.atFirst, back), many && flipButton(kit, 'right', 'Next (→)', model.atLast, next), diff --git a/plugins/ui/chat/images/src/web/viewer/view/stage.ts b/plugins/ui/chat/images/src/web/viewer/view/stage.ts index 5f04138d4..40fab49b2 100644 --- a/plugins/ui/chat/images/src/web/viewer/view/stage.ts +++ b/plugins/ui/chat/images/src/web/viewer/view/stage.ts @@ -1,57 +1,85 @@ +import type { Kit, Point, ZoomChange } from '@sand/ui-kit/contract' import type { Draw, Picture } from '../gallery' import type { Zoom } from './zoom' -import { div, event, preventThen } from '@vaakx-dev/vrui' +import { div, event } from '@vaakx-dev/vrui' const swipeDistance = 60 interface Drag { - image: HTMLElement - startX: number - startY: number - x: number - y: number + pointer: number + start: Point + last: Point } -export const viewerStage = (shown: Picture, draw: Draw, zoom: Zoom, flip: (by: number) => void, close: () => void) => { +interface StageParts { + kit: Kit + shown: Picture + draw: Draw + zoom: Zoom + flip(by: number): void + close(): void +} + +const pointOf = ({ clientX, clientY }: MouseEvent): Point => ({ x: clientX, y: clientY }) + +const swipedBy = ({ start }: Drag, end: Point) => { + const dx = end.x - start.x + const dy = end.y - start.y + if (Math.abs(dx) <= swipeDistance || Math.abs(dx) <= Math.abs(dy)) return 0 + return dx > 0 ? -1 : 1 +} + +export const viewerStage = ({ kit, shown, draw, zoom, flip, close }: StageParts) => { + let image: HTMLImageElement | undefined let drag: Drag | undefined + const zoomImage = (change: ZoomChange) => image && zoom.zoom(change, image) + const toggle = (at: Point) => image && zoom.toggle(at, image) + + const press = (pointer: PointerEvent) => { + drag = pointer.isPrimary && pointer.button === 0 ? { pointer: pointer.pointerId, start: pointOf(pointer), last: pointOf(pointer) } : undefined + if (drag) image?.setPointerCapture(pointer.pointerId) + } + + const pan = (pointer: PointerEvent) => { + if (drag?.pointer !== pointer.pointerId || !zoom.zoomed.get()) return + zoomImage({ factor: 1, from: drag.last, to: pointOf(pointer) }) + drag = { ...drag, last: pointOf(pointer) } + } + const release = (pointer: PointerEvent) => { - const dx = drag ? pointer.clientX - drag.startX : 0 - const dy = drag ? pointer.clientY - drag.startY : 0 + if (drag?.pointer !== pointer.pointerId) return + const by = swipedBy(drag, pointOf(pointer)) + drag = undefined + if (by && !zoom.zoomed.get()) flip(by) + } + + const cancel = () => { drag = undefined - if (!zoom.zoomed.get() && Math.abs(dx) > swipeDistance && Math.abs(dx) > Math.abs(dy)) flip(dx > 0 ? -1 : 1) } - const image = draw(shown, { + const picture = draw(shown, { class: ['max-h-full max-w-full touch-none select-none rounded-md object-contain', () => (zoom.zoomed.get() ? 'cursor-grab' : null)], props: { + ref: (node: HTMLImageElement) => { + image = node + }, draggable: false, style: { transform: zoom.transform }, - onDblClick: zoom.toggle, - onPointerDown: pointer => { - const target = pointer.currentTarget - if (pointer.button !== 0 || !(target instanceof HTMLElement)) return - target.setPointerCapture(pointer.pointerId) - drag = { image: target, startX: pointer.clientX, startY: pointer.clientY, x: pointer.clientX, y: pointer.clientY } - }, - onPointerMove: pointer => { - if (!drag || !zoom.zoomed.get()) return - zoom.pan(pointer.clientX - drag.x, pointer.clientY - drag.y, drag.image) - drag = { ...drag, x: pointer.clientX, y: pointer.clientY } - }, + onDblClick: (click: MouseEvent) => toggle(pointOf(click)), + onPointerDown: press, + onPointerMove: pan, onPointerUp: release, - onPointerCancel: () => { - drag = undefined - }, + onPointerCancel: cancel, }, }) return div( { - class: 'flex min-h-0 flex-1 items-center justify-center overflow-hidden px-4 pb-2 md:px-16', + class: 'flex min-h-0 flex-1 touch-none items-center justify-center overflow-hidden px-4 pb-2 md:px-16', onMouseDown: event(close, { self: true }), - onWheel: preventThen((wheel: WheelEvent) => zoom.wheel(wheel.deltaY)), + onMount: node => kit.gesture.zoomGesture(node, { zoom: zoomImage, toggle }, { wheel: 'zooms', surface: 'fixed' }), }, - image, + picture, ) } diff --git a/plugins/ui/chat/images/src/web/viewer/view/zoom.ts b/plugins/ui/chat/images/src/web/viewer/view/zoom.ts index 2a74c8cb7..860e40295 100644 --- a/plugins/ui/chat/images/src/web/viewer/view/zoom.ts +++ b/plugins/ui/chat/images/src/web/viewer/view/zoom.ts @@ -1,38 +1,63 @@ +import type { Point, ZoomChange } from '@sand/ui-kit/contract' import { derive, sig } from '@vaakx-dev/vrui' -const fit = 1 -const most = 8 -const step = 1.5 -const wheelSpeed = 500 +interface View { + scale: number + x: number + y: number +} + +const FIT = 1 +const MOST = 8 +const STEP = 1.5 +const DOUBLE_TAP_ZOOM = 2.5 + +const FITTED: View = { scale: FIT, x: 0, y: 0 } const clamp = (value: number, limit: number) => Math.min(limit, Math.max(-limit, value)) -export const zoomState = () => { - const scale = sig(fit) - const offset = sig({ x: 0, y: 0 }) - - const zoomTo = (wanted: number) => { - const next = Math.min(most, Math.max(fit, wanted)) - const kept = scale.get() > fit ? (next - fit) / (scale.get() - fit) : 0 - offset.set({ x: offset.get().x * kept, y: offset.get().y * kept }) - scale.set(next) - } +const clampScale = (scale: number) => Math.min(MOST, Math.max(FIT, scale)) - const pan = (dx: number, dy: number, image: HTMLElement) => { - const room = (scale.get() - fit) / 2 - offset.set({ x: clamp(offset.get().x + dx, image.offsetWidth * room), y: clamp(offset.get().y + dy, image.offsetHeight * room) }) - } +const restingCenter = (image: HTMLElement, { x, y }: View): Point => { + const box = image.getBoundingClientRect() + return { x: box.left + box.width / 2 - x, y: box.top + box.height / 2 - y } +} + +const inBounds = (image: HTMLElement, { scale, x, y }: View): View => { + const room = (scale - FIT) / 2 + return { scale, x: clamp(x, image.offsetWidth * room), y: clamp(y, image.offsetHeight * room) } +} + +const zoomed = (image: HTMLElement, view: View, { factor, from, to }: ZoomChange): View => { + const center = restingCenter(image, view) + const scale = clampScale(view.scale * factor) + const ratio = scale / view.scale + const x = to.x - center.x - (from.x - center.x - view.x) * ratio + const y = to.y - center.y - (from.y - center.y - view.y) * ratio + return inBounds(image, { scale, x, y }) +} + +const rescaled = (view: View, wanted: number): View => { + const scale = clampScale(wanted) + const kept = view.scale > FIT ? (scale - FIT) / (view.scale - FIT) : 0 + return { scale, x: view.x * kept, y: view.y * kept } +} + +export const zoomState = () => { + const view = sig(FITTED) + const zoomTo = (wanted: number) => view.set(rescaled(view.get(), wanted)) + const zoom = (change: ZoomChange, image: HTMLElement) => view.set(zoomed(image, view.get(), change)) + const fit = () => view.set(FITTED) return { - zoomed: derive(() => scale.get() > fit), - label: derive(() => (scale.get() === fit ? 'Fit' : `${Math.round(scale.get() * 100)}%`)), - transform: derive(() => `translate(${offset.get().x}px, ${offset.get().y}px) scale(${scale.get()})`), - zoomIn: () => zoomTo(scale.get() * step), - zoomOut: () => zoomTo(scale.get() / step), - wheel: (delta: number) => zoomTo(scale.get() * Math.exp(-delta / wheelSpeed)), - toggle: () => zoomTo(scale.get() === fit ? 2 : fit), - fit: () => zoomTo(fit), - pan, + zoomed: derive(() => view.get().scale > FIT), + label: derive(() => (view.get().scale === FIT ? 'Fit' : `${Math.round(view.get().scale * 100)}%`)), + transform: derive(() => `translate(${view.get().x}px, ${view.get().y}px) scale(${view.get().scale})`), + zoomIn: () => zoomTo(view.get().scale * STEP), + zoomOut: () => zoomTo(view.get().scale / STEP), + toggle: (at: Point, image: HTMLElement) => (view.get().scale > FIT ? fit() : zoom({ factor: DOUBLE_TAP_ZOOM, from: at, to: at }, image)), + zoom, + fit, } } diff --git a/plugins/ui/look/kit/src/gesture/index.ts b/plugins/ui/look/kit/src/gesture/index.ts index 096204467..45318928e 100644 --- a/plugins/ui/look/kit/src/gesture/index.ts +++ b/plugins/ui/look/kit/src/gesture/index.ts @@ -4,3 +4,4 @@ export { fromSystemEdge } from './edge' export { follow } from './follow' export { canScrollToward } from './scroll' export { Slide } from './slide' +export { zoomGesture, type Point, type Surface, type WheelUse, type ZoomChange, type ZoomOptions, type ZoomTarget } from './zoom' diff --git a/plugins/ui/look/kit/src/gesture/zoom.ts b/plugins/ui/look/kit/src/gesture/zoom.ts new file mode 100644 index 000000000..ba87a39eb --- /dev/null +++ b/plugins/ui/look/kit/src/gesture/zoom.ts @@ -0,0 +1,117 @@ +import { joinDisposers } from '@sand/util' +import { listen } from '@vaakx-dev/vrui' + +interface Point { + x: number + y: number +} + +interface ZoomChange { + factor: number + from: Point + to: Point +} + +interface ZoomTarget { + zoom(change: ZoomChange): void + toggle(at: Point): void +} + +type WheelUse = 'zooms' | 'scrolls' + +type Surface = 'fixed' | 'scaled' + +interface ZoomOptions { + wheel: WheelUse + surface: Surface +} + +interface Pinch { + spread: number + center: Point +} + +interface Tap { + at: Point + time: number +} + +const TAP_SLOP_PX = 10 +const DOUBLE_TAP_MS = 300 +const DOUBLE_TAP_REACH_PX = 32 +const WHEEL_SPEED = 300 +const CONTROLS = 'a[href], button, input, select, textarea, label, summary, [role=button], [contenteditable]' + +const pointOf = (touch: Touch): Point => ({ x: touch.clientX, y: touch.clientY }) + +const distance = (from: Point, to: Point) => Math.hypot(to.x - from.x, to.y - from.y) + +const pinchOf = (first: Touch, second: Touch): Pinch => ({ + spread: distance(pointOf(first), pointOf(second)), + center: { x: (first.clientX + second.clientX) / 2, y: (first.clientY + second.clientY) / 2 }, +}) + +const onControl = (target: EventTarget | null) => target instanceof Element && target.closest(CONTROLS) !== null + +const followsTap = (last: Tap | undefined, tap: Tap) => last !== undefined && tap.time - last.time <= DOUBLE_TAP_MS && distance(last.at, tap.at) <= DOUBLE_TAP_REACH_PX + +const wheelZooms = (event: WheelEvent, use: WheelUse) => use === 'zooms' || event.ctrlKey + +const zoomGesture = (node: EventTarget, target: ZoomTarget, { wheel, surface }: ZoomOptions) => { + let pinch: Pinch | undefined + let press: Tap | undefined + let lastTap: Tap | undefined + + const start = (event: TouchEvent) => { + const [first, second] = event.touches + press = first && !second && !onControl(event.target) ? { at: pointOf(first), time: event.timeStamp } : undefined + pinch = first && second ? pinchOf(first, second) : undefined + if (pinch) lastTap = undefined + } + + const move = (event: TouchEvent) => { + const [first, second] = event.touches + if (press && first && distance(press.at, pointOf(first)) > TAP_SLOP_PX) press = undefined + if (!pinch || !first || !second) return + event.preventDefault() + const next = pinchOf(first, second) + target.zoom({ factor: next.spread / pinch.spread, from: pinch.center, to: next.center }) + if (surface === 'fixed') pinch = next + } + + const end = (event: TouchEvent) => { + const tap = press && !event.touches.length ? { at: press.at, time: event.timeStamp } : undefined + press = undefined + if (event.touches.length < 2) pinch = undefined + if (!tap) return + if (!followsTap(lastTap, tap)) { + lastTap = tap + return + } + event.preventDefault() + lastTap = undefined + target.toggle(tap.at) + } + + const cancel = () => { + pinch = undefined + press = undefined + } + + const turn = (event: WheelEvent) => { + if (!wheelZooms(event, wheel)) return + event.preventDefault() + const at = { x: event.clientX, y: event.clientY } + target.zoom({ factor: Math.exp(-event.deltaY / WHEEL_SPEED), from: at, to: at }) + } + + return joinDisposers( + listen(node, 'touchstart', start, { passive: true }), + listen(node, 'touchmove', move, { passive: false }), + listen(node, 'touchend', end, { passive: false }), + listen(node, 'touchcancel', cancel), + listen(node, 'wheel', turn, { passive: false }), + ) +} + +export { zoomGesture, type Point, type Surface, type WheelUse, type ZoomChange, type ZoomOptions, type ZoomTarget } diff --git a/plugins/ui/look/kit/src/kit.ts b/plugins/ui/look/kit/src/kit.ts index a20d64963..416b19212 100644 --- a/plugins/ui/look/kit/src/kit.ts +++ b/plugins/ui/look/kit/src/kit.ts @@ -75,6 +75,7 @@ import { alongWay, direction } from './gesture/direction' import { fromSystemEdge } from './gesture/edge' import { follow } from './gesture/follow' import { canScrollToward } from './gesture/scroll' +import { zoomGesture } from './gesture/zoom' import { onPressOutside, popupTrigger, pressOpens } from './layers/outside' import { dismissible, hasOpenLayer, modal, returnFocus } from './layers/stack' import { listbox } from './listbox/model' @@ -89,7 +90,7 @@ import { topEdge } from './scroll/edge' import { firstRowBelow, keepAnchor, nearEnd, toEnd } from './scroll/end' import { followEnd } from './scroll/follow' -const gesture = { alongWay, canScrollToward, direction, editing, follow, fromSystemEdge, onSelection } +const gesture = { alongWay, canScrollToward, direction, editing, follow, fromSystemEdge, onSelection, zoomGesture } export const kit = { actionItem, diff --git a/plugins/ui/look/kit/src/sheets/viewer.ts b/plugins/ui/look/kit/src/sheets/viewer.ts index b16661566..1a0caa14d 100644 --- a/plugins/ui/look/kit/src/sheets/viewer.ts +++ b/plugins/ui/look/kit/src/sheets/viewer.ts @@ -1,5 +1,7 @@ +import { joinDisposers } from '@sand/util' import { derive, div, keys, read, resizeObserver, sig, type Child, type MaybeReactive, type Props } from '@vaakx-dev/vrui' import { iconButton, quietButton } from '../buttons/button' +import { zoomGesture, type Point, type ZoomChange } from '../gesture/zoom' import { icon } from '../icons/lucide' import { layer } from '../layer' import { modal } from '../layers/stack' @@ -49,13 +51,28 @@ export interface FitZoomOptions { type Chosen = 'start' | 'fit' | number +interface Stage { + scroller: HTMLElement + content: HTMLElement +} + const LEAST_ZOOM = 0.25 const MOST_ZOOM = 4 const ZOOM_STEP = 1.4 +const DOUBLE_TAP_ZOOM = 2 const STAGE_MARGIN = 24 const clampZoom = (level: number) => Math.min(MOST_ZOOM, Math.max(LEAST_ZOOM, level)) +const spotIn = (box: DOMRect, at: Point): Point => ({ x: (at.x - box.left) / box.width, y: (at.y - box.top) / box.height }) + +const keepSpot = ({ scroller, content }: Stage, { from, to }: ZoomChange, rescale: () => void) => { + const spot = spotIn(content.getBoundingClientRect(), from) + rescale() + const box = content.getBoundingClientRect() + scroller.scrollBy(box.left + spot.x * box.width - to.x, box.top + spot.y * box.height - to.y) +} + export const fitZoom = (size: Size, { readableLevel = LEAST_ZOOM }: FitZoomOptions = {}) => { const room = sig({ width: 0, height: 0 }) const fitted = derive(() => { @@ -78,6 +95,17 @@ export const fitZoom = (size: Size, { readableLevel = LEAST_ZOOM }: FitZoomOptio const zoomIn = () => chosen.set(clampZoom(level.get() * ZOOM_STEP)) const zoomOut = () => chosen.set(clampZoom(level.get() / ZOOM_STEP)) const fit = () => chosen.set('fit') + let stage: Stage | undefined + const zoom = (change: ZoomChange) => { + if (stage) keepSpot(stage, change, () => chosen.set(clampZoom(level.get() * change.factor))) + } + const toggle = (at: Point) => (level.get() > fitted.get() ? fit() : zoom({ factor: DOUBLE_TAP_ZOOM, from: at, to: at })) + const show = (shown: Stage) => { + stage = shown + return joinDisposers(zoomGesture(shown.scroller, { zoom, toggle }, { wheel: 'scrolls', surface: 'fixed' }), () => { + stage = undefined + }) + } return { size, room, @@ -87,22 +115,31 @@ export const fitZoom = (size: Size, { readableLevel = LEAST_ZOOM }: FitZoomOptio zoomIn, zoomOut, fit, + zoom, + toggle, + show, keys: keys({ '+': zoomIn, '=': zoomIn, '-': zoomOut, '0': fit }), } } export type FitZoom = ReturnType -export const zoomStage = (zoom: FitZoom, props: Props, ...children: Child[]) => - div( +export const zoomStage = (zoom: FitZoom, props: Props, ...children: Child[]) => { + const content = div( + { ...props, class: 'm-auto shrink-0', style: { width: `${zoom.size.width}px`, height: `${zoom.size.height}px`, zoom: () => String(zoom.level.get()) } }, + ...children, + ) + return div( { class: 'flex min-h-0 flex-1 overflow-auto', - onMount: node => { - resizeObserver(node, () => zoom.room.set({ width: node.clientWidth, height: node.clientHeight })) + onMount: scroller => { + resizeObserver(scroller, () => zoom.room.set({ width: scroller.clientWidth, height: scroller.clientHeight })) + return zoom.show({ scroller, content }) }, }, - div({ ...props, class: 'm-auto shrink-0', style: { width: `${zoom.size.width}px`, height: `${zoom.size.height}px`, zoom: () => String(zoom.level.get()) } }, ...children), + content, ) +} export const zoomControls = ({ surface, ...zoom }: ZoomView) => div(