文本与样式

用颜色、文本属性和主题令牌设置部署卡片的样式。

本章应用正在你的控制台中运行。按 ⌘⌥JCtrl+Shift+J⌘⌥KCtrl+Shift+K⌘⌥C 打开控制台(先开启开发者功能),然后试用。
观看本章3:24

本章内容

  • 文本属性
  • 主题令牌
  • 部署卡片
  • 主题

每个单元格都有一个字符、前景色、背景色和一组属性。Text.js 将它们编译成 %c CSS span,因此控制台能显示真实的颜色、粗体和斜体。

文本属性

<Text> 接受 bold、dim、italic、underline 和 strikethrough。嵌套的 <Text> 元素会成为同一行内带样式的 span。

<Text>  Deployed <Text bold>acme-web</Text> to <Text color="accent">iad1</Text></Text>

主题令牌

color prop 接受十六进制值、普通颜色名称(emerald)和主题令牌;Tailwind 调色板的色阶通过类名(text-emerald-400)指定。令牌随当前主题变化,因此涉及语义的颜色应优先使用令牌。添加一个状态组件:

app/status.tsx+15tsx
新增:import { Text } from "@textjs/app";新增:新增:export type DeployStatus = "ready" | "building" | "error" | "queued";新增:新增:export const STATUS = {新增:  ready: { label: "Ready", color: "success" },新增:  building: { label: "Building", color: "warning" },新增:  error: { label: "Error", color: "danger" },新增:  queued: { label: "Queued", color: "subtle" },新增:} as const;新增:新增:export function Status({ status }: { status: DeployStatus }) {新增:  const s = STATUS[status];新增:  return <Text color={s.color} wrap="nowrap">{`● ${s.label}`}</Text>;新增:}

部署卡片

bg-surface 让卡片在背景上凸显出来。部署 ID 使用状态颜色,构建时显示为斜体,出错时添加删除线。

app/page.tsx+23-1tsx
移除:import { Box, Spacer, Text, useInput } from "@textjs/app";新增:import { Box, Spacer, Text, useAppTheme, useInput } from "@textjs/app";新增:import { Status, STATUS, type DeployStatus } from "./status";新增:新增:const ORDER: DeployStatus[] = ["ready", "building", "error", "queued"];新增:export default function Page() {新增:  const { theme, cycleTheme } = useAppTheme();新增:  const [status, setStatus] = useState<DeployStatus>("ready");新增:新增:  useInput((e) => {新增:    if (e.input === "t") cycleTheme();新增:    if (e.input === "s") setStatus((s) => ORDER[(ORDER.indexOf(s) + 1) % ORDER.length]);新增:  });新增:  return (    <Box className="flex-col grow">      {/* top bar, now with the theme name on the right */}新增:      <Box className="flex-col border rounded px-2 py-1 bg-surface">新增:        <Box className="flex-row gap-2 h-1">新增:          <Text bold>acme-web</Text>新增:          <Status status={status} />新增:        </Box>新增:        <Text color="muted" wrap="truncate-end">feat: stream cells downward</Text>新增:        <Text color={STATUS[status].color} italic={status === "building"} strikethrough={status === "error"}>新增:          dpl_8fK2新增:        </Text>新增:      </Box>    </Box>  );}

wrap="truncate-end" 用 … 截断过长的提交信息,而不换到第二行。

主题

Text.js 内置五种主题:Geist Dark、OpenCode Dark、Tokyo Night、Amber CRT 和 Geist Light。在控制台中按 t 循环切换主题。整帧会使用新的调色板重绘,因为上面的每种颜色都是主题 Token。

试用

这是本章结束时的 Acme Deploys,正在 DevTools 中运行。点击输入区,然后使用下列按键。

▼ 03 · 文本与样式

打开控制台

⌘⌥J
CtrlShiftJ
⌘⌥K
CtrlShiftK
⌘⌥C

应用在 DevTools 中渲染。先在 Safari 设置 → 高级中开启“显示网页开发者功能”。 然后点击这里并按 t。

在桌面端打开

此应用在 DevTools 控制台中渲染,需要桌面浏览器。

测验

2 个问题

回答所有问题以完成本章。

Why use color="success" instead of a hex value?

 

What does wrap="truncate-end" do?