このページは機械翻訳のため、誤りを含む場合があります。 英語の原文を読む

要素

NavStack

ナビゲーションスタックは一度に1ページを表示し、その下のページを保持します。iOS と Mac Catalyst では UINavigationController を使い、システムヘッダーとスワイプバックを備えます。Android ではツールバーと予測型戻る操作を備えたページのスタックになります。 デスクトップ (macOS、Windows、Linux、GPUI) と Web では、各ページが上部にアプリ独自のヘッダーを表示し、戻るキーとブラウザーの戻るボタンでページが取り除かれます。NavStack がスタックで、NavPage がそのページの1つです。

ui-navigation.tsx
ui-navigation.tsxLive
// Navigation: a stack of pages with header options, pushed and popped; in a
// wide window the inbox and the open message side by side (master–detail).
import { type JSX, mount, signal, Text, View } from "nsh";
import { createNavStack, NavPage, NavStack } from "nsh/base";
import { button, buttonText, focusRing, hoverFill, size, tint, ui, wide } from "./palette";

function Button(props: { title: string; variant?: "primary" | "secondary"; onPress: () => void }) {
  const kind = () => (props.variant !== "secondary" ? "primary" : "secondary");
  return (
    <View role="button" onPress={props.onPress} {...button(kind())}>
      <Text style={buttonText(kind())}>{props.title}</Text>
    </View>
  );
}

type Route = { name: "home" } | { name: "detail"; id: number };

const nav = createNavStack<Route>([{ name: "home" }]);

// The page's own header where NSH draws none (the web, the desktops); iOS and
// Android show the system's, from `title` and `headerRight`.
function Header(props: { title: string; right?: JSX.Element }) {
  return (
    <View style={{ backgroundColor: ui().page, borderBottomWidth: 1, borderBottomColor: ui().line }} class="h-12 flex-row items-center px-2">
      <View class="w-20 flex-row">
        <If when={nav.routes().length > 1}>
          <View role="button" accessibilityLabel="Back" onPress={() => nav.pop()} hoverStyle={hoverFill()} focusStyle={focusRing()} class="rounded-md px-2 py-1 active:opacity-60">
            <Text style={{ fontSize: 17, color: ui().accent }}>‹ Back</Text>
          </View>
        </If>
      </View>
      <Text style={{ numberOfLines: 1, fontSize: 17, fontWeight: "600", color: ui().text }} class="flex-1 text-center">
        {props.title}
      </Text>
      <View class="w-20 flex-row justify-end px-2">{props.right}</View>
    </View>
  );
}

// A page's content: a column as wide as a phone, centered in a wider window.
function Body(props: { children: JSX.Element }) {
  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 16, paddingTop: 24 }}>
      <View style={{ width: "100%", maxWidth: 480, alignSelf: "center", gap: 12 }}>{props.children}</View>
    </View>
  );
}

function Home() {
  const opened = signal(0);
  return (
    <NavPage title="Inbox" header={<Header title="Inbox" />}>
      <Body>
        <Text style={{ color: ui().muted }}>{`Opened ${opened()} messages`}</Text>
        <Button
          title="Open message 1"
          onPress={() => {
            opened.set(opened() + 1);
            nav.push({ name: "detail", id: 1 });
          }}
        />
        <Button title="Open message 2" variant="secondary" onPress={() => nav.push({ name: "detail", id: 2 })} />
      </Body>
    </NavPage>
  );
}

function Detail(props: { id: number }) {
  const starred = signal(false);
  const star = () => (
    <Text onPress={() => starred.set(!starred())} style={{ fontSize: 17, color: ui().accent }} hoverStyle={hoverFill()} focusStyle={focusRing()} activeStyle={{ opacity: 0.7 }}>
      {starred() ? "★" : "☆"}
    </Text>
  );
  return (
    <NavPage title={`Message ${props.id}`} headerRight={star()} header={<Header title={`Message ${props.id}`} right={star()} />}>
      <Body>
        <Text style={{ color: ui().text }}>{`The body of message ${props.id}.`}</Text>
        <Button title="Next message" onPress={() => nav.push({ name: "detail", id: props.id + 1 })} />
        <Button title="Back to the inbox" variant="secondary" onPress={() => nav.popToRoot()} />
      </Body>
    </NavPage>
  );
}

const messages = [1, 2, 3, 4, 5, 6];

/** A wide window: the inbox on the start side, the selected message beside it. */
function Inbox() {
  const selected = signal(1);
  const starred = signal<number[]>([]);
  const star = (id: number) => (
    <Text
      onPress={() => starred.set(starred().includes(id) ? starred().filter((s) => s !== id) : [...starred(), id])}
      style={{ fontSize: 17, color: ui().accent }}
      hoverStyle={hoverFill()}
      focusStyle={focusRing()}
      activeStyle={{ opacity: 0.7 }}
    >
      {starred().includes(id) ? "★" : "☆"}
    </Text>
  );
  return (
    <View style={{ flex: 1, flexDirection: "row", backgroundColor: ui().page }}>
      <View style={{ width: 320, borderRightWidth: 1, borderRightColor: ui().line }}>
        <Header title="Inbox" />
        <View style={{ padding: 8, gap: 2 }}>
          <Each of={messages}>
            {(id) => (
              <View
                role="button"
                onPress={() => selected.set(id())}
                hoverStyle={selected() === id() ? undefined : hoverFill()}
                style={{
                  height: size.row + 12,
                  paddingHorizontal: 12,
                  borderRadius: 8,
                  justifyContent: "center",
                  gap: 2,
                  backgroundColor: selected() === id() ? tint(ui().accent, 0.14) : "transparent",
                }}
                focusStyle={focusRing()}
                activeStyle={{ opacity: 0.7 }}
              >
                <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
                  <Text style={{ flex: 1, fontSize: size.label, fontWeight: "600", color: ui().text }}>{`Message ${id()}`}</Text>
                  <Text style={{ fontSize: 12, color: ui().accent }}>{starred().includes(id()) ? "★" : ""}</Text>
                </View>
                <Text style={{ numberOfLines: 1, fontSize: 12, color: ui().muted }}>{`The body of message ${id()}.`}</Text>
              </View>
            )}
          </Each>
        </View>
      </View>
      <View style={{ flex: 1, minWidth: 0 }}>
        <Header title={`Message ${selected()}`} right={star(selected())} />
        <View style={{ padding: 24, gap: 12 }}>
          <Text style={{ color: ui().text }}>{`The body of message ${selected()}.`}</Text>
          <Text style={{ fontSize: 13, color: ui().muted }}>Click a message on the left; on a phone it opens as a page of a NavStack.</Text>
          <Button title="Next message" onPress={() => selected.set(selected() === messages.length ? 1 : selected() + 1)} />
        </View>
      </View>
    </View>
  );
}

function App() {
  return (
    <>
      {() =>
        wide() ? (
          <Inbox />
        ) : (
          <NavStack state={nav} style={{ flex: 1 }}>
            {(route) => (route.name === "home" ? <Home /> : <Detail id={route.id} />)}
          </NavStack>
        )
      }
    </>
  );
}

mount(App);

スタックはナビゲーションの動作 (遷移、戻るジェスチャーとボタン、覆われている間のページの状態) を担います。ページの内容とデスクトップのヘッダーはアプリ側のものです。

use nsh_base::{button, nav_page, nav_stack};
use nsh_core::prelude::*;

/// A button with the app's look.
fn action(title: &'static str, on_press: impl Fn() + 'static) -> impl IntoElement {
    button()
        .on_press(on_press)
        .rounded_lg()
        .bg(rgb(0x2563eb))
        .px_4()
        .py_3()
        .child(text(title).text_color(white()).font_weight(FontWeight::SEMIBOLD))
}

/// The header on the desktops and the web, with a back button over the first page.
fn bar(title: impl Into<SharedString>, routes: Signal<Vec<u32>>) -> impl IntoElement {
    view()
        .flex_row()
        .items_center()
        .gap_3()
        .px_4()
        .py_3()
        .border_b_1()
        .border_color(rgb(0xe5e5e5))
        .child(when(
            move || !routes.with(Vec::is_empty),
            move || {
                action("Back", move || {
                    routes.update(|r| {
                        r.pop();
                    })
                })
            },
        ))
        .child(text(title.into()).text_lg().font_weight(FontWeight::SEMIBOLD))
}

fn app() -> impl IntoElement {
    // The messages pushed over the inbox, bottom to top.
    let routes = signal(Vec::<u32>::new());
    nav_stack()
        .flex_1()
        .child(
            nav_page()
                .title("Inbox")
                .header(bar("Inbox", routes))
                .child(view().flex_1().p_4().child(action("Open message 1", move || {
                    routes.update(|r| r.push(1))
                }))),
        )
        .child(each(
            move || routes.get(),
            |id: &u32| *id,
            move |id, depth| {
                let title: SharedString = format!("Message {}", id.get_untracked()).into();
                nav_page()
                    .title(title.clone())
                    .header(bar(title, routes))
                    // The user went back natively: this page and those above it are gone.
                    .on_dismiss(move || routes.update(|r| r.truncate(depth.get_untracked())))
                    .child(view().flex_1().p_4().child(text("The message.")))
            },
        ))
}

iOS と Android では、ページは title と戻るボタンを持つシステムヘッダーを表示します。デスクトップと Web では header を表示します。スマートフォンのみを対象とするアプリでは header を省略し、デスクトップのみを対象とするアプリではシステムヘッダーのオプションを省略します。ナビゲーションガイドでは、アプリ全体のナビゲーション (スタックの状態、ダイアログ、Android の戻るボタン、タブ) を順に説明しています。

#スタックの仕組み

  • スタックのページは ルート です。ルートは任意の値で、スタックの最下部から最上部の順に並びます。通常、ルートはページを指す名前とそのパラメーターを持ちます。
  • TSX では、ルートは createNavStack が作る状態に保持されます。NavStack は push ごとに子関数を1回呼び出し、その結果をページとして表示します。ルートがスタックにある間はそのページを保持するため、他のページに覆われていてもページの状態 (シグナル、スクロール位置、入力) は維持されます。
  • Rust では、スタックの子がそのページです。nav_stack() に入れた nav_page() は push され、外したものは pop されます。ルートはシグナルに保持し、下にあるページが状態を保てるよう、ルートをキーにして each(..) でページを描画します。
  • push ごとに独立したページになります。同じルート値を2回 push した場合も同様です。
  • ユーザーがネイティブの操作でページを離れると (戻るボタン、スワイプバック、Android の戻る、デスクトップの戻るキー、ブラウザーの戻る)、そのページは取り除かれます。TSX ではスタックが状態からそのルートを削除するため、nav.routes() は常にユーザーが見ているものと一致します。Rust ではページが on_dismiss を通知するので、そこでルート (とその上のルート) を削除します。
  • TSX では、子関数が <NavPage> 以外を返した場合、既定のオプションを持つページになります。ヘッダーなどのオプションを設定するには <NavPage> を返してください。

#createNavStack

function createNavStack<R>(routes: R[]): NavStackState<R>

routes から始まるスタック (最下部から最上部の順) の状態を作成します。モジュールレベルなどで一度だけ作成し、<NavStack state> に渡してください。どのコードからもインポートしてナビゲートできます。

メンバー説明
routes: Accessor<readonly R[]>ルートの一覧 (最下部から最上部)。リアクティブです。
push(route: R): voidページを push します。
pop(count?: number): voidcount ページを pop します (既定は 1)。少なくとも1ページは常に残ります。
popToRoot(): void最初のページまで pop します。
replace(route: R): void最上部のページを置き換えます。
setRoutes(routes: R[]): voidページを置き換えます。残るルート (同じ値) は、そのページと状態を保持します。
remove(route: R): voidroute (=== で比較) に一致する最上位のページを、スタック内の位置にかかわらず削除します。

Rust では、同じ操作はルートのシグナルの変更で行います。routes.update(|r| r.push(route)) は push、r.pop() は pop、r.truncate(1) は保持している最初のページまで pop、routes.set(..) はページの置き換えです。

routes.update(|r| r.push(7));
routes.update(|r| r.truncate(r.len().saturating_sub(2)));
routes.set(vec![1, 2]);
let depth = move || routes.with(Vec::len);
プロパティRust型説明
stateページが子要素になるNavStackState<R>ルートを保持する状態 (createNavStack)。必須です。
children.child(..)(route: R, index: Accessor<number>) => JSX.Elementルートを描画します。オプションを指定するには <NavPage> を返します。必須です。
style、classスタイルメソッドスタックのスタイル。通常は flex: 1 です。
testID.test_id(..)stringテストと nsh test --trace でスタックを見つけます。

TSX の子関数は、ルートの値そのものと、スタック内での位置を返すアクセサーを受け取ります。

NavPage はスタックの1ページです。ページの内容、デスクトップと Web での header、iOS と Android でのシステムヘッダーのオプションを保持します。Rust では nav_page() がページを返し、そのビルダーメソッドはプロパティ名をスネークケースにしたものです。

プロパティRust型既定値説明
header.header(..)JSX.Elementなしデスクトップと Web: ページのヘッダー。ページの上部に、ページと同じ幅、レイアウトで決まる高さで配置され、その下に内容が続きます。
title.title(..)stringなしiOS と Android: システムヘッダーのタイトル。
headerVisible.header_visible(..)booleantrueiOS と Android: システムヘッダーを表示します。
headerTransparent.header_transparent(..)booleanfalseiOS と Android: 内容が透明なシステムヘッダーの下まで広がります。
hidesBottomBarWhenPushed.hides_bottom_bar_when_pushed(..)booleanfalseiOS: このページが最上部にある間、システムのタブバーが退場します。遷移の中でページと同じアニメーションで動き、バーが再構築されることはありません。ページが pop されると戻ってきます。
headerLargeTitle.header_large_title(..)booleanfalseiOS: 内容のスクロールに合わせてバーに縮小するラージタイトル。内容はヘッダーの下でスクロールします。
headerBackTitle.header_back_title(..)stringなしiOS と Android: このページに戻る戻るボタンのラベル (Android ではスクリーンリーダー向けの説明)。
headerBackVisible.header_back_visible(..)booleantrueiOS と Android: 戻るボタンを表示します。
headerLeft.header_left(..)JSX.ElementなしiOS と Android: 戻るボタンの代わりに、システムヘッダーの先頭側に置かれる内容。
headerRight.header_right(..)JSX.ElementなしiOS と Android: システムヘッダーの末尾側に置かれる内容。
headerTitle.header_title(..)JSX.ElementなしiOS と Android: タイトルの代わりに表示される内容。
headerStyle.header_style(..){ backgroundColor?, color?, tintColor? }プラットフォーム依存iOS と Android: システムヘッダーの色。背景、タイトル (color)、ボタン (tintColor) の色です。
headerClass.header_style_with(|s| ..)stringなし同じ色をクラスで指定します。bg-*、タイトル用の text-*、ボタン用の tint-* です (Rust では .bg(..)、.text_color(..)、.tint_color(..)。外観に追従するテーマカラー)。headerStyle が優先されます。
popOnBack.pop_on_back(..)booleantrue戻るボタンとスワイプバックでページを pop します。ページを離れるを参照してください。
popOnSwipe.pop_on_swipe(..)booleantrueインタラクティブな戻るジェスチャーでページを pop します。iOS ではスワイプバック、Android では指に追従する予測型戻る操作です。戻るボタンはどちらの設定でも pop します。
animation.animation(..)"default" | "slide" | "fade" | "none""default"ページの出入りの方法。
transitionShader.transition_shader(TransitionShader::new(program)){ source: string; uniforms?: Record<string, ShaderUniform>; duration?: number }なしanimation の代わりに、WGSL シェーダーでページが出入りします。shade(uv) は、下のページを sample_from、このページを sample_to として読み取ります。nsh.progress は duration ミリ秒 (既定は 350) かけて 0 から 1 に変化し、ページが退場するときは 1 から 0 に戻ります。システムが動きの軽減を求めている場合、ページは自身の animation を使います。Shaderを参照してください。
statusBar.status_bar(..){ foreground?, hidden?, animated? }なしiOS と Android: ページが最上部にある間のステータスバー。Status barを参照してください。
style、classスタイルメソッドなしページのスタイル。
children.child(..)JSX.Elementなし内容。
testID.test_id(..)stringなしテストと nsh test --trace でページを見つけます。
イベントRust説明
onBackPress.on_back_press(..)ユーザーがページで戻る操作をしました (ヘッダーの戻るボタン、Android の戻る、デスクトップでの Escape、Alt+Left、マウスの戻るボタン、ブラウザーの戻る)。popOnBack が pop を許可したかどうかにかかわらず発生します。
onDismiss.on_dismiss(..)ユーザーがページを pop しました (戻るボタン、スワイプ)。TSX ではそのルートはすでに削除されており、Rust ではここで削除します。

#ヘッダースロット

header、headerLeft、headerRight、headerTitle はスロットです。シグナルを読み取り、押下を処理し、ページの表示中に更新される通常の要素です。header はデスクトップと Web ではアプリのヘッダー全体になり、残りの3つは iOS と Android のシステムヘッダーに入ります。

use nsh_base::nav_page;
use nsh_core::prelude::*;

fn profile(edit: impl Fn() + 'static) -> Screen {
    nav_page()
        .title("Profile")
        .header(profile_bar())
        .header_style_with(|s| s.bg(rgb(0x1a7f37)).text_color(white()).tint_color(white()))
        .header_right(text("Edit").text_color(white()).on_press(move || edit()))
        .child(scroll().flex_1())
}

ページの内容はヘッダーの下から始まります。iOS と Android では不透明なシステムヘッダーの下、デスクトップと Web では header の下です。headerTransparent、headerLargeTitle、headerVisible={false} を使うと、iOS と Android では内容がページの最上部から始まります。ヘッダーとステータスバーを避けるには、env(safe-area-inset-top) または safeAreaInsets() を使ってください。

iOS では、headerVisible={false} は popOnSwipe と popOnBack が true の間、スワイプバックを有効に保ちます。インタラクティブな戻るジェスチャーが受理されると、遷移の開始とともに編集が終了するため、ドラッグ中にキーボードが閉じます。遷移をキャンセルすると、ほかのコントロールがフォーカスを取っていない場合に限り、同じエディターのフォーカスが復元されます。

nav_page()
    .title("Large title")
    .header_large_title(true)
    .child(scroll().flex_1())

#ページを離れる

popOnBack={false} は、たとえばフォームに未保存の変更があるときなどに、ユーザーをページにとどめます。false の間はスワイプバックが無効になり、戻るボタンとキーは pop せずに onBackPress を呼び出します。ユーザーに確認し、そのあとで自分で pop してください。

use nsh_base::{alert_dialog, nav_page};
use nsh_core::prelude::*;

fn edit_note(routes: Signal<Vec<u32>>) -> Screen {
    let note = signal(String::new());
    let confirm = move || {
        spawn(async move {
            let choice = alert_dialog()
                .title("Discard your changes?")
                .cancel("keep", "Keep editing")
                .destructive("discard", "Discard")
                .show()
                .await;
            if choice.is_ok_and(|r| r.action.as_deref() == Some("discard")) {
                routes.update(|r| {
                    r.pop();
                });
            }
        });
    };
    nav_page()
        .title("Edit")
        .pop_on_back(move || note.with(String::is_empty))
        .on_back_press(move || {
            if !note.with(String::is_empty) {
                confirm();
            }
        })
        .child(
            input()
                .value(note)
                .on_change(move |v: &str| note.set(v.to_owned()))
                .placeholder("A note"),
        )
}

onBackPress は、ページが pop される場合も含め、戻る操作のたびに呼び出されるため、ユーザーが戻ったことの通知にもなります。スワイプジェスチャーだけを無効にして戻るボタンは残すには、popOnSwipe={false} を使います。確認自体は AlertDialog で行います。

#プラットフォームごとの注意

  • iOS: システムヘッダー、戻るボタン、スワイプバックを備えた UINavigationController。headerLargeTitle は UIKit のラージタイトルです。遷移の実行中に届いたスタックの変更は、遷移の終了時に適用されます。
  • Android: ツールバー付きのスタックです。システムの戻るボタンで最上部のページが pop され、対応する Android バージョンでは予測型戻る操作が使われます。上矢印のスクリーンリーダー向けの説明は、下のページの headerBackTitle、またはシステムのものです。戻るボタンを自分で処理するには、BackHandler の BackHandler を参照してください。
  • Mac Catalyst: iOS と同じです。
  • デスクトップ (macOS、Windows、Linux、GPUI) と Web: 各ページは上部に header、その下に内容を表示します。デスクトップでは Escape、Alt+Left、マウスの戻るボタンで戻り、Web ではブラウザーの戻るボタンで戻ります。

シートやフルスクリーンのフローなど、スタックとそのヘッダーの上に表示する内容には、Dialog を使ってください。