@marktiderman/genesis-core 2.10.0 → 2.12.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.
- package/README.md +191 -1
- package/dist/{chunk-LGTXQTHA.js → chunk-2VJQVAJD.js} +3 -3
- package/dist/{chunk-LGTXQTHA.js.map → chunk-2VJQVAJD.js.map} +1 -1
- package/dist/chunk-2WS4LGYU.js +47 -0
- package/dist/chunk-2WS4LGYU.js.map +1 -0
- package/dist/{chunk-KXVDDDJY.js → chunk-3B5O36DU.js} +105 -13
- package/dist/chunk-3B5O36DU.js.map +1 -0
- package/dist/{chunk-EHFYSJJA.js → chunk-42QPCDQF.js} +3 -3
- package/dist/{chunk-EHFYSJJA.js.map → chunk-42QPCDQF.js.map} +1 -1
- package/dist/{chunk-RK365SO2.js → chunk-C62CMLWG.js} +8 -5
- package/dist/chunk-C62CMLWG.js.map +1 -0
- package/dist/chunk-HYYTAJBG.js +85 -0
- package/dist/chunk-HYYTAJBG.js.map +1 -0
- package/dist/{chunk-4ZR7472O.js → chunk-LOJGHR5O.js} +4 -4
- package/dist/{chunk-4ZR7472O.js.map → chunk-LOJGHR5O.js.map} +1 -1
- package/dist/{chunk-ON2V4RXX.js → chunk-OC4OGB2K.js} +19 -11
- package/dist/chunk-OC4OGB2K.js.map +1 -0
- package/dist/{chunk-HQAVDVIH.js → chunk-POMTRNAL.js} +4 -4
- package/dist/{chunk-HQAVDVIH.js.map → chunk-POMTRNAL.js.map} +1 -1
- package/dist/{chunk-VDEW4AOS.js → chunk-PSFKIG27.js} +55 -6
- package/dist/chunk-PSFKIG27.js.map +1 -0
- package/dist/{chunk-37RWGNIO.js → chunk-VFT6QKZW.js} +114 -5
- package/dist/chunk-VFT6QKZW.js.map +1 -0
- package/dist/{chunk-VDS6REM3.js → chunk-VJGU6E4U.js} +5 -5
- package/dist/{chunk-VDS6REM3.js.map → chunk-VJGU6E4U.js.map} +1 -1
- package/dist/{chunk-ZCE3CHPX.js → chunk-XVRIWP7B.js} +3 -3
- package/dist/{chunk-ZCE3CHPX.js.map → chunk-XVRIWP7B.js.map} +1 -1
- package/dist/{chunk-7FVTGKTX.js → chunk-YDMKMNDS.js} +2 -2
- package/dist/{chunk-7FVTGKTX.js.map → chunk-YDMKMNDS.js.map} +1 -1
- package/dist/{chunk-6WV6ST67.js → chunk-YNXLPOAB.js} +97 -10
- package/dist/chunk-YNXLPOAB.js.map +1 -0
- package/dist/{chunk-7GW3QR63.js → chunk-ZHC3MDCS.js} +101 -18
- package/dist/chunk-ZHC3MDCS.js.map +1 -0
- package/dist/conversation/index.d.ts +195 -0
- package/dist/conversation/index.js +110 -0
- package/dist/conversation/index.js.map +1 -0
- package/dist/csv.d.ts +1 -1
- package/dist/errors.js +1 -2
- package/dist/form-types.d.ts +1 -1
- package/dist/gallery/index.d.ts +79 -0
- package/dist/gallery/index.js +64 -0
- package/dist/gallery/index.js.map +1 -0
- package/dist/hooks/index.d.ts +6 -4
- package/dist/hooks/index.js +19 -18
- package/dist/hooks/mutation-mode.d.ts +29 -2
- package/dist/hooks/mutation-mode.js +9 -4
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +4 -4
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-link-options.js +6 -6
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +3 -3
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-one.js +4 -4
- package/dist/hooks/use-persisted-ui-state.d.ts +12 -0
- package/dist/hooks/use-persisted-ui-state.js +5 -0
- package/dist/hooks/use-persisted-ui-state.js.map +1 -0
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +2 -2
- package/dist/hooks/use-resource-form.d.ts +14 -1
- package/dist/hooks/use-resource-form.js +12 -9
- package/dist/hooks/use-resource.d.ts +17 -3
- package/dist/hooks/use-resource.js +12 -8
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.js +22 -21
- package/dist/offline/index.d.ts +84 -0
- package/dist/offline/index.js +413 -0
- package/dist/offline/index.js.map +1 -0
- package/dist/provider/index.d.ts +60 -7
- package/dist/provider/index.js +3 -3
- package/dist/resource-view/index.d.ts +79 -4
- package/dist/resource-view/index.js +141 -19
- package/dist/resource-view/index.js.map +1 -1
- package/dist/schema/index.d.ts +4 -3
- package/dist/schema/index.js +2 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-9WnGxZhj.d.ts → types-BzLv8yOm.d.ts} +8 -0
- package/dist/types-CsKSAKqs.d.ts +143 -0
- package/dist/{viewer-scope-bthEYSOB.d.ts → viewer-scope-Dx0N9AYk.d.ts} +3 -2
- package/dist/workspaces.d.ts +1 -1
- package/dist/{write-outcome-ZWlhhzRW.d.ts → write-outcome-DC5hORz-.d.ts} +1 -1
- package/dist/write-state-DVC4Yq9T.d.ts +58 -0
- package/package.json +15 -2
- package/dist/chunk-37RWGNIO.js.map +0 -1
- package/dist/chunk-6WV6ST67.js.map +0 -1
- package/dist/chunk-7GW3QR63.js.map +0 -1
- package/dist/chunk-KXVDDDJY.js.map +0 -1
- package/dist/chunk-ON2V4RXX.js.map +0 -1
- package/dist/chunk-PA6WJE5E.js +0 -115
- package/dist/chunk-PA6WJE5E.js.map +0 -1
- package/dist/chunk-RK365SO2.js.map +0 -1
- package/dist/chunk-VDEW4AOS.js.map +0 -1
package/README.md
CHANGED
|
@@ -84,6 +84,7 @@ const provider = createSupabaseProvider(supabase, {
|
|
|
84
84
|
},
|
|
85
85
|
},
|
|
86
86
|
tasks: {
|
|
87
|
+
version: { field: "version", kind: "integer" }, // see "Versioned writes" below
|
|
87
88
|
deleteMode: "bin",
|
|
88
89
|
toFormValues: (row) => ({ ...row, done: row.status === "done" }),
|
|
89
90
|
prepare: ({ done, ...rest }) => ({ ...rest, status: done ? "done" : "open" }),
|
|
@@ -97,7 +98,8 @@ const provider = createSupabaseProvider(supabase, {
|
|
|
97
98
|
| `binTables` / `resources[r].deleteMode: "bin"` | Recycle-bin delete: check the row is visible, delete it (asking for no rows, since a binning trigger reports none), read it back. Gone from view is success; still visible is `forbidden`; not visible to begin with is `gone`. Requires binned rows to drop out of the caller's view. `deleteMode: "hard"` opts a table back out. List every soft-delete table: one that isn't listed reports a successful bin as `gone`. |
|
|
98
99
|
| `prepare(values, context)` | Runs before every create and update, overrides included. Gets a copy of the values; may be async. Throw `DataWriteError("invalid", message)` to refuse; nothing is sent. |
|
|
99
100
|
| `create(row)` | Replaces the insert, e.g. a security-definer RPC. Return the row, or its id to have it read back. If the read-back fails, the create is still reported saved (with just the id), so nobody retries into a duplicate. |
|
|
100
|
-
| `update(id, row)` | Replaces the update. Return the row, or its id (or `true`) to have it read back. Returning nothing (or `false`) means no row changed: the provider reads the row back and throws `forbidden` or `gone`, so a function that silently skips a row never reports a save. |
|
|
101
|
+
| `update(id, row, context?)` | Replaces the update. Return the row, or its id (or `true`) to have it read back. Returning nothing (or `false`) means no row changed: the provider reads the row back and throws `forbidden` or `gone` (or `conflict`, with a `version` rule), so a function that silently skips a row never reports a save. With a `version` rule and a caller's `expectedVersion`, `context.expectedVersion` is the version the row must still be at: apply the change only at it. |
|
|
102
|
+
| `version: { field, kind }` | Checks every update and delete against the version the caller read the row at. See [Versioned writes](#versioned-writes). |
|
|
101
103
|
| `toFormValues(row)` | Row → edit-form values, for a form shaped differently from its table. Served as `DataProvider.toFormValues`, which `useResourceForm` applies in edit mode. The reverse is `prepare`. |
|
|
102
104
|
| `invalidates` | Other query keys a write makes stale, as a list or `(event) => keys`. Served as `DataProvider.invalidates`, which `useResource` and `useResourceForm` (and so `ResourcePage` and `ResourceForm`) invalidate after their writes, on top of `[resource]`. |
|
|
103
105
|
| `onWrite(event)` | Called after every committed create, update and delete, including writes made straight through the provider. Awaited; if it throws, the error is logged and the write is still reported saved. |
|
|
@@ -165,6 +167,92 @@ try {
|
|
|
165
167
|
}
|
|
166
168
|
```
|
|
167
169
|
|
|
170
|
+
### Versioned writes
|
|
171
|
+
|
|
172
|
+
Without a version, two people editing the same record both "save", and the second silently
|
|
173
|
+
overwrites the first. With a `version` rule, the second save is refused as a `conflict`:
|
|
174
|
+
|
|
175
|
+
```sql
|
|
176
|
+
-- genesis-supabase migration 0019 ships the trigger (the versioned-writes block).
|
|
177
|
+
alter table public.tasks add column version bigint not null default 1;
|
|
178
|
+
create trigger tasks_version_bump before update on public.tasks
|
|
179
|
+
for each row execute function public.genesis_version_bump('version');
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
createSupabaseProvider(supabase, {
|
|
184
|
+
resources: { tasks: { version: { field: "version", kind: "integer" } } },
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
- `capabilities("tasks")` reports `versionedWrites: true` and `version: { field, kind }`.
|
|
189
|
+
- `useResource` and `useResourceForm` (and so `ResourceView`, `ResourceForm` and `RecordView`'s
|
|
190
|
+
forms) send the version of the row the change was made on as `expectedVersion`: the record an edit
|
|
191
|
+
form opened with, else the row cached when the write was made (before an optimistic change or a
|
|
192
|
+
refetch replaces it). A write made while an earlier one on the same record is still unsettled is
|
|
193
|
+
checked against the version that one committed at. After a save they put the new version into
|
|
194
|
+
every cached copy, so the next edit is checked against it, not the one before.
|
|
195
|
+
- `RecordView`'s settings sections (web and native) send the version of the row as it was when
|
|
196
|
+
the person started editing (after a save, the version that save left), not a row that refreshed
|
|
197
|
+
meanwhile. They save only the fields the person changed.
|
|
198
|
+
- `useDraft` saves through the app's own `update(row, value)`: pass `expectedVersion` from the row
|
|
199
|
+
it's given to have a draft's saves checked.
|
|
200
|
+
- The version is read from the rows the app reads, so the resource's `select` or `source` view must
|
|
201
|
+
carry the column. If it doesn't, writes go out unchecked, with a warning in development.
|
|
202
|
+
- The update or delete runs `where id = … and version = …`. When no row matches, the provider
|
|
203
|
+
reads the row back: at another version is `conflict`, with `error.current` (the row as it is now,
|
|
204
|
+
read through the resource's `source` and `select`) and `error.currentVersion`; still at the
|
|
205
|
+
expected version is `forbidden`; not visible is `gone`. A `timestamp` version is compared as an
|
|
206
|
+
instant, so the same time formatted two ways (a realtime payload, a PostgREST read) is one version.
|
|
207
|
+
- An `update` rule replaces the check: it is given `{ expectedVersion }` and must apply it. One that
|
|
208
|
+
takes no third argument gets a warning in development.
|
|
209
|
+
- The database advances the version, never the client: the provider drops a submitted value, and
|
|
210
|
+
`genesis_version_bump` sets it to the old value plus one whatever an update writes. `kind:
|
|
211
|
+
"timestamp"` works the same with a column a trigger sets to `now()` on update (`moddatetime`).
|
|
212
|
+
- A write sent without `expectedVersion` (a row that wasn't read first, a provider without
|
|
213
|
+
capabilities) is not checked. A resource without the rule behaves exactly as before.
|
|
214
|
+
- A recycle-bin table checks the version before the delete, and the delete carries it too, so a
|
|
215
|
+
change landing between the two leaves the row in place and reads back as a `conflict`.
|
|
216
|
+
|
|
217
|
+
#### Showing a conflict
|
|
218
|
+
|
|
219
|
+
A conflict is a choice for the person, not just an error. `writeConflict(error, mine, { changed })`
|
|
220
|
+
turns a `conflict` into a `WriteConflict`: `theirs` (the row as it is now), `mine` (what the save
|
|
221
|
+
tried), `fields` (the ones this person changed that differ from theirs) and `currentVersion`.
|
|
222
|
+
`useResourceForm` keeps one as `conflict`, with `keepMine()`, `takeTheirs()` and
|
|
223
|
+
`dismissConflict()`. Keep mine sends only this person's changes as theirs to keep, at
|
|
224
|
+
`currentVersion`; every other field takes their value, so a field only they changed is never put
|
|
225
|
+
back. After take theirs, the next save is checked against their version. Until the person saves or
|
|
226
|
+
takes theirs, what they typed stays on the form, even when a rolled-back optimistic save refetches
|
|
227
|
+
their row, so neither a second conflict nor closing the sheet loses it. A form's own `onError`
|
|
228
|
+
still receives the conflict (to log it); `ResourceForm` doesn't toast it, since the sheet shows it. `ConflictSheet` (genesis-ui) and `NativeConflictSheet` (genesis-ui-native)
|
|
229
|
+
show it, theirs first; `ResourceForm`, `RecordView`'s settings sections and Data Studio's record
|
|
230
|
+
panel open it themselves.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { DataWriteError, writeConflict } from "@marktiderman/genesis-core";
|
|
234
|
+
|
|
235
|
+
const error = new DataWriteError("conflict", "Someone else changed this task.", {
|
|
236
|
+
current: { id: "t1", title: "Theirs", version: 5 },
|
|
237
|
+
currentVersion: "5",
|
|
238
|
+
});
|
|
239
|
+
const conflict = writeConflict(error, { title: "Mine" });
|
|
240
|
+
// conflict?.fields is ["title"]; send "keep mine" with expectedVersion: conflict.currentVersion.
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Outside a form, send "keep mine" with `useResource`'s `update(id, data, { expectedVersion })`
|
|
244
|
+
(`UpdateOptions`), from a `useResource` in pessimistic mode (the default): a conflict then rejects
|
|
245
|
+
`update` itself, so the screen can show the sheet again. In optimistic and undoable modes `update`
|
|
246
|
+
has already resolved, and a conflict goes to `onError` instead. It goes through the resource's write path like any update: queued behind another
|
|
247
|
+
write of the row, its committed version put into every cached copy, the screen's `onError` and
|
|
248
|
+
invalidations applied. So the next change of that row is checked against it. Calling
|
|
249
|
+
`provider.update` directly skips all of that, and a change made right after it would conflict with
|
|
250
|
+
the save it just made. `ResourceView`'s board sends its "keep mine" this way, and `RecordView`'s
|
|
251
|
+
settings sections (web and native) send every save this way, at the version the edit started on.
|
|
252
|
+
|
|
253
|
+
`WriteState` (`pending`, `sending`, `paused`, `failed`, `conflict`) is the one shape for showing
|
|
254
|
+
where a write stands, on a row or a form.
|
|
255
|
+
|
|
168
256
|
### Races, and what the read-back can't tell you
|
|
169
257
|
|
|
170
258
|
- A read-back runs after the write, so it reports what is true then. If
|
|
@@ -374,6 +462,66 @@ steps.setSorts([{ field: "stage", order: "desc" }]); // setSort(one) replaces th
|
|
|
374
462
|
scrolled (its sort value changed, or rows were added before it) is shown
|
|
375
463
|
where it first appeared, not twice.
|
|
376
464
|
|
|
465
|
+
## Open from the device (`/offline`)
|
|
466
|
+
|
|
467
|
+
Lists and records a person has already seen open at once from the device, before the network
|
|
468
|
+
answers, and then refresh as usual. `persistOffline` keeps the reads of the resources you list,
|
|
469
|
+
each record stored once, in a `LocalCache`, and puts them back into the QueryClient before the
|
|
470
|
+
screens first render:
|
|
471
|
+
|
|
472
|
+
```tsx
|
|
473
|
+
import { GenesisProvider } from "@marktiderman/genesis-core";
|
|
474
|
+
import { cacheScope, indexedDbLocalCache, persistOffline } from "@marktiderman/genesis-core/offline";
|
|
475
|
+
|
|
476
|
+
// Once, outside your components: the provider keeps the first one it's given.
|
|
477
|
+
const persist = persistOffline({ cache: indexedDbLocalCache(), resources: ["tasks", "people"], buster: "2026.11.1" });
|
|
478
|
+
|
|
479
|
+
// userId: undefined while the session loads, null once nobody is signed in.
|
|
480
|
+
export function Root({ provider, userId }: { provider: DataProvider; userId: string | null | undefined }) {
|
|
481
|
+
return (
|
|
482
|
+
<GenesisProvider provider={provider} persist={persist} persistScope={userId ? cacheScope(userId) : userId}>
|
|
483
|
+
<App />
|
|
484
|
+
</GenesisProvider>
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
- **Opt in per resource.** Only the listed resources' reads are written. Keeping data on a
|
|
490
|
+
device is a decision: leave out anything that shouldn't sit there unencrypted.
|
|
491
|
+
- **Whose cache.** `cacheScope(userId, workspaceKey)` keys every bucket to the person and the
|
|
492
|
+
workspace they're in, so another person's reads, or another workspace's, are never restored.
|
|
493
|
+
- **A device is one person's.** Restoring someone deletes every other person's reads first, and
|
|
494
|
+
`persistScope={null}` (nobody signed in) deletes them all. So a session that ended outside the
|
|
495
|
+
app (it expired, or was signed out elsewhere) leaves nothing on a shared device for the next
|
|
496
|
+
person. While the session is still loading, pass `undefined`: nothing is restored, saved or
|
|
497
|
+
deleted. When the scope arrives, the lists on screen are read again, and only reads made once
|
|
498
|
+
it's known are saved: nothing the client held or was reading before is trusted to be this
|
|
499
|
+
person's, so no change of person, workspace or provider mount carries reads over. Infinite
|
|
500
|
+
lists start again from their first page. Change `persistScope` only once the data provider's
|
|
501
|
+
session has: a scope must never name a person before requests are made as them. A sign-out
|
|
502
|
+
also calls off a restore still reading.
|
|
503
|
+
- **`ViewerScope` keeps them.** Inside this provider, a `ViewerScope` whose first viewer is
|
|
504
|
+
`persistScope`'s user keeps the restored reads instead of emptying the cache.
|
|
505
|
+
- **Only what the server said.** A read is kept when a fetch comes back, never an optimistic
|
|
506
|
+
change or a live hint's merge, which the next fetch confirms or undoes.
|
|
507
|
+
- **Fresh after.** A restored read carries the time it was fetched, so a screen refetches it once
|
|
508
|
+
it's stale (the client's `staleTime`), like any cached read, and it never replaces a newer read
|
|
509
|
+
already in the client. The first render waits at most 400 ms for the device; a slow device read
|
|
510
|
+
doesn't hold the app, and nothing waits on the server.
|
|
511
|
+
- **One shape per row.** Reads of whole rows (no `select`) share one stored copy of each record;
|
|
512
|
+
a newer read replaces it, so a field the server stops returning is gone, and a record that
|
|
513
|
+
comes back empty is deleted. A projected read (`select`) is kept as it came.
|
|
514
|
+
- **Expiry and size.** `maxAge` (default 7 days) drops older reads and `maxReads` (default 200)
|
|
515
|
+
keeps only the most recently fetched; each start deletes the rest and the rows nothing refers
|
|
516
|
+
to. A different `buster` (your app version), or a bucket that can't be read, discards it.
|
|
517
|
+
- **Client-only.** In a server-rendered app, give `persistScope` after hydration (`undefined` on the
|
|
518
|
+
server and the first client render): the screens render at once and restore in the background.
|
|
519
|
+
- **Adapters.** `indexedDbLocalCache()` on the web (`persist: true` asks the browser to keep the
|
|
520
|
+
storage; off by default, since some browsers ask the person, so the browser may evict it, and
|
|
521
|
+
it's rebuilt from the server), `sqliteLocalCache({ db })`
|
|
522
|
+
on the phone (genesis-native `/offline`), and `memoryLocalCache()` for tests. Each implements
|
|
523
|
+
`LocalCache`, and a wipe loses nothing but speed.
|
|
524
|
+
|
|
377
525
|
## Live updates (realtime)
|
|
378
526
|
|
|
379
527
|
`useResource(resource, { live: true })`, `useOne(resource, id, { live: true })`
|
|
@@ -555,6 +703,33 @@ const draft = useDraft({
|
|
|
555
703
|
`DraftController` is the same logic without React, for tests or other
|
|
556
704
|
frameworks.
|
|
557
705
|
|
|
706
|
+
## Remembered UI state
|
|
707
|
+
|
|
708
|
+
`usePersistedUiState(key, initial)` keeps a piece of UI state past a reload: a collapsed sidebar, a
|
|
709
|
+
table's column widths, a panel's size. It stores it through the app's storage adapter (`useStorage()`:
|
|
710
|
+
localStorage on the web, the adapter `GenesisProvider` was given on a phone).
|
|
711
|
+
|
|
712
|
+
```tsx
|
|
713
|
+
import { usePersistedUiState } from "@marktiderman/genesis-core/hooks";
|
|
714
|
+
|
|
715
|
+
function Sidebar() {
|
|
716
|
+
const [collapsed, setCollapsed] = usePersistedUiState("acme:sidebar", false);
|
|
717
|
+
return <button onClick={() => setCollapsed(!collapsed)}>{collapsed ? "Expand" : "Collapse"}</button>;
|
|
718
|
+
}
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
- **SSR-safe:** the server renders `initial` and the client hydrates against it, then shows the
|
|
722
|
+
stored value, so there's no hydration mismatch. A client-only render reads storage directly,
|
|
723
|
+
with no flash of the default.
|
|
724
|
+
- **In step:** every hook on the same key, on the page or in another tab, sees a write.
|
|
725
|
+
- **Defaults stay defaults:** `initial` is never written, so changing it reaches everyone who
|
|
726
|
+
hasn't chosen. `set(undefined)` clears the stored value back to `initial`.
|
|
727
|
+
- **Forgiving:** a stored value `parse` refuses reads as `initial`; a write storage won't keep
|
|
728
|
+
(a full quota, a private window) still applies while the component is mounted.
|
|
729
|
+
- **Optional:** a `null` key is plain state, for a component whose persistence a key prop turns on.
|
|
730
|
+
- **An existing format:** `parse` and `serialize` read and write what's already stored, for example
|
|
731
|
+
`"1"`/`"0"` as AppShell's collapsed sidebar does, so moving onto the hook keeps users' choices.
|
|
732
|
+
|
|
558
733
|
## Query keys
|
|
559
734
|
|
|
560
735
|
Build every cache key in one place, so a write invalidates what it made stale and nothing cached for
|
|
@@ -661,6 +836,21 @@ readinessChip(readinessOf(findings, { emptyCode: "no-lessons" }), { empty: "Add
|
|
|
661
836
|
// → { label: "Add a lesson", tone: "muted" }
|
|
662
837
|
```
|
|
663
838
|
|
|
839
|
+
## Conversations (`/conversation`)
|
|
840
|
+
|
|
841
|
+
The contract web and native messaging layouts share: `ThreadMessage` (with `kind`, `status`, `tone`),
|
|
842
|
+
`ThreadComposer` and `ComposerMode`, `ThreadLabels` with `DEFAULT_THREAD_LABELS`, `InboxItem`, and
|
|
843
|
+
`readReceiptFor`, `formatInboxTime` and `formatMessageTime`. genesis-ui's and genesis-ui-native's
|
|
844
|
+
`ThreadPage` and `InboxPage` render the same data. `useThreadJump` is the jump to one row: it
|
|
845
|
+
waits for the first page, loads until the row is held, highlights it and says when it can't be found.
|
|
846
|
+
|
|
847
|
+
```ts
|
|
848
|
+
import { readReceiptFor, type ThreadMessage } from "@marktiderman/genesis-core/conversation";
|
|
849
|
+
|
|
850
|
+
const rows: ThreadMessage[] = [{ id: "m1", body: "Hi", mine: true, timestamp: "2026-11-03T09:00:00Z" }];
|
|
851
|
+
const receiptOn = readReceiptFor(rows, "2026-11-03T09:05:00Z"); // "m1"
|
|
852
|
+
```
|
|
853
|
+
|
|
664
854
|
## Days and time zones (`/dates`)
|
|
665
855
|
|
|
666
856
|
A day is a `YYYY-MM-DD` string: the date on one time zone's clock. `new Date().toISOString().slice(0, 10)`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useDataProvider } from './chunk-
|
|
1
|
+
import { useDataProvider } from './chunk-PSFKIG27.js';
|
|
2
2
|
import { useQuery } from '@tanstack/react-query';
|
|
3
3
|
|
|
4
4
|
var providerIds = /* @__PURE__ */ new WeakMap();
|
|
@@ -27,5 +27,5 @@ function useCapabilities(resource, options = {}) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
export { capabilitiesQueryKey, useCapabilities };
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
31
|
-
//# sourceMappingURL=chunk-
|
|
30
|
+
//# sourceMappingURL=chunk-2VJQVAJD.js.map
|
|
31
|
+
//# sourceMappingURL=chunk-2VJQVAJD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-capabilities.ts"],"names":[],"mappings":";;;AAMA,IAAM,WAAA,uBAAkB,OAAA,EAAwB;AAChD,IAAI,cAAA,GAAiB,CAAA;AAErB,SAAS,WAAW,QAAA,EAA0B;AAC5C,EAAA,IAAI,EAAA,GAAK,WAAA,CAAY,GAAA,CAAI,QAAQ,CAAA;AACjC,EAAA,IAAI,OAAO,MAAA,EAAW;AACpB,IAAA,EAAA,GAAK,cAAA,EAAA;AACL,IAAA,WAAA,CAAY,GAAA,CAAI,UAAU,EAAE,CAAA;AAAA,EAC9B;AACA,EAAA,OAAO,EAAA;AACT;AAQO,SAAS,oBAAA,CAAqB,UAAkB,QAAA,EAAkD;AACvG,EAAA,OAAO,CAAC,gBAAA,EAAkB,UAAA,CAAW,QAAQ,CAAA,EAAG,YAAY,EAAE,CAAA;AAChE;AAOO,SAAS,eAAA,CACd,QAAA,EACA,OAAA,GAAiC,EAAC,EACI;AACtC,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,OAAO,QAAA,CAA+B;AAAA,IACpC,QAAA,EAAU,oBAAA,CAAqB,QAAA,EAAU,QAAQ,CAAA;AAAA,IACjD,OAAA,EAAS,MAAM,QAAA,CAAS,YAAA,CAAc,QAAQ,CAAA;AAAA,IAC9C,UAAU,OAAA,CAAQ,OAAA,IAAW,IAAA,KAAS,CAAC,CAAC,QAAA,CAAS,YAAA;AAAA;AAAA;AAAA,IAGjD,SAAA,EAAW;AAAA,GACZ,CAAA;AACH","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-capabilities.ts"],"names":[],"mappings":";;;AAMA,IAAM,WAAA,uBAAkB,OAAA,EAAwB;AAChD,IAAI,cAAA,GAAiB,CAAA;AAErB,SAAS,WAAW,QAAA,EAA0B;AAC5C,EAAA,IAAI,EAAA,GAAK,WAAA,CAAY,GAAA,CAAI,QAAQ,CAAA;AACjC,EAAA,IAAI,OAAO,MAAA,EAAW;AACpB,IAAA,EAAA,GAAK,cAAA,EAAA;AACL,IAAA,WAAA,CAAY,GAAA,CAAI,UAAU,EAAE,CAAA;AAAA,EAC9B;AACA,EAAA,OAAO,EAAA;AACT;AAQO,SAAS,oBAAA,CAAqB,UAAkB,QAAA,EAAkD;AACvG,EAAA,OAAO,CAAC,gBAAA,EAAkB,UAAA,CAAW,QAAQ,CAAA,EAAG,YAAY,EAAE,CAAA;AAChE;AAOO,SAAS,eAAA,CACd,QAAA,EACA,OAAA,GAAiC,EAAC,EACI;AACtC,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,OAAO,QAAA,CAA+B;AAAA,IACpC,QAAA,EAAU,oBAAA,CAAqB,QAAA,EAAU,QAAQ,CAAA;AAAA,IACjD,OAAA,EAAS,MAAM,QAAA,CAAS,YAAA,CAAc,QAAQ,CAAA;AAAA,IAC9C,UAAU,OAAA,CAAQ,OAAA,IAAW,IAAA,KAAS,CAAC,CAAC,QAAA,CAAS,YAAA;AAAA;AAAA;AAAA,IAGjD,SAAA,EAAW;AAAA,GACZ,CAAA;AACH","file":"chunk-2VJQVAJD.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { ProviderCapabilities } from \"../schema/types\";\n\n// A stable id per provider object, so capabilities cached for one provider\n// are never served for another that shares the same QueryClient.\nconst providerIds = new WeakMap<object, number>();\nlet nextProviderId = 1;\n\nfunction providerId(provider: object): number {\n let id = providerIds.get(provider);\n if (id === undefined) {\n id = nextProviderId++;\n providerIds.set(provider, id);\n }\n return id;\n}\n\n/**\n * The query key for `provider`'s capabilities for `resource`. It includes\n * the provider's identity: swapping the provider (another tenant, a\n * different store) asks the new one instead of reusing the old answer.\n * @internal\n */\nexport function capabilitiesQueryKey(provider: object, resource: string | undefined): readonly unknown[] {\n return [\"__capabilities\", providerId(provider), resource ?? \"\"];\n}\n\n/**\n * What the data provider can do for `resource` (`provider.capabilities`),\n * cached per provider and resource. `data` stays undefined for a provider\n * that doesn't report capabilities, so a UI keeps its defaults.\n */\nexport function useCapabilities(\n resource: string | undefined,\n options: { enabled?: boolean } = {},\n): UseQueryResult<ProviderCapabilities> {\n const provider = useDataProvider();\n return useQuery<ProviderCapabilities>({\n queryKey: capabilitiesQueryKey(provider, resource),\n queryFn: () => provider.capabilities!(resource),\n enabled: (options.enabled ?? true) && !!provider.capabilities,\n // Fresh for as long as this provider is in use; a swapped-out provider's\n // entry has no observers and is collected after the usual gcTime.\n staleTime: Infinity,\n });\n}\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { isDataWriteError } from './chunk-LG6TUBVM.js';
|
|
2
|
+
|
|
3
|
+
// src/schema/write-state.ts
|
|
4
|
+
var empty = (v) => v === null || v === void 0 || v === "";
|
|
5
|
+
var DATE = /^\d{4}-\d{2}-\d{2}([T ]|$)/;
|
|
6
|
+
function canonical(value) {
|
|
7
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
8
|
+
if (value instanceof Date) return value.toISOString();
|
|
9
|
+
if (value && typeof value === "object") {
|
|
10
|
+
return Object.fromEntries(
|
|
11
|
+
Object.keys(value).sort().map((k) => [k, canonical(value[k])])
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function same(a, b) {
|
|
17
|
+
if (Object.is(a, b) || empty(a) && empty(b)) return true;
|
|
18
|
+
if (empty(a) || empty(b)) return false;
|
|
19
|
+
if (typeof a === "number" || typeof b === "number") {
|
|
20
|
+
const x = Number(a);
|
|
21
|
+
const y = Number(b);
|
|
22
|
+
if (!Number.isNaN(x) && !Number.isNaN(y) && typeof a !== "boolean" && typeof b !== "boolean") return x === y;
|
|
23
|
+
}
|
|
24
|
+
const asTime = (v) => v instanceof Date ? v.getTime() : typeof v === "string" && DATE.test(v) ? Date.parse(v) : NaN;
|
|
25
|
+
const t = asTime(a);
|
|
26
|
+
if (!Number.isNaN(t) && t === asTime(b)) return true;
|
|
27
|
+
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
28
|
+
try {
|
|
29
|
+
return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function writeConflict(error, mine, options = {}) {
|
|
35
|
+
if (!isDataWriteError(error) || error.outcome !== "conflict" || !error.current) return null;
|
|
36
|
+
const row = error.current;
|
|
37
|
+
const theirs = options.view ? options.view(row) : row;
|
|
38
|
+
const changed = options.changed ? new Set(options.changed) : void 0;
|
|
39
|
+
const fields = Object.keys(mine).filter(
|
|
40
|
+
(field) => (!changed || changed.has(field)) && (!(field in theirs) || !same(mine[field], theirs[field]))
|
|
41
|
+
);
|
|
42
|
+
return { theirs, mine, fields, currentVersion: error.currentVersion ?? null };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export { writeConflict };
|
|
46
|
+
//# sourceMappingURL=chunk-2WS4LGYU.js.map
|
|
47
|
+
//# sourceMappingURL=chunk-2WS4LGYU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/schema/write-state.ts"],"names":[],"mappings":"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","file":"chunk-2WS4LGYU.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Where a write stands, and what a conflict asks the person to choose\n//\n// One shape for every surface that shows a write's progress: a form, a\n// record's settings, a row in a list, a chat message. `WriteConflict` is what\n// ConflictSheet (genesis-ui) and NativeConflictSheet (genesis-ui-native)\n// render: the row as someone else left it, beside what this person tried to\n// save, for the fields where the two differ.\n// ---------------------------------------------------------------------------\n\nimport { isDataWriteError } from \"./write-outcome\";\n\n/** A versioned write that met someone else's change (a `conflict` outcome). */\nexport interface WriteConflict {\n /** The row as it is now, after their change. */\n readonly theirs: Readonly<Record<string, unknown>>;\n /** The values this write tried to save. */\n readonly mine: Readonly<Record<string, unknown>>;\n /**\n * The fields this person changed whose value differs from `theirs`, in\n * `mine`'s order: the ones the choice is about. Empty when they already agree.\n */\n readonly fields: readonly string[];\n /** The version the row is at now: send \"keep mine\" at it. Null when the row carries none. */\n readonly currentVersion: string | null;\n}\n\n/**\n * Where one write stands, for a row's badge or a form's status.\n *\n * - `pending`: made, not yet sent (queued, or waiting out an undo delay).\n * - `sending`: on its way.\n * - `paused`: held until the person signs in again, or comes back online.\n * - `failed`: refused or broken; `message` says why in plain words.\n * - `conflict`: someone else changed the row first; see `conflict`.\n */\nexport type WriteState =\n | { readonly status: \"pending\" }\n | { readonly status: \"sending\" }\n | { readonly status: \"paused\"; readonly message: string }\n | { readonly status: \"failed\"; readonly message: string }\n | { readonly status: \"conflict\"; readonly message: string; readonly conflict: WriteConflict };\n\nconst empty = (v: unknown) => v === null || v === undefined || v === \"\";\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}([T ]|$)/;\n\n/** A JSON-like value with object keys in order, so `{x,y}` and `{y,x}` compare equal. */\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonical);\n if (value instanceof Date) return value.toISOString();\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value as object)\n .sort()\n .map((k) => [k, canonical((value as Record<string, unknown>)[k])]),\n );\n }\n return value;\n}\n\n/**\n * Equal for a choice. An empty input and a null column are the same; a number and the text a form\n * holds for it are the same; a date and a timestamp of that instant are the same; objects compare\n * by content, whatever their key order.\n */\nfunction same(a: unknown, b: unknown): boolean {\n if (Object.is(a, b) || (empty(a) && empty(b))) return true;\n if (empty(a) || empty(b)) return false;\n if (typeof a === \"number\" || typeof b === \"number\") {\n const x = Number(a);\n const y = Number(b);\n if (!Number.isNaN(x) && !Number.isNaN(y) && typeof a !== \"boolean\" && typeof b !== \"boolean\") return x === y;\n }\n const asTime = (v: unknown) => (v instanceof Date ? v.getTime() : typeof v === \"string\" && DATE.test(v) ? Date.parse(v) : NaN);\n const t = asTime(a);\n if (!Number.isNaN(t) && t === asTime(b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n try {\n return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));\n } catch {\n return false;\n }\n}\n\n/** Options for {@link writeConflict}. */\nexport interface WriteConflictOptions {\n /**\n * The fields this person changed. Only these are offered as a choice; the rest of `mine` is\n * what the form loaded, and \"keep mine\" must not put it back over theirs. Default: every field\n * of `mine`.\n */\n readonly changed?: Iterable<string>;\n /** Shapes their row like `mine` (a form's `toFormValues`), before comparing. */\n readonly view?: (row: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/**\n * The conflict `error` reports for a write of `mine`, or null when `error`\n * isn't a `conflict` that carries the row as it is now. A field `mine` has and\n * their row doesn't (a column it doesn't read) counts as different: the\n * person decides it, never a silent \"nothing to choose\".\n */\nexport function writeConflict(\n error: unknown,\n mine: Readonly<Record<string, unknown>>,\n options: WriteConflictOptions = {},\n): WriteConflict | null {\n if (!isDataWriteError(error) || error.outcome !== \"conflict\" || !error.current) return null;\n const row = error.current as Record<string, unknown>;\n const theirs = options.view ? options.view(row) : row;\n const changed = options.changed ? new Set(options.changed) : undefined;\n const fields = Object.keys(mine).filter(\n (field) => (!changed || changed.has(field)) && (!(field in theirs) || !same(mine[field], theirs[field])),\n );\n return { theirs, mine, fields, currentVersion: error.currentVersion ?? null };\n}\n"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { writeConflict } from './chunk-2WS4LGYU.js';
|
|
1
2
|
import { useUnsavedChangesGuard } from './chunk-RVWKVD5Q.js';
|
|
2
|
-
import { useOne } from './chunk-4ZR7472O.js';
|
|
3
|
-
import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-6WV6ST67.js';
|
|
4
|
-
import { useDataProvider, useStorage } from './chunk-VDEW4AOS.js';
|
|
5
3
|
import { relatedKeys } from './chunk-7NUL32W7.js';
|
|
4
|
+
import { useOne } from './chunk-LOJGHR5O.js';
|
|
5
|
+
import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-YNXLPOAB.js';
|
|
6
|
+
import { useDataProvider, useStorage } from './chunk-PSFKIG27.js';
|
|
7
|
+
import { patchCachedRow } from './chunk-AUVKRXRC.js';
|
|
6
8
|
import { titleCase } from './chunk-RYEXWQFD.js';
|
|
7
9
|
import { isDataWriteError } from './chunk-LG6TUBVM.js';
|
|
8
10
|
import { useMemo, useRef, useEffect, useState, useCallback } from 'react';
|
|
@@ -443,8 +445,25 @@ function useResourceForm(options) {
|
|
|
443
445
|
},
|
|
444
446
|
[form, showError, onError, action, resource]
|
|
445
447
|
);
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
+
const [conflictState, setConflictState] = useState(null);
|
|
449
|
+
const [rebased, setRebased] = useState(null);
|
|
450
|
+
const conflictsFound = useRef(0);
|
|
451
|
+
const rebasedFor = useRef(effectiveData);
|
|
452
|
+
useEffect(() => {
|
|
453
|
+
if (sameValue(rebasedFor.current, effectiveData)) return;
|
|
454
|
+
rebasedFor.current = effectiveData;
|
|
455
|
+
setRebased(null);
|
|
456
|
+
}, [effectiveData]);
|
|
457
|
+
const [unsettled, setUnsettled] = useState(null);
|
|
458
|
+
useEffect(() => {
|
|
459
|
+
if (!unsettled) return;
|
|
460
|
+
for (const key of unsettled.changed) {
|
|
461
|
+
if (!sameValue(form.getValues(key), unsettled.values[key])) form.setValue(key, unsettled.values[key], { shouldDirty: true });
|
|
462
|
+
}
|
|
463
|
+
}, [unsettled, defaultValues, form]);
|
|
464
|
+
const save = useCallback(
|
|
465
|
+
async (submitted, expectedVersion, keep) => {
|
|
466
|
+
if (expectedVersion === void 0) setConflictState(null);
|
|
448
467
|
const shown = structuredCloneSafe(form.getValues());
|
|
449
468
|
const opened = formSource;
|
|
450
469
|
const lockedOnEdit = new Set(action === "edit" ? resolvedFields.filter((f) => f.readOnlyOnEdit).map((f) => f.key) : []);
|
|
@@ -457,13 +476,26 @@ function useResourceForm(options) {
|
|
|
457
476
|
)
|
|
458
477
|
) : writable;
|
|
459
478
|
const touched = new Set(
|
|
460
|
-
Object.entries(changed).filter(([k, v]) => !sameValue(k in shown ? shown[k] : v, defaultValues[k])).map(([k]) => k)
|
|
479
|
+
keep ?? Object.entries(changed).filter(([k, v]) => !sameValue(k in shown ? shown[k] : v, defaultValues[k])).map(([k]) => k)
|
|
461
480
|
);
|
|
462
481
|
const formData = blankValues(changed, resolvedFields, action, touched);
|
|
482
|
+
const conflictOf = (error) => {
|
|
483
|
+
const found = writeConflict(error, formData, {
|
|
484
|
+
changed: touched,
|
|
485
|
+
...provider.toFormValues && formSource !== effectiveData ? { view: (row) => provider.toFormValues(resource, row) } : {}
|
|
486
|
+
});
|
|
487
|
+
if (found && isDataWriteError(error) && error.current) {
|
|
488
|
+
conflictsFound.current += 1;
|
|
489
|
+
setUnsettled({ changed: [...touched], values: { ...submitted } });
|
|
490
|
+
setConflictState({ conflict: found, submitted, changed: [...touched], row: error.current });
|
|
491
|
+
}
|
|
492
|
+
return found;
|
|
493
|
+
};
|
|
463
494
|
if (action === "edit" && Object.keys(formData).length === 0) {
|
|
495
|
+
setConflictState(null);
|
|
464
496
|
markSaved();
|
|
465
497
|
onSuccess?.({ ...effectiveData ?? {}, ...id != null && id !== "" ? { id } : {} });
|
|
466
|
-
return;
|
|
498
|
+
return true;
|
|
467
499
|
}
|
|
468
500
|
try {
|
|
469
501
|
let recordId;
|
|
@@ -483,15 +515,28 @@ function useResourceForm(options) {
|
|
|
483
515
|
// The cache holds rows; patch it only when the form's values are
|
|
484
516
|
// row-shaped (no provider.toFormValues reshaping this record).
|
|
485
517
|
data: formSource === effectiveData ? formData : void 0,
|
|
518
|
+
// The record the form shows: its version is the one this edit is checked against, even
|
|
519
|
+
// when the cache has since refetched a newer one.
|
|
520
|
+
...action === "edit" && (rebased ?? effectiveData) ? { base: rebased ?? effectiveData } : {},
|
|
521
|
+
...expectedVersion !== void 0 ? { expectedVersion } : {},
|
|
486
522
|
mode: mutationMode,
|
|
487
523
|
undoDelayMs,
|
|
488
524
|
onUndoable,
|
|
489
525
|
send: async (ctx) => {
|
|
490
526
|
const keepalive = ctx.keepalive ? { keepalive: true } : {};
|
|
491
|
-
const res = action === "create" ? await provider.create(resource, { data: formData, ...keepalive }) : await provider.update(resource, {
|
|
527
|
+
const res = action === "create" ? await provider.create(resource, { data: formData, ...keepalive }) : await provider.update(resource, {
|
|
528
|
+
id: recordId,
|
|
529
|
+
data: ctx.data ?? formData,
|
|
530
|
+
...keepalive,
|
|
531
|
+
...ctx.expectedVersion !== void 0 ? { expectedVersion: ctx.expectedVersion } : {}
|
|
532
|
+
});
|
|
492
533
|
return { record: res.data, audit: res.audit };
|
|
493
534
|
},
|
|
494
535
|
committed: async (result) => {
|
|
536
|
+
if (action === "edit" && mountedRef.current && result && typeof result === "object") {
|
|
537
|
+
const saved = result;
|
|
538
|
+
setRebased((prev) => ({ ...prev ?? effectiveData ?? {}, ...saved }));
|
|
539
|
+
}
|
|
495
540
|
if (autosaveEnabled && action === "create") {
|
|
496
541
|
try {
|
|
497
542
|
storage.removeItem(`genesis-draft:${resource}:new`);
|
|
@@ -512,8 +557,13 @@ function useResourceForm(options) {
|
|
|
512
557
|
);
|
|
513
558
|
await Promise.all(related.map((queryKey) => queryClient.invalidateQueries({ queryKey: [...queryKey] })));
|
|
514
559
|
},
|
|
515
|
-
failedLater: (error) =>
|
|
560
|
+
failedLater: (error) => {
|
|
561
|
+
if (mountedRef.current) conflictOf(error);
|
|
562
|
+
reportError(error, shown);
|
|
563
|
+
}
|
|
516
564
|
});
|
|
565
|
+
setConflictState(null);
|
|
566
|
+
setUnsettled(null);
|
|
517
567
|
markSaved();
|
|
518
568
|
if (outcome.status === "committed") {
|
|
519
569
|
onSuccess?.(outcome.record);
|
|
@@ -522,12 +572,50 @@ function useResourceForm(options) {
|
|
|
522
572
|
action === "edit" ? { ...before ?? effectiveData ?? {}, ...formData, id: recordId } : { ...formData }
|
|
523
573
|
);
|
|
524
574
|
}
|
|
575
|
+
return true;
|
|
525
576
|
} catch (err) {
|
|
577
|
+
conflictOf(err);
|
|
526
578
|
reportError(err instanceof Error ? err : new Error(String(err)));
|
|
579
|
+
return false;
|
|
527
580
|
}
|
|
528
581
|
},
|
|
529
|
-
[form, action, provider, resource, id, effectiveData, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues, resolvedFields]
|
|
582
|
+
[form, action, provider, resource, id, effectiveData, rebased, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues, resolvedFields]
|
|
530
583
|
);
|
|
584
|
+
const handleSubmit = useCallback(async (submitted) => {
|
|
585
|
+
await save(submitted);
|
|
586
|
+
}, [save]);
|
|
587
|
+
const keepMine = useCallback(async () => {
|
|
588
|
+
if (!conflictState) return;
|
|
589
|
+
const { conflict, submitted, changed } = conflictState;
|
|
590
|
+
const values = { ...submitted };
|
|
591
|
+
for (const key of Object.keys(values)) {
|
|
592
|
+
if (!changed.includes(key) && key in conflict.theirs) values[key] = conflict.theirs[key];
|
|
593
|
+
}
|
|
594
|
+
form.clearErrors("root");
|
|
595
|
+
const found = conflictsFound.current;
|
|
596
|
+
const ok = await save(values, conflict.currentVersion ?? void 0, changed);
|
|
597
|
+
if (!ok && conflictsFound.current === found) throw new Error(form.getFieldState("root").error?.message ?? "Not saved.");
|
|
598
|
+
}, [conflictState, form, save]);
|
|
599
|
+
const dismissConflict = useCallback(() => setConflictState(null), []);
|
|
600
|
+
const takeTheirs = useCallback(() => {
|
|
601
|
+
if (!conflictState) return;
|
|
602
|
+
const { row: theirs } = conflictState;
|
|
603
|
+
setConflictState(null);
|
|
604
|
+
setUnsettled(null);
|
|
605
|
+
setRebased({ ...effectiveData ?? {}, ...theirs });
|
|
606
|
+
form.clearErrors();
|
|
607
|
+
const recordId = id ?? effectiveData?.id;
|
|
608
|
+
if (recordId != null && recordId !== "") {
|
|
609
|
+
patchCachedRow(queryClient, resource, { ...theirs, id: recordId });
|
|
610
|
+
void invalidateResource(queryClient, resource);
|
|
611
|
+
}
|
|
612
|
+
const shown = action === "edit" && provider.toFormValues ? provider.toFormValues(resource, theirs) : theirs;
|
|
613
|
+
const next = { ...form.getValues() };
|
|
614
|
+
for (const key of /* @__PURE__ */ new Set([...resolvedFields.map((f) => f.key), ...Object.keys(next)])) {
|
|
615
|
+
if (key in shown) next[key] = shown[key];
|
|
616
|
+
}
|
|
617
|
+
form.reset(next);
|
|
618
|
+
}, [conflictState, form, id, effectiveData, queryClient, resource, action, provider, resolvedFields]);
|
|
531
619
|
const onSubmit = useCallback(
|
|
532
620
|
(e) => form.handleSubmit(handleSubmit)(e),
|
|
533
621
|
[form, handleSubmit]
|
|
@@ -541,10 +629,14 @@ function useResourceForm(options) {
|
|
|
541
629
|
isSaving,
|
|
542
630
|
isLoading,
|
|
543
631
|
isDirty,
|
|
544
|
-
confirmLeave
|
|
632
|
+
confirmLeave,
|
|
633
|
+
conflict: conflictState?.conflict ?? null,
|
|
634
|
+
keepMine,
|
|
635
|
+
takeTheirs,
|
|
636
|
+
dismissConflict
|
|
545
637
|
};
|
|
546
638
|
}
|
|
547
639
|
|
|
548
640
|
export { blankValues, buildArrayItemDefaults, useResourceForm };
|
|
549
|
-
//# sourceMappingURL=chunk-
|
|
550
|
-
//# sourceMappingURL=chunk-
|
|
641
|
+
//# sourceMappingURL=chunk-3B5O36DU.js.map
|
|
642
|
+
//# sourceMappingURL=chunk-3B5O36DU.js.map
|