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

元素

Tooltip

Tooltip 是緊鄰其對象的簡短提示:說明圖示按鈕的作用,或顯示被截斷標籤的完整文字。 在桌面平台與桌面瀏覽器上,指標在觸發元素上停留 delay(500 ms)後顯示,指標離開或按下觸發元素時隱藏。手機與平板只有在應用程式開啟時才會顯示 Tooltip (open)。它不會攔截指標或按壓操作,因此觸發元素的運作方式與沒有 Tooltip 時完全相同。

el-tooltip.tsx
el-tooltip.tsxLive
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 prop 傳入 (Common props),即 GPUI 的 .tooltip(..):該元素就是指標停留的對象,也是 Tooltip 定位時所依附的對象。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("Save")
        .p_2()
        .child(text("💾"))
        .tooltip(
            tooltip()
                .placement(Placement::Bottom)
                .rounded_md()
                .bg(rgb(0x111827))
                .px_2()
                .py_1()
                .child(text("Save the document").text_color(white())),
        )
}

Tooltip 預設顯示在觸發元素上方(placement),空間不足時會改到另一側,並且始終保持在安全區域內。使用 open 時,由應用程式決定何時顯示:它會跟隨 onOpenChange,後者會回報指標停留在觸發元素上或離開觸發元素,並且可以在任何裝置上顯示。

它會隨著你的轉場效果出現與消失:startingClass 是它在第一個影格的外觀,endingClass 則是隱藏後的外觀,在其 class 的 transition-* class 執行期間會保持該外觀;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>

#Props

PropRust類型預設值說明
children.child(..)JSX.Element無它所顯示的內容。
class、style.app_class(..)、Styled 方法string、StyleProp<ViewStyle>無氣泡的外觀:即 Tooltip 本身。
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觸發元素與 Tooltip 之間的間距。
margin.margin(..)number4它與安全區域邊緣保持的距離。

#Events

事件Rust說明
onOpenChange.on_open_change(|e| ..)指標停留在觸發元素上,或離開或按下觸發元素(reason "hover")。
onOpen.on_open(|| ..)已顯示。
onClose.on_close(|| ..)已消失,於退場效果結束之後;應用程式將其隱藏時也會觸發。

#Accessibility

Tooltip 會向螢幕閱讀器重複其觸發元素所傳達的內容:也請為觸發元素提供 accessibilityLabel,讓每個人都能獲得這項提示。