低代码平台的可视化搭建:Schema 驱动与拖拽实现
MrSmy Lv5

“低代码”是个被用坏的词。有的低代码是”可视化拖拽建页面”,有的是”配置化的表单引擎”,有的是”代码生成器”。这篇讲我们做的一个后台页面搭建器,重点是数据结构设计和拖拽的实现细节——这两块决定了平台能不能长大。

先明确做什么

我们做的是”运营后台的列表页/详情页搭建器”,需求:

  • 运营能拖拽组合组件(表格、表单、筛选、图表)
  • 配置数据源(接口地址、字段映射)
  • 支持自定义组件的接入
  • 产出的页面要能嵌入现有系统

不做:任意页面搭建(那是 Dreamweaver),只做”后台常见页面模式”。

范围收敛是低代码能成功的前提——**”什么都能搭”等于”什么都搭不好”**。

核心数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type NodeId = string

interface SchemaNode {
id: NodeId
type: string // 'Page' | 'Table' | 'Form' | 'Filter' ...
props: Record<string, any>
children?: NodeId[] // 只存 id,不嵌套
slots?: Record<string, NodeId[]>
}

interface PageSchema {
version: string
root: NodeId
nodes: Record<NodeId, SchemaNode> // 扁平 map
}

为什么用”扁平 map + children 存 id”而不是嵌套树:

操作 嵌套树 扁平 map
查找某节点 O(n) 递归 O(1)
移动节点 要在父节点数组里 splice 改两个 children 数组
更新 props 要逐层拷贝(或原地改) nodes[id].props = ...
撤销/重做 要深拷贝整棵树 记录 patch
序列化 嵌套深了容易栈溢出 天然扁平

扁平结构是”规范化(normalized)”的数据,和 Redux 的 entity store 一个思路。

代价:渲染时要自己递归组装,不能直接 JSON.stringify 出树形。写个 getTree():

1
2
3
4
5
6
7
function getTree(schema: PageSchema, id: NodeId = schema.root) {
const node = schema.nodes[id]
return {
...node,
children: node.children?.map((c) => getTree(schema, c)),
}
}

物料协议

组件要能被”配置”,必须描述自己:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
interface ComponentMeta {
type: string // 唯一标识
name: string // 显示名
category: 'layout' | 'data' | 'form' | 'chart'
icon?: string

// 属性配置(用于生成配置面板)
propsSchema: PropField[]

// 默认值
defaultProps: Record<string, any>

// 能接受子节点吗
acceptChildren?: boolean | string[]

// 运行时渲染
render: (props: any, ctx: RenderContext) => JSX.Element | null
}

interface PropField {
name: string
label: string
type: 'string' | 'number' | 'boolean' | 'select' | 'color' | 'json'
options?: { label: string; value: any }[]
default?: any
description?: string
}

配置面板是自动生成的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function PropsPanel({ node, meta, onChange }: Props) {
return (
<div className="props-panel">
{meta.propsSchema.map((field) => (
<Field
key={field.name}
field={field}
value={node.props[field.name]}
onChange={(v) => onChange({ ...node.props, [field.name]: v })}
/>
))}
</div>
)
}

这样加一个新组件只需要写 ComponentMeta,配置面板自动出现。这是低代码平台”能长大”的关键设计。

拖拽:不要用 HTML5 DnD

原生 draggable + dragstart/dragover/drop 看起来简单,实际有三个硬问题:

  1. 移动端不支持(draggable 在 iOS Safari 上基本不可用)
  2. 拖拽时的视觉反馈难做(拖影是浏览器生成的截图,无法自定义样式、无法显示”插入位置指示线”)
  3. dataTransfer 的限制(只能传字符串,且在 dragover 阶段读不到数据)

所以我们用 Pointer Events 手动实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
interface DragState {
nodeId: NodeId
startX: number
startY: number
ghostX: number
ghostY: number
target: { parentId: NodeId; index: number } | null
}

function useDrag(schema, dispatch) {
const [drag, setDrag] = useState<DragState | null>(null)

const onPointerDown = (e: PointerEvent, nodeId: NodeId) => {
// 只响应左键
if (e.button !== 0) return

const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
setDrag({
nodeId,
startX: e.clientX,
startY: e.clientY,
ghostX: e.clientX - rect.left,
ghostY: e.clientY - rect.top,
target: null,
})

// 关键:捕获指针,手指移出元素也能继续收到 move 事件
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
}

const onPointerMove = (e: PointerEvent) => {
if (!drag) return

// 超过阈值才算拖动(避免误触)
const dist = Math.hypot(e.clientX - drag.startX, e.clientY - drag.startY)
if (dist < 4 && !drag.target) return

const target = findDropTarget(e.clientX, e.clientY)
setDrag({ ...drag, target })
}

const onPointerUp = () => {
if (drag?.target) {
dispatch({ type: 'MOVE', nodeId: drag.nodeId, target: drag.target })
}
setDrag(null)
}

return { drag, onPointerDown, onPointerMove, onPointerUp }
}

setPointerCapture 是核心——它让指针事件”粘”在元素上,即使手指移到别的地方也能收到 pointermove/pointerup。没有它,拖动时快速移出元素就会丢失事件。

三种拖动来源(这决定了复杂度):

来源 行为
物料面板 → 画布 新建节点
画布内节点 → 画布 移动节点
画布节点 → 垃圾箱 删除

统一的抽象是”一个拖动带一个 payload”:

1
2
3
type DragPayload =
| { kind: 'create'; componentType: string }
| { kind: 'move'; nodeId: NodeId }

插入位置的计算

“放在哪”比”怎么拖”难。需要计算:

  1. 指针下是哪个容器(可能有嵌套)
  2. 插入到容器的第几个子节点前
  3. 是否不允许(比如不能把 Table 放进 Table)

用”插入指示线”视觉反馈:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function findDropTarget(x: number, y: number) {
const el = document.elementFromPoint(x, y)
const container = el?.closest('[data-drop-container]') as HTMLElement | null
if (!container) return null

const parentId = container.dataset.nodeId!
const childEls = Array.from(container.querySelectorAll(':scope > [data-node-id]')) as HTMLElement[]

// 找插入点:遍历子元素,看指针在哪个的中线以上
let index = childEls.length
for (let i = 0; i < childEls.length; i++) {
const rect = childEls[i].getBoundingClientRect()
const isHorizontal = container.dataset.layout === 'horizontal'
const mid = isHorizontal ? rect.left + rect.width / 2 : rect.top + rect.height / 2
const coord = isHorizontal ? x : y
if (coord < mid) {
index = i
break
}
}

return { parentId, index }
}

几个细节:

1. 防止拖到自己里面

1
2
3
4
5
6
7
8
9
10
11
12
13
function isDescendant(schema, ancestorId, nodeId) {
let cur = schema.nodes[nodeId]
while (cur) {
if (cur.id === ancestorId) return true
const parent = findParent(schema, cur.id)
cur = parent
}
return false
}

if (isDescendant(schema, drag.nodeId, target.parentId)) {
return null // 不合法,不显示指示线
}

否则会出现”把父节点拖进自己的子节点”,数据结构就成环了。

2. 冻结拖拽时的布局

拖动过程中,如果被拖的节点还在原位,插入位置的计算会一直受它影响。做法是**给被拖节点加 opacity: 0.4 并且 pointer-events: none**(保持在流里,但视觉上”半透明”)。

另一种做法是”移出文档流”(display: none),但那样布局会跳,用户会迷路。

3. 吸附与对齐

自由拖拽(绝对定位)会让布局很快就乱。我们**只支持”流式布局”**(flex/grid),拖拽只决定”插到哪”,不决定”坐标”。

这个决策极大地降低了复杂度——不需要处理吸附、对齐参考线、自由定位的响应式。代价是不能做”任意摆放”的页面,但后台页面本来就不需要。

撤销/重做

用 patch 而不是快照:

1
2
3
4
5
6
7
8
9
10
11
type Patch =
| { op: 'add'; id: NodeId; node: SchemaNode; parentId: NodeId; index: number }
| { op: 'remove'; id: NodeId }
| { op: 'move'; id: NodeId; from: { parentId: NodeId; index: number }; to: { parentId: NodeId; index: number } }
| { op: 'update'; id: NodeId; props: Record<string, any> }

interface HistoryEntry {
patches: Patch[]
inverse: Patch[]
label: string // '添加 Table'、'移动节点'
}

每次 dispatch 生成一对(正向 + 逆向):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function applyPatch(schema: PageSchema, p: Patch): PageSchema {
switch (p.op) {
case 'add': {
const nodes = { ...schema.nodes, [p.id]: p.node }
const parent = { ...nodes[p.parentId] }
const children = [...(parent.children ?? [])]
children.splice(p.index, 0, p.id)
parent.children = children
nodes[p.parentId] = parent
return { ...schema, nodes }
}
case 'remove': {
const nodes = { ...schema.nodes }
const parentId = findParentId(schema, p.id)!
const parent = { ...nodes[parentId] }
parent.children = parent.children!.filter((c) => c !== p.id)
nodes[parentId] = parent
delete nodes[p.id]
return { ...schema, nodes }
}
case 'move': { /* ... */ }
case 'update': {
return {
...schema,
nodes: { ...schema.nodes, [p.id]: { ...schema.nodes[p.id], props: p.props } },
}
}
}
}

撤销就是把 inverse 依次应用。

为什么不用深拷贝快照:一个中等页面 200 个节点,深拷贝一次约 2ms,撤销栈存 50 步就是 100ms 的内存操作。而且 patch 能生成”操作日志”(谁在什么时候加了什么)。

坑:拖拽过程中的中间态不该进历史栈。只在 pointerup 时提交一次 patch。

渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function NodeRenderer({ id, schema }: { id: NodeId; schema: PageSchema }) {
const node = schema.nodes[id]
const meta = registry.get(node.type)

if (!meta) {
return <div className="unknown-node">未知组件: {node.type}</div>
}

const ctx: RenderContext = {
schema,
// 给组件提供"取数据"的能力
fetchData: (sourceKey: string) => useDataSource(sourceKey),
// 给组件提供"触发行为"的能力
emit: (eventName: string) => runAction(node.props[`on${eventName}`]),
}

const children = node.children?.map((c) => <NodeRenderer key={c} id={c} schema={schema} />)

return (
<SelectionWrapper id={id}>
{meta.render({ ...meta.defaultProps, ...node.props, children }, ctx)}
</SelectionWrapper>
)
}

SelectionWrapper 是编辑器专用的——它处理 hover 高亮、点击选中、拖拽手柄。在”预览模式”下要跳过它:

1
2
3
4
5
6
7
const ModeContext = createContext<'edit' | 'preview'>('preview')

function SelectionWrapper({ id, children }) {
const mode = useContext(ModeContext)
if (mode === 'preview') return <>{children}</>
return <div data-node-id={id} className="selection-wrapper">{children}</div>
}

这个”编辑态注入外层 div”的做法有个副作用:CSS 布局会被破坏(多一层 div 影响 flex/grid 的话)。

解法:display: contents。

1
2
3
.selection-wrapper {
display: contents; /* 不影响布局,但仍然能接收事件 */
}

但 display: contents 的元素不能有背景、边框、padding,hover 高亮要用 outline 和伪元素(绝对定位的框):

1
2
3
4
5
6
7
.selection-wrapper {
display: contents;
}
.selection-wrapper:hover > * {
outline: 2px solid #4a90e2;
outline-offset: -2px;
}

这是踩过的一个坑——最初用普通 div 包裹,结果所有 flex 布局都乱了。

数据源配置

1
2
3
4
5
6
7
8
interface DataSource {
key: string
type: 'rest' | 'graphql' | 'static'
url: string
method?: 'GET' | 'POST'
params?: Record<string, any> // 支持 ${query.xxx} 这样的变量
transform?: string // 简单的字段映射表达式
}

组件通过 props.dataSource 引用 key:

1
2
3
4
5
6
7
8
9
10
{
"type": "Table",
"props": {
"dataSource": "orders",
"columns": [
{ "field": "orderNo", "title": "订单号" },
{ "field": "amount", "title": "金额", "format": "currency" }
]
}
}

变量替换:

1
2
3
4
5
6
7
8
9
10
11
12
function resolveParams(params: Record<string, any>, ctx: { query: Record<string, string> }) {
const out: Record<string, any> = {}
for (const [k, v] of Object.entries(params)) {
if (typeof v === 'string' && v.startsWith('${')) {
const path = v.slice(2, -1).split('.')
out[k] = path.reduce((o, key) => o?.[key], ctx)
} else {
out[k] = v
}
}
return out
}

**不要做”表达式引擎”**——那会变成”用一种新语言写代码”,运营学不会,开发嫌难用。只支持 ${a.b.c} 这种路径取值就够了。

自定义组件接入

这是低代码能否真正落地的关键:**平台永远覆盖不了所有需求,必须能”降级写代码”**。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 业务代码里注册
import { registerComponent } from '@platform/core'

registerComponent({
type: 'MyCustomChart',
name: '自定义图表',
category: 'chart',
propsSchema: [
{ name: 'height', label: '高度', type: 'number', default: 300 },
{ name: 'options', label: 'ECharts 配置', type: 'json' },
],
defaultProps: { height: 300, options: {} },
render: ({ height, options }) => {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const chart = echarts.init(ref.current!)
chart.setOption(options)
return () => chart.dispose()
}, [options])
return <div ref={ref} style={{ height }} />
},
})

平台端通过 JSON 配置启用:

1
2
3
{
"customComponents": ["https://admin.example.com/custom-components.js"]
}

沙箱问题:自定义组件是”任意 JS”,如果平台面向多个业务方,要隔离(iframe 或者 ShadowRealm,后者还没标准化)。

我们的平台只给内部用,所以直接 import,不做沙箱——这是明确接受的风险。

性能:几十个节点就卡

第一个版本在 80 个节点时,拖动开始掉帧。原因:

  1. 每次 pointermove 都 setState → 整棵树重渲染
  2. document.elementFromPoint 在复杂 DOM 上很慢
  3. 配置面板的受控输入导致全量重渲染

优化:

1. 拖拽状态用 ref + 直接操作 DOM

1
2
3
4
5
6
7
8
9
10
11
12
// 指示线不用 React 渲染,直接移动一个绝对定位的 div
const indicatorRef = useRef<HTMLDivElement>(null)

function onPointerMove(e) {
const target = findDropTarget(e.clientX, e.clientY)
if (target) {
const rect = getInsertRect(target)
indicatorRef.current!.style.transform =
`translate(${rect.x}px, ${rect.y}px)`
indicatorRef.current!.style.width = `${rect.width}px`
}
}

2. 节点渲染用 memo,props 引用稳定

1
2
3
const NodeRenderer = memo(({ id, schema }) => {
// schema.nodes 是不可变的,改一个节点只换那一个引用
})

前提是每次修改只替换被改的节点对象(immutable update),父节点和兄弟节点的引用不变,memo 才能生效。

3. 节流 elementFromPoint

1
const throttledFind = useThrottle(findDropTarget, 16)     // ~60fps

优化后 200 个节点能流畅拖动。

代码生成 vs 运行时渲染

两种产出方式:

运行时渲染 代码生成
实现 Schema → 渲染器 Schema → JSX 源码
灵活性 受限于渲染器 可以手改
升级 平台升级,所有页面生效 改过的代码不跟随
调试 难(要理解 schema 和渲染器) 容易(就是代码)
性能 多一层渲染开销 无额外开销

我们选运行时渲染,理由:

  1. 后台页面更新频繁,代码生成会导致”存了一份代码副本”,无法统一升级
  2. 运行时渲染能统一做权限、埋点、主题

代价是”要有运行时库”(我们的 core 约 60KB gzip)。后台不在意这点体积。

踩过的坑

1. schema 版本演进

第一个版本没有 version 字段。后来加”容器组件”概念时,旧 schema 没有 slots,解析时到处 if (node.slots)。

补救措施:加 version + 迁移函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
const migrations: Record<string, (s: any) => any> = {
'1': (s) => ({ ...s, version: '2', nodes: Object.fromEntries(
Object.entries(s.nodes).map(([id, n]: any) => [id, { ...n, slots: n.slots ?? {} }])
)}),
}

function migrate(schema: any) {
let s = schema
while (s.version !== CURRENT_VERSION) {
s = migrations[s.version](s)
}
return s
}

schema 必须从一开始就有版本号——这是最贵的教训。

2. 受控组件的输入卡顿

配置面板的输入框每次 onChange 都 dispatch 到全局 store,导致整棵树重渲染,输入”卡字”。

解法:本地 state + 防抖提交。

1
2
3
4
5
6
7
8
9
10
11
12
function TextField({ value, onChange }) {
const [local, setLocal] = useState(value)
const debounced = useDebouncedCallback((v) => onChange(v), 300)

return (
<input
value={local}
onChange={(e) => { setLocal(e.target.value); debounced(e.target.value) }}
onBlur={() => onChange(local)}
/>
)
}

3. 复制粘贴节点

复制一棵子树(含所有后代),用新的 id:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function cloneSubtree(schema, rootId) {
const idMap: Record<string, string> = {}
const walk = (id: string) => {
idMap[id] = nanoid()
schema.nodes[id].children?.forEach(walk)
}
walk(rootId)

const newNodes = {}
for (const [oldId, newId] of Object.entries(idMap)) {
const n = schema.nodes[oldId]
newNodes[newId] = {
...n,
id: newId,
children: n.children?.map((c) => idMap[c]),
}
}
return newNodes
}

忘了处理 idMap 就会出现”两个节点指向同一个子节点”,之后改一个另一个也变。

4. 平台的”最后一个功能”永远做不完

最初的目标是”覆盖 80% 的列表页”。实际到了 75% 时,剩下的 25% 每个都是”特殊情况”:

  • 需要在表格上方加一个自定义的统计条
  • 需要列宽拖拽后记住用户偏好
  • 需要行内编辑后局部刷新(不是整表刷新)

这些”一个页面一个样”的需求,低代码永远追不上。所以”自定义组件”的逃生口必须最早做。

一个判断:什么时候值得做低代码

条件 说明
有大量同构页面(> 50 个) 才值得投入
需求方是运营/产品(不是开发) 才能真正省人力
变化频繁(每周都有新页面) 收益随时间增长
有团队能长期维护平台 平台是产品,不是项目

不适合:页面少、需求稳定、只有开发在用(那不如写组件库)。

我们的实际效果:上线一年,运营自助创建了 240 个页面,开发从”每周做 3 个后台页面”降到”每周修 1 个平台 bug”。但平台本身的投入是 2 人 × 4 个月。

小结

低代码平台的核心设计决策:

决策 我们的选择 理由
数据结构 扁平 map + children 存 id O(1) 查找、O(1) 移动
拖拽 Pointer Events 手动实现 移动端可用 + 完全可控
布局 只支持流式(不支持自由定位) 复杂度降一个量级
编辑态注入 display: contents 包裹 不破坏布局
产出 运行时渲染(非代码生成) 可统一升级
逃生口 自定义组件注册 覆盖长尾需求
版本 schema 有 version + 迁移 一开始就要有

三个”如果重来会先做”的事:

  1. schema 版本号(第 1 天就加)
  2. 自定义组件机制(第 1 个月就做,不要等”需求来了再说”)
  3. 性能基准(定一个”200 节点流畅拖动”的验收标准,否则会一路欠债)

最后一点体会:低代码的难点不在技术,在边界。哪些能做、哪些不做、哪些”能配但要写代码”,这些决策决定了平台是”被用起来”还是”被抛弃”。

  • 本文标题:低代码平台的可视化搭建:Schema 驱动与拖拽实现
  • 本文作者:MrSmy
  • 创建时间:2023-06-25 20:41:00
  • 本文链接:https://fengyang.live/2023/06/25/低代码平台的可视化搭建:Schema驱动与拖拽实现/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!