@contember/react-binding 2.2.0-alpha.2 → 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 (58) hide show
  1. package/CLAUDE.md +8 -0
  2. package/dist/development/src/helperComponents/If.cjs +4 -4
  3. package/dist/development/src/helperComponents/If.cjs.map +1 -1
  4. package/dist/development/src/helperComponents/If.js +4 -4
  5. package/dist/development/src/helperComponents/If.js.map +1 -1
  6. package/dist/production/src/helperComponents/If.cjs +1 -1
  7. package/dist/production/src/helperComponents/If.cjs.map +1 -1
  8. package/dist/production/src/helperComponents/If.js +1 -1
  9. package/dist/production/src/helperComponents/If.js.map +1 -1
  10. package/dist/types/accessorPropagation/useAccessorUpdateSubscription.d.ts +1 -1
  11. package/dist/types/accessorPropagation/useAccessorUpdateSubscription.d.ts.map +1 -1
  12. package/dist/types/accessorPropagation/useEntityListSubTree.d.ts.map +1 -1
  13. package/dist/types/accessorPropagation/useEntityListSubTreeLoader.d.ts.map +1 -1
  14. package/dist/types/accessorPropagation/useEntitySubTree.d.ts.map +1 -1
  15. package/dist/types/accessorPropagation/useEntitySubTreeLoader.d.ts.map +1 -1
  16. package/dist/types/accessorPropagation/useExtendTree.d.ts +1 -1
  17. package/dist/types/accessorSorting/addEntityAtIndex.d.ts.map +1 -1
  18. package/dist/types/accessorSorting/repairEntitiesOrder.d.ts.map +1 -1
  19. package/dist/types/accessorSorting/sortEntities.d.ts.map +1 -1
  20. package/dist/types/accessorTree/AccessorTree.d.ts +4 -7
  21. package/dist/types/accessorTree/AccessorTree.d.ts.map +1 -1
  22. package/dist/types/accessorTree/useDataBinding.d.ts.map +1 -1
  23. package/dist/types/accessorTree/useEnvironmentWithSchema.d.ts.map +1 -1
  24. package/dist/types/entityEvents/useDataBindingEvent.d.ts.map +1 -1
  25. package/dist/types/entityEvents/useDerivedField.d.ts.map +1 -1
  26. package/dist/types/entityEvents/useEntityBeforePersist.d.ts +1 -1
  27. package/dist/types/entityEvents/useEntityBeforePersist.d.ts.map +1 -1
  28. package/dist/types/entityEvents/useEntityBeforeUpdate.d.ts +1 -1
  29. package/dist/types/entityEvents/useEntityBeforeUpdate.d.ts.map +1 -1
  30. package/dist/types/entityEvents/useEntityPersistError.d.ts +1 -1
  31. package/dist/types/entityEvents/useEntityPersistError.d.ts.map +1 -1
  32. package/dist/types/entityEvents/useEntityPersistSuccess.d.ts +1 -1
  33. package/dist/types/entityEvents/useEntityPersistSuccess.d.ts.map +1 -1
  34. package/dist/types/entityEvents/useOnConnectionUpdate.d.ts +1 -1
  35. package/dist/types/entityEvents/useOnConnectionUpdate.d.ts.map +1 -1
  36. package/dist/types/helperComponents/DeleteEntityTrigger.d.ts.map +1 -1
  37. package/dist/types/helperComponents/LabelMiddleware.d.ts.map +1 -1
  38. package/dist/types/helperComponents/helpers/FilterEvaluator.d.ts.map +1 -1
  39. package/dist/types/helperComponents/helpers/FilterFieldsCollector.d.ts.map +1 -1
  40. package/dist/types/helperComponents/helpers/evaluateCondition.d.ts.map +1 -1
  41. package/dist/types/helperComponents/persist/PersistOnKey.d.ts.map +1 -1
  42. package/dist/types/helperComponents/persist/PersistTrigger.d.ts.map +1 -1
  43. package/dist/types/helperComponents/persist/useDecoratedPersist.d.ts.map +1 -1
  44. package/dist/types/markers/IncrementalMarkerBuilder.d.ts.map +1 -1
  45. package/dist/types/markers/MarkerStaticAnalyzer.d.ts.map +1 -1
  46. package/dist/types/markers/MarkerTreeGenerator.d.ts.map +1 -1
  47. package/dist/types/tsconfig.tsbuildinfo +1 -1
  48. package/package.json +7 -7
  49. package/src/helperComponents/If.tsx +3 -1
  50. package/tests/cases/unit/core/accessorErrors.test.tsx +305 -0
  51. package/tests/cases/unit/core/persist.test.tsx +198 -0
  52. package/tests/cases/unit/helperComponents/if.test.tsx +68 -0
  53. package/tests/lib/bindingFactory.ts +3 -2
  54. package/tests/lib/harness/FakeContentApi.ts +257 -0
  55. package/tests/lib/harness/createBindingHarness.tsx +166 -0
  56. package/tests/lib/harness/index.ts +3 -0
  57. package/tests/lib/harness/readme.md +29 -0
  58. package/tests/lib/harness/wireData.ts +13 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@contember/react-binding",
3
3
  "license": "Apache-2.0",
4
- "version": "2.2.0-alpha.2",
4
+ "version": "2.2.0-alpha.5",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "main": "./dist/production/index.js",
@@ -29,12 +29,12 @@
29
29
  "ae:test": "api-extractor run"
30
30
  },
31
31
  "dependencies": {
32
- "@contember/binding": "2.1.0-beta.2",
33
- "@contember/client": "2.1.0-beta.2",
34
- "@contember/graphql-client": "2.1.0-beta.2",
35
- "@contember/react-client": "2.1.0-beta.2",
36
- "@contember/react-utils": "2.1.0-beta.2",
37
- "@contember/utilities": "2.1.0-beta.2",
32
+ "@contember/binding": "2.2.0-alpha.5",
33
+ "@contember/client": "2.2.0-alpha.5",
34
+ "@contember/graphql-client": "2.2.0-alpha.5",
35
+ "@contember/react-client": "2.2.0-alpha.5",
36
+ "@contember/react-utils": "2.2.0-alpha.5",
37
+ "@contember/utilities": "2.2.0-alpha.5",
38
38
  "@radix-ui/react-slot": "^1.2.4",
39
39
  "@radix-ui/primitive": "^1.1.3"
40
40
  },
@@ -72,7 +72,9 @@ const IfFilter = Component<IfFilterProps>(
72
72
  ({ children, condition, then, else: elseIn }, env) => {
73
73
  const desugaredFilter = QueryLanguage.desugarFilter(condition, env)
74
74
  const collectedFields = new FilterFieldsCollector(env.getSchema(), desugaredFilter).collectFields(env.getSubTreeNode().entity)
75
- const additionalFields = <>{Array.from(collectedFields).map(it => <Field field={it} key={it} />)}</>
75
+ // Nonbearing: reading a field to decide what to render must not be a reason to create the entity. A bearing
76
+ // field would also win the marker merge, overriding a nonbearing one registered for the same field elsewhere.
77
+ const additionalFields = <>{Array.from(collectedFields).map(it => <Field field={it} key={it} isNonbearing />)}</>
76
78
 
77
79
  return (
78
80
  <>
@@ -0,0 +1,305 @@
1
+ import { afterEach, describe, expect, it } from 'bun:test'
2
+ import { c, createSchema } from '@contember/schema-definition'
3
+ import { ErrorAccessor, ErrorPersistResult, isErrorPersistResult } from '@contember/binding-legacy'
4
+ import { ValidationError } from '@contember/client'
5
+ import { EntitySubTree, Field, HasMany, HasOne } from '../../../../src/index.js'
6
+ import { convertModelToAdminSchema } from '../../../lib/convertModelToAdminSchema.js'
7
+ import { BindingHarness, createBindingHarness, MutationErrorFixture, MutationFailure } from '../../../lib/harness/index.js'
8
+
9
+ namespace ErrorModel {
10
+ export class Article {
11
+ title = c.stringColumn()
12
+ author = c.manyHasOne(Author)
13
+ blocks = c.oneHasMany(Block, 'article')
14
+ }
15
+
16
+ export class Author {
17
+ name = c.stringColumn()
18
+ }
19
+
20
+ export class Block {
21
+ article = c.manyHasOne(Article, 'blocks').notNull()
22
+ order = c.intColumn().notNull()
23
+ content = c.stringColumn()
24
+ }
25
+ }
26
+
27
+ const schema = convertModelToAdminSchema(createSchema(ErrorModel).model)
28
+ const articleId = 'aaaaaaaa-0000-0000-0000-000000000001'
29
+ const authorId = 'cccccccc-0000-0000-0000-000000000001'
30
+ const firstBlockId = 'bbbbbbbb-0000-0000-0000-000000000001'
31
+ const secondBlockId = 'bbbbbbbb-0000-0000-0000-000000000002'
32
+ const absentBlockId = 'bbbbbbbb-0000-0000-0000-000000000009'
33
+
34
+ let harness: BindingHarness | undefined
35
+
36
+ afterEach(() => {
37
+ harness?.unmount()
38
+ harness = undefined
39
+ })
40
+
41
+ const mountArticle = async () => {
42
+ harness = await createBindingHarness({
43
+ schema,
44
+ data: {
45
+ article: {
46
+ id: articleId,
47
+ title: 'Hello',
48
+ author: { id: authorId, name: 'Jane' },
49
+ blocks: [
50
+ { id: firstBlockId, order: 0, content: 'first' },
51
+ { id: secondBlockId, order: 1, content: 'second' },
52
+ ],
53
+ },
54
+ },
55
+ node: (
56
+ <EntitySubTree entity={`Article(id = '${articleId}')`} alias="article">
57
+ <Field field="title" />
58
+ <HasOne field="author">
59
+ <Field field="name" />
60
+ </HasOne>
61
+ <HasMany field="blocks" orderBy="order">
62
+ <Field field="order" />
63
+ <Field field="content" />
64
+ </HasMany>
65
+ </EntitySubTree>
66
+ ),
67
+ })
68
+ return harness
69
+ }
70
+
71
+ const article = (harness: BindingHarness) => harness.getEntity('article')
72
+ const author = (harness: BindingHarness) => article(harness).getEntity('author')
73
+ const blocks = (harness: BindingHarness) => article(harness).getEntityList({ field: 'blocks', orderBy: 'order' })
74
+ const row = (harness: BindingHarness, id: string) => blocks(harness).getChildEntityById(id)
75
+
76
+ /** The message of every error sitting on an accessor, execution and validation alike. */
77
+ const messagesOn = (holder: { readonly errors: ErrorAccessor | undefined }) =>
78
+ holder.errors?.errors.map(error => error.type === 'execution' ? error.developerMessage : error.message)
79
+
80
+ type ErrorPath = ValidationError['path']
81
+
82
+ /** The path the engine reports for a list item: the relation, then the index carrying the alias the binding sent. */
83
+ const rowPath = (id: string, ...rest: ErrorPath): ErrorPath => [
84
+ { field: 'blocks' },
85
+ { index: 0, alias: `_${id.replace(/-/g, '_')}` },
86
+ ...rest,
87
+ ]
88
+
89
+ const executionError = (message: string, path: ErrorPath): MutationErrorFixture => ({ type: 'NotFoundOrDenied', message, paths: [path] })
90
+ const validationError = (message: string, path: ErrorPath): ValidationError => ({ message: { text: message }, path })
91
+
92
+ /** Dirties the tree, persists it against a response that fails, and hands back the rejection. */
93
+ const persistFailing = async (harness: BindingHarness, failure: Omit<MutationFailure, 'errorMessage'>): Promise<ErrorPersistResult> => {
94
+ harness.server.failNextMutation({ errorMessage: 'The mutation has failed.', ...failure })
95
+ await harness.update(() => {
96
+ article(harness).getField('title').updateValue('Goodbye')
97
+ })
98
+
99
+ let rejection: unknown
100
+ await harness.persist().then(() => {}, error => {
101
+ rejection = error
102
+ })
103
+ if (!isErrorPersistResult(rejection)) {
104
+ throw new Error('The persist was expected to fail.')
105
+ }
106
+ return rejection
107
+ }
108
+
109
+ describe('accessor errors', () => {
110
+ describe('where one execution error lands', () => {
111
+ it('on the entity the mutation was for', async () => {
112
+ const harness = await mountArticle()
113
+
114
+ await persistFailing(harness, { errors: [executionError('on the article', [])] })
115
+
116
+ expect(messagesOn(article(harness))).toEqual(['on the article'])
117
+ })
118
+
119
+ it('on a plain field', async () => {
120
+ const harness = await mountArticle()
121
+
122
+ await persistFailing(harness, { errors: [executionError('on the title', [{ field: 'title' }])] })
123
+
124
+ expect(messagesOn(article(harness).getField('title'))).toEqual(['on the title'])
125
+ expect(article(harness).errors).toBeUndefined()
126
+ })
127
+
128
+ it('on a has-one relation', async () => {
129
+ const harness = await mountArticle()
130
+
131
+ await persistFailing(harness, { errors: [executionError('on the author', [{ field: 'author' }])] })
132
+
133
+ expect(messagesOn(author(harness))).toEqual(['on the author'])
134
+ })
135
+
136
+ it('on a field of a has-one relation', async () => {
137
+ const harness = await mountArticle()
138
+
139
+ await persistFailing(harness, { errors: [executionError('on the name', [{ field: 'author' }, { field: 'name' }])] })
140
+
141
+ expect(messagesOn(author(harness).getField('name'))).toEqual(['on the name'])
142
+ expect(author(harness).errors).toBeUndefined()
143
+ })
144
+
145
+ it('on the list as a whole', async () => {
146
+ const harness = await mountArticle()
147
+
148
+ await persistFailing(harness, { errors: [executionError('on the blocks', [{ field: 'blocks' }])] })
149
+
150
+ expect(messagesOn(blocks(harness))).toEqual(['on the blocks'])
151
+ expect(row(harness, firstBlockId).errors).toBeUndefined()
152
+ })
153
+
154
+ it('on a list row', async () => {
155
+ const harness = await mountArticle()
156
+
157
+ const result = await persistFailing(harness, { errors: [executionError('on the first row', rowPath(firstBlockId))] })
158
+
159
+ expect(messagesOn(row(harness, firstBlockId))).toEqual(['on the first row'])
160
+ expect(row(harness, secondBlockId).errors).toBeUndefined()
161
+ expect(blocks(harness).errors).toBeUndefined()
162
+ expect(result.errors).toMatchObject([{ type: 'execution', code: 'NotFoundOrDenied' }])
163
+ })
164
+
165
+ it('on a field of a list row', async () => {
166
+ const harness = await mountArticle()
167
+
168
+ await persistFailing(harness, { errors: [executionError('on the first content', rowPath(firstBlockId, { field: 'content' }))] })
169
+
170
+ expect(messagesOn(row(harness, firstBlockId).getField('content'))).toEqual(['on the first content'])
171
+ expect(row(harness, firstBlockId).errors).toBeUndefined()
172
+ })
173
+
174
+ it('nowhere, when it names a row the list does not hold', async () => {
175
+ const harness = await mountArticle()
176
+
177
+ const result = await persistFailing(harness, { errors: [executionError('on a stranger', rowPath(absentBlockId))] })
178
+
179
+ expect(result.errors).toEqual([])
180
+ expect(blocks(harness).errors).toBeUndefined()
181
+ expect(article(harness).errors).toBeUndefined()
182
+ })
183
+ })
184
+
185
+ describe('several errors in one response', () => {
186
+ it('reach every failing row', async () => {
187
+ const harness = await mountArticle()
188
+
189
+ await persistFailing(harness, {
190
+ errors: [
191
+ executionError('on the first row', rowPath(firstBlockId)),
192
+ executionError('on the second row', rowPath(secondBlockId)),
193
+ ],
194
+ })
195
+
196
+ expect(messagesOn(row(harness, firstBlockId))).toEqual(['on the first row'])
197
+ expect(messagesOn(row(harness, secondBlockId))).toEqual(['on the second row'])
198
+ expect(blocks(harness).errors).toBeUndefined()
199
+ })
200
+
201
+ it('reach every failing field of a row', async () => {
202
+ const harness = await mountArticle()
203
+
204
+ const result = await persistFailing(harness, {
205
+ errors: [
206
+ executionError('on the first content', rowPath(firstBlockId, { field: 'content' })),
207
+ executionError('on the second content', rowPath(secondBlockId, { field: 'content' })),
208
+ ],
209
+ })
210
+
211
+ expect(messagesOn(row(harness, firstBlockId).getField('content'))).toEqual(['on the first content'])
212
+ expect(messagesOn(row(harness, secondBlockId).getField('content'))).toEqual(['on the second content'])
213
+ expect(result.errors).toHaveLength(2)
214
+ })
215
+
216
+ it('reach targets of different shapes at once', async () => {
217
+ const harness = await mountArticle()
218
+
219
+ const result = await persistFailing(harness, {
220
+ errors: [
221
+ executionError('on the title', [{ field: 'title' }]),
222
+ executionError('on the first row', rowPath(firstBlockId)),
223
+ executionError('on the second content', rowPath(secondBlockId, { field: 'content' })),
224
+ ],
225
+ })
226
+
227
+ expect(messagesOn(article(harness).getField('title'))).toEqual(['on the title'])
228
+ expect(messagesOn(row(harness, firstBlockId))).toEqual(['on the first row'])
229
+ expect(messagesOn(row(harness, secondBlockId).getField('content'))).toEqual(['on the second content'])
230
+ expect(result.errors).toHaveLength(3)
231
+ })
232
+ })
233
+
234
+ describe('validation errors', () => {
235
+ it('reach the field of the row they name', async () => {
236
+ const harness = await mountArticle()
237
+
238
+ await persistFailing(harness, {
239
+ validation: [validationError('Field is required', rowPath(firstBlockId, { field: 'content' }))],
240
+ })
241
+
242
+ expect(row(harness, firstBlockId).getField('content').errors?.errors).toEqual([
243
+ { type: 'validation', code: 'fieldRequired', message: 'Field is required' },
244
+ ])
245
+ })
246
+
247
+ it('reach every failing row of one response', async () => {
248
+ const harness = await mountArticle()
249
+
250
+ await persistFailing(harness, {
251
+ validation: [
252
+ validationError('Field is required', rowPath(firstBlockId, { field: 'content' })),
253
+ validationError('Too long', rowPath(secondBlockId, { field: 'content' })),
254
+ ],
255
+ })
256
+
257
+ expect(messagesOn(row(harness, firstBlockId).getField('content'))).toEqual(['Field is required'])
258
+ expect(row(harness, secondBlockId).getField('content').errors?.errors).toEqual([
259
+ { type: 'validation', code: undefined, message: 'Too long' },
260
+ ])
261
+ })
262
+
263
+ it('take precedence over the execution errors of the same response', async () => {
264
+ const harness = await mountArticle()
265
+
266
+ await persistFailing(harness, {
267
+ errors: [executionError('on the second row', rowPath(secondBlockId))],
268
+ validation: [validationError('Field is required', rowPath(firstBlockId, { field: 'content' }))],
269
+ })
270
+
271
+ expect(messagesOn(row(harness, firstBlockId).getField('content'))).toEqual(['Field is required'])
272
+ expect(row(harness, secondBlockId).errors).toBeUndefined()
273
+ })
274
+ })
275
+
276
+ describe('lifecycle', () => {
277
+ it('are cleared when the next persist starts, so a retry reaches the server', async () => {
278
+ const harness = await mountArticle()
279
+ await persistFailing(harness, { errors: [executionError('on the first row', rowPath(firstBlockId))] })
280
+
281
+ const result = await harness.persist()
282
+
283
+ expect(result.type).toBe('justSuccess')
284
+ expect(row(harness, firstBlockId).errors).toBeUndefined()
285
+ expect(harness.server.requests.filter(it => it.type === 'mutation')).toHaveLength(2)
286
+ })
287
+
288
+ it('are dropped one accessor at a time', async () => {
289
+ const harness = await mountArticle()
290
+ await persistFailing(harness, {
291
+ errors: [
292
+ executionError('on the first content', rowPath(firstBlockId, { field: 'content' })),
293
+ executionError('on the second content', rowPath(secondBlockId, { field: 'content' })),
294
+ ],
295
+ })
296
+
297
+ await harness.update(() => {
298
+ row(harness, firstBlockId).getField('content').clearErrors()
299
+ })
300
+
301
+ expect(row(harness, firstBlockId).getField('content').errors).toBeUndefined()
302
+ expect(messagesOn(row(harness, secondBlockId).getField('content'))).toEqual(['on the second content'])
303
+ })
304
+ })
305
+ })
@@ -0,0 +1,198 @@
1
+ import { afterEach, describe, expect, it } from 'bun:test'
2
+ import { c, createSchema } from '@contember/schema-definition'
3
+ import { EntityAccessor, ErrorPersistResult } from '@contember/binding-legacy'
4
+ import { EntitySubTree, Field, HasMany } from '../../../../src/index.js'
5
+ import { convertModelToAdminSchema } from '../../../lib/convertModelToAdminSchema.js'
6
+ import { BindingHarness, createBindingHarness } from '../../../lib/harness/index.js'
7
+
8
+ namespace PersistModel {
9
+ export class Article {
10
+ title = c.stringColumn()
11
+ blocks = c.oneHasMany(Block, 'article')
12
+ }
13
+
14
+ export class Block {
15
+ article = c.manyHasOne(Article, 'blocks').notNull()
16
+ order = c.intColumn().notNull()
17
+ content = c.stringColumn()
18
+ }
19
+ }
20
+
21
+ const schema = convertModelToAdminSchema(createSchema(PersistModel).model)
22
+ const articleId = 'aaaaaaaa-0000-0000-0000-000000000001'
23
+ const firstBlockId = 'bbbbbbbb-0000-0000-0000-000000000001'
24
+ const secondBlockId = 'bbbbbbbb-0000-0000-0000-000000000002'
25
+
26
+ const articleData = {
27
+ id: articleId,
28
+ title: 'Hello',
29
+ blocks: [
30
+ { id: firstBlockId, order: 0, content: 'first' },
31
+ { id: secondBlockId, order: 1, content: 'second' },
32
+ ],
33
+ }
34
+
35
+ let harness: BindingHarness | undefined
36
+
37
+ afterEach(() => {
38
+ harness?.unmount()
39
+ harness = undefined
40
+ })
41
+
42
+ const mountArticle = async (props: {
43
+ onBeforePersist?: EntityAccessor.EntityEventListenerMap['beforePersist']
44
+ onPersistSuccess?: EntityAccessor.EntityEventListenerMap['persistSuccess']
45
+ } = {}) => {
46
+ harness = await createBindingHarness({
47
+ schema,
48
+ data: { article: articleData },
49
+ node: (
50
+ <EntitySubTree entity={`Article(id = '${articleId}')`} alias="article" {...props}>
51
+ <Field field="title" />
52
+ <HasMany field="blocks" orderBy="order">
53
+ <Field field="order" />
54
+ <Field field="content" />
55
+ </HasMany>
56
+ </EntitySubTree>
57
+ ),
58
+ })
59
+ return harness
60
+ }
61
+
62
+ const blocksOf = (harness: BindingHarness) => harness.getEntity('article').getEntityList({ field: 'blocks', orderBy: 'order' })
63
+
64
+ describe('persist', () => {
65
+ it('loads the server response into accessors', async () => {
66
+ const harness = await mountArticle()
67
+
68
+ expect(harness.getEntity('article').getField('title').value).toBe('Hello')
69
+ expect(Array.from(blocksOf(harness)).map(it => it.getField('content').value)).toEqual(['first', 'second'])
70
+ })
71
+
72
+ it('sends nothing when the tree is untouched', async () => {
73
+ const harness = await mountArticle()
74
+
75
+ const result = await harness.persist()
76
+
77
+ expect(result.type).toBe('nothingToPersist')
78
+ expect(harness.server.requests.filter(it => it.type === 'mutation')).toHaveLength(0)
79
+ })
80
+
81
+ it('gives a created entity its server id', async () => {
82
+ const harness = await mountArticle()
83
+
84
+ await harness.update(() => {
85
+ blocksOf(harness).createNewEntity(getAccessor => {
86
+ getAccessor().getField('order').updateValue(2)
87
+ getAccessor().getField('content').updateValue('third')
88
+ })
89
+ })
90
+ const dummyId = Array.from(blocksOf(harness))[2].id
91
+ expect(Array.from(blocksOf(harness))[2].existsOnServer).toBe(false)
92
+
93
+ const result = await harness.persist()
94
+
95
+ expect(result.type).toBe('justSuccess')
96
+ const persistedBlocks = Array.from(blocksOf(harness))
97
+ expect(persistedBlocks).toHaveLength(3)
98
+ expect(persistedBlocks.every(it => it.existsOnServer)).toBe(true)
99
+ expect(persistedBlocks[2].id).toBe(harness.server.assignedIds.get(dummyId)!)
100
+ expect(persistedBlocks[2].getField('content').value).toBe('third')
101
+ })
102
+
103
+ it('keeps the ids of the entities it did not create', async () => {
104
+ const harness = await mountArticle()
105
+
106
+ await harness.update(() => {
107
+ harness.getEntity('article').getField('title').updateValue('Goodbye')
108
+ })
109
+ await harness.persist()
110
+
111
+ expect(harness.getEntity('article').id).toBe(articleId)
112
+ expect(Array.from(blocksOf(harness)).map(it => it.id)).toEqual([firstBlockId, secondBlockId])
113
+ expect(harness.server.assignedIds.size).toBe(0)
114
+ })
115
+
116
+ it('drops a deleted entity from the list', async () => {
117
+ const harness = await mountArticle()
118
+
119
+ await harness.update(() => {
120
+ blocksOf(harness).getChildEntityById(firstBlockId).deleteEntity()
121
+ })
122
+ await harness.persist()
123
+
124
+ expect(Array.from(blocksOf(harness)).map(it => it.id)).toEqual([secondBlockId])
125
+ })
126
+
127
+ it('runs beforePersist before the mutation goes out', async () => {
128
+ const harness = await mountArticle({
129
+ onBeforePersist: getAccessor => {
130
+ getAccessor().getField('title').updateValue('Rewritten by beforePersist')
131
+ },
132
+ })
133
+
134
+ await harness.update(() => {
135
+ harness.getEntity('article').getField('title').updateValue('Goodbye')
136
+ })
137
+ await harness.persist()
138
+
139
+ expect(harness.getEntity('article').getField('title').value).toBe('Rewritten by beforePersist')
140
+ const mutation = harness.server.requests.find(it => it.type === 'mutation')!
141
+ expect(JSON.stringify(mutation.variables)).toContain('Rewritten by beforePersist')
142
+ })
143
+
144
+ it('runs persistSuccess once the response has landed', async () => {
145
+ const seenTitles: (string | null)[] = []
146
+ const harness = await mountArticle({
147
+ onPersistSuccess: getAccessor => {
148
+ seenTitles.push(getAccessor().getField<string>('title').value)
149
+ },
150
+ })
151
+
152
+ await harness.update(() => {
153
+ harness.getEntity('article').getField('title').updateValue('Goodbye')
154
+ })
155
+ await harness.persist()
156
+
157
+ expect(seenTitles).toEqual(['Goodbye'])
158
+ })
159
+
160
+ it('reports a failed mutation through the persistError event', async () => {
161
+ const harness = await mountArticle()
162
+ const seenErrors: ErrorPersistResult[] = []
163
+ harness.bindingOperations.addEventListener('persistError', error => {
164
+ seenErrors.push(error)
165
+ })
166
+
167
+ harness.server.failNextMutation({ errorMessage: 'Nope.' })
168
+ await harness.update(() => {
169
+ harness.getEntity('article').getField('title').updateValue('Goodbye')
170
+ })
171
+
172
+ await expect(harness.persist()).rejects.toMatchObject({ type: 'invalidInput' })
173
+ expect(seenErrors).toHaveLength(1)
174
+ })
175
+
176
+ it('keeps the persistError event quiet when the caller asks for silent errors', async () => {
177
+ const harness = await mountArticle()
178
+ const seenErrors: ErrorPersistResult[] = []
179
+ harness.bindingOperations.addEventListener('persistError', error => {
180
+ seenErrors.push(error)
181
+ })
182
+ const reportedToCaller: unknown[] = []
183
+
184
+ harness.server.failNextMutation({ errorMessage: 'Nope.' })
185
+ await harness.update(() => {
186
+ harness.getEntity('article').getField('title').updateValue('Goodbye')
187
+ })
188
+
189
+ await expect(harness.persist({
190
+ silentErrors: true,
191
+ onPersistError: options => {
192
+ reportedToCaller.push(options)
193
+ },
194
+ })).rejects.toMatchObject({ type: 'invalidInput' })
195
+ expect(seenErrors).toHaveLength(0)
196
+ expect(reportedToCaller).toHaveLength(1)
197
+ })
198
+ })
@@ -0,0 +1,68 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { EntitySubTree, Field, HasOne, If } from '../../../../src/index.js'
3
+ import { createBinding } from '../../../lib/bindingFactory.js'
4
+ import { c, createSchema } from '@contember/schema-definition'
5
+ import { convertModelToAdminSchema } from '../../../lib/convertModelToAdminSchema.js'
6
+ import { EntityFieldMarkersContainer, HasOneRelationMarker, MarkerTreeRoot } from '@contember/binding'
7
+ import assert from 'assert'
8
+
9
+ namespace IfModel {
10
+ export class Article {
11
+ title = c.stringColumn()
12
+ image = c.oneHasOne(Image).inversedBy('article')
13
+ }
14
+
15
+ export class Image {
16
+ type = c.stringColumn()
17
+ url = c.stringColumn()
18
+ }
19
+ }
20
+
21
+ const schema = convertModelToAdminSchema(createSchema(IfModel).model)
22
+
23
+ const getImageFields = (markerTree: MarkerTreeRoot): EntityFieldMarkersContainer => {
24
+ const subTree = Array.from(markerTree.subTrees.values())[0]
25
+ const image = Array.from(subTree.fields.markers.values()).find(
26
+ (it): it is HasOneRelationMarker => it instanceof HasOneRelationMarker && it.parameters.field === 'image',
27
+ )
28
+ assert(image !== undefined)
29
+ return image.fields
30
+ }
31
+
32
+ describe('If', () => {
33
+ it('registers the fields of its condition as nonbearing', () => {
34
+ const { markerTree } = createBinding({
35
+ node: (
36
+ <EntitySubTree entity="Article(id = '123')">
37
+ <HasOne field="image">
38
+ <If condition="[type = 'hero']">
39
+ <Field field="url" />
40
+ </If>
41
+ </HasOne>
42
+ </EntitySubTree>
43
+ ),
44
+ schema,
45
+ })
46
+
47
+ const fields = getImageFields(markerTree)
48
+ // Deciding what to render must not be a reason to create the image — only filling the url is.
49
+ expect(fields.markers.get('type')?.isNonbearing).toBe(true)
50
+ expect(fields.markers.get('url')?.isNonbearing).toBe(false)
51
+ })
52
+
53
+ it('keeps the field bearing when it is also rendered as one', () => {
54
+ const { markerTree } = createBinding({
55
+ node: (
56
+ <EntitySubTree entity="Article(id = '123')">
57
+ <HasOne field="image">
58
+ <Field field="type" />
59
+ <If condition="[type = 'hero']" />
60
+ </HasOne>
61
+ </EntitySubTree>
62
+ ),
63
+ schema,
64
+ })
65
+
66
+ expect(getImageFields(markerTree).markers.get('type')?.isNonbearing).toBe(false)
67
+ })
68
+ })
@@ -27,7 +27,8 @@ export const createBinding = ({ node, schema }: { node: ReactNode; schema: Schem
27
27
  )
28
28
 
29
29
  const treeAugmenter = new TreeAugmenter(eventManager, stateInitializer, treeStore)
30
- treeAugmenter.extendTreeStates(undefined, generator.generate())
30
+ const markerTree = generator.generate()
31
+ treeAugmenter.extendTreeStates(undefined, markerTree)
31
32
 
32
- return { eventManager, treeStore, environment }
33
+ return { eventManager, treeStore, environment, markerTree }
33
34
  }