@nocobase/client-v2 2.2.0-alpha.3 → 2.2.0-alpha.5

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 (81) 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/components/form/TypedVariableInput.d.ts +9 -1
  6. package/es/components/form/filter/CollectionFilter.d.ts +2 -0
  7. package/es/components/form/filter/CollectionFilterPanel.d.ts +2 -0
  8. package/es/components/form/filter/useFilterActionProps.d.ts +2 -0
  9. package/es/entry-actions/EntryActionManager.d.ts +24 -0
  10. package/es/entry-actions/index.d.ts +9 -0
  11. package/es/flow/admin-shell/BaseLayoutModel.d.ts +6 -0
  12. package/es/flow/admin-shell/BaseLayoutRouteCoordinator.d.ts +7 -0
  13. package/es/flow/admin-shell/admin-layout/AppListRender.d.ts +2 -1
  14. package/es/flow/admin-shell/admin-layout/AppSwitcherActionPanelModel.d.ts +24 -0
  15. package/es/flow/admin-shell/admin-layout/index.d.ts +1 -0
  16. package/es/flow/admin-shell/admin-layout/useApplications.d.ts +7 -2
  17. package/es/flow/models/base/ActionModelCore.d.ts +2 -0
  18. package/es/flow/routeTransientInputArgs.d.ts +14 -0
  19. package/es/index.d.ts +6 -0
  20. package/es/index.mjs +229 -143
  21. package/es/utils/getRouteRuntimeVersion.d.ts +23 -0
  22. package/es/utils/index.d.ts +1 -0
  23. package/es/utils/markdownSanitize.d.ts +11 -0
  24. package/lib/index.js +219 -133
  25. package/package.json +7 -7
  26. package/src/BaseApplication.tsx +2 -0
  27. package/src/RouteRepository.ts +25 -0
  28. package/src/RouterManager.tsx +142 -1
  29. package/src/__tests__/RouteRepository.test.ts +23 -0
  30. package/src/__tests__/RouterManager.test.ts +125 -0
  31. package/src/__tests__/authRedirect.test.ts +17 -0
  32. package/src/__tests__/getRouteRuntimeVersion.test.ts +68 -0
  33. package/src/authRedirect.ts +38 -0
  34. package/src/components/form/JsonTextArea.tsx +4 -0
  35. package/src/components/form/TypedVariableInput.tsx +58 -34
  36. package/src/components/form/__tests__/TypedVariableInput.test.tsx +52 -0
  37. package/src/components/form/filter/CollectionFilter.tsx +4 -0
  38. package/src/components/form/filter/CollectionFilterPanel.tsx +4 -0
  39. package/src/components/form/filter/__tests__/useFilterActionProps.test.tsx +95 -0
  40. package/src/components/form/filter/useFilterActionProps.ts +37 -6
  41. package/src/entry-actions/EntryActionManager.ts +76 -0
  42. package/src/entry-actions/index.ts +10 -0
  43. package/src/flow/FlowPage.tsx +29 -2
  44. package/src/flow/__tests__/FlowPage.test.tsx +152 -25
  45. package/src/flow/__tests__/FlowRoute.test.tsx +547 -2
  46. package/src/flow/actions/__tests__/dataScopeFilter.test.ts +62 -0
  47. package/src/flow/actions/__tests__/openView.defineProps.route.test.tsx +80 -20
  48. package/src/flow/actions/dataScopeFilter.ts +10 -1
  49. package/src/flow/actions/dateTimeFormat.tsx +2 -2
  50. package/src/flow/actions/openView.tsx +21 -1
  51. package/src/flow/admin-shell/BaseLayoutModel.tsx +124 -0
  52. package/src/flow/admin-shell/BaseLayoutRouteCoordinator.ts +184 -42
  53. package/src/flow/admin-shell/__tests__/AdminLayoutRouteCoordinator.test.ts +1016 -119
  54. package/src/flow/admin-shell/admin-layout/AdminLayoutComponent.tsx +41 -4
  55. package/src/flow/admin-shell/admin-layout/AdminLayoutEntryGuard.test.tsx +177 -1
  56. package/src/flow/admin-shell/admin-layout/AdminLayoutEntryGuard.tsx +20 -0
  57. package/src/flow/admin-shell/admin-layout/AppListRender.tsx +13 -2
  58. package/src/flow/admin-shell/admin-layout/AppSwitcherActionPanelModel.tsx +289 -0
  59. package/src/flow/admin-shell/admin-layout/__tests__/AdminLayoutModel.test.tsx +436 -2
  60. package/src/flow/admin-shell/admin-layout/__tests__/TopbarActionsBar.test.tsx +48 -0
  61. package/src/flow/admin-shell/admin-layout/index.ts +1 -0
  62. package/src/flow/admin-shell/admin-layout/useApplications.tsx +81 -12
  63. package/src/flow/common/Markdown/Display.tsx +14 -3
  64. package/src/flow/common/Markdown/Edit.tsx +19 -7
  65. package/src/flow/components/FlowRoute.tsx +128 -16
  66. package/src/flow/internal/components/Markdown/util.ts +2 -1
  67. package/src/flow/models/base/ActionModel.tsx +10 -8
  68. package/src/flow/models/base/ActionModelCore.tsx +5 -0
  69. package/src/flow/models/blocks/table/TableColumnModel.tsx +6 -2
  70. package/src/flow/models/blocks/table/__tests__/TableColumnModel.test.tsx +51 -0
  71. package/src/flow/models/fields/AssociationFieldModel/RecordSelectFieldModel.tsx +45 -13
  72. package/src/flow/models/fields/TextareaFieldModel.tsx +42 -19
  73. package/src/flow/models/fields/__tests__/TextareaFieldModel.test.tsx +32 -1
  74. package/src/flow/models/topbar/TopbarActionModel.tsx +78 -3
  75. package/src/flow/routeTransientInputArgs.ts +27 -0
  76. package/src/flow/utils/__tests__/dateTimeFormat.test.ts +42 -0
  77. package/src/index.ts +6 -0
  78. package/src/nocobase-buildin-plugin/index.tsx +7 -1
  79. package/src/utils/getRouteRuntimeVersion.ts +185 -0
  80. package/src/utils/index.tsx +1 -0
  81. package/src/utils/markdownSanitize.ts +88 -0
@@ -52,7 +52,9 @@ export interface TypedVariableInputProps {
52
52
  * Allowed constant types. The `Constant` switcher entry always exposes a
53
53
  * typed submenu (matching v1 `Variable.Input`) so users can see what type
54
54
  * the constant is, even when only one type is permitted. Default: all four
55
- * supported types.
55
+ * supported types. Passing `[]` switches the component into a variable-only
56
+ * mode: constants/null are hidden, the empty state becomes a readonly
57
+ * placeholder, and clearing a selected variable resets to `null`.
56
58
  */
57
59
  types?: TypedConstantSpec[];
58
60
  /**
@@ -89,6 +91,12 @@ export interface TypedVariableInputProps {
89
91
  defaultToFirstConstantTypeWhenUndefined?: boolean;
90
92
  /** Variable-token delimiters. Default `['{{', '}}']` — see `VariableInput`. */
91
93
  delimiters?: VariableDelimiters;
94
+ /**
95
+ * Hide variable choices from the switcher. In variable-only mode this hides
96
+ * the selector button entirely; in mixed constant/variable mode it keeps the
97
+ * null/constant choices but removes variable entries.
98
+ */
99
+ hideVariable?: boolean;
92
100
  disabled?: boolean;
93
101
  placeholder?: string;
94
102
  style?: React.CSSProperties;
@@ -400,6 +408,7 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
400
408
  nullable = true,
401
409
  defaultToFirstConstantTypeWhenUndefined = true,
402
410
  delimiters,
411
+ hideVariable = false,
403
412
  disabled,
404
413
  placeholder,
405
414
  style,
@@ -418,13 +427,14 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
418
427
  const formatVariablePath = useMemo(() => makeFormatVariablePath(delimiters), [delimiters]);
419
428
 
420
429
  const normalizedTypes = useMemo(() => normalizeTypes(types), [types]);
430
+ const variableOnly = normalizedTypes.length === 0;
421
431
  const defaultedValue = useMemo(() => {
422
- if (!defaultToFirstConstantTypeWhenUndefined || value !== undefined) {
432
+ if (variableOnly || !defaultToFirstConstantTypeWhenUndefined || value !== undefined) {
423
433
  return undefined;
424
434
  }
425
435
  const firstType = normalizedTypes[0];
426
436
  return firstType ? defaultValueFor(firstType.type) : undefined;
427
- }, [defaultToFirstConstantTypeWhenUndefined, normalizedTypes, value]);
437
+ }, [defaultToFirstConstantTypeWhenUndefined, normalizedTypes, value, variableOnly]);
428
438
  const effectiveValue = value === undefined && defaultedValue !== undefined ? defaultedValue : value;
429
439
  const detected = useMemo(() => detectMode(effectiveValue, parseVariablePath), [effectiveValue, parseVariablePath]);
430
440
 
@@ -481,13 +491,13 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
481
491
  // `updateFlag` is read so this recomputes (with fresh option references) after a lazy load mutates the meta tree.
482
492
  void updateFlag;
483
493
  const items: SwitcherOption[] = [];
484
- if (nullable) {
494
+ if (!variableOnly && nullable) {
485
495
  items.push({ value: NULL_KEY, label: t('Null'), isLeaf: true });
486
496
  }
487
497
  // Always render Constant with a typed submenu — even when only one type is
488
498
  // allowed. Matches v1 `Variable.Input`, where clicking 常量 reveals 数字 /
489
499
  // 逻辑值 / etc. so the user can see what type the constant actually is.
490
- if (normalizedTypes.length > 0) {
500
+ if (!variableOnly && normalizedTypes.length > 0) {
491
501
  items.push({
492
502
  value: CONST_KEY,
493
503
  label: t('Constant'),
@@ -498,9 +508,11 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
498
508
  })),
499
509
  });
500
510
  }
501
- items.push(...buildContextSelectorItems(metaTree).map(fromContextItem));
511
+ if (!hideVariable) {
512
+ items.push(...buildContextSelectorItems(metaTree).map(fromContextItem));
513
+ }
502
514
  return items;
503
- }, [nullable, normalizedTypes, metaTree, updateFlag, t]);
515
+ }, [hideVariable, metaTree, normalizedTypes, nullable, t, updateFlag, variableOnly]);
504
516
 
505
517
  const onSwitcherChange = useCallback<NonNullable<CascaderProps<SwitcherOption>['onChange']>>(
506
518
  (path, selectedOptions) => {
@@ -530,6 +542,10 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
530
542
  );
531
543
 
532
544
  const onClearVariable = useCallback(() => {
545
+ if (variableOnly) {
546
+ onChange?.(null);
547
+ return;
548
+ }
533
549
  const first = normalizedTypes[0];
534
550
  if (first) {
535
551
  onChange?.(defaultValueFor(first.type));
@@ -538,7 +554,7 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
538
554
  if (nullable) {
539
555
  onChange?.(null);
540
556
  }
541
- }, [nullable, normalizedTypes, onChange]);
557
+ }, [nullable, normalizedTypes, onChange, variableOnly]);
542
558
 
543
559
  const constantTypeForRendering: TypedConstantType = useMemo(() => {
544
560
  const m = detected.mode;
@@ -553,6 +569,7 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
553
569
 
554
570
  const isVariable = detected.mode === 'variable';
555
571
  const isNull = detected.mode === 'null';
572
+ const showSwitcher = switcherOptions.length > 0 && !(hideVariable && isVariable);
556
573
 
557
574
  const variableLabels = useMemo(() => {
558
575
  // `updateFlag` is read so this recomputes after the preload effect below resolves a lazy level in the tree (same
@@ -565,11 +582,14 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
565
582
  if (isVariable && detected.variablePath?.length) {
566
583
  return detected.variablePath;
567
584
  }
585
+ if (variableOnly) {
586
+ return undefined;
587
+ }
568
588
  if (isNull) {
569
589
  return [NULL_KEY];
570
590
  }
571
591
  return [CONST_KEY, constantTypeForRendering];
572
- }, [constantTypeForRendering, detected.variablePath, isNull, isVariable]);
592
+ }, [constantTypeForRendering, detected.variablePath, isNull, isVariable, variableOnly]);
573
593
 
574
594
  // Preload a saved variable's label path across lazy levels. `resolveVariableLabels` can only read already-loaded
575
595
  // `children`; when a saved reference points below a node whose children are still a lazy thunk (e.g. a relation field
@@ -678,8 +698,8 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
678
698
  minHeight: token.controlHeight,
679
699
  border: `1px solid ${token.colorBorder}`,
680
700
  borderRadius: token.borderRadius,
681
- borderTopRightRadius: 0,
682
- borderBottomRightRadius: 0,
701
+ borderTopRightRadius: showSwitcher ? 0 : token.borderRadius,
702
+ borderBottomRightRadius: showSwitcher ? 0 : token.borderRadius,
683
703
  background: disabled ? token.colorBgContainerDisabled : token.colorBgContainer,
684
704
  overflow: 'hidden',
685
705
  }}
@@ -712,6 +732,8 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
712
732
  />
713
733
  ) : null}
714
734
  </div>
735
+ ) : variableOnly ? (
736
+ <Input placeholder={placeholder} readOnly disabled={disabled} style={{ width: '100%' }} />
715
737
  ) : isNull ? (
716
738
  // v1 used the `placeholder` slot (not `value`) so the antd default placeholder colour applies — keeps the
717
739
  // field looking visibly empty/inactive rather than holding a real text value.
@@ -726,31 +748,33 @@ export function TypedVariableInput(props: TypedVariableInputProps) {
726
748
  })
727
749
  )}
728
750
  </div>
729
- <Cascader<SwitcherOption>
730
- options={switcherOptions}
731
- value={switcherValue}
732
- onChange={onSwitcherChange}
733
- loadData={loadData}
734
- disabled={disabled}
735
- changeOnSelect
736
- >
737
- <Button
738
- aria-label="variable-switcher"
751
+ {showSwitcher ? (
752
+ <Cascader<SwitcherOption>
753
+ options={switcherOptions}
754
+ value={switcherValue}
755
+ onChange={onSwitcherChange}
756
+ loadData={loadData}
739
757
  disabled={disabled}
740
- type={isVariable ? 'primary' : 'default'}
741
- style={{
742
- flexShrink: 0,
743
- // `height: auto` (instead of antd's fixed control height) lets the button stretch to the value
744
- // component's height under the compact row's default `align-items: stretch` — so it stays joined to a
745
- // tall JSON textarea. Mirrors v1's `.ant-btn { height: auto }`.
746
- height: 'auto',
747
- fontStyle: 'italic',
748
- fontFamily: '"New York", "Times New Roman", Times, serif',
749
- }}
758
+ changeOnSelect
750
759
  >
751
- x
752
- </Button>
753
- </Cascader>
760
+ <Button
761
+ aria-label="variable-switcher"
762
+ disabled={disabled}
763
+ type={isVariable ? 'primary' : 'default'}
764
+ style={{
765
+ flexShrink: 0,
766
+ // `height: auto` (instead of antd's fixed control height) lets the button stretch to the value
767
+ // component's height under the compact row's default `align-items: stretch` — so it stays joined to a
768
+ // tall JSON textarea. Mirrors v1's `.ant-btn { height: auto }`.
769
+ height: 'auto',
770
+ fontStyle: 'italic',
771
+ fontFamily: '"New York", "Times New Roman", Times, serif',
772
+ }}
773
+ >
774
+ x
775
+ </Button>
776
+ </Cascader>
777
+ ) : null}
754
778
  </Space.Compact>
755
779
  {jsonError ? (
756
780
  <div style={{ marginTop: token.marginXXS, color: token.colorError, fontSize: token.fontSizeSM }}>
@@ -201,6 +201,58 @@ describe('TypedVariableInput - variable rendering', () => {
201
201
  fireEvent.click(clear as HTMLButtonElement);
202
202
  expect(handleChange).toHaveBeenCalledWith(0);
203
203
  });
204
+
205
+ it('treats types=[] as variable-only mode with a readonly placeholder before selection', async () => {
206
+ const ctx = createContextWithEnv();
207
+ renderWithCtx(
208
+ ctx,
209
+ <TypedVariableInput
210
+ value={undefined}
211
+ types={[]}
212
+ namespaces={['$env']}
213
+ placeholder="Select variable"
214
+ onChange={() => undefined}
215
+ />,
216
+ );
217
+
218
+ const input = await screen.findByPlaceholderText('Select variable');
219
+ expect(input).toBeInTheDocument();
220
+ expect(input).toHaveAttribute('readonly');
221
+ expect(screen.queryByRole('button', { name: 'variable-switcher' })).toBeInTheDocument();
222
+ });
223
+
224
+ it('clears a variable-only selection back to null', async () => {
225
+ const ctx = createContextWithEnv();
226
+ const handleChange = vi.fn();
227
+ const { container } = renderWithCtx(
228
+ ctx,
229
+ <TypedVariableInput value="{{$env.SMTP_PORT}}" types={[]} namespaces={['$env']} onChange={handleChange} />,
230
+ );
231
+
232
+ const clear = container.querySelector('button.clear-button') as HTMLButtonElement | null;
233
+ expect(clear).not.toBeNull();
234
+ fireEvent.click(clear as HTMLButtonElement);
235
+ expect(handleChange).toHaveBeenCalledWith(null);
236
+ });
237
+
238
+ it('hides the variable switcher when hideVariable=true in variable-only mode', async () => {
239
+ const ctx = createContextWithEnv();
240
+ renderWithCtx(
241
+ ctx,
242
+ <TypedVariableInput
243
+ value="{{$env.SMTP_PORT}}"
244
+ types={[]}
245
+ namespaces={['$env']}
246
+ hideVariable
247
+ onChange={() => undefined}
248
+ />,
249
+ );
250
+
251
+ await waitFor(() => {
252
+ expect(screen.getByRole('button', { name: 'variable-tag' })).toBeInTheDocument();
253
+ });
254
+ expect(screen.queryByRole('button', { name: 'variable-switcher' })).toBeNull();
255
+ });
204
256
  });
205
257
 
206
258
  describe('TypedVariableInput - object / JSON constant', () => {
@@ -21,6 +21,8 @@ export interface CollectionFilterProps {
21
21
  collection: Collection | undefined;
22
22
  /** Previously compiled filter param used to seed the editable filter group. */
23
23
  initialValue?: CompiledFilter;
24
+ /** Default compiled filter used both for initial empty state and Reset. */
25
+ defaultValue?: CompiledFilter;
24
26
  /** Called on Submit or Reset with the compiled NocoBase filter param (`undefined` when cleared). */
25
27
  onChange: (filter: CompiledFilter) => void;
26
28
  /** Translator. Defaults to identity. */
@@ -58,6 +60,7 @@ export const CollectionFilter: FC<CollectionFilterProps> = (props) => {
58
60
  const {
59
61
  collection,
60
62
  initialValue,
63
+ defaultValue,
61
64
  onChange,
62
65
  t = identity,
63
66
  filterableFieldNames,
@@ -75,6 +78,7 @@ export const CollectionFilter: FC<CollectionFilterProps> = (props) => {
75
78
  const filterAction = useFilterActionProps({
76
79
  collection,
77
80
  initialValue,
81
+ defaultValue,
78
82
  filterableFieldNames,
79
83
  nonfilterableFieldNames,
80
84
  noIgnore,
@@ -30,6 +30,8 @@ export interface CollectionFilterPanelProps {
30
30
  collection: Collection | undefined;
31
31
  /** Previously compiled filter param used to seed the editable filter group. */
32
32
  initialValue?: CompiledFilter;
33
+ /** Default compiled filter used both for initial empty state and Reset. */
34
+ defaultValue?: CompiledFilter;
33
35
  /** Called when the condition group structure changes or `reset()` is invoked. */
34
36
  onChange?: (filter: CompiledFilter) => void;
35
37
  /** Translator. Defaults to identity. */
@@ -51,6 +53,7 @@ export const CollectionFilterPanel = forwardRef<CollectionFilterPanelRef, Collec
51
53
  const {
52
54
  collection,
53
55
  initialValue,
56
+ defaultValue,
54
57
  onChange,
55
58
  t = identity,
56
59
  filterableFieldNames,
@@ -61,6 +64,7 @@ export const CollectionFilterPanel = forwardRef<CollectionFilterPanelRef, Collec
61
64
  const filterAction = useFilterActionProps({
62
65
  collection,
63
66
  initialValue,
67
+ defaultValue,
64
68
  filterableFieldNames,
65
69
  nonfilterableFieldNames,
66
70
  noIgnore,
@@ -0,0 +1,95 @@
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, FlowEngineProvider, type Collection } from '@nocobase/flow-engine';
11
+ import { renderHook } from '@testing-library/react';
12
+ import React from 'react';
13
+ import { describe, expect, it, vi } from 'vitest';
14
+ import { useFilterActionProps } from '../useFilterActionProps';
15
+
16
+ vi.mock('../../../flow/components/filter/useFilterOptions', () => ({
17
+ useFilterOptions: () => [],
18
+ }));
19
+
20
+ vi.mock('../CollectionFilterItem', () => ({
21
+ createCollectionFilterItem: () => undefined,
22
+ }));
23
+
24
+ function makeCollection(): Collection {
25
+ return {
26
+ getFields: () => [{ name: 'title' }, { name: 'type' }],
27
+ } as unknown as Collection;
28
+ }
29
+
30
+ function makeWrapper() {
31
+ const engine = new FlowEngine();
32
+ const Wrapper: React.FC = ({ children }) => <FlowEngineProvider engine={engine}>{children}</FlowEngineProvider>;
33
+ return Wrapper;
34
+ }
35
+
36
+ describe('useFilterActionProps', () => {
37
+ it('seeds the editable group from defaultValue when initialValue is missing', () => {
38
+ const { result } = renderHook(
39
+ () =>
40
+ useFilterActionProps({
41
+ collection: makeCollection(),
42
+ defaultValue: { $and: [{ title: { $includes: '' } }, { type: { $eq: undefined } }] },
43
+ onApply: () => undefined,
44
+ }),
45
+ { wrapper: makeWrapper() },
46
+ );
47
+
48
+ expect(result.current.value).toMatchObject({
49
+ logic: '$and',
50
+ items: [
51
+ { path: 'title', operator: '$includes', value: '' },
52
+ { path: 'type', operator: '$eq', value: undefined },
53
+ ],
54
+ });
55
+ });
56
+
57
+ it('reset restores defaultValue and emits its compiled filter', () => {
58
+ const onApply = vi.fn();
59
+ const { result } = renderHook(
60
+ () =>
61
+ useFilterActionProps({
62
+ collection: makeCollection(),
63
+ defaultValue: { $and: [{ title: { $includes: '' } }, { type: { $eq: undefined } }] },
64
+ initialValue: { $and: [{ title: { $includes: 'abc' } }] },
65
+ onApply,
66
+ }),
67
+ { wrapper: makeWrapper() },
68
+ );
69
+
70
+ result.current.onReset();
71
+
72
+ expect(result.current.value).toMatchObject({
73
+ logic: '$and',
74
+ items: [
75
+ { path: 'title', operator: '$includes', value: '' },
76
+ { path: 'type', operator: '$eq', value: undefined },
77
+ ],
78
+ });
79
+ expect(onApply).toHaveBeenCalledWith(undefined, 'reset');
80
+ });
81
+
82
+ it('counts only effective compiled conditions, so empty default rows do not highlight the button', () => {
83
+ const { result } = renderHook(
84
+ () =>
85
+ useFilterActionProps({
86
+ collection: makeCollection(),
87
+ defaultValue: { $and: [{ title: { $includes: '' } }, { type: { $eq: undefined } }] },
88
+ onApply: () => undefined,
89
+ }),
90
+ { wrapper: makeWrapper() },
91
+ );
92
+
93
+ expect(result.current.conditionCount).toBe(0);
94
+ });
95
+ });
@@ -43,6 +43,14 @@ const isCondition = (item: FilterGroupItem): item is CollectionFilterItemValue =
43
43
  typeof (item as CollectionFilterItemValue).path === 'string' &&
44
44
  Object.prototype.hasOwnProperty.call(item, 'operator');
45
45
 
46
+ const cloneFilterGroupItem = (item: FilterGroupItem): FilterGroupItem =>
47
+ isGroup(item) ? { logic: item.logic, items: item.items.map((child) => cloneFilterGroupItem(child)) } : { ...item };
48
+
49
+ const cloneFilterGroup = (group: FilterGroupValue): FilterGroupValue => ({
50
+ logic: group.logic,
51
+ items: group.items.map((item) => cloneFilterGroupItem(item)),
52
+ });
53
+
46
54
  /**
47
55
  * `true` when the rhs of a condition is "no real value yet" — covers `undefined` / `null` / empty string / empty array / empty plain object. Mirrors v1's `removeNullCondition` `isEmpty` predicate so half-filled rows ("Locked time → is → (no date picked yet)") get dropped on Submit instead of being sent to the server as `{lockedTs:{}}` and triggering a 500.
48
56
  */
@@ -164,6 +172,8 @@ export interface UseFilterActionPropsArgs extends UseFilterOptionsArgs {
164
172
  collection: Collection | undefined;
165
173
  /** Previously compiled filter param used to seed the editable filter group. */
166
174
  initialValue?: CompiledFilter;
175
+ /** Default compiled filter used both for initial empty state and Reset. */
176
+ defaultValue?: CompiledFilter;
167
177
  /**
168
178
  * Called when the user submits or resets the filter popover. Receives the compiled filter param (`undefined` when cleared) and which footer button triggered the call. Typical implementation: `(filter, action) => { listRequest.run(filter); if (action === 'submit') closePopover(); }`.
169
179
  */
@@ -216,12 +226,23 @@ export interface UseFilterActionPropsResult {
216
226
  * ```
217
227
  */
218
228
  export function useFilterActionProps(args: UseFilterActionPropsArgs): UseFilterActionPropsResult {
219
- const { collection, initialValue, onApply, filterableFieldNames, nonfilterableFieldNames, noIgnore, t } = args;
229
+ const {
230
+ collection,
231
+ initialValue,
232
+ defaultValue,
233
+ onApply,
234
+ filterableFieldNames,
235
+ nonfilterableFieldNames,
236
+ noIgnore,
237
+ t,
238
+ } = args;
239
+ const seedValue = initialValue ?? defaultValue;
240
+ const defaultGroup = decompileFilterGroup(defaultValue) || createEmptyGroup();
220
241
 
221
242
  // Held in a ref so the group object identity is stable for the lifetime of the host component — `<FilterContent>` mutates this object directly (push/splice on `items`, swap `logic`), and a fresh observable on every render would reset that internal state.
222
243
  const valueRef = useRef<FilterGroupValue>();
223
244
  if (!valueRef.current) {
224
- valueRef.current = observable(decompileFilterGroup(initialValue) || createEmptyGroup()) as FilterGroupValue;
245
+ valueRef.current = observable(decompileFilterGroup(seedValue) || createEmptyGroup()) as FilterGroupValue;
225
246
  }
226
247
  const value = valueRef.current;
227
248
 
@@ -240,9 +261,10 @@ export function useFilterActionProps(args: UseFilterActionPropsArgs): UseFilterA
240
261
  });
241
262
 
242
263
  const onReset = useMemoizedFn(() => {
243
- value.logic = '$and';
244
- value.items = [];
245
- onApply(undefined, 'reset');
264
+ const next = cloneFilterGroup(defaultGroup);
265
+ value.logic = next.logic;
266
+ value.items = next.items;
267
+ onApply(compileFilterGroup(value), 'reset');
246
268
  });
247
269
 
248
270
  const translate = useMemoizedFn((key: string) => (t ? t(key) : key));
@@ -261,7 +283,16 @@ export function useFilterActionProps(args: UseFilterActionPropsArgs): UseFilterA
261
283
  );
262
284
 
263
285
  // Re-read on each render so `observer`-wrapped hosts re-render when the reactive `items` array length changes. No useMemo needed — the `value` object's identity is stable (held in a ref), but its observable `items.length` is what we actually care about, and the eslint exhaustive-deps rule rightly complains about depending on a mutable property of a stable ref.
264
- const conditionCount = value.items.length;
286
+ const conditionCount = (() => {
287
+ const compiled = compileFilterGroup(value);
288
+ if (compiled?.$and && Array.isArray(compiled.$and)) {
289
+ return compiled.$and.length;
290
+ }
291
+ if (compiled?.$or && Array.isArray(compiled.$or)) {
292
+ return compiled.$or.length;
293
+ }
294
+ return 0;
295
+ })();
265
296
 
266
297
  return { value, options, FilterItem, ctx, onSubmit, onReset, conditionCount };
267
298
  }
@@ -0,0 +1,76 @@
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 {
11
+ define,
12
+ observable,
13
+ type FlowModelContext,
14
+ type SubModelItem,
15
+ type SubModelItemsType,
16
+ } from '@nocobase/flow-engine';
17
+
18
+ export type EntryActionScope = 'action-panel' | 'app-switcher' | string;
19
+
20
+ export type EntryActionProvider = (ctx: FlowModelContext) => SubModelItem[] | Promise<SubModelItem[]>;
21
+
22
+ type ProviderRecord = {
23
+ name: string;
24
+ scope: EntryActionScope;
25
+ provider: EntryActionProvider;
26
+ sort: number;
27
+ };
28
+
29
+ export class EntryActionManager {
30
+ private readonly providers = new Map<string, ProviderRecord>();
31
+ revision = 0;
32
+
33
+ constructor() {
34
+ define(this, {
35
+ revision: observable.ref,
36
+ });
37
+ }
38
+
39
+ register(name: string, options: { scope: EntryActionScope; provider: EntryActionProvider; sort?: number }) {
40
+ this.providers.set(name, {
41
+ name,
42
+ scope: options.scope,
43
+ provider: options.provider,
44
+ sort: options.sort ?? 0,
45
+ });
46
+ this.invalidate();
47
+ }
48
+
49
+ unregister(name: string) {
50
+ this.providers.delete(name);
51
+ this.invalidate();
52
+ }
53
+
54
+ invalidate() {
55
+ this.revision += 1;
56
+ }
57
+
58
+ getItems(scope: EntryActionScope): SubModelItemsType {
59
+ return async (ctx) => {
60
+ const providers = [...this.providers.values()]
61
+ .filter((item) => item.scope === scope)
62
+ .sort((a, b) => a.sort - b.sort);
63
+ const groups = await Promise.all(
64
+ providers.map(async (item) => {
65
+ try {
66
+ return await item.provider(ctx);
67
+ } catch (error) {
68
+ console.error(`[NocoBase] Failed to load entry action provider "${item.name}".`, error);
69
+ return [];
70
+ }
71
+ }),
72
+ );
73
+ return groups.flat();
74
+ };
75
+ }
76
+ }
@@ -0,0 +1,10 @@
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
+ export * from './EntryActionManager';
@@ -14,7 +14,7 @@ import {
14
14
  useFlowModelById,
15
15
  useFlowViewContext,
16
16
  } from '@nocobase/flow-engine';
17
- import type { FlowModel, FlowModelRendererProps, ModelConstructor } from '@nocobase/flow-engine';
17
+ import type { FlowEngineContext, FlowModel, FlowModelRendererProps, ModelConstructor } from '@nocobase/flow-engine';
18
18
  import { useRequest } from 'ahooks';
19
19
  import React from 'react';
20
20
  import FlowRoute from './components/FlowRoute';
@@ -57,10 +57,36 @@ type FlowPageProps = {
57
57
  showFlowSettings?: FlowModelRendererProps['showFlowSettings'];
58
58
  };
59
59
 
60
+ type FlowPageViewContext = FlowEngineContext & {
61
+ view?: {
62
+ inputArgs?: {
63
+ isMobileLayout?: unknown;
64
+ };
65
+ };
66
+ };
67
+
68
+ const bindViewLayoutState = (model: FlowModel, ctx?: FlowPageViewContext | null) => {
69
+ const hasViewMobileLayout = typeof ctx?.view?.inputArgs?.isMobileLayout === 'boolean';
70
+ const hasContextMobileLayout = typeof ctx?.isMobileLayout === 'boolean';
71
+ if (!hasViewMobileLayout && !hasContextMobileLayout) {
72
+ return;
73
+ }
74
+
75
+ model.context.defineProperty('isMobileLayout', {
76
+ get: () => {
77
+ if (typeof ctx?.isMobileLayout === 'boolean') {
78
+ return ctx.isMobileLayout;
79
+ }
80
+ return !!ctx?.view?.inputArgs?.isMobileLayout;
81
+ },
82
+ cache: false,
83
+ });
84
+ };
85
+
60
86
  export const FlowPage = React.memo((props: FlowPageProps & Record<string, unknown>) => {
61
87
  const { pageModelClass = 'ChildPageModel', parentId, onModelLoaded, defaultTabTitle, ...rest } = props;
62
88
  const flowEngine = useFlowEngine();
63
- const ctx = useFlowViewContext();
89
+ const ctx = useFlowViewContext<FlowPageViewContext>();
64
90
  const { loading, data, error } = useRequest(
65
91
  async () => {
66
92
  const ModelClass = await flowEngine.getModelClassAsync(pageModelClass);
@@ -105,6 +131,7 @@ export const FlowPage = React.memo((props: FlowPageProps & Record<string, unknow
105
131
  const data = await flowEngine.loadOrCreateModel(options, { skipSave: !flowEngine.context.flowSettingsEnabled });
106
132
  if (data?.uid && onModelLoaded) {
107
133
  data.context.addDelegate(ctx);
134
+ bindViewLayoutState(data, ctx);
108
135
  data.removeParentDelegate();
109
136
  onModelLoaded(data.uid, data);
110
137
  }