@stacksjs/defaults 0.75.613 → 0.75.614

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.
@@ -4,9 +4,17 @@
4
4
  // model's API lets the dashboard change are inputs; the rest are shown beside
5
5
  // them, read only, as context. Saving sends only what changed, then returns
6
6
  // to where the visitor came from: the record's page, or the list.
7
+ //
8
+ // Below them, the record's related rows (an order's lines), where the related
9
+ // model lets the dashboard write them. A row added, edited or deleted here is
10
+ // kept as a draft and saved with the record, all or nothing
11
+ // (stacksjs/stacks#3315): one refusal and nothing is saved, and the page
12
+ // points at the field or the row that was refused.
7
13
  import { useNavigation } from '@stacksjs/defaults/views/dashboard/composables/useNavigation'
8
- import type { ModelFormValues, ModelRecord } from '../../../../functions/dashboard-model-record'
9
- import { fetchModelRecord, modelNameFromSlug, modelFormFieldsFor, modelFormPayload, modelFormValues, modelRecordBackHref, modelRecordHref, modelRecordListLabel, modelRecordSections, updateModelRecord } from '../../../../functions/dashboard-model-record'
14
+ import type { ModelDraftListRow, ModelDrafts, ModelDraftState, ModelRelatedChanges, ModelSaveLocation } from '../../../../functions/dashboard-model-drafts'
15
+ import { modelDraftChangeCount, modelDraftIsNew, modelDraftKey, modelDraftListRows, modelDraftPut, modelDraftRemove, modelDraftRestore, modelDraftRowLabel, modelDraftValues, modelRelatedSaveChanges, saveModelRecordWithRelated } from '../../../../functions/dashboard-model-drafts'
16
+ import type { ModelFormValues, ModelRecord, ModelRelatedPanel } from '../../../../functions/dashboard-model-record'
17
+ import { fetchModelRecord, fetchModelRelated, modelNameFromSlug, modelFormFieldsFor, modelFormPayload, modelFormValues, modelRecordBackHref, modelRecordHref, modelRecordListLabel, modelRecordSections, modelRelatedAddsHere, updateModelRecord } from '../../../../functions/dashboard-model-record'
10
18
  import { dashboardLoaderTimer } from '../../../../functions/dashboard-loading'
11
19
  import { pushToast } from '../../../../functions/toasts'
12
20
 
@@ -23,6 +31,16 @@ const saving = state(false)
23
31
  const saveError = state('')
24
32
  const saveErrors = state<Record<string, string[]>>({})
25
33
 
34
+ // The record's related rows and what has been changed in them, unsaved.
35
+ const panels = state<ModelRelatedPanel[]>([])
36
+ const drafts = state<ModelDrafts>({})
37
+ // The row form open in a panel: a listed row by its id, or one added here by its key.
38
+ const rowEditor = state<{ panel: ModelRelatedPanel, key: string } | null>(null)
39
+ const rowValues = state<ModelFormValues>({})
40
+ // Where the last save was refused, when it was a row: shown on that row and in its form.
41
+ const refusedAt = state<ModelSaveLocation | null>(null)
42
+ const refusedErrors = state<Record<string, string[]>>({})
43
+
26
44
  // `/models/{slug}/{id}/edit`
27
45
  function slug(): string {
28
46
  return navigation.urlSegment(-3)
@@ -56,6 +74,113 @@ const context = derived(() => {
56
74
  const anonymized = derived(() => Boolean(record()?.anonymized))
57
75
  const canEdit = derived(() => Boolean(record()?.writeCapabilities.update) && writable().length > 0 && !anonymized())
58
76
 
77
+ /** The panels whose rows can be changed here: added, edited or deleted. */
78
+ const editablePanels = derived(() => panels().filter(panel => modelRelatedAddsHere(panel) || canEditRows(panel) || Boolean(panel.canDestroy)))
79
+ const pendingCount = derived(() => modelDraftChangeCount(panels(), drafts()))
80
+
81
+ function canEditRows(panel: ModelRelatedPanel): boolean {
82
+ return Boolean(panel.canUpdate) && (panel.fields?.length ?? 0) > 0
83
+ }
84
+
85
+ function listRows(panel: ModelRelatedPanel): ModelDraftListRow[] {
86
+ return modelDraftListRows(panel, drafts())
87
+ }
88
+
89
+ function rowLabel(panel: ModelRelatedPanel, row: ModelDraftListRow): string {
90
+ return modelDraftRowLabel(panel, row)
91
+ }
92
+
93
+ const STATE_LABELS: Record<ModelDraftState, string> = { kept: '', added: 'New', edited: 'Edited', removed: 'Will be deleted' }
94
+
95
+ function stateLabel(row: ModelDraftListRow): string {
96
+ return STATE_LABELS[row.state]
97
+ }
98
+
99
+ /** A second of a `hasOne` would break the "one": only offered while there is none. */
100
+ function canAddRow(panel: ModelRelatedPanel): boolean {
101
+ return modelRelatedAddsHere(panel) && (panel.kind === 'many' || listRows(panel).every(row => row.state === 'removed'))
102
+ }
103
+
104
+ /** A row added here, not one that is stored. */
105
+ function isNewRow(row: ModelDraftListRow): boolean {
106
+ return modelDraftIsNew(row.key)
107
+ }
108
+
109
+ function canEditRow(panel: ModelRelatedPanel, row: ModelDraftListRow): boolean {
110
+ return row.state !== 'removed' && (modelDraftIsNew(row.key) || canEditRows(panel))
111
+ }
112
+
113
+ function canRemoveRow(panel: ModelRelatedPanel, row: ModelDraftListRow): boolean {
114
+ return row.state !== 'removed' && (modelDraftIsNew(row.key) || Boolean(panel.canDestroy))
115
+ }
116
+
117
+ function openRow(panel: ModelRelatedPanel, key: string): void {
118
+ rowValues.set(modelDraftValues(panel, drafts(), key))
119
+ rowEditor.set({ panel, key })
120
+ }
121
+
122
+ function addRow(panel: ModelRelatedPanel): void {
123
+ openRow(panel, modelDraftKey(drafts(), panel.slug))
124
+ }
125
+
126
+ function editRow(panel: ModelRelatedPanel, row: ModelDraftListRow): void {
127
+ openRow(panel, row.key)
128
+ }
129
+
130
+ function removeRow(panel: ModelRelatedPanel, row: ModelDraftListRow): void {
131
+ drafts.set(modelDraftRemove(drafts(), panel, row.key))
132
+ }
133
+
134
+ function restoreRow(panel: ModelRelatedPanel, row: ModelDraftListRow): void {
135
+ drafts.set(modelDraftRestore(drafts(), panel, row.key))
136
+ }
137
+
138
+ function setRowValue(change: { name: string, value: string | boolean }): void {
139
+ rowValues.set({ ...rowValues(), [change.name]: change.value })
140
+ }
141
+
142
+ /** Keep the row's form with the other changes. Nothing is written until the record is saved. */
143
+ function keepRow(): void {
144
+ const current = rowEditor()
145
+ if (!current)
146
+ return
147
+ drafts.set(modelDraftPut(drafts(), current.panel, current.key, rowValues()))
148
+ rowEditor.set(null)
149
+ }
150
+
151
+ /** Whether this panel's row form is the one open. One row is changed at a time. */
152
+ function editingIn(panel: ModelRelatedPanel): boolean {
153
+ return rowEditor()?.panel.slug === panel.slug
154
+ }
155
+
156
+ function closeRowEditor(): void {
157
+ rowEditor.set(null)
158
+ }
159
+
160
+ const rowEditorTitle = derived(() => {
161
+ const current = rowEditor()
162
+ if (!current)
163
+ return ''
164
+ const kept = drafts()[current.panel.slug]?.added.some(row => row.key === current.key) ?? false
165
+ return `${modelDraftIsNew(current.key) && !kept ? 'Add' : 'Edit'} ${current.panel.label.toLowerCase()}`
166
+ })
167
+
168
+ function refusedHere(panel: ModelRelatedPanel, key: string): boolean {
169
+ const at = refusedAt()
170
+ return Boolean(at) && at!.panel === panel.slug && at!.row === key
171
+ }
172
+
173
+ /** Why the last save refused this row, under it on the list. */
174
+ function rowRefusal(panel: ModelRelatedPanel, row: ModelDraftListRow): string {
175
+ return refusedHere(panel, row.key) ? saveError() : ''
176
+ }
177
+
178
+ /** The row form's field messages, when it is the row the last save refused. */
179
+ const rowEditorErrors = derived(() => {
180
+ const current = rowEditor()
181
+ return current && refusedHere(current.panel, current.key) ? refusedErrors() : {}
182
+ })
183
+
59
184
  function setValue(change: { name: string, value: string | boolean }): void {
60
185
  values.set({ ...values(), [change.name]: change.value })
61
186
  }
@@ -70,6 +195,9 @@ async function loadRecord(): Promise<void> {
70
195
  const start = modelFormValues(loaded.fields, loaded.row)
71
196
  initial.set(start)
72
197
  values.set({ ...start })
198
+ // The rows are a part of the page that can fail on its own: without them
199
+ // the record's own fields are still edited and saved as before.
200
+ panels.set(await fetchModelRelated(slug(), recordId()).catch(() => []))
73
201
  }
74
202
  catch (error) {
75
203
  record.set(null)
@@ -86,13 +214,20 @@ async function save(): Promise<void> {
86
214
  if (!current || saving())
87
215
  return
88
216
  const fields = modelFormPayload(current.fields, values(), initial())
89
- if (Object.keys(fields).length === 0) {
217
+ const related = modelRelatedSaveChanges(panels(), drafts())
218
+ if (Object.keys(fields).length === 0 && related.length === 0) {
90
219
  navigate(returnHref())
91
220
  return
92
221
  }
93
222
  saving.set(true)
94
223
  saveError.set('')
95
224
  saveErrors.set({})
225
+ refusedAt.set(null)
226
+ refusedErrors.set({})
227
+ if (related.length > 0) {
228
+ await saveTogether(current, fields, related)
229
+ return
230
+ }
96
231
  const result = await updateModelRecord(slug(), recordId(), fields)
97
232
  saving.set(false)
98
233
  if (!result.ok) {
@@ -106,6 +241,32 @@ async function save(): Promise<void> {
106
241
  navigate(returnHref())
107
242
  }
108
243
 
244
+ /** The record and its rows in one request: all of it saved, or none of it. */
245
+ async function saveTogether(current: ModelRecord, fields: Record<string, unknown>, related: ModelRelatedChanges[]): Promise<void> {
246
+ const changes = pendingCount()
247
+ const result = await saveModelRecordWithRelated(slug(), recordId(), fields, related)
248
+ saving.set(false)
249
+ if (!result.ok) {
250
+ const at = result.at
251
+ const panel = at?.panel ? panels().find(candidate => candidate.slug === at.panel) : undefined
252
+ if (!panel || !at?.row) {
253
+ // The record's own fields: under each, as a single save shows them.
254
+ saveError.set(`Nothing was saved. ${result.error}`)
255
+ saveErrors.set(result.errors)
256
+ return
257
+ }
258
+ // One row: said on the row, and in its form when it is opened.
259
+ const words = Object.values(result.errors).flat().join(' ') || result.error
260
+ const row = listRows(panel).find(candidate => candidate.key === at.row)
261
+ refusedAt.set(at)
262
+ refusedErrors.set(result.errors)
263
+ saveError.set(`Nothing was saved. ${row ? rowLabel(panel, row) : `${panel.label} ${at.row}`}: ${words}`)
264
+ return
265
+ }
266
+ pushToast('success', `${current.modelName} ${recordId()} saved`, { detail: `With ${changes} ${changes === 1 ? 'change' : 'changes'} to its related rows.` })
267
+ navigate(returnHref())
268
+ }
269
+
109
270
  function cancel(): void {
110
271
  if (!saving())
111
272
  navigate(returnHref())
@@ -149,36 +310,87 @@ onMount(() => {
149
310
  description="Its name and email were removed and it can no longer sign in, so there is nothing to edit. Records that refer to it were kept."
150
311
  />
151
312
 
152
- <form :if="!loading() && canEdit()" id="model-edit-form" class="flex flex-col gap-6" @submit.prevent="save">
153
- <div :if="saveError()" role="alert" class="px-4 py-3 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/40 border border-red-200 rounded-lg dark:border-red-900">
154
- {{ saveError() }}
155
- </div>
313
+ <div :if="!loading() && canEdit()" class="flex flex-col gap-6">
314
+ <form id="model-edit-form" class="flex flex-col gap-6" @submit.prevent="save">
315
+ <div :if="saveError()" role="alert" class="px-4 py-3 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/40 border border-red-200 rounded-lg dark:border-red-900">
316
+ {{ saveError() }}
317
+ </div>
318
+
319
+ <div class="grid gap-6 grid-cols-1 items-start lg:grid-cols-2">
320
+ <Card padding="none">
321
+ <h2 class="px-6 py-4 font-semibold text-base text-neutral-900 dark:text-white border-b border-neutral-200 dark:border-neutral-700">{{ modelName() }} Details</h2>
322
+ <div class="p-6">
323
+ <ModelFieldInputs :fields="writable()" :slug="slug()" :values="values()" :errors="saveErrors()" :disabled="saving()" @change="setValue" />
324
+ </div>
325
+ </Card>
156
326
 
157
- <div class="grid gap-6 grid-cols-1 items-start lg:grid-cols-2">
158
- <Card padding="none">
159
- <h2 class="px-6 py-4 font-semibold text-base text-neutral-900 dark:text-white border-b border-neutral-200 dark:border-neutral-700">{{ modelName() }} Details</h2>
160
- <div class="p-6">
161
- <ModelFieldInputs :fields="writable()" :slug="slug()" :values="values()" :errors="saveErrors()" :disabled="saving()" @change="setValue" />
162
- </div>
163
- </Card>
164
-
165
- <Card :if="context().length > 0" padding="none">
166
- <div class="px-6 py-4 border-b border-neutral-200 dark:border-neutral-700">
167
- <h2 class="font-semibold text-base text-neutral-900 dark:text-white">Read only</h2>
168
- <p class="mt-1 text-neutral-500 text-xs dark:text-neutral-400">Set by the application. These cannot be changed from here.</p>
169
- </div>
170
- <dl class="grid gap-x-8 gap-y-6 grid-cols-1 sm:grid-cols-2 p-6">
171
- <div :for="detail in context()" :class="detail.wide ? 'min-w-0 sm:col-span-2' : 'min-w-0'">
172
- <dt class="font-medium text-neutral-900 text-sm dark:text-white">{{ detail.label }}</dt>
173
- <dd :class="detail.empty ? 'mt-1.5 text-sm text-neutral-400 dark:text-neutral-500' : 'mt-1.5 text-sm break-words text-neutral-700 dark:text-neutral-200'">{{ detail.value }}</dd>
327
+ <Card :if="context().length > 0" padding="none">
328
+ <div class="px-6 py-4 border-b border-neutral-200 dark:border-neutral-700">
329
+ <h2 class="font-semibold text-base text-neutral-900 dark:text-white">Read only</h2>
330
+ <p class="mt-1 text-neutral-500 text-xs dark:text-neutral-400">Set by the application. These cannot be changed from here.</p>
174
331
  </div>
175
- </dl>
176
- </Card>
332
+ <dl class="grid gap-x-8 gap-y-6 grid-cols-1 sm:grid-cols-2 p-6">
333
+ <div :for="detail in context()" :class="detail.wide ? 'min-w-0 sm:col-span-2' : 'min-w-0'">
334
+ <dt class="font-medium text-neutral-900 text-sm dark:text-white">{{ detail.label }}</dt>
335
+ <dd :class="detail.empty ? 'mt-1.5 text-sm text-neutral-400 dark:text-neutral-500' : 'mt-1.5 text-sm break-words text-neutral-700 dark:text-neutral-200'">{{ detail.value }}</dd>
336
+ </div>
337
+ </dl>
338
+ </Card>
339
+ </div>
340
+ </form>
341
+
342
+ <div :if="editablePanels().length > 0" class="flex flex-col gap-6" data-related-drafts>
343
+ <div :for="panel in editablePanels()" class="min-w-0" data-related-draft-panel>
344
+ <Card padding="none">
345
+ <div class="flex flex-wrap gap-3 items-center justify-between px-6 py-4 border-b border-neutral-200 dark:border-neutral-700">
346
+ <div class="min-w-0">
347
+ <h2 class="font-semibold text-base text-neutral-900 truncate dark:text-white">{{ panel.title }}</h2>
348
+ <p class="mt-1 text-neutral-500 text-xs dark:text-neutral-400">Changes here are saved with this record, all at once.</p>
349
+ </div>
350
+ <Button :if="canAddRow(panel)" variant="secondary" size="sm" :disabled="saving()" @click="addRow(panel)">
351
+ <span aria-hidden="true" class="h-3.5 w-3.5 i-hugeicons-add-01"></span>
352
+ {{ 'Add ' + panel.label.toLowerCase() }}
353
+ </Button>
354
+ </div>
355
+ <ul :if="listRows(panel).length > 0" class="divide-neutral-200 divide-y dark:divide-neutral-700">
356
+ <li :for="row in listRows(panel)" class="flex flex-wrap gap-3 items-center justify-between px-6 py-3" :data-draft-state="row.state">
357
+ <div class="min-w-0">
358
+ <p :class="row.state === 'removed' ? 'text-sm truncate text-neutral-400 line-through dark:text-neutral-500' : 'text-sm truncate text-neutral-900 dark:text-white'">{{ rowLabel(panel, row) }}</p>
359
+ <p :if="rowRefusal(panel, row)" role="alert" class="mt-1 text-red-600 text-xs dark:text-red-400">{{ rowRefusal(panel, row) }}</p>
360
+ </div>
361
+ <div class="flex flex-none gap-2 items-center">
362
+ <span :if="stateLabel(row)" class="px-2 py-0.5 font-medium text-neutral-700 text-xs dark:text-neutral-200 bg-neutral-100 dark:bg-neutral-800 rounded-full">{{ stateLabel(row) }}</span>
363
+ <span :if="canEditRow(panel, row)"><Button variant="secondary" size="sm" :disabled="saving()" @click="editRow(panel, row)">Edit</Button></span>
364
+ <span :if="canRemoveRow(panel, row)"><Button variant="secondary" size="sm" :disabled="saving()" @click="removeRow(panel, row)">{{ isNewRow(row) ? 'Discard' : 'Delete' }}</Button></span>
365
+ <span :if="row.state === 'removed'"><Button variant="secondary" size="sm" :disabled="saving()" @click="restoreRow(panel, row)">Keep</Button></span>
366
+ </div>
367
+ </li>
368
+ </ul>
369
+ <p :if="listRows(panel).length === 0 && !editingIn(panel)" class="px-6 py-5 text-neutral-500 text-sm dark:text-neutral-400">{{ 'No ' + panel.title.toLowerCase() + ' yet' }}</p>
370
+
371
+ <form :if="editingIn(panel)" id="related-draft-form" class="flex flex-col gap-5 px-6 py-5 bg-neutral-50 dark:bg-neutral-900/40 border-neutral-200 border-t dark:border-neutral-700" data-related-draft-editor @submit.prevent="keepRow">
372
+ <h3 class="font-medium text-neutral-900 text-sm dark:text-white">{{ rowEditorTitle() }}</h3>
373
+ <ModelFieldInputs
374
+ :fields="rowEditor()?.panel.fields ?? []"
375
+ :slug="rowEditor()?.panel.slug ?? ''"
376
+ :values="rowValues()"
377
+ :errors="rowEditorErrors()"
378
+ @change="setRowValue"
379
+ />
380
+ <div class="flex flex-wrap gap-2 items-center">
381
+ <Button variant="primary" size="sm" type="submit">Keep</Button>
382
+ <Button variant="secondary" size="sm" @click="closeRowEditor">Cancel</Button>
383
+ <span class="text-neutral-500 text-xs dark:text-neutral-400">Nothing is written until you save the record.</span>
384
+ </div>
385
+ </form>
386
+ </Card>
387
+ </div>
177
388
  </div>
178
389
 
179
390
  <div class="flex gap-3 items-center">
180
- <Button type="submit" variant="primary" :loading="saving()">Save changes</Button>
391
+ <Button type="submit" variant="primary" form="model-edit-form" :loading="saving()">Save changes</Button>
181
392
  <Button variant="secondary" :disabled="saving()" @click="cancel">Cancel</Button>
393
+ <span :if="pendingCount() > 0" class="text-neutral-500 text-sm dark:text-neutral-400">{{ pendingCount() + (pendingCount() === 1 ? ' related change' : ' related changes') + ' to save' }}</span>
182
394
  </div>
183
- </form>
395
+ </div>
184
396
  </div>
@@ -524,6 +524,8 @@ route.group({ prefix: '/api/dashboard', apiResponse: true }, () => {
524
524
  // actions enforce rather than the route.
525
525
  guard(route.post('/models/{slug}', 'Actions/Dashboard/Models/ModelStoreAction'))
526
526
  guard(route.patch('/models/{slug}/{id}', 'Actions/Dashboard/Models/ModelUpdateAction'))
527
+ // A record and its related rows, all or nothing (stacksjs/stacks#3315).
528
+ guard(route.patch('/models/{slug}/{id}/save', 'Actions/Dashboard/Models/ModelSaveAction'))
527
529
  guard(route.delete('/models/{slug}/{id}', 'Actions/Dashboard/Models/ModelDestroyAction'))
528
530
  // The actions a model lists under `dashboard.actions`, run on one record:
529
531
  // "Mark as shipped". The parameters other than `id` are named so that an