useWidget
HOOK

HOOKS & API / 运行时上下文

useWidget

读取当前小组件实例的实时运行时上下文:当前尺寸与宽高、按尺寸惰性匹配函数 match、外观主题、用户设置值、预览状态、基于 locales/ 的多语言翻译工具,以及实例专属的 fetch 函数。

签名#

签名
const {
  size, width, height, match,
  theme, settings, isPreview,
  t, locale, locales, defaultLocale, isZh,
  reduceMotion, fetch,
} = useWidget();

返回字段#

sizestring只读
当前实例的尺寸档位,值为 "small"、"medium"、"large" 或 "custom"(与 deskpack.json 完全一致,请勿写旧称 "middle")。
widthnumber只读
当前画布实时宽度(逻辑像素 pt),用户拖拽调整自由尺寸时实时变化。
heightnumber只读
当前画布实时高度(逻辑像素 pt)。
matchfunction工具函数
按当前尺寸声明式匹配视图或参数:match({ small?, medium?, large?, custom?, default? })。传 JSX 时建议用 () => <...> 包裹以惰性求值(未命中尺寸不会执行);选字号、间距等标量值可直接传值。提供 default 或 4 个尺寸齐全时返回非空 T,否则未命中返回 null。
themeWidgetTheme只读
当前材质、明暗模式、强调色与系统时间/温度偏好,完整字段见 主题与样式。
settingsobject只读
deskpack.json 中 options 的当前生效值(已自动合并用户修改与默认值)。如需在组件内修改,请用 useSetting。
isPreviewboolean只读
当组件显示在组件库、导入预览或缩略图中时为 true;此时网络和定时器暂停,请直接展示好看的示例数据。
localestring只读
当前生效的语言代码(来自 macOS 系统语言,或在工坊预览栏中选定的预览语言,如 "zh-Hans"、"en")。
localesobject可选
从组件包 locales/<tag>.json 加载的原始多语言词典表(按 BCP-47 标签索引)。
defaultLocalestring可选
deskpack.json 中声明的默认回退语言代码(未设置时默认为 "en")。
isZhboolean只读
当前是否处于中文语言环境。
tfunction工具函数
统一翻译函数:优先从 locales/<tag>.json 按键取值,支持嵌套点路径与 {var} 命名插值(如 t("status.done")、t("todayCount", { count })),并沿 BCP-47 回退链自动降级;单文件小组件也可使用内联写法 t("中文", "English")、t("中文", { en, ja }) 或位置插值 t("今日 {0} 项", "{0} today", count)。详见 多语言指南。
widgetIdstring只读
当前桌面小组件实例的唯一 ID(同款小组件拖出两张时各自独立)。
packageIdstring只读
来自 deskpack.json 的包 ID。
isProboolean只读
当前 Mac 是否已解锁 Deskset Pro。
isCommunityPackboolean可选
当前是否作为社区 .deskpack 包运行。
apiVersionnumber可选
宿主 SDK API 版本号(当前为 1),可用于做向后兼容判断。
reduceMotionboolean可选
用户是否在 macOS 系统设置中开启了「减少动态效果」;为 true 时建议避免位移动画。
fetchfunction可选
绑定当前实例身份的 fetch(url, init) 函数;在连续多步 await 请求场景下推荐优先使用。

按尺寸声明式渲染:match(...)#

所有小组件均为标准 React 函数组件。在 deskpack.json 的 sizes(及可选 sizeDimensions)声明支持的尺寸与自定义宽高后,可在组件顶部统一编写共享 Hooks、状态与卡片外框,再通过 match(...) 优雅分发各尺寸布局或样式数值:

TSX
import React, { HStack, Icon, Spacer, Text, VStack, useWidget } from "deskset-react";

export default function StatusCard() {
  const { width, settings, theme, t, isPreview, reduceMotion, match } = useWidget();
  const count = isPreview ? 12 : Number(settings.count || 0);

  // 选字号、间距、尺寸等标量值可直接写值(提供 default 时 TS 自动收窄为 number)
  const valueSize = match({ small: 24, medium: 30, large: 38, default: 30 });
  const pad = match({ small: 12, default: 16 });

  return (
    <VStack
      maxWidth={true}
      maxHeight={true}
      padding={pad}
      background={theme.isPure ? "clear" : "theme.card"}
      cornerRadius={theme.isPure ? 0 : theme.corner}
      clip={!theme.isPure}
      animation={reduceMotion ? "none" : "spring"}
    >
      {/* 选 JSX 时用 () => 包裹,只有当前命中的尺寸才会执行 */}
      {match({
        small: () => (
          <VStack maxWidth={true} maxHeight={true} alignment="leading" spacing={6}>
            <Icon name="checkmark.seal.fill" size={16} color="theme.accent" />
            <Spacer />
            <Text fontSize={valueSize} fontWeight="bold" monospacedDigits>
              {String(count)}
            </Text>
            <Text fontSize={12} color="theme.secondary" lineLimit={1}>
              {t("completed")}
            </Text>
          </VStack>
        ),
        medium: () => (
          <HStack maxWidth={true} maxHeight={true} spacing={12} alignment="center">
            <Icon name="checkmark.seal.fill" size={28} color="theme.accent" />
            <VStack alignment="leading" spacing={4}>
              <Text fontSize={13} fontWeight="semibold" color="theme.secondary">
                {t("completed")}
              </Text>
              <Text fontSize={valueSize} fontWeight="bold" monospacedDigits>
                {t("todayCount", { count })}
              </Text>
            </VStack>
            <Spacer />
          </HStack>
        ),
        default: () => (
          <VStack maxWidth={true} maxHeight={true} alignment="leading" spacing={8}>
            <HStack spacing={6} alignment="center">
              <Icon name="checkmark.seal.fill" size={18} color="theme.accent" />
              <Text fontSize={14} fontWeight="semibold" color="theme.secondary">
                {t("completed")}
              </Text>
              <Spacer />
              <Text fontSize={11} color="theme.tertiary" monospacedDigits>
                {`${Math.round(width)}pt`}
              </Text>
            </HStack>
            <Spacer />
            <Text fontSize={valueSize} fontWeight="bold" monospacedDigits>
              {t("todayCount", { count })}
            </Text>
          </VStack>
        ),
      })}
    </VStack>
  );
}

注意事项#

  • size 与 match 键名已统一为 "small"、"medium"、"large"、"custom";如果在代码里误写 size === "middle" 或 match({ middle: ... }),小组件工坊 会直接报错提示修正。
  • 传给 match(...) 的 JSX 分支请用 () => <...> 包裹以实现惰性求值,避免未命中尺寸里的 .map() 或派生计算白跑;另外不要在 match 的回调函数体内直接调用 React Hooks,把所有 Hooks 放在组件函数顶部即可。
  • 编写自由尺寸(custom)组件时,结合 width 和 height 动态调整字号与列数,效果最自然。