EmDash 的 Block Kit 允许沙盒插件将其后台 UI 描述为 JSON。宿主渲染这些块 — 不会有插件提供的 JavaScript 在浏览器中运行。
工作原理
- 用户导航到插件的后台页面
- 后台向插件的后台路由发送
page_load交互 - 插件返回包含块数组的
BlockResponse - 后台使用
BlockRenderer组件渲染这些块 - 当用户交互(点击按钮、提交表单)时,后台将交互发送回插件
- 插件返回新块,循环重复
// 插件后台路由处理器
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 | 小型柔和的帮助文本 |
columns | 2-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 交互式地构建和测试块布局。