@littlekit/ui-naive-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,874 @@
1
+ // 把标准布局和字段状态映射为 Naive UI 组件,事件通过 Vue 适配器返回 Core。
2
+ import { defineComponent, h, onMounted, ref } from 'vue';
3
+ import { NAlert, NButton, NCascader, NTreeSelect, NCheckbox, NCheckboxGroup, NConfigProvider, NDatePicker, NDataTable, enUS, zhCN, NForm, NFormItem, NInput, NInputNumber, NModal, NRadio, NRadioGroup, NSelect, NSwitch } from 'naive-ui';
4
+ import { getByPath, isUploadFileRef, isDateOutsideLimits, isTimePartDisabled, dateShortcutValue, dateShortcutLabels, validateDateValue } from '@littlekit/ui-core';
5
+ import { littleUiFieldDefaults, useLittleForm, useLittleDialog, useLittleTable, useLittleUiConfig } from '@littlekit/ui-vue3-adapter';
6
+ function scalar(value) {
7
+ return typeof value === 'string' || typeof value === 'number';
8
+ }
9
+ function selectOptions(options) {
10
+ return options.flatMap((option) => {
11
+ const children = selectOptions(option.children);
12
+ const label = String(option.label ?? '');
13
+ return [
14
+ ...(scalar(option.value) && children.length === 0
15
+ ? [{ value: option.value, label, disabled: option.disabled }]
16
+ : []),
17
+ ...children.map((entry) => option.disabled ? { ...entry, disabled: true } : entry)
18
+ ];
19
+ });
20
+ }
21
+ function selectedValue(value, multiple) {
22
+ return multiple
23
+ ? Array.isArray(value)
24
+ ? value.filter(scalar)
25
+ : []
26
+ : scalar(value)
27
+ ? value
28
+ : null;
29
+ }
30
+ function treeOptions(options, parentDisabled = false, disableBranches = false, lazy = false) {
31
+ return options.flatMap((option) => {
32
+ const disabled = parentDisabled || option.disabled;
33
+ const children = treeOptions(option.children, disabled, disableBranches, lazy);
34
+ const raw = option.extra && typeof option.extra === 'object'
35
+ ? option.extra
36
+ : {};
37
+ const branch = children.length > 0 ||
38
+ (lazy && raw.isLeaf === false && !Array.isArray(raw.children));
39
+ if (!scalar(option.value))
40
+ return [];
41
+ return [
42
+ {
43
+ value: option.value,
44
+ key: option.value,
45
+ label: String(option.label ?? ''),
46
+ disabled: disabled || (disableBranches && branch),
47
+ isLeaf: !branch,
48
+ leaf: !branch,
49
+ ...(children.length ? { children } : {})
50
+ }
51
+ ];
52
+ });
53
+ }
54
+ export const LittleForm = defineComponent({
55
+ name: 'LittleForm',
56
+ props: {
57
+ ui: Object,
58
+ controller: { type: Object, required: true },
59
+ showActions: { type: Boolean, default: true },
60
+ contentRenderers: {
61
+ type: Object,
62
+ default: () => ({})
63
+ }
64
+ },
65
+ emits: {
66
+ result: (_key, _result) => {
67
+ void _key;
68
+ void _result;
69
+ return true;
70
+ },
71
+ error: (_cause) => {
72
+ void _cause;
73
+ return true;
74
+ }
75
+ },
76
+ setup(props, { slots, emit }) {
77
+ const form = useLittleForm(props.controller);
78
+ const ui = useLittleUiConfig(() => props.ui);
79
+ const { controller, state } = form;
80
+ const pendingConfirm = ref();
81
+ const report = (cause) => emit('error', cause);
82
+ const render = (content) => form.renderContent(content, props.contentRenderers);
83
+ onMounted(() => {
84
+ void controller.initializeOptions().catch(report);
85
+ });
86
+ async function execute(key, confirmed = false) {
87
+ try {
88
+ const confirm = controller.getActionConfirm(key);
89
+ if (confirm && !confirmed) {
90
+ pendingConfirm.value = { key, schema: confirm };
91
+ return;
92
+ }
93
+ emit('result', key, await controller.executeAction(key));
94
+ }
95
+ catch (cause) {
96
+ report(cause);
97
+ }
98
+ }
99
+ function renderField(item, status) {
100
+ const { field, type, modelFields } = item;
101
+ const binding = form.field(field, modelFields.value);
102
+ const value = binding.value.value;
103
+ const disabled = status.disabled || status.readonly;
104
+ const label = render(item.label) ?? field;
105
+ const textLabel = item.label?.type === 'text' ? item.label.text : field;
106
+ const monthStates = [...state.value.calendarMonths.values()].filter((entry) => entry.field === field);
107
+ const optionState = state.value.optionStates.get(field);
108
+ const options = item.optionSource
109
+ ? selectOptions(controller.getOptions(field))
110
+ : [];
111
+ const error = modelFields.value
112
+ ? controller.getVisibleErrors(modelFields.value)[0]?.message
113
+ : undefined;
114
+ const required = modelFields.value !== undefined &&
115
+ controller.schema.rules[modelFields.value]?.some((rule) => rule.type === 'required' && rule.when === undefined);
116
+ const onUpdate = (next) => {
117
+ void binding.set(next).catch(report);
118
+ };
119
+ const onBlur = () => {
120
+ void binding.blur().catch(report);
121
+ };
122
+ const fieldDefaults = littleUiFieldDefaults(ui.value, type);
123
+ const attrs = { ...fieldDefaults, ...item.attrs };
124
+ const { controls, ...nativeAttrs } = attrs;
125
+ const common = {
126
+ ...nativeAttrs,
127
+ disabled,
128
+ onBlur,
129
+ 'data-field': field,
130
+ 'aria-label': textLabel
131
+ };
132
+ const multiple = item.selectionMode === 'multiple';
133
+ const isRemote = item.optionSource?.type === 'remote';
134
+ let input;
135
+ switch (type) {
136
+ case 'slot':
137
+ input =
138
+ slots[field]?.({
139
+ value,
140
+ model: form.model.value,
141
+ setValue: onUpdate,
142
+ disabled
143
+ }) ?? h('div', { class: 'little-slot' }, [render(item.description)]);
144
+ break;
145
+ case 'date':
146
+ case 'datetime':
147
+ case 'daterange':
148
+ case 'datetimerange': {
149
+ const range = type === 'daterange' || type === 'datetimerange';
150
+ const formatted = range
151
+ ? Array.isArray(value) &&
152
+ value.length === 2 &&
153
+ value.every((v) => typeof v === 'string')
154
+ ? [value[0], value[1]]
155
+ : null
156
+ : typeof value === 'string'
157
+ ? value
158
+ : null;
159
+ input = h(NDatePicker, {
160
+ ...common,
161
+ type,
162
+ valueFormat: type === 'datetime' || type === 'datetimerange'
163
+ ? 'yyyy-MM-dd HH:mm:ss'
164
+ : 'yyyy-MM-dd',
165
+ ...(item.dateLimit
166
+ ? {
167
+ isDateDisabled: (timestamp) => isDateOutsideLimits(new Date(timestamp), type === 'datetime' || type === 'datetimerange'
168
+ ? 'datetime'
169
+ : 'date', item.dateLimit, (path) => getByPath(form.model.value, path)) ||
170
+ controller.calendarDateDisabled(field, new Date(timestamp))
171
+ }
172
+ : {}),
173
+ ...(item.dateLimit &&
174
+ (type === 'datetime' || type === 'datetimerange')
175
+ ? {
176
+ isTimeDisabled: () => ({
177
+ isHourDisabled: (hour) => isTimePartDisabled(item.dateLimit, hour),
178
+ isMinuteDisabled: (minute, hour) => hour !== null &&
179
+ isTimePartDisabled(item.dateLimit, hour, minute),
180
+ isSecondDisabled: (second, minute, hour) => hour !== null &&
181
+ minute !== null &&
182
+ isTimePartDisabled(item.dateLimit, hour, minute, second)
183
+ })
184
+ }
185
+ : {}),
186
+ ...(item.dateDefaultTime === undefined
187
+ ? {}
188
+ : {
189
+ defaultTime: typeof item.dateDefaultTime === 'string'
190
+ ? item.dateDefaultTime
191
+ : [...item.dateDefaultTime]
192
+ }),
193
+ formattedValue: formatted,
194
+ 'onUpdate:formattedValue': onUpdate
195
+ });
196
+ break;
197
+ }
198
+ case 'upload': {
199
+ const files = Array.isArray(value)
200
+ ? value.filter(isUploadFileRef)
201
+ : [];
202
+ const tasks = state.value.uploadStates.get(field) ?? [];
203
+ const locked = disabled || state.value.submitting;
204
+ input = h('div', { class: 'little-upload' }, [
205
+ h('input', {
206
+ type: 'file',
207
+ 'aria-label': textLabel,
208
+ accept: item.upload?.accept?.join(','),
209
+ multiple: (item.upload?.maxCount ?? 1) > 1,
210
+ disabled: locked ||
211
+ files.length + tasks.length >= (item.upload?.maxCount ?? 1),
212
+ onBlur: onBlur,
213
+ onChange: (event) => {
214
+ const element = event.target;
215
+ const selected = Array.from(element.files ?? []);
216
+ element.value = '';
217
+ void controller.uploadFiles(field, selected).catch(report);
218
+ }
219
+ }),
220
+ h('ul', { class: 'little-upload-list' }, [
221
+ ...files.map((file) => h('li', { key: `file:${file.id}` }, [
222
+ h('span', file.name),
223
+ h(NButton, {
224
+ size: 'small',
225
+ disabled: locked,
226
+ onClick: () => controller.removeUploadFile(field, file.id)
227
+ }, { default: () => '移除' })
228
+ ])),
229
+ ...tasks.map((task) => h('li', { key: task.id }, [
230
+ h('span', task.name),
231
+ ...(task.status === 'uploading'
232
+ ? [
233
+ h('progress', {
234
+ max: 100,
235
+ value: task.progress,
236
+ 'aria-label': `${task.name} 上传进度`
237
+ }),
238
+ h('span', `${Math.round(task.progress)}%`)
239
+ ]
240
+ : [
241
+ h('span', { role: 'alert' }, task.error ?? '上传失败'),
242
+ h(NButton, {
243
+ size: 'small',
244
+ disabled: locked,
245
+ onClick: () => {
246
+ void controller
247
+ .retryUpload(field, task.id)
248
+ .catch(report);
249
+ }
250
+ }, { default: () => '重试' })
251
+ ]),
252
+ h(NButton, {
253
+ size: 'small',
254
+ disabled: locked,
255
+ onClick: () => controller.cancelUpload(field, task.id)
256
+ }, {
257
+ default: () => task.status === 'uploading' ? '取消' : '移除'
258
+ })
259
+ ]))
260
+ ])
261
+ ]);
262
+ break;
263
+ }
264
+ case 'switch':
265
+ input = h(NSwitch, {
266
+ ...common,
267
+ value: typeof value === 'boolean' ? value : false,
268
+ 'onUpdate:value': onUpdate
269
+ });
270
+ break;
271
+ case 'number':
272
+ input = h(NInputNumber, {
273
+ ...common,
274
+ ...(typeof controls === 'boolean' &&
275
+ item.attrs.showButton === undefined
276
+ ? { showButton: controls }
277
+ : {}),
278
+ value: typeof value === 'number' ? value : null,
279
+ 'onUpdate:value': onUpdate
280
+ });
281
+ break;
282
+ case 'tree-select':
283
+ case 'cascader': {
284
+ const nodes = treeOptions(item.optionSource ? controller.getOptions(field) : [], false, false, Boolean(item.treeLazy));
285
+ input = h(type === 'tree-select'
286
+ ? NTreeSelect
287
+ : NCascader, {
288
+ ...common,
289
+ options: nodes,
290
+ value: selectedValue(value, multiple),
291
+ multiple,
292
+ cascade: false,
293
+ ...(type === 'cascader' && item.treeLazy ? { remote: true } : {}),
294
+ leafOnly: true,
295
+ ...(item.treeLazy
296
+ ? {
297
+ onLoad: (node) => controller.loadTreeChildren(field, node.value)
298
+ }
299
+ : {}),
300
+ 'onUpdate:value': onUpdate,
301
+ 'onUpdate:show': (show) => {
302
+ if (show)
303
+ void binding.open().catch(report);
304
+ }
305
+ });
306
+ break;
307
+ }
308
+ case 'select':
309
+ input = h(NSelect, {
310
+ ...common,
311
+ value: selectedValue(value, multiple),
312
+ multiple,
313
+ options,
314
+ filterable: isRemote || attrs.filterable === true,
315
+ remote: isRemote,
316
+ loading: optionState?.loading ?? false,
317
+ 'onUpdate:value': onUpdate,
318
+ 'onUpdate:show': (show) => {
319
+ if (show)
320
+ void binding.open().catch(report);
321
+ },
322
+ onSearch: (query) => {
323
+ if (isRemote)
324
+ void binding.search(query).catch(report);
325
+ }
326
+ });
327
+ break;
328
+ case 'radio':
329
+ input = h(NRadioGroup, {
330
+ ...common,
331
+ value: scalar(value) ? value : null,
332
+ 'onUpdate:value': onUpdate
333
+ }, {
334
+ default: () => options.map((option) => h(NRadio, {
335
+ key: option.value,
336
+ value: option.value,
337
+ disabled: option.disabled
338
+ }, { default: () => option.label }))
339
+ });
340
+ break;
341
+ case 'checkbox':
342
+ input = h(NCheckboxGroup, {
343
+ ...common,
344
+ value: Array.isArray(value)
345
+ ? value.filter(scalar)
346
+ : scalar(value)
347
+ ? [value]
348
+ : [],
349
+ 'onUpdate:value': (next) => onUpdate(multiple ? next : (next.at(-1) ?? null))
350
+ }, {
351
+ default: () => options.map((option) => h(NCheckbox, {
352
+ key: option.value,
353
+ value: option.value,
354
+ label: option.label,
355
+ disabled: option.disabled
356
+ }))
357
+ });
358
+ break;
359
+ default:
360
+ input = h(NInput, {
361
+ ...common,
362
+ disabled: status.disabled,
363
+ readonly: status.readonly,
364
+ type: type === 'textarea' ? 'textarea' : 'text',
365
+ value: typeof value === 'string' ? value : '',
366
+ inputProps: { 'aria-label': textLabel },
367
+ 'onUpdate:value': onUpdate
368
+ });
369
+ }
370
+ return h('div', {
371
+ key: field,
372
+ class: 'little-field',
373
+ style: { '--little-span': item.span }
374
+ }, [
375
+ h(NFormItem, {
376
+ label: textLabel,
377
+ required: Boolean(required),
378
+ showFeedback: Boolean(error),
379
+ feedback: error ?? '',
380
+ ...(error ? { validationStatus: 'error' } : {})
381
+ }, { label: () => label, default: () => input }),
382
+ ...(monthStates.some((v) => v.status === 'loading')
383
+ ? [h('div', { role: 'status' }, '正在加载可用日期…')]
384
+ : []),
385
+ ...(monthStates.some((v) => v.status === 'error')
386
+ ? [
387
+ h('div', { role: 'alert' }, [
388
+ '可用日期加载失败,未加载的日期不可选。',
389
+ h(NButton, {
390
+ size: 'small',
391
+ onClick: () => controller.retryCalendarMonths(field)
392
+ }, { default: () => '重试' })
393
+ ])
394
+ ]
395
+ : []),
396
+ ...((type === 'tree-select' || type === 'cascader') &&
397
+ item.optionSource?.type === 'remote'
398
+ ? [
399
+ h('label', { class: 'little-tree-search' }, [
400
+ h('span', '搜索'),
401
+ h('input', {
402
+ type: 'search',
403
+ 'aria-label': `搜索${textLabel}`,
404
+ disabled,
405
+ placeholder: '输入关键字搜索',
406
+ onInput: (event) => {
407
+ void binding
408
+ .search(event.target.value)
409
+ .catch(report);
410
+ }
411
+ }),
412
+ ...(optionState?.loading
413
+ ? [h('span', { role: 'status' }, '正在搜索…')]
414
+ : [])
415
+ ])
416
+ ]
417
+ : []),
418
+ ...(item.dateShortcuts?.length
419
+ ? [
420
+ h('div', { class: 'little-date-shortcuts' }, item.dateShortcuts.map((shortcut) => {
421
+ const current = () => dateShortcutValue(shortcut, type === 'datetimerange' ? 'datetime' : 'date');
422
+ const allowed = () => validateDateValue(current(), type === 'datetimerange' ? 'datetime' : 'date', true, item.dateLimit ?? {}, (path) => getByPath(form.model.value, path)) &&
423
+ current().every((v) => {
424
+ const [year, month, day] = v
425
+ .slice(0, 10)
426
+ .split('-')
427
+ .map(Number);
428
+ return !controller.calendarDateDisabled(field, new Date(year, month - 1, day));
429
+ });
430
+ return h(NButton, {
431
+ key: shortcut,
432
+ size: 'small',
433
+ disabled: disabled || !allowed(),
434
+ onClick: () => {
435
+ if (allowed())
436
+ onUpdate(current());
437
+ }
438
+ }, { default: () => dateShortcutLabels[shortcut] });
439
+ }))
440
+ ]
441
+ : []),
442
+ ...(item.description && type !== 'slot'
443
+ ? [
444
+ h('div', { class: 'little-description' }, [
445
+ render(item.description)
446
+ ])
447
+ ]
448
+ : []),
449
+ ...(optionState?.error
450
+ ? [
451
+ h(NAlert, { type: 'error' }, { default: () => optionState.error?.message })
452
+ ]
453
+ : [])
454
+ ]);
455
+ }
456
+ function renderNode(node, parent) {
457
+ const status = controller.getNodeStatus(node, parent);
458
+ if (!status.visible)
459
+ return null;
460
+ if (!('children' in node))
461
+ return renderField(node, status);
462
+ return h(node.type === 'section' ? 'section' : 'div', {
463
+ ...('name' in node ? { key: node.name } : {}),
464
+ class: ['little-container', `little-${node.type}`],
465
+ style: { '--little-span': node.span }
466
+ }, [
467
+ ...(node.title ? [h('h2', [render(node.title)])] : []),
468
+ ...(node.description
469
+ ? [
470
+ h('p', { class: 'little-description' }, [
471
+ render(node.description)
472
+ ])
473
+ ]
474
+ : []),
475
+ h('div', { class: 'little-grid' }, node.children.map((child) => renderNode(child, status)))
476
+ ]);
477
+ }
478
+ return () => {
479
+ const snapshot = state.value;
480
+ const confirm = pendingConfirm.value;
481
+ const { size, locale, labelPosition, labelWidth, showRequiredMark } = ui.value;
482
+ const formTree = h('div', { class: 'little-form-shell' }, [
483
+ h(NForm, {
484
+ ...(size === undefined ? {} : { size }),
485
+ ...(labelPosition === undefined
486
+ ? {}
487
+ : labelPosition === 'top'
488
+ ? { labelPlacement: 'top' }
489
+ : {
490
+ labelPlacement: 'left',
491
+ labelAlign: labelPosition
492
+ }),
493
+ ...(labelWidth === undefined ? {} : { labelWidth }),
494
+ ...(showRequiredMark === undefined
495
+ ? {}
496
+ : { showRequireMark: showRequiredMark }),
497
+ onSubmit: (event) => event.preventDefault()
498
+ }, {
499
+ default: () => [
500
+ h('div', { class: 'little-grid' }, controller.schema.formLayout.map((node) => renderNode(node))),
501
+ ...(snapshot.submitError
502
+ ? [
503
+ h(NAlert, { type: 'error' }, { default: () => snapshot.submitError?.message })
504
+ ]
505
+ : []),
506
+ !props.showActions
507
+ ? null
508
+ : h('div', { class: 'little-actions' }, controller.schema.actions.map((action) => {
509
+ const status = controller.getActionStatus(action.key);
510
+ if (!status.visible)
511
+ return null;
512
+ return h(NButton, {
513
+ ...(size === undefined ? {} : { size }),
514
+ ...ui.value.actionDefaults?.button,
515
+ ...action.attrs,
516
+ key: action.key,
517
+ type: action.type === 'submit' ? 'primary' : 'default',
518
+ disabled: status.disabled,
519
+ loading: status.loading,
520
+ onClick: () => {
521
+ void execute(action.key);
522
+ }
523
+ }, { default: () => render(action.label) });
524
+ }))
525
+ ]
526
+ }),
527
+ h(NModal, {
528
+ show: Boolean(confirm),
529
+ ...(ui.value.actionDefaults?.confirm?.closeOnEscape === undefined
530
+ ? {}
531
+ : { closeOnEsc: ui.value.actionDefaults.confirm.closeOnEscape }),
532
+ ...(ui.value.actionDefaults?.confirm?.closeOnBackdrop === undefined
533
+ ? {}
534
+ : {
535
+ maskClosable: ui.value.actionDefaults.confirm.closeOnBackdrop
536
+ }),
537
+ preset: 'dialog',
538
+ title: confirm?.schema.title?.type === 'text'
539
+ ? confirm.schema.title.text
540
+ : locale === 'en-US'
541
+ ? 'Confirm action'
542
+ : '确认操作',
543
+ positiveText: locale === 'en-US' ? 'Confirm' : '确认',
544
+ negativeText: locale === 'en-US' ? 'Cancel' : '取消',
545
+ ...(size === undefined
546
+ ? {}
547
+ : {
548
+ positiveButtonProps: { size },
549
+ negativeButtonProps: { size }
550
+ }),
551
+ 'onUpdate:show': (show) => {
552
+ if (!show)
553
+ pendingConfirm.value = undefined;
554
+ },
555
+ onPositiveClick: () => {
556
+ pendingConfirm.value = undefined;
557
+ if (confirm)
558
+ void execute(confirm.key, true);
559
+ }
560
+ }, { default: () => render(confirm?.schema.content) })
561
+ ]);
562
+ return locale
563
+ ? h(NConfigProvider, { locale: locale === 'zh-CN' ? zhCN : enUS }, { default: () => formTree })
564
+ : formTree;
565
+ };
566
+ }
567
+ });
568
+ /** 控制器由调用方持有;表单可通过 form 属性或默认插槽提供。 */
569
+ export const LittleDialog = defineComponent({
570
+ name: 'LittleNaiveDialog',
571
+ props: {
572
+ controller: { type: Object, required: true },
573
+ form: Object,
574
+ ui: Object
575
+ },
576
+ emits: {
577
+ result: (result) => typeof result.status === 'string',
578
+ error: (...args) => args.length === 1
579
+ },
580
+ setup(props, { slots, emit }) {
581
+ const { state } = useLittleDialog(props.controller);
582
+ const close = (reason) => {
583
+ void props.controller
584
+ .requestClose(reason)
585
+ .then((result) => emit('result', result))
586
+ .catch((cause) => emit('error', cause));
587
+ };
588
+ const confirm = () => {
589
+ void props.controller
590
+ .confirm()
591
+ .then((result) => emit('result', result))
592
+ .catch((cause) => emit('error', cause));
593
+ };
594
+ return () => {
595
+ const schema = props.controller.schema;
596
+ const snapshot = state.value;
597
+ return h(NModal, {
598
+ show: snapshot.open,
599
+ preset: 'card',
600
+ title: schema.title,
601
+ closable: schema.showClose,
602
+ style: {
603
+ width: `min(${schema.width}px, 92vw)`,
604
+ maxHeight: '90vh',
605
+ overflow: 'auto'
606
+ },
607
+ displayDirective: 'show',
608
+ maskClosable: false,
609
+ closeOnEsc: schema.closeOnEscape,
610
+ onMaskClick: (event) => {
611
+ if (event.target instanceof Element &&
612
+ event.target.closest('.n-modal-container'))
613
+ close('mask');
614
+ },
615
+ 'onUpdate:show': (open) => {
616
+ if (!open)
617
+ close('escape');
618
+ },
619
+ onClose: () => {
620
+ close('close');
621
+ return false;
622
+ }
623
+ }, {
624
+ default: () => [
625
+ ...(snapshot.error
626
+ ? [
627
+ h(NAlert, { type: 'error' }, { default: () => snapshot.error })
628
+ ]
629
+ : []),
630
+ ...(props.form
631
+ ? [
632
+ h(LittleForm, {
633
+ controller: props.form,
634
+ showActions: false,
635
+ ...(props.ui ? { ui: props.ui } : {}),
636
+ onError: (cause) => emit('error', cause)
637
+ }, slots)
638
+ ]
639
+ : [slots.default?.()])
640
+ ],
641
+ footer: () => slots.footer?.({ state: snapshot, confirm, close }) ??
642
+ h('div', { class: 'little-dialog-actions' }, [
643
+ schema.showCancel &&
644
+ h(NButton, {
645
+ disabled: snapshot.phase === 'closing',
646
+ onClick: () => close('cancel')
647
+ }, { default: () => schema.cancelLabel }),
648
+ schema.showConfirm &&
649
+ h(NButton, {
650
+ type: 'primary',
651
+ loading: snapshot.phase === 'confirming',
652
+ disabled: snapshot.phase !== 'open',
653
+ onClick: confirm
654
+ }, { default: () => schema.confirmLabel })
655
+ ])
656
+ });
657
+ };
658
+ }
659
+ });
660
+ function tableCell(value) {
661
+ if (value === undefined || value === null)
662
+ return '—';
663
+ if (typeof value !== 'object')
664
+ return String(value);
665
+ try {
666
+ return JSON.stringify(value) ?? '—';
667
+ }
668
+ catch {
669
+ return '[无法显示]';
670
+ }
671
+ }
672
+ /** 远程只读表格;控制器生命周期由调用方管理。 */
673
+ export const LittleTable = defineComponent({
674
+ name: 'LittleNaiveTable',
675
+ props: {
676
+ controller: { type: Object, required: true },
677
+ autoLoad: { type: Boolean, default: true }
678
+ },
679
+ emits: {
680
+ error: (...args) => args.length === 1,
681
+ actionResult: (result) => typeof result === 'string'
682
+ },
683
+ setup(props, { emit, slots }) {
684
+ const { state } = useLittleTable(props.controller);
685
+ const controller = props.controller;
686
+ const report = (cause) => emit('error', cause);
687
+ const run = (work) => {
688
+ try {
689
+ void work().catch(report);
690
+ }
691
+ catch (cause) {
692
+ report(cause);
693
+ }
694
+ };
695
+ const sort = (key, direction) => {
696
+ const previous = controller.getState().sort;
697
+ if ((key === null && previous === null) ||
698
+ (key !== null &&
699
+ previous?.key === key &&
700
+ previous.direction === direction))
701
+ return;
702
+ run(() => controller.setSort(key, direction));
703
+ };
704
+ onMounted(() => {
705
+ if (props.autoLoad &&
706
+ !controller.getState().loaded &&
707
+ !controller.getState().loading &&
708
+ !controller.getState().error)
709
+ run(() => controller.refresh());
710
+ });
711
+ return () => {
712
+ const snapshot = state.value;
713
+ const pageCount = Math.max(1, Math.ceil(snapshot.total / snapshot.pageSize));
714
+ const rowKey = (row) => getByPath(row, controller.schema.rowKey);
715
+ const selectionInput = (row) => {
716
+ const key = rowKey(row);
717
+ return h('input', {
718
+ type: 'checkbox',
719
+ 'aria-label': `选择行 ${key}`,
720
+ checked: snapshot.selectedKeys.includes(key),
721
+ disabled: snapshot.loading || !!snapshot.error,
722
+ onChange: (event) => controller.setSelectedKeys(event.target.checked
723
+ ? [...snapshot.selectedKeys, key]
724
+ : snapshot.selectedKeys.filter((item) => item !== key))
725
+ });
726
+ };
727
+ const actionCell = (row) => h('div', [
728
+ ...controller.schema.actions.map((action) => h('button', {
729
+ type: 'button',
730
+ disabled: !!snapshot.pendingAction ||
731
+ !controller.isActionAllowed(action.key, rowKey(row)),
732
+ onClick: () => {
733
+ void controller
734
+ .requestAction(action.key, rowKey(row))
735
+ .then((result) => emit('actionResult', result))
736
+ .catch(report);
737
+ }
738
+ }, action.label)),
739
+ ...(slots.actions?.({ row, controller }) ?? [])
740
+ ]);
741
+ const selectAll = () => h('input', {
742
+ type: 'checkbox',
743
+ 'aria-label': '选择当前页全部',
744
+ checked: snapshot.rows.length > 0 &&
745
+ snapshot.rows.every((row) => snapshot.selectedKeys.includes(rowKey(row))),
746
+ indeterminate: snapshot.rows.some((row) => snapshot.selectedKeys.includes(rowKey(row))) &&
747
+ !snapshot.rows.every((row) => snapshot.selectedKeys.includes(rowKey(row))),
748
+ disabled: snapshot.loading || !!snapshot.error || !snapshot.rows.length,
749
+ onChange: (event) => {
750
+ const pageKeys = new Set(snapshot.rows.map(rowKey));
751
+ const otherKeys = snapshot.selectedKeys.filter((key) => !pageKeys.has(key));
752
+ controller.setSelectedKeys(event.target.checked
753
+ ? [...otherKeys, ...pageKeys]
754
+ : otherKeys);
755
+ }
756
+ });
757
+ const message = snapshot.error
758
+ ? `${snapshot.error}${snapshot.loaded ? '(显示上次成功结果)' : ''}`
759
+ : '';
760
+ return h('div', { class: 'little-table' }, [
761
+ ...(snapshot.actionError
762
+ ? [h('div', { role: 'alert' }, snapshot.actionError)]
763
+ : []),
764
+ ...(snapshot.actionBusy
765
+ ? [h('div', { role: 'status' }, '正在执行操作…')]
766
+ : []),
767
+ ...(snapshot.pendingAction
768
+ ? [
769
+ h('div', { role: 'group', 'aria-label': '确认操作' }, [
770
+ h('span', snapshot.pendingAction.message),
771
+ h('button', {
772
+ type: 'button',
773
+ onClick: () => {
774
+ void controller
775
+ .confirmAction()
776
+ .then((result) => emit('actionResult', result))
777
+ .catch(report);
778
+ }
779
+ }, '确认'),
780
+ h('button', { type: 'button', onClick: () => controller.cancelAction() }, '取消')
781
+ ])
782
+ ]
783
+ : []),
784
+ ...(message
785
+ ? [
786
+ h(NAlert, { type: 'error' }, { default: () => message }),
787
+ h('button', {
788
+ type: 'button',
789
+ onClick: () => run(() => controller.refresh())
790
+ }, '重试')
791
+ ]
792
+ : []),
793
+ ...(snapshot.loading
794
+ ? [h('div', { role: 'status' }, '正在加载…')]
795
+ : []),
796
+ h(NDataTable, {
797
+ columns: [
798
+ ...(controller.schema.selection
799
+ ? [
800
+ {
801
+ key: '__little_selection',
802
+ title: selectAll,
803
+ width: 48,
804
+ render: selectionInput
805
+ }
806
+ ]
807
+ : []),
808
+ ...controller.schema.columns
809
+ .filter((column) => column.visible)
810
+ .map((column) => ({
811
+ key: column.key,
812
+ title: column.title,
813
+ align: column.align,
814
+ ...(column.width ? { width: column.width } : {}),
815
+ ...(column.sortable
816
+ ? {
817
+ sorter: true,
818
+ sortOrder: snapshot.sort?.key === column.key
819
+ ? snapshot.sort.direction === 'asc'
820
+ ? 'ascend'
821
+ : 'descend'
822
+ : false
823
+ }
824
+ : {}),
825
+ render: (row) => tableCell(getByPath(row, column.field))
826
+ })),
827
+ ...(slots.actions || controller.schema.actions.length
828
+ ? [{ key: '__little_actions', title: '操作', render: actionCell }]
829
+ : [])
830
+ ],
831
+ data: snapshot.rows,
832
+ loading: snapshot.loading,
833
+ remote: true,
834
+ pagination: false,
835
+ rowKey: (row) => getByPath(row, controller.schema.rowKey),
836
+ 'onUpdate:sorter': (sorter) => {
837
+ const direction = sorter?.order === 'ascend'
838
+ ? 'asc'
839
+ : sorter?.order === 'descend'
840
+ ? 'desc'
841
+ : undefined;
842
+ sort(direction && typeof sorter?.columnKey === 'string'
843
+ ? sorter.columnKey
844
+ : null, direction);
845
+ }
846
+ }),
847
+ h('div', { class: 'little-table-pagination' }, [
848
+ h('span', `共 ${snapshot.total} 条 · 第 ${snapshot.page} / ${pageCount} 页`),
849
+ h('label', [
850
+ '每页 ',
851
+ h('select', {
852
+ value: snapshot.pageSize,
853
+ 'aria-label': '每页数量',
854
+ onChange: (event) => run(() => controller.setPageSize(Number(event.target.value)))
855
+ }, [...new Set([10, 20, 50, snapshot.pageSize])]
856
+ .sort((a, b) => a - b)
857
+ .map((size) => h('option', { value: size }, String(size))))
858
+ ]),
859
+ h(NButton, {
860
+ size: 'small',
861
+ disabled: snapshot.loading || snapshot.page <= 1,
862
+ onClick: () => run(() => controller.setPage(snapshot.page - 1))
863
+ }, { default: () => '上一页' }),
864
+ h(NButton, {
865
+ size: 'small',
866
+ disabled: snapshot.loading || snapshot.page >= pageCount,
867
+ onClick: () => run(() => controller.setPage(snapshot.page + 1))
868
+ }, { default: () => '下一页' })
869
+ ])
870
+ ]);
871
+ };
872
+ }
873
+ });
874
+ //# sourceMappingURL=index.js.map