快速入门
JSWidget 让你可以使用 JavaScript 和 JSX 语法编写 iOS/macOS 小组件。
基本结构
入口脚本(如 main.jsx)直接写顶层代码即可。桌面小组件在该文件中调用 $render() 渲染组件树;灵动岛等场景请改用 $dynamic_island,详见 API 文档。
jsx
$render(
<col>
<text font="title">Hello World</text>
</col>
);JSX 元素
JSWidget 提供了一套类似 SwiftUI 的 JSX 元素,直接对应到原生 SwiftUI 组件。
元素名称使用小写(与标准 JSX 不同):
jsx
// 布局容器
<col> // 垂直排列
<row> // 水平排列
<stack> // 层叠排列
// 内容元素
<text> // 文本
<image> // 图片
<spacer> // 间距常用属性
jsx
<col size="max" padding={16}>
<text font="title" color="#1e293b">标题</text>
<text font="caption" color="#64748b">副标题</text>
<spacer />
<text font="body">内容</text>
</col>font 可选值:largeTitle | title | title2 | title3 | headline | subheadline | body | callout | footnote | caption
color 格式:颜色名称("red")| 十六进制("#ff0000")| rgba("rgba(255,0,0,0.5)")
获取数据
使用 $http 或 fetch 发起网络请求,配合 async/await:
jsx
const response = await $http.get("https://api.example.com/data");
const data = JSON.parse(response);
$render(
<col size="max" padding={16}>
<text font="headline">{data.title}</text>
<text font="body">{data.description}</text>
</col>
);适配小组件尺寸
通过 $getenv("widget-size") 获取当前小组件尺寸,实现响应式布局:
jsx
const size = $getenv("widget-size"); // "small" | "medium" | "large"
$render(
<col size="max" padding={size === "small" ? 8 : 16}>
{size === "small" ? (
<text font="caption">简略内容</text>
) : (
<col>
<text font="title">完整内容</text>
<text font="body">详细描述...</text>
</col>
)}
</col>
);本地存储
使用 $storage 在脚本运行间持久化数据:
jsx
// 存储数据
$storage.setString("lastUpdate", new Date().toISOString());
$storage.setJSON("config", { theme: "dark", fontSize: 14 });
// 读取数据
const lastUpdate = $storage.getString("lastUpdate");
const config = $storage.getJSON("config");