本頁由機器翻譯,可能有錯誤。 閱讀英文原文

元素

Progress

進度條會顯示範圍已知的任務(下載、上傳、設定中的某個步驟)進行到哪裡,或是在 indeterminate 時表示範圍未知的任務正在進行中。它負責螢幕閱讀器取得的內容(範圍 0 到 100 的進度條角色與其值),以及指示器的寬度:軌道寬度的 value %。外觀由 app 決定:Progress 本身沒有顏色、尺寸、圓角、動態效果或標籤。它由軌道與其內的指示器組成,後面接著它的子元素(標籤、以文字呈現的值),每個部分都由 app 設定樣式。

el-progress.tsx
el-progress.tsxLive
import { cleanup, mount, signal, Text, View } from "nsh";
import { reduceMotion } from "nsh";
import { Button, Progress, Switch } from "nsh/base";
import { button, buttonText, desktop, focusRing, hoverFill, Log, Panel, size, Split, ui } from "./palette";

// The parts: geometry and motion in classes, colors from the palette. The
// label row comes first (`flex-col-reverse`: the children follow the track),
// its value tabular and at the trailing edge. An indeterminate indicator is a
// third of the track that sweeps from end to end (the app flips its
// translation, a transition moves it), and rests in the middle with reduced
// motion. A determinate one is the whole track, slid back by what is left to
// do, so a new value glides there (the track clips it). The pointer's hover
// and the keyboard's focus ring come from the palette. Buttons are as wide as
// their labels with a pointer.
const pad = desktop ? "px-3 py-3" : "px-4 py-4";
const track = "h-1.5 overflow-hidden rounded-full";
const SWEEP = 800;
const indicator = (indeterminate: boolean, end: boolean) =>
  !indeterminate
    ? "h-full w-full rounded-full transition-transform duration-180 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none"
    : reduceMotion()
      ? "h-full w-1/3 rounded-full translate-x-full"
      : `h-full w-1/3 rounded-full transition-transform duration-700 ease-in-out ${end ? "translate-x-[200%]" : "translate-x-0"}`;

function Transfer(props: { label: string; detail: string; value: number; indeterminate?: boolean; end: boolean }) {
  return (
    <Progress
      value={props.value}
      indeterminate={props.indeterminate}
      class={`flex-col-reverse gap-2 ${pad}`}
      trackClass={track}
      trackStyle={ui().inset}
      indicatorClass={indicator(!!props.indeterminate, props.end)}
      indicatorStyle={{ backgroundColor: ui().accent, translate: props.indeterminate ? undefined : `${props.value - 100}% 0` }}
    >
      <View class="flex-row items-baseline gap-3">
        <View style={{ flex: 1, gap: 2 }}>
          <Text style={{ fontSize: size.label, fontWeight: "500", color: ui().text }}>{props.label}</Text>
          <Text style={{ fontSize: size.detail, color: ui().muted }}>{props.detail}</Text>
        </View>
        <Text style={{ fontSize: size.label, color: ui().muted, fontVariant: ["tabular-nums"], textAlign: "right" }}>
          {props.indeterminate ? "—" : `${Math.round(props.value)}%`}
        </Text>
      </View>
    </Progress>
  );
}

function Action(props: { label: string; disabled?: boolean; onPress: () => void }) {
  return (
    <Button
      onPress={props.onPress}
      disabled={props.disabled}
      {...button("secondary", { style: desktop ? {} : { flex: 1 } })}
    >
      <Text style={buttonText()}>{props.label}</Text>
    </Button>
  );
}

function App() {
  const sent = signal(35);
  const running = signal(false);
  const unknown = signal(false);
  const events = signal<string[]>([]);
  const log = (line: string) => events.set([line, ...events()].slice(0, 5));
  // The sweep of the indeterminate bars: still with reduced motion.
  const end = signal(false);
  const sweep = setInterval(() => {
    if (!reduceMotion()) end.set(!end());
  }, SWEEP);
  cleanup(() => clearInterval(sweep));
  let timer: ReturnType<typeof setInterval> | undefined;
  const stop = () => {
    if (timer !== undefined) clearInterval(timer);
    timer = undefined;
    running.set(false);
  };
  const start = () => {
    if (sent() >= 100) sent.set(0);
    running.set(true);
    log(`Start at ${sent()}%`);
    timer = setInterval(() => {
      sent.set(Math.min(100, sent() + 5));
      if (sent() >= 100) {
        stop();
        log("Done: value 100");
      }
    }, 200);
  };
  const line = () => <View style={{ height: 1, marginLeft: desktop ? 12 : 16, backgroundColor: ui().line }} />;
  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>progress</Text>
      <Text style={{ color: ui().muted }}>{desktop ? "Click Start, or Tab to it and press Space" : "Tap Start to send the photos"}</Text>

      <Split
        gap={14}
        inspector={
          <>
            <Panel title="value · indeterminate">
              <Text style={{ fontSize: 13, color: ui().text, fontVariant: ["tabular-nums"] }}>
                {unknown() ? "indeterminate (no value for screen readers)" : `value ${sent()} of 100`}
              </Text>
              <View class={desktop ? "flex-row self-start gap-2" : "flex-row gap-2"}>
                <Action label={running() ? "Pause" : sent() >= 100 ? "Again" : "Start"} disabled={unknown()} onPress={() => (running() ? (stop(), log(`Pause at ${sent()}%`)) : start())} />
                <Action
                  label="Reset"
                  disabled={sent() === 0}
                  onPress={() => {
                    stop();
                    sent.set(0);
                    log("Reset: value 0");
                  }}
                />
              </View>
              <Switch
                checked={unknown()}
                onChange={({ checked }) => {
                  unknown.set(checked);
                  if (checked) stop();
                  log(checked ? "Size unknown: indeterminate" : "Size known: value " + sent());
                }}
                class={`-mx-2 flex-row-reverse items-center justify-between gap-3 rounded-lg px-2 ${desktop ? "py-1" : "py-2"} active:opacity-70`}
                hoverStyle={hoverFill()}
                focusStyle={focusRing()}
                trackClass={`${desktop ? "w-9" : "w-12"} rounded-full p-0.5 transition-colors motion-reduce:transition-none`}
                trackStyle={unknown() ? ui().accentFill : ui().inset}
                thumbClass={desktop ? "size-4 rounded-full transition-transform motion-reduce:transition-none checked:translate-x-4" : "size-5.5 rounded-full transition-transform motion-reduce:transition-none checked:translate-x-5"}
                thumbStyle={unknown() ? { backgroundColor: ui().onAccent } : ui().raised}
              >
                <Text style={{ flex: 1, fontSize: size.label, color: ui().text }}>Size unknown</Text>
              </Switch>
            </Panel>
            <Log title="events" lines={events()} minHeight={92} />
          </>
        }
      >
        <View style={{ ...ui().card, borderRadius: 16, overflow: "hidden" }}>
          <Transfer
            label="Sending 24 photos"
            detail={unknown() ? "Counting what to send" : sent() >= 100 ? "Sent" : `${Math.round((sent() / 100) * 24)} of 24`}
            value={sent()}
            indeterminate={unknown()}
            end={end()}
          />
          {line()}
          <Transfer label="Preparing the backup" detail="Its size is not known yet" value={0} indeterminate end={end()} />
          {line()}
          <Transfer label="Library" detail="212 GB of 256 GB" value={83} end={end()} />
        </View>
      </Split>
    </View>
  );
}

mount(App);
use nsh_base::{progress, theme};
use nsh_core::prelude::*;

fn upload(sent: Signal<f32>) -> impl IntoElement {
    progress()
        .value(sent)
        .accessibility_label("Uploading photos")
        .gap_2()
        .track_style(|s| s.h(px(8.0)).rounded_full().overflow_hidden().bg(move || theme().muted))
        .indicator_style(|s| s.h_full().rounded_full().bg(move || theme().primary))
        .child(
            text(move || format!("{:.0}%", sent.get()))
                .text_sm()
                .text_color(move || theme().muted_foreground),
        )
}

Progress 來自 nsh/base,也就是 Rust 中的 nsh-base crate。值由 app 掌控:進度條顯示 app 傳入的 value,並限制在 0 到 100 之間。在 Rust 中,progress() 會建立一個進度條,每個屬性都有對應的 setter(.value(..)、.indicator_style(..))、用於進度條本身的型別化樣式方法,以及用於其標籤的 .child(..)。

#屬性

屬性Rust型別預設值說明
value.value(..)number0任務進行到哪裡,以 0 到 100 的百分比表示(超出範圍時取最接近的端點)。指示器的寬度為軌道寬度的該比例,螢幕閱讀器會唸出此值。
indeterminate.indeterminate(..)booleanfalse任務的範圍未知:螢幕閱讀器會聽到沒有值的進度條,指示器的寬度由 app 決定(indicatorClass)。
accessibilityLabel.accessibility_label(..)string無螢幕閱讀器唸出的內容:當子元素沒有文字說明時,用來說明正在進行的是什麼。
trackClass、trackStyle.track_style(|s| ..)string、StyleProp<ViewStyle>無軌道,即指示器填滿的部分。
indicatorClass、indicatorStyle.indicator_style(|s| ..)string、StyleProp<ViewStyle>無軌道內的指示器:其高度、顏色與動態效果。
children.child(..)JSX.Element無軌道之後的內容:標籤或以文字呈現的值,螢幕閱讀器會唸出。
class、style樣式方法string、StyleProp<ViewStyle>無進度條本身:包住軌道與標籤的直欄(或橫列)。

#部件

部件位置樣式設定方式
進度條class、style
軌道進度條內,第一個trackClass、trackStyle
指示器軌道內indicatorClass、indicatorStyle;其寬度為軌道寬度的 value %
標籤進度條內,軌道之後它自己的元素(children)

指示器從軌道的起始邊緣開始;overflow-hidden 與軌道上的圓角會讓指示器的末端與軌道一起變圓。w-* class 或 indicatorStyle 中的 width 會取代由值決定的寬度,不確定進度的進度條就是這樣取得自己的寬度。

#不確定進度

範圍未知時,請設定 indeterminate,並為指示器指定由 app 自訂的寬度與動態效果。動態效果由 app 決定,而 motion-reduce: 會讓它在使用者要求減少動態效果時保持靜止:

<Progress
  value={0}
  indeterminate={connecting()}
  trackClass="h-2 overflow-hidden rounded-full bg-muted"
  indicatorClass={
    connecting()
      ? "h-full w-1/3 rounded-full bg-primary animate-pulse motion-reduce:animate-none"
      : "h-full rounded-full bg-primary"
  }
/>

#無障礙功能

  • 對螢幕閱讀器而言,進度條是單一元素,角色為 "progressbar",範圍為 0 到 100,並帶有其值(VoiceOver 與 TalkBack 會以百分比唸出);軌道與指示器是它的一部分。它的標籤是其子元素的文字;若沒有子元素文字,請提供 accessibilityLabel。
  • 在 indeterminate 時,它仍保有角色與範圍,但沒有值(在瀏覽器中:aria-valuenow 會被省略,這符合 ARIA 對不確定進度條的規定)。
  • 它不接受按壓,也不會取得鍵盤焦點:它只負責回報,而開始或停止任務的控制項由 app 提供。

關於標籤、角色與公告的一般說明,請參閱無障礙功能。

#平台說明

  • 每個平台都會繪製 app 所設定的樣式;指示器的寬度會立即隨 value 變化,而當 app 為變化加上動畫時,變化便會以動畫呈現。
  • 螢幕閱讀器:VoiceOver(iOS、macOS)會以百分比唸出值,並將進度條視為頻繁更新;TalkBack、UI Automation(Windows)、GTK 的無障礙功能(Linux)與瀏覽器(aria-valuenow)則會取得範圍與值。