-
Notifications
You must be signed in to change notification settings - Fork 6
/
DitoForm.vue
453 lines (414 loc) · 13.9 KB
/
DitoForm.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<template lang="pug">
.dito-form.dito-scroll-parent(
:class="{ 'dito-form-nested': isNestedRoute }"
)
// NOTE: Nested form components are kept alive by using `v-show` instead of
// `v-if` here, so event handling and other things still work with nested
// editing. Only render a router-view here if this isn't the last data route
// and not a nested form route, which will appear elsewhere in its own view.
router-view(
v-if="!(isLastUnnestedRoute || isNestedRoute)"
v-show="!isActive"
)
// Use a <div> for inlined forms, as we shouldn't nest actual <form> tags.
component.dito-scroll(
v-show="isActive"
:is="isNestedRoute ? 'div' : 'form'"
@submit.prevent
)
dito-schema(
:schema="schema"
:dataPath="dataPath"
:data="data"
:meta="meta"
:store="store"
:disabled="isLoading"
:selectedTab="selectedTab"
:menuHeader="true"
)
dito-buttons.dito-buttons-main.dito-buttons-large(
slot="buttons"
:buttons="buttonSchemas"
:dataPath="dataPath"
:data="data"
:meta="meta"
:store="store"
:disabled="isLoading"
)
</template>
<script>
import DitoComponent from '@/DitoComponent'
import RouteMixin from '@/mixins/RouteMixin'
import ResourceMixin from '@/mixins/ResourceMixin'
import { getResource, getMemberResource } from '@/utils/resource'
import { getButtonSchemas, isObjectSource } from '@/utils/schema'
import { clone, capitalize, parseDataPath, merge } from '@ditojs/utils'
// @vue/component
export default DitoComponent.component('dito-form', {
mixins: [RouteMixin, ResourceMixin],
data() {
return {
createdData: null,
clonedData: undefined,
sourceKey: null,
isForm: true
}
},
computed: {
verbs() {
// Add submit / submitted to the verbs returned by ResourceMixin
// NOTE: These get passed on to children through:
// `provide() ... { $verbs: () => this.verbs }` in ResourceMixin
const verbs = this.getVerbs()
const { isCreating, providesData } = this
return {
...verbs,
submit: isCreating ? verbs.create : verbs.save,
submitted: isCreating ? verbs.created : verbs.saved,
cancel: providesData ? verbs.cancel : verbs.close,
cancelled: providesData ? verbs.cancelled : verbs.closed
}
},
schema() {
return this.getItemFormSchema(
this.sourceSchema,
// If there is no data yet, provide an empty object with just the right
// type set, so the form can always be determined.
this.data || { type: this.type }
) || {} // Always return a schema object so we don't need to check for it.
},
buttonSchemas() {
return getButtonSchemas(
merge(
{
cancel: {
type: 'button',
events: {
click: () => this.cancel()
}
},
submit: !this.doesMutate && {
type: 'submit',
// Submit buttons close the form by default:
closeForm: true,
events: {
click: ({ target }) => target.submit()
}
}
},
this.schema.buttons
)
)
},
isActive() {
return this.isLastRoute || this.isLastUnnestedRoute
},
isTransient() {
return !this.providesData
},
isCreating() {
// this.param is inherited from RouteMixin
return this.param === 'create'
},
isDirty() {
return !this.doesMutate && !!this.mainSchemaComponent?.isDirty
},
selectedTab() {
return this.mainSchemaComponent?.selectedTab || null
},
doesMutate() {
// When `sourceSchema.mutate` is true, the form edits the inherited data
// directly instead of making a copy for application upon submit.
// See `inheritedData()` computed property for more details.
return this.sourceSchema.mutate
},
type() {
// The type of form to create, if there are multiple forms to choose from.
return this.$route.query.type
},
itemId() {
return this.isCreating
? null
: (this.param ?? null)
},
method() {
return this.isCreating ? 'post' : 'patch'
},
resource() {
const resource = this.getResource()
return getMemberResource(this.itemId, resource) || resource
},
breadcrumbPrefix() {
return capitalize(this.isCreating ? this.verbs.create : this.verbs.edit)
},
data() {
// Return different data "containers" based on different scenarios:
// 1. createdData, if we're in a form for a newly created object.
// 2. loadedData, if the form itself is the root of the data (e.g. when
// directly loading an editing root).
// 3. The data inherited from the parent, which itself may be either a
// view that loaded the data, or a form that either loaded the data, or
// also inherited it from its parent. Note that we use a clone of it,
// so, data changes aren't applied until setSourceData() is called.
return this.createdData || this.loadedData || this.inheritedData || null
},
dataPath() {
return this.getDataPathFrom(this.dataComponent)
},
sourceData() {
// Possible parents are DitoForm for forms, or DitoView for root lists.
// Both have a data property which abstracts away loading and inheriting
// of data.
let { data } = this.parentRouteComponent
if (data) {
// Handle nested data by splitting the dataPath, iterate through the
// actual data and look nest child-data up.
const dataParts = parseDataPath(
this.getDataPathFrom(this.parentRouteComponent)
)
// Compare dataParts against matched routePath parts, to identify those
// parts that need to be treated like ids and mapped to indices in data.
const pathParts = this.routeRecord.path.split('/')
const routeParts = pathParts.slice(pathParts.length - dataParts.length)
this.sourceKey = null
const lastDataPart = dataParts[dataParts.length - 1]
if (isObjectSource(this.sourceSchema) && lastDataPart === 'create') {
// If we have an object source and are creating, the dataPath needs to
// be shortened by the 'create' entry. This isn't needed for list
// sources, as there the parameter is actually mapped to the item id.
dataParts.length--
}
for (let i = 0, l = dataParts.length; i < l && data; i++) {
const dataPart = dataParts[i]
// If this is an :id part, find the index of the item with given id.
const key = /^:id/.test(routeParts[i])
? dataPart === 'create'
? null // There's no index for entries about to be created
: this.findItemIdIndex(this.sourceSchema, data, dataPart)
: dataPart
// Skip the final lookup but remember `sourceKey`, as we want the
// parent data so we can replace the entry at `sourceKey` on it.
if (i === l - 1) {
this.sourceKey = key
} else {
data = data[key]
}
}
}
return data
},
inheritedData() {
// Data inherited from parent, and cloned to protect against reactive
// changes until changes are applied through setSourceData(), unless
// `sourceSchema.mutate` is true, in which case data is mutated directly.
if (
this.isTransient &&
this.clonedData === undefined &&
this.sourceData &&
this.sourceKey !== null
) {
let data = this.sourceData[this.sourceKey]
if (!this.doesMutate) {
// Use a trick to store cloned inherited data in clonedData, to make
// it reactive and prevent it from being cloned multiple times.
this.clonedData = data = clone(data)
}
if (
data === null &&
!this.isCreating &&
isObjectSource(this.sourceSchema)
) {
// If data of an object source is null, redirect to its create route.
this.$router.push({ path: 'create', append: true })
}
return data
}
return this.clonedData
},
// @override ResourceMixin.hasData()
hasData() {
return !!this.data
},
itemLabel() {
return this.getItemLabel(this.sourceSchema, this.data, { extended: true })
}
},
watch: {
sourceData: 'clearClonedData',
// Needed for the 'create' redirect in `inheritedData()` to work:
create: 'setupData'
},
mounted() {
// Errors can get passed on through the meta object, so add them now.
// See DitoSchema.showValidationErrors() / SourceMixin.navigateToComponent()
const { errors } = this.meta
if (errors) {
delete this.meta.errors
this.showValidationErrors(errors, true)
}
},
methods: {
getDataPathFrom(route) {
// Get the data path by denormalizePath the relative route path
return this.api.denormalizePath(this.path
// DitoViews have nested routes, so don't remove their path.
.substring((route.isView ? 0 : route.path.length) + 1))
},
// @override ResourceMixin.setupData()
setupData() {
if (this.isCreating) {
this.createdData = this.createdData ||
this.createData(this.schema, this.type)
} else {
this.ensureData()
}
},
setSourceData(data) {
if (this.sourceData && this.sourceKey !== null) {
const { mainSchemaComponent } = this
this.$set(
this.sourceData,
this.sourceKey,
mainSchemaComponent.filterData(data)
)
mainSchemaComponent.onChange()
return true
}
return false
},
addSourceData(data) {
return isObjectSource(this.sourceSchema)
? this.setSourceData(data)
: !!this.sourceData?.push(data)
},
// @override ResourceMixin.clearData()
clearData() {
this.setData(null, true)
},
// @override ResourceMixin.setData()
setData(data, clear = false) {
// setData() is called after submit when data has changed.
if (this.isTransient) {
// For components with transient data, modify this.sourceData.
this.setSourceData(data)
} else {
this.createdData = null
this.loadedData = data
}
if (!clear) {
this.mainSchemaComponent.onLoad()
}
},
clearClonedData(newValue, oldValue) {
// Only clear if the watched sourceData itself changes in the form.
if (newValue !== oldValue) {
this.clonedData = undefined
}
},
async cancel() {
return this.close()
},
async close() {
return this.navigate(this.parentRouteComponent.path)
},
async submit(button, { validate = true, closeForm = false } = {}) {
if (validate && !this.validateAll()) {
return false
}
const getVerb = present => {
const verb = this.isCreating
? present ? 'create' : 'created'
: present ? 'submit' : 'submitted'
return this.verbs[verb]
}
// Allow buttons to override both method and resource path to submit to:
const butttonResource = getResource(button.schema.resource, {
parent: this.resource
})
const resource = butttonResource || this.resource
const method = resource?.method || this.method
const data = this.getPayloadData(button, method)
let success
if (!butttonResource && this.isTransient) {
success = await this.submitTransient(button, resource, method, data, {
notifySuccess: () => {
const verb = getVerb(false)
this.notify(
'info',
this.isCreating
? `Item ${capitalize(verb)}`
: `Change ${capitalize(verb)}`,
this.isCreating
? `${this.itemLabel} was ${verb}.`
: `Changes to ${this.itemLabel} were ${verb}.`,
this.transientNote
)
},
notifyError: () => {
const verb = getVerb(true)
this.notify(
'error',
'Request Error',
`Unable to ${verb} ${this.itemLabel}.`
)
}
})
} else {
success = await this.submitResource(button, resource, method, data, {
setData: true,
notifySuccess: () => {
const verb = getVerb(false)
this.notify(
'success',
`Successfully ${capitalize(verb)}`,
`${this.itemLabel} was ${verb}.`
)
},
notifyError: error => {
const verb = getVerb(true)
this.notify(
'error',
'Request Error',
`Unable to ${verb} ${this.itemLabel}${error ? ':' : ''}`,
error?.message || error
)
}
})
}
if (success) {
this.resetValidation()
if (closeForm || button.closeForm) {
this.close()
} else if (this.isCreating) {
// Redirect to the form editing the newly created item:
const id = this.getItemId(this.schema, this.data)
this.$router.replace({ path: `../${id}`, append: true })
}
}
return success
},
async submitTransient(button, resource, method, data, {
notifyError,
notifySuccess
}) {
// Handle the default "submitting" of transient, nested data:
const success = this.isCreating
? this.addSourceData(data)
: this.setSourceData(data)
if (success) {
await this.emitButtonEvent(button, 'success', {
resource,
notify: notifySuccess
})
} else {
await this.emitButtonEvent(button, 'error', {
resource,
error: 'Could not submit transient item',
notify: notifyError
})
}
return success
}
}
})
</script>