Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/native/host/ios/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,12 @@ fn request(mtm: MainThreadMarker, body: &NSDictionary<NSString, AnyObject>) {
}
} 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::<NSNumber>().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);
}
Expand Down
53 changes: 52 additions & 1 deletion apps/native/host/ios/src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ thread_local! {
const { RefCell::new(None) };
/// The swipe under the finger now.
static DRAG: RefCell<Option<Drag>> = const { RefCell::new(None) };
/// An image viewer is open: a horizontal swipe pages it (`page` replies) instead of going back.
static PAGER: Cell<bool> = const { Cell::new(false) };
}

/// A swipe going back, until the page it goes to is drawn under its picture.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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| {
Expand Down Expand Up @@ -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()
Expand All @@ -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;
};
Expand Down
19 changes: 18 additions & 1 deletion apps/native/src/ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<typeof makePushDevice> | 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. */
Expand Down Expand Up @@ -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))
}
Expand Down Expand Up @@ -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 })
Expand Down
4 changes: 4 additions & 0 deletions apps/native/src/mounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]

/**
Expand All @@ -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",
]

/**
Expand Down
3 changes: 3 additions & 0 deletions apps/native/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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({
Expand Down
18 changes: 18 additions & 0 deletions apps/web-foldkit/src/chat/image-viewer.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>("[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<HTMLElement>('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)
})
})
Loading
Loading