Deskset React Widget SDK — AI Quick Reference (llms.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#
- Import ALL primitives and hooks from
"deskset-react"(no HTML tags like<div>,<span>,<p>,<svg>; no CSS, no DOM, no Node.js APIs). - Export a default function component:
export default function MyWidget() { ... }. - Both
deskpack.jsonsizesanduseWidget().size/useWidget().matchuse the unified names"small" | "medium" | "large" | "custom". Declare supported sizes and optional custom dimensions indeskpack.json(sizes&sizeDimensions), and adapt inside your component viauseWidget().match({ small: () => <...>, medium: () => <...>, large: () => <...>, custom: () => <...>, default: () => <...> })or livewidth/height(pt). - Always support both Glass (
!theme.isPure) and Minimal/Transparent (theme.isPure) finishes:TSXconst card = { maxWidth: true, maxHeight: true, background: theme.isPure ? "clear" : "theme.card", cornerRadius: theme.isPure ? 0 : theme.corner, clip: !theme.isPure, } as const; - 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. - When
useWidget().isPreviewistrue, timers/network/storage/actions are disabled — render realistic sample data, never a loading spinner. - Default content sizes in points:
small=164×164,medium=344×164,large=344×344,custom=420×220(overridable viadeskpack.jsonsizeDimensions). 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 currentsizetheme:{ 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 fromlocales/<tag>.json(for tiny single-file widgets withoutlocales/,t("中文", "English"),t("中文", { en, ja }), andt("还差 {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 manifestoptionskeys; cannot touchappearance.*ordesktop.*)useInterval(callback: () => void, delayMs: number | null)(paused whendelayMs === nullorisPreview)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
StylePropson 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 })—opsentries:{ 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
_metalocalizes widget metadata & option labels/choices; other keys are string leaves or nested objects (dot-accessible viat("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._metafalls back todeskpack.jsonname/nameZh,description/descriptionZh, andoptions[k].label/labelZh/labelEn.
// 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#
{
"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..