如何管理設計系統

用 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 無關聯。