跳转到内容

Block Kit

EmDash 的 Block Kit 允许沙盒化插件将其管理界面描述为 JSON。由宿主渲染这些块——插件的 JavaScript 代码永远不会在浏览器中运行。

  1. 用户导航到插件的管理页面
  2. 管理界面向插件的管理路由发送 page_load 交互
  3. 插件返回一个包含块数组的 BlockResponse
  4. 管理界面使用 BlockRenderer 组件渲染这些块
  5. 当用户进行交互(点击按钮、提交表单)时,管理界面将交互发送回插件
  6. 插件返回新的块,循环重复
// Plugin admin route handler
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: [/* ... updated 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 来交互式地构建和测试块布局。