gbformdesign 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,634 +1,634 @@
1
- <template>
2
- <el-container class="_fc-designer gb-fc-designer" style="height: 100%">
3
- <el-main>
4
- <el-container style="height: 100%">
5
- <el-aside class="_fc-l-menu" width="40px">
6
- <el-tooltip effect="dark" content="组件列表" placement="right" :hide-after="0">
7
- <div class="_fc-l-menu-item" :class="{ active: activeModule === 'base' }" @click="activeModule = 'base'">
8
- <i class="fc-icon icon-menu"></i>
9
- </div>
10
- </el-tooltip>
11
- <el-tooltip effect="dark" content="JSON" placement="right" :hide-after="0">
12
- <div class="_fc-l-menu-item" :class="{ active: activeModule === 'json' }" @click="activeModule = 'json'">
13
- <i class="fc-icon icon-script"></i>
14
- </div>
15
- </el-tooltip>
16
- </el-aside>
17
-
18
- <el-aside v-show="!hiddenLeft" class="_fc-l" width="266px">
19
- <div class="_fc-l-close" @click="hiddenLeft = true"><i class="fc-icon icon-arrow"></i></div>
20
- <FcJsonPanel
21
- v-if="activeModule === 'json'"
22
- ref="jsonPanelRef"
23
- :components="modelValue"
24
- :form-options="formOptions"
25
- @update:components="applyComponents"
26
- @update:form-options="applyOptions"
27
- />
28
- <el-container v-else style="height: 100%">
29
- <el-header height="40px" class="_fc-l-tabs">
30
- <div class="_fc-l-tab" :class="{ active: activeMenuTab === 'menu' }" @click="activeMenuTab = 'menu'">
31
- 组件
32
- </div>
33
- <div class="_fc-l-tab" :class="{ active: activeMenuTab === 'tree' }" @click="activeMenuTab = 'tree'">
34
- 大纲
35
- </div>
36
- </el-header>
37
- <el-main v-show="activeMenuTab === 'menu'">
38
- <div v-for="category in categories" :key="category.key" class="_fc-l-group">
39
- <h4 class="_fc-l-title" @click="category.hidden = !category.hidden">
40
- {{ category.name }}
41
- <i class="fc-icon icon-arrow" :class="{ down: !category.hidden }"></i>
42
- </h4>
43
- <div v-show="!category.hidden" class="_fc-l-list">
44
- <div
45
- v-for="item in category.templates"
46
- :key="item.type"
47
- class="_fc-l-item"
48
- draggable="true"
49
- @dragstart="onMenuDragStart($event, item)"
50
- @dragend="onDragEnd"
51
- @click="addFromTemplate(item)"
52
- >
53
- <div class="_fc-l-icon"><i class="fc-icon" :class="iconOf(item.type)"></i></div>
54
- <span class="_fc-l-name">{{ item.name }}</span>
55
- </div>
56
- </div>
57
- </div>
58
- </el-main>
59
- <el-main v-show="activeMenuTab === 'tree'">
60
- <el-tree
61
- :data="treeData"
62
- node-key="id"
63
- :expand-on-click-node="false"
64
- default-expand-all
65
- @node-click="onTreeNodeClick"
66
- >
67
- <template #default="{ data }">
68
- <div class="_fc-tree-node" :class="{ active: activeId === data.rule?.id }">
69
- <div class="_fc-tree-label">
70
- <i class="fc-icon" :class="data.icon || 'icon-cell'"></i>
71
- <span>{{ data.label }}</span>
72
- </div>
73
- <div class="_fc-tree-more" @click.stop>
74
- <el-dropdown trigger="click" size="default" @command="(command) => onTreeCommand(command, data)">
75
- <i class="fc-icon icon-more"></i>
76
- <template #dropdown>
77
- <el-dropdown-menu>
78
- <el-dropdown-item command="copy">复制</el-dropdown-item>
79
- <el-dropdown-item command="delete">删除</el-dropdown-item>
80
- </el-dropdown-menu>
81
- </template>
82
- </el-dropdown>
83
- </div>
84
- </div>
85
- </template>
86
- </el-tree>
87
- </el-main>
88
- </el-container>
89
- </el-aside>
90
-
91
- <el-container class="_fc-m">
92
- <el-header class="_fc-m-tools" height="45">
93
- <div class="_fc-m-tools-l">
94
- <div class="devices">
95
- <i class="fc-icon icon-pc" :class="{ active: device === 'pc' }" @click="device = 'pc'"></i>
96
- <i class="fc-icon icon-pad" :class="{ active: device === 'pad' }" @click="device = 'pad'"></i>
97
- <i class="fc-icon icon-mobile" :class="{ active: device === 'mobile' }" @click="device = 'mobile'"></i>
98
- </div>
99
- <div class="line"></div>
100
- <div>
101
- <i class="fc-icon icon-pre-step" :class="{ disabled: !canUndo }" @click="undo"></i>
102
- <i class="fc-icon icon-next-step" :class="{ disabled: !canRedo }" @click="redo"></i>
103
- </div>
104
- </div>
105
- <div class="_fc-m-tools-r">
106
- <el-button :icon="Upload" plain size="small" @click="openImport">导入</el-button>
107
- <el-button type="primary" plain size="small" @click="previewVisible = true">
108
- <i class="fc-icon icon-preview"></i> 预览
109
- </el-button>
110
- <el-popconfirm title="确定清空所有组件?" width="200px" confirm-button-text="清空" cancel-button-text="取消" @confirm="clearRule">
111
- <template #reference>
112
- <el-button type="danger" plain size="small"><i class="fc-icon icon-delete"></i> 清空</el-button>
113
- </template>
114
- </el-popconfirm>
115
- </div>
116
- </el-header>
117
- <el-main class="_fc-m-con">
118
- <a class="gb-fc-watermark" href="javascript:void(0)">GbFlowDesign</a>
119
- <div
120
- ref="dragCon"
121
- class="_fc-m-drag"
122
- :class="device"
123
- :style="dragStyle"
124
- @dragover.prevent
125
- @drop.prevent="onCanvasDrop"
126
- >
127
- <el-form
128
- v-if="modelValue.length"
129
- :model="canvasData"
130
- :label-width="formOptions.labelWidth || '120px'"
131
- :size="formOptions.size === 'default' ? undefined : formOptions.size"
132
- >
133
- <FcCanvasField
134
- v-for="(component, index) in modelValue"
135
- :key="component.id || index"
136
- :component="component"
137
- :path="[index]"
138
- :form-data="canvasData"
139
- :form-rules="canvasRules"
140
- :active-id="activeId"
141
- />
142
- </el-form>
143
- <div v-else class="_fd-draggable-drag _fd-drag-box drag-holder" @click="clearActive"></div>
144
- </div>
145
- </el-main>
146
- </el-container>
147
-
148
- <el-aside v-show="!hiddenRight" class="_fc-r" width="320px">
149
- <div class="_fc-r-close" @click="hiddenRight = true"><i class="fc-icon icon-arrow"></i></div>
150
- <FcPropsPanel :component="activeComponent" :form-options="formOptions" @close="clearActive" />
151
- </el-aside>
152
-
153
- <div v-if="hiddenLeft" class="_fc-l-open" @click="hiddenLeft = false"><i class="fc-icon icon-arrow"></i></div>
154
- <div v-if="hiddenRight" class="_fc-r-open" @click="hiddenRight = false"><i class="fc-icon icon-arrow"></i></div>
155
-
156
- <FcPreviewDialog v-model="previewVisible" :components="modelValue" :form-options="formOptions" />
157
- </el-container>
158
- </el-main>
159
- </el-container>
160
- </template>
161
-
162
- <script setup>
163
- import { computed, nextTick, onMounted, provide, reactive, ref, watch } from 'vue'
164
- import { ElMessage } from 'element-plus'
165
- import { Upload } from '@element-plus/icons-vue'
166
- import FcCanvasField from './FcCanvasField.vue'
167
- import FcPropsPanel from './FcPropsPanel.vue'
168
- import FcJsonPanel from './FcJsonPanel.vue'
169
- import FcPreviewDialog from './FcPreviewDialog.vue'
170
- import { COMPONENT_CATEGORIES } from '../../design/constants/componentTemplates.js'
171
- import { COMPONENT_TYPES } from '../../design/constants/componentTypes.js'
172
- import { ensureComponentId, generateComponentId } from '../../design/utils/componentUtils.js'
173
- import { validateForm, exportForm, importForm } from '../../core/schema.js'
174
- import { downloadJSON, pickJSONFile } from '../../core/fileIO.js'
175
-
176
- defineOptions({ name: 'GbFormDesigner' })
177
-
178
- const props = defineProps({
179
- modelValue: { type: Array, default: () => [] },
180
- options: { type: Object, default: null },
181
- meta: { type: Object, default: () => ({}) },
182
- fileName: { type: String, default: 'form' }
183
- })
184
-
185
- const emit = defineEmits(['update:modelValue', 'update:options', 'import', 'export', 'validate', 'change'])
186
-
187
- const clone = (value) => JSON.parse(JSON.stringify(value ?? []))
188
-
189
- const localOptions = reactive({
190
- name: '',
191
- description: '',
192
- labelWidth: '120px',
193
- size: 'default',
194
- ...(props.options || {})
195
- })
196
-
197
- const formOptions = props.options ? reactive(props.options) : localOptions
198
-
199
- watch(
200
- () => props.options,
201
- (value) => {
202
- if (!value || value === formOptions) return
203
- Object.assign(formOptions, value)
204
- },
205
- { deep: true }
206
- )
207
-
208
- provide('fcFormOptions', formOptions)
209
-
210
- const activeModule = ref('base')
211
- const activeMenuTab = ref('menu')
212
- const hiddenLeft = ref(false)
213
- const hiddenRight = ref(false)
214
- const device = ref('pc')
215
- const previewVisible = ref(false)
216
- const activeId = ref('')
217
- const dragOver = ref('')
218
- const jsonPanelRef = ref(null)
219
-
220
- const dragStyle = {
221
- '--fc-drag-empty': "'拖拽左侧列表中的组件到此处'",
222
- '--fc-child-empty': "'点击右下角 + 按钮添加一列'"
223
- }
224
-
225
- const canvasData = reactive({})
226
- const canvasRules = {}
227
-
228
- const categories = ref(
229
- COMPONENT_CATEGORIES.map((category) => ({ ...category, hidden: false }))
230
- )
231
-
232
- const ICONS = {
233
- [COMPONENT_TYPES.INPUT]: 'icon-input',
234
- [COMPONENT_TYPES.TEXTAREA]: 'icon-textarea',
235
- [COMPONENT_TYPES.INPUT_NUMBER]: 'icon-number',
236
- [COMPONENT_TYPES.RADIO_GROUP]: 'icon-radio',
237
- [COMPONENT_TYPES.CHECKBOX_GROUP]: 'icon-checkbox',
238
- [COMPONENT_TYPES.SELECT]: 'icon-select',
239
- [COMPONENT_TYPES.SWITCH]: 'icon-switch',
240
- [COMPONENT_TYPES.DATE_PICKER]: 'icon-date',
241
- [COMPONENT_TYPES.ROW]: 'icon-row'
242
- }
243
-
244
- const iconOf = (type) => ICONS[type] || 'icon-input'
245
-
246
- // ==================== History ====================
247
-
248
- const history = ref([])
249
- const historyIndex = ref(-1)
250
- let restoring = false
251
- let historyTimer = null
252
-
253
- const snapshot = () => JSON.stringify({ components: props.modelValue, options: { ...formOptions } })
254
-
255
- const pushHistory = () => {
256
- const snap = snapshot()
257
- if (history.value[historyIndex.value] === snap) return
258
- history.value = history.value.slice(0, historyIndex.value + 1)
259
- history.value.push(snap)
260
- if (history.value.length > 50) history.value.shift()
261
- historyIndex.value = history.value.length - 1
262
- }
263
-
264
- const canUndo = computed(() => historyIndex.value > 0)
265
- const canRedo = computed(() => historyIndex.value < history.value.length - 1)
266
-
267
- const applyHistory = () => {
268
- const { components, options } = JSON.parse(history.value[historyIndex.value])
269
- restoring = true
270
- emit('update:modelValue', components)
271
- Object.assign(formOptions, options)
272
- nextTick(() => {
273
- restoring = false
274
- })
275
- }
276
-
277
- const undo = () => {
278
- if (!canUndo.value) return
279
- historyIndex.value -= 1
280
- applyHistory()
281
- }
282
-
283
- const redo = () => {
284
- if (!canRedo.value) return
285
- historyIndex.value += 1
286
- applyHistory()
287
- }
288
-
289
- watch(
290
- () => [props.modelValue, { ...formOptions }],
291
- () => {
292
- if (restoring) return
293
- clearTimeout(historyTimer)
294
- historyTimer = setTimeout(pushHistory, 300)
295
- },
296
- { deep: true }
297
- )
298
-
299
- onMounted(() => {
300
- pushHistory()
301
- })
302
-
303
- const applyComponents = (components) => {
304
- emit('update:modelValue', clone(components))
305
- }
306
-
307
- const applyOptions = (options) => {
308
- Object.assign(formOptions, options || {})
309
- emit('update:options', { ...formOptions })
310
- }
311
-
312
- // ==================== Field creation ====================
313
-
314
- const findTemplate = (type) => {
315
- for (const category of COMPONENT_CATEGORIES) {
316
- const found = category.templates.find((item) => item.type === type)
317
- if (found) return found
318
- }
319
- return null
320
- }
321
-
322
- const createFieldFromTemplate = (template) => {
323
- const component = clone(template)
324
- delete component.name
325
- delete component.icon
326
- ensureComponentId(component)
327
- component.props = component.props || {}
328
- if (!component.props.variableName) component.props.variableName = `field_${generateComponentId().split('_').pop()}`
329
- if (component.type === COMPONENT_TYPES.ROW) {
330
- component.children = [[], []]
331
- component.props.columns = component.props.columns || [{ span: 12 }, { span: 12 }]
332
- }
333
- return component
334
- }
335
-
336
- const createFieldByType = (type) => {
337
- const template = findTemplate(type)
338
- if (!template) return null
339
- return createFieldFromTemplate(template)
340
- }
341
-
342
- const addFromTemplate = (template) => {
343
- const component = createFieldFromTemplate(template)
344
- const list = [...props.modelValue, component]
345
- applyComponents(list)
346
- activeId.value = component.id
347
- }
348
-
349
- // ==================== Path helpers ====================
350
-
351
- const resolveParent = (path) => {
352
- if (path.length === 1) return { list: props.modelValue, index: path[0], node: null }
353
- const [rowIndex, , columnIndex, childIndex] = path
354
- const row = props.modelValue[rowIndex]
355
- return { list: row?.children?.[columnIndex] || [], index: childIndex, node: row }
356
- }
357
-
358
- const findById = (list, id) => {
359
- for (const component of list || []) {
360
- if (component.id === id) return component
361
- if (component.type === COMPONENT_TYPES.ROW) {
362
- for (const column of component.children || []) {
363
- const found = findById(column, id)
364
- if (found) return found
365
- }
366
- }
367
- }
368
- return null
369
- }
370
-
371
- const activeComponent = computed(() => (activeId.value ? findById(props.modelValue, activeId.value) : null))
372
-
373
- const active = (component) => {
374
- activeId.value = component.id
375
- }
376
-
377
- const clearActive = () => {
378
- activeId.value = ''
379
- }
380
-
381
- const newIdDeep = (component) => {
382
- component.id = generateComponentId()
383
- if (component.type === COMPONENT_TYPES.ROW) {
384
- ;(component.children || []).forEach((column) => column.forEach(newIdDeep))
385
- }
386
- return component
387
- }
388
-
389
- const copyAt = (path) => {
390
- const parent = resolveParent(path)
391
- const source = parent.list[path[path.length - 1]]
392
- if (!source) return
393
- const copy = newIdDeep(clone(source))
394
- parent.list.splice(parent.index + 1, 0, copy)
395
- applyComponents(props.modelValue)
396
- activeId.value = copy.id
397
- }
398
-
399
- const removeAt = (path) => {
400
- const parent = resolveParent(path)
401
- parent.list.splice(parent.index, 1)
402
- applyComponents(props.modelValue)
403
- if (activeId.value) {
404
- const stillThere = findById(props.modelValue, activeId.value)
405
- if (!stillThere) clearActive()
406
- }
407
- }
408
-
409
- // ==================== Drag & drop ====================
410
-
411
- const dragPayload = ref(null)
412
-
413
- const getDragPayload = () => {
414
- if (dragPayload.value) return dragPayload.value
415
- return null
416
- }
417
-
418
- const onMenuDragStart = (event, template) => {
419
- const payload = { kind: 'new', type: template.type }
420
- dragPayload.value = payload
421
- event.dataTransfer.effectAllowed = 'copy'
422
- event.dataTransfer.setData('application/x-gb-field', JSON.stringify(payload))
423
- event.dataTransfer.setData('text/plain', template.type)
424
- }
425
-
426
- const startDrag = (path) => {
427
- dragPayload.value = { kind: 'existing', path: [...path] }
428
- }
429
-
430
- const onDragEnd = () => {
431
- dragPayload.value = null
432
- dragOver.value = ''
433
- }
434
-
435
- const onCanvasDrop = (event) => {
436
- const raw = event.dataTransfer?.getData('application/x-gb-field')
437
- let payload = dragPayload.value
438
- if (raw) {
439
- try {
440
- payload = JSON.parse(raw)
441
- } catch {
442
- payload = dragPayload.value
443
- }
444
- }
445
- dragOver.value = ''
446
- dragPayload.value = null
447
- if (!payload) return
448
- dropAt(payload, { path: null, position: 'bottom' })
449
- }
450
-
451
- const dropAt = (payload, target) => {
452
- if (!payload) return
453
- let list = props.modelValue
454
- let index = props.modelValue.length
455
-
456
- if (target.column !== undefined && target.path) {
457
- const row = resolveParent(target.path).list[target.path[target.path.length - 1]]
458
- if (!row?.children?.[target.column]) return
459
- if (payload.kind === 'existing') {
460
- const moving = resolveParent(payload.path).list[payload.path[payload.path.length - 1]]
461
- if (moving?.type === COMPONENT_TYPES.ROW) {
462
- ElMessage.warning('分栏组件不能放入分栏内')
463
- return
464
- }
465
- }
466
- list = row.children[target.column]
467
- index = list.length
468
- } else if (target.path) {
469
- if (payload.kind === 'existing') {
470
- const isSelfOrChild =
471
- payload.path.length <= target.path.length &&
472
- payload.path.every((value, i) => value === target.path[i])
473
- if (isSelfOrChild) return
474
- }
475
- const parent = resolveParent(target.path)
476
- list = parent.list
477
- index = target.position === 'top' ? parent.index : parent.index + 1
478
- }
479
-
480
- let component
481
- if (payload.kind === 'new') {
482
- component = createFieldByType(payload.type)
483
- if (!component) return
484
- } else {
485
- const sourceParent = resolveParent(payload.path)
486
- component = sourceParent.list[sourceParent.index]
487
- if (!component) return
488
- if (sourceParent.list === list && sourceParent.index < index) index -= 1
489
- sourceParent.list.splice(sourceParent.index, 1)
490
- }
491
-
492
- list.splice(index, 0, component)
493
- applyComponents(props.modelValue)
494
- activeId.value = component.id
495
- }
496
-
497
- provide('fcDragOver', dragOver)
498
- provide('fcCanvasOps', {
499
- active,
500
- copy: copyAt,
501
- remove: removeAt,
502
- startDrag,
503
- endDrag: onDragEnd,
504
- getDragPayload,
505
- dropAt
506
- })
507
-
508
- // ==================== Tree ====================
509
-
510
- const buildTree = (list, parentPath = []) =>
511
- (list || []).map((component, index) => {
512
- const path = [...parentPath, index]
513
- const node = {
514
- id: component.id,
515
- label: component.props?.label || component.props?.variableName || component.type,
516
- icon: iconOf(component.type),
517
- rule: component,
518
- path
519
- }
520
- if (component.type === COMPONENT_TYPES.ROW) {
521
- node.children = (component.children || []).flatMap((column, columnIndex) =>
522
- buildTree(column || [], [...parentPath, index, 'children', columnIndex])
523
- )
524
- }
525
- return node
526
- })
527
-
528
- const treeData = computed(() => buildTree(props.modelValue))
529
-
530
- const onTreeNodeClick = (data) => {
531
- if (data.rule) activeId.value = data.rule.id
532
- }
533
-
534
- const onTreeCommand = (command, data) => {
535
- if (!data.path) return
536
- if (command === 'copy') copyAt(data.path)
537
- else if (command === 'delete') removeAt(data.path)
538
- }
539
-
540
- // ==================== Import / export / clear ====================
541
-
542
- const openImport = async () => {
543
- const picked = await pickJSONFile()
544
- if (!picked) return
545
- try {
546
- const result = importForm(picked.text)
547
- emit('update:modelValue', result.components)
548
- Object.assign(formOptions, result.options || {})
549
- emit('import', { components: result.components, options: { ...formOptions } })
550
- ElMessage.success('表单导入成功')
551
- } catch (error) {
552
- ElMessage.error(`导入失败:${error.message}`)
553
- }
554
- }
555
-
556
- const clearRule = () => {
557
- emit('update:modelValue', [])
558
- clearActive()
559
- ElMessage.success('表单已清空')
560
- }
561
-
562
- const validate = () => {
563
- const result = validateForm({ components: props.modelValue })
564
- emit('validate', result)
565
- return result
566
- }
567
-
568
- const getComponents = () => clone(props.modelValue)
569
- const getForm = () => ({ components: getComponents(), options: { ...formOptions } })
570
-
571
- const exportJSON = (space = 2) => {
572
- const payload = exportForm(props.modelValue, { ...props.meta, name: props.meta?.name || props.fileName }, { raw: true })
573
- payload.form.options = { ...formOptions }
574
- emit('export', payload)
575
- return JSON.stringify(payload, null, space)
576
- }
577
-
578
- const downloadForm = () => {
579
- const payload = exportForm(props.modelValue, { ...props.meta, name: props.meta?.name || props.fileName }, { raw: true })
580
- payload.form.options = { ...formOptions }
581
- downloadJSON(payload, `${props.meta?.name || props.fileName}-form.json`)
582
- emit('export', payload)
583
- ElMessage.success('表单 JSON 已导出')
584
- }
585
-
586
- const importJSON = (input) => {
587
- const result = importForm(input)
588
- emit('update:modelValue', result.components)
589
- Object.assign(formOptions, result.options || {})
590
- emit('import', { components: result.components, options: { ...formOptions } })
591
- return result
592
- }
593
-
594
- defineExpose({
595
- getComponents,
596
- getForm,
597
- importJSON,
598
- exportJSON,
599
- downloadForm,
600
- validate,
601
- clearForm: clearRule,
602
- undo,
603
- redo,
604
- components: computed(() => props.modelValue),
605
- formOptions
606
- })
607
- </script>
608
-
609
- <style lang="scss">
610
- .gb-fc-designer {
611
- ._fc-l-item {
612
- user-select: none;
613
- }
614
-
615
- .gb-fc-watermark {
616
- position: absolute;
617
- left: 50%;
618
- bottom: 9px;
619
- transform: translateX(-50%);
620
- font-size: 12px;
621
- color: #c0c4cc;
622
- text-decoration: none;
623
- z-index: 1;
624
- }
625
-
626
- .el-divider--horizontal {
627
- margin: 14px 0 10px;
628
- }
629
-
630
- ._fc-m-drag {
631
- min-height: 100%;
632
- }
633
- }
1
+ <template>
2
+ <el-container class="_fc-designer gb-fc-designer" style="height: 100%">
3
+ <el-main>
4
+ <el-container style="height: 100%">
5
+ <el-aside class="_fc-l-menu" width="40px">
6
+ <el-tooltip effect="dark" content="组件列表" placement="right" :hide-after="0">
7
+ <div class="_fc-l-menu-item" :class="{ active: activeModule === 'base' }" @click="activeModule = 'base'">
8
+ <i class="fc-icon icon-menu"></i>
9
+ </div>
10
+ </el-tooltip>
11
+ <el-tooltip effect="dark" content="JSON" placement="right" :hide-after="0">
12
+ <div class="_fc-l-menu-item" :class="{ active: activeModule === 'json' }" @click="activeModule = 'json'">
13
+ <i class="fc-icon icon-script"></i>
14
+ </div>
15
+ </el-tooltip>
16
+ </el-aside>
17
+
18
+ <el-aside v-show="!hiddenLeft" class="_fc-l" width="266px">
19
+ <div class="_fc-l-close" @click="hiddenLeft = true"><i class="fc-icon icon-arrow"></i></div>
20
+ <FcJsonPanel
21
+ v-if="activeModule === 'json'"
22
+ ref="jsonPanelRef"
23
+ :components="modelValue"
24
+ :form-options="formOptions"
25
+ @update:components="applyComponents"
26
+ @update:form-options="applyOptions"
27
+ />
28
+ <el-container v-else style="height: 100%">
29
+ <el-header height="40px" class="_fc-l-tabs">
30
+ <div class="_fc-l-tab" :class="{ active: activeMenuTab === 'menu' }" @click="activeMenuTab = 'menu'">
31
+ 组件
32
+ </div>
33
+ <div class="_fc-l-tab" :class="{ active: activeMenuTab === 'tree' }" @click="activeMenuTab = 'tree'">
34
+ 大纲
35
+ </div>
36
+ </el-header>
37
+ <el-main v-show="activeMenuTab === 'menu'">
38
+ <div v-for="category in categories" :key="category.key" class="_fc-l-group">
39
+ <h4 class="_fc-l-title" @click="category.hidden = !category.hidden">
40
+ {{ category.name }}
41
+ <i class="fc-icon icon-arrow" :class="{ down: !category.hidden }"></i>
42
+ </h4>
43
+ <div v-show="!category.hidden" class="_fc-l-list">
44
+ <div
45
+ v-for="item in category.templates"
46
+ :key="item.type"
47
+ class="_fc-l-item"
48
+ draggable="true"
49
+ @dragstart="onMenuDragStart($event, item)"
50
+ @dragend="onDragEnd"
51
+ @click="addFromTemplate(item)"
52
+ >
53
+ <div class="_fc-l-icon"><i class="fc-icon" :class="iconOf(item.type)"></i></div>
54
+ <span class="_fc-l-name">{{ item.name }}</span>
55
+ </div>
56
+ </div>
57
+ </div>
58
+ </el-main>
59
+ <el-main v-show="activeMenuTab === 'tree'">
60
+ <el-tree
61
+ :data="treeData"
62
+ node-key="id"
63
+ :expand-on-click-node="false"
64
+ default-expand-all
65
+ @node-click="onTreeNodeClick"
66
+ >
67
+ <template #default="{ data }">
68
+ <div class="_fc-tree-node" :class="{ active: activeId === data.rule?.id }">
69
+ <div class="_fc-tree-label">
70
+ <i class="fc-icon" :class="data.icon || 'icon-cell'"></i>
71
+ <span>{{ data.label }}</span>
72
+ </div>
73
+ <div class="_fc-tree-more" @click.stop>
74
+ <el-dropdown trigger="click" size="default" @command="(command) => onTreeCommand(command, data)">
75
+ <i class="fc-icon icon-more"></i>
76
+ <template #dropdown>
77
+ <el-dropdown-menu>
78
+ <el-dropdown-item command="copy">复制</el-dropdown-item>
79
+ <el-dropdown-item command="delete">删除</el-dropdown-item>
80
+ </el-dropdown-menu>
81
+ </template>
82
+ </el-dropdown>
83
+ </div>
84
+ </div>
85
+ </template>
86
+ </el-tree>
87
+ </el-main>
88
+ </el-container>
89
+ </el-aside>
90
+
91
+ <el-container class="_fc-m">
92
+ <el-header class="_fc-m-tools" height="45">
93
+ <div class="_fc-m-tools-l">
94
+ <div class="devices">
95
+ <i class="fc-icon icon-pc" :class="{ active: device === 'pc' }" @click="device = 'pc'"></i>
96
+ <i class="fc-icon icon-pad" :class="{ active: device === 'pad' }" @click="device = 'pad'"></i>
97
+ <i class="fc-icon icon-mobile" :class="{ active: device === 'mobile' }" @click="device = 'mobile'"></i>
98
+ </div>
99
+ <div class="line"></div>
100
+ <div>
101
+ <i class="fc-icon icon-pre-step" :class="{ disabled: !canUndo }" @click="undo"></i>
102
+ <i class="fc-icon icon-next-step" :class="{ disabled: !canRedo }" @click="redo"></i>
103
+ </div>
104
+ </div>
105
+ <div class="_fc-m-tools-r">
106
+ <el-button :icon="Upload" plain size="small" @click="openImport">导入</el-button>
107
+ <el-button type="primary" plain size="small" @click="previewVisible = true">
108
+ <i class="fc-icon icon-preview"></i> 预览
109
+ </el-button>
110
+ <el-popconfirm title="确定清空所有组件?" width="200px" confirm-button-text="清空" cancel-button-text="取消" @confirm="clearRule">
111
+ <template #reference>
112
+ <el-button type="danger" plain size="small"><i class="fc-icon icon-delete"></i> 清空</el-button>
113
+ </template>
114
+ </el-popconfirm>
115
+ </div>
116
+ </el-header>
117
+ <el-main class="_fc-m-con">
118
+ <a class="gb-fc-watermark" href="javascript:void(0)">GbFlowDesign</a>
119
+ <div
120
+ ref="dragCon"
121
+ class="_fc-m-drag"
122
+ :class="device"
123
+ :style="dragStyle"
124
+ @dragover.prevent
125
+ @drop.prevent="onCanvasDrop"
126
+ >
127
+ <el-form
128
+ v-if="modelValue.length"
129
+ :model="canvasData"
130
+ :label-width="formOptions.labelWidth || '120px'"
131
+ :size="formOptions.size === 'default' ? undefined : formOptions.size"
132
+ >
133
+ <FcCanvasField
134
+ v-for="(component, index) in modelValue"
135
+ :key="component.id || index"
136
+ :component="component"
137
+ :path="[index]"
138
+ :form-data="canvasData"
139
+ :form-rules="canvasRules"
140
+ :active-id="activeId"
141
+ />
142
+ </el-form>
143
+ <div v-else class="_fd-draggable-drag _fd-drag-box drag-holder" @click="clearActive"></div>
144
+ </div>
145
+ </el-main>
146
+ </el-container>
147
+
148
+ <el-aside v-show="!hiddenRight" class="_fc-r" width="320px">
149
+ <div class="_fc-r-close" @click="hiddenRight = true"><i class="fc-icon icon-arrow"></i></div>
150
+ <FcPropsPanel :component="activeComponent" :form-options="formOptions" @close="clearActive" />
151
+ </el-aside>
152
+
153
+ <div v-if="hiddenLeft" class="_fc-l-open" @click="hiddenLeft = false"><i class="fc-icon icon-arrow"></i></div>
154
+ <div v-if="hiddenRight" class="_fc-r-open" @click="hiddenRight = false"><i class="fc-icon icon-arrow"></i></div>
155
+
156
+ <FcPreviewDialog v-model="previewVisible" :components="modelValue" :form-options="formOptions" />
157
+ </el-container>
158
+ </el-main>
159
+ </el-container>
160
+ </template>
161
+
162
+ <script setup>
163
+ import { computed, nextTick, onMounted, provide, reactive, ref, watch } from 'vue'
164
+ import { ElMessage } from 'element-plus'
165
+ import { Upload } from 'gbicons'
166
+ import FcCanvasField from './FcCanvasField.vue'
167
+ import FcPropsPanel from './FcPropsPanel.vue'
168
+ import FcJsonPanel from './FcJsonPanel.vue'
169
+ import FcPreviewDialog from './FcPreviewDialog.vue'
170
+ import { COMPONENT_CATEGORIES } from '../../design/constants/componentTemplates.js'
171
+ import { COMPONENT_TYPES } from '../../design/constants/componentTypes.js'
172
+ import { ensureComponentId, generateComponentId } from '../../design/utils/componentUtils.js'
173
+ import { validateForm, exportForm, importForm } from '../../core/schema.js'
174
+ import { downloadJSON, pickJSONFile } from '../../core/fileIO.js'
175
+
176
+ defineOptions({ name: 'GbFormDesigner' })
177
+
178
+ const props = defineProps({
179
+ modelValue: { type: Array, default: () => [] },
180
+ options: { type: Object, default: null },
181
+ meta: { type: Object, default: () => ({}) },
182
+ fileName: { type: String, default: 'form' }
183
+ })
184
+
185
+ const emit = defineEmits(['update:modelValue', 'update:options', 'import', 'export', 'validate', 'change'])
186
+
187
+ const clone = (value) => JSON.parse(JSON.stringify(value ?? []))
188
+
189
+ const localOptions = reactive({
190
+ name: '',
191
+ description: '',
192
+ labelWidth: '120px',
193
+ size: 'default',
194
+ ...(props.options || {})
195
+ })
196
+
197
+ const formOptions = props.options ? reactive(props.options) : localOptions
198
+
199
+ watch(
200
+ () => props.options,
201
+ (value) => {
202
+ if (!value || value === formOptions) return
203
+ Object.assign(formOptions, value)
204
+ },
205
+ { deep: true }
206
+ )
207
+
208
+ provide('fcFormOptions', formOptions)
209
+
210
+ const activeModule = ref('base')
211
+ const activeMenuTab = ref('menu')
212
+ const hiddenLeft = ref(false)
213
+ const hiddenRight = ref(false)
214
+ const device = ref('pc')
215
+ const previewVisible = ref(false)
216
+ const activeId = ref('')
217
+ const dragOver = ref('')
218
+ const jsonPanelRef = ref(null)
219
+
220
+ const dragStyle = {
221
+ '--fc-drag-empty': "'拖拽左侧列表中的组件到此处'",
222
+ '--fc-child-empty': "'点击右下角 + 按钮添加一列'"
223
+ }
224
+
225
+ const canvasData = reactive({})
226
+ const canvasRules = {}
227
+
228
+ const categories = ref(
229
+ COMPONENT_CATEGORIES.map((category) => ({ ...category, hidden: false }))
230
+ )
231
+
232
+ const ICONS = {
233
+ [COMPONENT_TYPES.INPUT]: 'icon-input',
234
+ [COMPONENT_TYPES.TEXTAREA]: 'icon-textarea',
235
+ [COMPONENT_TYPES.INPUT_NUMBER]: 'icon-number',
236
+ [COMPONENT_TYPES.RADIO_GROUP]: 'icon-radio',
237
+ [COMPONENT_TYPES.CHECKBOX_GROUP]: 'icon-checkbox',
238
+ [COMPONENT_TYPES.SELECT]: 'icon-select',
239
+ [COMPONENT_TYPES.SWITCH]: 'icon-switch',
240
+ [COMPONENT_TYPES.DATE_PICKER]: 'icon-date',
241
+ [COMPONENT_TYPES.ROW]: 'icon-row'
242
+ }
243
+
244
+ const iconOf = (type) => ICONS[type] || 'icon-input'
245
+
246
+ // ==================== History ====================
247
+
248
+ const history = ref([])
249
+ const historyIndex = ref(-1)
250
+ let restoring = false
251
+ let historyTimer = null
252
+
253
+ const snapshot = () => JSON.stringify({ components: props.modelValue, options: { ...formOptions } })
254
+
255
+ const pushHistory = () => {
256
+ const snap = snapshot()
257
+ if (history.value[historyIndex.value] === snap) return
258
+ history.value = history.value.slice(0, historyIndex.value + 1)
259
+ history.value.push(snap)
260
+ if (history.value.length > 50) history.value.shift()
261
+ historyIndex.value = history.value.length - 1
262
+ }
263
+
264
+ const canUndo = computed(() => historyIndex.value > 0)
265
+ const canRedo = computed(() => historyIndex.value < history.value.length - 1)
266
+
267
+ const applyHistory = () => {
268
+ const { components, options } = JSON.parse(history.value[historyIndex.value])
269
+ restoring = true
270
+ emit('update:modelValue', components)
271
+ Object.assign(formOptions, options)
272
+ nextTick(() => {
273
+ restoring = false
274
+ })
275
+ }
276
+
277
+ const undo = () => {
278
+ if (!canUndo.value) return
279
+ historyIndex.value -= 1
280
+ applyHistory()
281
+ }
282
+
283
+ const redo = () => {
284
+ if (!canRedo.value) return
285
+ historyIndex.value += 1
286
+ applyHistory()
287
+ }
288
+
289
+ watch(
290
+ () => [props.modelValue, { ...formOptions }],
291
+ () => {
292
+ if (restoring) return
293
+ clearTimeout(historyTimer)
294
+ historyTimer = setTimeout(pushHistory, 300)
295
+ },
296
+ { deep: true }
297
+ )
298
+
299
+ onMounted(() => {
300
+ pushHistory()
301
+ })
302
+
303
+ const applyComponents = (components) => {
304
+ emit('update:modelValue', clone(components))
305
+ }
306
+
307
+ const applyOptions = (options) => {
308
+ Object.assign(formOptions, options || {})
309
+ emit('update:options', { ...formOptions })
310
+ }
311
+
312
+ // ==================== Field creation ====================
313
+
314
+ const findTemplate = (type) => {
315
+ for (const category of COMPONENT_CATEGORIES) {
316
+ const found = category.templates.find((item) => item.type === type)
317
+ if (found) return found
318
+ }
319
+ return null
320
+ }
321
+
322
+ const createFieldFromTemplate = (template) => {
323
+ const component = clone(template)
324
+ delete component.name
325
+ delete component.icon
326
+ ensureComponentId(component)
327
+ component.props = component.props || {}
328
+ if (!component.props.variableName) component.props.variableName = `field_${generateComponentId().split('_').pop()}`
329
+ if (component.type === COMPONENT_TYPES.ROW) {
330
+ component.children = [[], []]
331
+ component.props.columns = component.props.columns || [{ span: 12 }, { span: 12 }]
332
+ }
333
+ return component
334
+ }
335
+
336
+ const createFieldByType = (type) => {
337
+ const template = findTemplate(type)
338
+ if (!template) return null
339
+ return createFieldFromTemplate(template)
340
+ }
341
+
342
+ const addFromTemplate = (template) => {
343
+ const component = createFieldFromTemplate(template)
344
+ const list = [...props.modelValue, component]
345
+ applyComponents(list)
346
+ activeId.value = component.id
347
+ }
348
+
349
+ // ==================== Path helpers ====================
350
+
351
+ const resolveParent = (path) => {
352
+ if (path.length === 1) return { list: props.modelValue, index: path[0], node: null }
353
+ const [rowIndex, , columnIndex, childIndex] = path
354
+ const row = props.modelValue[rowIndex]
355
+ return { list: row?.children?.[columnIndex] || [], index: childIndex, node: row }
356
+ }
357
+
358
+ const findById = (list, id) => {
359
+ for (const component of list || []) {
360
+ if (component.id === id) return component
361
+ if (component.type === COMPONENT_TYPES.ROW) {
362
+ for (const column of component.children || []) {
363
+ const found = findById(column, id)
364
+ if (found) return found
365
+ }
366
+ }
367
+ }
368
+ return null
369
+ }
370
+
371
+ const activeComponent = computed(() => (activeId.value ? findById(props.modelValue, activeId.value) : null))
372
+
373
+ const active = (component) => {
374
+ activeId.value = component.id
375
+ }
376
+
377
+ const clearActive = () => {
378
+ activeId.value = ''
379
+ }
380
+
381
+ const newIdDeep = (component) => {
382
+ component.id = generateComponentId()
383
+ if (component.type === COMPONENT_TYPES.ROW) {
384
+ ;(component.children || []).forEach((column) => column.forEach(newIdDeep))
385
+ }
386
+ return component
387
+ }
388
+
389
+ const copyAt = (path) => {
390
+ const parent = resolveParent(path)
391
+ const source = parent.list[path[path.length - 1]]
392
+ if (!source) return
393
+ const copy = newIdDeep(clone(source))
394
+ parent.list.splice(parent.index + 1, 0, copy)
395
+ applyComponents(props.modelValue)
396
+ activeId.value = copy.id
397
+ }
398
+
399
+ const removeAt = (path) => {
400
+ const parent = resolveParent(path)
401
+ parent.list.splice(parent.index, 1)
402
+ applyComponents(props.modelValue)
403
+ if (activeId.value) {
404
+ const stillThere = findById(props.modelValue, activeId.value)
405
+ if (!stillThere) clearActive()
406
+ }
407
+ }
408
+
409
+ // ==================== Drag & drop ====================
410
+
411
+ const dragPayload = ref(null)
412
+
413
+ const getDragPayload = () => {
414
+ if (dragPayload.value) return dragPayload.value
415
+ return null
416
+ }
417
+
418
+ const onMenuDragStart = (event, template) => {
419
+ const payload = { kind: 'new', type: template.type }
420
+ dragPayload.value = payload
421
+ event.dataTransfer.effectAllowed = 'copy'
422
+ event.dataTransfer.setData('application/x-gb-field', JSON.stringify(payload))
423
+ event.dataTransfer.setData('text/plain', template.type)
424
+ }
425
+
426
+ const startDrag = (path) => {
427
+ dragPayload.value = { kind: 'existing', path: [...path] }
428
+ }
429
+
430
+ const onDragEnd = () => {
431
+ dragPayload.value = null
432
+ dragOver.value = ''
433
+ }
434
+
435
+ const onCanvasDrop = (event) => {
436
+ const raw = event.dataTransfer?.getData('application/x-gb-field')
437
+ let payload = dragPayload.value
438
+ if (raw) {
439
+ try {
440
+ payload = JSON.parse(raw)
441
+ } catch {
442
+ payload = dragPayload.value
443
+ }
444
+ }
445
+ dragOver.value = ''
446
+ dragPayload.value = null
447
+ if (!payload) return
448
+ dropAt(payload, { path: null, position: 'bottom' })
449
+ }
450
+
451
+ const dropAt = (payload, target) => {
452
+ if (!payload) return
453
+ let list = props.modelValue
454
+ let index = props.modelValue.length
455
+
456
+ if (target.column !== undefined && target.path) {
457
+ const row = resolveParent(target.path).list[target.path[target.path.length - 1]]
458
+ if (!row?.children?.[target.column]) return
459
+ if (payload.kind === 'existing') {
460
+ const moving = resolveParent(payload.path).list[payload.path[payload.path.length - 1]]
461
+ if (moving?.type === COMPONENT_TYPES.ROW) {
462
+ ElMessage.warning('分栏组件不能放入分栏内')
463
+ return
464
+ }
465
+ }
466
+ list = row.children[target.column]
467
+ index = list.length
468
+ } else if (target.path) {
469
+ if (payload.kind === 'existing') {
470
+ const isSelfOrChild =
471
+ payload.path.length <= target.path.length &&
472
+ payload.path.every((value, i) => value === target.path[i])
473
+ if (isSelfOrChild) return
474
+ }
475
+ const parent = resolveParent(target.path)
476
+ list = parent.list
477
+ index = target.position === 'top' ? parent.index : parent.index + 1
478
+ }
479
+
480
+ let component
481
+ if (payload.kind === 'new') {
482
+ component = createFieldByType(payload.type)
483
+ if (!component) return
484
+ } else {
485
+ const sourceParent = resolveParent(payload.path)
486
+ component = sourceParent.list[sourceParent.index]
487
+ if (!component) return
488
+ if (sourceParent.list === list && sourceParent.index < index) index -= 1
489
+ sourceParent.list.splice(sourceParent.index, 1)
490
+ }
491
+
492
+ list.splice(index, 0, component)
493
+ applyComponents(props.modelValue)
494
+ activeId.value = component.id
495
+ }
496
+
497
+ provide('fcDragOver', dragOver)
498
+ provide('fcCanvasOps', {
499
+ active,
500
+ copy: copyAt,
501
+ remove: removeAt,
502
+ startDrag,
503
+ endDrag: onDragEnd,
504
+ getDragPayload,
505
+ dropAt
506
+ })
507
+
508
+ // ==================== Tree ====================
509
+
510
+ const buildTree = (list, parentPath = []) =>
511
+ (list || []).map((component, index) => {
512
+ const path = [...parentPath, index]
513
+ const node = {
514
+ id: component.id,
515
+ label: component.props?.label || component.props?.variableName || component.type,
516
+ icon: iconOf(component.type),
517
+ rule: component,
518
+ path
519
+ }
520
+ if (component.type === COMPONENT_TYPES.ROW) {
521
+ node.children = (component.children || []).flatMap((column, columnIndex) =>
522
+ buildTree(column || [], [...parentPath, index, 'children', columnIndex])
523
+ )
524
+ }
525
+ return node
526
+ })
527
+
528
+ const treeData = computed(() => buildTree(props.modelValue))
529
+
530
+ const onTreeNodeClick = (data) => {
531
+ if (data.rule) activeId.value = data.rule.id
532
+ }
533
+
534
+ const onTreeCommand = (command, data) => {
535
+ if (!data.path) return
536
+ if (command === 'copy') copyAt(data.path)
537
+ else if (command === 'delete') removeAt(data.path)
538
+ }
539
+
540
+ // ==================== Import / export / clear ====================
541
+
542
+ const openImport = async () => {
543
+ const picked = await pickJSONFile()
544
+ if (!picked) return
545
+ try {
546
+ const result = importForm(picked.text)
547
+ emit('update:modelValue', result.components)
548
+ Object.assign(formOptions, result.options || {})
549
+ emit('import', { components: result.components, options: { ...formOptions } })
550
+ ElMessage.success('表单导入成功')
551
+ } catch (error) {
552
+ ElMessage.error(`导入失败:${error.message}`)
553
+ }
554
+ }
555
+
556
+ const clearRule = () => {
557
+ emit('update:modelValue', [])
558
+ clearActive()
559
+ ElMessage.success('表单已清空')
560
+ }
561
+
562
+ const validate = () => {
563
+ const result = validateForm({ components: props.modelValue })
564
+ emit('validate', result)
565
+ return result
566
+ }
567
+
568
+ const getComponents = () => clone(props.modelValue)
569
+ const getForm = () => ({ components: getComponents(), options: { ...formOptions } })
570
+
571
+ const exportJSON = (space = 2) => {
572
+ const payload = exportForm(props.modelValue, { ...props.meta, name: props.meta?.name || props.fileName }, { raw: true })
573
+ payload.form.options = { ...formOptions }
574
+ emit('export', payload)
575
+ return JSON.stringify(payload, null, space)
576
+ }
577
+
578
+ const downloadForm = () => {
579
+ const payload = exportForm(props.modelValue, { ...props.meta, name: props.meta?.name || props.fileName }, { raw: true })
580
+ payload.form.options = { ...formOptions }
581
+ downloadJSON(payload, `${props.meta?.name || props.fileName}-form.json`)
582
+ emit('export', payload)
583
+ ElMessage.success('表单 JSON 已导出')
584
+ }
585
+
586
+ const importJSON = (input) => {
587
+ const result = importForm(input)
588
+ emit('update:modelValue', result.components)
589
+ Object.assign(formOptions, result.options || {})
590
+ emit('import', { components: result.components, options: { ...formOptions } })
591
+ return result
592
+ }
593
+
594
+ defineExpose({
595
+ getComponents,
596
+ getForm,
597
+ importJSON,
598
+ exportJSON,
599
+ downloadForm,
600
+ validate,
601
+ clearForm: clearRule,
602
+ undo,
603
+ redo,
604
+ components: computed(() => props.modelValue),
605
+ formOptions
606
+ })
607
+ </script>
608
+
609
+ <style lang="scss">
610
+ .gb-fc-designer {
611
+ ._fc-l-item {
612
+ user-select: none;
613
+ }
614
+
615
+ .gb-fc-watermark {
616
+ position: absolute;
617
+ left: 50%;
618
+ bottom: 9px;
619
+ transform: translateX(-50%);
620
+ font-size: 12px;
621
+ color: #c0c4cc;
622
+ text-decoration: none;
623
+ z-index: 1;
624
+ }
625
+
626
+ .el-divider--horizontal {
627
+ margin: 14px 0 10px;
628
+ }
629
+
630
+ ._fc-m-drag {
631
+ min-height: 100%;
632
+ }
633
+ }
634
634
  </style>