@object-ui/fields 16.1.0 → 17.2.0

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 (129) hide show
  1. package/CHANGELOG.md +626 -0
  2. package/dist/FieldEditWidget.d.ts +9 -2
  3. package/dist/__tests__/spec-symbol-batch7.test.d.ts +8 -0
  4. package/dist/__tests__/widget-props-contract.test.d.ts +8 -0
  5. package/dist/field-type-alias.d.ts +16 -0
  6. package/dist/index.cjs +5 -5
  7. package/dist/index.d.ts +14 -11
  8. package/dist/index.js +2426 -2100
  9. package/dist/widgets/AddressField.d.ts +2 -2
  10. package/dist/widgets/AutoNumberField.d.ts +2 -2
  11. package/dist/widgets/AvatarField.d.ts +2 -2
  12. package/dist/widgets/BooleanField.d.ts +2 -2
  13. package/dist/widgets/CapabilityMultiSelectField.d.ts +2 -2
  14. package/dist/widgets/CheckboxesField.d.ts +2 -2
  15. package/dist/widgets/CodeField.d.ts +2 -2
  16. package/dist/widgets/ColorField.d.ts +2 -2
  17. package/dist/widgets/CurrencyField.d.ts +2 -2
  18. package/dist/widgets/DateField.d.ts +2 -2
  19. package/dist/widgets/DateTimeField.d.ts +2 -2
  20. package/dist/widgets/EmailField.d.ts +2 -2
  21. package/dist/widgets/FileField.d.ts +2 -2
  22. package/dist/widgets/FilterConditionField.d.ts +34 -2
  23. package/dist/widgets/FormulaField.d.ts +2 -2
  24. package/dist/widgets/GeolocationField.d.ts +2 -2
  25. package/dist/widgets/GridField.d.ts +2 -2
  26. package/dist/widgets/ImageField.d.ts +2 -2
  27. package/dist/widgets/ImageLightbox.d.ts +30 -0
  28. package/dist/widgets/ImageLightbox.test.d.ts +1 -0
  29. package/dist/widgets/LocationField.d.ts +2 -2
  30. package/dist/widgets/LookupField.d.ts +2 -2
  31. package/dist/widgets/LookupField.hydration.test.d.ts +1 -0
  32. package/dist/widgets/LookupField.idField.test.d.ts +1 -0
  33. package/dist/widgets/MasterDetailField.d.ts +2 -2
  34. package/dist/widgets/MultiSelectField.d.ts +2 -2
  35. package/dist/widgets/NumberField.d.ts +2 -2
  36. package/dist/widgets/ObjectField.d.ts +2 -2
  37. package/dist/widgets/ObjectRefField.d.ts +2 -2
  38. package/dist/widgets/PasswordField.d.ts +2 -2
  39. package/dist/widgets/PercentField.d.ts +2 -2
  40. package/dist/widgets/PhoneField.d.ts +2 -2
  41. package/dist/widgets/QRCodeField.d.ts +2 -2
  42. package/dist/widgets/RadioField.d.ts +2 -2
  43. package/dist/widgets/RatingField.d.ts +2 -2
  44. package/dist/widgets/RecipientPickerField.d.ts +2 -2
  45. package/dist/widgets/RecipientPickerField.test.d.ts +0 -0
  46. package/dist/widgets/RichTextField.d.ts +2 -2
  47. package/dist/widgets/SelectField.d.ts +2 -2
  48. package/dist/widgets/SignatureField.d.ts +2 -2
  49. package/dist/widgets/SliderField.d.ts +2 -2
  50. package/dist/widgets/SummaryField.d.ts +2 -2
  51. package/dist/widgets/TagsField.d.ts +2 -2
  52. package/dist/widgets/TextAreaField.d.ts +2 -2
  53. package/dist/widgets/TextField.d.ts +2 -2
  54. package/dist/widgets/TimeField.d.ts +2 -2
  55. package/dist/widgets/UrlField.d.ts +2 -2
  56. package/dist/widgets/UserField.d.ts +2 -2
  57. package/dist/widgets/VectorField.d.ts +2 -2
  58. package/dist/widgets/__tests__/FilterConditionField.matchAll.test.d.ts +8 -0
  59. package/dist/widgets/__tests__/FilterConditionField.operators.test.d.ts +8 -0
  60. package/dist/widgets/file-value.d.ts +99 -0
  61. package/dist/widgets/file-value.test.d.ts +1 -0
  62. package/dist/widgets/types.d.ts +119 -3
  63. package/dist/widgets/useFieldTranslation.d.ts +2 -0
  64. package/package.json +9 -8
  65. package/src/FieldEditWidget.test.ts +74 -2
  66. package/src/FieldEditWidget.tsx +50 -8
  67. package/src/__tests__/spec-symbol-batch7.test.ts +112 -0
  68. package/src/__tests__/widget-props-contract.test.tsx +129 -0
  69. package/src/complex-widgets.test.tsx +3 -3
  70. package/src/datetime-widgets.test.tsx +2 -2
  71. package/src/field-type-alias.ts +100 -0
  72. package/src/index.tsx +97 -134
  73. package/src/widgets/AddressField.tsx +2 -2
  74. package/src/widgets/AutoNumberField.tsx +2 -2
  75. package/src/widgets/AvatarField.tsx +2 -2
  76. package/src/widgets/BooleanField.tsx +2 -2
  77. package/src/widgets/CapabilityMultiSelectField.tsx +4 -4
  78. package/src/widgets/CheckboxesField.tsx +12 -9
  79. package/src/widgets/CodeField.tsx +2 -2
  80. package/src/widgets/ColorField.tsx +2 -2
  81. package/src/widgets/CurrencyField.tsx +2 -2
  82. package/src/widgets/DateField.tsx +2 -2
  83. package/src/widgets/DateTimeField.tsx +2 -2
  84. package/src/widgets/EmailField.tsx +2 -2
  85. package/src/widgets/FileField.tsx +90 -59
  86. package/src/widgets/FilterConditionField.tsx +112 -12
  87. package/src/widgets/FormulaField.tsx +2 -2
  88. package/src/widgets/GeolocationField.tsx +2 -2
  89. package/src/widgets/GridField.tsx +3 -3
  90. package/src/widgets/ImageField.tsx +73 -35
  91. package/src/widgets/ImageLightbox.test.tsx +52 -0
  92. package/src/widgets/ImageLightbox.tsx +108 -0
  93. package/src/widgets/LocationField.tsx +2 -2
  94. package/src/widgets/LookupField.hydration.test.tsx +136 -0
  95. package/src/widgets/LookupField.idField.test.tsx +61 -0
  96. package/src/widgets/LookupField.tsx +116 -19
  97. package/src/widgets/MasterDetailField.tsx +2 -2
  98. package/src/widgets/MultiSelectField.tsx +10 -7
  99. package/src/widgets/NumberField.tsx +2 -2
  100. package/src/widgets/ObjectField.tsx +2 -2
  101. package/src/widgets/ObjectRefField.tsx +13 -8
  102. package/src/widgets/PasswordField.tsx +2 -2
  103. package/src/widgets/PeoplePicker.test.tsx +20 -0
  104. package/src/widgets/PeoplePicker.tsx +15 -3
  105. package/src/widgets/PercentField.tsx +2 -2
  106. package/src/widgets/PhoneField.tsx +2 -2
  107. package/src/widgets/QRCodeField.tsx +2 -2
  108. package/src/widgets/RadioField.tsx +10 -7
  109. package/src/widgets/RatingField.tsx +2 -2
  110. package/src/widgets/RecipientPickerField.test.tsx +157 -0
  111. package/src/widgets/RecipientPickerField.tsx +40 -20
  112. package/src/widgets/RichTextField.tsx +2 -2
  113. package/src/widgets/SelectField.tsx +5 -5
  114. package/src/widgets/SignatureField.tsx +2 -2
  115. package/src/widgets/SliderField.tsx +2 -2
  116. package/src/widgets/SummaryField.tsx +2 -2
  117. package/src/widgets/TagsField.tsx +3 -3
  118. package/src/widgets/TextAreaField.tsx +6 -3
  119. package/src/widgets/TextField.tsx +2 -2
  120. package/src/widgets/TimeField.tsx +2 -2
  121. package/src/widgets/UrlField.tsx +2 -2
  122. package/src/widgets/UserField.tsx +2 -2
  123. package/src/widgets/VectorField.tsx +2 -2
  124. package/src/widgets/__tests__/FilterConditionField.matchAll.test.ts +66 -0
  125. package/src/widgets/__tests__/FilterConditionField.operators.test.ts +142 -0
  126. package/src/widgets/file-value.test.ts +230 -0
  127. package/src/widgets/file-value.ts +246 -0
  128. package/src/widgets/types.ts +129 -6
  129. package/src/widgets/useFieldTranslation.ts +30 -0
@@ -0,0 +1,66 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * Empty-criteria guard for the sharing-rule criteria builder
11
+ * (objectstack#3896).
12
+ *
13
+ * This widget used to tell an admin that an empty criteria meant "All
14
+ * records" — the most dangerous thing it could say, because it was describing
15
+ * a bug as a feature. A sharing rule with no predicate was stored as
16
+ * `criteria_json: null` and then evaluated as `find(object, { filter: {} })`,
17
+ * i.e. every record of the object granted to the recipient. `SharingRuleSchema`
18
+ * had always forbidden that shape ("never seeded as a permissive match-all",
19
+ * ADR-0049); the REST and data-API entries just never checked.
20
+ *
21
+ * The server now refuses to save such a rule and shares nothing for one
22
+ * already stored. These tests pin the client-side mirror of that predicate, so
23
+ * the widget warns while the admin is still looking at the empty builder
24
+ * rather than after a rejected save.
25
+ */
26
+ import { describe, it, expect } from 'vitest';
27
+ import { isMatchAllCriteria } from '../FilterConditionField';
28
+
29
+ describe('isMatchAllCriteria — shapes that would share every record', () => {
30
+ it('flags the empty and vacuous shapes', () => {
31
+ for (const shape of [
32
+ undefined,
33
+ null,
34
+ {}, // what a blank builder / blank textarea parses to
35
+ [],
36
+ true,
37
+ 42,
38
+ { $and: [] },
39
+ { $or: [] },
40
+ { $and: [{}] },
41
+ { $or: [{ stage: 'won' }, {}] }, // one unconstrained branch opens the OR
42
+ ]) {
43
+ expect(isMatchAllCriteria(shape), `${JSON.stringify(shape) ?? String(shape)}`).toBe(true);
44
+ }
45
+ });
46
+
47
+ it('passes anything that actually narrows the result set', () => {
48
+ for (const shape of [
49
+ { stage: 'won' },
50
+ { amount: { $gte: 100000 } },
51
+ [{ stage: 'won' }],
52
+ { $and: [{ stage: 'won' }] },
53
+ { $or: [{ a: 1 }, { b: 2 }] },
54
+ { health: 'red', budget: { $gt: 1 } },
55
+ ]) {
56
+ expect(isMatchAllCriteria(shape), JSON.stringify(shape)).toBe(false);
57
+ }
58
+ });
59
+
60
+ it('agrees with the server on the reported case: a rule saved with no criteria', () => {
61
+ // The builder emits '' for an empty group, which the widget parses to {}.
62
+ expect(isMatchAllCriteria({})).toBe(true);
63
+ // …and one real condition is enough to clear the gate.
64
+ expect(isMatchAllCriteria({ health: 'red' })).toBe(false);
65
+ });
66
+ });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * Operator spelling guard for the sharing-rule criteria builder (#2901).
11
+ *
12
+ * `condToMongo` emitted `$ncontains` — a token that appears nowhere in
13
+ * `@objectstack/spec` and that objectui's own `convertFiltersToAST` throws on,
14
+ * naming the correct spelling (`$notContains`) in its error message. So every
15
+ * "does not contain" rule authored here validated in the UI and was then
16
+ * rejected downstream. Nothing caught it because the builder's operator list is
17
+ * hand-written and never compared against the spec vocabulary.
18
+ *
19
+ * These tests pin the emitted spellings against `FieldOperatorsSchema`'s keys
20
+ * and pin the round-trip, including the pre-fix spelling that stored criteria
21
+ * still carry.
22
+ */
23
+ import { describe, it, expect } from 'vitest';
24
+ import { FieldOperatorsSchema } from '@objectstack/spec/data';
25
+ import { condToMongo, kvToCondition } from '../FilterConditionField';
26
+
27
+ /**
28
+ * The `$`-prefixed operator keys of the spec's `FieldOperatorsSchema` —
29
+ * DERIVED from the schema (#2942), so a 16th operator landing in the spec
30
+ * fails the reachability test below instead of drifting unnoticed.
31
+ */
32
+ const SPEC_OPERATORS = new Set(
33
+ Object.keys((FieldOperatorsSchema as unknown as { shape?: Record<string, unknown> }).shape ?? {}),
34
+ );
35
+
36
+ const noTypes = () => undefined;
37
+
38
+ /** Pull the operator keys out of a `{ field: { $op: v } }` fragment. */
39
+ function operatorsOf(frag: Record<string, any> | null): string[] {
40
+ if (!frag) return [];
41
+ return Object.values(frag).flatMap((v) =>
42
+ v !== null && typeof v === 'object' && !Array.isArray(v) ? Object.keys(v) : [],
43
+ );
44
+ }
45
+
46
+ describe('condToMongo emits only spec operator spellings', () => {
47
+ const builderOperators = [
48
+ 'equals', 'notEquals', 'contains', 'notContains', 'isEmpty', 'isNotEmpty',
49
+ 'greaterThan', 'lessThan', 'greaterOrEqual', 'lessOrEqual', 'in', 'notIn',
50
+ 'before', 'after',
51
+ 'startsWith', 'endsWith', 'isNull', 'isNotNull', 'exists', 'notExists',
52
+ ];
53
+
54
+ it.each(builderOperators)('%s emits a spec-defined operator', (operator) => {
55
+ const frag = condToMongo(
56
+ { id: 'c1', field: 'name', operator, value: operator === 'in' || operator === 'notIn' ? ['a'] : 'a' } as any,
57
+ noTypes,
58
+ );
59
+ const unknown = operatorsOf(frag).filter((op) => !SPEC_OPERATORS.has(op));
60
+ expect(unknown, `${operator} emits an operator @objectstack/spec does not define`).toEqual([]);
61
+ });
62
+
63
+ it('notContains emits $notContains, not the pre-fix $ncontains', () => {
64
+ const frag = condToMongo({ id: 'c1', field: 'name', operator: 'notContains', value: 'x' } as any, noTypes);
65
+ expect(frag).toEqual({ name: { $notContains: 'x' } });
66
+ });
67
+
68
+ it('between emits a range the spec defines', () => {
69
+ const frag = condToMongo({ id: 'c1', field: 'age', operator: 'between', value: [1, 5] } as any, noTypes);
70
+ expect(operatorsOf(frag).every((op) => SPEC_OPERATORS.has(op))).toBe(true);
71
+ });
72
+ });
73
+
74
+ describe('every spec field operator is reachable from the builder (#2942)', () => {
75
+ it('reads a non-empty operator vocabulary from the spec', () => {
76
+ expect([...SPEC_OPERATORS].length, 'could not read FieldOperatorsSchema.shape').toBeGreaterThan(0);
77
+ });
78
+
79
+ it('some builder operator emits every spec $-token', () => {
80
+ const builderOperators = [
81
+ 'equals', 'notEquals', 'contains', 'notContains', 'isEmpty', 'isNotEmpty',
82
+ 'greaterThan', 'lessThan', 'greaterOrEqual', 'lessOrEqual', 'in', 'notIn',
83
+ 'before', 'after', 'between',
84
+ 'startsWith', 'endsWith', 'isNull', 'isNotNull', 'exists', 'notExists',
85
+ ];
86
+ const emitted = new Set<string>();
87
+ for (const operator of builderOperators) {
88
+ const value = operator === 'in' || operator === 'notIn' ? ['a'] : operator === 'between' ? [1, 5] : 'a';
89
+ const frag = condToMongo({ id: 'c1', field: 'f', operator, value } as any, noTypes);
90
+ for (const op of operatorsOf(frag)) emitted.add(op);
91
+ }
92
+ // `$eq` is the spec's IMPLICIT equality form — `equals` deliberately
93
+ // emits the bare `{ field: value }` shape, never an explicit `$eq`.
94
+ // `$between` stays covered by the `$gte`+`$lte` pair `between` emits
95
+ // (kvToCondition reads that pair back as `between`).
96
+ const unreachable = [...SPEC_OPERATORS].filter(
97
+ (op) => op !== '$eq' && op !== '$between' && !emitted.has(op),
98
+ );
99
+ expect(
100
+ unreachable,
101
+ 'FieldOperatorsSchema accepts these but no builder operator can author them',
102
+ ).toEqual([]);
103
+ });
104
+ });
105
+
106
+ describe('kvToCondition round-trips what condToMongo writes', () => {
107
+ const cases: Array<[string, unknown]> = [
108
+ ['notEquals', 'a'],
109
+ ['contains', 'a'],
110
+ ['notContains', 'a'],
111
+ ['greaterThan', 1],
112
+ ['lessThan', 1],
113
+ ['greaterOrEqual', 1],
114
+ ['lessOrEqual', 1],
115
+ ['startsWith', 'a'],
116
+ ['endsWith', 'a'],
117
+ ['isNull', ''],
118
+ ['isNotNull', ''],
119
+ ['exists', ''],
120
+ ['notExists', ''],
121
+ ];
122
+
123
+ it.each(cases)('%s survives the round trip', (operator, value) => {
124
+ const frag = condToMongo({ id: 'c1', field: 'f', operator, value } as any, noTypes)!;
125
+ const [[field, v]] = Object.entries(frag);
126
+ expect(kvToCondition(field, v, 0)).toMatchObject({ field: 'f', operator });
127
+ });
128
+
129
+ it('still reads the pre-fix $ncontains so stored criteria keep loading', () => {
130
+ // Dropping this would make rules saved before the fix fail to load entirely
131
+ // ("criteria can't be represented") rather than migrate.
132
+ expect(kvToCondition('name', { $ncontains: 'x' }, 0)).toMatchObject({
133
+ field: 'name',
134
+ operator: 'notContains',
135
+ value: 'x',
136
+ });
137
+ });
138
+
139
+ it('rejects an operator it cannot represent rather than guessing', () => {
140
+ expect(kvToCondition('name', { $nope: 'x' }, 0)).toBeNull();
141
+ });
142
+ });
@@ -0,0 +1,230 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import {
3
+ isFileIdToken,
4
+ fileIdOf,
5
+ readFileValue,
6
+ readFileValues,
7
+ isImageValue,
8
+ fileValueForSubmit,
9
+ uploadResultView,
10
+ withRecentUploads,
11
+ } from './file-value';
12
+
13
+ const uploadResult = (over: Record<string, unknown> = {}) => ({
14
+ url: 'https://app.example.com/api/v1/storage/files/file_a',
15
+ name: 'a.png',
16
+ size: 1024,
17
+ mimeType: 'image/png',
18
+ ...over,
19
+ });
20
+
21
+ describe('isFileIdToken', () => {
22
+ it.each(['file_a', 'abc123', '0e2f4c1a-9b7d-4e3f-8a1b-2c3d4e5f6a7b', 'A-_9'])(
23
+ 'accepts the minted id %s',
24
+ (v) => expect(isFileIdToken(v)).toBe(true),
25
+ );
26
+
27
+ it.each([
28
+ 'https://cdn.example.com/a.png',
29
+ '/api/v1/storage/files/file_a',
30
+ 'data:image/png;base64,aGk=',
31
+ 'blob:http://localhost/abc',
32
+ 'a.png',
33
+ '',
34
+ ])('rejects the URL-shaped or dotted value %s', (v) => expect(isFileIdToken(v)).toBe(false));
35
+
36
+ it('rejects non-strings and over-long values', () => {
37
+ expect(isFileIdToken(null)).toBe(false);
38
+ expect(isFileIdToken(42)).toBe(false);
39
+ expect(isFileIdToken('a'.repeat(65))).toBe(false);
40
+ });
41
+ });
42
+
43
+ describe('fileIdOf', () => {
44
+ it('reads a bare reference', () => {
45
+ expect(fileIdOf('file_a')).toBe('file_a');
46
+ });
47
+
48
+ it('prefers file_id, then id', () => {
49
+ expect(fileIdOf({ file_id: 'legacy', id: 'expanded' })).toBe('legacy');
50
+ expect(fileIdOf({ id: 'expanded' })).toBe('expanded');
51
+ });
52
+
53
+ it('returns undefined when there is no id to read', () => {
54
+ expect(fileIdOf({ url: 'https://cdn.example.com/a.png', name: 'a.png' })).toBeUndefined();
55
+ expect(fileIdOf('https://cdn.example.com/a.png')).toBeUndefined();
56
+ expect(fileIdOf(null)).toBeUndefined();
57
+ });
58
+ });
59
+
60
+ describe('readFileValue', () => {
61
+ /**
62
+ * The casing split is the reason this module exists: the platform's expanded
63
+ * form is camelCase `mimeType`, the legacy inline blob is snake_case
64
+ * `mime_type`. A widget reading only one silently stops recognising images
65
+ * the moment the backend switches form.
66
+ */
67
+ it('reads the expanded form (camelCase mimeType)', () => {
68
+ const view = readFileValue({
69
+ id: 'file_a',
70
+ name: 'a.png',
71
+ size: 1024,
72
+ mimeType: 'image/png',
73
+ url: '/api/v1/storage/files/file_a',
74
+ });
75
+
76
+ expect(view).toMatchObject({
77
+ id: 'file_a',
78
+ name: 'a.png',
79
+ size: 1024,
80
+ mimeType: 'image/png',
81
+ url: '/api/v1/storage/files/file_a',
82
+ });
83
+ expect(isImageValue(view)).toBe(true);
84
+ });
85
+
86
+ it('reads the legacy inline blob (snake_case mime_type)', () => {
87
+ const view = readFileValue({
88
+ file_id: 'file_a',
89
+ name: 'a.png',
90
+ original_name: 'original.png',
91
+ size: 1024,
92
+ mime_type: 'image/png',
93
+ url: 'https://cdn.example.com/a.png',
94
+ });
95
+
96
+ expect(view).toMatchObject({ id: 'file_a', name: 'a.png', mimeType: 'image/png' });
97
+ expect(isImageValue(view)).toBe(true);
98
+ });
99
+
100
+ it('falls back to original_name when name is absent', () => {
101
+ expect(readFileValue({ original_name: 'orig.pdf' }).name).toBe('orig.pdf');
102
+ });
103
+
104
+ it('derives a name from the URL when the value carries none', () => {
105
+ expect(readFileValue({ url: 'https://cdn.example.com/docs/report%20v2.pdf' }).name).toBe(
106
+ 'report v2.pdf',
107
+ );
108
+ expect(readFileValue('https://cdn.example.com/a.png').name).toBe('a.png');
109
+ });
110
+
111
+ it('resolves a bare reference to the stable download URL', () => {
112
+ const view = readFileValue('file_a', 'File');
113
+
114
+ // The read path may leave a value in its bare-reference form (seen on the
115
+ // edit-form data path); the stable endpoint is derivable from the id, so a
116
+ // thumbnail still renders instead of a broken `<img src="">`.
117
+ expect(view).toMatchObject({ id: 'file_a', name: 'File' });
118
+ expect(view.url).toBe('/api/v1/storage/files/file_a');
119
+ });
120
+
121
+ it('derives the URL of an object that carries an id but no url', () => {
122
+ const view = readFileValue({ id: 'file_b', name: 'b.png' });
123
+ expect(view.url).toBe('/api/v1/storage/files/file_b');
124
+ });
125
+
126
+ it('treats a URL string as a URL, never as a reference', () => {
127
+ const view = readFileValue('/api/v1/storage/files/file_a');
128
+ expect(view.id).toBeUndefined();
129
+ expect(view.url).toBe('/api/v1/storage/files/file_a');
130
+ });
131
+
132
+ it('uses the supplied fallback name so widgets stay localised', () => {
133
+ expect(readFileValue({}, '文件').name).toBe('文件');
134
+ expect(readFileValue(null, '文件').name).toBe('文件');
135
+ });
136
+
137
+ it('is not an image when the MIME type says otherwise or is missing', () => {
138
+ expect(isImageValue(readFileValue({ mimeType: 'application/pdf' }))).toBe(false);
139
+ expect(isImageValue(readFileValue({ name: 'a.png' }))).toBe(false);
140
+ });
141
+ });
142
+
143
+ describe('readFileValues', () => {
144
+ it('normalises single, array and empty values', () => {
145
+ expect(readFileValues(null)).toEqual([]);
146
+ expect(readFileValues([])).toEqual([]);
147
+ expect(readFileValues('file_a')).toHaveLength(1);
148
+ expect(readFileValues(['file_a', 'file_b'])).toHaveLength(2);
149
+ });
150
+
151
+ it('drops null entries inside an array', () => {
152
+ expect(readFileValues(['file_a', null, 'file_b'])).toHaveLength(2);
153
+ });
154
+
155
+ it('handles a mixed-form array during the transition', () => {
156
+ const views = readFileValues([
157
+ 'file_a',
158
+ { id: 'file_b', name: 'b.png', mimeType: 'image/png' },
159
+ { name: 'c.png', mime_type: 'image/png', url: 'https://cdn.example.com/c.png' },
160
+ ]);
161
+
162
+ expect(views.map((v) => v.id)).toEqual(['file_a', 'file_b', undefined]);
163
+ expect(views.map(isImageValue)).toEqual([false, true, true]);
164
+ });
165
+ });
166
+
167
+ describe('fileValueForSubmit', () => {
168
+ it('submits the bare reference when the adapter surfaced a fileId', () => {
169
+ expect(fileValueForSubmit(uploadResult({ meta: { fileId: 'file_a' } }), 'orig.png')).toBe(
170
+ 'file_a',
171
+ );
172
+ });
173
+
174
+ /**
175
+ * Back-compat: the object-URL fallback adapter, or a backend predating
176
+ * file-as-reference, surfaces no fileId. The same build must keep working
177
+ * there, so it submits the legacy blob unchanged.
178
+ */
179
+ it('falls back to the legacy inline blob when there is no fileId', () => {
180
+ expect(fileValueForSubmit(uploadResult(), 'orig.png')).toEqual({
181
+ name: 'a.png',
182
+ original_name: 'orig.png',
183
+ size: 1024,
184
+ mime_type: 'image/png',
185
+ url: 'https://app.example.com/api/v1/storage/files/file_a',
186
+ });
187
+ });
188
+
189
+ it('ignores a meta.fileId that is not id-shaped', () => {
190
+ const v = fileValueForSubmit(uploadResult({ meta: { fileId: 'https://evil.example/x' } }));
191
+ expect(typeof v).toBe('object');
192
+ });
193
+
194
+ it('round-trips through readFileValue in both modes', () => {
195
+ const asRef = fileValueForSubmit(uploadResult({ meta: { fileId: 'file_a' } }));
196
+ const asBlob = fileValueForSubmit(uploadResult(), 'orig.png');
197
+
198
+ expect(readFileValue(asRef).id).toBe('file_a');
199
+ expect(readFileValue(asBlob).mimeType).toBe('image/png');
200
+ });
201
+ });
202
+
203
+ describe('withRecentUploads', () => {
204
+ it('fills in display details for a bare reference just uploaded', () => {
205
+ const view = uploadResultView(uploadResult({ meta: { fileId: 'file_a' } }), 'orig.png');
206
+ const merged = withRecentUploads(readFileValues('file_a'), { file_a: view });
207
+
208
+ expect(merged[0]).toMatchObject({
209
+ id: 'file_a',
210
+ name: 'a.png',
211
+ mimeType: 'image/png',
212
+ url: 'https://app.example.com/api/v1/storage/files/file_a',
213
+ });
214
+ // The raw value stays the reference — display enrichment must not change
215
+ // what the field submits.
216
+ expect(merged[0].raw).toBe('file_a');
217
+ });
218
+
219
+ it('leaves a value the backend already expanded alone', () => {
220
+ const stale = uploadResultView(uploadResult({ name: 'stale.png', meta: { fileId: 'file_a' } }));
221
+ const expanded = readFileValues([{ id: 'file_a', name: 'fresh.png', url: '/u', mimeType: 'image/png' }]);
222
+
223
+ expect(withRecentUploads(expanded, { file_a: stale })[0].name).toBe('fresh.png');
224
+ });
225
+
226
+ it('is a no-op with nothing remembered', () => {
227
+ const views = readFileValues('file_a');
228
+ expect(withRecentUploads(views, {})).toBe(views);
229
+ });
230
+ });
@@ -0,0 +1,246 @@
1
+ /**
2
+ * File field value shapes (ObjectStack ADR-0104 D3 wave 2).
3
+ *
4
+ * A `file`/`image`/`avatar`/`video`/`audio` field value reaches the UI in one
5
+ * of three forms, and every widget that renders one has to cope with all
6
+ * three — so the rules live here once rather than being re-derived per widget.
7
+ *
8
+ * 1. **Reference** — a bare `sys_file` id string. The form the backend stores
9
+ * once file-as-reference is adopted.
10
+ * 2. **Expanded** — `{ id, name, size, mimeType, url }`, what the read path
11
+ * returns after resolving a stored reference. Note `mimeType`: this comes
12
+ * from the platform's spec-owned `FileValueSchema` and is **camelCase**.
13
+ * 3. **Legacy inline blob** — `{ file_id?, name, original_name, size,
14
+ * mime_type, url }`, the pre-reference shape this package used to build
15
+ * itself, with **snake_case** `mime_type`.
16
+ *
17
+ * That casing split is the whole reason this module exists: a widget reading
18
+ * only `mime_type` silently stops recognising images the moment the backend
19
+ * starts returning the expanded form, and the failure looks like "thumbnails
20
+ * disappeared" rather than anything pointing at a value shape.
21
+ *
22
+ * ## Submitting
23
+ *
24
+ * When the upload adapter surfaced a `fileId`, the widget submits the **bare
25
+ * id** — the reference form. When it did not (the object-URL fallback adapter,
26
+ * an older backend), it submits the legacy blob unchanged. So the same build
27
+ * works against a backend that has adopted references and one that has not.
28
+ * Action params already POST a bare fileId; this brings record field values
29
+ * onto the same contract.
30
+ */
31
+
32
+ import { isFileIdToken } from '@objectstack/spec/data';
33
+
34
+ /** A file value normalised for rendering, whatever form it arrived in. */
35
+ export interface FileValueView {
36
+ /** `sys_file` id, when the value carries one. */
37
+ id?: string;
38
+ /** Best available display name. Never empty. */
39
+ name: string;
40
+ /** Resolvable URL, when the value carries one. A bare reference does not. */
41
+ url?: string;
42
+ size?: number;
43
+ mimeType?: string;
44
+ /** The value as it arrived, so callers can pass it through untouched. */
45
+ raw: unknown;
46
+ }
47
+
48
+ /**
49
+ * A minted file id: uuid/nanoid-shaped, and crucially not a URL — a URL always
50
+ * carries `:`, `/` or `.`, so it can never match.
51
+ *
52
+ * This IS the platform's arbiter now, not a mirror of it (objectui#3161,
53
+ * objectstack#4115 ledger batch 7). The declaration that stood here said it
54
+ * "mirrors the platform's `isFileIdToken`" while being a character-for-character
55
+ * copy of that function's body under that function's own name — the shape
56
+ * objectui#3003 argued about and objectui#3169 caught again in
57
+ * `isAggregatedViewContainer`: every value test and every behaviour test passes
58
+ * against a faithful copy, so reference identity is the only check that can tell
59
+ * a re-export from a fork. It is asserted in
60
+ * `__tests__/spec-symbol-batch7.test.ts`.
61
+ *
62
+ * Why it matters that this one is shared rather than duplicated: the regex is a
63
+ * WIRE decision. Widening it server-side (say, ids grow past 64 chars) while a
64
+ * copy here keeps the old bound turns every new id into "not a reference", and
65
+ * the widget then submits the legacy inline blob against a backend that expects
66
+ * a reference. That failure surfaces as a broken thumbnail, nowhere near a
67
+ * regex.
68
+ */
69
+ export { isFileIdToken };
70
+
71
+ /**
72
+ * The `sys_file` id a value refers to, or `undefined`.
73
+ *
74
+ * `file_id ?? id` matches the rule `serializeParamValues` already applies to
75
+ * action params — one extraction rule for both surfaces.
76
+ */
77
+ export function fileIdOf(value: unknown): string | undefined {
78
+ if (isFileIdToken(value)) return value;
79
+ if (value && typeof value === 'object') {
80
+ const o = value as Record<string, unknown>;
81
+ const id = o.file_id ?? o.id;
82
+ if (typeof id === 'string' && id) return id;
83
+ }
84
+ return undefined;
85
+ }
86
+
87
+ /**
88
+ * The stable download endpoint a bare `sys_file` id resolves to.
89
+ *
90
+ * `createObjectStackUploadAdapter` stores exactly this URL (`${basePath}/files/
91
+ * :id`, default base `/api/v1/storage`) as a completed upload's value, and the
92
+ * endpoint 302-redirects to a freshly-signed short-lived URL on every request —
93
+ * so it can be used directly as an `<img src>`. Building it here means a value
94
+ * still in its bare-reference form (the backend read path didn't expand it —
95
+ * seen on the edit-form data path, objectui image thumbnails rendering broken)
96
+ * resolves to a real URL instead of an empty `src`.
97
+ */
98
+ export const FILE_STORAGE_BASE_PATH = '/api/v1/storage';
99
+
100
+ /** The stable download URL for a `sys_file` id. */
101
+ export function fileUrlFromId(id: string): string {
102
+ return `${FILE_STORAGE_BASE_PATH}/files/${encodeURIComponent(id)}`;
103
+ }
104
+
105
+ /** Last path segment of a URL, used as a display name of last resort. */
106
+ function nameFromUrl(url: string): string {
107
+ const path = url.split(/[?#]/)[0] ?? url;
108
+ const seg = path.split('/').filter(Boolean).pop();
109
+ return seg ? decodeURIComponent(seg) : url;
110
+ }
111
+
112
+ /**
113
+ * Normalise one file value for display.
114
+ *
115
+ * @param fallbackName shown when the value carries no usable name — pass a
116
+ * translated string so the widget stays localised.
117
+ */
118
+ export function readFileValue(value: unknown, fallbackName = 'File'): FileValueView {
119
+ if (value == null) return { name: fallbackName, raw: value };
120
+
121
+ if (typeof value === 'string') {
122
+ // A bare id carries no name of its own (the backend expands it on read),
123
+ // but its URL is derivable from the stable download endpoint — so a value
124
+ // the read path left as a bare reference still renders a thumbnail instead
125
+ // of a broken `<img src="">`.
126
+ if (isFileIdToken(value)) return { id: value, name: fallbackName, url: fileUrlFromId(value), raw: value };
127
+ // Otherwise it is a URL (legacy external link, data:, blob:).
128
+ return { url: value, name: nameFromUrl(value), raw: value };
129
+ }
130
+
131
+ if (typeof value === 'object') {
132
+ const o = value as Record<string, unknown>;
133
+ const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined);
134
+ const id = fileIdOf(o);
135
+ // An object shape that carries an id but not its URL (a partially-expanded
136
+ // reference) still resolves to the stable endpoint, same as a bare id.
137
+ const url = str(o.url) ?? (id ? fileUrlFromId(id) : undefined);
138
+ const name =
139
+ str(o.name) ??
140
+ str(o.original_name) ??
141
+ (str(o.url) ? nameFromUrl(str(o.url) as string) : undefined) ??
142
+ fallbackName;
143
+ return {
144
+ id,
145
+ name,
146
+ url,
147
+ size: typeof o.size === 'number' ? o.size : undefined,
148
+ // Expanded form is camelCase, legacy blob is snake_case — accept both.
149
+ mimeType: str(o.mimeType) ?? str(o.mime_type),
150
+ raw: value,
151
+ };
152
+ }
153
+
154
+ return { name: fallbackName, raw: value };
155
+ }
156
+
157
+ /** Normalise a field value (single or `multiple`) to an array of views. */
158
+ export function readFileValues(value: unknown, fallbackName = 'File'): FileValueView[] {
159
+ if (value == null) return [];
160
+ const items = Array.isArray(value) ? value : [value];
161
+ return items.filter((v) => v != null).map((v) => readFileValue(v, fallbackName));
162
+ }
163
+
164
+ /** Does this value look like an image, by MIME type? */
165
+ export function isImageValue(view: FileValueView): boolean {
166
+ return (view.mimeType ?? '').startsWith('image/');
167
+ }
168
+
169
+ /** The subset of an upload result these helpers read. */
170
+ export interface UploadResultLike {
171
+ url: string;
172
+ name: string;
173
+ size: number;
174
+ mimeType: string;
175
+ meta?: Record<string, unknown>;
176
+ }
177
+
178
+ /**
179
+ * What to store in the field for a completed upload.
180
+ *
181
+ * Returns the bare `sys_file` id when the adapter surfaced one — the reference
182
+ * form — and the legacy inline blob when it did not, so a deployment whose
183
+ * upload adapter or backend predates file-as-reference keeps working unchanged.
184
+ */
185
+ export function fileValueForSubmit(
186
+ result: UploadResultLike,
187
+ originalName?: string,
188
+ ): string | Record<string, unknown> {
189
+ const fileId = (result.meta as { fileId?: unknown } | undefined)?.fileId;
190
+ if (isFileIdToken(fileId)) return fileId;
191
+ return {
192
+ name: result.name,
193
+ original_name: originalName ?? result.name,
194
+ size: result.size,
195
+ mime_type: result.mimeType,
196
+ url: result.url,
197
+ };
198
+ }
199
+
200
+ /**
201
+ * The display view of a just-completed upload.
202
+ *
203
+ * Submitting a bare id means the field value no longer carries the name, size
204
+ * or URL needed to render it, and the enriched form only comes back on the next
205
+ * read. Widgets keep these views keyed by id so an upload appears immediately
206
+ * instead of showing a bare token until a refetch.
207
+ */
208
+ export function uploadResultView(result: UploadResultLike, originalName?: string): FileValueView {
209
+ const id = isFileIdToken((result.meta as { fileId?: unknown } | undefined)?.fileId)
210
+ ? ((result.meta as { fileId?: string }).fileId as string)
211
+ : undefined;
212
+ return {
213
+ id,
214
+ name: result.name || originalName || 'File',
215
+ url: result.url,
216
+ size: result.size,
217
+ mimeType: result.mimeType,
218
+ raw: result,
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Merge locally-known upload views over a field value's own views, matched by
224
+ * id. A value that is still a bare reference picks up the name/URL captured at
225
+ * upload time; anything already enriched by the backend is left alone.
226
+ */
227
+ export function withRecentUploads(
228
+ views: FileValueView[],
229
+ recent: Record<string, FileValueView>,
230
+ ): FileValueView[] {
231
+ if (Object.keys(recent).length === 0) return views;
232
+ return views.map((v) => {
233
+ const known = v.id ? recent[v.id] : undefined;
234
+ if (!known) return v;
235
+ // A value the backend already expanded carries its own URL on the raw
236
+ // object — leave that alone. A bare reference (string id, or an id-only
237
+ // object) has only the synthetic download URL `readFileValue` derived, so
238
+ // the just-uploaded name/mimeType still fills in.
239
+ const rawHasOwnUrl =
240
+ !!v.raw &&
241
+ typeof v.raw === 'object' &&
242
+ typeof (v.raw as Record<string, unknown>).url === 'string' &&
243
+ !!(v.raw as Record<string, unknown>).url;
244
+ return rawHasOwnUrl ? v : { ...known, raw: v.raw };
245
+ });
246
+ }