元素

Progress

进度条显示一个有明确工作量的任务完成了多少(下载、上传、设置中的一步),或者在 indeterminate 时表示一个工作量未知的任务正在进行。它负责屏幕阅读器读到的内容(进度条角色、0 到 100 的范围和数值)以及指示条的宽度:轨道宽度的 value 百分比。外观由应用决定:Progress 没有自己的颜色、尺寸、圆角、动效或文字。它由一条轨道、轨道里的指示条以及之后的子元素(标签、数值文字)组成,应用为每个部件设置样式。

el-progress.tsx
el-progress.tsx运行中
import { cleanup, mount, signal, Text, View } from "nsh";
import { reduceMotion } from "nsh/accessibility";
import { Button, Progress, Switch } from "nsh/base";
import { 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; 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 rounded-full"
    : 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 }}
    >
      <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}
      class="items-center justify-center rounded-lg border px-3 active:opacity-70 disabled:opacity-40"
      style={{ height: size.control, flex: desktop ? undefined : 1, borderColor: ui().border }}
      hoverStyle={props.disabled ? undefined : hoverFill()}
      focusStyle={focusRing()}
    >
      <Text style={{ fontSize: desktop ? 13 : 15, fontWeight: "600", color: ui().text }}>{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={(next) => {
                  unknown.set(next);
                  if (next) stop();
                  log(next ? "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::ui::prelude::*;

fn upload(sent: Signal<f32>) -> impl IntoElement {
    progress()
        .value(sent)
        .accessibility_label("正在上传照片")
        .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。数值由应用持有:进度条显示应用传入的 value,限定在 0 到 100 之间。在 Rust 中,progress() 创建一个进度条,每个属性有对应的设置方法(.value(..)、.indicator_style(..)),进度条本身用类型化的样式方法,标签用 .child(..)。

#属性

属性Rust类型默认值说明
value.value(..)number0任务完成了多少,0 到 100 的百分比(超出范围时取最近的一端)。指示条占轨道宽度的这个比例,屏幕阅读器读出它。
indeterminate.indeterminate(..)booleanfalse任务的工作量未知:屏幕阅读器听到一个没有数值的进度条,指示条的宽度由应用决定(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-* 类或 indicatorStyle 里的 width 会取代按数值算出的宽度,不确定进度条就是这样得到自己的宽度。

#不确定进度

工作量未知时,设置 indeterminate,并给指示条应用自己的宽度和动效。动效由应用选择,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 表示不确定进度条的方式)。
  • 它不接受按压,也不获得键盘焦点:它只报告进度,开始或停止任务的控件由应用提供。

标签、角色和播报的一般用法见无障碍。

#平台说明

  • 各平台绘制应用设置的样式;指示条的宽度立即跟随 value,应用为它加上动画时变化会有动画。
  • 屏幕阅读器:VoiceOver(iOS、macOS)以百分比读出数值,并把进度条当作频繁更新的元素;TalkBack、UI Automation(Windows)、GTK 的无障碍(Linux)和浏览器(aria-valuenow)得到范围和数值。