Block Kit

本頁內容

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

運作原理

  1. 使用者導航到外掛程式的管理頁面。
  2. 管理端向外掛程式的管理路由發送 page_load 互動。
  3. 外掛程式返回包含區塊陣列的 BlockResponse
  4. 管理端使用 BlockRenderer 元件渲染區塊。
  5. 當使用者互動(點擊按鈕、提交表單)時,管理端將互動發送回外掛程式。
  6. 外掛程式返回新的區塊,循環重複。
import { definePlugin } from "emdash";
import type { PluginContext } from "emdash";

interface BlockInteraction {
	type: "page_load" | "block_action" | "form_submit";
	page?: string;
	action_id?: string;
	values?: Record<string, unknown>;
}

export default definePlugin({
	routes: {
		admin: {
			handler: async (routeCtx, ctx: PluginContext) => {
				const interaction = routeCtx.input as BlockInteraction;

				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: [/* ... updated blocks ... */],
						toast: { message: "Settings saved", type: "success" },
					};
				}

				return { blocks: [] };
			},
		},
	},
});

標準格式的路由處理器接受兩個參數:routeCtx(包含 inputrequestrequestMeta)和 ctxPluginContext)。

區塊類型

TypeDescription
header大號粗體標題
section帶可選配件元素的文字
divider水平分隔線
fields兩欄標籤/值網格
table帶格式化、排序、分頁的資料表
actions水平排列的按鈕和控制項列
stats帶趨勢指標的儀表板指標卡
form帶條件可見性和提交的輸入欄位
image帶標題的區塊級圖像
context小號靜音幫助文字
columns帶巢狀區塊的 2-3 欄佈局
empty帶圖示、標題、描述、可選命令列和操作按鈕的空狀態佔位符
accordion包裹巢狀區塊的可摺疊部分

元素類型

TypeDescription
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 互動式地建構和測試區塊佈局。