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

要素

List

List は、長い、または上限のないデータを表示します。存在するのはビューポート付近の行だけで、ユーザーがスクロールすると、画面から出た行は新しく入ってくる行のために再利用されます。どの行が存在するか、その位置、列、スティッキーヘッダー、可視性(viewability)はすべてネイティブで計算されるため、数千項目のリストのスクロールも、20 項目のリストと同じコストで済みます。Rust では virtual_list(count, |at| row)、TSX では nsh の <List> で作成します。

el-list.tsx
el-list.tsxLive
import { List, type ListRef, mount, signal, Text, View } from "nsh";
import { button, buttonText, desktop, Inspector, Panel, size, tint, ui, wide } from "./palette";

type Trade = { id: string; symbol: string; shares: number; change: number };

const symbols = ["AAPL", "NVDA", "TSLA", "MSFT", "AMZN", "META", "GOOG", "AMD", "NFLX", "INTC"];
const LIMIT = 200;

// A page of made-up trades; ids keep counting so every row has its own key.
let next = 0;
const page = (n: number): Trade[] =>
  Array.from({ length: n }, () => {
    const i = next++;
    return { id: `t${i}`, symbol: symbols[(i * 7) % symbols.length], shares: 10 + ((i * 37) % 290), change: (((i * 53) % 200) - 100) / 10 };
  });

function App() {
  const trades = signal(page(40));
  const loading = signal(false);
  const loads = signal(0);
  const refreshing = signal(false);
  const visible = signal("");
  let list!: ListRef;

  const loadMore = () => {
    if (loading() || trades().length >= LIMIT) return;
    loading.set(true);
    setTimeout(() => {
      trades.set([...trades(), ...page(20)]);
      loads.update((n) => n + 1);
      loading.set(false);
    }, 600);
  };

  const refresh = () => {
    refreshing.set(true);
    setTimeout(() => {
      next = 0;
      trades.set(page(40));
      loads.set(0);
      refreshing.set(false);
    }, 800);
  };
  const viewable = ({ viewableItems }: { viewableItems: { index: number }[] }) =>
    visible.set(viewableItems.length ? `${viewableItems[0].index}–${viewableItems[viewableItems.length - 1].index}` : "");
  const toIndex = () => list.scrollToIndex({ index: Math.min(100, trades().length - 1), viewPosition: 0.5 });
  const toEnd = () => list.scrollToEnd({ animated: true });
  const status = () => (loading() ? "Loading 20 more…" : trades().length >= LIMIT ? "The end" : "");
  const changeColor = (t: Trade) => (t.change >= 0 ? ui().up : ui().down);

  // A phone: cards in one column, pull to refresh.
  const cards = () => (
    <View style={{ flex: 1, backgroundColor: ui().page, paddingTop: 24 }}>
      <View style={{ paddingHorizontal: 16, gap: 6, paddingBottom: 8 }}>
        <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>list</Text>
        <Text style={{ color: ui().muted }}>
          {trades().length} rows · onLoadMore {loads()}× · visible {visible()}
        </Text>
      </View>
      <List
        ref={list}
        testID="trades"
        each={trades()}
        keyExtractor={(t) => t.id}
        numColumns={1}
        estimatedItemSize={64}
        style={{ flex: 1 }}
        contentStyle={{ paddingHorizontal: 16, paddingTop: 4, paddingBottom: 16, gap: 8 }}
        onLoadMore={loadMore}
        loadMoreThreshold={0.5}
        refreshing={refreshing()}
        onRefresh={refresh}
        viewabilityConfig={{ itemVisibleThreshold: 0.5 }}
        onViewableItemsChange={viewable}
        header={
          <View style={{ ...ui().card, borderRadius: 14, padding: 14, gap: 10, marginBottom: 4 }}>
            <Text style={{ color: ui().muted }}>
              {desktop ? "Scroll with the wheel or trackpad" : "Swipe up; pull down to refresh"}: more rows load near the end, up to {LIMIT}.
            </Text>
            <View style={{ flexDirection: "row", gap: 8 }}>
              <Chip label="scrollToIndex 100" onPress={toIndex} />
              <Chip label="scrollToEnd" onPress={toEnd} />
            </View>
          </View>
        }
        footer={<Text style={{ color: ui().faint, textAlign: "center", paddingVertical: 16 }}>{status()}</Text>}
      >
        {(trade, index) => (
          <View style={{ ...ui().row, flex: 1, flexDirection: "row", alignItems: "center", gap: 12, padding: 14, borderRadius: 12 }}>
            <Text style={{ color: ui().faint, width: 32, fontVariant: ["tabular-nums"] }}>{index()}</Text>
            <View style={{ flex: 1 }}>
              <Text style={{ color: ui().text, fontWeight: "600" }}>{trade().symbol}</Text>
              <Text style={{ color: ui().muted, fontSize: 12 }}>
                {trade().shares} shares · key {trade().id}
              </Text>
            </View>
            <Text
              style={{
                color: changeColor(trade()),
                backgroundColor: tint(changeColor(trade()), 0.12),
                paddingHorizontal: 8,
                paddingVertical: 3,
                borderRadius: 6,
                overflow: "hidden",
                fontWeight: "600",
                fontVariant: ["tabular-nums"],
              }}
            >
              {trade().change >= 0 ? "+" : ""}
              {trade().change.toFixed(1)}%
            </Text>
          </View>
        )}
      </List>
    </View>
  );

  // A wide window: a table with fixed column lanes, its controls beside it.
  const cell = { fontSize: 13, fontVariant: ["tabular-nums" as const] };
  const lanes = { index: 48, shares: 88, key: 104, change: 88 };
  const table = () => (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>list</Text>
      <Text style={{ color: ui().muted }}>
        {desktop ? "Scroll with the wheel or trackpad" : "Swipe up"}: more rows load near the end, up to {LIMIT}.
      </Text>
      <View style={{ flex: 1, flexDirection: "row", gap: 16 }}>
        <View style={{ ...ui().card, flex: 1, minWidth: 0, borderRadius: 12, overflow: "hidden" }}>
          <View
            style={{
              flexDirection: "row",
              alignItems: "center",
              gap: 12,
              height: size.rowSm,
              paddingHorizontal: 12,
              borderBottomWidth: 1,
              borderBottomColor: ui().border,
              backgroundColor: ui().inset.backgroundColor,
            }}
          >
            <Text style={{ ...cell, width: lanes.index, textAlign: "right", fontSize: 12, fontWeight: "600", color: ui().muted }}>#</Text>
            <Text style={{ ...cell, flex: 1, fontSize: 12, fontWeight: "600", color: ui().muted }}>Symbol</Text>
            <Text style={{ ...cell, width: lanes.shares, textAlign: "right", fontSize: 12, fontWeight: "600", color: ui().muted }}>Shares</Text>
            <Text style={{ ...cell, width: lanes.key, paddingStart: 16, fontSize: 12, fontWeight: "600", color: ui().muted }}>Key</Text>
            <Text style={{ ...cell, width: lanes.change, textAlign: "right", fontSize: 12, fontWeight: "600", color: ui().muted }}>Change</Text>
          </View>
          <List
            ref={list}
            testID="trades"
            each={trades()}
            keyExtractor={(t) => t.id}
            estimatedItemSize={size.row}
            style={{ flex: 1 }}
            onLoadMore={loadMore}
            loadMoreThreshold={0.5}
            refreshing={refreshing()}
            onRefresh={refresh}
            viewabilityConfig={{ itemVisibleThreshold: 0.5 }}
            onViewableItemsChange={viewable}
            footer={<Text style={{ color: ui().faint, fontSize: 13, textAlign: "center", paddingVertical: 12 }}>{status()}</Text>}
          >
            {(trade, index) => (
              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  gap: 12,
                  height: size.row - 4,
                  paddingHorizontal: 12,
                  borderBottomWidth: 1,
                  borderBottomColor: ui().line,
                }}
              >
                <Text style={{ ...cell, width: lanes.index, textAlign: "right", color: ui().faint }}>{index()}</Text>
                <Text style={{ ...cell, flex: 1, fontWeight: "600", color: ui().text }}>{trade().symbol}</Text>
                <Text style={{ ...cell, width: lanes.shares, textAlign: "right", color: ui().text }}>{trade().shares}</Text>
                <Text style={{ ...cell, width: lanes.key, paddingStart: 16, color: ui().muted }}>{trade().id}</Text>
                <Text style={{ ...cell, width: lanes.change, textAlign: "right", fontWeight: "600", color: changeColor(trade()) }}>
                  {trade().change >= 0 ? "+" : ""}
                  {trade().change.toFixed(1)}%
                </Text>
              </View>
            )}
          </List>
        </View>
        <Inspector>
          <Panel title="rows · onLoadMore · visible">
            <Text style={{ fontSize: 13, color: ui().text, fontVariant: ["tabular-nums"] }}>
              {trades().length} rows · {loads()}× · visible {visible()}
            </Text>
          </Panel>
          <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
            <Chip label="scrollToIndex 100" onPress={toIndex} />
            <Chip label="scrollToEnd" onPress={toEnd} />
          </View>
        </Inspector>
      </View>
    </View>
  );

  return <>{() => (wide() ? table() : cards())}</>;
}

function Chip(props: { label: string; onPress: () => void }) {
  return (
    <View onPress={props.onPress} {...button()}>
      <Text style={buttonText()}>{props.label}</Text>
    </View>
  );
}

mount(App);
use nsh_core::prelude::*;

#[derive(Clone, PartialEq)]
struct Contact {
    id: usize,
    name: String,
}

fn app() -> impl IntoElement {
    let contacts = signal(
        (0..1000).map(|i| Contact { id: i, name: format!("Contact {}", i + 1) }).collect::<Vec<_>>(),
    );
    virtual_list(move || contacts.with(|c| c.len()), move |at| {
        view().h(px(56.0)).px_4().justify_center().child(
            text(move || contacts.with(|c| format!("{}. {}", at.index() + 1, c[at.index()].name)))
                .text_base(),
        )
    })
    .estimated_item_size(px(56.0))
    .flex_1()
}

TSX では List はジェネリックです。List<T> は each と行関数でアイテムの型が一致していることを検査し、TypeScript はその型を each から推論します(List API を参照)。Rust では virtual_list が行数(値、シグナル、またはクロージャ。リストはその場で増減します)と、Position の行を構築する関数を受け取ります。行はコンポーネントのデータを at.index() で読み取ります。

すべての行が存在してよい短いリスト(設定ページやフォームなど)には、スクロールビュー内の Each のほうが簡単です。グループ化されたテーブルのようなスタイルのリストについては、設定画面スタイルのリストを参照してください。リストガイドでは、無限ローディング、チャット、セクションといったパターンを扱います。

#行はリサイクルされる

行関数は、アイテムごとではなくセルごとに一度だけ実行されます。セルが別のアイテムに再利用されると、その位置が変わり(TSX: item() と index() アクセサ、Rust: at.index())、それを読み取るすべてのものが更新されます。

virtual_list(move || messages.with(|m| m.len()), move |at| {
    text(move || messages.with(|m| m[at.index()].body.clone()))
})

そのため、アイテムごとの状態は、行関数の中で作成したシグナルではなく、データの中(id をキーにして)に保持してください。そのようなシグナルはセルに残り続け、別のアイテムに表示されてしまいます。

次のアイテムを待っているセルは、その行がなくなるか別のセルに表示された時点で非表示になります。そのため、スクリーンリーダー、タッチ、UI テストからは各行が一度だけ見えます。

#Props

PropRust型デフォルト説明
eachvirtual_list(count, ..)readonly T[]アイテム。
childrenvirtual_list(.., |at| row)(item: () => T, index: () => number) => JSX.Element1 行を描画します。
estimatedItemSize.estimated_item_size(px(..))number50まだ計測されていないアイテムのサイズ(ポイント単位)。見積もりが近いほど、スクロールバーが安定します。
horizontal.horizontal()booleanfalse横方向にスクロールします。
viewport.viewport(ListViewport::..)"own" | "parent""own""own": リストは独自のスクロールビュー内でスクロールします。"parent": 親のレイアウト内で全長のまま配置され、周囲のスクロールビューのビューポート付近の行を描画します。ページの他の部分と一緒にそのスクロールビューがスクロールします(ページ内のリストを参照)。リストの作成時に選択します。
numColumns.columns(n)number11 行あたりのアイテム数(縦方向のリスト)。
inverted.inverted()booleanfalse末尾から配置され、アイテム 0 が最後になります(チャット形式)。末尾までスクロールした状態で始まり、内容が変わっても末尾からの距離を保ちます。
maintainVisibleContentPosition.follow_end(px(threshold)){ autoscrollToBottomThreshold?: number }反転していないリスト向け: 内容の末尾にいるとき、または末尾からその点数以内にいるとき、内容が増えたりビューポートが縮んだりしても、リストは末尾に留まります。それより上にスクロールしている場合は、表示中の内容が維持されます。
stickyHeaderIndices.sticky_header_indices([..])number[]通り過ぎるまでスクロールされたとき、先頭に固定されるアイテム(1 列、反転なし)。
contentStyle.content_padding(..), .content_padding_x(..), .row_gap(..), .column_gap(..), …ListContentStyle内容のパディングとギャップ(ポイント単位): padding, paddingHorizontal, paddingVertical, paddingTop, paddingRight, paddingBottom, paddingLeft, gap, rowGap, columnGap。
contentClassstring内容のパディングとギャップをクラスで指定します(p-*, gap-*)。contentStyle が優先されます。
header.header(el)ListSlotアイテムの前に表示: コンポーネント(Header)または要素(<Header />)。
footer.footer(el)ListSlotアイテムの後に表示します。
empty.empty(el)ListSloteach が空の間、アイテムの代わりに表示されます。
separator.separator(|| el)ListSlotアイテムの間に表示します(1 列)。
initialScrollIndex.initial_scroll_index(i)number最初のフレームの前に、このアイテムまでスクロールします。
keyExtractor.keys(|| ids)(item: T, index: number) => stringitem.key、item.id、またはインデックス可視性トークンにおけるアイテムのキー。Rust では行の識別子で、前方で行が追加・削除されても、行がセルとサイズを保持します。
onLoadMore.on_load_more(..)() => void末尾が近づいています: さらに読み込みます。
loadMoreThreshold.load_more_threshold(viewports)number1末尾にどれだけ近づいたとき(ビューポート単位)に onLoadMore が発火するか。
onLoadMoreAtStart.on_load_more_at_start(..)() => void先頭が近づいています(ユーザーまたはスクロールコマンドがリストを動かした後): 最初のアイテムより前の内容を読み込みます。
loadMoreAtStartThreshold.load_more_at_start_threshold(viewports)number1先頭にどれだけ近づいたとき(ビューポート単位)に onLoadMoreAtStart が発火するか。
onViewableItemsChange.on_viewable_items_change(..)(info: { viewableItems: ViewToken<T>[]; changed: ViewToken<T>[] }) => voidアイテムが可視になった、または可視でなくなりました。
viewabilityConfig.viewability(..), .minimum_view_time(..)ViewabilityConfigアイテムがどのような場合に可視とみなされるか(下記)。
refreshing.refreshing(..)booleanプルして更新のスピナーを表示します。
onRefresh.on_refresh(..)() => voidユーザーがプルして更新しました。
refreshIndicator.refresh_indicator(Some(height)){ height: number }アプリが独自のインジケーターを描画します。高さは height ポイントです。プラットフォームのスピナーは非表示になり、プルが height に達すると更新が行われ、更新中はコンテンツの上に height が確保されます。高さが 0 以下の場合は指定なしとして扱われます。
pullValue.pull_value(&value)AnimatedValueリストが先頭を越えてどれだけ引っ張られたかが渡されるアニメーション値です(静止時は 0、引っ張るほど増加。更新中にコンテンツの上に確保される余白は height と refreshIndicator の場合)。アプリ独自のインジケーター用です。
scrollbar.scrollbar(..)boolean | ScrollbarThemetrueスクロールインジケーターを表示します。プラットフォーム標準のもの、またはアプリがテーマを設定した後は、アプリの組み込みバーが使われます。オブジェクトを渡すと、そのビュー固有のテーマになります。デスクトップおよびデスクトップブラウザーでは、横方向のビューはこれを保持します。マウス用のスクロールバーだからです。
scrollValue.scroll_value(&value)AnimatedValueスクロールオフセットが渡されるアニメーション値です。スクロール連動アニメーション用です。
keyboardDismissMode.keyboard_dismiss_mode(..)"none" | "on-drag" | "interactive""none"ドラッグでキーボードを閉じるかどうか。
styleStyled メソッドStyleProp<ViewStyle>リスト自身のスタイル(サイズに上限が必要です: flex: 1 または高さ)。
testID.test_id(id)stringUI テストがリストのスクロールビューを見つけるための id(nsh test の id:、XCUITest、UI Automator)。
ref.element_ref(&handle)ListRef | (node: ListRef) => voidリストの ref(ref メソッドを参照)。

リストは、Scroll のスクロール用 props も受け取ります(Rust では Scrollable メソッド): pagingEnabled、snapToInterval、snapToOffsets、snapToAlignment、disableIntervalMomentum、decelerationRate、bounces、contentInset、contentOffset、keyboardShouldPersistTaps、scrollEventThrottle、scrollable。リストはスケールを維持します。

すべての要素が受け取る props(共通 props)は、そのままリストのスクロールビューに渡されます: testID、accessibilityLabel およびその他のアクセシビリティ props、スタイル、onLayout、タッチおよびレスポンダー props。UI テストは、他のビューと同様に testID でリストを見つけます。

ViewabilityConfig(Rust: Viewability { item_visible_threshold, view_area_coverage_threshold } と .minimum_view_time(..)):

フィールド型説明
itemVisibleThresholdnumberアイテムがどれだけ見えている必要があるか(0 から 1)。
viewAreaCoverageThresholdnumberアイテムがビューポートのどれだけを覆っている必要があるか(0 から 1)。どちらのしきい値も指定しない場合は、1 ピクセルでも見えていれば可視とみなされます。
minimumViewTimenumberアイテムが報告されるまでに、可視の状態を保つ必要があるミリ秒数。

ViewToken<T> は { item, key, index, isViewable } です。Rust のリスナーは ViewableItems を受け取ります。indices() は可視な行の範囲、changed() は新たに可視になった、または可視でなくなった行です。

#イベント

イベントRustペイロード発生タイミング
onScroll.on_scrollScrollEventオフセットが変化したとき。
onScrollDragStart / onScrollDragEnd.on_scroll_drag_start / .on_scroll_drag_end{ offset }ドラッグが開始 / 終了したとき。
onMomentumStart / onMomentumEnd.on_momentum_start / .on_momentum_end{ offset }慣性スクロールが開始 / 終了したとき。
onScrollEnd.on_scroll_end{ offset }スクロールが停止したとき。
onLoadMore.on_load_moreなし末尾から loadMoreThreshold ビューポート以内になったとき。
onLoadMoreAtStart.on_load_more_at_startなし先頭から loadMoreAtStartThreshold ビューポート以内になったとき。スクロール後、接近ごとに一度。
onViewableItemsChange.on_viewable_items_change{ viewableItems, changed }(ViewableItems)可視性が変化したとき。
onRefresh.on_refreshなしプルして更新されたとき。

#Ref メソッド

メソッドRust説明
scrollToIndex({ index, animated?, viewPosition?, viewOffset? })scroll_to_index(index, percentage(0.5), px(0.0), animated)アイテム index が見えるようにスクロールします。viewPosition で配置を指定します: 0 はビューポートの先頭(デフォルト)、0.5 は中央、1 は末尾です。viewOffset でさらにずらせます。現在の(計測済み、または見積もりの)アイテムサイズを使ってネイティブで解決されます。
scrollToOffset({ offset, animated? })scroll_to_offset(px(..), animated)リストの軸方向のオフセットまでスクロールします。
scrollToEnd({ animated? })scroll_to_end(animated)内容の末尾(反転リストでは先頭)までスクロールします。
scrollTo({ x?, y?, animated? })scroll_to(point(..), animated)オフセットまでスクロールします。

#例

ヘッダーと可視性を備えたグリッド:

let visible = signal(SharedString::default());
let list = element_ref();

virtual_list(move || photos.with(|p| p.len()), move |at| {
    image(move || photos.with(|p| p[at.index()].url.clone())).h(px(120.0)).rounded(px(8.0))
})
.element_ref(&list)
.columns(3)
.estimated_item_size(px(120.0))
.content_padding(px(12.0))
.row_gap(px(8.0))
.column_gap(px(8.0))
.viewability(Viewability { item_visible_threshold: Some(Percentage(0.5)), ..Viewability::default() })
.on_viewable_items_change(move |items: &ViewableItems| {
    visible.set(format!("{} visible", items.indices().count()).into())
})
.header(
    text("Jump to 60")
        .on_press(move || list.scroll_to_index(60, percentage(0.5), px(0.0), true)),
)
.flex_1()

チャット:

virtual_list(move || messages.with(|m| m.len()), move |at| bubble(messages, at))
    .keys(move || messages.with(|m| m.iter().map(|m| m.id).collect::<Vec<_>>()))
    .inverted()
    .estimated_item_size(px(64.0))
    .keyboard_dismiss_mode(KeyboardDismissMode::Interactive)
    .flex_1()

アイテム 0 が最新のメッセージで、最下部に描画されます。アイテムの先頭に追加された新しいメッセージは、ユーザーが読んでいる内容を動かすことなく表示されます。

#プラットフォームに関する注意

  • 表示中の行より上にアイテムを挿入しても、両プラットフォームで表示中の行は位置を保ちます。
  • 右から左へのレイアウトでは、横方向のリストはネイティブでミラーリングされます。
  • スティッキーヘッダーは、すべてのスクロールフレームでネイティブに固定されます。