元素

Tooltip

工具提示是显示在所说明内容旁边的简短提示:图标按钮的作用、被截断的标签的完整文字。在桌面平台和桌面浏览器中,指针在触发元素上停留 delay(500 毫秒)后显示,指针离开或按下触发元素时隐藏。在任何设备上,键盘焦点停在触发元素上时它也会立即显示,焦点离开或按下 Escape 时隐藏,键盘用户因此能读到同样的提示。除此之外,手机和平板只在应用打开它(open)时显示。它从不接收指针或按压,所以触发元素的行为与没有它时完全一样。

el-tooltip.tsx
el-tooltip.tsx运行中
import { mount, signal, Text, View } from "nsh";
import { type OpenChangeReason, Tooltip } from "nsh/base";
import { button, buttonText, createPresence, desktop, Inspector, Log, Panel, Stage, ui, wide } from "./palette";

/** An icon button with a hint of the app's look, above or below it. */
function Tool(props: {
  icon: string;
  label: string;
  hint: string;
  placement: "top" | "bottom";
  pinned: boolean;
  onPress: () => void;
  onOpenChange: (e: { open: boolean; reason: OpenChangeReason }) => void;
}) {
  const hovered = signal(false);
  // The bubble stays made between showings: it comes in from its side as it shows.
  const presence = createPresence(props.placement);
  return (
    <View style={{ alignItems: "center", gap: 6 }}>
      <View
        onPress={props.onPress}
        accessibilityLabel={props.label}
        {...button("secondary", { align: "center", style: { width: desktop ? 36 : 52, height: desktop ? 36 : 52, paddingHorizontal: 0 } })}
        tooltip={
          <Tooltip
            open={props.pinned || hovered()}
            placement={props.placement}
            offset={8}
            margin={8}
            delay={400}
            onOpenChange={(e) => {
              hovered.set(e.open);
              props.onOpenChange(e);
            }}
            onOpen={presence.show}
            onClose={presence.hide}
          >
            <View style={{ backgroundColor: ui().text, borderRadius: 7, paddingHorizontal: 10, paddingVertical: 6, ...presence.style }}>
              <Text style={{ fontSize: 13, color: ui().page }}>{props.hint}</Text>
            </View>
          </Tooltip>
        }
      >
        <Text style={{ fontSize: desktop ? 17 : 22, color: ui().text }}>{props.icon}</Text>
      </View>
      <Text style={{ fontSize: 11, color: ui().faint }}>{props.placement}</Text>
    </View>
  );
}

function App() {
  const events = signal<string[]>([]);
  const pressed = signal("—");
  const pinned = signal(false);
  const log = (name: string) => ({ open, reason }: { open: boolean; reason: OpenChangeReason }) =>
    events.set([`${name} ${open ? "shown" : "hidden"} · ${reason}`, ...events()].slice(0, 6));
  const tools = () => (
    <>
      <Tool icon="★" label="Star" hint="Add to favorites" placement="top" pinned={pinned()} onPress={() => pressed.set("Star")} onOpenChange={log("Star")} />
      <Tool icon="↗" label="Share" hint="Share with your team" placement="bottom" pinned={pinned()} onPress={() => pressed.set("Share")} onOpenChange={log("Share")} />
      <Tool icon="✕" label="Delete" hint="Move to the trash" placement="top" pinned={pinned()} onPress={() => pressed.set("Delete")} onOpenChange={log("Delete")} />
    </>
  );
  // The `tooltip` prop of any element: a `Tooltip` with the app's look.
  const pin = () => (
    <View
      tooltip={
        <Tooltip style={{ backgroundColor: ui().text, borderRadius: 7, paddingHorizontal: 10, paddingVertical: 6 }}>
          <Text style={{ fontSize: 13, color: ui().page }}>Shows every tooltip without a pointer</Text>
        </Tooltip>
      }
      onPress={() => pinned.set(!pinned())}
      {...button("secondary", { align: "center", style: wide() ? {} : { flex: 1 } })}
    >
      <Text style={buttonText()}>
        {wide() ? (pinned() ? "Unpin the tooltips" : "Pin the tooltips") : pinned() ? "Unpin" : "Pin"}
      </Text>
    </View>
  );
  const onPress = () => (
    <Panel title="onPress">
      <Text style={{ fontSize: 13, color: ui().text }}>{pressed()}</Text>
    </Panel>
  );
  const changes = () => <Log title="onOpenChange({ open, reason })" lines={events()} minHeight={130} />;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>tooltip</Text>
      <Text style={{ color: ui().muted }}>
        {desktop ? "Rest the pointer on a button; a click still presses it" : "Tooltips follow a pointer: pin them to see them here"}
      </Text>

      {() =>
        wide() ? (
          <View style={{ flex: 1, flexDirection: "row", gap: 16 }}>
            <Stage gap={40}>
              <View style={{ flexDirection: "row", justifyContent: "center", gap: 64 }}>{tools()}</View>
              {pin()}
            </Stage>
            <Inspector>
              {onPress()}
              {changes()}
            </Inspector>
          </View>
        ) : (
          <>
            <View style={{ flex: 1, minHeight: 200, flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 28 }}>{tools()}</View>
            <View style={{ flexDirection: "row", gap: 8 }}>{pin()}</View>
            {onPress()}
            {changes()}
          </>
        )
      }
    </View>
  );
}

mount(App);

把 nsh/base 的 Tooltip 作为每个元素都有的 tooltip 属性传入(见通用属性),与 GPUI 的 .tooltip(..) 相同:该元素就是指针停留的对象,也是它定位的参照。工具提示本身就是气泡:用 class / style 设置样式,子元素是它的内容。

use nsh_base::tooltip;
use nsh_core::prelude::*;

fn save_button(on_save: impl Fn() + 'static) -> impl IntoElement {
    view()
        .on_press(on_save)
        .accessibility_label("保存")
        .p_2()
        .child(text("💾"))
        .tooltip(
            tooltip()
                .placement(Placement::Bottom)
                .rounded_md()
                .bg(rgb(0x111827))
                .px_2()
                .py_1()
                .child(text("保存文档").text_color(white())),
        )
}

它默认显示在触发元素上方(placement),空间不够时换到另一侧,并始终位于安全区之内。设置 open 后由应用决定何时显示:应用跟随 onOpenChange(它报告指针在触发元素上停留或离开,以及键盘焦点的到来和离开),并且可以在任何设备上显示它。

在终端里,工具提示是一行文字,和终端应用显示提示的方式一样:键盘焦点或指针在触发元素上时,提示内容立即显示在屏幕最下面一行,用终端自己的颜色;焦点和指针离开后这一行清空。指针停在触发元素上时,显示指针那个提示,而不是焦点那个。Toast 显示时,这一行让给 Toast 的消息。终端里不等待 delay(设为 Infinity 时仍然只在应用用 open 打开时显示)。工具提示自己的外观和过渡只作用于其他设备上的气泡;它的子元素原样显示,包括快捷键的 Kbd。

它随你的过渡出现和离开:startingClass 是它第一帧的外观,endingClass 是隐藏后的外观,在它的 class 里的 transition-* 类播放期间保留,随后触发 onClose。

<Tooltip
  class="rounded-md bg-gray-900 px-2 py-1 transition-opacity duration-100"
  startingClass="opacity-0"
  endingClass="opacity-0"
>
  <Text class="text-white">Save the document</Text>
</Tooltip>

#属性

属性Rust类型默认值说明
children.child(..)JSX.Element无提示的内容。
class、style.app_class(..)、Styled 方法string、StyleProp<ViewStyle>无气泡的外观:即工具提示本身。
startingClass、startingStyle.starting_class(..)、.starting_style(..)string、StyleProp<ViewStyle>无它第一帧的外观:它的过渡从这里开始。
endingClass、endingStyle.ending_class(..)、.ending_style(..)string、StyleProp<ViewStyle>无它隐藏后的外观:过渡播放期间它会保留。
open.open(..)boolean无是否显示,由应用控制。
defaultOpen.default_open(..)booleanfalse没有 open 时,初始是否显示。
delay.delay(..)number500指针在触发元素上停留多少毫秒后显示(键盘焦点会让它立即显示);Infinity:不会自行显示,指针和焦点都不会让它显示,只在应用打开它时显示。
disabled.disabled(..)booleanfalse它从不显示。
placement.placement(..)"top" | "bottom" | "left" | "right""top"它位于触发元素的哪一侧。
align.align(..)"start" | "center" | "end""center"它沿这一侧如何与触发元素对齐。
offset.offset(..)number4触发元素与工具提示之间的间距。
margin.margin(..)number4它与安全区边缘保持的距离。

#事件

事件Rust说明
onOpenChange.on_open_change(|e| ..)指针在触发元素上停留了,或离开、按下了它(reason 为 "hover");键盘焦点来到或离开了它("focus");它显示时按下了 Escape("cancel")。
onOpen.on_open(|| ..)它已显示。
onClose.on_close(|| ..)它已消失(在离开过渡之后),应用隐藏它时也会触发。

#无障碍

工具提示把触发元素的说明重复给屏幕阅读器:也给触发元素设置 accessibilityLabel,让每个人都能得到这条提示。