@nocobase/client-v2 2.3.0-alpha.1 → 3.0.0-alpha.2

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.
Files changed (123) hide show
  1. package/es/acl/ACLProvider.d.ts +10 -0
  2. package/es/authRedirect.d.ts +5 -0
  3. package/es/components/AttachmentUpload.d.ts +51 -0
  4. package/es/components/form/ScanInput/useCodeScanner.d.ts +2 -2
  5. package/es/components/index.d.ts +1 -0
  6. package/es/flow/actions/linkageRules.d.ts +1 -0
  7. package/es/flow/admin-shell/admin-layout/NocoBaseLogo.d.ts +10 -0
  8. package/es/flow/components/FlowRoute.d.ts +2 -2
  9. package/es/flow/internal/registerDeviceTypeContext.d.ts +10 -0
  10. package/es/flow/models/base/ActionModelCore.d.ts +4 -2
  11. package/es/flow/models/base/BlockGridModel.d.ts +3 -0
  12. package/es/flow/models/blocks/table/TableColumnModel.d.ts +1 -0
  13. package/es/flow/models/fields/DateTimeFieldModel/dateLimit.d.ts +15 -7
  14. package/es/index.d.ts +4 -1
  15. package/es/index.mjs +139 -125
  16. package/es/nocobase-buildin-plugin/currentUserAuthStatus.d.ts +11 -0
  17. package/es/nocobase-buildin-plugin/index.d.ts +9 -0
  18. package/es/settings-app/SettingsApplication.d.ts +18 -0
  19. package/es/settings-app/SettingsBrand.d.ts +16 -0
  20. package/es/settings-app/SettingsBuildInPlugin.d.ts +9 -0
  21. package/es/settings-app/SettingsDocumentRedirect.d.ts +10 -0
  22. package/es/settings-app/SettingsGroupNav.d.ts +17 -0
  23. package/es/settings-app/SettingsPluginSettingsManager.d.ts +14 -0
  24. package/es/settings-app/SettingsRouterManager.d.ts +15 -0
  25. package/es/settings-app/SettingsSearch.d.ts +17 -0
  26. package/es/settings-app/SettingsShell.d.ts +10 -0
  27. package/es/settings-app/isSettingsApp.d.ts +18 -0
  28. package/es/settings-app/runtimePaths.d.ts +18 -0
  29. package/es/settings-app/settingsDocumentPath.d.ts +14 -0
  30. package/es/settings-app/settingsTheme.d.ts +87 -0
  31. package/es/settings-app/useSettingsThemeConfig.d.ts +22 -0
  32. package/es/settings-center/AdminSettingsLayout.d.ts +2 -2
  33. package/es/settings-center/groups.d.ts +66 -0
  34. package/es/settings-center/useSettingsGroups.d.ts +36 -0
  35. package/es/settings-center/useSettingsSearch.d.ts +35 -0
  36. package/es/settings-center/utils.d.ts +24 -0
  37. package/es/theme/index.d.ts +1 -0
  38. package/es/theme/itemActive.d.ts +24 -0
  39. package/es/theme/type.d.ts +9 -0
  40. package/lib/index.js +141 -127
  41. package/lib/locale/languageCodes.js +1 -0
  42. package/package.json +8 -7
  43. package/src/__tests__/authRedirect.test.ts +137 -0
  44. package/src/__tests__/browserChecker.test.ts +124 -6
  45. package/src/__tests__/mockSettingsApplication.ts +29 -0
  46. package/src/__tests__/nocobase-buildin-plugin-auth.test.tsx +51 -10
  47. package/src/__tests__/plugin-manager.test.tsx +7 -6
  48. package/src/__tests__/settings-application.test.ts +164 -0
  49. package/src/__tests__/settings-auth-routes.test.ts +71 -0
  50. package/src/__tests__/settings-center.test.tsx +38 -37
  51. package/src/__tests__/settings-layout-root.test.tsx +260 -0
  52. package/src/__tests__/settings-runtime-paths.test.ts +99 -0
  53. package/src/__tests__/settings-shell.test.tsx +200 -0
  54. package/src/acl/ACLProvider.tsx +21 -0
  55. package/src/authRedirect.ts +72 -3
  56. package/src/components/AttachmentUpload.tsx +275 -0
  57. package/src/components/form/ScanInput/CodeScanner.tsx +61 -34
  58. package/src/components/form/ScanInput/__tests__/CodeScanner.test.tsx +101 -0
  59. package/src/components/form/ScanInput/__tests__/useCodeScanner.test.tsx +114 -18
  60. package/src/components/form/ScanInput/useCodeScanner.ts +166 -23
  61. package/src/components/index.ts +1 -0
  62. package/src/flow/__tests__/FlowRoute.test.tsx +126 -8
  63. package/src/flow/__tests__/PluginFlowEngine.test.ts +58 -0
  64. package/src/flow/actions/__tests__/actionLinkageRules.forkProps.test.ts +314 -0
  65. package/src/flow/actions/__tests__/dataScopeFormValueClear.test.ts +102 -0
  66. package/src/flow/actions/linkageRules.tsx +26 -6
  67. package/src/flow/admin-shell/admin-layout/AdminLayoutComponent.tsx +1 -56
  68. package/src/flow/admin-shell/admin-layout/NocoBaseLogo.tsx +77 -0
  69. package/src/flow/admin-shell/admin-layout/TopbarActionsBar.tsx +37 -14
  70. package/src/flow/admin-shell/admin-layout/__tests__/TopbarActionsBar.test.tsx +77 -13
  71. package/src/flow/common/Markdown/style.ts +4 -0
  72. package/src/flow/components/BlockItemCard.tsx +2 -2
  73. package/src/flow/components/FlowRoute.tsx +71 -29
  74. package/src/flow/index.ts +2 -0
  75. package/src/flow/internal/registerDeviceTypeContext.ts +39 -0
  76. package/src/flow/models/base/ActionModelCore.tsx +11 -2
  77. package/src/flow/models/base/BlockGridModel.tsx +26 -0
  78. package/src/flow/models/base/CollectionBlockModel.tsx +6 -2
  79. package/src/flow/models/base/PageModel/PageTabModel.tsx +67 -17
  80. package/src/flow/models/base/PageModel/__tests__/PageTabModel.test.ts +509 -12
  81. package/src/flow/models/base/__tests__/ActionModelCore.render.test.tsx +49 -0
  82. package/src/flow/models/base/__tests__/BlockGridModel.selectSceneActivation.test.ts +124 -0
  83. package/src/flow/models/base/__tests__/CollectionBlockModel.addAppends.test.ts +41 -0
  84. package/src/flow/models/blocks/filter-form/FilterFormBlockModel.tsx +27 -3
  85. package/src/flow/models/blocks/filter-form/__tests__/defaultValues.wiring.test.ts +32 -4
  86. package/src/flow/models/blocks/js-block/JSBlock.tsx +1 -1
  87. package/src/flow/models/blocks/table/TableBlockModel.tsx +3 -1
  88. package/src/flow/models/blocks/table/TableColumnModel.tsx +30 -1
  89. package/src/flow/models/blocks/table/__tests__/TableBlockModel.quickEditRefresh.test.ts +12 -0
  90. package/src/flow/models/blocks/table/__tests__/TableColumnModel.test.tsx +33 -0
  91. package/src/flow/models/fields/DateTimeFieldModel/__tests__/DateTimeNoTzFieldModel.dateLimit.test.tsx +149 -0
  92. package/src/flow/models/fields/DateTimeFieldModel/dateLimit.ts +149 -113
  93. package/src/flow/models/fields/JsonFieldModel.tsx +31 -8
  94. package/src/flow/models/fields/__tests__/JsonFieldModel.test.ts +82 -0
  95. package/src/flow/models/topbar/TopbarActionModel.tsx +52 -180
  96. package/src/flow/utils/dataScopeFormValueClear.ts +4 -3
  97. package/src/index.ts +10 -1
  98. package/src/locale/languageCodes.ts +1 -0
  99. package/src/nocobase-buildin-plugin/currentUserAuthStatus.ts +58 -0
  100. package/src/nocobase-buildin-plugin/index.tsx +99 -71
  101. package/src/settings-app/SettingsApplication.ts +31 -0
  102. package/src/settings-app/SettingsBrand.tsx +108 -0
  103. package/src/settings-app/SettingsBuildInPlugin.ts +10 -0
  104. package/src/settings-app/SettingsDocumentRedirect.tsx +26 -0
  105. package/src/settings-app/SettingsGroupNav.tsx +124 -0
  106. package/src/settings-app/SettingsPluginSettingsManager.ts +38 -0
  107. package/src/settings-app/SettingsRouterManager.ts +92 -0
  108. package/src/settings-app/SettingsSearch.tsx +238 -0
  109. package/src/settings-app/SettingsShell.tsx +167 -0
  110. package/src/settings-app/isSettingsApp.ts +21 -0
  111. package/src/settings-app/runtimePaths.ts +104 -0
  112. package/src/settings-app/settingsDocumentPath.ts +66 -0
  113. package/src/settings-app/settingsTheme.ts +301 -0
  114. package/src/settings-app/useSettingsThemeConfig.ts +100 -0
  115. package/src/settings-center/AdminSettingsLayout.tsx +122 -141
  116. package/src/settings-center/SystemSettingsPage.tsx +4 -170
  117. package/src/settings-center/groups.ts +108 -0
  118. package/src/settings-center/useSettingsGroups.ts +105 -0
  119. package/src/settings-center/useSettingsSearch.ts +173 -0
  120. package/src/settings-center/utils.tsx +50 -1
  121. package/src/theme/index.tsx +1 -0
  122. package/src/theme/itemActive.ts +31 -0
  123. package/src/theme/type.ts +10 -0
@@ -8,140 +8,176 @@
8
8
  */
9
9
 
10
10
  import { autorun } from '@formily/reactive';
11
- import { Form } from 'antd';
12
- import { useFlowContext } from '@nocobase/flow-engine';
11
+ import { Form, type FormInstance } from 'antd';
12
+ import { resolveRunJSObjectValues, useFlowContext } from '@nocobase/flow-engine';
13
13
  import { dayjs } from '@nocobase/utils/client';
14
+ import type { ConfigType, Dayjs } from 'dayjs';
14
15
  import { first, last } from 'lodash';
15
- import React, { useEffect, useRef, useState } from 'react';
16
+ import { useCallback, useEffect, useRef, useState } from 'react';
16
17
 
17
18
  type DateLimitProps = {
18
- _minDate?: any;
19
- _maxDate?: any;
20
- currentForm?: any;
19
+ _minDate?: unknown;
20
+ _maxDate?: unknown;
21
+ currentForm?: unknown;
21
22
  };
22
23
 
23
- export function useDateLimit(props: DateLimitProps) {
24
- const ctx = useFlowContext();
25
- const isAntdFormInstance = typeof props.currentForm?.getFieldsValue === 'function';
26
- const currentFormValues = Form.useWatch([], isAntdFormInstance ? props.currentForm : undefined);
27
- const [minDate, setMinDate] = useState<dayjs.Dayjs | null>(null);
28
- const [maxDate, setMaxDate] = useState<dayjs.Dayjs | null>(null);
29
- const [disabledDate, setDisabledDate] = useState<any>(null);
30
- const [disabledTime, setDisabledTime] = useState<any>(null);
31
- const disposeRef = useRef<any>(null);
24
+ type DisabledTimeConfig = {
25
+ disabledHours: () => number[];
26
+ disabledMinutes: (selectedHour: number) => number[];
27
+ disabledSeconds: (selectedHour: number, selectedMinute: number) => number[];
28
+ };
32
29
 
33
- useEffect(() => {
34
- if (disposeRef.current) {
35
- disposeRef.current();
36
- }
30
+ type DisabledDate = (current: Dayjs) => boolean;
31
+ type DisabledTime = (current: Dayjs | null) => DisabledTimeConfig;
37
32
 
38
- disposeRef.current = autorun(() => {
39
- void limitDate();
40
- });
33
+ function isAntdFormInstance(value: unknown): value is FormInstance {
34
+ if (!value || typeof value !== 'object') return false;
35
+ return typeof (value as Partial<FormInstance>).getFieldsValue === 'function';
36
+ }
41
37
 
42
- return () => {
43
- disposeRef.current?.();
44
- };
45
- }, [ctx, currentFormValues, props._maxDate, props._minDate]);
38
+ function parseDateLimitValue(value: unknown): Dayjs | null {
39
+ if (!value) return null;
40
+ const parsed = dayjs(value as ConfigType);
41
+ return parsed.isValid() ? parsed : null;
42
+ }
46
43
 
47
- const limitDate = async () => {
48
- const resolvedParams = await ctx.resolveJsonTemplate({
49
- _minDate: props._minDate,
50
- _maxDate: props._maxDate,
51
- });
44
+ export function useDateLimit(props: DateLimitProps) {
45
+ const ctx = useFlowContext();
46
+ const currentForm = isAntdFormInstance(props.currentForm) ? props.currentForm : undefined;
47
+ const currentFormValues = Form.useWatch([], currentForm);
48
+ const [minDate, setMinDate] = useState<Dayjs | null>(null);
49
+ const [maxDate, setMaxDate] = useState<Dayjs | null>(null);
50
+ const [disabledDate, setDisabledDate] = useState<DisabledDate | null>(null);
51
+ const [disabledTime, setDisabledTime] = useState<DisabledTime | null>(null);
52
+ const evaluationIdRef = useRef(0);
53
+
54
+ const limitDate = useCallback(async () => {
55
+ const evaluationId = ++evaluationIdRef.current;
56
+
57
+ try {
58
+ const runJSResolvedParams = await resolveRunJSObjectValues(ctx, {
59
+ _minDate: props._minDate,
60
+ _maxDate: props._maxDate,
61
+ });
62
+ const resolvedParams = (await ctx.resolveJsonTemplate({
63
+ _minDate: runJSResolvedParams._minDate,
64
+ _maxDate: runJSResolvedParams._maxDate,
65
+ })) as { _minDate?: unknown; _maxDate?: unknown };
66
+
67
+ if (evaluationId !== evaluationIdRef.current) return;
68
+
69
+ const nextMinRaw = Array.isArray(resolvedParams?._minDate)
70
+ ? first(resolvedParams._minDate)
71
+ : resolvedParams?._minDate;
72
+ const nextMaxRaw = Array.isArray(resolvedParams?._maxDate)
73
+ ? last(resolvedParams._maxDate)
74
+ : resolvedParams?._maxDate;
75
+ const nextMinDate = parseDateLimitValue(nextMinRaw);
76
+ const nextMaxDate = parseDateLimitValue(nextMaxRaw);
77
+
78
+ setMinDate(nextMinDate);
79
+ setMaxDate(nextMaxDate);
80
+
81
+ const fullTimeArr = Array.from({ length: 60 }, (_, i) => i);
82
+
83
+ const nextDisabledDate: DisabledDate = (current) => {
84
+ if (!dayjs.isDayjs(current)) return false;
85
+
86
+ const min = nextMinDate?.startOf('day') || null;
87
+ const max = nextMaxDate?.endOf('day') || null;
88
+
89
+ if (min && current.startOf('day').isBefore(min)) {
90
+ return true;
91
+ }
92
+ if (max && current.startOf('day').isAfter(max)) {
93
+ return true;
94
+ }
95
+ return false;
96
+ };
52
97
 
53
- const nextMinRaw = Array.isArray(resolvedParams?._minDate)
54
- ? first(resolvedParams._minDate)
55
- : resolvedParams?._minDate;
56
- const nextMaxRaw = Array.isArray(resolvedParams?._maxDate)
57
- ? last(resolvedParams._maxDate)
58
- : resolvedParams?._maxDate;
59
- const nextMinDate = nextMinRaw ? dayjs(nextMinRaw) : null;
60
- const nextMaxDate = nextMaxRaw ? dayjs(nextMaxRaw) : null;
61
-
62
- setMinDate(nextMinDate?.isValid?.() ? nextMinDate : null);
63
- setMaxDate(nextMaxDate?.isValid?.() ? nextMaxDate : null);
64
-
65
- const fullTimeArr = Array.from({ length: 60 }, (_, i) => i);
66
-
67
- const nextDisabledDate = (current: dayjs.Dayjs) => {
68
- if (!dayjs.isDayjs(current)) return false;
69
-
70
- const min = nextMinDate?.isValid?.() ? nextMinDate.startOf('day') : null;
71
- const max = nextMaxDate?.isValid?.() ? nextMaxDate.endOf('day') : null;
72
-
73
- if (min && current.startOf('day').isBefore(min)) {
74
- return true;
75
- }
76
- if (max && current.startOf('day').isAfter(max)) {
77
- return true;
78
- }
79
- return false;
80
- };
98
+ const nextDisabledTime: DisabledTime = (current) => {
99
+ if (!current || (!nextMinDate && !nextMaxDate)) {
100
+ return { disabledHours: () => [], disabledMinutes: () => [], disabledSeconds: () => [] };
101
+ }
81
102
 
82
- const nextDisabledTime = (current: dayjs.Dayjs) => {
83
- if (!current || (!nextMinDate?.isValid?.() && !nextMaxDate?.isValid?.())) {
84
- return { disabledHours: () => [], disabledMinutes: () => [], disabledSeconds: () => [] };
85
- }
103
+ const isCurrentMinDay = !!nextMinDate && current.isSame(nextMinDate, 'day');
104
+ const isCurrentMaxDay = !!nextMaxDate && current.isSame(nextMaxDate, 'day');
86
105
 
87
- const isCurrentMinDay = !!nextMinDate?.isValid?.() && current.isSame(nextMinDate, 'day');
88
- const isCurrentMaxDay = !!nextMaxDate?.isValid?.() && current.isSame(nextMaxDate, 'day');
106
+ const disabledHours = () => {
107
+ const hours = [];
108
+ if (isCurrentMinDay && nextMinDate) {
109
+ for (let hour = 0; hour < nextMinDate.hour(); hour++) {
110
+ hours.push(hour);
111
+ }
112
+ }
113
+ if (isCurrentMaxDay && nextMaxDate) {
114
+ for (let hour = nextMaxDate.hour() + 1; hour < 24; hour++) {
115
+ hours.push(hour);
116
+ }
117
+ }
118
+ return hours;
119
+ };
89
120
 
90
- const disabledHours = () => {
91
- const hours = [];
92
- if (isCurrentMinDay && nextMinDate) {
93
- for (let hour = 0; hour < nextMinDate.hour(); hour++) {
94
- hours.push(hour);
121
+ const disabledMinutes = (selectedHour: number) => {
122
+ if (isCurrentMinDay && nextMinDate && selectedHour === nextMinDate.hour()) {
123
+ return fullTimeArr.filter((minute) => minute < nextMinDate.minute());
95
124
  }
96
- }
97
- if (isCurrentMaxDay && nextMaxDate) {
98
- for (let hour = nextMaxDate.hour() + 1; hour < 24; hour++) {
99
- hours.push(hour);
125
+ if (isCurrentMaxDay && nextMaxDate && selectedHour === nextMaxDate.hour()) {
126
+ return fullTimeArr.filter((minute) => minute > nextMaxDate.minute());
100
127
  }
101
- }
102
- return hours;
128
+ return [];
129
+ };
130
+
131
+ const disabledSeconds = (selectedHour: number, selectedMinute: number) => {
132
+ if (
133
+ isCurrentMinDay &&
134
+ nextMinDate &&
135
+ selectedHour === nextMinDate.hour() &&
136
+ selectedMinute === nextMinDate.minute()
137
+ ) {
138
+ return fullTimeArr.filter((second) => second < nextMinDate.second());
139
+ }
140
+ if (
141
+ isCurrentMaxDay &&
142
+ nextMaxDate &&
143
+ selectedHour === nextMaxDate.hour() &&
144
+ selectedMinute === nextMaxDate.minute()
145
+ ) {
146
+ return fullTimeArr.filter((second) => second > nextMaxDate.second());
147
+ }
148
+ return [];
149
+ };
150
+
151
+ return {
152
+ disabledHours,
153
+ disabledMinutes,
154
+ disabledSeconds,
155
+ };
103
156
  };
104
157
 
105
- const disabledMinutes = (selectedHour: number) => {
106
- if (isCurrentMinDay && nextMinDate && selectedHour === nextMinDate.hour()) {
107
- return fullTimeArr.filter((minute) => minute < nextMinDate.minute());
108
- }
109
- if (isCurrentMaxDay && nextMaxDate && selectedHour === nextMaxDate.hour()) {
110
- return fullTimeArr.filter((minute) => minute > nextMaxDate.minute());
111
- }
112
- return [];
113
- };
158
+ setDisabledDate(() => nextDisabledDate);
159
+ setDisabledTime(() => nextDisabledTime);
160
+ } catch (error) {
161
+ if (evaluationId !== evaluationIdRef.current) return;
114
162
 
115
- const disabledSeconds = (selectedHour: number, selectedMinute: number) => {
116
- if (
117
- isCurrentMinDay &&
118
- nextMinDate &&
119
- selectedHour === nextMinDate.hour() &&
120
- selectedMinute === nextMinDate.minute()
121
- ) {
122
- return fullTimeArr.filter((second) => second < nextMinDate.second());
123
- }
124
- if (
125
- isCurrentMaxDay &&
126
- nextMaxDate &&
127
- selectedHour === nextMaxDate.hour() &&
128
- selectedMinute === nextMaxDate.minute()
129
- ) {
130
- return fullTimeArr.filter((second) => second > nextMaxDate.second());
131
- }
132
- return [];
133
- };
163
+ ctx.logger?.warn?.({ err: error }, 'Failed to resolve date range limit');
164
+ setMinDate(null);
165
+ setMaxDate(null);
166
+ setDisabledDate(null);
167
+ setDisabledTime(null);
168
+ }
169
+ }, [ctx, props._maxDate, props._minDate]);
134
170
 
135
- return {
136
- disabledHours,
137
- disabledMinutes,
138
- disabledSeconds,
139
- };
140
- };
171
+ useEffect(() => {
172
+ const dispose = autorun(() => {
173
+ limitDate();
174
+ });
141
175
 
142
- setDisabledDate(() => nextDisabledDate);
143
- setDisabledTime(() => nextDisabledTime);
144
- };
176
+ return () => {
177
+ evaluationIdRef.current += 1;
178
+ dispose();
179
+ };
180
+ }, [currentFormValues, limitDate]);
145
181
 
146
182
  return {
147
183
  minDate,
@@ -13,6 +13,22 @@ import JSON5 from 'json5';
13
13
  import React, { useState, useEffect, useRef } from 'react';
14
14
  import { FieldModel } from '../base/FieldModel';
15
15
 
16
+ const jsonValidationRuleMarker = '__jsonSyntaxValidation';
17
+
18
+ interface JsonValidationRule {
19
+ [jsonValidationRuleMarker]: true;
20
+ type: 'any';
21
+ validator?: (_rule: unknown, value: unknown) => Promise<void>;
22
+ }
23
+
24
+ function isRuleObject(rule: unknown): rule is Record<string, unknown> {
25
+ return typeof rule === 'object' && rule !== null;
26
+ }
27
+
28
+ function isJsonValidationRule(rule: unknown): rule is JsonValidationRule {
29
+ return isRuleObject(rule) && rule[jsonValidationRuleMarker] === true;
30
+ }
31
+
16
32
  const jsonCss = css`
17
33
  font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
18
34
  font-size: 14px;
@@ -40,7 +56,7 @@ export const JsonInput = observer((props: any) => {
40
56
  }
41
57
 
42
58
  internalChange.current = false;
43
- }, [value]);
59
+ }, [_JSON, space, value]);
44
60
 
45
61
  // 用户输入时
46
62
  const handleChange = (ev) => {
@@ -91,23 +107,30 @@ JsonFieldModel.registerFlow({
91
107
  key: 'jsonInitSetting',
92
108
  steps: {
93
109
  initValidation: {
94
- handler(ctx, params) {
95
- const rules = ctx.model.parent.props.rules || [];
110
+ handler(ctx) {
111
+ const currentRules = Array.isArray(ctx.model.parent.props.rules) ? ctx.model.parent.props.rules : [];
112
+ const rules = currentRules.filter((rule: unknown) => {
113
+ return (!isRuleObject(rule) || Object.keys(rule).length > 0) && !isJsonValidationRule(rule);
114
+ });
96
115
  // 添加 JSON 语法校验规则
97
116
  rules.push({
98
- validator: (_, value) => {
117
+ // validator 函数序列化后会被丢弃;保留 any 类型可避免持久化规则退化为默认字符串校验。
118
+ type: 'any',
119
+ [jsonValidationRuleMarker]: true,
120
+ validator: (_rule: unknown, value: unknown) => {
99
121
  // 允许空
100
122
  if (value === null || value === undefined || value === '') return Promise.resolve();
101
123
  // 如果已经是对象/数组,直接通过
102
124
  if (typeof value === 'object') return Promise.resolve();
103
125
  try {
104
- JSON.parse(value);
126
+ JSON.parse(String(value));
105
127
  return Promise.resolve();
106
- } catch (err) {
107
- return Promise.reject(ctx.t('Invalid JSON format') + ': ' + err.message);
128
+ } catch (error) {
129
+ const message = error instanceof Error ? error.message : String(error);
130
+ return Promise.reject(ctx.t('Invalid JSON format') + ': ' + message);
108
131
  }
109
132
  },
110
- });
133
+ } satisfies JsonValidationRule);
111
134
  ctx.model.parent.setProps({
112
135
  rules,
113
136
  });
@@ -0,0 +1,82 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { FlowEngine, FlowModel } from '@nocobase/flow-engine';
11
+ import { describe, expect, it } from 'vitest';
12
+ import { JsonFieldModel } from '../JsonFieldModel';
13
+
14
+ interface ValidationRule {
15
+ required?: boolean;
16
+ type?: string;
17
+ validator?: (_rule: unknown, value: unknown) => Promise<void>;
18
+ }
19
+
20
+ function createModels(rules: ValidationRule[]) {
21
+ const engine = new FlowEngine();
22
+ engine.registerModels({ JsonFieldModel });
23
+ const parent = engine.createModel<FlowModel<{ subModels: { field: JsonFieldModel } }>>({
24
+ use: FlowModel,
25
+ uid: 'json-form-item',
26
+ props: { rules },
27
+ subModels: {
28
+ field: {
29
+ use: JsonFieldModel,
30
+ uid: 'json-field',
31
+ },
32
+ },
33
+ });
34
+
35
+ return { field: parent.subModels.field, parent };
36
+ }
37
+
38
+ function initializeJsonValidation(field: JsonFieldModel) {
39
+ const step = field.getFlow('jsonInitSetting')?.steps.initValidation;
40
+ if (!step) {
41
+ throw new Error('JSON validation step is not registered');
42
+ }
43
+ step.handler(field.context, {});
44
+ }
45
+
46
+ describe('JsonFieldModel validation', () => {
47
+ it('replaces legacy empty rules with one serializable JSON validation rule', async () => {
48
+ const { field, parent } = createModels([{}, { required: true }]);
49
+
50
+ initializeJsonValidation(field);
51
+
52
+ const rules = parent.props.rules as ValidationRule[];
53
+ expect(rules).toHaveLength(2);
54
+ expect(rules[0]).toEqual({ required: true });
55
+ expect(rules[1]).toMatchObject({ type: 'any' });
56
+ expect(rules[1].validator).toBeTypeOf('function');
57
+ if (!rules[1].validator) {
58
+ throw new Error('JSON validator is missing');
59
+ }
60
+ await expect(rules[1].validator({}, { name: 'NocoBase' })).resolves.toBeUndefined();
61
+ await expect(rules[1].validator({}, '{"name":')).rejects.toContain('Invalid JSON format');
62
+
63
+ const persistedRules = JSON.parse(JSON.stringify(parent.serialize())).props.rules as ValidationRule[];
64
+ expect(persistedRules).toHaveLength(2);
65
+ expect(persistedRules[1]).toMatchObject({ type: 'any' });
66
+ expect(persistedRules[1].validator).toBeUndefined();
67
+ });
68
+
69
+ it('re-registers the runtime validator without duplicating its persisted placeholder', () => {
70
+ const { field, parent } = createModels([{}]);
71
+ initializeJsonValidation(field);
72
+ const persistedRules = JSON.parse(JSON.stringify(parent.serialize())).props.rules as ValidationRule[];
73
+ parent.setProps({ rules: persistedRules });
74
+
75
+ initializeJsonValidation(field);
76
+
77
+ const rules = parent.props.rules as ValidationRule[];
78
+ expect(rules).toHaveLength(1);
79
+ expect(rules[0]).toMatchObject({ type: 'any' });
80
+ expect(rules[0].validator).toBeTypeOf('function');
81
+ });
82
+ });