@littlekit/ui-element-plus-renderer 0.0.0-stage → 0.2.0-beta.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.
package/dist/index.js ADDED
@@ -0,0 +1,1009 @@
1
+ // Element Plus 只呈现状态,字段变更、校验、请求与动作仍经过同一个控制器。
2
+ import { defineComponent, h, onMounted, onScopeDispose, shallowRef, useId } from 'vue';
3
+ import { ElAlert, ElButton, ElCascader, ElTreeSelect, ElTable, ElTableColumn, ElCheckbox, ElCheckboxGroup, ElConfigProvider, ElDialog, ElDatePicker, ElForm, ElFormItem, ElInput, ElInputNumber, ElOption, ElRadio, ElRadioGroup, ElSelect, ElSwitch } from 'element-plus';
4
+ import { getByPath, isUploadFileRef, isDateOutsideLimits, isTimePartDisabled, dateShortcutValue, dateShortcutLabels, validateDateValue } from '@littlekit/ui-core';
5
+ import en from 'element-plus/es/locale/lang/en.mjs';
6
+ import zhCn from 'element-plus/es/locale/lang/zh-cn.mjs';
7
+ import { littleUiFieldDefaults, useLittleForm, useLittleDialog, useLittleTable, useLittleUiConfig } from '@littlekit/ui-vue3-adapter';
8
+ // 仅在渲染入口适配 Select 的组件类型。Element Plus 的通用组件声明
9
+ // 与 Vue h 的 exactOptionalPropertyTypes 重载存在冲突。
10
+ const SelectControl = ElSelect;
11
+ const SelectOption = ElOption;
12
+ // Provider 的对外类型与 Select 一样,在这里收窄为渲染器实际传入的属性。
13
+ const ConfigProvider = ElConfigProvider;
14
+ function isOptionValue(value) {
15
+ return typeof value === 'string' || typeof value === 'number';
16
+ }
17
+ function displayOptions(options, parentDisabled = false) {
18
+ return options.flatMap((option) => {
19
+ const disabled = option.disabled || parentDisabled;
20
+ if (option.children.length)
21
+ return displayOptions(option.children, disabled);
22
+ return isOptionValue(option.value)
23
+ ? [{ value: option.value, label: String(option.label ?? ''), disabled }]
24
+ : [];
25
+ });
26
+ }
27
+ function treeOptions(options, parentDisabled = false, disableBranches = false, lazy = false) {
28
+ return options.flatMap((option) => {
29
+ const disabled = parentDisabled || option.disabled;
30
+ const children = treeOptions(option.children, disabled, disableBranches, lazy);
31
+ const raw = option.extra && typeof option.extra === 'object'
32
+ ? option.extra
33
+ : {};
34
+ const branch = children.length > 0 ||
35
+ (lazy && raw.isLeaf === false && !Array.isArray(raw.children));
36
+ if (!isOptionValue(option.value))
37
+ return [];
38
+ return [
39
+ {
40
+ value: option.value,
41
+ key: option.value,
42
+ label: String(option.label ?? ''),
43
+ disabled: disabled || (disableBranches && branch && !lazy),
44
+ isLeaf: !branch,
45
+ leaf: !branch,
46
+ ...(children.length ? { children } : {})
47
+ }
48
+ ];
49
+ });
50
+ }
51
+ export const LittleForm = defineComponent({
52
+ name: 'LittleElementPlusForm',
53
+ props: {
54
+ ui: Object,
55
+ controller: { type: Object, required: true },
56
+ showActions: { type: Boolean, default: true },
57
+ contentRenderers: {
58
+ type: Object,
59
+ default: () => ({})
60
+ }
61
+ },
62
+ emits: {
63
+ result: (key, result) => typeof key === 'string' && Boolean(result),
64
+ error: (..._args) => _args.length === 1
65
+ },
66
+ setup(props, { slots, emit }) {
67
+ const form = useLittleForm(props.controller);
68
+ const ui = useLittleUiConfig(() => props.ui);
69
+ const { controller, state } = form;
70
+ const lazyRootCache = new Map();
71
+ const uid = useId();
72
+ const confirmation = shallowRef();
73
+ const report = (cause) => emit('error', cause);
74
+ const render = (content) => form.renderContent(content, props.contentRenderers);
75
+ onMounted(() => {
76
+ void controller.initializeOptions().catch(report);
77
+ });
78
+ async function execute(key, confirmed = false) {
79
+ try {
80
+ const schema = controller.getActionConfirm(key);
81
+ if (schema && !confirmed) {
82
+ confirmation.value = { key, schema };
83
+ return;
84
+ }
85
+ emit('result', key, await controller.executeAction(key));
86
+ }
87
+ catch (cause) {
88
+ report(cause);
89
+ }
90
+ }
91
+ function renderField(item, status) {
92
+ const { field, type, modelFields } = item;
93
+ const path = modelFields.value;
94
+ const binding = form.field(field, path);
95
+ const value = binding.value.value;
96
+ const id = `${uid}-${encodeURIComponent(field)}`;
97
+ const label = render(item.label) ?? field;
98
+ const textLabel = item.label?.type === 'text' ? item.label.text : field;
99
+ const change = (next) => {
100
+ void binding.set(next).catch(report);
101
+ };
102
+ const blur = () => {
103
+ void binding.blur().catch(report);
104
+ };
105
+ const disabled = status.disabled || status.readonly;
106
+ const fieldDefaults = littleUiFieldDefaults(ui.value, type);
107
+ const attrs = { ...fieldDefaults, ...item.attrs };
108
+ const common = {
109
+ ...attrs,
110
+ ...(attrs.size === 'medium' ? { size: 'default' } : {}),
111
+ id,
112
+ 'aria-label': textLabel,
113
+ disabled,
114
+ onBlur: blur,
115
+ 'onUpdate:modelValue': change,
116
+ validateEvent: false
117
+ };
118
+ const monthStates = [...state.value.calendarMonths.values()].filter((entry) => entry.field === field);
119
+ const optionState = state.value.optionStates.get(field);
120
+ const options = item.optionSource
121
+ ? displayOptions(controller.getOptions(field))
122
+ : [];
123
+ const multiple = item.selectionMode === 'multiple';
124
+ const scalar = isOptionValue(value) ? value : undefined;
125
+ const list = Array.isArray(value) ? value.filter(isOptionValue) : [];
126
+ let control;
127
+ switch (type) {
128
+ case 'slot':
129
+ control =
130
+ slots[field]?.({
131
+ value,
132
+ model: form.model.value,
133
+ setValue: change,
134
+ disabled
135
+ }) ?? h('div', [render(item.description)]);
136
+ break;
137
+ case 'date':
138
+ case 'datetime':
139
+ case 'daterange':
140
+ case 'datetimerange': {
141
+ const range = type === 'daterange' || type === 'datetimerange';
142
+ const formatted = range
143
+ ? Array.isArray(value) &&
144
+ value.length === 2 &&
145
+ value.every((v) => typeof v === 'string')
146
+ ? value
147
+ : null
148
+ : typeof value === 'string'
149
+ ? value
150
+ : null;
151
+ control = h(ElDatePicker, {
152
+ ...common,
153
+ type,
154
+ valueFormat: type === 'datetime' || type === 'datetimerange'
155
+ ? 'YYYY-MM-DD HH:mm:ss'
156
+ : 'YYYY-MM-DD',
157
+ ...(item.dateLimit
158
+ ? {
159
+ disabledDate: (date) => isDateOutsideLimits(date, type === 'datetime' || type === 'datetimerange'
160
+ ? 'datetime'
161
+ : 'date', item.dateLimit, (path) => getByPath(form.model.value, path)) || controller.calendarDateDisabled(field, date)
162
+ }
163
+ : {}),
164
+ ...(item.dateLimit &&
165
+ (type === 'datetime' || type === 'datetimerange')
166
+ ? {
167
+ disabledHours: () => Array.from({ length: 24 }, (_, i) => i).filter((hour) => isTimePartDisabled(item.dateLimit, hour)),
168
+ disabledMinutes: (hour) => Array.from({ length: 60 }, (_, i) => i).filter((minute) => isTimePartDisabled(item.dateLimit, hour, minute)),
169
+ disabledSeconds: (hour, minute) => Array.from({ length: 60 }, (_, i) => i).filter((second) => isTimePartDisabled(item.dateLimit, hour, minute, second))
170
+ }
171
+ : {}),
172
+ ...(item.dateDefaultTime === undefined
173
+ ? {}
174
+ : {
175
+ defaultTime: (typeof item.dateDefaultTime === 'string'
176
+ ? [item.dateDefaultTime]
177
+ : item.dateDefaultTime)
178
+ .map((value) => {
179
+ const [hour, minute, second] = value
180
+ .split(':')
181
+ .map(Number);
182
+ return new Date(2000, 0, 1, hour, minute, second);
183
+ })
184
+ .reduce((_, value, index, array) => array.length === 1 ? value : array, [])
185
+ }),
186
+ modelValue: formatted,
187
+ 'onUpdate:modelValue': (next) => change(next == null || next === '' ? null : next)
188
+ });
189
+ break;
190
+ }
191
+ case 'upload': {
192
+ const files = Array.isArray(value)
193
+ ? value.filter(isUploadFileRef)
194
+ : [];
195
+ const tasks = state.value.uploadStates.get(field) ?? [];
196
+ const locked = disabled || state.value.submitting;
197
+ control = h('div', { class: 'little-upload' }, [
198
+ h('input', {
199
+ type: 'file',
200
+ 'aria-label': textLabel,
201
+ accept: item.upload?.accept?.join(','),
202
+ multiple: (item.upload?.maxCount ?? 1) > 1,
203
+ disabled: locked ||
204
+ files.length + tasks.length >= (item.upload?.maxCount ?? 1),
205
+ onBlur: blur,
206
+ onChange: (event) => {
207
+ const element = event.target;
208
+ const selected = Array.from(element.files ?? []);
209
+ element.value = '';
210
+ void controller.uploadFiles(field, selected).catch(report);
211
+ }
212
+ }),
213
+ h('ul', { class: 'little-upload-list' }, [
214
+ ...files.map((file) => h('li', { key: `file:${file.id}` }, [
215
+ h('span', file.name),
216
+ h(ElButton, {
217
+ size: 'small',
218
+ disabled: locked,
219
+ onClick: () => controller.removeUploadFile(field, file.id)
220
+ }, { default: () => '移除' })
221
+ ])),
222
+ ...tasks.map((task) => h('li', { key: task.id }, [
223
+ h('span', task.name),
224
+ ...(task.status === 'uploading'
225
+ ? [
226
+ h('progress', {
227
+ max: 100,
228
+ value: task.progress,
229
+ 'aria-label': `${task.name} 上传进度`
230
+ }),
231
+ h('span', `${Math.round(task.progress)}%`)
232
+ ]
233
+ : [
234
+ h('span', { role: 'alert' }, task.error ?? '上传失败'),
235
+ h(ElButton, {
236
+ size: 'small',
237
+ disabled: locked,
238
+ onClick: () => {
239
+ void controller
240
+ .retryUpload(field, task.id)
241
+ .catch(report);
242
+ }
243
+ }, { default: () => '重试' })
244
+ ]),
245
+ h(ElButton, {
246
+ size: 'small',
247
+ disabled: locked,
248
+ onClick: () => controller.cancelUpload(field, task.id)
249
+ }, {
250
+ default: () => task.status === 'uploading' ? '取消' : '移除'
251
+ })
252
+ ]))
253
+ ])
254
+ ]);
255
+ break;
256
+ }
257
+ case 'switch':
258
+ control = h(ElSwitch, {
259
+ ...common,
260
+ modelValue: typeof value === 'boolean' ? value : false
261
+ });
262
+ break;
263
+ case 'number':
264
+ control = h(ElInputNumber, {
265
+ ...common,
266
+ modelValue: typeof value === 'number' ? value : null
267
+ });
268
+ break;
269
+ case 'tree-select':
270
+ case 'cascader': {
271
+ const nodes = treeOptions(item.optionSource ? controller.getOptions(field) : [], false, type === 'tree-select', Boolean(item.treeLazy));
272
+ const tree = type === 'tree-select';
273
+ let rootNodes = nodes;
274
+ let revision = 0;
275
+ if (item.treeLazy) {
276
+ const roots = nodes.map((node) => ({
277
+ value: node.value,
278
+ key: node.key,
279
+ label: node.label,
280
+ disabled: node.disabled,
281
+ isLeaf: node.isLeaf,
282
+ leaf: node.leaf
283
+ }));
284
+ const source = item.optionSource;
285
+ const deps = source && (source.type === 'loader' || source.type === 'remote')
286
+ ? source.effectiveDependsOn.map((path) => getByPath(form.model.value, path))
287
+ : [];
288
+ let signature;
289
+ try {
290
+ signature = JSON.stringify([roots, deps]);
291
+ }
292
+ catch {
293
+ signature = JSON.stringify(roots);
294
+ }
295
+ const countNodes = (items) => items.reduce((count, node) => count + 1 + countNodes(node.children ?? []), 0);
296
+ const count = countNodes(nodes);
297
+ const cached = lazyRootCache.get(field);
298
+ if (cached &&
299
+ cached.signature === signature &&
300
+ count >= cached.count) {
301
+ rootNodes = cached.nodes;
302
+ revision = cached.revision;
303
+ }
304
+ else
305
+ revision = (cached?.revision ?? 0) + 1;
306
+ lazyRootCache.set(field, {
307
+ signature,
308
+ nodes: rootNodes,
309
+ count,
310
+ revision
311
+ });
312
+ }
313
+ const lazyLoad = (node, resolve, reject) => {
314
+ if (node.level === 0) {
315
+ resolve(rootNodes);
316
+ return;
317
+ }
318
+ const value = node.data?.value ?? node.value;
319
+ if (!isOptionValue(value)) {
320
+ reject();
321
+ return;
322
+ }
323
+ void controller
324
+ .loadTreeChildren(field, value)
325
+ .then(() => {
326
+ const find = (items) => {
327
+ for (const item of items) {
328
+ if (Object.is(item.value, value))
329
+ return item;
330
+ const found = find(item.children);
331
+ if (found)
332
+ return found;
333
+ }
334
+ return undefined;
335
+ };
336
+ const found = find(controller.getOptions(field));
337
+ resolve(treeOptions(found?.children ?? [], false, tree, true));
338
+ })
339
+ .catch(() => reject());
340
+ };
341
+ control = h((tree ? ElTreeSelect : ElCascader), {
342
+ ...common,
343
+ ...(item.treeLazy ? { key: `${field}:${revision}` } : {}),
344
+ ...(tree
345
+ ? {
346
+ data: item.treeLazy ? rootNodes : nodes,
347
+ nodeKey: 'value',
348
+ showCheckbox: multiple,
349
+ checkStrictly: !item.treeLazy,
350
+ ...(item.treeLazy
351
+ ? {
352
+ lazy: true,
353
+ load: lazyLoad,
354
+ props: { isLeaf: 'leaf' }
355
+ }
356
+ : {})
357
+ }
358
+ : {
359
+ options: item.treeLazy ? rootNodes : nodes,
360
+ props: {
361
+ multiple,
362
+ emitPath: false,
363
+ checkStrictly: false,
364
+ ...(item.treeLazy
365
+ ? { lazy: true, lazyLoad, leaf: 'leaf' }
366
+ : {})
367
+ }
368
+ }),
369
+ multiple,
370
+ modelValue: multiple ? list : (scalar ?? null),
371
+ onVisibleChange: (show) => {
372
+ if (show)
373
+ void binding.open().catch(report);
374
+ }
375
+ });
376
+ break;
377
+ }
378
+ case 'select': {
379
+ const remote = item.optionSource?.type === 'remote';
380
+ control = h(SelectControl, {
381
+ ...common,
382
+ modelValue: multiple ? list : (scalar ?? null),
383
+ multiple,
384
+ remote,
385
+ filterable: remote || attrs.filterable === true,
386
+ loading: optionState?.loading ?? false,
387
+ valueOnClear: () => null,
388
+ // 防抖由 Core 负责;组件只适配搜索与展开事件。
389
+ debounce: 0,
390
+ remoteMethod: (query) => {
391
+ if (remote)
392
+ void binding.search(query).catch(report);
393
+ },
394
+ onVisibleChange: (visible) => {
395
+ if (visible)
396
+ void binding.open().catch(report);
397
+ }
398
+ }, {
399
+ default: () => options.map((option) => h(SelectOption, {
400
+ key: option.value,
401
+ value: option.value,
402
+ label: option.label,
403
+ disabled: option.disabled
404
+ }))
405
+ });
406
+ break;
407
+ }
408
+ case 'radio':
409
+ control = h(ElRadioGroup, { ...common, modelValue: scalar ?? '' }, {
410
+ default: () => options.map((option) => h(ElRadio, {
411
+ key: option.value,
412
+ value: option.value,
413
+ disabled: option.disabled
414
+ }, { default: () => option.label }))
415
+ });
416
+ break;
417
+ case 'checkbox':
418
+ control = h(ElCheckboxGroup, {
419
+ ...common,
420
+ modelValue: multiple
421
+ ? list
422
+ : scalar === undefined
423
+ ? []
424
+ : [scalar],
425
+ 'onUpdate:modelValue': (values) => change(multiple ? values : (values.at(-1) ?? null))
426
+ }, {
427
+ default: () => options.map((option) => h(ElCheckbox, {
428
+ key: option.value,
429
+ value: option.value,
430
+ disabled: option.disabled
431
+ }, { default: () => option.label }))
432
+ });
433
+ break;
434
+ default:
435
+ control = h(ElInput, {
436
+ ...common,
437
+ disabled: status.disabled,
438
+ readonly: status.readonly,
439
+ type: type === 'textarea' ? 'textarea' : 'text',
440
+ modelValue: typeof value === 'string' ? value : ''
441
+ });
442
+ }
443
+ const error = path === undefined
444
+ ? ''
445
+ : (controller.getVisibleErrors(path)[0]?.message ?? '');
446
+ const required = path !== undefined &&
447
+ controller.schema.rules[path]?.some((rule) => rule.type === 'required' && rule.when === undefined);
448
+ return h('div', {
449
+ key: field,
450
+ class: 'little-el-field',
451
+ 'data-field': field,
452
+ style: { '--little-el-span': item.span }
453
+ }, [
454
+ h(ElFormItem, {
455
+ label: textLabel,
456
+ for: id,
457
+ error,
458
+ required: Boolean(required)
459
+ }, { label: () => label, default: () => control }),
460
+ ...(monthStates.some((v) => v.status === 'loading')
461
+ ? [h('div', { role: 'status' }, '正在加载可用日期…')]
462
+ : []),
463
+ ...(monthStates.some((v) => v.status === 'error')
464
+ ? [
465
+ h('div', { role: 'alert' }, [
466
+ '可用日期加载失败,未加载的日期不可选。',
467
+ h(ElButton, {
468
+ size: 'small',
469
+ onClick: () => controller.retryCalendarMonths(field)
470
+ }, { default: () => '重试' })
471
+ ])
472
+ ]
473
+ : []),
474
+ ...((type === 'tree-select' || type === 'cascader') &&
475
+ item.optionSource?.type === 'remote'
476
+ ? [
477
+ h('label', { class: 'little-tree-search' }, [
478
+ h('span', '搜索'),
479
+ h('input', {
480
+ type: 'search',
481
+ 'aria-label': `搜索${textLabel}`,
482
+ disabled,
483
+ placeholder: '输入关键字搜索',
484
+ onInput: (event) => {
485
+ void binding
486
+ .search(event.target.value)
487
+ .catch(report);
488
+ }
489
+ }),
490
+ ...(optionState?.loading
491
+ ? [h('span', { role: 'status' }, '正在搜索…')]
492
+ : [])
493
+ ])
494
+ ]
495
+ : []),
496
+ ...(item.dateShortcuts?.length
497
+ ? [
498
+ h('div', { class: 'little-date-shortcuts' }, item.dateShortcuts.map((shortcut) => {
499
+ const current = () => dateShortcutValue(shortcut, type === 'datetimerange' ? 'datetime' : 'date');
500
+ const allowed = () => validateDateValue(current(), type === 'datetimerange' ? 'datetime' : 'date', true, item.dateLimit ?? {}, (path) => getByPath(form.model.value, path)) &&
501
+ current().every((v) => {
502
+ const [year, month, day] = v
503
+ .slice(0, 10)
504
+ .split('-')
505
+ .map(Number);
506
+ return !controller.calendarDateDisabled(field, new Date(year, month - 1, day));
507
+ });
508
+ return h(ElButton, {
509
+ key: shortcut,
510
+ size: 'small',
511
+ disabled: disabled || !allowed(),
512
+ onClick: () => {
513
+ if (allowed())
514
+ change(current());
515
+ }
516
+ }, { default: () => dateShortcutLabels[shortcut] });
517
+ }))
518
+ ]
519
+ : []),
520
+ ...(item.description && type !== 'slot'
521
+ ? [
522
+ h('p', { class: 'little-el-description' }, [
523
+ render(item.description)
524
+ ])
525
+ ]
526
+ : []),
527
+ ...(optionState?.error
528
+ ? [
529
+ h(ElAlert, {
530
+ title: optionState.error.message,
531
+ type: 'error',
532
+ closable: false
533
+ })
534
+ ]
535
+ : [])
536
+ ]);
537
+ }
538
+ function renderNode(node, parent) {
539
+ const status = controller.getNodeStatus(node, parent);
540
+ if (!status.visible)
541
+ return null;
542
+ if (!('children' in node))
543
+ return renderField(node, status);
544
+ return h(node.type === 'section' ? 'section' : 'div', {
545
+ ...('name' in node ? { key: node.name } : {}),
546
+ class: 'little-el-container',
547
+ style: { '--little-el-span': node.span }
548
+ }, [
549
+ ...(node.title ? [h('h2', [render(node.title)])] : []),
550
+ ...(node.description
551
+ ? [
552
+ h('p', { class: 'little-el-description' }, [
553
+ render(node.description)
554
+ ])
555
+ ]
556
+ : []),
557
+ h('div', { class: 'little-el-grid' }, node.children.map((child) => renderNode(child, status)))
558
+ ]);
559
+ }
560
+ return () => {
561
+ const snapshot = state.value;
562
+ const confirm = confirmation.value;
563
+ const { size, locale, labelPosition, labelWidth, showRequiredMark } = ui.value;
564
+ const nativeSize = size === 'medium' ? 'default' : size;
565
+ const formTree = h('div', { class: 'little-el-form' }, [
566
+ h(ElForm, {
567
+ model: snapshot.model,
568
+ labelPosition: labelPosition ?? 'top',
569
+ ...(labelWidth === undefined ? {} : { labelWidth }),
570
+ ...(showRequiredMark === undefined
571
+ ? {}
572
+ : { hideRequiredAsterisk: !showRequiredMark }),
573
+ onSubmit: (event) => event.preventDefault()
574
+ }, {
575
+ default: () => [
576
+ h('div', { class: 'little-el-grid' }, controller.schema.formLayout.map((node) => renderNode(node))),
577
+ ...(snapshot.submitError
578
+ ? [
579
+ h(ElAlert, {
580
+ title: snapshot.submitError.message,
581
+ type: 'error',
582
+ closable: false
583
+ })
584
+ ]
585
+ : []),
586
+ !props.showActions
587
+ ? null
588
+ : h('div', { class: 'little-el-actions' }, controller.schema.actions.map((action) => {
589
+ const status = controller.getActionStatus(action.key);
590
+ if (!status.visible)
591
+ return null;
592
+ const buttonAttrs = {
593
+ ...ui.value.actionDefaults?.button,
594
+ ...action.attrs
595
+ };
596
+ const { size: buttonSize, ...nativeButtonAttrs } = buttonAttrs;
597
+ return h(ElButton, {
598
+ ...nativeButtonAttrs,
599
+ ...(buttonSize === 'medium'
600
+ ? { size: 'default' }
601
+ : buttonSize === 'small' ||
602
+ buttonSize === 'large' ||
603
+ buttonSize === 'default'
604
+ ? { size: buttonSize }
605
+ : {}),
606
+ key: action.key,
607
+ nativeType: 'button',
608
+ type: action.type === 'submit' ? 'primary' : 'default',
609
+ disabled: status.disabled,
610
+ loading: status.loading,
611
+ onClick: () => {
612
+ void execute(action.key);
613
+ }
614
+ }, { default: () => render(action.label) });
615
+ }))
616
+ ]
617
+ }),
618
+ h(ElDialog, {
619
+ modelValue: Boolean(confirm),
620
+ ...(ui.value.actionDefaults?.confirm?.closeOnEscape === undefined
621
+ ? {}
622
+ : {
623
+ closeOnPressEscape: ui.value.actionDefaults.confirm.closeOnEscape
624
+ }),
625
+ ...(ui.value.actionDefaults?.confirm?.closeOnBackdrop === undefined
626
+ ? {}
627
+ : {
628
+ closeOnClickModal: ui.value.actionDefaults.confirm.closeOnBackdrop
629
+ }),
630
+ appendToBody: true,
631
+ width: 'min(440px, 92vw)',
632
+ title: confirm?.schema.title?.type === 'text'
633
+ ? confirm.schema.title.text
634
+ : locale === 'en-US'
635
+ ? 'Confirm action'
636
+ : '确认操作',
637
+ 'onUpdate:modelValue': (open) => {
638
+ if (!open)
639
+ confirmation.value = undefined;
640
+ }
641
+ }, {
642
+ ...(confirm?.schema.title?.type === 'render'
643
+ ? { header: () => render(confirm.schema.title) }
644
+ : {}),
645
+ default: () => render(confirm?.schema.content),
646
+ footer: () => [
647
+ h(ElButton, {
648
+ onClick: () => {
649
+ confirmation.value = undefined;
650
+ }
651
+ }, { default: () => (locale === 'en-US' ? 'Cancel' : '取消') }),
652
+ h(ElButton, {
653
+ type: 'primary',
654
+ onClick: () => {
655
+ confirmation.value = undefined;
656
+ if (confirm)
657
+ void execute(confirm.key, true);
658
+ }
659
+ }, { default: () => (locale === 'en-US' ? 'Confirm' : '确认') })
660
+ ]
661
+ })
662
+ ]);
663
+ return locale || nativeSize
664
+ ? h(ConfigProvider, {
665
+ ...(locale === undefined
666
+ ? {}
667
+ : { locale: locale === 'zh-CN' ? zhCn : en }),
668
+ ...(nativeSize === undefined ? {} : { size: nativeSize })
669
+ }, { default: () => formTree })
670
+ : formTree;
671
+ };
672
+ }
673
+ });
674
+ /** Element Plus 的原生关闭入口统一交给控制器和关闭拦截器。 */
675
+ export const LittleDialog = defineComponent({
676
+ name: 'LittleElementPlusDialog',
677
+ props: {
678
+ controller: { type: Object, required: true },
679
+ form: Object,
680
+ ui: Object
681
+ },
682
+ emits: {
683
+ result: (result) => typeof result.status === 'string',
684
+ error: (...args) => args.length === 1
685
+ },
686
+ setup(props, { slots, emit }) {
687
+ const { state } = useLittleDialog(props.controller);
688
+ const modalClass = `little-dialog-overlay-${useId()}`;
689
+ let nativeCloseReason = 'close';
690
+ const resetNativeCloseReason = () => {
691
+ nativeCloseReason = 'close';
692
+ };
693
+ const onNativeKey = (event) => {
694
+ const root = document.getElementsByClassName(modalClass)[0];
695
+ if (event.key === 'Escape' &&
696
+ !event.isComposing &&
697
+ root &&
698
+ event.target instanceof Node &&
699
+ root.contains(event.target)) {
700
+ nativeCloseReason = 'escape';
701
+ queueMicrotask(resetNativeCloseReason);
702
+ }
703
+ };
704
+ const onNativeClick = (event) => {
705
+ const target = event.target;
706
+ if (target instanceof Element &&
707
+ target.classList.contains('el-overlay-dialog') &&
708
+ document.getElementsByClassName(modalClass)[0]?.contains(target)) {
709
+ nativeCloseReason = 'mask';
710
+ queueMicrotask(resetNativeCloseReason);
711
+ }
712
+ };
713
+ onMounted(() => {
714
+ if (typeof document === 'undefined')
715
+ return;
716
+ document.addEventListener('keydown', onNativeKey, true);
717
+ document.addEventListener('click', onNativeClick, true);
718
+ });
719
+ onScopeDispose(() => {
720
+ if (typeof document === 'undefined')
721
+ return;
722
+ document.removeEventListener('keydown', onNativeKey, true);
723
+ document.removeEventListener('click', onNativeClick, true);
724
+ });
725
+ const close = (reason) => {
726
+ void props.controller
727
+ .requestClose(reason)
728
+ .then((result) => emit('result', result))
729
+ .catch((cause) => emit('error', cause));
730
+ };
731
+ const confirm = () => {
732
+ void props.controller
733
+ .confirm()
734
+ .then((result) => emit('result', result))
735
+ .catch((cause) => emit('error', cause));
736
+ };
737
+ return () => {
738
+ const schema = props.controller.schema;
739
+ const snapshot = state.value;
740
+ return h(ElDialog, {
741
+ modelValue: snapshot.open,
742
+ title: schema.title,
743
+ showClose: schema.showClose,
744
+ width: `min(${schema.width}px, 92vw)`,
745
+ appendToBody: true,
746
+ modalClass,
747
+ destroyOnClose: false,
748
+ closeOnClickModal: schema.closeOnMask,
749
+ closeOnPressEscape: schema.closeOnEscape,
750
+ beforeClose: () => {
751
+ const reason = nativeCloseReason;
752
+ resetNativeCloseReason();
753
+ close(reason);
754
+ }
755
+ }, {
756
+ default: () => [
757
+ ...(snapshot.error
758
+ ? [
759
+ h(ElAlert, {
760
+ type: 'error',
761
+ title: snapshot.error,
762
+ closable: false
763
+ })
764
+ ]
765
+ : []),
766
+ ...(props.form
767
+ ? [
768
+ h(LittleForm, {
769
+ controller: props.form,
770
+ showActions: false,
771
+ ...(props.ui ? { ui: props.ui } : {}),
772
+ onError: (cause) => emit('error', cause)
773
+ }, slots)
774
+ ]
775
+ : [slots.default?.()])
776
+ ],
777
+ footer: () => slots.footer?.({ state: snapshot, confirm, close }) ??
778
+ h('div', { class: 'little-dialog-actions' }, [
779
+ schema.showCancel &&
780
+ h(ElButton, {
781
+ disabled: snapshot.phase === 'closing',
782
+ onClick: () => close('cancel')
783
+ }, { default: () => schema.cancelLabel }),
784
+ schema.showConfirm &&
785
+ h(ElButton, {
786
+ type: 'primary',
787
+ loading: snapshot.phase === 'confirming',
788
+ disabled: snapshot.phase !== 'open',
789
+ onClick: confirm
790
+ }, { default: () => schema.confirmLabel })
791
+ ])
792
+ });
793
+ };
794
+ }
795
+ });
796
+ function tableCell(value) {
797
+ if (value === undefined || value === null)
798
+ return '—';
799
+ if (typeof value !== 'object')
800
+ return String(value);
801
+ try {
802
+ return JSON.stringify(value) ?? '—';
803
+ }
804
+ catch {
805
+ return '[无法显示]';
806
+ }
807
+ }
808
+ /** 远程只读表格;控制器生命周期由调用方管理。 */
809
+ export const LittleTable = defineComponent({
810
+ name: 'LittleElementPlusTable',
811
+ props: {
812
+ controller: { type: Object, required: true },
813
+ autoLoad: { type: Boolean, default: true }
814
+ },
815
+ emits: {
816
+ error: (...args) => args.length === 1,
817
+ actionResult: (result) => typeof result === 'string'
818
+ },
819
+ setup(props, { emit, slots }) {
820
+ const { state } = useLittleTable(props.controller);
821
+ const controller = props.controller;
822
+ const report = (cause) => emit('error', cause);
823
+ const run = (work) => {
824
+ try {
825
+ void work().catch(report);
826
+ }
827
+ catch (cause) {
828
+ report(cause);
829
+ }
830
+ };
831
+ const sort = (key, direction) => {
832
+ const previous = controller.getState().sort;
833
+ if ((key === null && previous === null) ||
834
+ (key !== null &&
835
+ previous?.key === key &&
836
+ previous.direction === direction))
837
+ return;
838
+ run(() => controller.setSort(key, direction));
839
+ };
840
+ onMounted(() => {
841
+ if (props.autoLoad &&
842
+ !controller.getState().loaded &&
843
+ !controller.getState().loading &&
844
+ !controller.getState().error)
845
+ run(() => controller.refresh());
846
+ });
847
+ return () => {
848
+ const snapshot = state.value;
849
+ const pageCount = Math.max(1, Math.ceil(snapshot.total / snapshot.pageSize));
850
+ const rowKey = (row) => getByPath(row, controller.schema.rowKey);
851
+ const selectionInput = (row) => {
852
+ const key = rowKey(row);
853
+ return h('input', {
854
+ type: 'checkbox',
855
+ 'aria-label': `选择行 ${key}`,
856
+ checked: snapshot.selectedKeys.includes(key),
857
+ disabled: snapshot.loading || !!snapshot.error,
858
+ onChange: (event) => controller.setSelectedKeys(event.target.checked
859
+ ? [...snapshot.selectedKeys, key]
860
+ : snapshot.selectedKeys.filter((item) => item !== key))
861
+ });
862
+ };
863
+ const actionCell = (row) => h('div', [
864
+ ...controller.schema.actions.map((action) => h('button', {
865
+ type: 'button',
866
+ disabled: !!snapshot.pendingAction ||
867
+ !controller.isActionAllowed(action.key, rowKey(row)),
868
+ onClick: () => {
869
+ void controller
870
+ .requestAction(action.key, rowKey(row))
871
+ .then((result) => emit('actionResult', result))
872
+ .catch(report);
873
+ }
874
+ }, action.label)),
875
+ ...(slots.actions?.({ row, controller }) ?? [])
876
+ ]);
877
+ const selectAll = () => h('input', {
878
+ type: 'checkbox',
879
+ 'aria-label': '选择当前页全部',
880
+ checked: snapshot.rows.length > 0 &&
881
+ snapshot.rows.every((row) => snapshot.selectedKeys.includes(rowKey(row))),
882
+ indeterminate: snapshot.rows.some((row) => snapshot.selectedKeys.includes(rowKey(row))) &&
883
+ !snapshot.rows.every((row) => snapshot.selectedKeys.includes(rowKey(row))),
884
+ disabled: snapshot.loading || !!snapshot.error || !snapshot.rows.length,
885
+ onChange: (event) => {
886
+ const pageKeys = new Set(snapshot.rows.map(rowKey));
887
+ const otherKeys = snapshot.selectedKeys.filter((key) => !pageKeys.has(key));
888
+ controller.setSelectedKeys(event.target.checked
889
+ ? [...otherKeys, ...pageKeys]
890
+ : otherKeys);
891
+ }
892
+ });
893
+ const message = snapshot.error
894
+ ? `${snapshot.error}${snapshot.loaded ? '(显示上次成功结果)' : ''}`
895
+ : '';
896
+ return h('div', { class: 'little-table' }, [
897
+ ...(snapshot.actionError
898
+ ? [h('div', { role: 'alert' }, snapshot.actionError)]
899
+ : []),
900
+ ...(snapshot.actionBusy
901
+ ? [h('div', { role: 'status' }, '正在执行操作…')]
902
+ : []),
903
+ ...(snapshot.pendingAction
904
+ ? [
905
+ h('div', { role: 'group', 'aria-label': '确认操作' }, [
906
+ h('span', snapshot.pendingAction.message),
907
+ h('button', {
908
+ type: 'button',
909
+ onClick: () => {
910
+ void controller
911
+ .confirmAction()
912
+ .then((result) => emit('actionResult', result))
913
+ .catch(report);
914
+ }
915
+ }, '确认'),
916
+ h('button', { type: 'button', onClick: () => controller.cancelAction() }, '取消')
917
+ ])
918
+ ]
919
+ : []),
920
+ ...(message
921
+ ? [
922
+ h(ElAlert, { type: 'error', title: message, closable: false }),
923
+ h('button', {
924
+ type: 'button',
925
+ onClick: () => run(() => controller.refresh())
926
+ }, '重试')
927
+ ]
928
+ : []),
929
+ ...(snapshot.loading
930
+ ? [h('div', { role: 'status' }, '正在加载…')]
931
+ : []),
932
+ h(ElTable, {
933
+ data: snapshot.rows,
934
+ rowKey: controller.schema.rowKey,
935
+ defaultSort: snapshot.sort
936
+ ? {
937
+ prop: snapshot.sort.key,
938
+ order: snapshot.sort.direction === 'asc'
939
+ ? 'ascending'
940
+ : 'descending'
941
+ }
942
+ : undefined,
943
+ onSortChange: (event) => {
944
+ const direction = event.order === 'ascending'
945
+ ? 'asc'
946
+ : event.order === 'descending'
947
+ ? 'desc'
948
+ : undefined;
949
+ sort(direction && typeof event.prop === 'string' ? event.prop : null, direction);
950
+ }
951
+ }, {
952
+ default: () => [
953
+ ...(controller.schema.selection
954
+ ? [
955
+ h(ElTableColumn, { key: '__little_selection', width: 48 }, {
956
+ header: selectAll,
957
+ default: ({ row }) => selectionInput(row)
958
+ })
959
+ ]
960
+ : []),
961
+ ...controller.schema.columns
962
+ .filter((column) => column.visible)
963
+ .map((column) => h(ElTableColumn, {
964
+ key: column.key,
965
+ prop: column.key,
966
+ label: column.title,
967
+ align: column.align,
968
+ ...(column.width ? { width: column.width } : {}),
969
+ ...(column.sortable ? { sortable: 'custom' } : {})
970
+ }, {
971
+ default: ({ row }) => tableCell(getByPath(row, column.field))
972
+ })),
973
+ ...(slots.actions || controller.schema.actions.length
974
+ ? [
975
+ h(ElTableColumn, { key: '__little_actions', label: '操作' }, {
976
+ default: ({ row }) => actionCell(row)
977
+ })
978
+ ]
979
+ : [])
980
+ ]
981
+ }),
982
+ h('div', { class: 'little-table-pagination' }, [
983
+ h('span', `共 ${snapshot.total} 条 · 第 ${snapshot.page} / ${pageCount} 页`),
984
+ h('label', [
985
+ '每页 ',
986
+ h('select', {
987
+ value: snapshot.pageSize,
988
+ 'aria-label': '每页数量',
989
+ onChange: (event) => run(() => controller.setPageSize(Number(event.target.value)))
990
+ }, [...new Set([10, 20, 50, snapshot.pageSize])]
991
+ .sort((a, b) => a - b)
992
+ .map((size) => h('option', { value: size }, String(size))))
993
+ ]),
994
+ h(ElButton, {
995
+ size: 'small',
996
+ disabled: snapshot.loading || snapshot.page <= 1,
997
+ onClick: () => run(() => controller.setPage(snapshot.page - 1))
998
+ }, { default: () => '上一页' }),
999
+ h(ElButton, {
1000
+ size: 'small',
1001
+ disabled: snapshot.loading || snapshot.page >= pageCount,
1002
+ onClick: () => run(() => controller.setPage(snapshot.page + 1))
1003
+ }, { default: () => '下一页' })
1004
+ ])
1005
+ ]);
1006
+ };
1007
+ }
1008
+ });
1009
+ //# sourceMappingURL=index.js.map