如何管理设计系统

用 SDK 以编程方式创建、更新设计系统,并将其应用到屏幕。

设计系统为你的项目定义视觉规则——颜色、排版、间距。当你把它应用到屏幕时,每个屏幕都会遵循同一套视觉语言。有了 SDK,你无需打开 Stitch UI,就能创建、更新和应用设计系统。

创建设计系统

import { stitch } from "@google/stitch-sdk";

const project = stitch.project("your-project-id");
const ds = await project.createDesignSystem({ displayName: "My Theme" });
console.log(`Created: ${ds.id}`);

displayName 是显示在 Stitch UI 中的名称。取一个描述性的名字——比如 “Brand Dark Mode” 就比 “DS 1” 好。

列出现有的设计系统

const systems = await project.listDesignSystems();
for (const ds of systems) {
  console.log(`${ds.id}: ${ds.data?.displayName}`);
}

通过 ID 引用设计系统

如果已经知道资产 ID,就可以跳过网络请求:

const ds = project.designSystem("existing-asset-id");

这样只会创建一个句柄,不会从服务器获取任何内容。当你从前面的步骤或 Stitch UI 中已经知道 ID 时,就用这种方式。

从 DESIGN.md 创建

已经有定义视觉识别规范的 DESIGN.md?只需两次调用,就能把它上传并转换为设计系统:

import { readFileSync } from "node:fs";

const markdown = readFileSync("DESIGN.md", "utf-8");
const instance = await project.uploadDesignMd(Buffer.from(markdown, "utf-8").toString("base64"));
const ds = await project.createDesignSystemFromDesignMd(
  { id: instance.id, sourceScreen: instance.sourceScreen },
  "DESKTOP",
);

完整的操作指引——包括如何应用结果以及直接使用 callTool——请参阅如何从 DESIGN.md 创建设计系统。

更新设计系统

const updated = await ds.update({ displayName: "Updated Theme" });

应用到屏幕

应用设计系统会用新的视觉令牌重新渲染屏幕。你需要 SelectedScreenInstance 对象——从项目的屏幕实例中获取:

const projectData = await stitch.callTool("get_project", {
  name: `projects/${project.id}`,
});

// Extract screen instances
const instances = projectData.screenInstances.map((si: any) => ({
  id: si.id,
  sourceScreen: si.sourceScreen,
}));

// Apply the design system to all screens
const screens = await ds.apply(instances);
console.log(`Applied to ${screens.length} screens`);

实例对象中只应包含 id 和 sourceScreen。位置或尺寸之类的多余字段会引发 “invalid argument” 错误。

完整工作流:创建并应用

以下是端到端的模式——创建项目、生成屏幕、创建设计系统并应用它:

import { stitch } from "@google/stitch-sdk";

const project = await stitch.createProject("Themed App");

// Generate a few screens
const home = await project.generate("A landing page for a productivity app");
const settings = await project.generate("A settings page with dark theme toggle");

// Create and apply a design system
const ds = await project.createDesignSystem({ displayName: "Productivity Theme" });

// Get screen instances for applying
const projectData = await stitch.callTool("get_project", {
  name: `projects/${project.id}`,
});

const instances = projectData.screenInstances.map((si: any) => ({
  id: si.id,
  sourceScreen: si.sourceScreen,
}));

await ds.apply(instances);
console.log("Design system applied to all screens");

原文: https://stitch.withgoogle.com/docs/sdk/design-systems/

本页翻译自 Google Stitch 官方文档,原文版权归 Google LLC 所有。本站为独立第三方翻译,与 Google 无关联。