元素

HoverCard

悬停卡片在不离开当前页面的情况下预览触发元素所指向的内容:一次提及背后的个人资料、一个链接背后的页面、一个股票代码背后的报价。在桌面平台和桌面浏览器中,指针在触发元素上停留 openDelay(600 毫秒)后,或键盘焦点来到触发元素上时,它会打开。指针从触发元素移到卡片上再移回来时,它保持打开,所以卡片里的链接和按钮都能使用;指针离开两者 closeDelay(300 毫秒)后,它会关闭。Escape 和外部按压会立即关闭它。在手机和平板上,按下触发元素会打开和关闭它,外部按压会关闭它。

el-hover-card.tsx
el-hover-card.tsx运行中
import { type JSX, mount, signal, Text, View } from "nsh";
import { HoverCard, type OpenChangeReason } from "nsh/base";
import { desktop, focusRing, Inspector, Log, PopIn, type PopupSide, Segmented, Stage, tint, ui, wide } from "./palette";

type Placement = PopupSide;

/** A card's surface, the look the app gives it; `PopIn` brings it in from the trigger's side. */
const surface = (width: number) => ({ ...ui().card, width, borderRadius: 12, padding: 14, gap: 10 });

/** The popup's box fades on its way out (its ending class, kept while the transition runs). */
const exit = { popupClass: "transition-opacity duration-150 ease-in motion-reduce:transition-none", popupEndingClass: "opacity-0" };

function App() {
  const openDelay = signal(600);
  const closeDelay = signal(300);
  const placement = signal<Placement>("bottom");
  const events = signal<string[]>([]);
  const following = signal(false);
  const price = signal(227.52);
  let timer: ReturnType<typeof setInterval> | undefined;
  const log = (name: string) => ({ open, reason }: { open: boolean; reason: OpenChangeReason }) =>
    events.set([`${name} ${open ? "opened" : "closed"} · ${reason}`, ...events()].slice(0, 6));
  const shared = () => ({ ...exit, openDelay: openDelay(), closeDelay: closeDelay(), placement: placement(), offset: 8, margin: 12 });
  // Running text in a wrapping row: one piece per word, so a line breaks
  // between words, and the row's gap is the space between them.
  const words = (s: string) => s.split(" ").map((w) => <Text style={{ fontSize: 15, color: ui().text }}>{w}</Text>);

  // A mention: the person's card, with a button that works because the
  // pointer can move into the card.
  const mention = () => (
    <HoverCard {...shared()} onOpenChange={log("@ada")} trigger={
      <View role="link" onPress={() => events.set(["onPress /people/ada", ...events()].slice(0, 6))} focusStyle={focusRing(1)} style={{ borderRadius: 4, borderWidth: 1, borderColor: "transparent", paddingHorizontal: 2, marginHorizontal: -3 }} hoverStyle={{ backgroundColor: tint(ui().accent, 0.14) }}>
        <Text style={{ fontSize: 15, fontWeight: "600", color: ui().accent }}>@ada</Text>
      </View>
    }>
      <PopIn side={placement()} style={surface(260)}>
        <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
          <View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: tint(ui().accent, 0.18), alignItems: "center", justifyContent: "center" }}>
            <Text style={{ fontSize: 15, fontWeight: "600", color: ui().accent }}>AL</Text>
          </View>
          <View style={{ flex: 1, gap: 2 }}>
            <Text style={{ fontSize: 15, fontWeight: "600", color: ui().text }}>Ada Lovelace</Text>
            <Text style={{ fontSize: 12, color: ui().muted }}>Analyst · Engines</Text>
          </View>
        </View>
        <Text style={{ fontSize: 13, lineHeight: 18, color: ui().text }}>Writes the first programs for the Analytical Engine.</Text>
        <View
          onPress={() => following.set(!following())}
          style={{ height: 30, borderRadius: 8, alignItems: "center", justifyContent: "center", ...(following() ? ui().raised : ui().accentFill), transitionProperty: "background-color", transitionDuration: 150 }}
        >
          <Text style={{ fontSize: 13, fontWeight: "500", color: following() ? ui().text : ui().onAccent }}>{following() ? "Following" : "Follow"}</Text>
        </View>
      </PopIn>
    </HoverCard>
  );

  // A link with a preview of the page behind it.
  const preview = () => (
    <HoverCard {...shared()} onOpenChange={log("taffy")} trigger={
      <View role="link" onPress={() => events.set(["onPress github.com/DioxusLabs/taffy", ...events()].slice(0, 6))} focusStyle={focusRing(1)} style={{ borderBottomWidth: 1, borderBottomColor: tint(ui().accent, 0.4) }}>
        <Text style={{ fontSize: 15, color: ui().accent }}>Taffy</Text>
      </View>
    }>
      <PopIn side={placement()} style={{ ...surface(280), padding: 0, gap: 0, overflow: "hidden" }}>
        <View style={{ height: 64, backgroundImage: "linear-gradient(135deg, #3b82f6, #8b5cf6)" }} />
        <View style={{ padding: 12, gap: 4 }}>
          <Text style={{ fontSize: 11, color: ui().faint }}>github.com</Text>
          <Text style={{ fontSize: 14, fontWeight: "600", color: ui().text }}>taffy: flexbox, grid and block layout</Text>
          <Text style={{ fontSize: 12, color: ui().muted }}>A high-performance UI layout library written in Rust.</Text>
        </View>
      </PopIn>
    </HoverCard>
  );

  // A ticker whose quote ticks while its card is open.
  const ticker = () => (
    <HoverCard
      {...shared()}
      onOpenChange={log("$AAPL")}
      onOpen={() => (timer = setInterval(() => price.set(Math.round((price() + (Math.random() - 0.48) * 0.6) * 100) / 100), 900))}
      onClose={() => clearInterval(timer)}
      trigger={
        <View focusable focusStyle={focusRing(1)} style={{ paddingHorizontal: 8, height: 26, borderRadius: 13, justifyContent: "center", borderWidth: 1, borderColor: tint(ui().up, 0.3), backgroundColor: tint(ui().up, 0.1) }}>
          <Text style={{ fontSize: 13, fontWeight: "600", color: ui().up }}>$AAPL ▲</Text>
        </View>
      }
    >
      <PopIn side={placement()} style={surface(220)}>
        <Text style={{ fontSize: 12, color: ui().muted }}>Apple Inc. · live</Text>
        <Text style={{ fontSize: 26, fontWeight: "600", color: ui().text, fontVariant: ["tabular-nums"] }}>{price().toFixed(2)}</Text>
        <Text style={{ fontSize: 13, color: price() >= 224.1 ? ui().up : ui().down, fontVariant: ["tabular-nums"] }}>
          {price() >= 224.1 ? "+" : ""}
          {(price() - 224.1).toFixed(2)} today
        </Text>
      </PopIn>
    </HoverCard>
  );

  const stage = (): JSX.Element => (
    <View style={{ gap: 18, alignItems: "flex-start" }}>
      <View style={{ flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 4, rowGap: 6 }}>
        {words("Ask")}
        {mention()}
        {words("about the layout engine,")}
        {/* The period stays with the link. */}
        <View style={{ flexDirection: "row", alignItems: "center" }}>
          {preview()}
          {words(".")}
        </View>
      </View>
      <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
        {words("Today:")}
        {ticker()}
      </View>
    </View>
  );
  const controls = () => (
    <>
      <Segmented label="openDelay" options={[0, 300, 600, 1200]} value={openDelay()} onChange={(v) => openDelay.set(v)} />
      <Segmented label="closeDelay" options={[0, 300, 1000]} value={closeDelay()} onChange={(v) => closeDelay.set(v)} />
      <Segmented label="placement" options={["top", "bottom", "left", "right"] as Placement[]} value={placement()} onChange={(v) => placement.set(v)} />
    </>
  );
  const changes = () => <Log title="onOpenChange({ open, reason })" lines={events()} minHeight={110} />;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>hover card</Text>
      <Text style={{ color: ui().muted }}>
        {desktop ? "Rest the pointer on a mention, a link or a ticker, then move into the card" : "Tap a mention, a link or a ticker; tap outside to close"}
      </Text>

      {() =>
        wide() ? (
          <View style={{ flex: 1, flexDirection: "row", gap: 16 }}>
            <Stage gap={24}>{stage()}</Stage>
            <Inspector>
              {controls()}
              {changes()}
            </Inspector>
          </View>
        ) : (
          <>
            {controls()}
            <View style={{ flex: 1, minHeight: 220, justifyContent: "center" }}>{stage()}</View>
            {changes()}
          </>
        )
      }
    </View>
  );
}

mount(App);

来自 nsh/base 的 HoverCard 自己不绘制任何东西:触发元素是你的元素,弹出层和其中的内容也都属于你。

use nsh_base::hover_card;
use nsh_core::prelude::*;

fn mention() -> impl IntoElement {
    hover_card()
        .offset(px(8.0))
        .popup_class("w-72 gap-2 rounded-xl border border-border bg-popover p-4 shadow-lg")
        .trigger(text("@ada").text_color(rgb(0x2563eb)))
        .child(text("Ada Lovelace").font_weight(FontWeight::SEMIBOLD))
        .child(text("Writes the first programs for the Analytical Engine."))
}

触发元素保留自己的角色、按压和外观:带 role="link" 和自己 onPress 的视图按下后仍会去往它指向的地方,卡片只是为它加上预览。内容在每次打开时创建,所以可以在那时加载它要显示的东西。在手机和平板上,按压会打开卡片,触发元素会告诉屏幕阅读器它的卡片是否已打开。在 Toolbar 中,触发元素可以是工具栏的一项,卡片里的内容则不是:其中的按钮和链接保留自己的 Tab 停靠点,工具栏的 disabled 也不会改变它们。

#延迟

openDelay 让指针经过触发元素去往别处时,卡片不会一闪而开;closeDelay 给指针留出穿过触发元素与卡片之间空隙的时间。两者都以毫秒为单位。指针和延迟都在原生层跟踪,所以在触发元素上停留、在它与卡片之间移动时,直到卡片打开或关闭之前,都不会运行你的代码。openDelay 为 Infinity 时,打开交给应用(以及触摸屏上对触发元素的按压);closeDelay 为 Infinity 时,关闭交给 Escape、外部按压和应用。

<HoverCard openDelay={300} closeDelay={150} trigger={<Text>AAPL</Text>}>
  <Quote symbol="AAPL" />
</HoverCard>

#打开状态

没有 open 时,卡片自己保存状态,初始值为 defaultOpen。有 open 时,状态由应用持有:在 onOpenChange({ open, reason }) 中修改它,每次打开或关闭的请求都会带着原因报告给它:"hover"(指针)、"focus"(键盘焦点)、"triggerPress"(触摸屏上的按压)、"pressOutside" 或 "cancel"(Escape 或返回键)。

const open = signal(false);

<HoverCard open={open()} onOpenChange={(e) => open.set(e.open)} trigger={<Text>@ada</Text>}>
  <Profile id="ada" />
</HoverCard>

#出现与离开

悬停卡片随你的过渡出现和离开,与 Popover 相同。popupStartingClass 是弹出层第一帧的外观,popupClass 里的 transition-* 类把它过渡到自己的外观。popupEndingClass 是关闭后的外观:卡片会保留下来、不再接收指针,直到这些过渡播放完毕才离开,随后触发 onClose。在离开途中指针再次停留在触发元素上时,它会回来。用户要求减少动态效果时,它立即出现、立即离开。

<HoverCard
  popupClass="rounded-xl bg-popover p-4 shadow-lg transition-all duration-150 ease-out"
  popupStartingClass="opacity-0 scale-95"
  popupEndingClass="opacity-0 scale-95"
  trigger={<Text>@ada</Text>}
>
  <Profile id="ada" />
</HoverCard>

它默认位于触发元素下方(placement、align),空间不够时换到另一侧,并始终位于安全区之内。onPosition({ placement, bounds, available }) 说明它放在了哪里。

#属性

属性Rust类型默认值说明
open.open(..)boolean无是否打开,由应用控制。
defaultOpen.default_open(..)booleanfalse没有 open 时,初始是否打开。
openDelay.open_delay(..)number600指针在触发元素上停留、或焦点停在它上面多少毫秒后打开;Infinity:不会自行打开。
closeDelay.close_delay(..)number300指针离开触发元素和卡片多少毫秒后关闭;Infinity:不会自行关闭。
placement.placement(..)"top" | "bottom" | "left" | "right""bottom"它位于触发元素的哪一侧。
align.align(..)"start" | "center" | "end""center"它沿这一侧如何与触发元素对齐。
offset.offset(..)number0触发元素与卡片之间的间距。
margin.margin(..)number0它与安全区边缘保持的距离。
popupClass、popupStylepopup_class、popup_stylestring、StyleProp<ViewStyle>无弹出层(装着内容的卡片)的外观。
popupStartingClass、popupStartingStylepopup_starting_class、popup_starting_stylestring、StyleProp<ViewStyle>无弹出层第一帧的外观,叠加在它自己的外观之上:它的过渡从这里开始。
popupEndingClass、popupEndingStylepopup_ending_class、popup_ending_stylestring、StyleProp<ViewStyle>无弹出层关闭后的外观,叠加在它自己的外观之上:过渡播放期间它会保留。
trigger.trigger(..)JSX.Element无它预览的元素;它相对这个元素放置。
children.child(..)JSX.Element无内容,每次打开时创建。

#事件

事件Rust说明
onOpenChange.on_open_change(|e| ..)它请求打开或关闭,附带原因:"hover"、"focus"、"triggerPress"、"pressOutside" 或 "cancel"。
onOpen.on_open(|| ..)它已显示。
onClose.on_close(|| ..)它已消失(在离开过渡之后),应用关闭它时也会触发。
onPosition.on_position(|e| ..)弹出层已放置:placement(它所在的一侧)、bounds(它的框)、available(那一侧的空间)。

#无障碍

悬停卡片是对触发元素的补充:触发元素保留自己的角色和标签,按下它时打开或执行的东西也不变。键盘用户在焦点停在触发元素上时得到卡片,Escape 关闭它。卡片自己不获取焦点,所以 Tab 照常从触发元素往后移动;卡片里重要的内容,也应能从触发元素通往的页面中找到。