@nocobase/client-v2 2.2.0-beta.7 → 2.2.0-beta.9

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 (113) hide show
  1. package/es/BaseApplication.d.ts +2 -0
  2. package/es/RouteRepository.d.ts +8 -0
  3. package/es/RouterManager.d.ts +15 -0
  4. package/es/authRedirect.d.ts +1 -0
  5. package/es/entry-actions/EntryActionManager.d.ts +24 -0
  6. package/es/entry-actions/index.d.ts +9 -0
  7. package/es/flow/actions/afterSuccess.d.ts +8 -1
  8. package/es/flow/actions/index.d.ts +1 -1
  9. package/es/flow/admin-shell/BaseLayoutModel.d.ts +6 -0
  10. package/es/flow/admin-shell/BaseLayoutRouteCoordinator.d.ts +7 -0
  11. package/es/flow/admin-shell/admin-layout/AdminLayoutSlotModels.d.ts +1 -0
  12. package/es/flow/admin-shell/admin-layout/AppListRender.d.ts +2 -1
  13. package/es/flow/admin-shell/admin-layout/AppSwitcherActionPanelModel.d.ts +24 -0
  14. package/es/flow/admin-shell/admin-layout/index.d.ts +1 -0
  15. package/es/flow/admin-shell/admin-layout/useApplications.d.ts +7 -2
  16. package/es/flow/models/base/ActionModelCore.d.ts +2 -0
  17. package/es/flow/models/blocks/form/submitHandler.d.ts +1 -1
  18. package/es/flow/models/blocks/form/value-runtime/runtime.d.ts +9 -0
  19. package/es/flow/models/blocks/js-block/JSBlock.d.ts +1 -0
  20. package/es/flow/models/blocks/table/TableActionsColumnModel.d.ts +1 -0
  21. package/es/flow/models/blocks/table/TableBlockModel.d.ts +1 -0
  22. package/es/flow/models/blocks/table/dragSort/dragSortHooks.d.ts +1 -1
  23. package/es/flow/models/blocks/table/dragSort/dragSortSettings.d.ts +2 -1
  24. package/es/flow/models/blocks/table/dragSort/dragSortUtils.d.ts +6 -4
  25. package/es/flow/resolveViewParamsToViewList.d.ts +1 -1
  26. package/es/flow/routeTransientInputArgs.d.ts +14 -0
  27. package/es/index.d.ts +2 -0
  28. package/es/index.mjs +243 -141
  29. package/es/utils/markdownSanitize.d.ts +11 -0
  30. package/lib/index.js +232 -130
  31. package/package.json +7 -7
  32. package/src/BaseApplication.tsx +2 -0
  33. package/src/RouteRepository.ts +25 -0
  34. package/src/RouterManager.tsx +142 -1
  35. package/src/__tests__/RouteRepository.test.ts +23 -0
  36. package/src/__tests__/RouterManager.test.ts +125 -0
  37. package/src/__tests__/authRedirect.test.ts +17 -0
  38. package/src/authRedirect.ts +38 -0
  39. package/src/collection-manager/field-configure.ts +1 -1
  40. package/src/collection-manager/interfaces/id.ts +1 -1
  41. package/src/collection-manager/interfaces/m2m.tsx +2 -2
  42. package/src/collection-manager/interfaces/m2o.tsx +2 -2
  43. package/src/collection-manager/interfaces/nanoid.ts +1 -1
  44. package/src/collection-manager/interfaces/o2m.tsx +2 -2
  45. package/src/collection-manager/interfaces/obo.tsx +2 -2
  46. package/src/collection-manager/interfaces/oho.tsx +2 -2
  47. package/src/collection-manager/interfaces/properties/index.ts +2 -2
  48. package/src/collection-manager/interfaces/uuid.ts +1 -1
  49. package/src/entry-actions/EntryActionManager.ts +76 -0
  50. package/src/entry-actions/index.ts +10 -0
  51. package/src/flow/FlowPage.tsx +29 -2
  52. package/src/flow/__tests__/FlowPage.test.tsx +152 -25
  53. package/src/flow/__tests__/FlowRoute.test.tsx +547 -2
  54. package/src/flow/__tests__/getKey.test.ts +7 -0
  55. package/src/flow/__tests__/resolveViewParamsToViewList.test.ts +34 -0
  56. package/src/flow/actions/__tests__/afterSuccess.test.ts +73 -0
  57. package/src/flow/actions/__tests__/dataScopeFilter.test.ts +62 -0
  58. package/src/flow/actions/__tests__/openView.defineProps.route.test.tsx +164 -0
  59. package/src/flow/actions/afterSuccess.tsx +142 -3
  60. package/src/flow/actions/dataScopeFilter.ts +10 -1
  61. package/src/flow/actions/dateTimeFormat.tsx +2 -2
  62. package/src/flow/actions/index.ts +1 -1
  63. package/src/flow/actions/openView.tsx +59 -5
  64. package/src/flow/admin-shell/BaseLayoutModel.tsx +149 -3
  65. package/src/flow/admin-shell/BaseLayoutRouteCoordinator.ts +187 -42
  66. package/src/flow/admin-shell/__tests__/AdminLayoutRouteCoordinator.test.ts +1020 -110
  67. package/src/flow/admin-shell/admin-layout/AdminLayoutComponent.tsx +42 -4
  68. package/src/flow/admin-shell/admin-layout/AdminLayoutEntryGuard.test.tsx +177 -1
  69. package/src/flow/admin-shell/admin-layout/AdminLayoutEntryGuard.tsx +20 -0
  70. package/src/flow/admin-shell/admin-layout/AdminLayoutSlotModels.tsx +5 -4
  71. package/src/flow/admin-shell/admin-layout/AppListRender.tsx +13 -2
  72. package/src/flow/admin-shell/admin-layout/AppSwitcherActionPanelModel.tsx +289 -0
  73. package/src/flow/admin-shell/admin-layout/__tests__/AdminLayoutModel.test.tsx +518 -2
  74. package/src/flow/admin-shell/admin-layout/__tests__/TopbarActionsBar.test.tsx +48 -0
  75. package/src/flow/admin-shell/admin-layout/index.ts +1 -0
  76. package/src/flow/admin-shell/admin-layout/useApplications.tsx +81 -12
  77. package/src/flow/common/Markdown/Display.tsx +14 -3
  78. package/src/flow/common/Markdown/Edit.tsx +19 -7
  79. package/src/flow/components/FlowRoute.tsx +128 -16
  80. package/src/flow/getViewDiffAndUpdateHidden.tsx +1 -0
  81. package/src/flow/internal/components/Markdown/util.ts +2 -1
  82. package/src/flow/models/base/ActionModel.tsx +10 -8
  83. package/src/flow/models/base/ActionModelCore.tsx +11 -4
  84. package/src/flow/models/base/__tests__/ActionModelCore.render.test.tsx +37 -0
  85. package/src/flow/models/blocks/filter-form/fields/FilterFormCustomFieldModel.tsx +1 -1
  86. package/src/flow/models/blocks/form/FormActionModel.tsx +1 -1
  87. package/src/flow/models/blocks/form/__tests__/submitHandler.test.ts +54 -1
  88. package/src/flow/models/blocks/form/submitHandler.ts +17 -3
  89. package/src/flow/models/blocks/form/value-runtime/__tests__/runtime.test.ts +87 -0
  90. package/src/flow/models/blocks/form/value-runtime/runtime.ts +91 -0
  91. package/src/flow/models/blocks/js-block/JSBlock.tsx +223 -2
  92. package/src/flow/models/blocks/js-block/__tests__/JSBlockModel.test.tsx +150 -0
  93. package/src/flow/models/blocks/table/TableActionsColumnModel.tsx +35 -12
  94. package/src/flow/models/blocks/table/TableBlockModel.tsx +25 -14
  95. package/src/flow/models/blocks/table/TableColumnModel.tsx +6 -2
  96. package/src/flow/models/blocks/table/__tests__/TableActionsColumnModel.test.tsx +57 -1
  97. package/src/flow/models/blocks/table/__tests__/TableBlockModel.dragSort.test.ts +127 -0
  98. package/src/flow/models/blocks/table/__tests__/TableBlockModel.rowSelection.test.tsx +1 -0
  99. package/src/flow/models/blocks/table/__tests__/TableColumnModel.test.tsx +51 -0
  100. package/src/flow/models/blocks/table/dragSort/dragSortHooks.tsx +28 -17
  101. package/src/flow/models/blocks/table/dragSort/dragSortSettings.ts +13 -6
  102. package/src/flow/models/blocks/table/dragSort/dragSortUtils.ts +15 -2
  103. package/src/flow/models/fields/AssociationFieldModel/RecordSelectFieldModel.tsx +45 -13
  104. package/src/flow/models/fields/TextareaFieldModel.tsx +42 -19
  105. package/src/flow/models/fields/__tests__/TextareaFieldModel.test.tsx +32 -1
  106. package/src/flow/models/topbar/TopbarActionModel.tsx +78 -3
  107. package/src/flow/resolveViewParamsToViewList.tsx +11 -3
  108. package/src/flow/routeTransientInputArgs.ts +27 -0
  109. package/src/flow/utils/__tests__/dateTimeFormat.test.ts +42 -0
  110. package/src/index.ts +2 -0
  111. package/src/nocobase-buildin-plugin/index.tsx +7 -1
  112. package/src/settings-center/SystemSettingsPage.tsx +1 -1
  113. package/src/utils/markdownSanitize.ts +88 -0
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { SingleRecordResource } from '@nocobase/flow-engine';
11
11
  import { describe, expect, it, vi } from 'vitest';
12
+ import { EditFormModel } from '../EditFormModel';
12
13
  import { submitHandler } from '../submitHandler';
13
14
 
14
15
  describe('submitHandler', () => {
@@ -52,13 +53,14 @@ describe('submitHandler', () => {
52
53
  t: (value: string) => value,
53
54
  };
54
55
 
55
- await submitHandler(ctx, {
56
+ const responseRecord = await submitHandler(ctx, {
56
57
  assignedValues: {
57
58
  status: 'published',
58
59
  reviewer: 'Alice',
59
60
  },
60
61
  });
61
62
 
63
+ expect(responseRecord).toEqual({ id: 1 });
62
64
  expect(resource.save).toHaveBeenCalledWith(
63
65
  {
64
66
  title: 'Draft title',
@@ -68,4 +70,55 @@ describe('submitHandler', () => {
68
70
  undefined,
69
71
  );
70
72
  });
73
+
74
+ it('returns the refreshed record for edit forms when the save response is empty', async () => {
75
+ const refreshedRecord = { id: 2, title: 'Updated title' };
76
+ const resource = Object.create(SingleRecordResource.prototype);
77
+ resource.getMeta = vi.fn((key: string) => (key === 'currentFilterByTk' ? 2 : undefined));
78
+ resource.setFilterByTk = vi.fn(() => resource);
79
+ resource.save = vi.fn(async () => undefined);
80
+ resource.refresh = vi.fn(async () => undefined);
81
+ resource.getData = vi.fn(() => refreshedRecord);
82
+
83
+ const blockModel = Object.create(EditFormModel.prototype);
84
+ const form = {
85
+ validateFields: vi.fn(async () => undefined),
86
+ getFieldsValue: vi.fn(() => ({
87
+ title: 'Updated title',
88
+ })),
89
+ };
90
+ Object.defineProperty(blockModel, 'context', { value: { form } });
91
+ Object.defineProperty(blockModel, 'collection', {
92
+ value: {
93
+ name: 'posts',
94
+ getFilterByTK: (record: { id?: number }) => record.id,
95
+ },
96
+ });
97
+ blockModel.resetUserModifiedFields = vi.fn();
98
+
99
+ const responseRecord = await submitHandler(
100
+ {
101
+ resource,
102
+ blockModel,
103
+ model: {
104
+ getStepParams: vi.fn(),
105
+ },
106
+ message: {
107
+ error: vi.fn(),
108
+ },
109
+ t: (value: string) => value,
110
+ },
111
+ {},
112
+ );
113
+
114
+ expect(responseRecord).toBe(refreshedRecord);
115
+ expect(resource.setFilterByTk).toHaveBeenCalledWith(2);
116
+ expect(resource.save).toHaveBeenCalledWith(
117
+ {
118
+ title: 'Updated title',
119
+ },
120
+ undefined,
121
+ );
122
+ expect(resource.refresh).toHaveBeenCalled();
123
+ });
71
124
  });
@@ -12,6 +12,16 @@ import { mergeAssignFieldValues, resolveAssignFieldValues } from '../assign-form
12
12
  import type { FormBlockModel } from './FormBlockModel';
13
13
  import { omitHiddenModelValuesFromSubmit, shouldSkipSubmitValidation, validateSubmitForm } from './submitValues';
14
14
 
15
+ function getResponseRecord(response: unknown) {
16
+ if (!response || typeof response !== 'object') {
17
+ return response;
18
+ }
19
+ if ('data' in response) {
20
+ return (response as { data?: unknown }).data;
21
+ }
22
+ return response;
23
+ }
24
+
15
25
  export async function submitHandler(ctx, params, cb?: (values?: any, filterByTk?: any) => void) {
16
26
  const resource = ctx.resource;
17
27
  const blockModel = ctx.blockModel as FormBlockModel;
@@ -41,30 +51,34 @@ export async function submitHandler(ctx, params, cb?: (values?: any, filterByTk?
41
51
  resource.setFilterByTk(currentFilterByTk);
42
52
  }
43
53
  }
44
- const data: any = cb ? await cb(values) : await resource.save(values, params.requestConfig);
54
+ const data: unknown = cb ? await cb(values) : await resource.save(values, params.requestConfig);
55
+ let responseRecord = getResponseRecord(data);
45
56
  if (isEditFormModel) {
46
57
  resource.isNewRecord = false;
47
58
  // 编辑表单保存成功后,表单应回到“已同步”状态:下一次刷新应允许覆盖为服务端值
48
59
  blockModel.resetUserModifiedFields?.();
49
60
  await resource.refresh();
61
+ responseRecord = responseRecord ?? resource.getData?.();
50
62
  } else {
51
63
  blockModel.form.resetFields();
52
64
  blockModel.emitter.emit('onFieldReset');
53
65
  blockModel.resetUserModifiedFields?.();
54
66
  blockModel.formValueRuntime?.resetAfterFormReset?.();
55
67
  if (ctx.view.inputArgs.collectionName === blockModel.collection.name && ctx.view.inputArgs.onChange) {
56
- ctx.view.inputArgs.onChange(data?.data);
68
+ ctx.view.inputArgs.onChange(responseRecord);
57
69
  }
58
70
  }
71
+ return responseRecord;
59
72
  } else if (resource instanceof MultiRecordResource) {
60
73
  const currentFilterByTk = resource.getMeta('currentFilterByTk');
61
74
  if (!currentFilterByTk) {
62
75
  ctx.message.error(ctx.t('No filterByTk found for multi-record resource.'));
63
76
  return;
64
77
  }
65
- (await cb)
78
+ const data = cb
66
79
  ? await cb(values, currentFilterByTk)
67
80
  : await resource.update(currentFilterByTk, values, params.requestConfig);
68
81
  blockModel.resetUserModifiedFields?.();
82
+ return getResponseRecord(data) ?? blockModel.getCurrentRecord?.();
69
83
  }
70
84
  }
@@ -127,6 +127,93 @@ function createFieldContext(runtime: FormValueRuntime) {
127
127
  }
128
128
 
129
129
  describe('FormValueRuntime (default rules)', () => {
130
+ it('builds draft snapshots from current user-edited values only', async () => {
131
+ const engineEmitter = new EventEmitter();
132
+ const blockEmitter = new EventEmitter();
133
+ const formStub = createFormStub({});
134
+ const dispatchEvent = vi.fn();
135
+
136
+ const blockModel = {
137
+ uid: 'form-user-edited-draft-snapshot',
138
+ flowEngine: { emitter: engineEmitter },
139
+ emitter: blockEmitter,
140
+ dispatchEvent,
141
+ getAclActionName: () => 'create',
142
+ } as ConstructorParameters<typeof FormValueRuntime>[0]['model'];
143
+
144
+ const runtime = new FormValueRuntime({ model: blockModel, getForm: () => formStub as unknown as FormInstance });
145
+ runtime.mount({ sync: true });
146
+
147
+ const blockCtx = createFieldContext(runtime);
148
+ await runtime.setFormValues(blockCtx, [{ path: ['fixed'], value: 'Fixed auto value' }], { source: 'system' });
149
+ await runtime.setFormValues(blockCtx, [{ path: ['defaultTitle'], value: 'Default auto value' }], {
150
+ source: 'default',
151
+ });
152
+ await runtime.setFormValues(blockCtx, [{ path: ['overrideTitle'], value: 'Override auto value' }], {
153
+ source: 'override',
154
+ });
155
+
156
+ expect(runtime.getUserEditedValuePatches()).toEqual([]);
157
+ expect(runtime.getUserEditedValuesSnapshot()).toEqual({});
158
+
159
+ await runtime.setFormValues(
160
+ blockCtx,
161
+ [
162
+ { path: ['title'], value: 'Manual title' },
163
+ { path: ['roles', 0, 'roleName'], value: 'Manual role' },
164
+ ],
165
+ { source: 'user' },
166
+ );
167
+
168
+ expect(runtime.getUserEditedValuePatches()).toEqual([
169
+ { path: ['title'], value: 'Manual title' },
170
+ { path: ['roles', 0, 'roleName'], value: 'Manual role' },
171
+ ]);
172
+ expect(runtime.getUserEditedValuesSnapshot()).toEqual({
173
+ title: 'Manual title',
174
+ roles: [{ roleName: 'Manual role' }],
175
+ });
176
+
177
+ await runtime.setFormValues(blockCtx, [{ path: ['title'], value: 'Fixed title' }], { source: 'system' });
178
+
179
+ expect(runtime.getUserEditedValuesSnapshot()).toEqual({
180
+ roles: [{ roleName: 'Manual role' }],
181
+ });
182
+ });
183
+
184
+ it('omits non-user descendant values from parent user-edited draft patches', async () => {
185
+ const engineEmitter = new EventEmitter();
186
+ const blockEmitter = new EventEmitter();
187
+ const formStub = createFormStub({});
188
+ const dispatchEvent = vi.fn();
189
+
190
+ const blockModel = {
191
+ uid: 'form-user-edited-parent-draft-patch',
192
+ flowEngine: { emitter: engineEmitter },
193
+ emitter: blockEmitter,
194
+ dispatchEvent,
195
+ getAclActionName: () => 'create',
196
+ } as ConstructorParameters<typeof FormValueRuntime>[0]['model'];
197
+
198
+ const runtime = new FormValueRuntime({ model: blockModel, getForm: () => formStub as unknown as FormInstance });
199
+ runtime.mount({ sync: true });
200
+
201
+ const blockCtx = createFieldContext(runtime);
202
+ await runtime.setFormValues(
203
+ blockCtx,
204
+ [{ path: ['roles'], value: [{ roleName: 'Manual role', fixedRoleName: 'Initial fixed role' }] }],
205
+ { source: 'user' },
206
+ );
207
+ await runtime.setFormValues(blockCtx, [{ path: ['roles', 0, 'fixedRoleName'], value: 'System fixed role' }], {
208
+ source: 'system',
209
+ });
210
+
211
+ expect(runtime.getUserEditedValuePatches()).toEqual([{ path: ['roles'], value: [{ roleName: 'Manual role' }] }]);
212
+ expect(runtime.getUserEditedValuesSnapshot()).toEqual({
213
+ roles: [{ roleName: 'Manual role' }],
214
+ });
215
+ });
216
+
130
217
  it('skips object patches when values are unchanged', async () => {
131
218
  const engineEmitter = new EventEmitter();
132
219
  const blockEmitter = new EventEmitter();
@@ -38,6 +38,11 @@ type FormBlockModel = FlowModel & {
38
38
  getAclActionName?: () => string;
39
39
  };
40
40
 
41
+ export type FormValuePatch = {
42
+ path: NamePath;
43
+ value: unknown;
44
+ };
45
+
41
46
  export class FormValueRuntime {
42
47
  private readonly model: FormBlockModel;
43
48
  private readonly getForm: () => FormInstance;
@@ -142,6 +147,49 @@ export class FormValueRuntime {
142
147
  return this.getForm().getFieldsValue(true);
143
148
  }
144
149
 
150
+ getUserEditedValuePatches(): FormValuePatch[] {
151
+ const snapshot = this.getFormValuesSnapshot();
152
+ if (!snapshot || typeof snapshot !== 'object') {
153
+ return [];
154
+ }
155
+
156
+ const patches: FormValuePatch[] = [];
157
+ const pathKeys = Array.from(this.userEditedSet).sort(
158
+ (a, b) => pathKeyToNamePath(a).length - pathKeyToNamePath(b).length,
159
+ );
160
+
161
+ for (const pathKey of pathKeys) {
162
+ if (!this.isCurrentUserEditedPath(pathKey)) {
163
+ continue;
164
+ }
165
+
166
+ const namePath = pathKeyToNamePath(pathKey);
167
+ if (!namePath.length || !_.has(snapshot, namePath as any)) {
168
+ continue;
169
+ }
170
+
171
+ const value = _.get(snapshot, namePath as any);
172
+ if (typeof value === 'undefined') {
173
+ continue;
174
+ }
175
+
176
+ patches.push({
177
+ path: namePath,
178
+ value: this.omitNonUserDescendantValues(pathKey, this.toMirrorSnapshot(value)),
179
+ });
180
+ }
181
+
182
+ return patches;
183
+ }
184
+
185
+ getUserEditedValuesSnapshot(): Record<string, unknown> {
186
+ const values: Record<string, unknown> = {};
187
+ for (const patch of this.getUserEditedValuePatches()) {
188
+ _.set(values, patch.path as any, patch.value);
189
+ }
190
+ return values;
191
+ }
192
+
145
193
  private toMirrorSnapshot(value: any) {
146
194
  const raw = isObservable(value) ? toJS(value) : value;
147
195
  return _.cloneDeepWith(raw, (item) => {
@@ -1453,6 +1501,49 @@ export class FormValueRuntime {
1453
1501
  return null;
1454
1502
  }
1455
1503
 
1504
+ private findLatestWriteMeta(pathKey: string): FormValueWriteMeta | undefined {
1505
+ let latest: FormValueWriteMeta | undefined;
1506
+ const namePath = pathKeyToNamePath(pathKey);
1507
+ const prefix: NamePath = [];
1508
+
1509
+ for (let i = 0; i < namePath.length; i++) {
1510
+ prefix.push(namePath[i]);
1511
+ const meta = this.lastWriteMetaByPathKey.get(namePathToPathKey(prefix as any));
1512
+ if (!meta) {
1513
+ continue;
1514
+ }
1515
+ if (!latest || meta.writeSeq >= latest.writeSeq) {
1516
+ latest = meta;
1517
+ }
1518
+ }
1519
+
1520
+ return latest;
1521
+ }
1522
+
1523
+ private isCurrentUserEditedPath(pathKey: string) {
1524
+ const lastWrite = this.findLatestWriteMeta(pathKey);
1525
+ return !lastWrite || lastWrite.source === 'user';
1526
+ }
1527
+
1528
+ private omitNonUserDescendantValues(pathKey: string, value: unknown) {
1529
+ if (!value || typeof value !== 'object') {
1530
+ return value;
1531
+ }
1532
+
1533
+ const namePath = pathKeyToNamePath(pathKey);
1534
+ for (const childKey of this.lastWriteMetaByPathKey.keys()) {
1535
+ if (!this.isDescendantPathKey(childKey, pathKey)) {
1536
+ continue;
1537
+ }
1538
+ if (this.isCurrentUserEditedPath(childKey)) {
1539
+ continue;
1540
+ }
1541
+ _.unset(value as Record<string, unknown>, pathKeyToNamePath(childKey).slice(namePath.length) as any);
1542
+ }
1543
+
1544
+ return value;
1545
+ }
1546
+
1456
1547
  private isDescendantPathKey(candidateKey: string, parentKey: string) {
1457
1548
  if (!candidateKey || !parentKey || candidateKey === parentKey) return false;
1458
1549
  const candidatePath = pathKeyToNamePath(candidateKey);
@@ -16,24 +16,238 @@ import { CodeEditor } from '../../../components/code-editor';
16
16
 
17
17
  const NAMESPACE = 'client';
18
18
 
19
+ const getRootElement = (element: HTMLElement | null) => {
20
+ if (!element) return document.documentElement;
21
+ return (
22
+ (element.closest('.nb-block-grid') as HTMLElement | null) ||
23
+ (element.closest('.nb-page-wrapper') as HTMLElement | null) ||
24
+ (element.closest('.nb-page') as HTMLElement | null) ||
25
+ document.documentElement
26
+ );
27
+ };
28
+
29
+ const getOuterHeight = (element?: HTMLElement | null) => {
30
+ if (!element) return 0;
31
+ const rect = element.getBoundingClientRect();
32
+ const style = window.getComputedStyle(element);
33
+ const marginTop = parseFloat(style.marginTop) || 0;
34
+ const marginBottom = parseFloat(style.marginBottom) || 0;
35
+ return rect.height + marginTop + marginBottom;
36
+ };
37
+
38
+ const getPadding = (element: HTMLElement | null) => {
39
+ if (!element || element === document.documentElement) {
40
+ return { top: 0, bottom: 0 };
41
+ }
42
+ const style = window.getComputedStyle(element);
43
+ return {
44
+ top: parseFloat(style.paddingTop) || 0,
45
+ bottom: parseFloat(style.paddingBottom) || 0,
46
+ };
47
+ };
48
+
49
+ const getPageHeader = (root: HTMLElement) => {
50
+ const page = root.closest('.nb-page') as HTMLElement | null;
51
+ if (!page) return null;
52
+ return (
53
+ (page.querySelector('.ant-page-header') as HTMLElement | null) ||
54
+ (page.querySelector('.pageHeaderCss') as HTMLElement | null)
55
+ );
56
+ };
57
+
58
+ const getAddBlockContainer = (root: HTMLElement) => {
59
+ const button = root.querySelector('[data-flow-add-block]') as HTMLElement | null;
60
+ if (!button) return null;
61
+ return (button.parentElement as HTMLElement | null) || button;
62
+ };
63
+
64
+ function getValidPageTop(a: number, b: number) {
65
+ const aValid = a > 0;
66
+ const bValid = b > 0;
67
+
68
+ if (aValid) return a;
69
+ if (bValid) return b;
70
+ return 0;
71
+ }
72
+
73
+ const usePlainHostHeight = ({
74
+ height,
75
+ heightMode,
76
+ hostRef,
77
+ marginBlock,
78
+ }: {
79
+ height?: number;
80
+ heightMode?: string;
81
+ hostRef: React.RefObject<HTMLDivElement>;
82
+ marginBlock: number;
83
+ }) => {
84
+ const [fullHeight, setFullHeight] = React.useState<number>();
85
+ const updateFullHeight = React.useCallback(() => {
86
+ if (heightMode !== 'fullHeight' || typeof window === 'undefined') {
87
+ setFullHeight((prev) => (prev === undefined ? prev : undefined));
88
+ return;
89
+ }
90
+ const hostEl = hostRef.current;
91
+ if (!hostEl) return;
92
+ const root = getRootElement(hostEl);
93
+ const hostRect = hostEl.getBoundingClientRect();
94
+ const rootRect = root === document.documentElement ? { top: 0 } : root.getBoundingClientRect();
95
+ const padding = getPadding(root);
96
+ const addBlockContainer = getAddBlockContainer(root);
97
+ const pageTop = rootRect.top + padding.top;
98
+ const topOffset = Math.max(0, hostRect.top - pageTop);
99
+ let bottomOffset = padding.bottom + marginBlock;
100
+ if (addBlockContainer) {
101
+ const gapBetween = marginBlock;
102
+ bottomOffset = gapBetween + getOuterHeight(addBlockContainer) + padding.bottom;
103
+ }
104
+ const nextHeight = Math.max(
105
+ 0,
106
+ Math.floor(window.innerHeight - getValidPageTop(pageTop, 110) - topOffset - bottomOffset - 1),
107
+ );
108
+ setFullHeight((prev) => (prev === nextHeight ? prev : nextHeight));
109
+ }, [heightMode, hostRef, marginBlock]);
110
+
111
+ React.useLayoutEffect(() => {
112
+ updateFullHeight();
113
+ }, [updateFullHeight]);
114
+
115
+ React.useEffect(() => {
116
+ if (heightMode !== 'fullHeight' || typeof window === 'undefined') return;
117
+ const hostEl = hostRef.current;
118
+ if (!hostEl || typeof ResizeObserver === 'undefined') return;
119
+ const root = getRootElement(hostEl);
120
+ const pageHeader = getPageHeader(root);
121
+ const addBlockContainer = getAddBlockContainer(root);
122
+ const observer = new ResizeObserver(() => updateFullHeight());
123
+ observer.observe(hostEl);
124
+ if (root instanceof HTMLElement) {
125
+ observer.observe(root);
126
+ }
127
+ if (pageHeader) observer.observe(pageHeader);
128
+ if (addBlockContainer) observer.observe(addBlockContainer);
129
+ window.addEventListener('resize', updateFullHeight);
130
+ return () => {
131
+ observer.disconnect();
132
+ window.removeEventListener('resize', updateFullHeight);
133
+ };
134
+ }, [heightMode, hostRef, updateFullHeight]);
135
+
136
+ if (heightMode === 'specifyValue') {
137
+ return height;
138
+ }
139
+ if (heightMode === 'fullHeight') {
140
+ return fullHeight;
141
+ }
142
+ return null;
143
+ };
144
+
145
+ const JSBlockPlainHost = ({
146
+ uid,
147
+ className,
148
+ heightMode,
149
+ height,
150
+ style,
151
+ beforeContent,
152
+ afterContent,
153
+ contentRef,
154
+ marginBlock,
155
+ ...rest
156
+ }: React.HTMLAttributes<HTMLDivElement> & {
157
+ uid: string;
158
+ heightMode?: string;
159
+ height?: number;
160
+ beforeContent?: React.ReactNode;
161
+ afterContent?: React.ReactNode;
162
+ contentRef: React.RefObject<HTMLDivElement>;
163
+ marginBlock: number;
164
+ }) => {
165
+ const hostRef = React.useRef<HTMLDivElement | null>(null);
166
+ const resolvedHeight = usePlainHostHeight({ height, heightMode, hostRef, marginBlock });
167
+
168
+ return (
169
+ <div
170
+ {...rest}
171
+ ref={hostRef}
172
+ id={`model-${uid}`}
173
+ className={className}
174
+ style={{
175
+ display: 'flex',
176
+ flexDirection: 'column',
177
+ height: resolvedHeight ?? undefined,
178
+ minHeight: 0,
179
+ overflow: 'auto',
180
+ ...(style || {}),
181
+ }}
182
+ >
183
+ {beforeContent}
184
+ <div ref={contentRef} />
185
+ {afterContent}
186
+ </div>
187
+ );
188
+ };
189
+
19
190
  export class JSBlockModel extends BlockModel {
20
191
  // Avoid double-run on first mount; only rerun after remounts
21
192
  private _mountedOnce = false;
193
+
194
+ get showBlockCard() {
195
+ return this.getStepParams('jsSettings', 'showBlockCard')?.showBlockCard !== false;
196
+ }
197
+
22
198
  renderComponent(): React.ReactNode {
23
199
  return <div ref={this.context.ref} />;
24
200
  }
25
201
  render() {
26
202
  const decoratorProps = this.decoratorProps || {};
27
- const { className, id: _ignoredId, title, description, ...rest } = decoratorProps;
203
+ const {
204
+ className,
205
+ id: _ignoredId,
206
+ title,
207
+ description,
208
+ showCard: _ignoredShowCard,
209
+ heightMode,
210
+ height,
211
+ style,
212
+ beforeContent,
213
+ afterContent,
214
+ ...rest
215
+ } = decoratorProps;
28
216
  const mergedClassName = ['code-block', className].filter(Boolean).join(' ');
29
217
 
218
+ if (!this.showBlockCard) {
219
+ return (
220
+ <JSBlockPlainHost
221
+ {...rest}
222
+ uid={this.uid}
223
+ className={mergedClassName}
224
+ heightMode={heightMode}
225
+ height={height}
226
+ style={style}
227
+ beforeContent={beforeContent}
228
+ afterContent={afterContent}
229
+ contentRef={this.context.ref}
230
+ marginBlock={this.context.themeToken?.marginBlock ?? 0}
231
+ />
232
+ );
233
+ }
234
+
235
+ const cardProps = {
236
+ ...rest,
237
+ height,
238
+ style,
239
+ ...(beforeContent === undefined ? {} : { beforeContent }),
240
+ ...(afterContent === undefined ? {} : { afterContent }),
241
+ };
242
+
30
243
  return (
31
244
  <BlockItemCard
32
245
  id={`model-${this.uid}`}
33
246
  className={mergedClassName}
34
247
  title={title}
35
248
  description={description}
36
- {...rest}
249
+ heightMode={heightMode}
250
+ {...cardProps}
37
251
  >
38
252
  <div ref={this.context.ref} />
39
253
  </BlockItemCard>
@@ -61,6 +275,13 @@ JSBlockModel.registerFlow({
61
275
  key: 'jsSettings',
62
276
  title: 'JavaScript settings',
63
277
  steps: {
278
+ showBlockCard: {
279
+ title: tExpr('Show block card'),
280
+ uiMode: { type: 'switch', key: 'showBlockCard' },
281
+ defaultParams: {
282
+ showBlockCard: true,
283
+ },
284
+ },
64
285
  runJs: {
65
286
  title: tExpr('Write JavaScript'),
66
287
  useRawParams: true,