diff --git a/apps/native/README.md b/apps/native/README.md index be7e36c4e..4bdd0db99 100644 --- a/apps/native/README.md +++ b/apps/native/README.md @@ -167,6 +167,13 @@ to the right from anywhere on the page (as in Slack) does that under the finger, finishes at the finger's speed, the runtime drawing where it goes while the page slides off. A press on the tab bar never waits on a picture: the bar and the page stay live while the tab draws. +**Haptics** (`web-foldkit/src/platform/feedback.ts`, `host/src/feedback.rs`). Components own +them, never features: a Switch, Checkbox, Radio, ChoiceBox or tab marks its pressed element +`data-native-feedback="selection"`, and the host plays it as the finger lifts, before the press +reaches the runtime; a success, warning or error toast plays its outcome through the bridge +(`{ feedback }`). `NATIVE_DEBUG=1` logs each one (`[host] haptic Selection`), since the +simulator plays none. + **Live data** (`HAZEL_DATA=live bun run ios`, with `VITE_APP_URL`/`VITE_BACKEND_URL` for a dev stack on this Mac, and `HAZEL_SESSION_TOKEN` from `dev:sign-in` for a PR preview, which has no OAuth) signs in as the Mac app does: the sign-in link opens in the system's sign-in diff --git a/apps/native/host/ios/src/bridge.rs b/apps/native/host/ios/src/bridge.rs index f65ef6369..c32acd9e5 100644 --- a/apps/native/host/ios/src/bridge.rs +++ b/apps/native/host/ios/src/bridge.rs @@ -111,7 +111,7 @@ pub fn environment(name: &str) -> Option { } /// Whether a debug setting is on; read once. -fn environment_flag(name: &'static str) -> bool { +pub fn environment_flag(name: &'static str) -> bool { thread_local! { static FLAGS: RefCell> = RefCell::new(HashMap::new()); } @@ -368,8 +368,11 @@ fn request(mtm: MainThreadMarker, body: &NSDictionary) { STORAGE.set(Some(entries)); } else if let Some(text) = field("copy") { unsafe { UIPasteboard::generalPasteboard().setString(Some(&NSString::from_str(&text))) }; - } else if body.objectForKey(ns_string!("haptic")).is_some() { - crate::system::haptic(mtm); + } else if let Some(kind) = field("feedback") { + match hazel_native::feedback::Feedback::parse(&kind) { + Some(kind) => hazel_native::feedback::play(kind), + None => log(&format!("[host] no haptic is called {kind}")), + } } else if let Some(path) = field("swipeBack") { crate::system::set_swipe_back(mtm, &path); } else if let Some(navigation) = field("navigate") { diff --git a/apps/native/host/ios/src/main.rs b/apps/native/host/ios/src/main.rs index 3c05615d2..11463888b 100644 --- a/apps/native/host/ios/src/main.rs +++ b/apps/native/host/ios/src/main.rs @@ -49,6 +49,8 @@ fn main() { // The UIKit views the app's `data-native` elements get, and HTML renders' web views, go // where their boxes were drawn, after every frame. islands::install(); + // Presses marked `data-native-feedback`, and outcomes the runtime asks for, play UIKit haptics. + hazel_native::feedback::set_player(system::feedback); // Before the app runs, as Apple asks: a tap on a notification that launches it is heard. if let Some(mtm) = objc2::MainThreadMarker::new() { push::install(mtm); diff --git a/apps/native/host/ios/src/system.rs b/apps/native/host/ios/src/system.rs index 7fd314195..262d7245f 100644 --- a/apps/native/host/ios/src/system.rs +++ b/apps/native/host/ios/src/system.rs @@ -1,5 +1,5 @@ -//! The phone's own controls the app asks for (`web-foldkit/src/platform/system-ui.ts`): a tap of -//! the finger, and navigation that moves as a navigation stack's does. +//! The phone's own controls the app asks for (`web-foldkit/src/platform/system-ui.ts`): haptics, +//! and navigation that moves as a navigation stack's does. //! //! Rune draws the whole page in one view, so the page left behind is gone once the next is //! drawn. The runtime says before every in-app navigation where it goes (`navigate`), and the @@ -17,6 +17,7 @@ use std::time::{Duration, Instant}; use block2::RcBlock; use dispatch2::{DispatchQueue, DispatchTime}; +use hazel_native::feedback::Feedback; use objc2::rc::Retained; use objc2::runtime::{Bool, ProtocolObject}; use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; @@ -24,22 +25,45 @@ use objc2_core_foundation::{CGAffineTransform, CGFloat, CGSize}; use objc2_foundation::{NSObject, NSObjectProtocol}; use objc2_ui_kit::{ UIBezierPath, UIColor, UIGestureRecognizer, UIGestureRecognizerDelegate, - UIImpactFeedbackGenerator, UIImpactFeedbackStyle, UIPanGestureRecognizer, UIView, + UIImpactFeedbackGenerator, UIImpactFeedbackStyle, UINotificationFeedbackGenerator, + UINotificationFeedbackType, UIPanGestureRecognizer, UISelectionFeedbackGenerator, UIView, UIViewAnimationOptions, }; use serde_json::Value; use crate::bridge::{log, reply, window}; -/// A tap of the finger, as a long-press's menu gives. -pub fn haptic(mtm: MainThreadMarker) { - // `feedbackGeneratorWithStyle:forView:` replaces it from iOS 17.5; the app runs on 17.0. +/// Plays a haptic (`hazel_native::feedback`): a press's, or an outcome the runtime asks for. +/// `NATIVE_DEBUG=1` logs each, since the simulator plays none. +pub fn feedback(kind: Feedback) { + let Some(mtm) = MainThreadMarker::new() else { + return; + }; + if crate::bridge::environment_flag("NATIVE_DEBUG") { + log(&format!("[host] haptic {kind:?}")); + } + // The generators' `…forView:` constructors replace these from iOS 17.5; the app runs on 17.0. #[allow(deprecated)] - let generator = UIImpactFeedbackGenerator::initWithStyle( - UIImpactFeedbackGenerator::alloc(mtm), - UIImpactFeedbackStyle::Medium, - ); - generator.impactOccurred(); + match kind { + Feedback::Selection => { + UISelectionFeedbackGenerator::init(UISelectionFeedbackGenerator::alloc(mtm)) + .selectionChanged() + } + Feedback::Impact => UIImpactFeedbackGenerator::initWithStyle( + UIImpactFeedbackGenerator::alloc(mtm), + UIImpactFeedbackStyle::Medium, + ) + .impactOccurred(), + Feedback::Success | Feedback::Warning | Feedback::Error => { + let generator = + UINotificationFeedbackGenerator::init(UINotificationFeedbackGenerator::alloc(mtm)); + generator.notificationOccurred(match kind { + Feedback::Success => UINotificationFeedbackType::Success, + Feedback::Warning => UINotificationFeedbackType::Warning, + _ => UINotificationFeedbackType::Error, + }); + } + } } // PICTURES OF PAGES diff --git a/apps/native/host/src/feedback.rs b/apps/native/host/src/feedback.rs new file mode 100644 index 000000000..ea627ec2d --- /dev/null +++ b/apps/native/host/src/feedback.rs @@ -0,0 +1,52 @@ +//! Haptic feedback (`web-foldkit/src/platform/feedback.ts`). A component marks the element whose +//! press means something (`data-native-feedback`); the press plays it here, as the finger lifts, +//! before the event reaches the runtime. Outcomes (a toast's kind) come from the runtime instead. +//! A shell with haptics installs the player (`set_player`); without one nothing plays. +use std::collections::HashMap; +use std::sync::OnceLock; + +/// The attribute a component puts on the pressed element. +pub const ATTR: &str = "data-native-feedback"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Feedback { + /// A discrete value changed. + Selection, + /// A deliberate commit with weight. + Impact, + Success, + Warning, + Error, +} + +impl Feedback { + pub fn parse(name: &str) -> Option { + match name { + "selection" => Some(Self::Selection), + "impact" => Some(Self::Impact), + "success" => Some(Self::Success), + "warning" => Some(Self::Warning), + "error" => Some(Self::Error), + _ => None, + } + } +} + +static PLAYER: OnceLock = OnceLock::new(); + +/// Installs the shell's haptics; called once, on the main thread's side of the shell. +pub fn set_player(play: fn(Feedback)) { + let _ = PLAYER.set(play); +} + +/// Plays `kind`, where the shell has haptics. +pub fn play(kind: Feedback) { + if let Some(play) = PLAYER.get() { + play(kind); + } +} + +/// What a press on the element plays: its `data-native-feedback`, if it names a kind. +pub fn of(attrs: &HashMap) -> Option { + attrs.get(ATTR).and_then(|name| Feedback::parse(name)) +} diff --git a/apps/native/host/src/lib.rs b/apps/native/host/src/lib.rs index 27c1ed8de..0a4c84415 100644 --- a/apps/native/host/src/lib.rs +++ b/apps/native/host/src/lib.rs @@ -1,6 +1,7 @@ //! Hazel's Foldkit app drawn with Rune: the runtime's wire tree as Rune elements, and the events, //! layout and edits sent back to it. A shell (the macOS app in `main.rs`) runs the runtime and //! installs where the messages go (`outbox::set_writer`). +pub mod feedback; pub mod fetch; pub mod frames; pub mod fx; diff --git a/apps/native/host/src/render/handlers.rs b/apps/native/host/src/render/handlers.rs index f71494e2f..b0abb79d1 100644 --- a/apps/native/host/src/render/handlers.rs +++ b/apps/native/host/src/render/handlers.rs @@ -6,6 +6,7 @@ use std::collections::HashMap; use rune::{Cursor, El}; use serde_json::json; +use crate::feedback::{self, Feedback}; use crate::html::{focusable, is_checkable, script_focusable}; use crate::layout::focus_styles; use crate::outbox::{write_line, write_text}; @@ -17,8 +18,14 @@ use super::state::State; /// A press as the browser reports it, for the handlers the element has. Rune reports a press /// when it is released, so all of them go then (a menu opens on release, not on press). A link's -/// click carries its `href`, which the runtime follows unless the handler prevents it. -pub(super) fn press_handlers(e: El, on: &HashMap, href: Option<&String>) -> El { +/// click carries its `href`, which the runtime follows unless the handler prevents it. `feedback` +/// plays first, so the finger feels it before the runtime has seen the press. +pub(super) fn press_handlers( + e: El, + on: &HashMap, + href: Option<&String>, + feedback: Option, +) -> El { let events: Vec<(&'static str, u32)> = PRESS_EVENTS .iter() .filter_map(|kind| on.get(*kind).map(|&id| (*kind, id))) @@ -28,6 +35,9 @@ pub(super) fn press_handlers(e: El, on: &HashMap, href: Option<&Str } let href = href.cloned(); e.cursor(Cursor::Pointer).on_press(move |_: &mut State| { + if let Some(kind) = feedback { + feedback::play(kind); + } for (kind, id) in &events { match (&href, *kind) { (Some(href), "click") => send_click(*id, href), @@ -50,6 +60,7 @@ pub(super) fn presses( if ctx.no_pointer { return e; } + let feedback = feedback::of(attrs); // A press or Space on a checkbox toggles it, and on an unchecked radio checks it: `change`. if is_checkable(tag, attrs) && let Some(&change) = on.get("change") @@ -58,6 +69,9 @@ pub(super) fn presses( attrs.get("type").is_some_and(|t| t == "checkbox") || !attrs.contains_key("checked"); let click = on.get("click").copied(); return e.cursor(Cursor::Pointer).on_press(move |_: &mut State| { + if let Some(kind) = feedback { + feedback::play(kind); + } if let Some(id) = click { send(id, "click", None); } @@ -67,7 +81,7 @@ pub(super) fn presses( }); } if PRESS_EVENTS.iter().any(|k| on.contains_key(*k)) { - return press_handlers(e, on, link_href(tag, attrs)); + return press_handlers(e, on, link_href(tag, attrs), feedback); } if let Some(href) = link_href(tag, attrs) { let href = href.clone(); diff --git a/apps/native/host/src/render/media.rs b/apps/native/host/src/render/media.rs index 21a2b6bae..5bd6242ff 100644 --- a/apps/native/host/src/render/media.rs +++ b/apps/native/host/src/render/media.rs @@ -137,7 +137,7 @@ pub(super) fn build_img( _ => e.pixels(image.pixels()), }; } - press_handlers(apply_box(e, st), on, None) + press_handlers(apply_box(e, st), on, None, None) } /// The box of an `` that sets neither its width nor its height (`w-auto h-auto`, a chat diff --git a/apps/native/host/src/tests.rs b/apps/native/host/src/tests.rs index 760518972..ef136c946 100644 --- a/apps/native/host/src/tests.rs +++ b/apps/native/host/src/tests.rs @@ -3651,3 +3651,39 @@ fn pre_code_with_token_spans_breaks_at_its_newlines() { "boot starts its own line: {first:?} {boot:?}" ); } + +#[test] +fn a_press_plays_its_elements_haptic_before_the_runtime_hears_it() { + use crate::feedback::{self, Feedback}; + static PLAYED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + feedback::set_player(|kind| PLAYED.lock().unwrap().push(kind)); + sent_events(0); + let mut marked = with_attrs( + e( + "label", + json!({ "display": "block", "h": 20 }), + vec![t("Mute")], + ), + json!({ "data-native-feedback": "selection" }), + ); + marked["on"] = json!({ "click": 981 }); + let mut plain = e("button", json!({ "display": "block", "h": 20 }), vec![]); + plain["on"] = json!({ "click": 982 }); + let mut rt = runtime( + e("div", json!({ "flex": "col" }), vec![marked, plain]), + (200.0, 100.0), + ); + for y in [10.0, 30.0] { + rt.pointer_move(5.0, y); + rt.pointer_down(5.0, y); + rt.pointer_up(5.0, y); + rt.frame(0.1); + } + assert_eq!( + *PLAYED.lock().unwrap(), + [Feedback::Selection], + "only the marked press plays" + ); + assert_eq!(sent_events(981).len(), 1, "the marked press still clicks"); + assert_eq!(sent_events(982).len(), 1); +} diff --git a/apps/native/src/ios.ts b/apps/native/src/ios.ts index a6297dc42..7139ded14 100644 --- a/apps/native/src/ios.ts +++ b/apps/native/src/ios.ts @@ -6,6 +6,7 @@ import { nativeClient, nativeHeaders } from "@hazel/auth/contract" import type { PrecompiledStyles } from "@hazel/foldkit-rune" import { parseHostLine } from "@hazel/foldkit-rune" +import type { Feedback } from "../../web-foldkit/src/platform/feedback" import { PUSH_DEVICE_GLOBAL, type PushDevice } from "../../web-foldkit/src/platform/push-device" import { SYSTEM_UI_GLOBAL, type SystemUi } from "../../web-foldkit/src/platform/system-ui" import { readConfig } from "./config" @@ -33,8 +34,8 @@ export type IosRequest = * the host takes a picture of the page it leaves. `back`: to where the back chevron leads. */ | { readonly navigate: string } - /** A tap of the finger (`host/ios/src/system.rs`). */ - | { readonly haptic: true } + /** A haptic of this kind (`host/ios/src/system.rs`, `web-foldkit/src/platform/feedback.ts`). */ + | { readonly feedback: Feedback } /** Where the edge swipe goes back to; empty turns the swipe off. */ | { readonly swipeBack: string } /** The runtime followed a notification's path (`openPath`): the host stops holding it. */ @@ -228,7 +229,7 @@ const platform: NativePlatform = { } const systemUi: SystemUi = { - haptic: () => request({ haptic: true }), + feedback: (kind) => request({ feedback: kind }), setSwipeBack: (href) => { const target = { href } backTargets.push(target) diff --git a/apps/web-foldkit/src/app/modal-host.scene.test.ts b/apps/web-foldkit/src/app/modal-host.scene.test.ts index 679bacb43..1c9aa5b2d 100644 --- a/apps/web-foldkit/src/app/modal-host.scene.test.ts +++ b/apps/web-foldkit/src/app/modal-host.scene.test.ts @@ -19,7 +19,7 @@ import * as CreateSection from "../overlay/modal/create-section" import { orgSwitcherEntries, userMenuEntries } from "../shell/menus" import * as Shell from "../shell/model" import { ada, after, hazelOrg, rootScene, signedIn } from "../test/root-fixtures" -import { drainToast } from "../test/toast-fixtures" +import { drainToast, playToastFeedback } from "../test/toast-fixtures" import * as Menu from "../ui/menu" import { FocusTriggerOnPress } from "../ui/menu-view" import * as Modal from "../ui/modal" @@ -75,6 +75,7 @@ describe("modal host", () => { sceneExpect(dialog).toBeAbsent(), Mount.expectEnded(Modal.AcquireResources), sceneExpect(text("Section created successfully")).toExist(), + playToastFeedback, ...drainToast(), ) }) @@ -94,6 +95,7 @@ describe("modal host", () => { sceneExpect(dialog).toExist(), sceneExpect(role("button", { name: "Create section" })).toBeEnabled(), sceneExpect(text("Could not create the section")).toExist(), + playToastFeedback, ...drainToast(), ) }) diff --git a/apps/web-foldkit/src/app/out-messages.story.test.ts b/apps/web-foldkit/src/app/out-messages.story.test.ts index f69e1ae3f..899ad0a06 100644 --- a/apps/web-foldkit/src/app/out-messages.story.test.ts +++ b/apps/web-foldkit/src/app/out-messages.story.test.ts @@ -6,6 +6,7 @@ import { Command, given, message, model, story } from "foldkit/story" import { describe, expect, test } from "vitest" import { update } from "../main" import * as CommandPalette from "../overlay/command-palette" +import * as Toaster from "../overlay/toaster" import { FocusInput, SetPresenceStatus } from "../overlay/command-palette/commands" import { LayoutHotkeyActionId } from "../overlay/hotkeys" import * as ChannelsSidebar from "../shell/channels-sidebar" @@ -157,6 +158,7 @@ describe("RequestedSignOut", () => { model((m) => expect(m.toasts.entries.map((entry) => entry.payload.title)).toEqual(["Failed to sign out"]), ), + Command.resolve(Toaster.PlayToastFeedback, Toaster.Message.CompletedToastFeedback()), UiToast.test.drainEntry({ entryId: "toaster-entry-0" }), model((m) => expect(m.toasts.entries).toEqual([])), ) diff --git a/apps/web-foldkit/src/app/shell.scene.test.ts b/apps/web-foldkit/src/app/shell.scene.test.ts index 99e668282..4c497eea1 100644 --- a/apps/web-foldkit/src/app/shell.scene.test.ts +++ b/apps/web-foldkit/src/app/shell.scene.test.ts @@ -26,7 +26,7 @@ import { CreateChannel, FocusInput } from "../overlay/command-palette/commands" import * as ChannelsSidebar from "../shell/channels-sidebar" import * as Shell from "../shell/model" import { after, ada, hazelOrg, rootScene, signedIn } from "../test/root-fixtures" -import { drainToast } from "../test/toast-fixtures" +import { drainToast, playToastFeedback } from "../test/toast-fixtures" import * as CommandMenu from "../ui/command-menu" import { PortalCommandMenu } from "../ui/command-menu-view" import * as Menu from "../ui/menu" @@ -185,6 +185,7 @@ describe("command palette", () => { Mount.expectEnded(PortalCommandMenu), sceneExpect(text("Channel created successfully")).toExist(), // The toast enters, its 4s lifetime runs out, then it is removed after its exit animation. + playToastFeedback, ...drainToast(), sceneExpect(text("Channel created successfully")).toBeAbsent(), ) diff --git a/apps/web-foldkit/src/overlay/toaster.test.ts b/apps/web-foldkit/src/overlay/toaster.test.ts index 0c90de3dd..f49f3bf4b 100644 --- a/apps/web-foldkit/src/overlay/toaster.test.ts +++ b/apps/web-foldkit/src/overlay/toaster.test.ts @@ -103,6 +103,20 @@ describe("root toaster", () => { }) }) +describe("toast haptics", () => { + const commandNames = (intent: Toaster.ToastRequest["intent"]) => + Toaster.push(Toaster.init(), { intent, title: "T", description: null }).commands?.map( + (command) => command.name, + ) ?? [] + + test("an outcome's toast plays its haptic, an info or loading one does not", () => { + for (const intent of ["success", "warning", "error"] as const) + expect(commandNames(intent), intent).toContain("PlayToastFeedback") + for (const intent of ["info", "loading"] as const) + expect(commandNames(intent), intent).not.toContain("PlayToastFeedback") + }) +}) + describe("update toast replacement", () => { test("a failure replaces availability in place, dropping the action and starting a timer", () => { const initial = Toaster.push(Toaster.init(), available).model @@ -120,7 +134,9 @@ describe("update toast replacement", () => { payload: { kind: "error", title: "Failed", maybeAction: Option.none() }, }) expect(Option.isSome(failed.model.entries[0]!.maybeDuration)).toBe(true) - expect(failed.commands?.map((command) => command.name)).toEqual(["WaitBeforeDismissal"]) + // One dismissal timer, restarted in place: never a second one running beside it. + const timers = (failed.commands ?? []).filter((command) => command.name === "WaitBeforeDismissal") + expect(timers).toHaveLength(1) }) test("creates a new toast after its action dismissed the previous one", () => { diff --git a/apps/web-foldkit/src/overlay/toaster.ts b/apps/web-foldkit/src/overlay/toaster.ts index b5cc53eb1..b0393c9b4 100644 --- a/apps/web-foldkit/src/overlay/toaster.ts +++ b/apps/web-foldkit/src/overlay/toaster.ts @@ -1,8 +1,9 @@ -import { Option, Schema } from "effect" +import { Effect, Option, Schema } from "effect" import { Command, Subscription, type Update } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" import { defineMessageUnion } from "foldkit/message" import { toastEntryClassName, toastEntryFromTopClassName } from "~/components/ui/toast.styles" +import { playFeedback } from "../platform/feedback" import * as Toast from "../ui/toast" import * as ToastView from "../ui/toast-view" import { ToastAction, ToastRequest } from "./toasts" @@ -22,6 +23,7 @@ export type Model = Toast.Model export const Message = defineMessageUnion({ GotToastMessage: { message: Toast.Message }, ClickedAction: { entryId: Schema.String, action: ToastAction }, + CompletedToastFeedback: {}, }) export type Message = typeof Message.Type @@ -39,11 +41,27 @@ const lift = (result: { commands: Command.mapMessages(result.commands ?? [], (message) => Message.GotToastMessage({ message })), }) +// COMMAND + +/** An outcome's toast plays its haptic as it shows (`platform/feedback.ts`). */ +const OutcomeKind = Schema.Literals(["success", "warning", "error"]) +const isOutcome = Schema.is(OutcomeKind) + +export const PlayToastFeedback = Command.define("PlayToastFeedback", { + args: { kind: OutcomeKind }, + messages: [Message.CompletedToastFeedback], + execute: ({ kind }) => + Effect.sync(() => { + playFeedback(kind) + return Message.CompletedToastFeedback() + }), +}) + // UPDATE /** `toast.success(title, { id, description })` and friends; a known `id` updates that toast in place. */ -export const push = (model: Model, request: ToastRequest): Return => - lift( +export const push = (model: Model, request: ToastRequest): Return => { + const shown = lift( Toast.show( model, { @@ -56,12 +74,18 @@ export const push = (model: Model, request: ToastRequest): Return => request.isSticky === true, ), ) + const { intent } = request + return isOutcome(intent) + ? { ...shown, commands: [...(shown.commands ?? []), PlayToastFeedback({ kind: intent })] } + : shown +} /** Clicking a toast's action dismisses it and hands its `action` to the root. */ export const update = (model: Model, message: Message): ReturnWithAction => Message.match(message, { GotToastMessage: ({ message: toastMessage }) => lift(Toast.update(model, toastMessage)), ClickedAction: ({ entryId, action }) => ({ ...lift(Toast.dismiss(model, entryId)), action }), + CompletedToastFeedback: () => ({ model }), }) // SUBSCRIPTION diff --git a/apps/web-foldkit/src/platform/feedback.ts b/apps/web-foldkit/src/platform/feedback.ts new file mode 100644 index 000000000..339919a8f --- /dev/null +++ b/apps/web-foldkit/src/platform/feedback.ts @@ -0,0 +1,30 @@ +import type { Attribute, HtmlBuilder } from "foldkit/html" +import { systemUi } from "./system-ui" + +/** + * Haptic feedback, where the shell has it (the iOS app). The app never asks for a buzz; a + * component plays the one its kind of interaction means, so features get it by using the + * component: + * + * - `selection`: a discrete value changed (Switch, Checkbox, Radio, Tabs, ChoiceBox). + * - `impact`: something with weight arrived under the finger (a context menu opening as a sheet). + * - `success` / `warning` / `error`: how something turned out (a Toast of that kind). + * + * Plain buttons, links, navigation and typing play nothing; the system's own menus (a long + * press's, a Select's) play their own. A browser and the desktop shells play nothing either. + */ +export type Feedback = "selection" | "impact" | "success" | "warning" | "error" + +/** What a press itself means; an outcome comes later, from `playFeedback`. */ +export type PressFeedback = Extract + +/** + * Marks the pressed element: the native host plays it the moment the finger lifts, before the + * press reaches the runtime (`apps/native/host/src/render/handlers.rs`). Put it on the element + * that carries the press handler. + */ +export const pressFeedback = (h: HtmlBuilder, kind: PressFeedback): Attribute => + h.Attribute("data-native-feedback", kind) + +/** Plays an outcome's feedback now: run it from a component's Command (a Toast of that kind). */ +export const playFeedback = (kind: Feedback): void => systemUi()?.feedback(kind) diff --git a/apps/web-foldkit/src/platform/system-ui.ts b/apps/web-foldkit/src/platform/system-ui.ts index 8b226c48f..e16b0ded6 100644 --- a/apps/web-foldkit/src/platform/system-ui.ts +++ b/apps/web-foldkit/src/platform/system-ui.ts @@ -1,3 +1,5 @@ +import type { Feedback } from "./feedback" + /** * The phone's own controls, where the app runs in a native shell that has them: the iOS app * (`apps/native/src/ios.ts`) installs them on the global object before the app starts, as the @@ -7,8 +9,8 @@ */ export type SystemUi = Readonly<{ - /** A tap of the finger, as a long-press's menu opening gives. */ - haptic: () => void + /** Plays a haptic (`platform/feedback.ts` says which kind means what). */ + feedback: (kind: Feedback) => void /** From now on the edge swipe goes to `href`, until the function this returns runs. */ setSwipeBack: (href: string) => () => void }> diff --git a/apps/web-foldkit/src/test/toast-fixtures.ts b/apps/web-foldkit/src/test/toast-fixtures.ts index 6e11ead0c..af9f73e32 100644 --- a/apps/web-foldkit/src/test/toast-fixtures.ts +++ b/apps/web-foldkit/src/test/toast-fixtures.ts @@ -1,6 +1,7 @@ import * as Animation from "@foldkit/ui/animation" import * as UiToast from "@foldkit/ui/toast" import * as Scene from "foldkit/scene" +import * as Toaster from "../overlay/toaster" /** * Scene steps for the root toaster's `@foldkit/ui` Toast. `Toast.test.drainEntry` is Story-only, so @@ -48,3 +49,9 @@ export const drainToast = (entryId: string = FIRST_TOAST, version = 0) => [ ), leaveToast(entryId), ] + +/** A success, warning or error toast plays its haptic as it shows (`overlay/toaster.ts`). */ +export const playToastFeedback = Scene.Command.resolve( + Toaster.PlayToastFeedback, + Toaster.Message.CompletedToastFeedback(), +) diff --git a/apps/web-foldkit/src/ui/aria-radio.ts b/apps/web-foldkit/src/ui/aria-radio.ts index 7027b4e96..cbab80936 100644 --- a/apps/web-foldkit/src/ui/aria-radio.ts +++ b/apps/web-foldkit/src/ui/aria-radio.ts @@ -1,4 +1,5 @@ import type { Html, HtmlBuilder } from "foldkit/html" +import { pressFeedback } from "../platform/feedback" import * as Collection from "./aria/collection" import * as Interaction from "./aria/interaction" import { visuallyHiddenStyle } from "./checkbox" @@ -83,6 +84,7 @@ export const ariaRadioGroup = ( defaultAction: "Prevent", focusSelector: Collection.idAttributeSelector(id), }), + ...(isSelected ? [] : [pressFeedback(h, "selection")]), ]), ], [ diff --git a/apps/web-foldkit/src/ui/checkbox.scene.test.ts b/apps/web-foldkit/src/ui/checkbox.scene.test.ts index c92df6fde..d1e56f937 100644 --- a/apps/web-foldkit/src/ui/checkbox.scene.test.ts +++ b/apps/web-foldkit/src/ui/checkbox.scene.test.ts @@ -73,6 +73,19 @@ describe("checkbox scene", () => { ) }) + test("a press on the checkbox plays the selection haptic natively; a disabled one plays nothing", () => { + Scene.scene( + { update, view: view() }, + Scene.given(init()), + Scene.expect(control).toHaveAttr("data-native-feedback", "selection"), + ) + Scene.scene( + { update, view: view({ isDisabled: true }) }, + Scene.given(init()), + Scene.expect(control).not.toHaveAttr("data-native-feedback"), + ) + }) + test("a disabled checkbox is disabled and ignores clicks", () => { Scene.scene( { update, view: view({ isDisabled: true }) }, diff --git a/apps/web-foldkit/src/ui/checkbox.ts b/apps/web-foldkit/src/ui/checkbox.ts index 818d616bb..37eee8e0f 100644 --- a/apps/web-foldkit/src/ui/checkbox.ts +++ b/apps/web-foldkit/src/ui/checkbox.ts @@ -8,6 +8,7 @@ import { checkboxStyles, } from "~/components/ui/checkbox.styles" import { IconCheck, IconMinus } from "../icons" +import { pressFeedback } from "../platform/feedback" import * as Collection from "./aria/collection" import * as Field from "./field" @@ -84,6 +85,7 @@ export const checkbox = ( focusSelector: Collection.idAttributeSelector(options.id), ...(options.stopsClickPropagation ? { propagation: "Stop" as const } : {}), }), + pressFeedback(h, "selection"), ]), ], [ diff --git a/apps/web-foldkit/src/ui/choice-box.scene.test.ts b/apps/web-foldkit/src/ui/choice-box.scene.test.ts index 95127910e..2269b83ca 100644 --- a/apps/web-foldkit/src/ui/choice-box.scene.test.ts +++ b/apps/web-foldkit/src/ui/choice-box.scene.test.ts @@ -101,6 +101,20 @@ describe("choice-box scene", () => { Scene.scene(config, Scene.given(plan), Scene.keydown(grid, "a"), Scene.expectIgnored()) }) + test("an enabled row plays the selection haptic natively; a disabled or read-only one plays nothing", () => { + Scene.scene( + config, + Scene.given(plan), + Scene.expect(row("Free")).toHaveAttr("data-native-feedback", "selection"), + Scene.expect(row("Enterprise")).not.toHaveAttr("data-native-feedback"), + ) + Scene.scene( + { update, view: viewWith({ isReadOnly: true }) }, + Scene.given(plan), + Scene.expect(row("Free")).not.toHaveAttr("data-native-feedback"), + ) + }) + test("a read-only choice box ignores row clicks", () => { Scene.scene( { update, view: viewWith({ isReadOnly: true }) }, diff --git a/apps/web-foldkit/src/ui/choice-box.ts b/apps/web-foldkit/src/ui/choice-box.ts index d5fae9ea2..56ab4a471 100644 --- a/apps/web-foldkit/src/ui/choice-box.ts +++ b/apps/web-foldkit/src/ui/choice-box.ts @@ -13,6 +13,7 @@ import { choiceBoxLabelStyles, choiceBoxStyles, } from "~/components/ui/choice-box.styles" +import { pressFeedback } from "../platform/feedback" import { announce, gridSelectionMessage } from "./aria/announcer" import * as Interaction from "./aria/interaction" import { checkbox } from "./checkbox" @@ -300,7 +301,12 @@ export const choiceBox = ( ...Interaction.stateAttributes(h, state), ] : []), - ...(isReadOnly ? [] : [h.OnClick(send(Message.ClickedItem({ key: item.key })))]), + ...(isReadOnly + ? [] + : [ + h.OnClick(send(Message.ClickedItem({ key: item.key }))), + pressFeedback(h, "selection"), + ]), ]), ], [ diff --git a/apps/web-foldkit/src/ui/menu-view.ts b/apps/web-foldkit/src/ui/menu-view.ts index 20348f39f..a09dc252c 100644 --- a/apps/web-foldkit/src/ui/menu-view.ts +++ b/apps/web-foldkit/src/ui/menu-view.ts @@ -27,7 +27,7 @@ import { import { popoverContentBase, popoverInnerClassName } from "~/components/ui/popover.styles" import { IconCheck, IconChevronRight } from "../icons" import { type NativeMenuLook, nativeIsland } from "../platform/native-island" -import { systemUi } from "../platform/system-ui" +import { playFeedback } from "../platform/feedback" import { dismissButton, focusScopeSentinel, openModalPopover, positionOverlay } from "./aria/overlay" import { Placement } from "./aria/placement" import { MOBILE_QUERY } from "./viewport" @@ -95,7 +95,7 @@ const PortalMenu = Mount.defineStream("PortalMenu", { Effect.acquireRelease( Effect.sync(() => { // A long-press's menu taps the finger as it opens, where the shell can. - if (isSheetOnPhone) systemUi()?.haptic() + if (isSheetOnPhone) playFeedback("impact") // useMenuItem focuses an item in onHoverStart, synchronously, so the click that follows // lands on a focused item and never focuses it with the mouse (Chrome keeps :focus-visible). const onPointerOver = (event: Event) => { diff --git a/apps/web-foldkit/src/ui/radio.scene.test.ts b/apps/web-foldkit/src/ui/radio.scene.test.ts index 123a07201..22ede97d3 100644 --- a/apps/web-foldkit/src/ui/radio.scene.test.ts +++ b/apps/web-foldkit/src/ui/radio.scene.test.ts @@ -60,6 +60,15 @@ describe("radio group scene", () => { ) }) + test("only an unselected radio plays the selection haptic: pressing the chosen one changes nothing", () => { + Scene.scene( + { update, view: styledView() }, + Scene.given(init({ choice: "free" })), + Scene.expect(Scene.selector("label[data-native-feedback]")).toContainText("Pro"), + Scene.expect(Scene.selector("label[data-selected]")).not.toHaveAttr("data-native-feedback"), + ) + }) + test("an arrow key's native change moves the selection", () => { Scene.scene( { update, view: styledView() }, diff --git a/apps/web-foldkit/src/ui/radio.ts b/apps/web-foldkit/src/ui/radio.ts index 167966493..e54b6f72d 100644 --- a/apps/web-foldkit/src/ui/radio.ts +++ b/apps/web-foldkit/src/ui/radio.ts @@ -6,6 +6,7 @@ import { radioLayoutStyles, radioStyles, } from "~/components/ui/radio.styles" +import { pressFeedback } from "../platform/feedback" import * as Collection from "./aria/collection" import { visuallyHiddenStyle } from "./checkbox" import * as Field from "./field" @@ -79,6 +80,7 @@ export const radioGroup = ( defaultAction: "Prevent", focusSelector: Collection.idAttributeSelector(id), }), + ...(isSelected ? [] : [pressFeedback(h, "selection")]), ]), ], [ diff --git a/apps/web-foldkit/src/ui/switch.scene.test.ts b/apps/web-foldkit/src/ui/switch.scene.test.ts index 7b00c4cb1..1779df055 100644 --- a/apps/web-foldkit/src/ui/switch.scene.test.ts +++ b/apps/web-foldkit/src/ui/switch.scene.test.ts @@ -50,6 +50,19 @@ describe("switch scene", () => { ) }) + test("a press on the switch plays the selection haptic natively; a disabled one plays nothing", () => { + Scene.scene( + { update, view: view() }, + Scene.given(init()), + Scene.expect(control).toHaveAttr("data-native-feedback", "selection"), + ) + Scene.scene( + { update, view: view({ isDisabled: true }) }, + Scene.given(init()), + Scene.expect(control).not.toHaveAttr("data-native-feedback"), + ) + }) + test("Space on the switch flips it through the native change", () => { Scene.scene( { update, view: view() }, diff --git a/apps/web-foldkit/src/ui/switch.ts b/apps/web-foldkit/src/ui/switch.ts index 375c5ab8e..8d9731098 100644 --- a/apps/web-foldkit/src/ui/switch.ts +++ b/apps/web-foldkit/src/ui/switch.ts @@ -1,6 +1,7 @@ import type { Html, HtmlBuilder } from "foldkit/html" import { twJoin, twMerge } from "tailwind-merge" import { switchIndicatorStyles, switchStyles, switchThumbStyles } from "~/components/ui/switch.styles" +import { pressFeedback } from "../platform/feedback" import * as Collection from "./aria/collection" import { visuallyHiddenStyle } from "./checkbox" import * as Field from "./field" @@ -44,6 +45,7 @@ export const switchControl = ( defaultAction: "Prevent", focusSelector: Collection.idAttributeSelector(options.id), }), + pressFeedback(h, "selection"), ]), ], [ diff --git a/apps/web-foldkit/src/ui/tab-strip.ts b/apps/web-foldkit/src/ui/tab-strip.ts index 09544cd8f..20296f103 100644 --- a/apps/web-foldkit/src/ui/tab-strip.ts +++ b/apps/web-foldkit/src/ui/tab-strip.ts @@ -1,6 +1,7 @@ import type { Attribute, Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" import { tabsStyles } from "~/components/ui/tabs.styles" +import { pressFeedback } from "../platform/feedback" /** * A horizontal tab list whose selection is the route (the chat tab bar and the channel settings @@ -26,6 +27,7 @@ export const tabView = ( h.DataAttribute("slot", "tab"), h.Role("tab"), h.Tabindex(options.isSelected ? 0 : -1), + ...(options.isSelected ? [] : [pressFeedback(h, "selection")]), ...(options.attributes ?? []), ], [ diff --git a/apps/web-foldkit/src/ui/tabs.scene.test.ts b/apps/web-foldkit/src/ui/tabs.scene.test.ts index 3bd550231..395536e36 100644 --- a/apps/web-foldkit/src/ui/tabs.scene.test.ts +++ b/apps/web-foldkit/src/ui/tabs.scene.test.ts @@ -87,6 +87,16 @@ describe("tabs scene", () => { ) }) + test("only an unselected, enabled tab plays the selection haptic natively", () => { + Scene.scene( + { update, view }, + Scene.given(init()), + Scene.expect(tab("Members")).toHaveAttr("data-native-feedback", "selection"), + Scene.expect(tab("General")).not.toHaveAttr("data-native-feedback"), + Scene.expect(tab("Billing")).not.toHaveAttr("data-native-feedback"), + ) + }) + test("clicking a tab tells the parent, which swaps the panel", () => { Scene.scene( { update, view }, diff --git a/apps/web-foldkit/src/ui/tabs.ts b/apps/web-foldkit/src/ui/tabs.ts index 9f01fccf8..e82c42515 100644 --- a/apps/web-foldkit/src/ui/tabs.ts +++ b/apps/web-foldkit/src/ui/tabs.ts @@ -3,6 +3,7 @@ import { Array } from "effect" import type { Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" import { tabsStyles } from "~/components/ui/tabs.styles" +import { pressFeedback } from "../platform/feedback" /** * The `@foldkit/ui` Tabs, styled. The parent owns the selected tab: it passes it to the view as @@ -43,6 +44,7 @@ export const layout = ( info.value, [ ...info.tab, + ...(info.isActive || info.isDisabled ? [] : [pressFeedback(h, "selection")]), h.Class(twMerge(...tabsStyles.tab("horizontal", false))), h.DataAttribute("slot", "tab"), ],