English

コンテキストメニュー

訪問者が要素を右クリックしたとき、ポインタの位置に開く操作の一覧です。

実行結果

context_menu.rs
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(
        "チャット",
        initial,
    )
    .child(
        div()
            .css(stack(rem(1)))
            .child(p().text("メッセージを右クリックしてください。"))
            .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(
                "メッセージ",
                [
                    MenuItem::new(
                        "返信",
                        status.set(said(site, picked, L { en: "Replying to ", ja: "" }, L { en: ".", ja: " さんに返信します。" })),
                    ),
                    MenuItem::new(
                        "削除",
                        status.set(said(
                            site,
                            picked,
                            L { en: "Deleted the message from ", ja: "" },
                            L { en: ".", ja: " さんのメッセージを削除しました。" },
                        )),
                    )
                    .destructive(),
                ],
            ))
            .child(p().role(Role::Status).bind_text(status)),
    )
}

アクセシビリティ

メニューは作るときに渡したラベルを名前とする role="menu" を持ち、各操作は role="menuitem" を持ちます。ここは メニュー と同じです。メニューは popover="auto" なので、ブラウザがページの上に重ねて表示し、Escape か外側のクリックで閉じます。開くとフォーカスは無効でない最初の操作に移り、閉じるとフォーカスは開く前の要素に戻ります。

キーかポインタ動作
右クリックポインタの位置にメニューを開きます。開いている間にもう一度開くと、メニューが移ります
Shift+F10、メニューキーキーからイベントを送るブラウザ(Chrome など)では、フォーカスのある要素の左下にメニューを開きます
下矢印、上矢印次か前の操作に移ります。無効な操作は飛ばします
Home、End最初か最後の操作に移ります
Enter、Space操作を実行し、メニューを閉じます
Escape、Tab、Shift+Tabメニューを閉じます

Safari と macOS の Web ビューは、キーからはコンテキストメニューのイベントを送りません。そのため、そこではポインタを使わない訪問者はメニューを開けません。各行に メニュー のボタンを置くなど、同じ操作を別の方法でも使えるようにしてください。

コンテキストメニューを作る

ContextMenu<S> は NodeRef<S> から作る Copy のハンドルで、const として宣言します。宣言のしかたは ハンドル で説明しています。操作には メニュー と同じ MenuItem<S> を使います。メニューを開くのは El::on_context_menu で、その文は訪問者がメニューを求めた位置を 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;
}
項目動作
on_context_menu訪問者が要素の中でコンテキストメニューを求めたときに文を実行し、ブラウザ自身のメニューを出さないようにします。実行するのは、ハンドラを持つ要素のうち最も内側のものだけです
open_atメニューの左上を at に合わせて開く文。メニューがビューポートの端からはみ出すときは、at の左か上に開きます
menuitems を順に並べたメニュー。label はスクリーンリーダーが読み上げる名前です。ページに 1 回だけ置きます

1 つのメニューをリストのすべての行で使えます。行の文はどの行かを表すシグナルを先に設定してからメニューを開き、各操作はそのシグナルを読みます。位置は Point なので、Sig<S, Point> に入れておくこともできます。

コンパイルエラーになるもの

open_at は Expr<S, Point> か、それに変換できる値を受け取るので、ほかの型のシグナルを渡すと 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()));

操作は impl IntoStmt<S> を受け取るので、ほかのページの文を渡すと E0308 になります。ContextMenu::new は NodeRef を受け取るので、DialogRef を渡すと E0308 になります。

検査されないこと

1 つのハンドルの menu をページに 2 回置くと、Page::render が two elements carry the node ref … where the runtime can reach both というメッセージで panic します。ページにメニューがないまま open_at を実行すると、ブラウザのコンソールに警告が出ます。on_context_menu がブラウザ自身のメニューを止めるので、メニューは何も表示されません。

例: メッセージの操作

各メッセージは picked に自分の id を設定してから、1 つだけのメニューを開きます。メニューの操作は状態のテキストを設定します。

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();