Block Kit

本頁內容

EmDash 的 Block Kit 允許沙盒外掛將其後台 UI 描述為 JSON。宿主渲染這些區塊 — 不會有外掛提供的 JavaScript 在瀏覽器中執行。

運作原理

  1. 使用者導覽到外掛的後台頁面
  2. 後台向外掛的後台路由傳送 page_load 互動
  3. 外掛傳回包含區塊陣列的 BlockResponse
  4. 後台使用 BlockRenderer 元件渲染這些區塊
  5. 當使用者互動(點選按鈕、提交表單)時,後台將互動傳送回外掛
  6. 外掛傳回新區塊,迴圈重複
// 外掛後台路由處理器
routes: {
  admin: {
    handler: async (ctx, { request }) => {
      const interaction = await request.json();

      if (interaction.type === "page_load") {
        return {
          blocks: [
            { type: "header", text: "My Plugin Settings" },
            {
              type: "form",
              block_id: "settings",
              fields: [
                { type: "text_input", action_id: "api_url", label: "API URL" },
                { type: "toggle", action_id: "enabled", label: "Enabled", initial_value: true },
              ],
              submit: { label: "Save", action_id: "save" },
            },
          ],
        };
      }

      if (interaction.type === "form_submit" && interaction.action_id === "save") {
        await ctx.kv.set("settings", interaction.values);
        return {
          blocks: [/* ... 更新的區塊 ... */],
          toast: { message: "Settings saved", type: "success" },
        };
      }
    },
  },
}

區塊類型

類型描述
header大型粗體標題
section帶有可選附件元素的文字
divider水平分隔線
fields兩欄標籤/值網格
table帶格式化、排序、分頁的資料表
actions按鈕和控制項的水平列
stats帶趨勢指示器的儀表板指標卡片
form帶條件可見性和提交的輸入欄位
image帶標題的區塊級圖片
context小型柔和的說明文字
columns2-3 欄版面配置,包含巢狀區塊

元素類型

類型描述
button帶可選確認對話方塊的操作按鈕
text_input單行或多行文字輸入
number_input帶最小/最大值的數字輸入
select下拉選擇
toggle開/關開關
secret_input用於 API 金鑰和權杖的遮罩輸入

建構器助手

@emdash-cms/blocks 套件匯出建構器助手以獲得更清晰的程式碼:

import { blocks, elements } from "@emdash-cms/blocks";

const { header, form, section, stats } = blocks;
const { textInput, toggle, select, button } = elements;

return {
  blocks: [
    header("SEO Settings"),
    form({
      blockId: "settings",
      fields: [
        textInput("site_title", "Site Title", { initialValue: "My Site" }),
        toggle("generate_sitemap", "Generate Sitemap", { initialValue: true }),
        select("robots", "Default Robots", [
          { label: "Index, Follow", value: "index,follow" },
          { label: "No Index", value: "noindex,follow" },
        ]),
      ],
      submit: { label: "Save", actionId: "save" },
    }),
  ],
};

條件欄位

表單欄位可以根據其他欄位值有條件地顯示:

{
  "type": "toggle",
  "action_id": "auth_enabled",
  "label": "Enable Authentication"
}
{
  "type": "secret_input",
  "action_id": "api_key",
  "label": "API Key",
  "condition": { "field": "auth_enabled", "eq": true }
}

api_key 欄位僅在 auth_enabled 切換開啟時出現。條件在用戶端評估,無需往返。

試一試

使用 Block Playground 互動式地建置和測試區塊版面配置。