---
title: "渲染目标与界面：托盘、面板、小组件与刘海屏 · Metrix.Bar"
description: "掌握 Metrix.Bar 全部渲染表面契约：菜单栏自定义内容与动画、浮动面板、对话框、独立窗口、系统小组件、刘海屏、覆盖层与选区浮窗。"
canonical: "https://metrix.bar/zh/docs/surfaces"
language: "zh-Hans"
updated: "2026-11-30T14:33:33+08:00"
---

# 渲染目标与界面

> Metrix.Bar 各类渲染目标契约：菜单栏托盘、面板、窗口、屏幕侧栏、系统小组件、刘海屏、屏幕覆盖层与选区浮窗。

## 概述

`render(env)` 返回一个普通对象，可按需提供任意子集的渲染输出（无界面 Worker 可直接省略 `render`）：

```js
export default {
  render(env) {
    return {
      tray: { title: "42" },
      panel: { type: "Column", props: { padding: 16 }, children: [/* ... */] },
      widget: { small: { type: "Text", props: { text: "42", fontSize: 28, bold: true } } },
      notch: { compact: { leading: /* ... */, trailing: /* ... */ }, minimal: /* ... */, expanded: /* ... */ },
      overlay: null,
      selectionPopover: null,
    };
  },
};
```

同一看板实例的所有入口共享同一个 Worker、状态与已提交的渲染结果。通过 `$metrix.outputs()` 或 `event("outputs", snapshot)` 按需构建树，避免无谓渲染。

---

## 菜单栏与系统托盘（`tray`）

返回 `tray: null` 或 `tray.hidden: true`（探测 `render.tray.hidden`）可隐藏菜单栏项同时保留屏幕侧栏入口。结合 `<bar hide-when-empty="true">`（探测 `hide-when-empty`），当 `title`、`content`、`iconAnimation`、`error` 与未清空的 `icon` 均为空时自动隐藏菜单栏项。

| 字段                                  | 说明                                                                                                                                                                  |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`                               | 显示在 macOS 菜单栏、Windows 托盘提示或 Linux 托盘菜单第一项的短文本。                                                                                                |
| `icon`                                | 系统图标名、远程图片 URL（需 `<network>`）或 `data:` URI。在 macOS 传 `icon: null`（探测 `render.tray.icon.clear`）可清除图标仅显 `title`；省略或 `""` 保持当前图标。 |
| `iconTemplate`                        | `true` 强制按 macOS 模板图渲染，自动适配明暗主题与高亮。                                                                                                              |
| `iconAnimation`                       | macOS 宿主驱动的帧动画（优先级高于 `content` 与 `icon`）。                                                                                                            |
| `content`                             | macOS 受限原生展示树（优先级高于 `icon`/`title`）。                                                                                                                   |
| `tooltip`                             | 悬停提示文本（侧栏提示按 `tray.title` → `tray.error` → `tray.tooltip` → `bar.title` 回退）。                                                                          |
| `error`                               | 取数失败原因（保留上次有效 `title` 并在面板内解释详情）。看板状态维持 `ok`；`title` 为空时 macOS 菜单栏显示 `!`。                                                     |
| `hideDefaultRefresh`                  | `true` 隐藏托盘右键菜单中宿主默认的“刷新”项（探测 `render.tray.menu.hideDefaultRefresh`）。                                                                           |
| `menu`                                | 右键 `MenuItem[]` 菜单；刷新时按 `id` 原地更新并推迟打开期间的结构重建，保留焦点与已展开子菜单。                                                                      |
| `dropFiles` / `onDrop` / `onDragOver` | 在 macOS 菜单栏项及全平台屏幕侧栏图标接收本地文件/目录拖入（见[文件拖放](/zh/docs/components.md#文件拖放)）。                                                                   |

### 菜单栏自定义内容（`tray.content`）

原生 macOS 就绪后支持（探测 `await $metrix.caniuse("render.tray.content")`）；请保留简洁的 `tray.title`/`tray.icon` 作为跨平台与无障碍回退。

- **根节点**：整数 `width`（`16..240` DIP）与 `height: 22`。
- **允许节点与限额**：`Row`、`Column`、`Text`、`Spacer`、`Chart`，以及在 `render.tray.content.icon` 为 `true` 时允许 `Icon`（内联 `svg` ≤ 2048 UTF-8 字节，可选 `fontSize` `8..22`）。整树最多 64 节点、深度 12、文本与内联 SVG 合计 ≤ 4096 字节。
- **属性**：布局 `width`/`height`/`gap`/`padding`/`paddingX`/`paddingY`（`0..240`）、`alignItems`、`justify`；`Text` 支持 `text`、`fontSize`（`8..22`）、`fontWeight`（`100..900`，步长 100）；`Chart` 支持 `type: "line" | "area"`、`series: [{ name, points: [{ x, y }] }]`、`strokeWidth`（`0.5..4`），单图最多 4 条系列、全树最多 120 点（有限 JS 安全整数范围内数值，无坐标轴/图例/悬停/动画）。所有元素在透明背景上使用系统模板前景色，拒绝回调与外部资源。

```js
const tray = { title: "CPU 24%", icon: "ri:cpu-line" };
if (await $metrix.caniuse("render.tray.content")) {
  tray.content = {
    type: "Row",
    props: { width: 96, height: 22, alignItems: "center" },
    children: [{ type: "Text", props: { text: "CPU 24%", fontSize: 12 } }],
  };
}
```

### 菜单栏图标动画（`tray.iconAnimation`）

在 macOS 菜单栏 `tray.title` 旁播放内联 SVG 帧动画（探测 `await $metrix.caniuse("render.tray.iconAnimation")`）。

- `frames`：`1..8` 个独立内联 SVG 字符串数组（每帧 ≤ 2048 UTF-8 字节，保持一致 `viewBox`），按标准菜单栏图标尺寸栅格化并应用 `tray.iconTemplate`。
- `intervalMS`：`80..1000` 整数循环播放，或 `0` 仅展示首帧（开启 macOS 减弱动态效果时同样固定首帧）。播放独立于 Worker 刷新周期；不可用时依次回退 `tray.content`、`tray.icon`/`tray.title`。

### 菜单项格式（`MenuItem[]`）

`tray.menu`、节点 `contextMenu`、`popoverMenu`、`popoverMenuButton` 与 `MenuButton` / `PopoverMenuButton` 共用：

| 字段                           | 说明                                                                                                                                                     |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                           | 可选稳定 ID，用于在刷新期间原地更新菜单项（探测 `render.tray.menu.id`）。                                                                                |
| `label`、`onClick`、`disabled` | 文案、点击回调、禁用状态。                                                                                                                               |
| `subtitle`、`badge`、`icon`    | 副标题、尾部徽章、图标引用（探测 `render.tray.menu.subtitle/badge/icon`）。                                                                              |
| `separator`                    | `true` 渲染分隔线并忽略其余字段。                                                                                                                        |
| `checked`、`radio`、`danger`   | 勾选/单选标记（单选互斥由脚本维护；探测 `render.tray.menu.radio`）及危险操作高亮。                                                                       |
| `keepOpen`                     | 支持的后端点击后保持系统菜单展开（探测 `render.tray.menu.keepOpen`）。                                                                                   |
| `shortcut`、`tooltip`          | 菜单快捷键展示（如 `"Cmd+Shift+P"`，探测 `render.tray.menu.shortcut`；全局热键请用 `registerShortcut`）与 macOS 悬停提示（`render.tray.menu.tooltip`）。 |
| `items`                        | 递归子菜单 `MenuItem[]`。                                                                                                                                |

---

## 面板、屏幕侧栏与窗口（`panel`）

### 打开方式与窗口外观

用户可为六个触发源（`menubar`、`sidebar-left`、`sidebar-right`、`sidebar-bottom`、`shortcut`、`notch`）分别开关并选择打开方式；`<bar open-mode="…" window-style="…">` 仅提供作者默认值：

- **`flyout`（默认）**：从菜单栏或屏幕侧栏图标旁展开的无箭头浮动面板；macOS 保留圆角与系统阴影（`material="transparent"` 时移除）。
- **`dialog`**：全屏半透明遮罩（约 12% 黑色，高对比度约 40%）居中显示面板卡片，不进入系统全屏空间。尺寸按 `preferredWidth`/`preferredHeight` → `width`/`height` → `320×480` DIP 取值，最大占屏幕 80%（四周留白 ≥ 10%），超出内部滚动。点外部或按 `Esc` 关闭（优先关闭内部浮层）。Linux GNOME 原生 Wayland 不可用。
- **`window` / `fullscreen`**：可调大小的独立窗口（面板根设 `resizable: false` 可锁定尺寸），失焦不关闭，记忆尺寸、最大化与全屏状态（`open-mode="fullscreen"` 探测 `open-mode.fullscreen`）。重复触发会聚焦或恢复已开窗口；最小化仍计为打开，不触发 `collapse` 事件。
- **窗口外观（`window-style`）**：`standard`（标准标题栏）、`immersive`（内容从 `(0,0)` 绘制到标题栏后方并保留原生按钮）或 `frameless`（完全无标题栏与边框，探测 `window-style.frameless`）。沉浸式与无边框窗口的非交互区可拖拽移动；组合 `window-style="frameless"` 与 `material="transparent"` 可实现透明无边框悬浮窗。

### 面板材质

通过根属性 `<bar material="glass" | "solid" | "transparent">` 设置宿主面板材质（保存并重载源码后在下次打开生效）：

- **`glass`（默认）**：保留系统毛玻璃（Vibrancy）或半透明 Glass 回退，控件表面半透明；若面板根节点设置不透明背景会遮盖宿主材质。
- **`solid`**：不透明主题 Surface 背景与常规控件。
- **`transparent`**（探测 `render.panel.material.transparent`）：移除宿主填充、边框与阴影，使自定义卡片或异形面板直接悬浮于桌面（不改变 Dialog 遮罩）。

### 响应式窗口与安全区

- 在面板根节点设置 `preferredWidth` / `preferredHeight` 指定初始窗口、浮动面板与预览尺寸且不锁死布局；未设高度时，浮动面板与管理窗口预览自适应内容高度，上限 **640 DIP**（更高内容在内部使用 `Scroll`）。
- 沉浸式窗口中给根 `Box`/`Column`/`Row`/`Grid` 设置 `safeArea: true`，背景仍从 `(0,0)` 铺满，子内容、点击热区与裁切自动避开标题栏按钮（不可用于状态样式；嵌套不重复累加）。将 `Scroll` 置于安全区内部并配 `grow: 1, minHeight: 0`。
- 仅在需要列数切换等结构断点时读取 `env.viewport`（`{ width, height, titleBar: { height, left, right } }`，单位 DIP）；常规缩放交给原生弹性/网格布局。

```js
const panel = {
  type: "Column",
  props: { preferredWidth: 420, preferredHeight: 560, fill: true, minHeight: 0, safeArea: true },
  children: [
    Header(),
    { type: "Scroll", props: { grow: 1, minHeight: 0, fillWidth: true }, children: [Body()] },
  ],
};
```

### 屏幕侧栏

屏幕侧栏一次仅展开一个屏幕边缘轨道（指针在屏幕外缘中间 25%–75%、2 DIP 宽的热区停留约 100 ms 展开，离开轨道/面板/菜单 300 ms 后收起）。图标按 `tray.icon` → `bar.icon` → 通用图标回退。按住 `Cmd`（macOS）或 `Ctrl`（Windows/Linux）拖动图标可全局排序看板。Linux 需要 X11 或支持 `libgtk-layer-shell.so.0` 的 Wayland 合成器。

### 程序化面板控制（`$metrix.panel`）

需要 `panel="true"`（默认）。若声明 `<bar panel="false">`，点击托盘/侧栏图标直接弹右键菜单，隐藏面板预览与面板专属设置，点击系统小组件改为在主窗口打开该看板，`$metrix.panel.*` 拒绝执行，且 `caniuse("panel")` / `caniuse("render.panel")` 返回 `false`。

以下方法无需 `apis` 声明，仅操作当前看板，均返回 `Promise<PanelState>`（`{ open, mode, source, alwaysOnTop, alwaysOnTopSupported, alwaysOnTopEffective, fullScreen }`；`mode` 为 `flyout|dialog|window|null`，`source` 为 `menubar|notch|sidebar-left|sidebar-right|sidebar-bottom|shortcut|desktop-app|programmatic|null`）：

- `$metrix.panel.open()`、`close()`、`toggle()`、`state()`（含 `$metrix.togglePanel()`）：遵循生效的默认 `open_mode`（无屏幕定位能力时 Dialog 拒绝打开）。预检仅允许 `state()`。
- `await $metrix.panel.setAlwaysOnTop(boolean)`：持久化并应用独立窗口置顶偏好（探测 `panel.setAlwaysOnTop`；macOS/Windows 返回实际 `alwaysOnTopEffective`，X11 返回 `null`，Wayland 拒绝开启但允许清除）。
- `await $metrix.panel.setFullScreen(boolean)` 与 `await $metrix.panel.isFullScreen()`：切换或查询独立窗口原生全屏状态（探测 `panel.setFullScreen`、`panel.isFullScreen`）。

---

## 系统小组件（`widget`）

在 `<bar>` 上声明 `widget="true"` 并从 `render()` 返回 `widget: { small?, medium?, large? }`。缺失尺寸按 `small` → `medium` → `large` 顺序回退。探测 `widget` 与 `render.widget`。需要 macOS 14+、Windows 11 22H2+、KDE Plasma 6（配套 plasmoid）或 Linux `MetrixWidgetAdapters/`（Cinnamon Desklet、Eww、Quickshell）。

各平台物理宽高比不同（macOS `small` 为正方形、`medium` 为横向宽卡；Windows `small` 为横向宽卡、`medium` 近似正方形；KDE Plasma 默认 `180×180`，达到 `300×180` 切至 `medium`、达到 `300×360` 切至 `large`）。请根据只读 `$metrix.platform`（`"darwin" | "windows" | "linux" | "js"`）区分结构，切勿拿 `env.viewport` 当小组件尺寸：

```js
const isWin = $metrix.platform === "windows";
return {
  widget: {
    small: isWin ? horizontalSummary() : squareSummary(),
    medium: isWin ? squareDetails() : horizontalDetails(),
    large: fullDetails(),
  },
};
```

### 支持的小组件子集

仅支持显式属性，不支持 `tw` 类名、回调、交互控件与 Markdown（文本严格按字面渲染；点击卡片打开或聚焦看板窗口）：

| 组件                      | 支持的展示属性                                                                                                                                                          |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `Column`、`Row`、`Box`    | `gap`、`padding`、`alignItems`（`start`/`center`/`end`）、`width`、`height`、`background`、`radius`                                                                     |
| `Grid`                    | `Column` 属性 + `columns`（`1..12`，等宽列）                                                                                                                            |
| `Text`                    | `text`、`fontSize`（`8..96`）、`fontWeight`（`100..900`）、`bold`、`italic`、`color`/`textColor`、`maxLines`（`1..10`）、`textAlign`、`padding`                         |
| `RichText`                | `Text` 样式 + `spans`（≤ 128 个纯文本片段：`text`、`size`、`weight`、`italic`、`underline`、`strikethrough`、`color`；探测 `render.widget.richText`）                   |
| `Badge`                   | `text`、`fontSize`、`fontWeight`、`bold`、`italic`、`color`/`textColor`、`background`（探测 `render.widget.badge.background`）、`padding`                               |
| `Avatar`                  | `name`、`src`、`size`（`8..96`，默认 `32`）、`color`/`textColor`、`background`、`padding`（探测 `render.widget.avatar`）                                                |
| `Icon`                    | 内联 `svg`（≤ 64 KiB，单色遮罩渲染）、`size`（`8..96`，默认 `16`）、`color`/`textColor`、`padding`                                                                      |
| `Image`                   | `src`（已授权 URL 或 `metrix-image://`）、`width`、`height`、`radius`、`padding`                                                                                        |
| `Progress`                | `value`（`0..1`）、`color`/`textColor`、`padding`                                                                                                                       |
| `Meter`                   | `value`、`min`（`0`）、`max`（`1`）、`levels: { warning?, critical? }`、`color`/`textColor`、`padding`（探测 `render.widget.meter`）                                    |
| `Chart`                   | `type`（`line`/`area`/`bar`/`pie`）、`height`、`width`、`series`、`data`、`innerRadius`（`0..0.95`）、`yDomain`、`strokeWidth`、`padding`（探测 `render.widget.chart`） |
| `Spacer`、`Divider`、文本 | 原生间距、分隔线（`orientation: "horizontal"                                                                                                                            | "vertical"`，探测 `render.widget.divider.orientation`）或字面文本 |

- **颜色**：`primary`、`secondary`、`accent`、`success`、`warning`、`error` 或 `#RRGGBB` / `#RRGGBBAA`。
- **小组件 `Chart`**：宿主以 2× 密度渲染为透明 PNG 快照（最大 `1024×256` DIP），不含坐标轴、图例与悬停（传入交互属性会报错）。`line`/`area`/`bar` 最多 4 条 `series`（每条最多 256 个等距数值或 `{ y }`）；`pie` 最多 16 项 `{ value, color }`。
- **Windows Adaptive Cards 1.6**：语义背景映射为卡片样式（忽略十六进制背景与 `radius`），自定义十六进制文字色回退为主文本色，首行自动为系统菜单留空，`Progress` 用比例列与缓存色块绘制。
- **限额与生命周期**：上限 512 节点、深度 24、512 KiB 目录；图片单边 ≤ 2048 px、总像素 ≤ 1,048,576、源文件 ≤ 8 MiB / PNG ≤ 4 MiB，共享 64 MiB / 128 文件缓存。密钥、输入与诊断错误绝不导出。刷新失败保留上次成功快照。已配置小组件需求使 Worker 保持活跃（自动轮询最低 1 分钟）；卡片刷新时机由系统决定。

---

## 刘海屏（`notch`）

在 `<bar>` 上声明 `notch="true"`。macOS 与 Windows 开通 Plus 后可用（无物理刘海显示器自动启用虚拟刘海；Linux 隐藏）。探测 `await $metrix.caniuse("render.notch")`。

从 `render()` 返回 `notch: { compact: { leading, trailing }, minimal, expanded, activity?, onFileDrop?, transferFormats?, onTransferDrop? }`：

- **状态与尺寸**：按 `$metrix.outputs().notch`（`"compact" | "minimal" | "expanded"` 或省略）仅渲染当前所需状态。
  - `compact.leading` / `compact.trailing`：摄像头左右两翼（宽 ≥ 36 DIP，高约 20–26 DIP）——每侧只放一个图标、封面或不超过 4 个字符的数值（如 `100%`）。
  - `minimal`：第二个刘海屏看板在岛屿旁的小圆形气泡（更多看板在该气泡计数，并在展开视图中切换）。
  - `expanded`：可交互面板树（上限 `460×340` DIP，超出滚动），支持常规 Worker 回调；macOS 悬停预览，macOS/Windows 点击展开并带固定、切换与打开完整面板按钮。
- **临时活动（`notch.activity`）**：`{ id, expiresAt }`（每次新活动用新 `id`，绝对 Unix 毫秒时间戳 `expiresAt`，最长 8 小时；探测 `render.notch.activity`）可将看板临时切入岛屿，到期、移除或用户关闭后恢复原顺序。
- **程序化自动展开（`$metrix.notch.setState`）**：需用户在看板显示设置开启 **允许自动展开刘海屏**（默认关闭；探测 `notch.setState`）：
  ```js
  if (await $metrix.caniuse("notch.setState")) {
    await $metrix.notch?.setState("expanded", { durationMs: 8000 });
  }
  ```
  `durationMs` 范围 `1..30000`（默认 `8000`），不抢占当前应用键盘焦点，结束后有 3 秒冷却期，返回 `"accepted" | "busy" | "unavailable" | "idle"`。调用 `setState("collapsed")` 可提前收起本 Worker 的自动预览。
- **拖放**：设置 `notch.onFileDrop`（探测 `render.notch.fileDrop`，事件 `source: "notch"`）或 `notch.transferFormats` + `notch.onTransferDrop`（探测 `render.notch.transfer`），详见[文件拖放](/zh/docs/components.md#文件拖放)与[富媒体传输](/zh/docs/components.md#富媒体传输)。

---

## 屏幕覆盖层（`overlay`）

声明 `<bar overlay="true">` 后，可通过 `render().overlay` 渲染无边框全屏透明覆盖层，并用 `$metrix.overlay` 控制：

- `await $metrix.overlay.open({ displays?: "primary" | "cursor" | "all" | string[], clickThrough?: boolean })` → `{ open, displays, clickThrough }`
- `await $metrix.overlay.close()` / `await $metrix.overlay.state()`

启用 `clickThrough: true`（探测 `overlay.clickThrough`）时，除标记了 `inputRegion: true` 的子树外，所有鼠标事件均穿透至下层应用。按 `Esc` 可关闭覆盖层；点击穿透模式必须依赖全局退出快捷键（macOS `Cmd+Shift+Esc`，Windows/Linux `Ctrl+Shift+Esc`），快捷键不可用时 `open()` 会拒绝。Worker 关闭或看板停用时自动关闭覆盖层。探测 `overlay`、`overlay.*` 与 `render.overlay`（无 layer-shell 的 GNOME 原生 Wayland 返回 `false`）。

---

## 选区浮窗（`selectionPopover`）

声明 `<selection-actions>` 的看板可返回独立的 `render().selectionPopover` 组件树（省略时回退 `render().panel`），将结果锚定在选中文本旁显示而不替换主面板，并通过 `$metrix.selectionPopover` 控制：

- `await $metrix.selectionPopover.open({ anchor?: { x, y, width, height }, pinned?: boolean })` → `{ open, pinned }`
- `await $metrix.selectionPopover.close()` / `setPinned(boolean)` / `state()`

按 `Esc` 始终可关闭选区浮窗；给任意标题栏容器设置 `dragWindow: true` 即可自由拖拽。探测 `selectionPopover`、`selectionPopover.*` 与 `render.selectionPopover`。
