Context menu
A list of actions that opens at the pointer when the visitor right-clicks an element.
Result
use hypersig::html::{Role, div, each, li, p, ul};
use hypersig::style::Style;
use hypersig::style::pattern::stack;
use hypersig::style::value::{BorderStyle, px, raw, rem};
use hypersig::{Expr, Page, Sig, Signals};
use hypersig_ui::{ContextMenu, MenuItem, token};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize, Clone, PartialEq)]
pub(super) struct Message {
author: String,
text: String,
}
#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Chat {
messages: Vec<Message>,
/// The author of the message whose menu is open.
picked: String,
status: String,
}
hypersig::node_ref!(const MESSAGE_ACTIONS: NodeRef<Chat>);
const MESSAGE_MENU: ContextMenu<Chat> = ContextMenu::new(MESSAGE_ACTIONS);
/// `before`, the author `picked` names, and `after`, which English and
/// Japanese put on different sides of the name.
fn said(site: Site, picked: Sig<Chat, String>, before: L<&str>, after: L<&str>) -> Expr<Chat, String> {
Expr::lit(&site.t(before).to_owned()).concat(picked).concat(site.t(after))
}
pub(super) fn page() -> Page<Chat> {
let picked = Chat::picked();
let status = Chat::status();
let message = |author: &str, text: L<&str>| Message {
author: author.to_owned(),
text: site.t(text).to_owned(),
};
let initial = Chat {
messages: vec![
message(
"Ada",
L {
en: "The build is green again.",
ja: "ビルドがまた通るようになりました。",
},
),
message(
"Grace",
L {
en: "Thanks, I'll tag the release.",
ja: "ありがとう。リリースのタグを付けます。",
},
),
],
picked: String::new(),
status: String::new(),
};
Page::new(
"Chat",
initial,
)
.child(
div()
.css(stack(rem(1)))
.child(p().text("Right-click a message."))
.child(
ul().css(stack(rem(0.5)).padding(px(0)).margin(px(0)))
.child(each(Chat::messages(), |message| {
li().css(
Style::new()
.list_style_type(raw("none"))
.padding(rem(0.5))
.border_width(px(1))
.border_style(BorderStyle::Solid)
.border_color(token::border().var())
.border_radius(px(6)),
)
.bind_text(message.at(Message::author()).concat(": ").concat(message.at(Message::text())))
.on_context_menu(move |at| {
picked
.set(message.at(Message::author()))
.then(MESSAGE_MENU.open_at(at))
})
})),
)
.child(MESSAGE_MENU.menu(
"Message",
[
MenuItem::new(
"Reply",
status.set(said(site, picked, L { en: "Replying to ", ja: "" }, L { en: ".", ja: " さんに返信します。" })),
),
MenuItem::new(
"Delete",
status.set(said(
site,
picked,
L { en: "Deleted the message from ", ja: "" },
L { en: ".", ja: " さんのメッセージを削除しました。" },
)),
)
.destructive(),
],
))
.child(p().role(Role::Status).bind_text(status)),
)
}Accessibility
The menu has role="menu", named by the label it is built with, and each action role="menuitem", as in a Menu. It is a popover="auto", so the browser shows it above the page and closes it on Escape or on a click outside. When it opens, focus moves to the first action that is not disabled, and when it closes, focus returns to the element that had it.
| Key or pointer | What it does |
|---|---|
| Right click | Opens the menu at the pointer. Opening it while it is open moves it |
| Shift+F10, the menu key | Opens the menu at the bottom left corner of the focused element, in a browser that sends the event from a key, such as Chrome |
| Down, Up | Moves to the next or previous action, skipping disabled ones |
| Home, End | Moves to the first or last action |
| Enter, Space | Runs the action and closes the menu |
| Escape, Tab, Shift+Tab | Closes the menu |
Safari and the web view of macOS send no context menu event from a key, so there a visitor without a pointer cannot open the menu. Give its actions another way in as well, such as a Menu button on each row.
Building a context menu
A ContextMenu<S> is a Copy handle built from a NodeRef<S>, declared as a const, as Handles covers. Its actions are the MenuItem<S> values a Menu takes. An element opens it from El::on_context_menu, whose statement receives where the visitor asked, as an Expr<S, Point>:
impl<S> ContextMenu<S> {
pub const fn new(menu: NodeRef<S>) -> Self;
pub fn open_at(self, at: impl IntoExpr<S, Point>) -> Stmt<S>;
pub fn menu(self, label: impl Into<String>, items: impl IntoIterator<Item = MenuItem<S>>) -> El<S>;
}
impl<S> El<S> {
pub fn on_context_menu<B: IntoStmt<S>>(self, handle: impl FnOnce(Expr<S, Point>) -> B) -> Self;
}| Item | What it does |
|---|---|
on_context_menu | Runs the statement when the visitor asks for a context menu inside the element, and keeps the browser's own menu from showing. Only the innermost element with a handler runs it |
open_at | A statement that opens the menu with its top left corner at at, or left of it or above it where the menu would cross the viewport's edge |
menu | The menu, named label for a screen reader, holding items in order. Place it once on the page |
One menu serves every row of a list. The row's statement first sets a signal that says which row it is, then opens the menu, and each action reads that signal. The position is a Point, so a Sig<S, Point> can also keep it.
What fails to compile
open_at takes an Expr<S, Point> or something that converts to one, so a signal of another type is E0308:
use hypersig::html::li;
use hypersig::{NodeRef, Signals};
use hypersig_ui::ContextMenu;
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Chat {
picked: i32,
}
hypersig::node_ref!(const MESSAGE_ACTIONS: NodeRef<Chat>);
const MESSAGE_MENU: ContextMenu<Chat> = ContextMenu::new(MESSAGE_ACTIONS);
// `open_at` takes a position, and `picked` is an `i32`.
let row = li().on_context_menu(|_| MESSAGE_MENU.open_at(Chat::picked()));The actions take impl IntoStmt<S>, so a statement of another page is E0308, and ContextMenu::new takes a NodeRef, so a DialogRef is E0308.
What is not checked
One handle's menu placed twice on a page makes Page::render panic with two elements carry the node ref … where the runtime can reach both. An open_at with no menu on the page writes a warning to the browser's console, and the browser shows no menu at all, because on_context_menu keeps its own from showing.
Example: message actions
Each message sets picked to its id and opens the one menu, whose actions set a status:
use hypersig::html::{Role, each, li, p, ul};
use hypersig::{NodeRef, Page, Signals};
use hypersig_ui::{ContextMenu, MenuItem};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize, Clone, PartialEq)]
struct Message {
id: i32,
text: String,
}
#[derive(Signals, Serialize, Deserialize)]
struct Chat {
messages: Vec<Message>,
picked: i32,
status: String,
}
hypersig::node_ref!(const MESSAGE_ACTIONS: NodeRef<Chat>);
const MESSAGE_MENU: ContextMenu<Chat> = ContextMenu::new(MESSAGE_ACTIONS);
let picked = Chat::picked();
let status = Chat::status();
let chat = Chat {
messages: vec![Message { id: 1, text: "The build is green again.".to_owned() }],
picked: 0,
status: String::new(),
};
let html = Page::new("Chat", chat)
.child(ul().child(each(Chat::messages(), |message| {
li().bind_text(message.at(Message::text())).on_context_menu(move |at| {
picked.set(message.at(Message::id())).then(MESSAGE_MENU.open_at(at))
})
})))
.child(MESSAGE_MENU.menu(
"Message",
[
MenuItem::new("Reply", status.set("Replying.")),
MenuItem::new("Delete", status.set("Deleted the message.")).destructive(),
],
))
.child(p().role(Role::Status).bind_text(status))
.render();