@jskit-ai/http-web 0.2.66 → 0.2.68
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/CHANGELOG.md +1 -0
- package/locales/en.json +9 -0
- package/package.json +17 -7
- package/patterns/crud-screen-set/PATTERN.md +7 -0
- package/src/client/components/CrudAddEditScreen.vue +34 -0
- package/src/client/components/EditConflictNotice.vue +69 -0
- package/src/client/composables/crud/crudSchemaFormHelpers.js +26 -0
- package/src/client/composables/records/useAddEdit.js +7 -3
- package/src/client/composables/runtime/useAddEditCore.js +57 -18
- package/src/client/composables/runtime/useUnsavedEdits.js +180 -0
- package/src/client/index.js +2 -0
- package/src/client/types.js +18 -1
- package/test/addEditKeepsEdits.test.js +242 -0
- package/test/crudAddEditActions.test.js +2 -0
- package/test/crudEditKeepsEdits.browser.test.js +130 -0
- package/test/exportsContract.test.js +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A form whose record is read again (a realtime event, the window regaining focus, Retry, a save's write to its cache) keeps what the person changed and has not saved, and takes every other field. `useAddEdit()`, and so `useCrudAddEdit()` and `useCrudAddEditScreen()`, wrote each read through `mapLoadedToModel` straight into the form, so a live update replaced what the person was typing without a word. Every write of fetched data into a form, each read, a save's answer and the new `applyLoaded(payload)`, now goes through `useUnsavedEdits` (new, `@jskit-ai/http-web/client/composables/useUnsavedEdits`): it runs the mapper into a copy of the form and gives the form each field the person has not changed since it last took the server's values. A field whose server value changed under the person's change keeps their value and is listed in the runtime's new `conflicts` (`{ key, value }`, the server's value) until they take it (`acceptServerValue(key)`), keep theirs (`keepOwnValue(key)`, until the server's value changes again), save it or type the server's value. `CrudAddEditScreen` shows each after its fields with the new `EditConflictNotice` ("Title changed to “Dune Messiah” while you were editing.", with Use the new Title and Keep your Title; message keys `jskit.http.form.conflict.*`). A save's answer replaces the fields it sent and keeps one the person changed while it ran. A read of another record (another query key) still starts from the form's initial values. **Behaviour change:** `isFieldLocked` no longer includes the read again (`isRefetching`): the fields stay editable while it runs, where they turned read-only and dropped what the person typed meanwhile. Save still waits for it (`isSubmitDisabled`, `isSubmitPending`). A `mapLoadedToModel` or `mapPayloadToModel` that writes anywhere but the record it is given (its first argument) bypasses all this: write into that record. `test/addEditKeepsEdits.test.js` proves it on a real TanStack query, and `test/crudEditKeepsEdits.browser.test.js` (`JSKIT_HTTP_WEB_KEPT_EDITS_BROWSER=1`) through the CRUD edit screen with the window regaining focus.
|
|
5
6
|
- **Breaking:** `useList()`, `useView()` and `useAddEdit()` (and so `useCrudList()`, `useCrudView()`, `useCrudAddEdit()` and the three CRUD screens) leave shell-web's request recovery banner out of their read unless the caller passes `requestRecovery`: the default was on, and is now off (`meta.jskit.requestRecovery` is `false`). Fix: a read whose screen shows no `loadError` (a lookup feeding a select, a section that hides its read) passes `requestRecovery: true` (or a label, or an options object) to keep the banner; a screen that shows the read's `loadError` needs no change. Why: these reads show their failure where it happened, as `loadError` with Retry, and report it once as `resource-load`, while the banner reported the same network failure again with its own Retry, so the page showed it twice. Where the old shape shows, the read is refused: a `requestRecoveryLabel` given without `requestRecovery: true`, which named the banner before, is a `TypeError` at setup naming both fixes (pass `requestRecovery: true`, or drop the label where the screen shows `loadError`), and the CRUD screens no longer default a label of their own (the catalog's `jskit.http.crud.records`, which only that default used, is gone; no dependent project uses it). The rule lives in one helper, `resolveScreenReadRequestRecovery`. JSKIT's own reads that show no load error ask for the banner: the CRUD lookup fields' and list filters' options and `useCrudListParentTitle()`'s parent read; the crud-screen-set pattern's Book screens no longer pass a label. `useEndpointResource()` and `useListCore()` keep request recovery on by default, as before.
|
|
6
7
|
- `toUiErrorMessage` and `toQueryErrorMessage` no longer show the browser's "signal timed out" for a request past its deadline as if the server had said it: the caller's fallback copy shows, and without one "The server took too long to answer. Try again." (`jskit.http.feedback.timedOut`). Before, a read that took longer than 30 seconds showed "signal timed out" on the page.
|
|
7
8
|
- The CRUD screens' command buttons keep keyboard focus while they run, through shell-web's `pending` and `v-pending`: the form's Save while it saves or the record reloads after it (`addEdit.isSubmitPending`, new on `useAddEdit()` and the runtimes built on it, alongside `isSubmitDisabled`, which still includes it), the list's Refresh and "Load more", the Retry of a list, record or form that failed to load, and the delete dialog's Delete. Each reads as unavailable and ignores a second press meanwhile, where it was `disabled` and dropped focus to the page body (the dialog's Delete kept focus but never read as unavailable). A save the server refuses with a field error moves focus to that field. When the last page of "Load more" takes the button away, focus moves to the first record that page added.
|
package/locales/en.json
CHANGED
|
@@ -96,6 +96,15 @@
|
|
|
96
96
|
"timedOut": "The server took too long to answer. Try again.",
|
|
97
97
|
"validationFailed": "Validation failed."
|
|
98
98
|
},
|
|
99
|
+
"form": {
|
|
100
|
+
"conflict": {
|
|
101
|
+
"accept": "Use the new {field}",
|
|
102
|
+
"changed": "{field} changed while you were editing.",
|
|
103
|
+
"changedTo": "{field} changed to “{value}” while you were editing.",
|
|
104
|
+
"cleared": "{field} was cleared while you were editing.",
|
|
105
|
+
"keep": "Keep your {field}"
|
|
106
|
+
}
|
|
107
|
+
},
|
|
99
108
|
"list": {
|
|
100
109
|
"label": "List",
|
|
101
110
|
"loadFailed": "Unable to load list.",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/http-web",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.68",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"./client": "./src/client/index.js",
|
|
10
10
|
"./client/components/CrudAddEditScreen": "./src/client/components/CrudAddEditScreen.vue",
|
|
11
11
|
"./client/components/CrudDeleteAction": "./src/client/components/CrudDeleteAction.vue",
|
|
12
|
+
"./client/components/EditConflictNotice": "./src/client/components/EditConflictNotice.vue",
|
|
12
13
|
"./client/components/CrudListBulkActionSurface": "./src/client/components/CrudListBulkActionSurface.vue",
|
|
13
14
|
"./client/components/CrudListFilterSurface": "./src/client/components/CrudListFilterSurface.vue",
|
|
14
15
|
"./client/components/CrudListScreen": "./src/client/components/CrudListScreen.vue",
|
|
@@ -35,6 +36,7 @@
|
|
|
35
36
|
"./client/composables/crudLookupFieldRuntime": "./src/client/composables/crud/crudLookupFieldRuntime.js",
|
|
36
37
|
"./client/composables/useEndpointResource": "./src/client/composables/runtime/useEndpointResource.js",
|
|
37
38
|
"./client/composables/useList": "./src/client/composables/records/useList.js",
|
|
39
|
+
"./client/composables/useUnsavedEdits": "./src/client/composables/runtime/useUnsavedEdits.js",
|
|
38
40
|
"./client/composables/usePagedCollection": "./src/client/composables/usePagedCollection.js",
|
|
39
41
|
"./client/composables/useRealtimeQueryInvalidation": "./src/client/composables/useRealtimeQueryInvalidation.js",
|
|
40
42
|
"./client/composables/useUiFeedback": "./src/client/composables/runtime/useUiFeedback.js",
|
|
@@ -47,20 +49,20 @@
|
|
|
47
49
|
"./locales/en.json": "./locales/en.json"
|
|
48
50
|
},
|
|
49
51
|
"dependencies": {
|
|
50
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
52
|
+
"@jskit-ai/resource-crud-core": "0.1.229"
|
|
51
53
|
},
|
|
52
54
|
"peerDependencies": {
|
|
53
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
54
|
-
"@jskit-ai/kernel": "0.2.
|
|
55
|
-
"@jskit-ai/realtime": "0.2.
|
|
56
|
-
"@jskit-ai/shell-web": "0.2.
|
|
55
|
+
"@jskit-ai/http-runtime": "0.2.37",
|
|
56
|
+
"@jskit-ai/kernel": "0.2.36",
|
|
57
|
+
"@jskit-ai/realtime": "0.2.62",
|
|
58
|
+
"@jskit-ai/shell-web": "0.2.59",
|
|
57
59
|
"@tanstack/vue-query": "^5.90.5",
|
|
58
60
|
"vue": "^3.5.13",
|
|
59
61
|
"vue-router": "^5.0.4",
|
|
60
62
|
"vuetify": "^4.3.0"
|
|
61
63
|
},
|
|
62
64
|
"devDependencies": {
|
|
63
|
-
"@jskit-ai/material-web": "0.1.
|
|
65
|
+
"@jskit-ai/material-web": "0.1.17"
|
|
64
66
|
},
|
|
65
67
|
"description": "Neutral Vue request, command, resource, and CRUD UI runtime for JSKIT web applications.",
|
|
66
68
|
"jskit": {
|
|
@@ -122,6 +124,14 @@
|
|
|
122
124
|
"subpath": "./client/components/CrudAddEditScreen",
|
|
123
125
|
"summary": "Exports the shared CRUD add/edit screen."
|
|
124
126
|
},
|
|
127
|
+
{
|
|
128
|
+
"subpath": "./client/composables/useUnsavedEdits",
|
|
129
|
+
"summary": "Exports what keeps a form's unsaved edits when its record is read again, and lists the fields the server changed under them."
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"subpath": "./client/components/EditConflictNotice",
|
|
133
|
+
"summary": "Exports the notice a form shows for each field whose server value changed while the person edited it."
|
|
134
|
+
},
|
|
125
135
|
{
|
|
126
136
|
"subpath": "./client/components/SelectField",
|
|
127
137
|
"summary": "Exports the select/autocomplete field that never shows a stored id as its title."
|
|
@@ -105,6 +105,13 @@ options; `addEditOptions` carries only request and route options for
|
|
|
105
105
|
`addEditOptions.fallbackSaveError` when given, otherwise the resource's
|
|
106
106
|
`messages.saveError`; the request error and its toast use the same string.
|
|
107
107
|
|
|
108
|
+
`mapPayloadToModel(model, payload)` writes into the `model` it is given, never
|
|
109
|
+
into the page's form state: the form runtime passes a copy, so a record read
|
|
110
|
+
again (a realtime event, the window regaining focus) keeps what the person
|
|
111
|
+
changed and has not saved, and `CrudAddEditScreen` names each field whose
|
|
112
|
+
server value changed under them. The Record form actions guide lists the
|
|
113
|
+
runtime's `conflicts`.
|
|
114
|
+
|
|
108
115
|
Save navigation is configured in the top-level `saveSuccess` object. The default
|
|
109
116
|
prefers a configured record-view URL, then the list. A create-and-list variation
|
|
110
117
|
sets `navigateToView: false` and `saveSuccess.listUrlTemplate` to its list
|
|
@@ -5,8 +5,10 @@ import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageAct
|
|
|
5
5
|
import { useShellPageClose } from "@jskit-ai/shell-web/client/composables/useShellPageClose";
|
|
6
6
|
import { useShellNavigation } from "@jskit-ai/shell-web/client/navigation/useShellNavigation";
|
|
7
7
|
import { vPending } from "@jskit-ai/shell-web/client/directives/vPending";
|
|
8
|
+
import { describeCrudFieldValue } from "../composables/crud/crudSchemaFormHelpers.js";
|
|
8
9
|
import { isRetryableLoadStatus } from "../composables/support/resourceLoadStateHelpers.js";
|
|
9
10
|
import { useJskitText } from "../i18n.js";
|
|
11
|
+
import EditConflictNotice from "./EditConflictNotice.vue";
|
|
10
12
|
|
|
11
13
|
// A new or edit page as Material 3 lays out a full-screen form: the top app bar's leading close (X) cancels, Save is
|
|
12
14
|
// its one primary action, and the form's fields are below on the page. Where the bar has no Up arrow to turn into the
|
|
@@ -59,6 +61,33 @@ function resolveFieldErrors(fieldKey) {
|
|
|
59
61
|
return props.screen.resolveFieldErrors(fieldKey);
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
// The fields whose server value changed while the person edited them (the form keeps the person's values), as the
|
|
65
|
+
// notice after the fields names them. A screen a page builds without a record read has none.
|
|
66
|
+
const conflictItems = computed(() => {
|
|
67
|
+
const fields = unref(formRuntime.value.formFields) || [];
|
|
68
|
+
return (unref(addEdit.value.conflicts) || []).map(({ key, value }) => {
|
|
69
|
+
const field = fields.find((entry) => entry.key === key) || { key };
|
|
70
|
+
return {
|
|
71
|
+
key,
|
|
72
|
+
label: String(text(field.label) || key),
|
|
73
|
+
value: describeCrudFieldValue(field, value, {
|
|
74
|
+
yes: t("jskit.http.crud.yes"),
|
|
75
|
+
no: t("jskit.http.crud.no"),
|
|
76
|
+
lookupLabel
|
|
77
|
+
})
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// A lookup's value is an id: the notice names the option it is, once the field's options hold it.
|
|
83
|
+
function lookupLabel(field, value) {
|
|
84
|
+
if (!props.resolveLookupItems) {
|
|
85
|
+
return "";
|
|
86
|
+
}
|
|
87
|
+
const items = props.resolveLookupItems(field.key, { selectedValue: value });
|
|
88
|
+
return items.find((item) => item.value === value)?.label || "";
|
|
89
|
+
}
|
|
90
|
+
|
|
62
91
|
function resolveCancelTo(target = cancelTo.value) {
|
|
63
92
|
return props.screen.resolveCancelTo(target);
|
|
64
93
|
}
|
|
@@ -137,6 +166,11 @@ useShellPageClose({ label: () => t("jskit.http.actions.cancel"), close: cancel }
|
|
|
137
166
|
:set-lookup-search="setLookupSearch"
|
|
138
167
|
/>
|
|
139
168
|
</v-row>
|
|
169
|
+
<EditConflictNotice
|
|
170
|
+
:items="conflictItems"
|
|
171
|
+
@accept="addEdit.acceptServerValue"
|
|
172
|
+
@keep="addEdit.keepOwnValue"
|
|
173
|
+
/>
|
|
140
174
|
</v-form>
|
|
141
175
|
</section>
|
|
142
176
|
</template>
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
import { useJskitText } from "../i18n.js";
|
|
3
|
+
|
|
4
|
+
// What a form says when the server's value of a field changed while the person was editing it: one line per field,
|
|
5
|
+
// with the server's value, and the choice to use it or keep the person's own. Until they choose the form keeps theirs,
|
|
6
|
+
// and saving saves theirs. A form puts it after its fields, so nothing the person is typing in moves, and its region
|
|
7
|
+
// announces each new line politely: a line is no alert of its own, and takes no name a field already has.
|
|
8
|
+
|
|
9
|
+
defineProps({
|
|
10
|
+
items: {
|
|
11
|
+
type: /** @type {import("vue").PropType<import("../types.js").EditConflictItem[]>} */ (Array),
|
|
12
|
+
required: true
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
const emit = defineEmits(["accept", "keep"]);
|
|
16
|
+
const { t } = useJskitText();
|
|
17
|
+
|
|
18
|
+
// A long value, such as a prompt, shows its start; using it takes the whole value.
|
|
19
|
+
const SHOWN_LENGTH = 160;
|
|
20
|
+
|
|
21
|
+
function message(item) {
|
|
22
|
+
if (item.value === "") {
|
|
23
|
+
return t("jskit.http.form.conflict.cleared", { field: item.label });
|
|
24
|
+
}
|
|
25
|
+
if (item.value === null) {
|
|
26
|
+
return t("jskit.http.form.conflict.changed", { field: item.label });
|
|
27
|
+
}
|
|
28
|
+
const shown = item.value.length > SHOWN_LENGTH ? `${item.value.slice(0, SHOWN_LENGTH).trimEnd()}…` : item.value;
|
|
29
|
+
return t("jskit.http.form.conflict.changedTo", { field: item.label, value: shown });
|
|
30
|
+
}
|
|
31
|
+
</script>
|
|
32
|
+
|
|
33
|
+
<template>
|
|
34
|
+
<div class="edit-conflict-notice" role="status" aria-live="polite">
|
|
35
|
+
<v-alert
|
|
36
|
+
v-for="item in items"
|
|
37
|
+
:key="item.key"
|
|
38
|
+
role="none"
|
|
39
|
+
color="warning-container"
|
|
40
|
+
icon="$warning"
|
|
41
|
+
variant="flat"
|
|
42
|
+
density="comfortable"
|
|
43
|
+
:rounded="12"
|
|
44
|
+
>
|
|
45
|
+
<div class="d-flex align-center ga-3 flex-wrap">
|
|
46
|
+
<span>{{ message(item) }}</span>
|
|
47
|
+
<v-spacer />
|
|
48
|
+
<v-btn variant="text" size="small" class="text-none" @click="emit('accept', item.key)">
|
|
49
|
+
{{ t("jskit.http.form.conflict.accept", { field: item.label }) }}
|
|
50
|
+
</v-btn>
|
|
51
|
+
<v-btn variant="text" size="small" class="text-none" @click="emit('keep', item.key)">
|
|
52
|
+
{{ t("jskit.http.form.conflict.keep", { field: item.label }) }}
|
|
53
|
+
</v-btn>
|
|
54
|
+
</div>
|
|
55
|
+
</v-alert>
|
|
56
|
+
</div>
|
|
57
|
+
</template>
|
|
58
|
+
|
|
59
|
+
<style scoped>
|
|
60
|
+
.edit-conflict-notice {
|
|
61
|
+
display: flex;
|
|
62
|
+
flex-direction: column;
|
|
63
|
+
gap: 8px;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
.edit-conflict-notice:not(:empty) {
|
|
67
|
+
margin-top: 16px;
|
|
68
|
+
}
|
|
69
|
+
</style>
|
|
@@ -408,6 +408,31 @@ function applyCrudPayloadToForm(fields = [], model = {}, payload = {}) {
|
|
|
408
408
|
}
|
|
409
409
|
}
|
|
410
410
|
|
|
411
|
+
/**
|
|
412
|
+
* The server's value of a form field as the conflict notice shows it (an EditConflictItem's `value`): "" when it is
|
|
413
|
+
* empty, null for a lookup's id whose label is not loaded, and otherwise the text the field shows.
|
|
414
|
+
* @param {Record<string, any>} field A normalized form field.
|
|
415
|
+
* @param {unknown} value The value as the form holds it.
|
|
416
|
+
* @param {{ yes: string, no: string, lookupLabel: (field: Record<string, any>, value: string) => string }} words
|
|
417
|
+
* @returns {string | null}
|
|
418
|
+
*/
|
|
419
|
+
function describeCrudFieldValue(field, value, { yes, no, lookupLabel }) {
|
|
420
|
+
if (value === null || value === undefined || value === "") {
|
|
421
|
+
return "";
|
|
422
|
+
}
|
|
423
|
+
if (resolveFormFieldType(field) === "boolean") {
|
|
424
|
+
return value ? yes : no;
|
|
425
|
+
}
|
|
426
|
+
if (isLookupFormField(field)) {
|
|
427
|
+
return lookupLabel(field, String(value)) || null;
|
|
428
|
+
}
|
|
429
|
+
if (Array.isArray(value)) {
|
|
430
|
+
return value.map(String).join(", ");
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
return String(value);
|
|
434
|
+
}
|
|
435
|
+
|
|
411
436
|
function resolveCrudRouteBoundFieldValues(fields = [], routeParams = {}) {
|
|
412
437
|
const sourceRouteParams = asPlainObject(routeParams);
|
|
413
438
|
const values = {};
|
|
@@ -455,6 +480,7 @@ export {
|
|
|
455
480
|
createCrudFormModel,
|
|
456
481
|
buildCrudFormPayload,
|
|
457
482
|
applyCrudPayloadToForm,
|
|
483
|
+
describeCrudFieldValue,
|
|
458
484
|
resolveCrudRouteBoundFieldValues,
|
|
459
485
|
applyCrudRouteBoundFieldValues,
|
|
460
486
|
resolveCrudFieldErrors
|
|
@@ -174,9 +174,9 @@ function useAddEdit({
|
|
|
174
174
|
const isInitialLoading = operationScope.isLoading(endpointResource.isInitialLoading);
|
|
175
175
|
const isFetching = operationScope.isLoading(endpointResource.isFetching);
|
|
176
176
|
const isRefetching = computed(() => Boolean(isFetching.value && !isInitialLoading.value));
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
);
|
|
177
|
+
// Fields lock while the form saves. A read of the record again leaves them open: it keeps what the person changes
|
|
178
|
+
// meanwhile, as it keeps every unsaved edit, so the person goes on typing through it.
|
|
179
|
+
const isFieldLocked = computed(() => Boolean(!canSave.value || addEdit.saving.value));
|
|
180
180
|
const isSubmitDisabled = computed(() =>
|
|
181
181
|
Boolean(isInitialLoading.value || isRefetching.value || !canSave.value || addEdit.saving.value)
|
|
182
182
|
);
|
|
@@ -232,6 +232,10 @@ function useAddEdit({
|
|
|
232
232
|
message: addEdit.message,
|
|
233
233
|
messageType: addEdit.messageType,
|
|
234
234
|
submit: addEdit.submit,
|
|
235
|
+
conflicts: addEdit.conflicts,
|
|
236
|
+
acceptServerValue: addEdit.acceptServerValue,
|
|
237
|
+
keepOwnValue: addEdit.keepOwnValue,
|
|
238
|
+
applyLoaded: addEdit.applyLoaded,
|
|
235
239
|
refresh,
|
|
236
240
|
resource: endpointResource,
|
|
237
241
|
recordId: addEditUiRuntime.recordId,
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { useQueryClient } from "@tanstack/vue-query";
|
|
2
|
-
import { computed, ref } from "vue";
|
|
2
|
+
import { computed, ref, toValue, watch } from "vue";
|
|
3
3
|
import { validateOperationInput } from "./operationValidationHelpers.js";
|
|
4
|
-
import { ignoreLoadedPayload
|
|
4
|
+
import { ignoreLoadedPayload } from "./modelStateHelpers.js";
|
|
5
|
+
import { useUnsavedEdits } from "./useUnsavedEdits.js";
|
|
5
6
|
import { toUiFieldErrors } from "../support/errorMessageHelpers.js";
|
|
6
7
|
import { emptyRecord } from "../support/scopeHelpers.js";
|
|
7
8
|
import { useJskitText } from "../../i18n.js";
|
|
@@ -14,7 +15,8 @@ function saveParsedInput(parsedInput) {
|
|
|
14
15
|
|
|
15
16
|
/** @param {import("../../types.js").AddEditCoreOptions} options */
|
|
16
17
|
function useAddEditCore({
|
|
17
|
-
|
|
18
|
+
// readable-check: allow required-collaborators - data: the form's record, empty for a form whose fields live elsewhere
|
|
19
|
+
model = {},
|
|
18
20
|
resource,
|
|
19
21
|
queryKey,
|
|
20
22
|
canSave,
|
|
@@ -29,17 +31,46 @@ function useAddEditCore({
|
|
|
29
31
|
messages = {}
|
|
30
32
|
}) {
|
|
31
33
|
const queryClient = useQueryClient();
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
34
|
+
// Every write of fetched data into the form goes through `edits`: a read of the record, a save's response and
|
|
35
|
+
// applyLoaded() each keep what the person changed and has not saved, and list the fields whose server value changed
|
|
36
|
+
// under such a change.
|
|
37
|
+
const edits = useUnsavedEdits({ model });
|
|
38
|
+
|
|
39
|
+
function writeLoaded(payload) {
|
|
40
|
+
return (target) => mapLoadedToModel(target, payload, {
|
|
41
|
+
queryClient,
|
|
42
|
+
resource
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A record with no data yet (a new query key, or one the cache dropped) starts from the form's initial values.
|
|
47
|
+
watch(
|
|
48
|
+
() => resource.query.isPending.value,
|
|
49
|
+
(isPending) => {
|
|
50
|
+
if (isPending) {
|
|
51
|
+
edits.reset();
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
immediate: true
|
|
41
56
|
}
|
|
42
|
-
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
// Each read of the record: its first load and every read again (a realtime event, the window regaining focus,
|
|
60
|
+
// Retry, a save's write to the cache). The query key names the record, so another record's data starts over.
|
|
61
|
+
watch(
|
|
62
|
+
() => resource.data.value,
|
|
63
|
+
(payload) => {
|
|
64
|
+
if (!payload) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
edits.merge(writeLoaded(payload), JSON.stringify(toValue(queryKey)));
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
immediate: true
|
|
72
|
+
}
|
|
73
|
+
);
|
|
43
74
|
|
|
44
75
|
const submitting = ref(false);
|
|
45
76
|
const saving = computed(() => Boolean(submitting.value || resource.isSaving.value));
|
|
@@ -79,6 +110,8 @@ function useAddEditCore({
|
|
|
79
110
|
validationAttempted.value = true;
|
|
80
111
|
|
|
81
112
|
const rawPayload = resolveRawPayload();
|
|
113
|
+
// What this save sends: its response replaces these fields, except one the person changes while it runs.
|
|
114
|
+
const sent = edits.captureFields();
|
|
82
115
|
|
|
83
116
|
const validationResult = validateOperationInput({
|
|
84
117
|
input,
|
|
@@ -103,10 +136,7 @@ function useAddEditCore({
|
|
|
103
136
|
const queryKeySnapshot = queryKey.value;
|
|
104
137
|
const payload = await resource.save(savePayload);
|
|
105
138
|
|
|
106
|
-
|
|
107
|
-
queryClient,
|
|
108
|
-
resource
|
|
109
|
-
});
|
|
139
|
+
edits.mergeSaved(writeLoaded(payload), sent);
|
|
110
140
|
|
|
111
141
|
if (queryKeySnapshot !== undefined) {
|
|
112
142
|
queryClient.setQueryData(queryKeySnapshot, payload);
|
|
@@ -132,6 +162,11 @@ function useAddEditCore({
|
|
|
132
162
|
}
|
|
133
163
|
}
|
|
134
164
|
|
|
165
|
+
/** A record of the form's own read that other code read, such as a settings page's one read of all its forms. */
|
|
166
|
+
function applyLoaded(payload) {
|
|
167
|
+
edits.merge(writeLoaded(payload));
|
|
168
|
+
}
|
|
169
|
+
|
|
135
170
|
return {
|
|
136
171
|
saving,
|
|
137
172
|
fieldErrors,
|
|
@@ -140,7 +175,11 @@ function useAddEditCore({
|
|
|
140
175
|
validationAttempted,
|
|
141
176
|
validationErrors,
|
|
142
177
|
resetValidation,
|
|
143
|
-
submit
|
|
178
|
+
submit,
|
|
179
|
+
conflicts: edits.conflicts,
|
|
180
|
+
acceptServerValue: edits.acceptServerValue,
|
|
181
|
+
keepOwnValue: edits.keepOwnValue,
|
|
182
|
+
applyLoaded
|
|
144
183
|
};
|
|
145
184
|
}
|
|
146
185
|
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { ref, toRaw } from "vue";
|
|
2
|
+
|
|
3
|
+
// A list or a plain record holds field values; any other object, such as a Date or a File, is one value.
|
|
4
|
+
function isPlainRecord(value) {
|
|
5
|
+
if (value === null || typeof value !== "object") {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
const prototype = Object.getPrototypeOf(value);
|
|
9
|
+
return prototype === Object.prototype || prototype === null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// A field's value as it is now, unchanged by a later change to the form's own lists and records.
|
|
13
|
+
function copyValue(value) {
|
|
14
|
+
const raw = toRaw(value);
|
|
15
|
+
if (Array.isArray(raw)) {
|
|
16
|
+
return raw.map(copyValue);
|
|
17
|
+
}
|
|
18
|
+
if (isPlainRecord(raw)) {
|
|
19
|
+
return Object.fromEntries(Object.entries(raw).map(([key, entry]) => [key, copyValue(entry)]));
|
|
20
|
+
}
|
|
21
|
+
return raw;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sameValue(left, right) {
|
|
25
|
+
if (Object.is(left, right)) {
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
29
|
+
return left.length === right.length && left.every((entry, index) => sameValue(entry, right[index]));
|
|
30
|
+
}
|
|
31
|
+
if (isPlainRecord(left) && isPlainRecord(right)) {
|
|
32
|
+
const keys = Object.keys(left);
|
|
33
|
+
return keys.length === Object.keys(right).length &&
|
|
34
|
+
keys.every((key) => Object.hasOwn(right, key) && sameValue(left[key], right[key]));
|
|
35
|
+
}
|
|
36
|
+
if (left instanceof Date && right instanceof Date) {
|
|
37
|
+
return left.getTime() === right.getTime();
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Read through the form's proxy, so a field the form holds as a ref copies as its value.
|
|
43
|
+
function copyFields(fields) {
|
|
44
|
+
return Object.fromEntries(Object.keys(fields).map((key) => [key, copyValue(fields[key])]));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* What a person has changed in a form and not saved, kept when the record the form edits is read again.
|
|
49
|
+
*
|
|
50
|
+
* Every path that writes fetched data into the form goes through it: `merge(writeLoaded)` for a read of the record,
|
|
51
|
+
* `mergeSaved(writeLoaded, sent)` for a save's response. `writeLoaded` writes what the server sent into a copy of
|
|
52
|
+
* the form, and the form takes from it each field the person has not changed since it last took the server's
|
|
53
|
+
* values. A field they changed keeps their value; when the server's value of it changed meanwhile, `conflicts` lists
|
|
54
|
+
* the field with the server's value until the person takes it (`acceptServerValue`), keeps theirs
|
|
55
|
+
* (`keepOwnValue`), saves it, or types the server's value.
|
|
56
|
+
* @param {{ model: Record<string, unknown> }} options
|
|
57
|
+
*/
|
|
58
|
+
function useUnsavedEdits({ model }) {
|
|
59
|
+
const initial = copyFields(model);
|
|
60
|
+
// The values the form last took from the server: at first its own initial values.
|
|
61
|
+
let taken = initial;
|
|
62
|
+
/**
|
|
63
|
+
* The record those values came from; a merge from another record starts the form over.
|
|
64
|
+
* @type {string | undefined}
|
|
65
|
+
*/
|
|
66
|
+
let takenRecord;
|
|
67
|
+
/** @type {import("vue").Ref<import("../../types.js").EditConflict[]>} */
|
|
68
|
+
const conflicts = ref([]);
|
|
69
|
+
|
|
70
|
+
function setConflict(key, value) {
|
|
71
|
+
const index = conflicts.value.findIndex((conflict) => conflict.key === key);
|
|
72
|
+
if (index >= 0 && sameValue(conflicts.value[index].value, value)) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const next = [...conflicts.value];
|
|
76
|
+
next.splice(index >= 0 ? index : next.length, index >= 0 ? 1 : 0, { key, value: copyValue(value) });
|
|
77
|
+
conflicts.value = next;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function clearConflict(key) {
|
|
81
|
+
if (conflicts.value.some((conflict) => conflict.key === key)) {
|
|
82
|
+
conflicts.value = conflicts.value.filter((conflict) => conflict.key !== key);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The form's initial values, as for a record never read: what a new record, or one with no data yet, starts from.
|
|
87
|
+
function reset() {
|
|
88
|
+
for (const key of Object.keys(model)) {
|
|
89
|
+
if (!Object.hasOwn(initial, key)) {
|
|
90
|
+
delete model[key];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for (const [key, value] of Object.entries(initial)) {
|
|
94
|
+
model[key] = copyValue(value);
|
|
95
|
+
}
|
|
96
|
+
taken = initial;
|
|
97
|
+
takenRecord = undefined;
|
|
98
|
+
conflicts.value = [];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Gives the form what `writeLoaded` wrote of the server's values, for each field the person has not changed since
|
|
102
|
+
// `base`, the values the form took last or a save sent.
|
|
103
|
+
function mergeSince(writeLoaded, base) {
|
|
104
|
+
const current = copyFields(model);
|
|
105
|
+
const loaded = { ...current, ...copyFields(base) };
|
|
106
|
+
writeLoaded(loaded);
|
|
107
|
+
for (const [key, value] of Object.entries(loaded)) {
|
|
108
|
+
const mine = current[key];
|
|
109
|
+
if (sameValue(mine, base[key])) {
|
|
110
|
+
// The person has not changed it: it takes the server's value.
|
|
111
|
+
if (!sameValue(mine, value)) {
|
|
112
|
+
model[key] = copyValue(value);
|
|
113
|
+
}
|
|
114
|
+
clearConflict(key);
|
|
115
|
+
} else if (sameValue(mine, value)) {
|
|
116
|
+
// The server now holds what the person typed.
|
|
117
|
+
clearConflict(key);
|
|
118
|
+
} else if (!sameValue(value, base[key])) {
|
|
119
|
+
// The server's value changed under the person's edit: both stay, and the person chooses.
|
|
120
|
+
setConflict(key, value);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
taken = loaded;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* A read of the record: its first load, or a read again. A read of another record (its `record`, such as its query
|
|
128
|
+
* key, differs) starts the form over from its initial values.
|
|
129
|
+
* @param {(target: Record<string, unknown>) => void} writeLoaded Writes the server's values into the form's copy.
|
|
130
|
+
* @param {string} [record]
|
|
131
|
+
*/
|
|
132
|
+
function merge(writeLoaded, record = takenRecord) {
|
|
133
|
+
if (takenRecord !== undefined && record !== takenRecord) {
|
|
134
|
+
reset();
|
|
135
|
+
}
|
|
136
|
+
mergeSince(writeLoaded, taken);
|
|
137
|
+
takenRecord = record;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The form's values now: what a save sends, which `mergeSaved` then compares its response with. */
|
|
141
|
+
function captureFields() {
|
|
142
|
+
return copyFields(model);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* A save's response: the fields the save sent take it, and a field changed while the save ran keeps the person's
|
|
147
|
+
* value.
|
|
148
|
+
* @param {(target: Record<string, unknown>) => void} writeLoaded
|
|
149
|
+
* @param {Record<string, unknown>} sent What `captureFields()` returned when the save started.
|
|
150
|
+
*/
|
|
151
|
+
function mergeSaved(writeLoaded, sent) {
|
|
152
|
+
mergeSince(writeLoaded, sent);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The person takes the server's value of a field in conflict. */
|
|
156
|
+
function acceptServerValue(key) {
|
|
157
|
+
const conflict = conflicts.value.find((entry) => entry.key === key);
|
|
158
|
+
if (conflict) {
|
|
159
|
+
model[key] = copyValue(conflict.value);
|
|
160
|
+
clearConflict(key);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The person keeps their own value of a field in conflict; a later change of the server's value raises it again. */
|
|
165
|
+
function keepOwnValue(key) {
|
|
166
|
+
clearConflict(key);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
conflicts,
|
|
171
|
+
captureFields,
|
|
172
|
+
merge,
|
|
173
|
+
mergeSaved,
|
|
174
|
+
reset,
|
|
175
|
+
acceptServerValue,
|
|
176
|
+
keepOwnValue
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export { useUnsavedEdits };
|
package/src/client/index.js
CHANGED
|
@@ -4,6 +4,7 @@ export { default as CrudListBulkActionSurface } from "./components/CrudListBulkA
|
|
|
4
4
|
export { default as CrudListFilterSurface } from "./components/CrudListFilterSurface.vue";
|
|
5
5
|
export { default as CrudListScreen } from "./components/CrudListScreen.vue";
|
|
6
6
|
export { default as CrudViewScreen } from "./components/CrudViewScreen.vue";
|
|
7
|
+
export { default as EditConflictNotice } from "./components/EditConflictNotice.vue";
|
|
7
8
|
export { defineCrudListBulkActions } from "./bulkActions.js";
|
|
8
9
|
export { defineCrudListFilters } from "./filters.js";
|
|
9
10
|
export { defineCrudListRowActions } from "./rowActions.js";
|
|
@@ -15,6 +16,7 @@ export { useList } from "./composables/records/useList.js";
|
|
|
15
16
|
export { usePagedCollection } from "./composables/usePagedCollection.js";
|
|
16
17
|
export { useRealtimeQueryInvalidation } from "./composables/useRealtimeQueryInvalidation.js";
|
|
17
18
|
export { useUiFeedback } from "./composables/runtime/useUiFeedback.js";
|
|
19
|
+
export { useUnsavedEdits } from "./composables/runtime/useUnsavedEdits.js";
|
|
18
20
|
export { useView } from "./composables/records/useView.js";
|
|
19
21
|
export {
|
|
20
22
|
configureHttpWebClient,
|
package/src/client/types.js
CHANGED
|
@@ -32,6 +32,23 @@
|
|
|
32
32
|
/** @typedef {Record<string, any> | import("vue").Ref<Record<string, any>> | ((context: Record<string, any>) => Record<string, any>) | null} RequestQueryParams */
|
|
33
33
|
/** @typedef {(model: any, payload: any, context: Record<string, any>) => void} MapLoadedToModel */
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* A field whose server value changed while the person was editing it: the form keeps the person's value, and
|
|
37
|
+
* `value` is the server's, which the person may take.
|
|
38
|
+
* @typedef {object} EditConflict
|
|
39
|
+
* @property {string} key The form model's field.
|
|
40
|
+
* @property {unknown} value The server's value, as the form holds a value of that field.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One line of `EditConflictNotice`: a field in conflict as the person reads it.
|
|
45
|
+
* @typedef {object} EditConflictItem
|
|
46
|
+
* @property {string} key The form model's field.
|
|
47
|
+
* @property {string} label The field's label.
|
|
48
|
+
* @property {string | null} value The server's value as the field shows it; "" when the server cleared it, and null
|
|
49
|
+
* when it cannot be shown, such as a lookup's id whose label is not loaded.
|
|
50
|
+
*/
|
|
51
|
+
|
|
35
52
|
/**
|
|
36
53
|
* What an operation's `realtime` option declares, or `false` to refuse a resource's own.
|
|
37
54
|
* @typedef {object} OperationRealtime
|
|
@@ -546,7 +563,7 @@
|
|
|
546
563
|
* @property {import("vue").MaybeRef<string>} [subtitle]
|
|
547
564
|
* @property {import("vue").MaybeRef<string>} [saveLabel]
|
|
548
565
|
* @property {import("vue").MaybeRef<unknown>} [cancelTo]
|
|
549
|
-
* @property {{ showFormSkeleton: boolean }} formRuntime
|
|
566
|
+
* @property {{ showFormSkeleton: boolean, formFields?: Record<string, any>[] }} formRuntime
|
|
550
567
|
* @property {Partial<AddEditRuntime>} addEdit
|
|
551
568
|
* @property {Record<string, any>} formState
|
|
552
569
|
* @property {(fieldKey: string) => string[]} resolveFieldErrors
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query";
|
|
4
|
+
import { computed, createSSRApp, effectScope, h, nextTick, reactive, ref } from "vue";
|
|
5
|
+
import { useAddEditCore } from "../src/client/composables/runtime/useAddEditCore.js";
|
|
6
|
+
import { useEndpointResource } from "../src/client/composables/runtime/useEndpointResource.js";
|
|
7
|
+
|
|
8
|
+
// A form's record is read again while the person edits it: a realtime event, the window regaining focus and Retry
|
|
9
|
+
// each refetch the form's query. These drive the form runtime over a real query client, against a fake server whose
|
|
10
|
+
// records a test changes as another person saving them would.
|
|
11
|
+
|
|
12
|
+
/** Lets the query client's reads and the watchers they trigger run. */
|
|
13
|
+
async function settle() {
|
|
14
|
+
for (let round = 0; round < 6; round += 1) {
|
|
15
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
16
|
+
await nextTick();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function editForm(t, { records, recordId = "1" }) {
|
|
21
|
+
const server = structuredClone(records);
|
|
22
|
+
const saves = [];
|
|
23
|
+
let savesHeld = null;
|
|
24
|
+
const client = {
|
|
25
|
+
async request(path, options) {
|
|
26
|
+
const id = path.split("/").at(-1);
|
|
27
|
+
if (options.method === "GET") {
|
|
28
|
+
return structuredClone(server[id]);
|
|
29
|
+
}
|
|
30
|
+
saves.push(structuredClone(options.body));
|
|
31
|
+
await savesHeld?.promise;
|
|
32
|
+
// The server trims what it stores, so a saved response can differ from what the form sent.
|
|
33
|
+
server[id] = { ...server[id], title: options.body.title.trim(), author: options.body.author.trim() };
|
|
34
|
+
return structuredClone(server[id]);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
38
|
+
const app = createSSRApp({ render: () => h("div") });
|
|
39
|
+
app.use(VueQueryPlugin, { queryClient });
|
|
40
|
+
const id = ref(recordId);
|
|
41
|
+
const model = reactive({ title: "", author: "" });
|
|
42
|
+
const scope = effectScope();
|
|
43
|
+
let form = null;
|
|
44
|
+
app.runWithContext(() => {
|
|
45
|
+
scope.run(() => {
|
|
46
|
+
const queryKey = computed(() => ["books", id.value]);
|
|
47
|
+
const resource = useEndpointResource({ queryKey, path: computed(() => `/books/${id.value}`), client });
|
|
48
|
+
form = useAddEditCore({
|
|
49
|
+
model,
|
|
50
|
+
resource,
|
|
51
|
+
queryKey,
|
|
52
|
+
canSave: ref(true),
|
|
53
|
+
fieldBag: { clear() {}, apply() {} },
|
|
54
|
+
feedback: { clear() {}, success() {}, error() {} },
|
|
55
|
+
mapLoadedToModel(target, loaded) {
|
|
56
|
+
target.title = loaded.title;
|
|
57
|
+
target.author = loaded.author;
|
|
58
|
+
},
|
|
59
|
+
buildRawPayload: (current) => ({ title: current.title, author: current.author })
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
t.after(() => {
|
|
64
|
+
scope.stop();
|
|
65
|
+
queryClient.clear();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
server,
|
|
70
|
+
saves,
|
|
71
|
+
model,
|
|
72
|
+
form,
|
|
73
|
+
queryClient,
|
|
74
|
+
id,
|
|
75
|
+
holdSaves() {
|
|
76
|
+
savesHeld = Promise.withResolvers();
|
|
77
|
+
return savesHeld;
|
|
78
|
+
},
|
|
79
|
+
async readAgain() {
|
|
80
|
+
await queryClient.refetchQueries({ queryKey: ["books", id.value], exact: true });
|
|
81
|
+
await settle();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const DUNE = Object.freeze({ title: "Dune", author: "Herbert" });
|
|
87
|
+
|
|
88
|
+
test("a record read again keeps the field the person edited and takes the fields they left", async (t) => {
|
|
89
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
90
|
+
await settle();
|
|
91
|
+
assert.deepEqual({ ...fixture.model }, DUNE);
|
|
92
|
+
|
|
93
|
+
fixture.model.title = "Dune (draft)";
|
|
94
|
+
fixture.server[1].author = "Frank Herbert";
|
|
95
|
+
await fixture.readAgain();
|
|
96
|
+
|
|
97
|
+
assert.equal(fixture.model.title, "Dune (draft)", "the read kept the person's unsaved title");
|
|
98
|
+
assert.equal(fixture.model.author, "Frank Herbert", "the field the person left took the server's new value");
|
|
99
|
+
assert.deepEqual(fixture.form.conflicts.value, [], "the server's title did not change, so nothing conflicts");
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("a server change to a field the person edited keeps both values, and the person chooses", async (t) => {
|
|
103
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
104
|
+
await settle();
|
|
105
|
+
|
|
106
|
+
fixture.model.title = "Dune (draft)";
|
|
107
|
+
fixture.server[1].title = "Dune Messiah";
|
|
108
|
+
await fixture.readAgain();
|
|
109
|
+
assert.equal(fixture.model.title, "Dune (draft)");
|
|
110
|
+
assert.deepEqual(fixture.form.conflicts.value, [{ key: "title", value: "Dune Messiah" }]);
|
|
111
|
+
|
|
112
|
+
// Another read with the server's value unchanged keeps the conflict as it is.
|
|
113
|
+
await fixture.readAgain();
|
|
114
|
+
assert.deepEqual(fixture.form.conflicts.value, [{ key: "title", value: "Dune Messiah" }]);
|
|
115
|
+
|
|
116
|
+
fixture.form.acceptServerValue("title");
|
|
117
|
+
assert.equal(fixture.model.title, "Dune Messiah");
|
|
118
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
119
|
+
|
|
120
|
+
// The accepted value is the server's, so the field is no longer the person's edit: the next change reaches it.
|
|
121
|
+
fixture.server[1].title = "Children of Dune";
|
|
122
|
+
await fixture.readAgain();
|
|
123
|
+
assert.equal(fixture.model.title, "Children of Dune");
|
|
124
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("keeping one's own value ends the conflict until the server changes that field again", async (t) => {
|
|
128
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
129
|
+
await settle();
|
|
130
|
+
|
|
131
|
+
fixture.model.title = "Mine";
|
|
132
|
+
fixture.server[1].title = "Theirs";
|
|
133
|
+
await fixture.readAgain();
|
|
134
|
+
fixture.form.keepOwnValue("title");
|
|
135
|
+
assert.equal(fixture.model.title, "Mine");
|
|
136
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
137
|
+
|
|
138
|
+
await fixture.readAgain();
|
|
139
|
+
assert.equal(fixture.model.title, "Mine");
|
|
140
|
+
assert.deepEqual(fixture.form.conflicts.value, [], "the same server value does not conflict again");
|
|
141
|
+
|
|
142
|
+
fixture.server[1].title = "Theirs, again";
|
|
143
|
+
await fixture.readAgain();
|
|
144
|
+
assert.equal(fixture.model.title, "Mine");
|
|
145
|
+
assert.deepEqual(fixture.form.conflicts.value, [{ key: "title", value: "Theirs, again" }]);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test("a field the person changed back to the server's value takes the next read", async (t) => {
|
|
149
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
150
|
+
await settle();
|
|
151
|
+
|
|
152
|
+
fixture.model.title = "Dune (draft)";
|
|
153
|
+
fixture.model.title = "Dune";
|
|
154
|
+
fixture.server[1].title = "Dune Messiah";
|
|
155
|
+
await fixture.readAgain();
|
|
156
|
+
assert.equal(fixture.model.title, "Dune Messiah");
|
|
157
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("a server value that reaches what the person typed ends their conflict", async (t) => {
|
|
161
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
162
|
+
await settle();
|
|
163
|
+
|
|
164
|
+
fixture.model.title = "Dune Messiah";
|
|
165
|
+
fixture.server[1].title = "Dune II";
|
|
166
|
+
await fixture.readAgain();
|
|
167
|
+
assert.deepEqual(fixture.form.conflicts.value, [{ key: "title", value: "Dune II" }]);
|
|
168
|
+
|
|
169
|
+
fixture.server[1].title = "Dune Messiah";
|
|
170
|
+
await fixture.readAgain();
|
|
171
|
+
assert.equal(fixture.model.title, "Dune Messiah");
|
|
172
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test("a save takes its response for the fields it sent and keeps a field changed while it ran", async (t) => {
|
|
176
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
177
|
+
await settle();
|
|
178
|
+
|
|
179
|
+
fixture.model.title = " Dune Messiah ";
|
|
180
|
+
const held = fixture.holdSaves();
|
|
181
|
+
const saving = fixture.form.submit();
|
|
182
|
+
await settle();
|
|
183
|
+
assert.deepEqual(fixture.saves, [{ title: " Dune Messiah ", author: "Herbert" }]);
|
|
184
|
+
fixture.model.author = "Frank Herbert";
|
|
185
|
+
held.resolve();
|
|
186
|
+
await saving;
|
|
187
|
+
await settle();
|
|
188
|
+
|
|
189
|
+
assert.equal(fixture.model.title, "Dune Messiah", "the field the save sent took the server's stored value");
|
|
190
|
+
assert.equal(fixture.model.author, "Frank Herbert", "the field changed while the save ran kept the person's value");
|
|
191
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("saving a field in conflict saves the person's value and ends the conflict", async (t) => {
|
|
195
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
196
|
+
await settle();
|
|
197
|
+
|
|
198
|
+
fixture.model.title = "Mine";
|
|
199
|
+
fixture.server[1].title = "Theirs";
|
|
200
|
+
await fixture.readAgain();
|
|
201
|
+
assert.deepEqual(fixture.form.conflicts.value, [{ key: "title", value: "Theirs" }]);
|
|
202
|
+
|
|
203
|
+
await fixture.form.submit();
|
|
204
|
+
await settle();
|
|
205
|
+
assert.deepEqual(fixture.saves, [{ title: "Mine", author: "Herbert" }]);
|
|
206
|
+
assert.equal(fixture.model.title, "Mine");
|
|
207
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test("opening another record shows that record, never the last record's edits", async (t) => {
|
|
211
|
+
const fixture = editForm(t, { records: { 1: DUNE, 2: { title: "Emma", author: "Austen" } } });
|
|
212
|
+
await settle();
|
|
213
|
+
fixture.model.title = "Dune (draft)";
|
|
214
|
+
fixture.server[1].title = "Dune Messiah";
|
|
215
|
+
await fixture.readAgain();
|
|
216
|
+
assert.equal(fixture.form.conflicts.value.length, 1);
|
|
217
|
+
|
|
218
|
+
// Record 2 is already cached, as after visiting it, so the form gets its data without a pending read.
|
|
219
|
+
fixture.queryClient.setQueryData(["books", "2"], { title: "Emma", author: "Austen" });
|
|
220
|
+
fixture.id.value = "2";
|
|
221
|
+
await settle();
|
|
222
|
+
assert.deepEqual({ ...fixture.model }, { title: "Emma", author: "Austen" });
|
|
223
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
224
|
+
|
|
225
|
+
// Back on record 1, the form shows record 1 again; the edit made on record 2 stays behind.
|
|
226
|
+
fixture.model.title = "Emma (draft)";
|
|
227
|
+
fixture.id.value = "1";
|
|
228
|
+
await settle();
|
|
229
|
+
assert.deepEqual({ ...fixture.model }, { title: "Dune Messiah", author: "Herbert" });
|
|
230
|
+
assert.deepEqual(fixture.form.conflicts.value, []);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
test("a record another read hands the form, as a settings page's shared read does, keeps the person's edits too", async (t) => {
|
|
234
|
+
const fixture = editForm(t, { records: { 1: DUNE } });
|
|
235
|
+
await settle();
|
|
236
|
+
|
|
237
|
+
fixture.model.title = "Dune (draft)";
|
|
238
|
+
fixture.form.applyLoaded({ title: "Dune Messiah", author: "Frank Herbert" });
|
|
239
|
+
assert.equal(fixture.model.title, "Dune (draft)");
|
|
240
|
+
assert.equal(fixture.model.author, "Frank Herbert");
|
|
241
|
+
assert.deepEqual(fixture.form.conflicts.value, [{ key: "title", value: "Dune Messiah" }]);
|
|
242
|
+
});
|
|
@@ -12,7 +12,9 @@ import { useCrudAddEditScreen } from "../src/client/composables/useCrudAddEditSc
|
|
|
12
12
|
|
|
13
13
|
const componentUrl = new URL("../src/client/components/CrudAddEditScreen.vue", import.meta.url).href;
|
|
14
14
|
// The shell's app bar actions render in place as buttons; to, disabled and the click handler fall through to them.
|
|
15
|
+
// The form's conflict notice renders nothing here: these forms read no record.
|
|
15
16
|
const SHELL_PAGE_ACTION_STUBS = {
|
|
17
|
+
"/EditConflictNotice.vue": "export default { render: () => null };",
|
|
16
18
|
"/ShellPageActions.vue":
|
|
17
19
|
'import { defineComponent, h } from "vue"; export default defineComponent({ setup: (_props, { slots }) => () => h("div", {}, slots.default?.()) });',
|
|
18
20
|
"/ShellPageAction.vue":
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import process from "node:process";
|
|
4
|
+
import test from "node:test";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { expect } from "@playwright/test";
|
|
7
|
+
import { sharedBrowserFixture } from "../../../tooling/testUtils/browserFixture.mjs";
|
|
8
|
+
|
|
9
|
+
// An edit form reads its record again while the person edits it: a realtime event, the window regaining focus or
|
|
10
|
+
// Retry. Here the window regaining focus refetches it (TanStack's refetchOnWindowFocus), against a books API whose
|
|
11
|
+
// record another person changes meanwhile. The page is the crud-screen-set pattern's edit page in the real shell.
|
|
12
|
+
const SKIP = process.env.JSKIT_HTTP_WEB_KEPT_EDITS_BROWSER === "1"
|
|
13
|
+
? false
|
|
14
|
+
: "set JSKIT_HTTP_WEB_KEPT_EDITS_BROWSER=1 to check that an edit form read again keeps the person's unsaved edits";
|
|
15
|
+
const FIXTURE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../fixtures/crud-screens");
|
|
16
|
+
const open = sharedBrowserFixture({ fixtureRoot: FIXTURE_ROOT });
|
|
17
|
+
const JSON_API = "application/vnd.api+json";
|
|
18
|
+
|
|
19
|
+
function bookDocument(record) {
|
|
20
|
+
return {
|
|
21
|
+
contentType: JSON_API,
|
|
22
|
+
body: JSON.stringify({
|
|
23
|
+
data: {
|
|
24
|
+
type: "books",
|
|
25
|
+
id: "1",
|
|
26
|
+
attributes: { ...record, createdAt: "2026-01-02T10:00:00.000Z", updatedAt: "2026-01-02T10:00:00.000Z" }
|
|
27
|
+
}
|
|
28
|
+
})
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Book 1 as the server holds it, which the test changes as another person saving it would. `holdRead()` makes the
|
|
33
|
+
// next read of it wait until the test answers it with the record as it is then.
|
|
34
|
+
async function serveBook(page) {
|
|
35
|
+
const server = { record: { title: "Dune", author: "Herbert", notes: null }, saves: [], held: null };
|
|
36
|
+
server.holdRead = () => {
|
|
37
|
+
const read = Promise.withResolvers();
|
|
38
|
+
server.held = read;
|
|
39
|
+
return read.promise;
|
|
40
|
+
};
|
|
41
|
+
await page.route("**/api/**", async (route) => {
|
|
42
|
+
const request = route.request();
|
|
43
|
+
const { pathname } = new URL(request.url());
|
|
44
|
+
const key = `${request.method()} ${pathname}`;
|
|
45
|
+
if (key === "GET /api/session") {
|
|
46
|
+
await route.fulfill({ contentType: "application/json", body: JSON.stringify({ csrfToken: "test-token" }) });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (key === "GET /api/books/1") {
|
|
50
|
+
const held = server.held;
|
|
51
|
+
server.held = null;
|
|
52
|
+
if (held) {
|
|
53
|
+
await new Promise((answered) => held.resolve(async () => {
|
|
54
|
+
await route.fulfill(bookDocument(server.record)).catch(() => {});
|
|
55
|
+
answered();
|
|
56
|
+
}));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
await route.fulfill(bookDocument(server.record));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (key === "PATCH /api/books/1") {
|
|
63
|
+
const { attributes } = request.postDataJSON().data;
|
|
64
|
+
server.saves.push(attributes);
|
|
65
|
+
server.record = { ...server.record, ...attributes };
|
|
66
|
+
await route.fulfill(bookDocument(server.record));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
await route.fulfill({ status: 404, contentType: JSON_API, body: JSON.stringify({ errors: [{ status: "404" }] }) });
|
|
70
|
+
});
|
|
71
|
+
return server;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The person comes back to the window: TanStack reads the form's record again.
|
|
75
|
+
function returnToWindow(page) {
|
|
76
|
+
return page.evaluate(() => window.dispatchEvent(new Event("visibilitychange")));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
test("an edit form read again keeps what the person typed, takes the fields they left, and says when the server changed theirs", {
|
|
80
|
+
skip: SKIP,
|
|
81
|
+
timeout: 120_000
|
|
82
|
+
}, async (t) => {
|
|
83
|
+
const { vite, browser } = await open(t);
|
|
84
|
+
const page = await browser.newPage({ baseURL: vite.baseURL, viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" });
|
|
85
|
+
t.after(() => page.close());
|
|
86
|
+
const server = await serveBook(page);
|
|
87
|
+
await page.goto("/books/1/edit");
|
|
88
|
+
const title = page.getByRole("textbox", { name: "Title" });
|
|
89
|
+
const author = page.getByRole("textbox", { name: "Author" });
|
|
90
|
+
await expect(title).toHaveValue("Dune");
|
|
91
|
+
|
|
92
|
+
await title.fill("Dune (my edit)");
|
|
93
|
+
server.record = { ...server.record, title: "Dune Messiah", author: "Frank Herbert" };
|
|
94
|
+
const read = server.holdRead();
|
|
95
|
+
await returnToWindow(page);
|
|
96
|
+
const answer = await read;
|
|
97
|
+
|
|
98
|
+
// While the record is read again the person can go on typing, and what they type stays.
|
|
99
|
+
await expect(title).toBeEditable();
|
|
100
|
+
await title.press("End");
|
|
101
|
+
await title.pressSequentially("!");
|
|
102
|
+
await answer();
|
|
103
|
+
|
|
104
|
+
await expect(author).toHaveValue("Frank Herbert");
|
|
105
|
+
await expect(title).toHaveValue("Dune (my edit)!");
|
|
106
|
+
const notice = page.locator(".crud-add-edit-form").getByRole("status");
|
|
107
|
+
await expect(notice).toContainText("Title changed to “Dune Messiah” while you were editing.");
|
|
108
|
+
await expect(notice.getByText(/Author/u)).toHaveCount(0);
|
|
109
|
+
|
|
110
|
+
await notice.getByRole("button", { name: "Use the new Title" }).click();
|
|
111
|
+
await expect(title).toHaveValue("Dune Messiah");
|
|
112
|
+
await expect(notice.getByRole("button")).toHaveCount(0);
|
|
113
|
+
|
|
114
|
+
// Kept instead: the person's value stays, and the same server value does not raise it again.
|
|
115
|
+
await title.fill("Dune, mine");
|
|
116
|
+
server.record = { ...server.record, title: "Dune, theirs" };
|
|
117
|
+
await returnToWindow(page);
|
|
118
|
+
await expect(notice).toContainText("Title changed to “Dune, theirs” while you were editing.");
|
|
119
|
+
await notice.getByRole("button", { name: "Keep your Title" }).click();
|
|
120
|
+
await expect(notice.getByRole("button")).toHaveCount(0);
|
|
121
|
+
await returnToWindow(page);
|
|
122
|
+
await page.waitForTimeout(500);
|
|
123
|
+
await expect(notice.getByRole("button")).toHaveCount(0);
|
|
124
|
+
await expect(title).toHaveValue("Dune, mine");
|
|
125
|
+
|
|
126
|
+
await page.getByRole("button", { name: "Save changes" }).click();
|
|
127
|
+
await expect.poll(() => server.saves.length).toBe(1);
|
|
128
|
+
assert.equal(server.saves[0].title, "Dune, mine");
|
|
129
|
+
assert.equal(server.saves[0].author, "Frank Herbert");
|
|
130
|
+
});
|
|
@@ -21,6 +21,7 @@ test("http-web exports are explicit and aligned with production and generated us
|
|
|
21
21
|
"./client/components/CrudListFilterSurface",
|
|
22
22
|
"./client/components/CrudListScreen",
|
|
23
23
|
"./client/components/CrudViewScreen",
|
|
24
|
+
"./client/components/EditConflictNotice",
|
|
24
25
|
"./client/components/SelectField",
|
|
25
26
|
"./client/bulkActions",
|
|
26
27
|
"./client/filters",
|
|
@@ -46,6 +47,7 @@ test("http-web exports are explicit and aligned with production and generated us
|
|
|
46
47
|
"./client/composables/usePagedCollection",
|
|
47
48
|
"./client/composables/useRealtimeQueryInvalidation",
|
|
48
49
|
"./client/composables/useUiFeedback",
|
|
50
|
+
"./client/composables/useUnsavedEdits",
|
|
49
51
|
"./client/composables/useView",
|
|
50
52
|
"./client/crudHttpClient",
|
|
51
53
|
"./client/lib/httpClient",
|