diff --git a/apps/native/host/ios/src/bridge.rs b/apps/native/host/ios/src/bridge.rs index c32acd9e5..1d9c06ed9 100644 --- a/apps/native/host/ios/src/bridge.rs +++ b/apps/native/host/ios/src/bridge.rs @@ -375,6 +375,12 @@ fn request(mtm: MainThreadMarker, body: &NSDictionary) { } } else if let Some(path) = field("swipeBack") { crate::system::set_swipe_back(mtm, &path); + } else if let Some(on) = body + .objectForKey(ns_string!("swipePager")) + .and_then(|value| value.downcast::().ok()) + { + let on = on.as_bool(); + crate::system::set_swipe_pager(mtm, on); } else if let Some(navigation) = field("navigate") { crate::system::navigate(mtm, &navigation); } diff --git a/apps/native/host/ios/src/system.rs b/apps/native/host/ios/src/system.rs index 262d7245f..79930e657 100644 --- a/apps/native/host/ios/src/system.rs +++ b/apps/native/host/ios/src/system.rs @@ -98,6 +98,8 @@ thread_local! { const { RefCell::new(None) }; /// The swipe under the finger now. static DRAG: RefCell> = const { RefCell::new(None) }; + /// An image viewer is open: a horizontal swipe pages it (`page` replies) instead of going back. + static PAGER: Cell = const { Cell::new(false) }; } /// A swipe going back, until the page it goes to is drawn under its picture. @@ -409,7 +411,19 @@ const RELEASE: f64 = 0.32; /// on while there is one. pub fn set_swipe_back(mtm: MainThreadMarker, path: &str) { BACK.set((!path.is_empty()).then(|| path.to_string())); - let enabled = !path.is_empty(); + sync_swipe(mtm); +} + +/// While an image viewer is open, the same pan pages it either way: let go far or fast enough, +/// the runtime hears `page` (1 toward the next slide, -1 back), and nothing slides here. +pub fn set_swipe_pager(mtm: MainThreadMarker, on: bool) { + PAGER.set(on); + sync_swipe(mtm); +} + +/// The pan is on while a back chevron or a pager wants it, made the first time one does. +fn sync_swipe(mtm: MainThreadMarker) { + let enabled = BACK.with_borrow(Option::is_some) || PAGER.get(); if SWIPE.with_borrow(Option::is_none) { if !enabled { return; @@ -604,6 +618,35 @@ fn slide_off( ); } +/// A pager's swipe let go: past `PAGE_SHARE` of the width (where its flick would carry it), or +/// flicked hard, it pages; heading left is toward the next slide. +fn page_swipe(swipe: &UIPanGestureRecognizer) { + // UIGestureRecognizerState 3: ended. + let state: isize = unsafe { msg_send![swipe, state] }; + let Some(window) = window(swipe.mtm()) else { + return; + }; + if state != 3 { + return; + } + let width = window.bounds().size.width; + let moved = swipe.translationInView(Some(&window)).x; + let velocity = swipe.velocityInView(Some(&window)).x; + let projected = moved + velocity * PROJECTION; + let step = if velocity.abs() > PAGE_VELOCITY || projected.abs() > width * PAGE_SHARE { + if projected < 0.0 { 1 } else { -1 } + } else { + return; + }; + feedback(Feedback::Selection); + reply(&serde_json::json!({ "page": step })); +} + +/// A pager's swipe pages once its flick would carry it past this share of the width. +const PAGE_SHARE: CGFloat = 0.25; +/// A flick this fast (points per second) pages however short. +const PAGE_VELOCITY: CGFloat = 500.0; + /// The swipe's cover goes once the slide is at rest and the page under it drawn (or `anyway`). fn finish_return(anyway: bool) { let done = RETURNING.with_borrow(|returning| { @@ -638,6 +681,10 @@ define_class!( }; let moved = swipe.translationInView(Some(&window)); let velocity = swipe.velocityInView(Some(&window)); + if PAGER.get() { + let sideways = |x: CGFloat, y: CGFloat| x.abs() > y.abs() * 1.2; + return Bool::new(sideways(velocity.x, velocity.y) || sideways(moved.x, moved.y)); + } let rightward = |x: CGFloat, y: CGFloat| x > 0.0 && x > y.abs() * 1.2; Bool::new( !MOVING.get() @@ -652,6 +699,10 @@ define_class!( #[unsafe(method(pan:))] fn pan(&self, swipe: &UIPanGestureRecognizer) { let mtm = self.mtm(); + if PAGER.get() { + page_swipe(swipe); + return; + } let (Some(window), Some(page)) = (window(mtm), page(mtm)) else { return; }; diff --git a/apps/native/src/ios.ts b/apps/native/src/ios.ts index 7139ded14..15ad227ed 100644 --- a/apps/native/src/ios.ts +++ b/apps/native/src/ios.ts @@ -38,6 +38,8 @@ export type IosRequest = | { readonly feedback: Feedback } /** Where the edge swipe goes back to; empty turns the swipe off. */ | { readonly swipeBack: string } + /** Horizontal swipes page an image viewer (`page` replies) instead of going back. */ + | { readonly swipePager: boolean } /** The runtime followed a notification's path (`openPath`): the host stops holding it. */ | { readonly openedPath: string } /** `localStorage`'s entries to save (`host/ios/src/storage.rs`), as JSON. */ @@ -73,13 +75,17 @@ type BackReply = { readonly back: true } /** A notification's tap opens the app at this path (`host/ios/src/push.rs`). */ type OpenPathReply = { readonly openPath: string } /** What the host hands the worker that is not a line or a fetch's answer. */ -type HostReply = BackReply | PushToken | OpenPathReply +/** A horizontal swipe let go while an image viewer pages (`swipePager`): toward the next, or back. */ +type PageReply = { readonly page: -1 | 1 } +type HostReply = BackReply | PushToken | OpenPathReply | PageReply /** What waits for the runtime to start: the push token, a notification's path. */ const afterStart: Array<() => void> = [] let isRuntimeStarted = false const whenStarted = (run: () => void) => (isRuntimeStarted ? run() : afterStart.push(run)) /** Set below, once `log` exists. */ let push: ReturnType | undefined +/** The image viewers' pagers, latest last: a horizontal swipe pages the latest. */ +const pagers: Array<{ readonly onPage: (step: -1 | 1) => void }> = [] /** The back chevrons on screen, latest last: the swipe goes where the latest leads. */ const backTargets: Array<{ readonly href: string }> = [] /** A URL's path, query and hash: what the host keys its pictures of pages by. */ @@ -109,6 +115,7 @@ const openPath = (path: string) => { } const hostReply = (reply: HostReply) => { if ("back" in reply) goBack() + else if ("page" in reply) pagers.at(-1)?.onPage(reply.page) else if ("pushToken" in reply) whenStarted(() => void push?.register(reply)) else if ("openPath" in reply) whenStarted(() => openPath(reply.openPath)) } @@ -241,6 +248,16 @@ const systemUi: SystemUi = { request({ swipeBack: back === undefined ? "" : pathOf(back.href) }) } }, + setSwipePager: (onPage) => { + const pager = { onPage } + pagers.push(pager) + request({ swipePager: true }) + return () => { + const index = pagers.indexOf(pager) + if (index !== -1) pagers.splice(index, 1) + request({ swipePager: pagers.length > 0 }) + } + }, } push = makePushDevice({ config: readConfig(process.env), log }) diff --git a/apps/native/src/mounts.ts b/apps/native/src/mounts.ts index e72a40818..a44f8f393 100644 --- a/apps/native/src/mounts.ts +++ b/apps/native/src/mounts.ts @@ -33,6 +33,8 @@ export const OVERLAY_MOUNTS = [ "AnchorTooltip", // A Dialog shows itself (`Dom.showDialog`, which the render target answers) when it mounts. "AcquireResources", + // The image viewer: portalled to the window's root and modal, closed by Escape. + "ImageViewerNativeModal", ] /** @@ -47,6 +49,8 @@ export const SCRIPT_MOUNTS = [ "AutoFocusOnboardingInput", // The edge swipe a back chevron enables (`platform/system-ui.ts`). "SwipeBack", + // The image viewer's slides page with the phone's horizontal swipe. + "ImageViewerSwipePager", ] /** diff --git a/apps/native/src/runtime.ts b/apps/native/src/runtime.ts index 06b28970c..e4015bb49 100644 --- a/apps/native/src/runtime.ts +++ b/apps/native/src/runtime.ts @@ -6,6 +6,7 @@ * host answers (`desktop-bridge.ts`), the data source (`data-source.ts`), the app's modules and * stylesheet, the element bridge and render target, and last the host connection. */ +import { RENDERER_GLOBAL } from "../../web-foldkit/src/platform/renderer" import { Option } from "effect" import { makeElementBridge, makeRuneTarget, type HostToRuntime } from "@hazel/foldkit-rune" import { readConfig } from "./config" @@ -69,6 +70,8 @@ export const startRuntime = async (platform: NativePlatform) => { // Read by the web app's local cache (`core/db/local-cache-host.ts`) as its modules load. Like // `localStorage`, it is kept only with live data. globalThis.__hazelLocalCacheHost = platform.localCache?.({ persist: config.dataMode === "live" }) + // Read by the app's views that pick a shape without their DOM-only Mounts (`platform/renderer.ts`). + Object.assign(globalThis, { [RENDERER_GLOBAL]: "rune" }) /** The Tauri APIs the host answers: the keychain sign-in, and updates where it offers them. */ const desktopBridge = makeDesktopBridge({ diff --git a/apps/web-foldkit/src/chat/image-viewer.browser.test.ts b/apps/web-foldkit/src/chat/image-viewer.browser.test.ts index 5299ba3de..59adcfa2e 100644 --- a/apps/web-foldkit/src/chat/image-viewer.browser.test.ts +++ b/apps/web-foldkit/src/chat/image-viewer.browser.test.ts @@ -280,4 +280,22 @@ describe("image viewer in a real browser", () => { await userEvent.keyboard("{Escape}") await waitFor(() => viewer() === null) }) + + test("a thumbnail pressed while the track still moves lands the track on it", async () => { + await sleep(450) + await open(0) + const track = document.querySelector("[data-viewer-slides]") as HTMLElement + // A swipe toward the second slide, still in flight (a phone's momentum) when the press lands. + track.scrollTo({ left: track.clientWidth, behavior: "smooth" }) + await waitFor(() => track.scrollLeft > 0) + document.querySelector('button[aria-label="photo-3.png"]')?.click() + await waitFor(() => counter() === "3 of 3") + // The swipe runs out without taking the selection back. + await sleep(600) + expect(counter()).toBe("3 of 3") + expect(activeMedia()?.getAttribute("alt")).toBe("photo-3.png") + expect(Math.abs(track.scrollLeft - (activeSlide()?.offsetLeft ?? -1))).toBeLessThan(2) + await userEvent.keyboard("{Escape}") + await waitFor(() => viewer() === null) + }) }) diff --git a/apps/web-foldkit/src/chat/image-viewer.ts b/apps/web-foldkit/src/chat/image-viewer.ts index 5457f4e39..08e238790 100644 --- a/apps/web-foldkit/src/chat/image-viewer.ts +++ b/apps/web-foldkit/src/chat/image-viewer.ts @@ -1,4 +1,4 @@ -import { Effect, Queue, Schema, Stream } from "effect" +import { Effect, Option, Queue, Schema, Stream } from "effect" import { Mount } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" import { defineMessageUnion } from "foldkit/message" @@ -14,7 +14,9 @@ import { } from "../icons" import { avatar } from "../ui/avatar" import { ariaButton, button } from "../ui/button" -import { containFocus, portalOverlay } from "../ui/aria/overlay" +import { containFocus, isolateOverlay, portalOverlay, watchInteractOutside } from "../ui/aria/overlay" +import { isNativeRenderer } from "../platform/renderer" +import { systemUi } from "../platform/system-ui" import type { ChatAttachmentView } from "./attachments" import { embedMarkdownView } from "./embeds/embed-markdown" import { attachViewer, PART, type Viewer } from "./viewer/gestures" @@ -50,7 +52,11 @@ export interface ImageViewerInputs { readonly toAction?: (action: ImageViewerAction, image: ChatAttachmentView) => M } -const Intent = defineMessageUnion({ PressedClose: {}, PressedSelect: { index: Schema.Number } }) +const Intent = defineMessageUnion({ + PressedClose: {}, + PressedSelect: { index: Schema.Number }, + Swiped: { step: Schema.Number }, +}) type Intent = typeof Intent.Type // The selected slide as the Model has it, which the track and the thumbnails follow. @@ -74,7 +80,7 @@ const observeSelected = (element: Element, follow: (index: number) => void) => { /** The thumbnail strip (`containScroll: "keepSnaps"`, `dragFree`), kept on the selected slide. */ const ThumbCarousel = Mount.defineStream("ImageViewerThumbCarousel", { - messages: [Intent.PressedClose, Intent.PressedSelect], + messages: [Intent.PressedClose, Intent.PressedSelect, Intent.Swiped], execute: ({ element }) => Stream.callback(() => Effect.acquireRelease( @@ -156,7 +162,7 @@ const acquire = (open: () => () => void) => * keep the morph's plate on the slide on view. The gestures report a slide, or a dismissal. */ const ImageViewerMount = Mount.defineStream("ImageViewerPortal", { - messages: [Intent.PressedClose, Intent.PressedSelect], + messages: [Intent.PressedClose, Intent.PressedSelect, Intent.Swiped], execute: ({ element }) => Stream.callback((queue) => Effect.gen(function* () { @@ -224,6 +230,41 @@ const ImageViewerMount = Mount.defineStream("ImageViewerPortal", { ), }) +/** + * The viewer in the Rune-native app, which never runs the DOM Mounts above: the host portals it + * to the window's root and makes it modal, and Escape (the host's dismissal) closes it. + */ +const NativeImageViewerModal = Mount.defineStream("ImageViewerNativeModal", { + messages: [Intent.PressedClose, Intent.PressedSelect, Intent.Swiped], + execute: ({ element }) => + Stream.callback((queue) => + Effect.gen(function* () { + yield* acquire(() => portalOverlay(element)) + yield* isolateOverlay(element, "image-viewer") + yield* acquire(() => + watchInteractOutside(element, `[${VIEWER_ATTRIBUTE}]`, () => + Queue.offerUnsafe(queue, Intent.PressedClose()), + ), + ) + return yield* Effect.never + }), + ), +}) + +/** The phone shell's swipe pages the native viewer (`platform/system-ui.ts`), where it has one. */ +const NativeSwipePager = Mount.defineStream("ImageViewerSwipePager", { + messages: [Intent.PressedClose, Intent.PressedSelect, Intent.Swiped], + execute: () => + Stream.callback((queue) => + acquire( + () => + systemUi()?.setSwipePager?.((step) => + Queue.offerUnsafe(queue, Intent.Swiped({ step })), + ) ?? NO_RELEASE, + ).pipe(Effect.flatMap(() => Effect.never)), + ), +}) + const toolbarButton = ( h: HtmlBuilder, onPress: M | undefined, @@ -336,12 +377,18 @@ const slideView = ( index: number, selectedIndex: number, count: number, + isNative = false, ): Html => { const isActive = index === selectedIndex return h.keyed("div")( image.id, [ - h.Class("relative box-border flex h-full min-w-full flex-[0_0_100%] flex-col items-center"), + h.Class( + // One slide at a time in Rune, which sizes no `flex-basis: 100%`: pinned to the edges. + isNative + ? "absolute inset-0 box-border flex flex-col items-center" + : "relative box-border flex h-full min-w-full flex-[0_0_100%] flex-col items-center", + ), h.DataAttribute("viewer-slide", ""), h.Role("group"), h.AriaRoleDescription("slide"), @@ -353,7 +400,11 @@ const slideView = ( : [ h.div( [ - h.Class("flex min-h-0 w-full flex-1 items-center justify-center"), + h.Class( + isNative + ? "relative min-h-0 w-full flex-1" + : "flex min-h-0 w-full flex-1 items-center justify-center", + ), h.DataAttribute("viewer-zoom", ""), ], [ @@ -366,7 +417,11 @@ const slideView = ( h.DataAttribute("viewer-media", ""), ...(isActive ? [h.DataAttribute("active", "")] : []), h.Class( - "block h-auto max-h-full w-auto min-w-0 max-w-full select-none rounded-md object-contain", + // Rune does not shrink an auto-sized picture to its box: there it + // fills its box and fits inside it. + isNative + ? "block size-full select-none object-contain" + : "block h-auto max-h-full w-auto min-w-0 max-w-full select-none rounded-md object-contain", ), ]), ], @@ -387,18 +442,31 @@ export const imageViewerView = (h: HtmlBuilder, inputs: ImageViewerInputs< const selectedIndex = Math.min(Math.max(inputs.index, 0), Math.max(images.length - 1, 0)) const current = images[selectedIndex] const hasMany = images.length > 1 + // Rune runs none of the DOM gestures: one slide at a time, chosen by the Model alone. + const isNative = isNativeRenderer() + const select = (index: number) => + inputs.toSelect(Math.min(Math.max(index, 0), Math.max(images.length - 1, 0))) const act = (action: ImageViewerAction) => inputs.toAction && current ? inputs.toAction(action, current) : undefined const actions: ReadonlyArray = [ - [undefined, "Zoom out", IconMinus(h, { className: "size-4" }), "out"], - [undefined, "Zoom in", IconPlus(h, { className: "size-4" }), "in"], + // Zoom is the gestures' to do, which Rune does not run. + ...(isNative + ? [] + : ([ + [undefined, "Zoom out", IconMinus(h, { className: "size-4" }), "out"], + [undefined, "Zoom in", IconPlus(h, { className: "size-4" }), "in"], + ] as const)), [act("download"), "Download", IconDownload(h, { className: "size-4" })], [act("copyUrl"), "Copy image URL", IconCopy(h, { className: "size-4" })], [act("openInBrowser"), "Open in browser", IconExternalLink(h, { className: "size-4" })], [inputs.toClose(), "Close", IconClose(h, { className: "size-4" })], ] const toMessage = (intent: Intent) => - intent._tag === "PressedClose" ? inputs.toClose() : inputs.toSelect(intent.index) + Intent.match(intent, { + PressedClose: () => inputs.toClose(), + PressedSelect: ({ index }) => select(index), + Swiped: ({ step }) => select(selectedIndex + step), + }) return h.div( [ h.Class("fixed inset-0 isolate z-9999"), @@ -406,12 +474,14 @@ export const imageViewerView = (h: HtmlBuilder, inputs: ImageViewerInputs< // Legacy renders the viewer through a React portal inside the message list, so React's // pointerleave never sees the pointer leave the list for it. Hover tracking reads this. h.DataAttribute(LIST_PORTAL_ATTRIBUTE, ""), - h.OnMount(Mount.mapMessage(ImageViewerMount(), toMessage)), + h.OnMount(Mount.mapMessage(isNative ? NativeImageViewerModal() : ImageViewerMount(), toMessage)), ], [ h.div([ h.Class("absolute inset-0 bg-black/90"), - h.DataAttribute("viewer-backdrop", ""), + // Thinned by a pull (`--viewer-pull-progress`), which only the browser's gestures make; + // Rune draws the backdrop as it is. + ...(isNative ? [] : [h.DataAttribute("viewer-backdrop", "")]), h.AriaHidden(true), ]), h.div( @@ -422,21 +492,55 @@ export const imageViewerView = (h: HtmlBuilder, inputs: ImageViewerInputs< h.AriaModal(true), h.AriaLabel(hasMany ? "Image gallery" : "Image viewer"), h.Tabindex(-1), + ...(isNative + ? [ + h.OnKeyDownPreventDefault((key) => + key === "ArrowLeft" || key === "ArrowUp" + ? Option.some(select(selectedIndex - 1)) + : key === "ArrowRight" || key === "ArrowDown" + ? Option.some(select(selectedIndex + 1)) + : key === "Home" + ? Option.some(select(0)) + : key === "End" + ? Option.some(select(images.length - 1)) + : Option.none(), + ), + ] + : []), ], [ h.div( [ h.Class("relative flex h-full w-full"), - h.DataAttribute("viewer-slides", ""), + // The scroll-snap track is the browser's; in Rune it would be a bare + // scroller the Model cannot move, so there only the open slide is drawn. + ...(isNative ? [] : [h.DataAttribute("viewer-slides", "")]), h.Attribute(SELECTED_ATTRIBUTE, String(selectedIndex)), h.Role("group"), h.AriaRoleDescription("carousel"), h.AriaLabel("Images"), ], - images.map((image, index) => - slideView(h, image, index, selectedIndex, images.length), - ), + isNative + ? current === undefined + ? [] + : [slideView(h, current, selectedIndex, selectedIndex, images.length, true)] + : images.map((image, index) => + slideView(h, image, index, selectedIndex, images.length), + ), ), + ...(isNative && hasMany && systemUi()?.setSwipePager !== undefined + ? [ + // Remounted on every slide, so a swipe steps from the slide on view. + h.keyed("span")( + `swipe:${selectedIndex}`, + [ + h.Class("hidden"), + h.OnMount(Mount.mapMessage(NativeSwipePager(), toMessage)), + ], + [], + ), + ] + : []), h.div( [h.Class("sr-only"), h.AriaLive("polite"), h.AriaAtomic(true)], [announcement(current, selectedIndex, images.length)], @@ -475,26 +579,47 @@ export const imageViewerView = (h: HtmlBuilder, inputs: ImageViewerInputs< : []), ...(hasMany ? [ - h.div( - [ - h.Class( - "absolute top-5 left-1/2 -translate-x-1/2 rounded-md bg-black/50 px-3 py-1.5 text-sm text-white tabular-nums max-md:top-[calc(env(safe-area-inset-top)+4rem)] max-md:right-3 max-md:left-auto max-md:translate-x-0", + isNative + ? // Rune keeps `left-1/2 -translate-x-1/2` centred at every width, so + // on a phone the counter would sit on the author: a row places it. + h.div( + [ + h.Class( + "pointer-events-none absolute inset-x-0 top-5 flex justify-center max-md:top-[calc(env(safe-area-inset-top)+4rem)] max-md:justify-end max-md:px-3", + ), + h.DataAttribute("viewer-chrome", ""), + h.AriaHidden(true), + ], + [ + h.div( + [ + h.Class( + "rounded-md bg-black/50 px-3 py-1.5 text-sm text-white tabular-nums", + ), + ], + [ + String(selectedIndex + 1), + " of ", + String(images.length), + ], + ), + ], + ) + : h.div( + [ + h.Class( + "absolute top-5 left-1/2 -translate-x-1/2 rounded-md bg-black/50 px-3 py-1.5 text-sm text-white tabular-nums max-md:top-[calc(env(safe-area-inset-top)+4rem)] max-md:right-3 max-md:left-auto max-md:translate-x-0", + ), + h.DataAttribute("viewer-chrome", ""), + h.AriaHidden(true), + ], + [String(selectedIndex + 1), " of ", String(images.length)], ), - h.DataAttribute("viewer-chrome", ""), - h.AriaHidden(true), - ], - [String(selectedIndex + 1), " of ", String(images.length)], - ), - navButton( - h, - "left", - inputs.toSelect(Math.max(selectedIndex - 1, 0)), - selectedIndex === 0, - ), + navButton(h, "left", select(selectedIndex - 1), selectedIndex === 0), navButton( h, "right", - inputs.toSelect(Math.min(selectedIndex + 1, images.length - 1)), + select(selectedIndex + 1), selectedIndex === images.length - 1, ), ] @@ -523,15 +648,26 @@ export const imageViewerView = (h: HtmlBuilder, inputs: ImageViewerInputs< [ h.div( [ + // Embla drags the strip in a browser; Rune scrolls a + // plain row sideways itself. h.Class( - "pointer-events-auto max-w-2xl overflow-hidden rounded-md", + isNative + ? "pointer-events-auto flex max-w-2xl overflow-x-auto rounded-md" + : "pointer-events-auto max-w-2xl overflow-hidden rounded-md", ), h.Attribute(SELECTED_ATTRIBUTE, String(selectedIndex)), - h.OnMount(Mount.mapMessage(ThumbCarousel(), toMessage)), + ...(isNative + ? [] + : [ + h.OnMount( + Mount.mapMessage(ThumbCarousel(), toMessage), + ), + ]), ], [ h.div( - [h.Class("flex gap-2")], + // Centred in Rune's scroller, which is as wide as it may be. + [h.Class(isNative ? "mx-auto flex gap-2" : "flex gap-2")], images.map((image, index) => thumbView( h, diff --git a/apps/web-foldkit/src/chat/viewer/gestures.ts b/apps/web-foldkit/src/chat/viewer/gestures.ts index bf37df950..9a1581704 100644 --- a/apps/web-foldkit/src/chat/viewer/gestures.ts +++ b/apps/web-foldkit/src/chat/viewer/gestures.ts @@ -32,7 +32,7 @@ export type ViewerEvent = | Readonly<{ _tag: "Dismiss" }> export type Viewer = Readonly<{ - /** Jumps to a slide. Dropped while a swipe is still in flight. */ + /** Jumps to a slide; asked mid-swipe, once the track has stopped. */ goTo: (index: number) => void zoomBy: (step: "in" | "out" | "reset") => void /** Moves the view over a zoomed shot by this many pixels. */ @@ -113,6 +113,8 @@ export const attachViewer = (content: HTMLElement, emit: (event: ViewerEvent) => let isScrolling = false let isJumping = false + /** A slide asked for while the track was still moving: it is jumped to once the track stops. */ + let pending: number | null = null let scrollIdle = 0 let scrollFrame = 0 @@ -149,6 +151,8 @@ export const attachViewer = (content: HTMLElement, emit: (event: ViewerEvent) => } const syncActive = () => { + // The slide asked for mid-swipe stays selected while the swipe runs out under it. + if (pending !== null) return const index = M.slideAt(offsets(), track.scrollLeft) if (index !== active) activate(index) } @@ -158,6 +162,14 @@ export const attachViewer = (content: HTMLElement, emit: (event: ViewerEvent) => isScrolling = false // Anything measured while the slide was still travelling is off by the distance it had left. frame = null + const asked = pending + pending = null + // A thumbnail or arrow pressed mid-swipe wins over where the swipe ended, or the track + // would rest on one slide while the counter and the thumbnails show another. + if (asked !== null && jump(asked)) { + if (asked !== active) activate(asked) + return + } syncActive() } @@ -561,6 +573,19 @@ export const attachViewer = (content: HTMLElement, emit: (event: ViewerEvent) => else glide(M.clampPose(measured, pose), SETTLE_MS, SETTLE) } + // Safari and Chrome on Android start their own scroll or pinch from a touch that `touch-action` + // should have left to us (a second finger landing on a horizontal pan, a pull starting on an + // edge): once a gesture is ours, the touch's default is cancelled so the browser lets it be. + listen( + track, + "touchmove", + (event) => { + if (event.touches.length >= 2 || mode === "pull" || mode === "pan" || mode === "pinch") + event.preventDefault() + }, + { passive: false }, + ) + listen(track, "pointerup", (event) => release(event, false)) listen(track, "pointercancel", (event) => release(event, true)) @@ -648,7 +673,10 @@ export const attachViewer = (content: HTMLElement, emit: (event: ViewerEvent) => if (typeof ResizeObserver === "function") { const observer = new ResizeObserver(() => { - jump(active) + // A phone's toolbar showing or hiding resizes the viewer mid-swipe: jumping then would + // yank the slide back under the finger, so the jump waits for the track to stop. + if (isScrolling) pending ??= active + else jump(active) remeasure() }) observer.observe(track) @@ -663,7 +691,11 @@ export const attachViewer = (content: HTMLElement, emit: (event: ViewerEvent) => const viewer: Viewer = { goTo: (index) => { - if (isScrolling || !jump(index)) return + if (isScrolling) { + pending = index + return + } + if (!jump(index)) return if (index !== active) activate(index) }, zoomBy: (step) => { diff --git a/apps/web-foldkit/src/chat/viewer/image-viewer.css b/apps/web-foldkit/src/chat/viewer/image-viewer.css index 0d92a77ad..5e05147b8 100644 --- a/apps/web-foldkit/src/chat/viewer/image-viewer.css +++ b/apps/web-foldkit/src/chat/viewer/image-viewer.css @@ -181,8 +181,15 @@ visibility 0s linear 200ms; } -/* A finger swipes; the step buttons are for a pointer. */ -@media (hover: none), (max-width: 767px) { +/* A finger swipes; the step buttons are for a pointer. Two rules, not one query list: the native + app's resolver (`@hazel/foldkit-rune`) reads only single queries. */ +@media (hover: none) { + [data-viewer-step] { + display: none; + } +} + +@media (max-width: 767px) { [data-viewer-step] { display: none; } diff --git a/apps/web-foldkit/src/page/chat/overlay-views.ts b/apps/web-foldkit/src/page/chat/overlay-views.ts index 0755460ae..2205c3cc3 100644 --- a/apps/web-foldkit/src/page/chat/overlay-views.ts +++ b/apps/web-foldkit/src/page/chat/overlay-views.ts @@ -60,6 +60,9 @@ export const trackHoverAttribute = (h: H) => /** `MessageToolbar` in its body portal, for the hovered message. */ export const messageToolbarOverlay = (h: H, model: Model): Html => { const overlays = model.overlays + // The image viewer covers the list: its toolbar would otherwise stay on the image's message + // (Rune draws the portalled toolbar over the viewer, and the pointer never left the message). + if (Overlays.imageViewerOf(overlays) !== null) return h.empty const messageId = Overlays.hoveredMessageIdOf(overlays) const row = messageId === null ? undefined : model.rows.find((candidate) => candidate.key === messageId) if (messageId === null || row === undefined || row._tag !== "MessageRow") return h.empty diff --git a/apps/web-foldkit/src/platform/renderer.ts b/apps/web-foldkit/src/platform/renderer.ts new file mode 100644 index 000000000..d24914e2b --- /dev/null +++ b/apps/web-foldkit/src/platform/renderer.ts @@ -0,0 +1,13 @@ +/** + * Which renderer draws the app. The browser runs the DOM; the Rune-native app (`apps/native`) + * draws the same views itself and runs only the Mounts it lists (`apps/native/src/mounts.ts`), so + * a view whose behaviour lives in a DOM-only Mount picks a shape that works without it. The native + * runtime sets the global before the app's modules load. + */ + +export const RENDERER_GLOBAL = "__HAZEL_RENDERER__" + +type RendererGlobal = typeof globalThis & { [RENDERER_GLOBAL]?: "rune" } + +/** Whether Rune draws the app (the native Mac and iOS apps), not a browser. */ +export const isNativeRenderer = (): boolean => (globalThis as RendererGlobal)[RENDERER_GLOBAL] === "rune" diff --git a/apps/web-foldkit/src/platform/system-ui.ts b/apps/web-foldkit/src/platform/system-ui.ts index e16b0ded6..47daf3dc3 100644 --- a/apps/web-foldkit/src/platform/system-ui.ts +++ b/apps/web-foldkit/src/platform/system-ui.ts @@ -13,6 +13,11 @@ export type SystemUi = Readonly<{ feedback: (kind: Feedback) => void /** From now on the edge swipe goes to `href`, until the function this returns runs. */ setSwipeBack: (href: string) => () => void + /** + * From now on a horizontal swipe pages (`onPage(1)` toward the next, `-1` the previous) instead + * of going back, until the function this returns runs. An image viewer's slides. + */ + setSwipePager?: (onPage: (step: -1 | 1) => void) => () => void }> /** The global a shell installs its controls as. */