@contember/react-binding 2.1.0-rc.1 → 2.1.0-rc.3

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.
@@ -0,0 +1,257 @@
1
+ import {
2
+ EntityAccessor,
3
+ EntityFieldMarkers,
4
+ EntityId,
5
+ EntityListSubTreeMarker,
6
+ EntitySubTreeMarker,
7
+ FieldMarker,
8
+ HasManyRelationMarker,
9
+ HasOneRelationMarker,
10
+ MarkerTreeRoot,
11
+ PRIMARY_KEY_NAME,
12
+ TreeStore,
13
+ } from '@contember/binding-legacy'
14
+ import { MutationGenerator, SubMutationOperation } from '@contember/binding-legacy'
15
+ import { ContentQueryBuilder, MutationError, Result, ValidationError } from '@contember/client'
16
+ import { GraphQlClient } from '@contember/graphql-client'
17
+ import { WireConnection, wireConnection, WireEntity, WireValue } from './wireData'
18
+
19
+ export type EntityFixture = { [fieldName: string]: FixtureValue }
20
+ export type FixtureValue = string | number | boolean | null | EntityId | EntityFixture | EntityFixture[]
21
+
22
+ /** Read fixtures, keyed by sub-tree alias. Fields are addressed by their name, not by a placeholder. */
23
+ export type SubTreeFixtures = { [alias: string]: EntityFixture | EntityFixture[] | null }
24
+
25
+ export interface RecordedRequest {
26
+ type: 'query' | 'mutation'
27
+ query: string
28
+ variables: Record<string, unknown>
29
+ }
30
+
31
+ /** A {@link MutationError} as it travels over the wire, where the code is a plain string rather than an enum member. */
32
+ export type MutationErrorFixture = Omit<MutationError, 'type'> & { readonly type: `${Result.ExecutionErrorType}` }
33
+
34
+ export interface MutationFailure {
35
+ errorMessage: string
36
+ /** Execution errors, i.e. what the engine reports when the write itself is refused. */
37
+ errors?: MutationErrorFixture[]
38
+ /** Validation errors. The engine reports these instead of running the mutation, so they take precedence. */
39
+ validation?: ValidationError[]
40
+ }
41
+
42
+ /**
43
+ * An ideal content API for the data binding to talk to. It accepts every mutation, echoes back what the binding
44
+ * has in its tree and hands out a fresh id to everything the binding has just created — which is the part that
45
+ * matters, because that id swap is what the binding has to survive.
46
+ *
47
+ * It deliberately does not interpret the mutation input, so it cannot tell you that a mutation was wrong. Assert
48
+ * on {@link FakeContentApi.requests} for that.
49
+ */
50
+ export class FakeContentApi {
51
+ public readonly requests: RecordedRequest[] = []
52
+
53
+ /** Ids handed out to entities that had none, keyed by the dummy id they used to carry. */
54
+ public readonly assignedIds = new Map<EntityId, EntityId>()
55
+
56
+ private data: SubTreeFixtures = {}
57
+ private nextFailure: MutationFailure | undefined = undefined
58
+ private idCounter = 0
59
+
60
+ public constructor(
61
+ private readonly context: {
62
+ markerTree: MarkerTreeRoot
63
+ treeStore: TreeStore
64
+ queryBuilder: ContentQueryBuilder
65
+ },
66
+ ) {
67
+ }
68
+
69
+ public setData(data: SubTreeFixtures): void {
70
+ this.data = data
71
+ }
72
+
73
+ /** Make the next persist come back as a failed transaction. */
74
+ public failNextMutation(failure: MutationFailure): void {
75
+ this.nextFailure = failure
76
+ }
77
+
78
+ public createClient(): GraphQlClient {
79
+ return new GraphQlClient({
80
+ url: 'http://localhost/content',
81
+ fetcher: async (_url, options) => {
82
+ const body = JSON.parse(String(options?.body)) as { query: string; variables: Record<string, unknown> }
83
+ const type = body.query.startsWith('mutation') ? 'mutation' : 'query'
84
+ this.requests.push({ type, query: body.query, variables: body.variables })
85
+
86
+ const data = type === 'mutation' ? { mut: this.respondToMutation() } : this.respondToQuery()
87
+
88
+ return new Response(JSON.stringify({ data }), { headers: { 'Content-Type': 'application/json' } })
89
+ },
90
+ })
91
+ }
92
+
93
+ private respondToQuery(): Record<string, WireEntity | WireEntity[] | null> {
94
+ const response: Record<string, WireEntity | WireEntity[] | null> = {}
95
+
96
+ for (const [placeholder, marker] of this.context.markerTree.subTrees) {
97
+ if (marker.parameters.isCreating) {
98
+ continue
99
+ }
100
+ const fixture = this.data[this.aliasOf(placeholder)] ?? null
101
+
102
+ if (marker instanceof EntityListSubTreeMarker) {
103
+ const rows = Array.isArray(fixture) ? fixture : (fixture === null ? [] : [fixture])
104
+ response[placeholder] = rows.map(row => this.fromFixture(marker.fields.markers, row, marker.entityName))
105
+ } else if (marker instanceof EntitySubTreeMarker) {
106
+ if (Array.isArray(fixture)) {
107
+ throw new Error(`The '${this.aliasOf(placeholder)}' sub-tree is a single entity, but its fixture is a list.`)
108
+ }
109
+ response[placeholder] = fixture === null ? null : this.fromFixture(marker.fields.markers, fixture, marker.entityName)
110
+ }
111
+ }
112
+
113
+ return response
114
+ }
115
+
116
+ private respondToMutation() {
117
+ const { operations } = MutationGenerator.getPersistMutation(this.context.treeStore, this.context.queryBuilder)
118
+ const failure = this.nextFailure
119
+ this.nextFailure = undefined
120
+ const results: Record<string, unknown> = {}
121
+
122
+ for (const operation of operations) {
123
+ results[operation.alias] = failure === undefined
124
+ ? {
125
+ ok: true,
126
+ errorMessage: null,
127
+ errors: [],
128
+ validation: null,
129
+ node: this.nodeForOperation(operation),
130
+ }
131
+ : {
132
+ ok: false,
133
+ errorMessage: failure.errorMessage,
134
+ errors: failure.errors ?? [],
135
+ validation: this.validationResult(failure),
136
+ node: null,
137
+ }
138
+ }
139
+
140
+ return {
141
+ ok: failure === undefined,
142
+ errorMessage: failure?.errorMessage ?? null,
143
+ errors: failure?.errors ?? [],
144
+ validation: failure === undefined ? null : this.validationResult(failure),
145
+ ...results,
146
+ }
147
+ }
148
+
149
+ private validationResult(failure: MutationFailure) {
150
+ return failure.validation === undefined ? null : { valid: false, errors: failure.validation }
151
+ }
152
+
153
+ private nodeForOperation(operation: SubMutationOperation): WireEntity | null {
154
+ const subTree = this.getSubTreeState(operation.subTreePlaceholder)
155
+
156
+ if (operation.type === 'delete') {
157
+ const entityName = subTree.type === 'entityList' ? subTree.entityName : subTree.entity.entityName
158
+ return { [PRIMARY_KEY_NAME]: operation.id, __typename: entityName }
159
+ }
160
+ if (subTree.type === 'entityRealm') {
161
+ return this.fromAccessor(subTree.getAccessor(), operation.markers)
162
+ }
163
+ return this.fromAccessor(subTree.getAccessor().getChildEntityById(operation.id), operation.markers)
164
+ }
165
+
166
+ private getSubTreeState(placeholder: string) {
167
+ for (const subTreeStates of this.context.treeStore.subTreeStatesByRoot.values()) {
168
+ const state = subTreeStates.get(placeholder)
169
+ if (state !== undefined) {
170
+ return state
171
+ }
172
+ }
173
+ throw new Error(`The mutation targets an unknown sub-tree '${placeholder}'.`)
174
+ }
175
+
176
+ /** Builds what the server would return for an entity it has just written, straight off the binding's own tree. */
177
+ private fromAccessor(entity: EntityAccessor, markers: EntityFieldMarkers): WireEntity {
178
+ const result: WireEntity = {
179
+ [PRIMARY_KEY_NAME]: this.idOf(entity),
180
+ __typename: entity.name,
181
+ }
182
+
183
+ for (const [placeholder, marker] of markers) {
184
+ if (marker instanceof FieldMarker) {
185
+ if (marker.fieldName === PRIMARY_KEY_NAME) {
186
+ continue
187
+ }
188
+ result[placeholder] = entity.getField({ hasOneRelationPath: [], field: marker.fieldName }).value as WireValue
189
+ } else if (marker instanceof HasOneRelationMarker) {
190
+ const child = entity.getEntity({ hasOneRelationPath: [marker.parameters] })
191
+ result[placeholder] = child.existsOnServer || child.hasUnpersistedChanges
192
+ ? this.fromAccessor(child, marker.fields.markers)
193
+ : null
194
+ } else if (marker instanceof HasManyRelationMarker) {
195
+ const children = entity.getEntityList({ hasOneRelationPath: [], hasManyRelation: marker.parameters })
196
+ result[placeholder] = wireConnection(Array.from(children).map(child => this.fromAccessor(child, marker.fields.markers)))
197
+ }
198
+ }
199
+
200
+ return result
201
+ }
202
+
203
+ private fromFixture(markers: EntityFieldMarkers, fixture: EntityFixture, entityName: string): WireEntity {
204
+ const id = fixture[PRIMARY_KEY_NAME]
205
+ if (typeof id !== 'string' && typeof id !== 'number') {
206
+ throw new Error(`Every ${entityName} fixture needs an id.`)
207
+ }
208
+ const result: WireEntity = { [PRIMARY_KEY_NAME]: id, __typename: entityName }
209
+
210
+ for (const [placeholder, marker] of markers) {
211
+ if (marker instanceof FieldMarker) {
212
+ if (marker.fieldName === PRIMARY_KEY_NAME) {
213
+ continue
214
+ }
215
+ result[placeholder] = (fixture[marker.fieldName] ?? null) as WireValue
216
+ } else if (marker instanceof HasOneRelationMarker) {
217
+ const child = fixture[marker.parameters.field]
218
+ result[placeholder] = child == null
219
+ ? null
220
+ : this.fromFixture(marker.fields.markers, child as EntityFixture, this.entityNameOfRelation(marker))
221
+ } else if (marker instanceof HasManyRelationMarker) {
222
+ const children = (fixture[marker.parameters.field] ?? []) as EntityFixture[]
223
+ result[placeholder] = wireConnection(
224
+ children.map(child => this.fromFixture(marker.fields.markers, child, this.entityNameOfRelation(marker))),
225
+ ) satisfies WireConnection
226
+ }
227
+ }
228
+
229
+ return result
230
+ }
231
+
232
+ private entityNameOfRelation(marker: HasOneRelationMarker | HasManyRelationMarker): string {
233
+ return marker.environment.getSubTreeNode().entity.name
234
+ }
235
+
236
+ private idOf(entity: EntityAccessor): EntityId {
237
+ if (entity.idOnServer !== undefined) {
238
+ return entity.idOnServer
239
+ }
240
+ const alreadyAssigned = this.assignedIds.get(entity.id)
241
+ if (alreadyAssigned !== undefined) {
242
+ return alreadyAssigned
243
+ }
244
+ const assigned = `00000000-0000-4000-8000-${String(++this.idCounter).padStart(12, '0')}`
245
+ this.assignedIds.set(entity.id, assigned)
246
+ return assigned
247
+ }
248
+
249
+ private aliasOf(placeholder: string): string {
250
+ for (const [alias, aliasedPlaceholder] of this.context.markerTree.placeholdersByAliases) {
251
+ if (aliasedPlaceholder === placeholder) {
252
+ return alias
253
+ }
254
+ }
255
+ return placeholder
256
+ }
257
+ }
@@ -0,0 +1,166 @@
1
+ import { act, render } from '@testing-library/react'
2
+ import { ReactNode, useSyncExternalStore } from 'react'
3
+ import {
4
+ BindingOperations,
5
+ createQueryBuilder,
6
+ DataBinding,
7
+ EntityAccessor,
8
+ EntityListAccessor,
9
+ Environment,
10
+ PersistOptions,
11
+ Schema,
12
+ SchemaStore,
13
+ SuccessfulPersistResult,
14
+ TreeStore,
15
+ } from '@contember/binding-legacy'
16
+ import { AccessorTree, AccessorTreeState, MarkerTreeGenerator } from '@contember/react-binding'
17
+ import { FakeContentApi, SubTreeFixtures } from './FakeContentApi'
18
+
19
+ export interface BindingHarnessOptions {
20
+ schema: SchemaStore
21
+ /** The very same tree the binding renders. Sub-trees are addressed by their alias throughout the harness. */
22
+ node: ReactNode
23
+ /** What the content API answers the initial query with, keyed by sub-tree alias. */
24
+ data?: SubTreeFixtures
25
+ /** The binding debug-logs every query it sends and every error it receives. Turn this on to see them. */
26
+ logRequests?: boolean
27
+ }
28
+
29
+ export interface BindingHarness {
30
+ readonly server: FakeContentApi
31
+ /** The very same operations a component would reach through `useBindingOperations`. */
32
+ readonly bindingOperations: BindingOperations<ReactNode>
33
+ readonly treeStore: TreeStore
34
+ readonly environment: Environment
35
+ getEntity(alias: string): EntityAccessor
36
+ getEntityList(alias: string): EntityListAccessor
37
+ /**
38
+ * Runs everything the callback does inside a single `act`, so React only re-renders once it returns. Put several
39
+ * steps in one call to keep them in the same window — a persist followed by an edit, say, which is where the
40
+ * interesting races live.
41
+ */
42
+ update(performUpdates: () => void | Promise<void>): Promise<void>
43
+ persist(options?: PersistOptions): Promise<SuccessfulPersistResult>
44
+ unmount(): void
45
+ }
46
+
47
+ /**
48
+ * Mounts a data binding on top of {@link FakeContentApi} and renders `node` through it, so that a test drives the
49
+ * real thing: the query goes out, the accessors carry server data, `persist` really generates a mutation and the
50
+ * response really lands back in the tree.
51
+ */
52
+ export const createBindingHarness = async (
53
+ { schema: schemaStore, node, data, logRequests = false }: BindingHarnessOptions,
54
+ ): Promise<BindingHarness> => {
55
+ const schema = new Schema(schemaStore)
56
+ const environment = Environment.create().withSchema(schema)
57
+ const treeStore = new TreeStore(schema)
58
+ const markerTree = new MarkerTreeGenerator(node, environment).generate()
59
+ const server = new FakeContentApi({ markerTree, treeStore, queryBuilder: createQueryBuilder(schema) })
60
+
61
+ if (data !== undefined) {
62
+ server.setData(data)
63
+ }
64
+
65
+ // The binding debug-logs its queries and dumps a console.table of every error it receives.
66
+ const quietly = async (operation: () => Promise<void>) => {
67
+ if (logRequests) {
68
+ return await operation()
69
+ }
70
+ const { debug, table } = console
71
+ console.debug = () => {}
72
+ console.table = () => {}
73
+ try {
74
+ await operation()
75
+ } finally {
76
+ console.debug = debug
77
+ console.table = table
78
+ }
79
+ }
80
+
81
+ let state: AccessorTreeState = { name: 'initializing', environment }
82
+ let bindingOperations: BindingOperations<ReactNode> | undefined
83
+ const subscribers = new Set<() => void>()
84
+ const publish = (newState: AccessorTreeState) => {
85
+ state = newState
86
+ for (const subscriber of subscribers) {
87
+ subscriber()
88
+ }
89
+ }
90
+
91
+ const client = server.createClient()
92
+ const binding = new DataBinding<ReactNode>(
93
+ client,
94
+ client,
95
+ client,
96
+ treeStore,
97
+ environment,
98
+ (fragment, env) => new MarkerTreeGenerator(fragment, env).generate(),
99
+ callback => callback(),
100
+ data => {
101
+ bindingOperations = data.bindingOperations
102
+ publish({ name: 'initialized', environment, data })
103
+ },
104
+ error => publish({ name: 'error', environment, error }),
105
+ () => {},
106
+ { skipStateUpdateAfterPersist: false },
107
+ )
108
+
109
+ const subscribe = (onStoreChange: () => void) => {
110
+ subscribers.add(onStoreChange)
111
+ return () => subscribers.delete(onStoreChange)
112
+ }
113
+ const getState = () => state
114
+
115
+ const Root = () => {
116
+ const currentState = useSyncExternalStore(subscribe, getState)
117
+ return (
118
+ <AccessorTree state={currentState}>
119
+ {currentState.name === 'initialized' ? node : null}
120
+ </AccessorTree>
121
+ )
122
+ }
123
+
124
+ let result!: ReturnType<typeof render>
125
+ await quietly(async () => {
126
+ await act(async () => {
127
+ result = render(<Root />)
128
+ await binding.extendTree(node)
129
+ })
130
+ })
131
+
132
+ if (bindingOperations === undefined) {
133
+ throw new Error('The binding failed to initialize.')
134
+ }
135
+ const operations = bindingOperations
136
+
137
+ const update = async (performUpdates: () => void | Promise<void>) => {
138
+ await quietly(async () => {
139
+ await act(async () => {
140
+ await performUpdates()
141
+ })
142
+ })
143
+ }
144
+
145
+ const persist = async (options?: PersistOptions) => {
146
+ let persistResult!: SuccessfulPersistResult
147
+ await quietly(async () => {
148
+ await act(async () => {
149
+ persistResult = await operations.persist(options)
150
+ })
151
+ })
152
+ return persistResult
153
+ }
154
+
155
+ return {
156
+ server,
157
+ bindingOperations: operations,
158
+ treeStore,
159
+ environment,
160
+ getEntity: alias => treeStore.getSubTreeState('entity', undefined, alias, environment).getAccessor(),
161
+ getEntityList: alias => treeStore.getSubTreeState('entityList', undefined, alias, environment).getAccessor(),
162
+ update,
163
+ persist,
164
+ unmount: () => result.unmount(),
165
+ }
166
+ }
@@ -0,0 +1,3 @@
1
+ export * from './createBindingHarness'
2
+ export * from './FakeContentApi'
3
+ export * from './wireData'
@@ -0,0 +1,29 @@
1
+ # Binding test harness
2
+
3
+ `createBindingHarness` mounts a real `DataBinding` on a fake content API and renders a tree through it, so a test
4
+ can drive the whole thing: the read query goes out, accessors carry server data, `persist` generates a real
5
+ mutation and the response really lands back in the tree — including the id swap that turns a freshly created
6
+ entity into a persisted one.
7
+
8
+ ```tsx
9
+ const harness = await createBindingHarness({
10
+ schema: convertModelToAdminSchema(createSchema(Model).model),
11
+ data: { article: { id: articleId, title: 'Hello', blocks: [{ id: blockId, order: 0 }] } },
12
+ node: <EntitySubTree entity={`Article(id = '${articleId}')`} alias="article">…</EntitySubTree>,
13
+ })
14
+
15
+ await harness.update(() => harness.getEntity('article').getField('title').updateValue('Goodbye'))
16
+ await harness.persist()
17
+ ```
18
+
19
+ Read fixtures are keyed by sub-tree alias and address fields by name — the harness translates them to placeholders
20
+ through the marker tree.
21
+
22
+ Everything a test does to the tree belongs in `harness.update`, which wraps it in a single `act`. Several steps in
23
+ one call stay in the same window, which is how you reach the races that only happen before React re-renders.
24
+
25
+ ## What it does not do
26
+
27
+ The fake API does not read the mutation it is sent. It answers by echoing the binding's own tree back with fresh
28
+ ids, so it cannot tell you that a mutation was wrong — assert on `harness.server.requests` for that. It also
29
+ answers reads from fixtures rather than from a store, so filters and ordering are whatever the fixture says.
@@ -0,0 +1,13 @@
1
+ import { EntityId } from '@contember/binding-legacy'
2
+
3
+ /**
4
+ * The shape the content API puts on the wire, as opposed to `ReceivedEntityData`, which is what the client works
5
+ * with once `ContentClient` has unwrapped the relay-style connections.
6
+ */
7
+ export type WireEntity = { [placeholderName: string]: WireValue }
8
+
9
+ export type WireConnection = { edges: { node: WireEntity }[] }
10
+
11
+ export type WireValue = string | number | boolean | null | EntityId | WireEntity | WireConnection
12
+
13
+ export const wireConnection = (nodes: WireEntity[]): WireConnection => ({ edges: nodes.map(node => ({ node })) })