@crombolo/schema 0.45.0 → 0.47.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.
@@ -0,0 +1,612 @@
1
+ /**
2
+ * Changes to a form (story 251): its settings, pages, fieldsets, fields and
3
+ * workflows, each a pure function from the form to the changed form, or the
4
+ * reason it cannot change. Whether the site takes it is the check's to say.
5
+ * A page or fieldset is named by its caption, or by its place, from 1.
6
+ */
7
+ import type {
8
+ FormCondition,
9
+ FormSettingValue,
10
+ FormWorkflowTrigger,
11
+ SchemaForm,
12
+ SchemaFormField,
13
+ SchemaFormGroup,
14
+ SchemaFormPage,
15
+ SchemaFormWorkflow,
16
+ } from '@crombolo/core'
17
+ import { allFormFields } from '@crombolo/core'
18
+
19
+ export type FormEditResult = { ok: true; form: SchemaForm } | { ok: false; reason: string }
20
+
21
+ const refuse = (reason: string): FormEditResult => ({ ok: false, reason })
22
+ const done = (form: SchemaForm): FormEditResult => ({ ok: true, form })
23
+
24
+ /** "Name", "Email address": a caption from an alias when none is given. */
25
+ const captionFor = (alias: string) =>
26
+ alias
27
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
28
+ .replace(/[-_]+/g, ' ')
29
+ .replace(/^./, (c) => c.toUpperCase())
30
+
31
+ export interface FormChanges {
32
+ name?: string
33
+ storeEntries?: boolean
34
+ requiresApproval?: boolean
35
+ stepPages?: boolean
36
+ submitLabel?: string
37
+ nextLabel?: string
38
+ previousLabel?: string
39
+ /** "" takes it away. */
40
+ messageOnSubmit?: string
41
+ /** A page's key, or null for none. */
42
+ redirectTo?: string | null
43
+ theme?: string
44
+ honeypot?: boolean
45
+ /** 0 takes it away. */
46
+ minimumSubmitSeconds?: number
47
+ /** 0 takes it away. */
48
+ maxEntries?: number
49
+ }
50
+
51
+ const text = (value: string | undefined) => (value ? value : undefined)
52
+ const positive = (value: number | undefined) => (value && value > 0 ? value : undefined)
53
+
54
+ /** The form's own settings: its name, what it keeps, its buttons and what follows sending. */
55
+ export function updateForm(form: SchemaForm, changes: FormChanges): FormEditResult {
56
+ const next: SchemaForm = { ...form }
57
+ if (changes.name !== undefined) next.name = changes.name
58
+ if (changes.storeEntries !== undefined) next.storeEntries = changes.storeEntries
59
+ if (changes.requiresApproval !== undefined) next.requiresApproval = changes.requiresApproval
60
+ if (changes.stepPages !== undefined) next.stepPages = changes.stepPages || undefined
61
+ if (changes.submitLabel !== undefined) next.submitLabel = text(changes.submitLabel)
62
+ if (changes.nextLabel !== undefined) next.nextLabel = text(changes.nextLabel)
63
+ if (changes.previousLabel !== undefined) next.previousLabel = text(changes.previousLabel)
64
+ if (changes.messageOnSubmit !== undefined) next.messageOnSubmit = text(changes.messageOnSubmit)
65
+ if (changes.redirectTo !== undefined) next.redirectTo = changes.redirectTo ?? undefined
66
+ if (changes.theme !== undefined) next.theme = text(changes.theme)
67
+ if (changes.honeypot !== undefined) next.honeypot = changes.honeypot
68
+ if (changes.minimumSubmitSeconds !== undefined)
69
+ next.minimumSubmitSeconds = positive(changes.minimumSubmitSeconds)
70
+ if (changes.maxEntries !== undefined) next.maxEntries = positive(changes.maxEntries)
71
+ return done(next)
72
+ }
73
+
74
+ /** A condition from `field=value` (is) and `field!=value` (is not) rules; null takes it away. */
75
+ export function formConditionFrom(
76
+ rules: readonly string[],
77
+ match: 'all' | 'any' = 'all',
78
+ ): FormCondition | string {
79
+ const parsed: FormCondition['rules'] = []
80
+ for (const rule of rules) {
81
+ const not = rule.indexOf('!=')
82
+ const eq = rule.indexOf('=')
83
+ if (eq < 1) return `"${rule}" is not a rule: write <field>=<value> or <field>!=<value>`
84
+ if (not > 0 && not < eq)
85
+ parsed.push({
86
+ field: rule.slice(0, not).trim(),
87
+ operator: 'isNot',
88
+ value: rule.slice(not + 2),
89
+ })
90
+ else parsed.push({ field: rule.slice(0, eq).trim(), operator: 'is', value: rule.slice(eq + 1) })
91
+ }
92
+ return { action: 'show', match, rules: parsed }
93
+ }
94
+
95
+ function findPage(form: SchemaForm, ref: string): number | string {
96
+ const n = Number(ref)
97
+ if (Number.isInteger(n) && String(n) === ref.trim()) {
98
+ if (n >= 1 && n <= form.pages.length) return n - 1
99
+ return `"${form.name}" has no page ${ref}: it has ${form.pages.length}`
100
+ }
101
+ const index = form.pages.findIndex((p) => (p.caption ?? '').toLowerCase() === ref.toLowerCase())
102
+ return index >= 0 ? index : `"${form.name}" has no page "${ref}"`
103
+ }
104
+
105
+ function findGroup(page: SchemaFormPage, ref: string, form: SchemaForm): number | string {
106
+ const n = Number(ref)
107
+ if (Number.isInteger(n) && String(n) === ref.trim()) {
108
+ if (n >= 1 && n <= page.groups.length) return n - 1
109
+ return `that page of "${form.name}" has no fieldset ${ref}: it has ${page.groups.length}`
110
+ }
111
+ const index = page.groups.findIndex((g) => (g.caption ?? '').toLowerCase() === ref.toLowerCase())
112
+ return index >= 0 ? index : `that page of "${form.name}" has no fieldset "${ref}"`
113
+ }
114
+
115
+ /** Where a field sits: its page, fieldset and place. */
116
+ function locate(form: SchemaForm, alias: string) {
117
+ for (const [p, page] of form.pages.entries())
118
+ for (const [g, group] of page.groups.entries()) {
119
+ const f = group.fields.findIndex((field) => field.alias.toLowerCase() === alias.toLowerCase())
120
+ if (f >= 0) return { p, g, f, field: group.fields[f] as SchemaFormField }
121
+ }
122
+ return undefined
123
+ }
124
+
125
+ const withGroups = (
126
+ form: SchemaForm,
127
+ change: (page: SchemaFormPage, p: number) => SchemaFormPage,
128
+ ): SchemaForm => ({ ...form, pages: form.pages.map(change) })
129
+
130
+ export interface FormFieldPlacement {
131
+ page?: string
132
+ group?: string
133
+ before?: string
134
+ after?: string
135
+ }
136
+
137
+ /** The page, fieldset and place a field goes to: the last fieldset of the last page unless said. */
138
+ function target(
139
+ form: SchemaForm,
140
+ at: FormFieldPlacement,
141
+ ): { p: number; g: number; i: number | undefined } | string {
142
+ const anchor = at.before ?? at.after
143
+ if (anchor) {
144
+ const found = locate(form, anchor)
145
+ if (!found) return `"${form.name}" has no field "${anchor}" to put it beside`
146
+ return { p: found.p, g: found.g, i: at.before ? found.f : found.f + 1 }
147
+ }
148
+ const p = at.page ? findPage(form, at.page) : form.pages.length - 1
149
+ if (typeof p === 'string') return p
150
+ const page = form.pages[p]
151
+ if (!page) return `"${form.name}" has no pages`
152
+ const g = at.group ? findGroup(page, at.group, form) : page.groups.length - 1
153
+ if (typeof g === 'string') return g
154
+ if (!page.groups[g]) return `that page of "${form.name}" has no fieldsets`
155
+ return { p, g, i: undefined }
156
+ }
157
+
158
+ function insert(
159
+ form: SchemaForm,
160
+ field: SchemaFormField,
161
+ at: { p: number; g: number; i: number | undefined },
162
+ ) {
163
+ return withGroups(form, (page, p) =>
164
+ p !== at.p
165
+ ? page
166
+ : {
167
+ ...page,
168
+ groups: page.groups.map((group, g) => {
169
+ if (g !== at.g) return group
170
+ const fields = [...group.fields]
171
+ fields.splice(at.i ?? fields.length, 0, field)
172
+ return { ...group, fields }
173
+ }),
174
+ },
175
+ )
176
+ }
177
+
178
+ const withoutField = (form: SchemaForm, alias: string): SchemaForm =>
179
+ withGroups(form, (page) => ({
180
+ ...page,
181
+ groups: page.groups.map((group) => ({
182
+ ...group,
183
+ fields: group.fields.filter((f) => f.alias.toLowerCase() !== alias.toLowerCase()),
184
+ })),
185
+ }))
186
+
187
+ export interface FormFieldChanges {
188
+ type?: string
189
+ caption?: string
190
+ helpText?: string
191
+ mandatory?: boolean
192
+ mandatoryMessage?: string
193
+ pattern?: string
194
+ patternMessage?: string
195
+ sensitive?: boolean
196
+ placeholder?: string
197
+ defaultValue?: string
198
+ /** A choice list, in order; replaces the one there. */
199
+ values?: string[]
200
+ /** A bundle field type's own settings, stored as given. */
201
+ settings?: Record<string, FormSettingValue>
202
+ /** Null takes its condition away. */
203
+ condition?: FormCondition | null
204
+ }
205
+
206
+ function applyField(field: SchemaFormField, changes: FormFieldChanges): SchemaFormField {
207
+ const next: SchemaFormField = { ...field }
208
+ if (changes.type !== undefined) next.type = changes.type
209
+ if (changes.caption !== undefined) next.caption = changes.caption
210
+ if (changes.helpText !== undefined) next.helpText = text(changes.helpText)
211
+ if (changes.mandatory !== undefined) next.mandatory = changes.mandatory
212
+ if (changes.mandatoryMessage !== undefined) next.mandatoryMessage = text(changes.mandatoryMessage)
213
+ if (changes.pattern !== undefined) next.pattern = text(changes.pattern)
214
+ if (changes.patternMessage !== undefined) next.patternMessage = text(changes.patternMessage)
215
+ if (changes.sensitive !== undefined) next.sensitive = changes.sensitive
216
+ if (changes.placeholder !== undefined) next.placeholder = text(changes.placeholder)
217
+ if (changes.defaultValue !== undefined) next.defaultValue = text(changes.defaultValue)
218
+ if (changes.values !== undefined) next.values = [...changes.values]
219
+ if (changes.settings !== undefined) next.settings = { ...field.settings, ...changes.settings }
220
+ if (changes.condition !== undefined) next.condition = changes.condition ?? undefined
221
+ return next
222
+ }
223
+
224
+ /** A field added: its alias new to the form, placed where `at` says. */
225
+ export function addFormField(
226
+ form: SchemaForm,
227
+ alias: string,
228
+ type: string,
229
+ changes: FormFieldChanges = {},
230
+ at: FormFieldPlacement = {},
231
+ ): FormEditResult {
232
+ if (locate(form, alias)) return refuse(`"${form.name}" already has a field "${alias}"`)
233
+ const place = target(form, at)
234
+ if (typeof place === 'string') return refuse(place)
235
+ const field = applyField(
236
+ {
237
+ alias,
238
+ type,
239
+ caption: captionFor(alias),
240
+ mandatory: false,
241
+ sensitive: false,
242
+ values: [],
243
+ accept: [],
244
+ },
245
+ changes,
246
+ )
247
+ return done(insert(form, field, place))
248
+ }
249
+
250
+ export function updateFormField(
251
+ form: SchemaForm,
252
+ alias: string,
253
+ changes: FormFieldChanges,
254
+ ): FormEditResult {
255
+ const found = locate(form, alias)
256
+ if (!found) return refuse(`"${form.name}" has no field "${alias}"`)
257
+ const next = applyField(found.field, changes)
258
+ return done(
259
+ withGroups(form, (page, p) => ({
260
+ ...page,
261
+ groups: page.groups.map((group, g) => ({
262
+ ...group,
263
+ fields: group.fields.map((f, i) =>
264
+ p === found.p && g === found.g && i === found.f ? next : f,
265
+ ),
266
+ })),
267
+ })),
268
+ )
269
+ }
270
+
271
+ export function moveFormField(
272
+ form: SchemaForm,
273
+ alias: string,
274
+ at: FormFieldPlacement,
275
+ ): FormEditResult {
276
+ const found = locate(form, alias)
277
+ if (!found) return refuse(`"${form.name}" has no field "${alias}"`)
278
+ if (!at.page && !at.group && !at.before && !at.after)
279
+ return refuse('say where: a page, a fieldset, or before or after another field')
280
+ if ((at.before ?? at.after)?.toLowerCase() === alias.toLowerCase())
281
+ return refuse('a field cannot go beside itself')
282
+ const without = withoutField(form, alias)
283
+ const place = target(without, at)
284
+ if (typeof place === 'string') return refuse(place)
285
+ return done(insert(without, found.field, place))
286
+ }
287
+
288
+ /** Fields whose conditions name `alias`, which removing it would leave pointing at nothing. */
289
+ const dependents = (form: SchemaForm, alias: string) =>
290
+ [
291
+ ...allFormFields(form)
292
+ .filter((f) => f.condition?.rules.some((r) => r.field === alias))
293
+ .map((f) => f.alias),
294
+ ...form.pages.flatMap((page, p) =>
295
+ [
296
+ page.condition?.rules.some((r) => r.field === alias) ? `page ${p + 1}` : '',
297
+ ...page.groups.map((g, i) =>
298
+ g.condition?.rules.some((r) => r.field === alias)
299
+ ? `fieldset ${i + 1} of page ${p + 1}`
300
+ : '',
301
+ ),
302
+ ].filter(Boolean),
303
+ ),
304
+ ] as string[]
305
+
306
+ export function removeFormField(form: SchemaForm, alias: string): FormEditResult {
307
+ const found = locate(form, alias)
308
+ if (!found) return refuse(`"${form.name}" has no field "${alias}"`)
309
+ const using = dependents(form, found.field.alias)
310
+ if (using.length > 0)
311
+ return refuse(
312
+ `what shows depends on "${found.field.alias}" in ${using.join(', ')}: change those conditions first`,
313
+ )
314
+ return done(withoutField(form, alias))
315
+ }
316
+
317
+ export interface FormPlacement {
318
+ before?: string
319
+ after?: string
320
+ }
321
+
322
+ const placeAt = <T>(list: readonly T[], item: T, index: number | undefined): T[] => {
323
+ const out = [...list]
324
+ out.splice(index ?? out.length, 0, item)
325
+ return out
326
+ }
327
+
328
+ export interface FormPageChanges {
329
+ caption?: string
330
+ condition?: FormCondition | null
331
+ }
332
+
333
+ /** A page added, with one empty fieldset, at the end or beside another page. */
334
+ export function addFormPage(
335
+ form: SchemaForm,
336
+ changes: FormPageChanges = {},
337
+ at: FormPlacement = {},
338
+ ): FormEditResult {
339
+ const anchor = at.before ?? at.after
340
+ let index: number | undefined
341
+ if (anchor) {
342
+ const found = findPage(form, anchor)
343
+ if (typeof found === 'string') return refuse(found)
344
+ index = at.before ? found : found + 1
345
+ }
346
+ const page: SchemaFormPage = {
347
+ ...(changes.caption ? { caption: changes.caption } : {}),
348
+ groups: [{ columns: 1, fields: [] }],
349
+ ...(changes.condition ? { condition: changes.condition } : {}),
350
+ }
351
+ return done({ ...form, pages: placeAt(form.pages, page, index) })
352
+ }
353
+
354
+ export function updateFormPage(
355
+ form: SchemaForm,
356
+ ref: string,
357
+ changes: FormPageChanges,
358
+ ): FormEditResult {
359
+ const p = findPage(form, ref)
360
+ if (typeof p === 'string') return refuse(p)
361
+ return done(
362
+ withGroups(form, (page, i) =>
363
+ i !== p
364
+ ? page
365
+ : {
366
+ ...page,
367
+ ...(changes.caption !== undefined ? { caption: text(changes.caption) } : {}),
368
+ ...(changes.condition !== undefined
369
+ ? { condition: changes.condition ?? undefined }
370
+ : {}),
371
+ },
372
+ ),
373
+ )
374
+ }
375
+
376
+ export function moveFormPage(form: SchemaForm, ref: string, at: FormPlacement): FormEditResult {
377
+ const p = findPage(form, ref)
378
+ if (typeof p === 'string') return refuse(p)
379
+ const anchor = at.before ?? at.after
380
+ if (!anchor) return refuse('say where: before or after another page')
381
+ const page = form.pages[p] as SchemaFormPage
382
+ const rest = form.pages.filter((_, i) => i !== p)
383
+ const others = { ...form, pages: rest }
384
+ const found = findPage(others, anchor)
385
+ if (typeof found === 'string') return refuse(found)
386
+ return done({ ...form, pages: placeAt(rest, page, at.before ? found : found + 1) })
387
+ }
388
+
389
+ const fieldsOf = (page: SchemaFormPage) => page.groups.flatMap((g) => g.fields)
390
+
391
+ /** A page removed; its fields moved to the last fieldset of another, or refused while it has any. */
392
+ export function removeFormPage(form: SchemaForm, ref: string, moveTo?: string): FormEditResult {
393
+ const p = findPage(form, ref)
394
+ if (typeof p === 'string') return refuse(p)
395
+ if (form.pages.length === 1) return refuse(`"${form.name}" has only this page`)
396
+ const page = form.pages[p] as SchemaFormPage
397
+ const held = fieldsOf(page)
398
+ if (held.length > 0 && !moveTo)
399
+ return refuse(
400
+ `that page holds ${held.length} field(s) (${held.map((f) => f.alias).join(', ')}); name a page to move them to, or move them first`,
401
+ )
402
+ const rest = { ...form, pages: form.pages.filter((_, i) => i !== p) }
403
+ if (!moveTo) return done(rest)
404
+ const named = findPage(form, moveTo)
405
+ if (typeof named === 'string') return refuse(named)
406
+ if (named === p) return refuse('a page cannot take its own fields')
407
+ const t = named > p ? named - 1 : named
408
+ return done(
409
+ withGroups(rest, (target, i) => {
410
+ if (i !== t) return target
411
+ const groups = [...target.groups]
412
+ const last = groups.length - 1
413
+ groups[last] = {
414
+ ...(groups[last] as SchemaFormGroup),
415
+ fields: [...(groups[last]?.fields ?? []), ...held],
416
+ }
417
+ return { ...target, groups }
418
+ }),
419
+ )
420
+ }
421
+
422
+ export interface FormGroupChanges {
423
+ caption?: string
424
+ columns?: number
425
+ condition?: FormCondition | null
426
+ }
427
+
428
+ export function addFormGroup(
429
+ form: SchemaForm,
430
+ pageRef: string,
431
+ changes: FormGroupChanges = {},
432
+ at: FormPlacement = {},
433
+ ): FormEditResult {
434
+ const p = findPage(form, pageRef)
435
+ if (typeof p === 'string') return refuse(p)
436
+ const page = form.pages[p] as SchemaFormPage
437
+ const anchor = at.before ?? at.after
438
+ let index: number | undefined
439
+ if (anchor) {
440
+ const found = findGroup(page, anchor, form)
441
+ if (typeof found === 'string') return refuse(found)
442
+ index = at.before ? found : found + 1
443
+ }
444
+ const group: SchemaFormGroup = {
445
+ ...(changes.caption ? { caption: changes.caption } : {}),
446
+ columns: changes.columns ?? 1,
447
+ fields: [],
448
+ ...(changes.condition ? { condition: changes.condition } : {}),
449
+ }
450
+ return done(
451
+ withGroups(form, (pg, i) =>
452
+ i !== p ? pg : { ...pg, groups: placeAt(pg.groups, group, index) },
453
+ ),
454
+ )
455
+ }
456
+
457
+ export function updateFormGroup(
458
+ form: SchemaForm,
459
+ pageRef: string,
460
+ ref: string,
461
+ changes: FormGroupChanges,
462
+ ): FormEditResult {
463
+ const p = findPage(form, pageRef)
464
+ if (typeof p === 'string') return refuse(p)
465
+ const g = findGroup(form.pages[p] as SchemaFormPage, ref, form)
466
+ if (typeof g === 'string') return refuse(g)
467
+ if (changes.columns !== undefined && changes.columns < 1)
468
+ return refuse('a fieldset has at least one column')
469
+ return done(
470
+ withGroups(form, (page, i) =>
471
+ i !== p
472
+ ? page
473
+ : {
474
+ ...page,
475
+ groups: page.groups.map((group, j) =>
476
+ j !== g
477
+ ? group
478
+ : {
479
+ ...group,
480
+ ...(changes.caption !== undefined ? { caption: text(changes.caption) } : {}),
481
+ ...(changes.columns !== undefined ? { columns: changes.columns } : {}),
482
+ ...(changes.condition !== undefined
483
+ ? { condition: changes.condition ?? undefined }
484
+ : {}),
485
+ },
486
+ ),
487
+ },
488
+ ),
489
+ )
490
+ }
491
+
492
+ export function moveFormGroup(
493
+ form: SchemaForm,
494
+ pageRef: string,
495
+ ref: string,
496
+ at: FormPlacement,
497
+ ): FormEditResult {
498
+ const p = findPage(form, pageRef)
499
+ if (typeof p === 'string') return refuse(p)
500
+ const page = form.pages[p] as SchemaFormPage
501
+ const g = findGroup(page, ref, form)
502
+ if (typeof g === 'string') return refuse(g)
503
+ const anchor = at.before ?? at.after
504
+ if (!anchor) return refuse('say where: before or after another fieldset')
505
+ const group = page.groups[g] as SchemaFormGroup
506
+ const rest = page.groups.filter((_, i) => i !== g)
507
+ const found = findGroup({ ...page, groups: rest }, anchor, form)
508
+ if (typeof found === 'string') return refuse(found)
509
+ return done(
510
+ withGroups(form, (pg, i) =>
511
+ i !== p ? pg : { ...pg, groups: placeAt(rest, group, at.before ? found : found + 1) },
512
+ ),
513
+ )
514
+ }
515
+
516
+ /** A fieldset removed; its fields moved to another on its page, or refused while it has any. */
517
+ export function removeFormGroup(
518
+ form: SchemaForm,
519
+ pageRef: string,
520
+ ref: string,
521
+ moveTo?: string,
522
+ ): FormEditResult {
523
+ const p = findPage(form, pageRef)
524
+ if (typeof p === 'string') return refuse(p)
525
+ const page = form.pages[p] as SchemaFormPage
526
+ const g = findGroup(page, ref, form)
527
+ if (typeof g === 'string') return refuse(g)
528
+ if (page.groups.length === 1) return refuse('that page has only this fieldset')
529
+ const held = (page.groups[g] as SchemaFormGroup).fields
530
+ if (held.length > 0 && !moveTo)
531
+ return refuse(
532
+ `that fieldset holds ${held.length} field(s) (${held.map((f) => f.alias).join(', ')}); name a fieldset to move them to, or move them first`,
533
+ )
534
+ const rest = page.groups.filter((_, i) => i !== g)
535
+ let groups = rest
536
+ if (moveTo) {
537
+ const named = findGroup(page, moveTo, form)
538
+ if (typeof named === 'string') return refuse(named)
539
+ if (named === g) return refuse('a fieldset cannot take its own fields')
540
+ const t = named > g ? named - 1 : named
541
+ groups = rest.map((group, i) =>
542
+ i === t ? { ...group, fields: [...group.fields, ...held] } : group,
543
+ )
544
+ }
545
+ return done(withGroups(form, (pg, i) => (i !== p ? pg : { ...pg, groups })))
546
+ }
547
+
548
+ export interface FormWorkflowChanges {
549
+ name?: string
550
+ on?: FormWorkflowTrigger
551
+ /** Merged over its settings, as given. */
552
+ settings?: Record<string, unknown>
553
+ unset?: readonly string[]
554
+ }
555
+
556
+ const formWorkflowNamed = (form: SchemaForm, name: string) =>
557
+ form.workflows.filter((w) => w.name.toLowerCase() === name.toLowerCase())
558
+
559
+ export function addFormWorkflow(
560
+ form: SchemaForm,
561
+ type: string,
562
+ name: string,
563
+ changes: Omit<FormWorkflowChanges, 'name' | 'unset'> = {},
564
+ ): FormEditResult {
565
+ if (formWorkflowNamed(form, name).length > 0)
566
+ return refuse(`"${form.name}" already has a workflow "${name}"`)
567
+ const workflow: SchemaFormWorkflow = {
568
+ type,
569
+ name,
570
+ on: changes.on ?? 'submit',
571
+ settings: { ...changes.settings },
572
+ }
573
+ return done({ ...form, workflows: [...form.workflows, workflow] })
574
+ }
575
+
576
+ export function updateFormWorkflow(
577
+ form: SchemaForm,
578
+ name: string,
579
+ changes: FormWorkflowChanges,
580
+ ): FormEditResult {
581
+ const found = formWorkflowNamed(form, name)
582
+ if (found.length === 0) return refuse(`"${form.name}" has no workflow "${name}"`)
583
+ if (found.length > 1)
584
+ return refuse(`"${form.name}" has ${found.length} workflows called "${name}"`)
585
+ const workflow = found[0] as SchemaFormWorkflow
586
+ if (
587
+ changes.name &&
588
+ changes.name.toLowerCase() !== name.toLowerCase() &&
589
+ formWorkflowNamed(form, changes.name).length > 0
590
+ )
591
+ return refuse(`"${form.name}" already has a workflow "${changes.name}"`)
592
+ const settings: Record<string, unknown> = { ...workflow.settings, ...changes.settings }
593
+ for (const key of changes.unset ?? []) {
594
+ if (!(key in settings)) return refuse(`the workflow "${workflow.name}" has no setting "${key}"`)
595
+ delete settings[key]
596
+ }
597
+ const next: SchemaFormWorkflow = {
598
+ ...workflow,
599
+ ...(changes.name ? { name: changes.name } : {}),
600
+ ...(changes.on ? { on: changes.on } : {}),
601
+ settings,
602
+ }
603
+ return done({ ...form, workflows: form.workflows.map((w) => (w === workflow ? next : w)) })
604
+ }
605
+
606
+ export function removeFormWorkflow(form: SchemaForm, name: string): FormEditResult {
607
+ const found = formWorkflowNamed(form, name)
608
+ if (found.length === 0) return refuse(`"${form.name}" has no workflow "${name}"`)
609
+ if (found.length > 1)
610
+ return refuse(`"${form.name}" has ${found.length} workflows called "${name}"`)
611
+ return done({ ...form, workflows: form.workflows.filter((w) => w !== found[0]) })
612
+ }
@@ -8,13 +8,8 @@
8
8
  */
9
9
  import { BUILT_IN_MEDIA_TYPES } from '@crombolo/data'
10
10
  import { storageTypeFor } from './builtin.ts'
11
- import {
12
- blockElements,
13
- contentTypeAliasOf,
14
- dataTypeOf,
15
- effectiveProperties,
16
- pascal,
17
- } from './generate.ts'
11
+ import { effectiveProperties } from './compositions.ts'
12
+ import { blockElements, contentTypeAliasOf, dataTypeOf, pascal } from './generate.ts'
18
13
  import type { SchemaContentType, SchemaSet } from './model.ts'
19
14
 
20
15
  export interface DeliveryTypesOptions {
package/src/generate.ts CHANGED
@@ -1,17 +1,7 @@
1
- /**
2
- * `crombolo generate`: TypeScript for the content types in a schema set, so a
3
- * view can name a property and have the compiler check it. Umbraco's
4
- * ModelsBuilder, minus the DLL.
5
- */
6
- import { BUILT_IN_MEDIA_TYPES, SYSTEM_CONTENT_TYPES } from '@crombolo/data'
7
- import {
8
- BUILTIN_DATA_TYPES,
9
- builtInContentTypeSchema,
10
- builtInMediaTypeSchema,
11
- storageTypeFor,
12
- } from './builtin.ts'
1
+ import { BUILTIN_DATA_TYPES, storageTypeFor } from './builtin.ts'
2
+ import { effectiveProperties } from './compositions.ts'
13
3
  import { typeKeyFor } from './keys.ts'
14
- import { allProperties, type SchemaBlock, type SchemaContentType, type SchemaSet } from './model.ts'
4
+ import type { SchemaBlock, SchemaSet } from './model.ts'
15
5
 
16
6
  export function pascal(alias: string): string {
17
7
  const cleaned = alias.replace(/[^A-Za-z0-9]+(.)?/g, (_, next: string | undefined) =>
@@ -123,11 +113,11 @@ function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
123
113
  return 'string'
124
114
  case 'Umbraco.BlockList': {
125
115
  const { content, settings } = blockElements(set, config, blocks)
126
- return `Array<BlockItem & { content: ${elementUnion(content)}; settings: ${settings.length ? `${elementUnion(settings)} | null` : 'PublishedElement | null'} }>`
116
+ return `BlockListValue<BlockItem & { content: ${elementUnion(content)}; settings: ${settings.length ? `${elementUnion(settings)} | null` : 'PublishedElement | null'} }>`
127
117
  }
128
118
  case 'Umbraco.BlockGrid': {
129
119
  const { content } = blockElements(set, config, blocks)
130
- return `Array<BlockGridItem & { content: ${elementUnion(content)} }>`
120
+ return `BlockListValue<BlockGridItem & { content: ${elementUnion(content)} }>`
131
121
  }
132
122
  }
133
123
  switch (storageTypeFor(editor)) {
@@ -142,29 +132,6 @@ function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
142
132
  }
143
133
  }
144
134
 
145
- /** Every property a type carries, including those from its compositions. */
146
- export function effectiveProperties(
147
- set: SchemaSet,
148
- type: SchemaContentType,
149
- seen = new Set<string>(),
150
- ) {
151
- if (seen.has(type.alias)) return []
152
- seen.add(type.alias)
153
- const out = [...allProperties(type)]
154
- for (const alias of type.compositions) {
155
- // A built-in type such as `seoFields` has no file until a site extends it.
156
- const shipped = SYSTEM_CONTENT_TYPES.find((t) => t.alias === alias)
157
- const shippedMedia = BUILT_IN_MEDIA_TYPES.find((t) => t.alias === alias)
158
- const composed =
159
- set.contentTypes.find((t) => t.alias === alias) ??
160
- set.mediaTypes?.find((t) => t.alias === alias) ??
161
- (shipped ? builtInContentTypeSchema(shipped) : undefined) ??
162
- (shippedMedia ? builtInMediaTypeSchema(shippedMedia) : undefined)
163
- if (composed) out.push(...effectiveProperties(set, composed, seen))
164
- }
165
- return out
166
- }
167
-
168
135
  export function generateTypes(set: SchemaSet): string {
169
136
  const out: string[] = [
170
137
  '// Generated by `crombolo generate` from schema/*.toml. Do not edit.',
@@ -192,6 +159,7 @@ export function generateTypes(set: SchemaSet): string {
192
159
  const used = [
193
160
  'BlockGridItem',
194
161
  'BlockItem',
162
+ 'BlockListValue',
195
163
  'Link',
196
164
  'MediaWithCrops',
197
165
  'PublishedContent',