diff --git a/apps/native/README.md b/apps/native/README.md index 4bdd0db99..ffabb9b57 100644 --- a/apps/native/README.md +++ b/apps/native/README.md @@ -245,12 +245,12 @@ Foldkit view hazel_native (host/src/islands.rs) iOS shell own links and clicks DOM events, on the existing wire delegate callbacks ``` -| Component | Where | Native view | Who draws | Comes back as | -| -------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------- | --------------------------------------------------------- | -| `tab-bar` | the mobile nav (`shell/mobile`) | `UITabBar`, with the items' counts as badges | UIKit | the `click` of the item's own link or button | -| `menu` | every Select's trigger, and every menu whose items are all words (`Menu.nativeMenuItems`) | a clear `UIButton` with a `UIMenu` | Rune | `change` on the trigger, with the item's key | -| `date-picker` | every DatePicker's field | a clear `UIButton` that presents a calendar sheet | Rune | `change` on the field, `yyyy-MM-dd` | -| `context-menu` | every message row | none: one `UIContextMenuInteraction` on Rune's view finds the row under a held press | Rune | `change` on the row: the action's key, or `react:` | +| Component | Where | Native view | Who draws | Comes back as | +| -------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------- | ------------------------------------------------------- | +| `tab-bar` | the mobile nav (`shell/mobile`) | `UITabBar`, with the items' counts as badges | UIKit | the `click` of the item's own link or button | +| `menu` | every Select's trigger, and every menu whose items are all words (`Menu.nativeMenuItems`) | a clear `UIButton` with a `UIMenu` | Rune | `change` on the trigger, with the item's key | +| `date-picker` | every DatePicker's field | a clear `UIButton` that presents a calendar sheet | Rune | `change` on the field, `yyyy-MM-dd` | +| `context-menu` | every message row, and sidebar channel and DM rows (`Menu.longPressMenu`) | none: one `UIContextMenuInteraction` on Rune's view finds the row under a held press | Rune | `change` on the row: the item's key, or `react:` | Nothing new crosses the wire: the host replays DOM events on handlers the tree already carries, so a component needs no Message of its own beyond what its `change` maps to. diff --git a/apps/native/host/ios/src/context_menu.rs b/apps/native/host/ios/src/context_menu.rs index 70ba46e44..00d6b89bd 100644 --- a/apps/native/host/ios/src/context_menu.rs +++ b/apps/native/host/ios/src/context_menu.rs @@ -1,10 +1,12 @@ -//! The `context-menu` island: the system's long-press menu for an element Rune draws (a message). +//! The `context-menu` island: the system's long-press menu for an element Rune draws (a message, +//! a sidebar row). //! //! Unlike the other islands it has no view of its own. A list holds many of these and scrolls, //! so each one is only a region: where its element was drawn in the last frame. One //! `UIContextMenuInteraction` on Rune's view asks, when a press has been held, which region is -//! under the finger, and opens that element's menu (`props.groups`, with a row of quick -//! reactions from `props.reactions`). A choice is a `change` on the element, with the action's key. +//! under the finger (the innermost), and opens that element's menu (`props.items`, as a `menu` +//! island's, with a row of quick choices from `props.quick`). A choice is a `change` on the +//! element, with the item's key. use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::ptr::NonNull; @@ -19,16 +21,15 @@ use objc2_core_foundation::{CGPoint, CGRect, CGSize}; use objc2_foundation::{NSArray, NSCopying, NSObject, NSObjectProtocol, NSString, ns_string}; use objc2_ui_kit::{ UIAction, UIBezierPath, UIColor, UIContextMenuConfiguration, UIContextMenuInteraction, - UIContextMenuInteractionAnimating, UIContextMenuInteractionDelegate, UIEdgeInsets, UIImage, - UIInteraction, UIMenu, UIMenuElement, UIMenuElementAttributes, UIMenuElementSize, - UIMenuOptions, UIPreviewParameters, UIPreviewTarget, UITargetedPreview, UIUserInterfaceStyle, - UIView, + UIContextMenuInteractionAnimating, UIContextMenuInteractionDelegate, UIEdgeInsets, + UIInteraction, UIMenu, UIMenuElement, UIMenuElementSize, UIMenuOptions, UIPreviewParameters, + UIPreviewTarget, UITargetedPreview, UIUserInterfaceStyle, UIView, }; type Rect = [f32; 4]; /// How many small elements a menu shows side by side; more wrap onto rows of their own. -const REACTIONS_IN_A_ROW: usize = 4; +const QUICK_IN_A_ROW: usize = 4; struct Region { spec: IslandSpec, @@ -109,31 +110,33 @@ pub fn end(mtm: MainThreadMarker, parent: &UIView) { INTERACTION.set(Some((interaction, delegate))); } -/// The island whose element is drawn at `at`, and where. +/// The island whose element is drawn at `at`, and where: the innermost, when one sits in another. fn region_at(at: CGPoint) -> Option<(IslandSpec, Rect)> { REGIONS.with_borrow(|regions| { - regions.values().find_map(|region| { - let (rect, holes) = region.shown.as_ref()?; - let pressed = contains(*rect, at) && !holes.iter().any(|hole| contains(*hole, at)); - pressed.then(|| (region.spec.clone(), *rect)) - }) + regions + .values() + .filter_map(|region| { + let (rect, holes) = region.shown.as_ref()?; + let pressed = contains(*rect, at) && !holes.iter().any(|hole| contains(*hole, at)); + pressed.then(|| (region.spec.clone(), *rect)) + }) + .min_by(|(_, [.., aw, ah]), (_, [.., bw, bh])| (aw * ah).total_cmp(&(bw * bh))) }) } +/// A quick choice: a `change` on the element with `value`. fn action( mtm: MainThreadMarker, island: &IslandSpec, title: &str, - symbol: Option<&str>, value: String, ) -> Retained { let island = island.clone(); let handler = RcBlock::new(move |_: NonNull| islands::change(&island, &value)); - let image = symbol.and_then(|symbol| UIImage::systemImageNamed(&NSString::from_str(symbol))); unsafe { UIAction::actionWithTitle_image_identifier_handler( &NSString::from_str(title), - image.as_deref(), + None, None, RcBlock::as_ptr(&handler), mtm, @@ -152,53 +155,44 @@ fn inline(mtm: MainThreadMarker, children: Vec>) -> Reta ) } -/// The element's menu: its quick reactions in a row, then each group of actions. +/// The element's menu: its quick choices in a row (`props.quick`), then its items +/// (`props.items`, the `menu` island's shape: groups between separators, submenus). fn menu_of(mtm: MainThreadMarker, island: &IslandSpec) -> Retained { let props = &island.props; - let text = |value: &serde_json::Value, name: &str| { - value - .get(name) - .and_then(|field| field.as_str()) - .map(str::to_string) - }; let mut sections: Vec> = Vec::new(); - let prefix = text(props, "reactionPrefix").unwrap_or_default(); - let reactions: Vec> = props - .get("reactions") - .and_then(|reactions| reactions.as_array()) + let quick = props.get("quick"); + let prefix = quick + .and_then(|quick| quick.get("prefix")) + .and_then(|prefix| prefix.as_str()) + .unwrap_or_default(); + let choices: Vec> = quick + .and_then(|quick| quick.get("choices")) + .and_then(|choices| choices.as_array()) .into_iter() .flatten() - .filter_map(|emoji| emoji.as_str()) + .filter_map(|choice| choice.as_str()) // As many as the system lays out in one row. - .take(REACTIONS_IN_A_ROW) - .map(|emoji| { - Retained::into_super(action(mtm, island, emoji, None, format!("{prefix}{emoji}"))) + .take(QUICK_IN_A_ROW) + .map(|choice| { + Retained::into_super(action(mtm, island, choice, format!("{prefix}{choice}"))) }) .collect(); - if !reactions.is_empty() { - let row = inline(mtm, reactions); + if !choices.is_empty() { + let row = inline(mtm, choices); row.setPreferredElementSize(UIMenuElementSize::Small); sections.push(Retained::into_super(row)); } - let groups = props.get("groups").and_then(|groups| groups.as_array()); - for group in groups.into_iter().flatten() { - let items: Vec> = group - .as_array() - .into_iter() - .flatten() - .filter_map(|item| { - let key = text(item, "key")?; - let title = text(item, "label").unwrap_or_else(|| key.clone()); - let item_action = action(mtm, island, &title, text(item, "symbol").as_deref(), key); - if item.get("destructive").and_then(|d| d.as_bool()) == Some(true) { - item_action.setAttributes(UIMenuElementAttributes::Destructive); - } - Some(Retained::into_super(item_action)) - }) - .collect(); - if !items.is_empty() { - sections.push(Retained::into_super(inline(mtm, items))); - } + let items = props + .get("items") + .and_then(|items| items.as_array()) + .map_or(&[][..], |items| items.as_slice()); + let children = crate::islands::menu_children(mtm, island, None, items); + // Several groups come as sections already; one group is a section of its own here, divided + // from the quick row. + if crate::islands::groups_of(items).len() > 1 { + sections.extend(children); + } else if !children.is_empty() { + sections.push(Retained::into_super(inline(mtm, children))); } UIMenu::menuWithChildren(&NSArray::from_retained_slice(§ions), mtm) } diff --git a/apps/native/host/ios/src/islands.rs b/apps/native/host/ios/src/islands.rs index d3442c7d0..e74393090 100644 --- a/apps/native/host/ios/src/islands.rs +++ b/apps/native/host/ios/src/islands.rs @@ -221,8 +221,6 @@ fn tint_tab_bar(bar: &UITabBar, spec: &IslandSpec) { } } -/// The system menu of a Select's options (`props.items`), the selected one checked. A choice is -/// a `change` on the island's element, with the option's key. /// The island's menu (`props.items`, from a Select or the app's menus): items, `{ separator }` /// between groups (each group an inline section), and `{ label, items }` submenus. A choice is a /// `change` on the island with the item's key. @@ -238,16 +236,13 @@ fn menu_of(mtm: MainThreadMarker, spec: &IslandSpec) -> Retained { UIMenu::menuWithChildren(&NSArray::from_retained_slice(&children), mtm) } -fn menu_children( +pub(crate) fn menu_children( mtm: MainThreadMarker, spec: &IslandSpec, selected: Option<&str>, options: &[serde_json::Value], ) -> Vec> { - let groups: Vec<&[serde_json::Value]> = options - .split(|option| option.get("separator").is_some()) - .filter(|group| !group.is_empty()) - .collect(); + let groups = groups_of(options); let element = |option: &serde_json::Value| menu_element(mtm, spec, selected, option); if groups.len() <= 1 { return options.iter().filter_map(element).collect(); @@ -258,6 +253,14 @@ fn menu_children( .collect() } +/// The menu's groups: the runs of items between separators. More than one shows as sections. +pub(crate) fn groups_of(options: &[serde_json::Value]) -> Vec<&[serde_json::Value]> { + options + .split(|option| option.get("separator").is_some()) + .filter(|group| !group.is_empty()) + .collect() +} + /// A group of items shown as one section of the menu, divided from the next. fn inline_section( mtm: MainThreadMarker, diff --git a/apps/web-foldkit/src/page/chat/channel/messages.scene.test.ts b/apps/web-foldkit/src/page/chat/channel/messages.scene.test.ts index ae7210eff..198fd2d46 100644 --- a/apps/web-foldkit/src/page/chat/channel/messages.scene.test.ts +++ b/apps/web-foldkit/src/page/chat/channel/messages.scene.test.ts @@ -27,6 +27,7 @@ import * as EmojiDialog from "../../../emoji-picker/dialog" import { PopoverEvent, popoverId } from "../../../picker-popover/popover" import type { EmojiData } from "../../../emoji-picker/data" import * as Overlays from "../overlays" +import { TOP_EMOJIS } from "../../../chat/message/toolbar" import { imageAttachmentOf } from "../../../test/chat-messages" import { PageOutMessage } from "../../out-message" import { @@ -243,6 +244,41 @@ describe("hover toolbar", () => { ) }) + // The contract with the iOS host's `context_menu.rs`: `items` as a `menu` island's, `quick` above. + test("a long press on a message opens its context menu natively, words, symbols and quick reactions", () => { + const item = (key: string, label: string, symbol: string) => ({ key, label, symbol }) + const separator = { separator: true } + const props = (own: boolean) => + JSON.stringify({ + items: [ + item("add-reaction", "Add Reaction", "face.smiling"), + separator, + item("reply", "Reply", "arrowshape.turn.up.left"), + ...(own ? [item("edit", "Edit Message", "pencil")] : []), + item("thread", "Reply in Thread", "bubble.left.and.bubble.right"), + separator, + item("copy", "Copy Text", "doc.on.doc"), + item("pin", "Pin Message", "pin"), + separator, + ...(own ? [{ ...item("delete", "Delete Message", "trash"), destructive: true }] : []), + item("copy-id", "Copy Message ID", "number"), + ], + quick: { choices: TOP_EMOJIS, prefix: Overlays.NATIVE_REACTION }, + }) + // Ada's own message, then Grace's: the island wraps each row. + const rows = Scene.all.selector('[data-native="context-menu"]') + const withProps = (own: boolean) => Scene.all.selector(`[data-native-props='${props(own)}']`) + Scene.scene( + channelScene, + Scene.given(derivedModel()), + mountedChannel(), + Scene.expectAll(rows).toHaveCount(2), + Scene.expectAll(withProps(true)).toHaveCount(1), + Scene.expectAll(withProps(false)).toHaveCount(1), + Scene.expect(Scene.selector('[data-native="context-menu"]')).toHaveHandler("change"), + ) + }) + test("another user's message offers neither Edit nor Delete", () => { Scene.scene( channelScene, diff --git a/apps/web-foldkit/src/page/chat/overlays.ts b/apps/web-foldkit/src/page/chat/overlays.ts index 646c4c5c5..6bfdb2498 100644 --- a/apps/web-foldkit/src/page/chat/overlays.ts +++ b/apps/web-foldkit/src/page/chat/overlays.ts @@ -285,19 +285,22 @@ export const moreMenuEntries = (facts: MessageFacts): ReadonlyArray Menu.item("pin"), ] +/** A message's context menu; the words are what the system's menu shows (`textValue`). */ export const contextMenuEntries = (facts: MessageFacts, messageId: MessageId): ReadonlyArray => [ Menu.separator, - Menu.item("add-reaction"), + Menu.item("add-reaction", { textValue: "Add Reaction" }), Menu.separator, - Menu.item("reply"), - ...(facts.isOwnMessage(messageId) ? [Menu.item("edit")] : []), - ...(facts.isThreadChannel ? [] : [Menu.item("thread")]), + Menu.item("reply", { textValue: "Reply" }), + ...(facts.isOwnMessage(messageId) ? [Menu.item("edit", { textValue: "Edit Message" })] : []), + ...(facts.isThreadChannel ? [] : [Menu.item("thread", { textValue: "Reply in Thread" })]), Menu.separator, - Menu.item("copy"), - Menu.item("pin"), + Menu.item("copy", { textValue: "Copy Text" }), + Menu.item("pin", { textValue: facts.isPinned(messageId) ? "Unpin Message" : "Pin Message" }), Menu.separator, - ...(facts.isOwnMessage(messageId) ? [Menu.item("delete", { intent: "Danger" })] : []), - Menu.item("copy-id"), + ...(facts.isOwnMessage(messageId) + ? [Menu.item("delete", { intent: "Danger", textValue: "Delete Message" })] + : []), + Menu.item("copy-id", { textValue: "Copy Message ID" }), ] /** The "More actions" menu of a message: the open one, or a closed one. */ diff --git a/apps/web-foldkit/src/page/chat/row-context.ts b/apps/web-foldkit/src/page/chat/row-context.ts index 5fb9662d5..8888b111f 100644 --- a/apps/web-foldkit/src/page/chat/row-context.ts +++ b/apps/web-foldkit/src/page/chat/row-context.ts @@ -1,4 +1,5 @@ import type { ChannelId, MessageId } from "@hazel/schema" +import { Option } from "effect" import { type ChildAttribute, childAttributes, type Html, type HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" import { menuHeaderBase } from "~/components/ui/menu.styles" @@ -19,9 +20,9 @@ import { TOP_EMOJIS } from "../../chat/message/toolbar" import { popoverTrigger } from "../../chat/popover-host" import { profilePopoverContent } from "../../chat/profile-popover" import type * as TooltipHost from "../../chat/tooltip-host" -import { nativeIsland } from "../../platform/native-island" +import { nativeContextMenu } from "../../platform/native-island" import { button } from "../../ui/button" -import type * as Menu from "../../ui/menu" +import * as Menu from "../../ui/menu" import { contextMenuView, menuLabel } from "../../ui/menu-view" import type * as Popover from "../../ui/popover" import * as Overlays from "./overlays" @@ -137,60 +138,51 @@ const contextMenuContent = return contextItem(h, key, "Copy Message ID", icon(IconHashtag)) } -/** Each action's title and SF Symbol in the system menu a native shell opens for the row. */ -const nativeAction = (key: string, isPinned: boolean): Readonly<{ label: string; symbol: string }> => { - if (key === "add-reaction") return { label: "Add Reaction", symbol: "face.smiling" } - if (key === "reply") return { label: "Reply", symbol: "arrowshape.turn.up.left" } - if (key === "edit") return { label: "Edit Message", symbol: "pencil" } - if (key === "thread") return { label: "Reply in Thread", symbol: "bubble.left.and.bubble.right" } - if (key === "copy") return { label: "Copy Text", symbol: "doc.on.doc" } - if (key === "pin") - return isPinned - ? { label: "Unpin Message", symbol: "pin.slash" } - : { label: "Pin Message", symbol: "pin" } - if (key === "delete") return { label: "Delete Message", symbol: "trash" } - return { label: "Copy Message ID", symbol: "number" } -} +/** Each action's SF Symbol in the system menu a native shell opens for the row. */ +const nativeSymbols = (isPinned: boolean): Readonly> => ({ + "add-reaction": "face.smiling", + reply: "arrowshape.turn.up.left", + edit: "pencil", + thread: "bubble.left.and.bubble.right", + copy: "doc.on.doc", + pin: isPinned ? "pin.slash" : "pin", + delete: "trash", + "copy-id": "number", +}) + +/** Every row's native menu reads no selection: none of its items are checked. */ +const UNSELECTED_MENU = Menu.init({ id: "message-context-menu" }) /** - * The row as a native `context-menu`: on iOS a long press on it opens the system menu with the - * context menu's own entries and quick reactions, and the choice is a `change` here. The row - * draws as it is everywhere. + * A long press on the row opens its context menu as the system's (iOS), with quick reactions + * above it; the choice is a `change` here. The row draws as it is everywhere. */ -const nativeContextMenu = ( +const rowLongPress = ( h: H, row: MessageRow, currentUserId: Model["currentUserId"], isThreadChannel: boolean, ): ReadonlyArray => { const { id, isPinned } = row.message - const entries = Overlays.contextMenuEntries( - { - isOwnMessage: () => row.message.authorId === currentUserId, - isPinned: () => isPinned, - isThreadChannel, - }, - id, - ) - // Each run of items between separators is a group of the menu. - const groups: Array> = [[]] - for (const entry of entries) { - if (entry._tag === "Separator") groups.push([]) - if (entry._tag === "Item") - groups.at(-1)?.push({ - key: entry.item.key, - ...nativeAction(entry.item.key, isPinned), - destructive: entry.item.key === "delete", - }) + const facts = { + isOwnMessage: () => row.message.authorId === currentUserId, + isPinned: () => isPinned, + isThreadChannel, } - return childAttributes([ - ...nativeIsland(h, "context-menu", { - reactions: TOP_EMOJIS, - reactionPrefix: Overlays.NATIVE_REACTION, - groups: groups.filter((group) => group.length > 0), - }), - h.OnChange((value) => toOverlays(Overlays.Message.ChoseNativeAction({ messageId: id, value }))), - ]) + const items = Menu.nativeMenuItems(UNSELECTED_MENU, Overlays.contextMenuEntries(facts, id), { + symbols: nativeSymbols(isPinned), + }) + return Option.match(items, { + onNone: () => [], + onSome: (found) => + childAttributes( + nativeContextMenu( + h, + { items: found, quick: { choices: TOP_EMOJIS, prefix: Overlays.NATIVE_REACTION } }, + (value) => toOverlays(Overlays.Message.ChoseNativeAction({ messageId: id, value })), + ), + ), + }) } const userNamesOf = (users: Model["lookups"]["users"]) => @@ -219,8 +211,7 @@ const buildIdleContext = ( reply: (row, reply) => replyActions(h, row, reply, null, () => []), toHtmlRenderMessage, toPressEmbedAction, - contextMenu: (row, render) => - render(nativeContextMenu(h, row, currentUserId, isThreadChannel), h.empty), + contextMenu: (row, render) => render(rowLongPress(h, row, currentUserId, isThreadChannel), h.empty), avatar: (row: MessageRow) => popoverTrigger(h, { key: Overlays.avatarPopoverKey(row.message.id), @@ -281,10 +272,7 @@ const buildOwnerContext = (h: H, model: Model, nowMs: number): RowContext contextMenu === null || contextMenu.messageId !== row.message.id - ? render( - nativeContextMenu(h, row, model.currentUserId, factsOf(model).isThreadChannel), - h.empty, - ) + ? render(rowLongPress(h, row, model.currentUserId, factsOf(model).isThreadChannel), h.empty) : h.submodel({ slotId: "message-context-menu", model: contextMenu.menu, diff --git a/apps/web-foldkit/src/platform/native-island.ts b/apps/web-foldkit/src/platform/native-island.ts index ff893096d..e5ac67845 100644 --- a/apps/web-foldkit/src/platform/native-island.ts +++ b/apps/web-foldkit/src/platform/native-island.ts @@ -3,8 +3,8 @@ import type { Attribute, HtmlBuilder } from "foldkit/html" /** * Native islands: marks an element the Rune-native app may show or drive with a real platform * view (`apps/native/host/src/islands.rs`): a `UITabBar` for the mobile nav, a system menu for a - * Select, the system's long-press menu for a message. The element and its children stay the whole UI everywhere else: the browser ignores - * these attributes, and a native shell without the component draws the element as it is. + * Select, the system's long-press menu for a row (`nativeContextMenu`). The element and its + * children stay the whole UI everywhere else: the browser ignores these attributes, and a native shell without the component draws the element as it is. * * Nothing comes back through a channel of its own. The native view replays DOM events on this * markup: a tab press is the `click` of the item it stands for, a picker's choice is a `change` @@ -70,3 +70,20 @@ export type NativeMenuLook = Readonly<{ /** Items that read as destructive (red) natively, beyond their `intent`. */ destructive?: ReadonlyArray }> + +/** + * A `context-menu` island: a long press on the element opens the system's menu for it (iOS's + * `UIContextMenuInteraction`), lifting the element as drawn. `quick` is a row of small choices + * above the items (a message's reactions), each chosen as `prefix + choice`. + */ +export type NativeContextMenu = Readonly<{ + items: ReadonlyArray + quick?: Readonly<{ choices: ReadonlyArray; prefix: string }> +}> + +/** The element's long-press menu; a choice is `onChoose` with the item's key. */ +export const nativeContextMenu = ( + h: HtmlBuilder, + menu: NativeContextMenu, + onChoose: (key: string) => Message, +): ReadonlyArray> => [...nativeIsland(h, "context-menu", menu), h.OnChange(onChoose)] diff --git a/apps/web-foldkit/src/shell/channels-sidebar/items.ts b/apps/web-foldkit/src/shell/channels-sidebar/items.ts index c2dadacbd..fa313bdd3 100644 --- a/apps/web-foldkit/src/shell/channels-sidebar/items.ts +++ b/apps/web-foldkit/src/shell/channels-sidebar/items.ts @@ -1,5 +1,5 @@ import type { ChannelId } from "@hazel/schema" -import type { Html, HtmlBuilder } from "foldkit/html" +import type { Attribute, Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" import { styles as avatarStyles } from "~/components/ui/avatar/styles" import { cx } from "~/utils/cx" @@ -122,9 +122,11 @@ export const channelItem = ( partners: ReadonlyArray, context: RowLinkContext, menu: Html = dotsMenuTrigger(h, "Channel options"), + /** The row's long-press menu (`rowLongPress`). */ + longPress: ReadonlyArray> = [], ): Html => { const href = chatHref(context, entry.channel.id) - return sidebarItem(h, {}, [ + return sidebarItem(h, { attributes: longPress }, [ sidebarLink(h, { href, isActive: context.isActive, activeClassName: CHANNEL_ACTIVE }, [ h.span( // Positioned only for the partner marks: needless positioned spans slow every hit test. @@ -341,11 +343,13 @@ export const dmItem = ( notificationCount: number, context: DmRowContext, menu: Html = dotsMenuTrigger(h, "Conversation options"), + /** The row's long-press menu (`dmLongPress`). */ + longPress: ReadonlyArray> = [], ): Html => { const href = chatHref(context, channel.id) const partners = dmPartners(channel, context.currentUserId) const only = partners[0] - return sidebarItem(h, {}, [ + return sidebarItem(h, { attributes: longPress }, [ sidebarLink( h, { href, isActive: context.isActive, activeClassName: CHANNEL_ACTIVE }, diff --git a/apps/web-foldkit/src/shell/channels-sidebar/long-press.scene.test.ts b/apps/web-foldkit/src/shell/channels-sidebar/long-press.scene.test.ts new file mode 100644 index 000000000..c32bce72f --- /dev/null +++ b/apps/web-foldkit/src/shell/channels-sidebar/long-press.scene.test.ts @@ -0,0 +1,109 @@ +// @vitest-environment jsdom +import { ChannelId, ChannelMemberId, OrganizationId } from "@hazel/schema" +import { Schema } from "effect" +import type { HtmlBuilder } from "foldkit/html" +import * as Scene from "foldkit/scene" +import { describe, test } from "vitest" +import { AppRoute } from "../../route" +import * as Menu from "../../ui/menu" +import { FocusTriggerOnPress } from "../../ui/menu-view" +import type { ChannelEntry } from "./rows" +import type { Message, Model } from "./model" +import { sectionGroupContent } from "./view" + +/** A sidebar row's "⋯" menu is also its long-press menu on iOS: the same entries, as words. */ + +const uuid = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}` +const general = Schema.decodeSync(ChannelId)(uuid(1)) +const dmGrace = Schema.decodeSync(ChannelId)(uuid(2)) +const member = (n: number) => ({ + id: Schema.decodeSync(ChannelMemberId)(uuid(200 + n)), + isMuted: false, + isFavorite: false, + notificationCount: 0, +}) +const generalEntry: ChannelEntry = { + channel: { id: general, name: "general", type: "public", icon: null, sectionId: null }, + member: member(1), +} + +const sidebar: Model = { + organizationId: Schema.decodeSync(OrganizationId)(uuid(9)), + currentUserId: null, + membership: null, + sections: [], + sectionChannels: { default: [generalEntry] }, + favorites: [], + threads: [], + dmChannelIds: [dmGrace], + dmChannels: { [dmGrace]: { id: dmGrace, type: "single", members: [], currentUser: member(2) } }, + presence: [], + unreadCounts: [], + connectMounts: [], + organizations: [], + memberChannelIds: [general, dmGrace], + discoverableChannels: [], + isCreateChannelHintDismissed: true, + openMenu: null, +} + +const view = (model: Model, h: HtmlBuilder) => + h.div( + [], + sectionGroupContent(h, model, { + orgSlug: "hazel", + route: AppRoute.ChatIndex({ orgSlug: "hazel" }), + activeChannelId: null, + nowMs: 0, + paletteKey: null, + createChannelKey: null, + onActiveMount: h.Attribute("data-active", ""), + onBrowseChannels: h.Attribute("data-browse", ""), + onDismissCreateChannelHint: h.Attribute("data-dismiss", ""), + toParentMessage: (message) => message, + sectionAction: () => h.empty, + }), + ) + +const update = (model: Model) => ({ model, commands: [] }) +const triggerMounted = Scene.Mount.resolve(FocusTriggerOnPress, Menu.Message.CompletedFocusTriggerOnPress()) + +// What the host's `context_menu.rs` reads: the row's own entries as words, symbols and danger. +const toggles = [ + { key: "mute", label: "Mute", symbol: "bell.slash" }, + { key: "favorite", label: "Favorite", symbol: "star" }, + { separator: true }, +] +const channelMenu = JSON.stringify({ + items: [ + ...toggles, + { key: "settings", label: "Settings", symbol: "gearshape" }, + { separator: true }, + { key: "leave", label: "Leave", symbol: "rectangle.portrait.and.arrow.right", destructive: true }, + ], +}) +const dmMenu = JSON.stringify({ + items: [...toggles, { key: "hide", label: "Hide conversation", symbol: "eye.slash", destructive: true }], +}) +// The long press's island, not the dots trigger's `menu` island, which carries the same items. +const rowsWith = (props: string) => + Scene.all.selector(`[data-native="context-menu"][data-native-props='${props}']`) +const dotsWith = (props: string) => Scene.all.selector(`[data-native="menu"][data-native-props='${props}']`) + +describe("sidebar long-press menus", () => { + test("a channel row and a DM row each carry their own menu as the system's long-press menu", () => { + Scene.scene( + { update, view }, + Scene.given(sidebar), + // Each row's dots trigger focuses itself on press. + triggerMounted, + triggerMounted, + Scene.expectAll(Scene.all.selector('[data-native="context-menu"]')).toHaveCount(2), + Scene.expectAll(rowsWith(channelMenu)).toHaveCount(1), + Scene.expectAll(rowsWith(dmMenu)).toHaveCount(1), + // One menu, two triggers: the dots carry exactly the same items. + Scene.expectAll(dotsWith(channelMenu)).toHaveCount(1), + Scene.expectAll(dotsWith(dmMenu)).toHaveCount(1), + ) + }) +}) diff --git a/apps/web-foldkit/src/shell/channels-sidebar/menus.ts b/apps/web-foldkit/src/shell/channels-sidebar/menus.ts index ed2e53f12..7c4bafc80 100644 --- a/apps/web-foldkit/src/shell/channels-sidebar/menus.ts +++ b/apps/web-foldkit/src/shell/channels-sidebar/menus.ts @@ -1,6 +1,6 @@ import type { ChannelSectionId } from "@hazel/schema" import { Array, Option, Schema } from "effect" -import type { ChildAttribute, Html, HtmlBuilder } from "foldkit/html" +import type { Attribute, ChildAttribute, Html, HtmlBuilder } from "foldkit/html" import { IconCirclePlus, IconClose, @@ -17,7 +17,7 @@ import { } from "../../icons" import { button } from "../../ui/button" import * as Menu from "../../ui/menu" -import { menuLabel, view as menuView } from "../../ui/menu-view" +import { longPressMenu, menuLabel, view as menuView } from "../../ui/menu-view" import { SectionAction } from "./model" import type { ChannelEntry, Section, SidebarMember } from "./rows" @@ -205,24 +205,32 @@ const rowMenuContent = return section ? [text(section.name)] : [] } +type RowMenuOptions = Readonly<{ + menu: Menu.Model + entry: ChannelEntry + sections: ReadonlyArray
+ canDelete: boolean + toMessage: (message: Menu.Message) => M +}> + +/** A channel row's menu, which its dots trigger and a long press on the row both open. */ +const rowMenu = (options: RowMenuOptions) => ({ + entries: rowMenuEntries(options.sections, options.canDelete, options.entry.member), + native: { symbols: rowSymbols(options.entry.member) }, +}) + +/** A long press on a channel row opens its menu as the system's (iOS). */ +export const rowLongPress = (h: HtmlBuilder, options: RowMenuOptions): ReadonlyArray> => + longPressMenu(h, { menu: options.menu, ...rowMenu(options), toParentMessage: options.toMessage }) + /** `ChannelItem`'s ``: the dots trigger and `MenuContent placement="right top" className="w-42"`. */ -export const rowMenuView = ( - h: HtmlBuilder, - options: Readonly<{ - menu: Menu.Model - entry: ChannelEntry - sections: ReadonlyArray
- canDelete: boolean - toMessage: (message: Menu.Message) => M - }>, -): Html => +export const rowMenuView = (h: HtmlBuilder, options: RowMenuOptions): Html => h.submodel({ slotId: options.menu.id, model: options.menu, view: menuView, viewInputs: { - entries: rowMenuEntries(options.sections, options.canDelete, options.entry.member), - native: { symbols: rowSymbols(options.entry.member) }, + ...rowMenu(options), toTrigger: rowMenuTrigger( h, options.entry.channel.type === "single" || options.entry.channel.type === "direct" @@ -237,23 +245,31 @@ export const rowMenuView = ( toParentMessage: options.toMessage, }) +type DmMenuOptions = Readonly<{ + menu: Menu.Model + channelId: string + member: SidebarMember + toMessage: (message: Menu.Message) => M +}> + +/** A DM row's menu, which its dots trigger and a long press on the row both open. */ +const dmMenu = (options: DmMenuOptions) => ({ + entries: dmMenuEntries(options.member), + native: { symbols: rowSymbols(options.member) }, +}) + +/** A long press on a DM row opens its menu as the system's (iOS). */ +export const dmLongPress = (h: HtmlBuilder, options: DmMenuOptions): ReadonlyArray> => + longPressMenu(h, { menu: options.menu, ...dmMenu(options), toParentMessage: options.toMessage }) + /** `DmChannelItem`'s ``: Mute, Favorite and Hide conversation, on the same dots trigger. */ -export const dmMenuView = ( - h: HtmlBuilder, - options: Readonly<{ - menu: Menu.Model - channelId: string - member: SidebarMember - toMessage: (message: Menu.Message) => M - }>, -): Html => +export const dmMenuView = (h: HtmlBuilder, options: DmMenuOptions): Html => h.submodel({ slotId: options.menu.id, model: options.menu, view: menuView, viewInputs: { - entries: dmMenuEntries(options.member), - native: { symbols: rowSymbols(options.member) }, + ...dmMenu(options), toTrigger: rowMenuTrigger(h, "Conversation options"), content: (key: string): ReadonlyArray => { const text = (value: string, className?: string) => diff --git a/apps/web-foldkit/src/shell/channels-sidebar/view.ts b/apps/web-foldkit/src/shell/channels-sidebar/view.ts index db467d68b..9821d4314 100644 --- a/apps/web-foldkit/src/shell/channels-sidebar/view.ts +++ b/apps/web-foldkit/src/shell/channels-sidebar/view.ts @@ -7,7 +7,7 @@ import { AppRoute, hrefOf } from "../../route" import { sidebarItem, sidebarLink } from "../../ui/sidebar" import type * as Menu from "../../ui/menu" import { canOn, openRowMenu } from "./menu-update" -import { closedRowMenu, dmMenuView, rowMenuView } from "./menus" +import { closedRowMenu, dmLongPress, dmMenuView, rowLongPress, rowMenuView } from "./menus" import { Message, type Model } from "./model" import { createChannelHint } from "./create-channel-hint" import { hotkeyLabel } from "./hotkey-label" @@ -124,8 +124,16 @@ const channelRowView = ( toParentMessage: (message: Message) => M, threads: ReadonlyArray, activeThreadId: ChannelId | null, -): Html => - treeRow(h, { +): Html => { + const menu = { + menu: openMenu ?? closedRowMenu(entry.channel.id), + canDelete, + entry, + sections, + toMessage: (message: Menu.Message) => + toParentMessage(Message.GotRowMenuMessage({ channelId: entry.channel.id, orgSlug, message })), + } + return treeRow(h, { onActiveMount, treeId, key: entry.channel.id, @@ -139,19 +147,12 @@ const channelRowView = ( notificationCount, partners, { orgSlug, isActive: isLinkActive }, - rowMenuView(h, { - menu: openMenu ?? closedRowMenu(entry.channel.id), - canDelete, - entry, - sections, - toMessage: (message) => - toParentMessage( - Message.GotRowMenuMessage({ channelId: entry.channel.id, orgSlug, message }), - ), - }), + rowMenuView(h, menu), + rowLongPress(h, menu), ), children: threadItems(h, threads, activeThreadId, orgSlug), }) +} /** Favorites render `ChannelItem` without `partnerOrgs`, so they never show the shared-org badge. */ const channelRow = ( @@ -206,8 +207,15 @@ const dmRowView = ( onActiveMount: Attribute | null, openMenu: Menu.Model | null, toParentMessage: (message: Message) => M, -): Html => - treeRow(h, { +): Html => { + const menu = { + menu: openMenu ?? closedRowMenu(channel.id), + channelId: channel.id, + member: channel.currentUser, + toMessage: (message: Menu.Message) => + toParentMessage(Message.GotRowMenuMessage({ channelId: channel.id, orgSlug, message })), + } + return treeRow(h, { onActiveMount, treeId, key: channel.id, @@ -220,15 +228,11 @@ const dmRowView = ( channel, notificationCount, { orgSlug, isActive: isLinkActive, currentUserId, nowMs, presence }, - dmMenuView(h, { - menu: openMenu ?? closedRowMenu(channel.id), - channelId: channel.id, - member: channel.currentUser, - toMessage: (message) => - toParentMessage(Message.GotRowMenuMessage({ channelId: channel.id, orgSlug, message })), - }), + dmMenuView(h, menu), + dmLongPress(h, menu), ), }) +} /** A `DmChannelItem` renders nothing until its channel and the user's membership load. */ const dmRow = ( diff --git a/apps/web-foldkit/src/ui/menu-long-press.scene.test.ts b/apps/web-foldkit/src/ui/menu-long-press.scene.test.ts new file mode 100644 index 000000000..9b5dd88ce --- /dev/null +++ b/apps/web-foldkit/src/ui/menu-long-press.scene.test.ts @@ -0,0 +1,71 @@ +// @vitest-environment jsdom +import * as Scene from "foldkit/scene" +import type { HtmlBuilder } from "foldkit/html" +import { describe, test } from "vitest" +import { type Entry, init, item, leaf, type Message, type Model, separator, update } from "./menu" +import type { NativeMenuItem } from "../platform/native-island" +import { longPressMenu } from "./menu-view" + +/** `longPressMenu`: a row carries its menu's own entries as the system's long-press menu. */ + +const entries: ReadonlyArray = [ + item("mute", { textValue: "Mute" }), + item("move", { textValue: "Move to", submenu: [leaf("a", { textValue: "Section A" })] }), + separator, + item("leave", { textValue: "Leave", intent: "Danger" }), +] + +const viewOf = (rowEntries: ReadonlyArray) => (model: Model, h: HtmlBuilder) => + h.div( + [ + h.Id("row"), + ...longPressMenu(h, { + menu: model, + entries: rowEntries, + native: { symbols: { mute: "bell.slash" } }, + toParentMessage: (message) => message, + }), + ], + ["#support"], + ) + +const row = Scene.selector("#row") + +const MUTE = { key: "mute", label: "Mute", symbol: "bell.slash" } +const LEAVE = { key: "leave", label: "Leave", destructive: true } +const propsWith = (sectionA: NativeMenuItem) => + JSON.stringify({ + items: [MUTE, { label: "Move to", items: [sectionA] }, { separator: true }, LEAVE], + }) + +describe("long-press menu scene", () => { + test("a row carries its menu's entries, words and symbols as a context-menu island", () => { + Scene.scene( + { update, view: viewOf(entries) }, + Scene.given(init({ id: "row-menu" })), + Scene.expect(row).toHaveAttr("data-native", "context-menu"), + Scene.expect(row).toHaveHandler("change"), + Scene.expect(row).toHaveAttr("data-native-props", propsWith({ key: "a", label: "Section A" })), + ) + }) + + test("the system menu's choice is the menu's own: a single-select menu checks it", () => { + Scene.scene( + { update, view: viewOf(entries) }, + Scene.given(init({ id: "row-menu", selectionMode: "Single" })), + Scene.change(row, "a"), + Scene.expect(row).toHaveAttr( + "data-native-props", + propsWith({ key: "a", label: "Section A", checked: true }), + ), + ) + }) + + test("a menu whose entries are not all words gets no long-press menu", () => { + Scene.scene( + { update, view: viewOf([item("mute"), item("leave", { textValue: "Leave" })]) }, + Scene.given(init({ id: "row-menu" })), + Scene.expect(row).not.toHaveAttr("data-native"), + ) + }) +}) diff --git a/apps/web-foldkit/src/ui/menu-view.ts b/apps/web-foldkit/src/ui/menu-view.ts index a09dc252c..b0b309fb3 100644 --- a/apps/web-foldkit/src/ui/menu-view.ts +++ b/apps/web-foldkit/src/ui/menu-view.ts @@ -1,6 +1,7 @@ import { Array, Effect, Option, Queue, Schema, Stream } from "effect" import { Mount, Submodel } from "foldkit" import { + type Attribute, type ChildAttribute, childAttributes, type Html, @@ -26,7 +27,7 @@ import { } from "~/components/ui/menu.styles" import { popoverContentBase, popoverInnerClassName } from "~/components/ui/popover.styles" import { IconCheck, IconChevronRight } from "../icons" -import { type NativeMenuLook, nativeIsland } from "../platform/native-island" +import { type NativeMenuLook, nativeContextMenu, nativeIsland } from "../platform/native-island" import { playFeedback } from "../platform/feedback" import { dismissButton, focusScopeSentinel, openModalPopover, positionOverlay } from "./aria/overlay" import { Placement } from "./aria/placement" @@ -305,6 +306,28 @@ export const view = Submodel.defineView((model, view ) }) +/** + * A long press on the element (a row) opens this menu's `entries` as the system's context menu, + * where the shell has one (iOS): the same menu a "⋯" trigger opens, so a choice comes back as the + * same `ChoseFromNativeMenu`. Nothing where the entries are not all words, and nothing in a browser. + */ +export const longPressMenu = ( + h: HtmlBuilder, + options: Readonly<{ + menu: Model + entries: ReadonlyArray + native?: NativeMenuLook + toParentMessage: (message: Message) => ParentMessage + }>, +): ReadonlyArray> => + Option.match(nativeMenuItems(options.menu, options.entries, options.native), { + onNone: () => [], + onSome: (items) => + nativeContextMenu(h, { items }, (key) => + options.toParentMessage(Message.ChoseFromNativeMenu({ key, entries: options.entries })), + ), + }) + /** `ContextMenu` + `ContextMenuTrigger` + `ContextMenuContent`; init the Model with `anchor: "Pointer"`. */ export const contextMenuView = Submodel.defineView((model, viewInputs, h) => { const triggerAttributes = childAttributes([