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
12 changes: 6 additions & 6 deletions apps/native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<emoji>` |
| 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:<emoji>` |

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.
Expand Down
100 changes: 47 additions & 53 deletions apps/native/host/ios/src/context_menu.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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<UIAction> {
let island = island.clone();
let handler = RcBlock::new(move |_: NonNull<UIAction>| 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,
Expand All @@ -152,53 +155,44 @@ fn inline(mtm: MainThreadMarker, children: Vec<Retained<UIMenuElement>>) -> 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<UIMenu> {
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<Retained<UIMenuElement>> = Vec::new();
let prefix = text(props, "reactionPrefix").unwrap_or_default();
let reactions: Vec<Retained<UIMenuElement>> = 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<Retained<UIMenuElement>> = 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<Retained<UIMenuElement>> = 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(&sections), mtm)
}
Expand Down
17 changes: 10 additions & 7 deletions apps/native/host/ios/src/islands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -238,16 +236,13 @@ fn menu_of(mtm: MainThreadMarker, spec: &IslandSpec) -> Retained<UIMenu> {
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<Retained<UIMenuElement>> {
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();
Expand All @@ -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,
Expand Down
36 changes: 36 additions & 0 deletions apps/web-foldkit/src/page/chat/channel/messages.scene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 11 additions & 8 deletions apps/web-foldkit/src/page/chat/overlays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,19 +285,22 @@ export const moreMenuEntries = (facts: MessageFacts): ReadonlyArray<Menu.Entry>
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.Entry> => [
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. */
Expand Down
Loading
Loading