AI 速查 (llms.txt)
AI 速查

进阶参考 / AI 速查

Deskset React Widget SDK — AI Quick Reference (llms.txt)

将这份精炼单文件规范直接喂给 Claude、ChatGPT、Gemini 或 Cursor,即可一次生成符合 Deskset 原生规范的 TSX 小组件。

打开纯文本 .txt

Use this reference when writing Deskset desktop widgets in TypeScript/TSX. Deskset runs .tsx source directly in a sandboxed JavaScriptCore VM (built-in Sucrase transpiler, zero external bundler or Node.js required) and renders the returned element tree into native macOS SwiftUI views.

Hard Rules#

  1. Import ALL primitives and hooks from "deskset-react" (no HTML tags like <div>, <span>, <p>, <svg>; no CSS, no DOM, no Node.js APIs).
  2. Export a default function component: export default function MyWidget() { ... }.
  3. Both deskpack.json sizes and useWidget().size / useWidget().match use the unified names "small" | "medium" | "large" | "custom". Declare supported sizes and optional custom dimensions in deskpack.json (sizes & sizeDimensions), and adapt inside your component via useWidget().match({ small: () => <...>, medium: () => <...>, large: () => <...>, custom: () => <...>, default: () => <...> }) or live width / height (pt).
  4. Always support both Glass (!theme.isPure) and Minimal/Transparent (theme.isPure) finishes:
    TSX
       const card = {
         maxWidth: true,
         maxHeight: true,
         background: theme.isPure ? "clear" : "theme.card",
         cornerRadius: theme.isPure ? 0 : theme.corner,
         clip: !theme.isPure,
       } as const;
  5. Prefer semantic theme colors for text and chrome so Minimal mode auto-adapts to dark/light wallpapers:
    theme.ink, theme.secondary, theme.tertiary, theme.accent, theme.card (background only), theme.faint, theme.raised, theme.track, theme.divider, theme.surface, theme.danger, theme.success, theme.warning, theme.blue, theme.purple.
  6. When useWidget().isPreview is true, timers/network/storage/actions are disabled — render realistic sample data, never a loading spinner.
  7. Default content sizes in points: small = 164×164, medium = 344×164, large = 344×344, custom = 420×220 (overridable via deskpack.json sizeDimensions). Keep first render < 250 ms and node count well under 1000.

Hooks & Runtime APIs (from "deskset-react")#

  • React hooks: useState, useReducer, useRef, useMemo, useCallback, useEffect, useLayoutEffect, useContext, createContext, Fragment, Children, cloneElement
  • API_VERSION (1)
  • useWidget() -> { widgetId, packageId, size: "small"|"medium"|"large"|"custom", width, height, isPreview, isPro, isCommunityPack, locale, locales, defaultLocale, isZh, t(key, vars?), match, settings, theme, apiVersion, reduceMotion, fetch }
    • match({ small?, medium?, large?, custom?, default? }): declaratively pick JSX (wrap in () => <...> for lazy evaluation) or scalar values (e.g. match({ small: 12, medium: 16, default: 18 })) for the current size
    • theme: { style: "modern", material: "glass"|"graphite"|"pure", isDark, isPure, accent, ink, secondary, surface, corner, wallpaperTone?, use24Hour?, firstWeekday?, tempUnit?, timeZone?, utcOffsetSeconds? }
    • t("key") / t("nested.key") / t("summary", { done: 3, total: 5 }) resolves from locales/<tag>.json (for tiny single-file widgets without locales/, t("中文", "English"), t("中文", { en, ja }), and t("还差 {0} 次", "{0} to go", n) also work).
  • useStorage<T>(key: string, defaultValue: T) -> [value, setValue] (per-instance persistent JSON, max 256 KiB/key, 512 KiB/instance)
  • useSetting<T>(key: string, fallback: T) -> [value, setValue] (reads/writes manifest options keys; cannot touch appearance.* or desktop.*)
  • useInterval(callback: () => void, delayMs: number | null) (paused when delayMs === null or isPreview)
  • useFetch<T>(url: string | null | undefined, { refreshMs?, method?, headers?, body?, responseType?: "json"|"text", fallback? }) -> { data, loading, error, status, reload } (direct public HTTP/HTTPS fetch, no manifest domain list needed)
  • useHostData<T>(service: "clock"|"calendar"|"system"|"battery", fallback: T, params?) -> live read-only snapshot (directly available, no manifest permissions needed)
  • useHostAction() -> act(action, payload):
    • act("openURL", { url })
    • act("copyText", { text })
    • act("openInspector")
    • act("updateSetting", { key, value })

UI Primitives (from "deskset-react")#

  • Common StyleProps on all primitives:
    padding (number or { top, bottom, leading, trailing, horizontal, vertical }), spacing, alignment (leading|center|trailing|top|bottom|topLeading|topTrailing|bottomLeading|bottomTrailing|firstTextBaseline|lastTextBaseline), width, height, minWidth, minHeight, maxWidth (true|number), maxHeight (true|number), background, material (ultraThin|thin|regular|thick|pill|glass), gradient ({ colors, start?, end?, kind?: "linear"|"radial"|"angular" }), cornerRadius, clip, borderColor, borderWidth, shadow (bool or { color?, radius?, x?, y? }), opacity, blurRadius, offsetX, offsetY, zIndex, rotation (deg), scale (0–8), animation (none|spring|easeInOut|easeIn|easeOut|linear), animationDuration (0.05–2s), onClick(), onClickAt({ x, y, width, height }), onHover(hovered)
  • Layout: VStack, HStack, ZStack, Box, FullBleed, Spacer({ minLength? }), Divider({ color?, opacity?, vertical? }), ScrollView({ axis?: "vertical"|"horizontal", showsIndicators? }), Grid({ columns?, rowSpacing?, columnSpacing? })
  • Content:
    • Text({ text?, fontSize?, fontWeight?, fontDesign?: "default"|"rounded"|"monospaced"|"serif", color?, lineLimit?, multilineAlignment?, monospacedDigits?, minimumScaleFactor?, strikethrough?, italic?, tracking?, lineSpacing? })
    • Icon({ name, size?, weight?, color?, renderingMode? }) (SF Symbols)
    • Image({ asset?, src?, base64?, scaleMode?: "fill"|"fit", tintOverlay? })
    • Badge({ text, icon?, color?, background?, fontSize? })
  • Data Viz:
    • ProgressBar({ value, total?, color?, trackColor?, height?, orientation?: "horizontal"|"vertical" })
    • Ring({ value, total?, color?, trackColor?, lineWidth?, size? })
    • RingGauge({ value, total?, size?, lineWidth?, color?, trackColor?, gradientColors?, icon?, iconSize?, centerText?, centerFontSize?, subText?, subFontSize?, textColor? })
    • Chart({ kind: "line"|"area"|"bar"|"heatmap", values, labels?, color?, secondaryColor?, minValue?, maxValue?, showBaseline?, columns? })
    • Canvas({ viewWidth?, viewHeight?, ops }) — ops entries: { op: "rect"|"roundedRect"|"circle"|"ellipse"|"arc"|"line"|"polyline"|"polygon"|"text", x?, y?, w?, h?, r?, rx?, ry?, x1?, y1?, x2?, y2?, cx?, cy?, startDeg?, endDeg?, anticlockwise?, closed?, points?, text?, fontSize?, fontWeight?, fontDesign?, italic?, align?, fill?, fillGradient?, stroke?, strokeGradient?, lineWidth?, lineCap?, dash?, dashPhase?, rotateDeg?, pivotX?, pivotY?, opacity? }
  • Controls:
    • Button({ title?, icon?, iconSize?, fontSize?, variant?: "plain"|"tinted"|"filled"|"pill"|"circle"|"glass", color?, disabled?, onClick? })
    • Toggle({ value, label?, color?, onChange? })
    • Slider({ value, min?, max?, step?, color?, onChange? })
    • TextField({ value, placeholder?, multiline?, fontSize?, lineSpacing?, color?, onChange?, onSubmit? })
    • Segmented({ options: [{ id, label, icon? }], value, onChange? })

Localization (locales/)#

Preferred i18n pattern: put UTF-8 JSON translation files in locales/<tag>.json (BCP-47 tag matching ^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$, 2–35 chars, max 64 files, ≤ 1 MiB total, no case-insensitive duplicates) and set "defaultLocale": "en" in deskpack.json.

  • Optional _meta localizes widget metadata & option labels/choices; other keys are string leaves or nested objects (dot-accessible via t("status.done")) with {var} interpolation (t("remaining", { count: 3 })).
  • Resolution chain: exact locale -> stripped subtag (zh-Hans-CN -> zh-Hans -> zh) -> defaultLocale -> "en" -> raw key. _meta falls back to deskpack.json name/nameZh, description/descriptionZh, and options[k].label/labelZh/labelEn.
JSON
// locales/en.json
{
  "_meta": {
    "name": "My Widget",
    "description": "Short description",
    "options": {
      "title": "Title",
      "mode": { "label": "Mode", "choices": { "compact": "Compact", "detailed": "Detailed" } }
    }
  },
  "status": { "done": "Done for today" },
  "summary": "{done} of {total} completed"
}

deskpack.json Template#

JSON
{
  "id": "com.you.my-widget",
  "name": "My Widget",
  "nameZh": "我的小组件",
  "version": "1.0.0",
  "description": "Short description",
  "descriptionZh": "简短说明",
  "defaultLocale": "en",
  "author": "@you",
  "category": "productivity",
  "icon": "sparkles",
  "sizes": ["small", "medium", "large"],
  "styles": ["glass", "minimal"],
  "accentColor": "#FF6B2C",
  "minimumAppVersion": "1.3.0",
  "options": {
    "title": { "type": "string", "label": "标题", "labelEn": "Title", "default": "Hello", "order": 1 },
    "goal": { "type": "number", "label": "目标", "labelEn": "Goal", "default": 10, "min": 1, "max": 100, "order": 2 },
    "mode": { "type": "choice", "label": "模式", "labelEn": "Mode", "choices": ["compact", "detailed"], "default": "compact", "order": 3 },
    "enabled": { "type": "boolean", "label": "启用提醒", "labelEn": "Enable reminder", "default": true, "order": 4 },
    "tint": { "type": "color", "label": "主题色", "labelEn": "Accent", "default": "#0EA5E9", "order": 5 }
  }
}

Note: id must match ^[a-z0-9][a-z0-9._-]{2,63}$. Valid category values: "time"|"productivity"|"media"|"info"|"system"|"community". Declare "styles": ["glass", "minimal"] to expose per-widget Glass/Minimal switching. Option keys cannot start with appearance. or desktop..