@xeplr/ui-factory 1.0.6 → 1.0.8

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.
@@ -1,7 +1,8 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
2
  import { CONTROLS, controlGroups } from './controls.js'
3
3
  import {
4
- createScreen, renameScreen, setScreenProperty, addControl as addControlTo, moveNode, setNodeProperty,
4
+ createScreen, renameScreen, setScreenProperty, addControl as addControlTo, moveNode, setNodeProperty, setNodeStep,
5
+ steppers, stepsOf, stepOf, nodesForSteps,
5
6
  removeNodes
6
7
  } from './document.js'
7
8
  import { validateDocument } from './validateDocument.js'
@@ -98,17 +99,42 @@ export function useFactoryBuilder({ document: given, name, onSave, onChange, onP
98
99
  /** A screen property by path — `source`, `width`, `style.fontSize`. */
99
100
  const setScreen = useCallback((path, value) => update((d) => setScreenProperty(d, path, value)), [update])
100
101
 
102
+ // ── steps ─────────────────────────────────────────────────────────────
103
+ // Which step of each stepper is open on the canvas. Everything dropped while
104
+ // a step is open belongs to that step, and the canvas shows only that step —
105
+ // so one screen holds as many little screens as it has steps.
106
+ const [openSteps, setOpenSteps] = useState({})
107
+ const stepperNodes = useMemo(() => steppers(doc, controls), [doc, controls])
108
+ const [building, setBuilding] = useState(null) // the stepper being built
109
+ const activeStepper = stepperNodes.find((n) => n.id === building) || stepperNodes[stepperNodes.length - 1] || null
110
+ const stepAt = useCallback((id) => (Number.isInteger(openSteps[id]) ? openSteps[id] : 0), [openSteps])
111
+
112
+ const goToStep = useCallback((id, index) => {
113
+ setBuilding(id)
114
+ setOpenSteps((o) => ({ ...o, [id]: index }))
115
+ }, [])
116
+
117
+ /** The step a new control lands on: the one open on the stepper being built. */
118
+ const dropStep = useCallback(() => (
119
+ activeStepper ? { of: activeStepper.id, index: stepAt(activeStepper.id) } : null
120
+ ), [activeStepper, stepAt])
121
+
122
+ /** Moves a control to a step, or to none — shown whatever step is open. */
123
+ const setStep = useCallback((id, step) => update((d) => setNodeStep(d, id, step)), [update])
124
+
125
+ const visibleNodes = useMemo(() => nodesForSteps(doc, openSteps, controls), [doc, openSteps, controls])
126
+
101
127
  /** Adds a control and selects it, so its properties are open straight away. */
102
128
  const addControl = useCallback((type, at) => {
103
129
  let added = null
104
130
  update((d) => {
105
- const r = addControlTo(d, type, { at }, controls)
131
+ const r = addControlTo(d, type, { at, step: dropStep() }, controls)
106
132
  added = r.node
107
133
  return r.document
108
134
  })
109
135
  if (added) setSelected(new Set([added.id]))
110
136
  return added
111
- }, [update, controls])
137
+ }, [update, controls, dropStep])
112
138
 
113
139
  const moveControl = useCallback((id, patch) => update((d) => moveNode(d, id, patch)), [update])
114
140
 
@@ -271,6 +297,17 @@ export function useFactoryBuilder({ document: given, name, onSave, onChange, onP
271
297
  setScreen,
272
298
  addControl,
273
299
  moveControl,
300
+ steps: {
301
+ nodes: stepperNodes,
302
+ building: activeStepper ? activeStepper.id : null,
303
+ active: stepAt,
304
+ count: (id) => stepsOf(stepperNodes.find((n) => n.id === id)).length,
305
+ labels: (id) => stepsOf(stepperNodes.find((n) => n.id === id)),
306
+ go: goToStep,
307
+ of: stepOf,
308
+ set: setStep
309
+ },
310
+ visibleNodes,
274
311
  setProperty,
275
312
  removeSelected,
276
313
  duplicateSelected,
@@ -1,6 +1,6 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
- import { CONTROLS } from './controls.js'
3
- import { inputNodes } from './document.js'
2
+ import { CONTROLS, CHOICE_TYPES } from './controls.js'
3
+ import { inputNodes, nodesForSteps, steppers, stepsOf, stepOf } from './document.js'
4
4
  import { validateDocument } from './validateDocument.js'
5
5
  import { initialValues, parseInput, saveState, fieldError, optionValue, recordValues, listSource } from './values.js'
6
6
  import { hookMethod } from './hooks.js'
@@ -19,6 +19,7 @@ import { hookMethod } from './hooks.js'
19
19
  // fetchRecords({ source, screen, node }) → rows, for a list
20
20
  // onDelete({ id, source, screen, record })
21
21
  // fetchOptions({ table, node }) → [{ id, name }], for a table dropdown
22
+ // uploadFile(file, { screen, field, node }) → { path } — a file field's upload
22
23
  //
23
24
  // ── LIST → EDIT IN A POPUP ───────────────────────────────────────────────
24
25
  // A list whose `editScreen` names another screen opens that screen in a popup
@@ -34,6 +35,8 @@ export const AUTOSAVE_DELAY = 700
34
35
  * @param recordKey the id field on a record (default 'id')
35
36
  * @param onSave async (values, { id, source, document }) → saved record | void
36
37
  * @param fetchOptions async ({ table, node }) → [{ id, name }]
38
+ * @param uploadFile async (file, { screen, field, node }) → { path } — what a file field saves
39
+ * @param fileUrl (path) → the address an attached file is read back from
37
40
  * @param fetchRecords async ({ source, node }) → records, for lists
38
41
  * @param onDelete async ({ id, source, record }) → void
39
42
  * @param onChange (values) → void — every change, before any save
@@ -45,7 +48,7 @@ export const AUTOSAVE_DELAY = 700
45
48
  * @param hooks a FactoryHooks (or an object with some of its methods) — get / save / delete / actions
46
49
  */
47
50
  export function useFactoryScreen({
48
- document: doc, record, recordKey = 'id', onSave, fetchOptions, fetchRecords, fetchRecord, onDelete, onChange, screens, loadScreen, hooks,
51
+ document: doc, record, recordKey = 'id', onSave, fetchOptions, fetchRecords, fetchRecord, onDelete, onChange, screens, loadScreen, hooks, uploadFile, fileUrl,
49
52
  autosaveDelay = AUTOSAVE_DELAY, controls = CONTROLS
50
53
  } = {}) {
51
54
  const check = useMemo(() => validateDocument(doc, controls), [doc, controls])
@@ -116,7 +119,7 @@ export function useFactoryScreen({
116
119
  const fetchOptionsRef = useRef(fetchOptions); fetchOptionsRef.current = fetchOptions
117
120
  useEffect(() => {
118
121
  let cancelled = false
119
- const tableNodes = optionNodes.filter((n) => n.type === 'dropdown' && n.props.data?.source === 'table')
122
+ const tableNodes = optionNodes.filter((n) => CHOICE_TYPES.includes(n.type) && n.props.data?.source === 'table')
120
123
  if (!tableNodes.length) { setOptions({}); return undefined }
121
124
  setOptions(Object.fromEntries(tableNodes.map((n) => [n.id, { loading: true, items: [], error: null }])))
122
125
  const byTable = new Map()
@@ -141,6 +144,54 @@ export function useFactoryScreen({
141
144
  return () => { cancelled = true }
142
145
  }, [optionNodes])
143
146
 
147
+ // ── steps ─────────────────────────────────────────────────────────────
148
+ // A stepper shows one step at a time. Which step each is open at lives here;
149
+ // the fields of the steps not showing are still filled in, still checked and
150
+ // still saved — a step is what the person sees, not a separate form.
151
+ const [openSteps, setOpenSteps] = useState({})
152
+ const stepperNodes = useMemo(() => (check.ok ? steppers(doc, controls) : []), [check.ok, doc, controls])
153
+ const visibleNodes = useMemo(() => (check.ok ? nodesForSteps(doc, openSteps, controls) : []), [check.ok, doc, openSteps, controls])
154
+
155
+ // A screen whose steps changed under it (a field moved to another step, a
156
+ // step removed) must not stay open at a step that is gone.
157
+ useEffect(() => {
158
+ setOpenSteps((open) => {
159
+ let changed = false
160
+ const next = {}
161
+ stepperNodes.forEach((n) => {
162
+ const count = stepsOf(n).length
163
+ const at = Number.isInteger(open[n.id]) ? open[n.id] : 0
164
+ next[n.id] = Math.min(Math.max(at, 0), Math.max(count - 1, 0))
165
+ if (next[n.id] !== open[n.id]) changed = true
166
+ })
167
+ return changed || Object.keys(next).length !== Object.keys(open).length ? next : open
168
+ })
169
+ }, [stepperNodes])
170
+
171
+ const stepControl = useMemo(() => {
172
+ const at = (id) => (Number.isInteger(openSteps[id]) ? openSteps[id] : 0)
173
+ return {
174
+ nodes: stepperNodes,
175
+ active: at,
176
+ count: (id) => stepsOf(stepperNodes.find((n) => n.id === id)).length,
177
+ go: (id, index) => setOpenSteps((o) => ({ ...o, [id]: index })),
178
+ /** The fields on this step, so Next can hold at a step that is not filled in. */
179
+ fieldsOn: (id, index) => inputNodes(doc, controls).filter((n) => {
180
+ const step = stepOf(n)
181
+ return step && step.of === id && step.index === index
182
+ })
183
+ }
184
+ }, [stepperNodes, openSteps, doc, controls])
185
+
186
+ // ── a file field's upload ─────────────────────────────────────────────
187
+ const uploadRef = useRef(uploadFile); uploadRef.current = uploadFile
188
+ const upload = useCallback(async (file, node) => {
189
+ if (!uploadRef.current) throw new Error('No uploadFile was provided, so a file cannot be attached')
190
+ const out = await uploadRef.current(file, { screen: doc.id, field: node.props.name, node })
191
+ if (!out || !out.path) throw new Error('The upload did not answer with the stored file')
192
+ return out
193
+ }, [doc.id])
194
+
144
195
  const optionsFor = useCallback((node) => {
145
196
  if (node.props.data?.source === 'static') return { loading: false, items: node.props.data.options, error: null }
146
197
  return options[node.id] || { loading: false, items: [], error: null }
@@ -229,7 +280,8 @@ export function useFactoryScreen({
229
280
  const onChangeRef = useRef(onChange); onChangeRef.current = onChange
230
281
  const setValue = useCallback((node, raw) => {
231
282
  let value = parseInput(node, raw)
232
- if (node.type === 'dropdown' && value !== undefined) value = optionValue(optionsFor(node).items, value)
283
+ if ((node.type === 'dropdown' || node.type === 'radio') && value !== undefined) value = optionValue(optionsFor(node).items, value)
284
+ if (node.type === 'multiselect' && Array.isArray(value)) value = value.map((v) => optionValue(optionsFor(node).items, v))
233
285
  const name = node.props.name
234
286
  const next = { ...live.current.values }
235
287
  if (value === undefined) delete next[name]
@@ -412,6 +464,10 @@ export function useFactoryScreen({
412
464
  setValue,
413
465
  touch,
414
466
  optionsFor,
467
+ steps: stepControl,
468
+ visibleNodes,
469
+ upload,
470
+ fileUrl,
415
471
  flush,
416
472
  saveNow: runSave,
417
473
  openRecord,
@@ -10,7 +10,7 @@
10
10
  // Loud by design: a screen that half-renders — a dropdown with no options, two
11
11
  // fields writing the same key — looks like a data problem to whoever uses it.
12
12
 
13
- import { CONTROLS, LABEL_VARIANTS, LIST_ACTIONS, STYLE_KEYS, SCREEN_STYLE_KEYS } from './controls.js'
13
+ import { CONTROLS, LABEL_VARIANTS, LIST_ACTIONS, STYLE_KEYS, SCREEN_STYLE_KEYS, LAYOUTS, MULTI_SEPARATOR, MAX_FILE_MB, STEP_LIMIT, acceptList } from './controls.js'
14
14
  import { DOCUMENT_KIND, DOCUMENT_VERSION } from './document.js'
15
15
  import { RESERVED_COLUMNS, MAX_IDENTIFIER } from './tableSchema.js'
16
16
 
@@ -93,7 +93,15 @@ export function validateDocument(doc, controls = CONTROLS) {
93
93
  }
94
94
 
95
95
  checkStyle(props.style, def.styles || [], `${at}.props.style`, err, `"${node.type}"`)
96
- if (node.type === 'dropdown') checkDataSource(props.data, `${at}.props.data`, err)
96
+ if (node.type === 'dropdown' || node.type === 'radio' || node.type === 'multiselect') {
97
+ checkDataSource(props.data, `${at}.props.data`, err, node.type === 'multiselect')
98
+ }
99
+ if (node.type === 'radio' || node.type === 'multiselect') {
100
+ if (props.layout !== undefined && !LAYOUTS.includes(props.layout)) err(`${at}.props.layout`, `must be one of: ${LAYOUTS.join(', ')}`)
101
+ }
102
+ if (node.type === 'file') checkFile(props, at, err)
103
+ if (node.type === 'stepper') checkSteps(props, at, err)
104
+ checkStep(node, doc, at, err)
97
105
  if (node.type === 'list') checkList(props, doc, at, err)
98
106
  if (node.type === 'label') {
99
107
  if (typeof props.text !== 'string') err(`${at}.props.text`, 'must be a string')
@@ -130,16 +138,86 @@ function checkGeometry(node, at, err) {
130
138
  function checkDefault(node, def, at, err) {
131
139
  const v = node.props.default
132
140
  if (v === undefined) return
141
+ const isDatetime = node.type === 'datetime'
133
142
  const ok = {
134
143
  string: () => typeof v === 'string',
135
144
  number: () => typeof v === 'number' && Number.isFinite(v),
136
145
  boolean: () => typeof v === 'boolean',
137
- date: () => typeof v === 'string' && ISO_DATE.test(v)
146
+ array: () => Array.isArray(v),
147
+ date: () => typeof v === 'string' && (isDatetime ? ISO_DATETIME.test(v) : ISO_DATE.test(v))
138
148
  }[def.valueType]
139
- if (ok && !ok()) err(`${at}.props.default`, `must be a ${def.valueType === 'date' ? 'date as "YYYY-MM-DD"' : def.valueType}`)
149
+ if (ok && !ok()) err(`${at}.props.default`, `must be ${dateWord(def.valueType, isDatetime)}`)
150
+ }
151
+
152
+ function dateWord(valueType, isDatetime) {
153
+ if (valueType === 'date') return isDatetime ? 'a date and time as "YYYY-MM-DDTHH:MM"' : 'a date as "YYYY-MM-DD"'
154
+ if (valueType === 'array') return 'an array'
155
+ return `a ${valueType}`
140
156
  }
141
157
 
142
158
  const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
159
+ const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/
160
+
161
+ /**
162
+ * A stepper's steps: at least two, each with a key of its own, so a control can
163
+ * be tied to one and stay tied to it when the others are renamed.
164
+ */
165
+ function checkSteps(props, at, err) {
166
+ const steps = props.steps
167
+ if (!Array.isArray(steps)) { err(`${at}.props.steps`, 'must be an array of { key, label }'); return }
168
+ if (steps.length < 2) err(`${at}.props.steps`, 'needs at least two steps — one step is not a journey')
169
+ if (steps.length > STEP_LIMIT) err(`${at}.props.steps`, `has ${steps.length} steps — at most ${STEP_LIMIT}`)
170
+ const seen = new Set()
171
+ steps.forEach((s, j) => {
172
+ const p = `${at}.props.steps[${j}]`
173
+ if (!s || typeof s !== 'object') { err(p, 'must be { key, label }'); return }
174
+ if (!nonEmptyString(s.key)) err(`${p}.key`, 'must be a non-empty string — what the controls on this step point at')
175
+ else if (seen.has(s.key)) err(`${p}.key`, `"${s.key}" appears twice`)
176
+ else seen.add(s.key)
177
+ if (!nonEmptyString(s.label)) err(`${p}.label`, 'must be a non-empty string — what the person reads')
178
+ const extra = Object.keys(s).filter((k) => k !== 'key' && k !== 'label')
179
+ if (extra.length) err(p, `only "key" and "label" are used — remove: ${extra.join(', ')}`)
180
+ })
181
+ if (props.showNumbers !== undefined && typeof props.showNumbers !== 'boolean') err(`${at}.props.showNumbers`, 'must be true or false')
182
+ }
183
+
184
+ /** A node's `step`: a stepper that exists, and one of its steps. */
185
+ function checkStep(node, doc, at, err) {
186
+ if (node.step === undefined) return
187
+ const step = node.step
188
+ if (!step || typeof step !== 'object' || Array.isArray(step)) { err(`${at}.step`, 'must be { of, index } — the stepper, and which step'); return }
189
+ const extra = Object.keys(step).filter((k) => k !== 'of' && k !== 'index')
190
+ if (extra.length) err(`${at}.step`, `only "of" and "index" are used — remove: ${extra.join(', ')}`)
191
+ if (!nonEmptyString(step.of)) { err(`${at}.step.of`, 'must be the id of a stepper on this screen'); return }
192
+ if (step.of === node.id) { err(`${at}.step.of`, 'a stepper cannot be a step of itself'); return }
193
+ const owner = (doc.nodes || []).find((n) => n && n.id === step.of)
194
+ if (!owner || owner.type !== 'stepper') { err(`${at}.step.of`, `"${step.of}" is not a stepper on this screen`); return }
195
+ const count = Array.isArray(owner.props?.steps) ? owner.props.steps.length : 0
196
+ if (!Number.isInteger(step.index) || step.index < 0 || step.index >= count) {
197
+ err(`${at}.step.index`, `must be a step of "${step.of}" — it has ${count}`)
198
+ }
199
+ }
200
+
201
+ /** A file field: which extensions it takes, and how big a file may be. */
202
+ function checkFile(props, at, err) {
203
+ if (props.accept !== undefined) {
204
+ if (typeof props.accept !== 'string') err(`${at}.props.accept`, 'must be a string of extensions, e.g. ".pdf,.docx"')
205
+ else {
206
+ const list = acceptList(props.accept)
207
+ if (!list.length) err(`${at}.props.accept`, 'names no extension — ".pdf,.docx", or leave it out for any file')
208
+ list.forEach((x) => {
209
+ if (!EXTENSION.test(x)) err(`${at}.props.accept`, `"${x}" is not an extension — letters and digits after a dot, e.g. ".xlsx"`)
210
+ })
211
+ }
212
+ }
213
+ if (props.maxSize !== undefined) {
214
+ if (!(Number.isFinite(props.maxSize) && props.maxSize > 0 && props.maxSize <= MAX_FILE_MB)) {
215
+ err(`${at}.props.maxSize`, `must be a number of megabytes from 1 to ${MAX_FILE_MB}`)
216
+ }
217
+ }
218
+ }
219
+
220
+ const EXTENSION = /^\.[a-z0-9]{1,12}$/
143
221
 
144
222
  function checkValidation(node, def, at, err) {
145
223
  const v = node.props.validation
@@ -161,14 +239,18 @@ function checkValidation(node, def, at, err) {
161
239
  } else if (key === 'pattern') {
162
240
  try { new RegExp(val) } catch (_) { err(path, `"${val}" is not a valid regular expression`) }
163
241
  if (typeof val !== 'string') err(path, 'must be a string')
242
+ } else if (key === 'minItems' || key === 'maxItems') {
243
+ if (!(Number.isInteger(val) && val >= 0)) err(path, 'must be a whole number, 0 or more')
164
244
  } else if (key === 'patternMessage') {
165
245
  if (typeof val !== 'string') err(path, 'must be a string')
166
246
  } else if (def.valueType === 'number') {
167
247
  if (!(typeof val === 'number' && Number.isFinite(val))) err(path, 'must be a number')
168
248
  } else if (def.valueType === 'date') {
169
- if (!(typeof val === 'string' && ISO_DATE.test(val))) err(path, 'must be a date as "YYYY-MM-DD"')
249
+ const re = node.type === 'datetime' ? ISO_DATETIME : ISO_DATE
250
+ if (!(typeof val === 'string' && re.test(val))) err(path, `must be ${dateWord('date', node.type === 'datetime')}`)
170
251
  }
171
252
  })
253
+ if (v.minItems != null && v.maxItems != null && v.minItems > v.maxItems) err(`${at}.props.validation`, 'minItems is greater than maxItems — nothing could pass')
172
254
  if (v.minLength != null && v.maxLength != null && v.minLength > v.maxLength) err(`${at}.props.validation`, 'minLength is greater than maxLength — nothing could pass')
173
255
  if (typeof v.min === 'number' && typeof v.max === 'number' && v.min > v.max) err(`${at}.props.validation`, 'min is greater than max — nothing could pass')
174
256
  if (typeof v.min === 'string' && typeof v.max === 'string' && v.min > v.max) err(`${at}.props.validation`, 'min is after max — no date could pass')
@@ -178,7 +260,7 @@ function checkValidation(node, def, at, err) {
178
260
  * A dropdown's options: typed in, or read from a table. Either way each option
179
261
  * is { id, name } — the id is what is saved, the name is what is shown.
180
262
  */
181
- function checkDataSource(data, at, err) {
263
+ function checkDataSource(data, at, err, multi) {
182
264
  if (!data || typeof data !== 'object') {
183
265
  err(at, 'is required — { "source": "static", "options": [{ "id", "name" }] } or { "source": "table", "table": "<name>" }')
184
266
  return
@@ -190,6 +272,7 @@ function checkDataSource(data, at, err) {
190
272
  const p = `${at}.options[${j}]`
191
273
  if (!o || typeof o !== 'object') { err(p, 'must be { id, name }'); return }
192
274
  if (!(typeof o.id === 'string' || typeof o.id === 'number') || o.id === '') err(`${p}.id`, 'must be a non-empty string or a number')
275
+ else if (multi && String(o.id).includes(MULTI_SEPARATOR)) err(`${p}.id`, `"${o.id}" contains "${MULTI_SEPARATOR}" — several choices are stored in one column, separated by it`)
193
276
  else if (seen.has(o.id)) err(`${p}.id`, `"${o.id}" appears twice`)
194
277
  else seen.add(o.id)
195
278
  if (!nonEmptyString(o.name)) err(`${p}.name`, 'must be a non-empty string — what the user sees')
package/src/values.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // them. validateValues() below applies the same rules in the browser, with
12
12
  // messages written for the person filling the form in rather than for a log.
13
13
 
14
- import { CONTROLS } from './controls.js'
14
+ import { CONTROLS, MULTI_SEPARATOR } from './controls.js'
15
15
  import { inputNodes } from './document.js'
16
16
 
17
17
  /** schema-handler field schema for the screen's inputs, in reading order. */
@@ -24,7 +24,9 @@ export function formSchema(doc, controls = CONTROLS) {
24
24
  if (p.label) field.description = p.label
25
25
  if (p.required) field.required = true
26
26
  if (p.default !== undefined) field.default = p.default
27
- if (node.type === 'dropdown' && p.data?.source === 'static') {
27
+ // A multi-select's value is an array, so schema-handler's `options` (which
28
+ // compares one value) cannot check it — chooseable(node) does, on both sides.
29
+ if ((node.type === 'dropdown' || node.type === 'radio') && p.data?.source === 'static') {
28
30
  field.options = p.data.options.map((o) => o.id)
29
31
  }
30
32
  const v = p.validation && { ...p.validation }
@@ -44,6 +46,7 @@ export function initialValues(doc, provided = {}, controls = CONTROLS) {
44
46
  if (provided[name] !== undefined) out[name] = provided[name]
45
47
  else if (node.props.default !== undefined) out[name] = node.props.default
46
48
  else if (node.type === 'checkbox') out[name] = false
49
+ else if (node.type === 'multiselect') out[name] = []
47
50
  })
48
51
  return out
49
52
  }
@@ -55,12 +58,13 @@ export function initialValues(doc, provided = {}, controls = CONTROLS) {
55
58
  */
56
59
  export function parseInput(node, raw) {
57
60
  if (node.type === 'checkbox') return Boolean(raw)
61
+ if (node.type === 'multiselect') return Array.isArray(raw) ? raw : fromDbValue(node, raw) || []
58
62
  if (raw === undefined || raw === null || raw === '') return undefined
59
63
  if (node.type === 'number') {
60
64
  const n = typeof raw === 'number' ? raw : Number(String(raw).trim())
61
65
  return Number.isFinite(n) ? n : raw // left as typed; validation says why
62
66
  }
63
- if (node.type === 'dropdown') return raw
67
+ if (node.type === 'dropdown' || node.type === 'radio') return raw
64
68
  return String(raw)
65
69
  }
66
70
 
@@ -90,6 +94,15 @@ export function fieldError(node, value, loadedOptions) {
90
94
  if (node.type === 'checkbox') {
91
95
  return p.required && value !== true ? `${label} must be ticked` : null
92
96
  }
97
+ if (node.type === 'multiselect') {
98
+ const chosen = Array.isArray(value) ? value : []
99
+ if (!chosen.length) return p.required ? `${label} is required` : null
100
+ if (v.minItems != null && chosen.length < v.minItems) return `${label}: choose at least ${v.minItems}`
101
+ if (v.maxItems != null && chosen.length > v.maxItems) return `${label}: choose at most ${v.maxItems}`
102
+ const allowed = chooseable(node, loadedOptions)
103
+ if (allowed && chosen.some((c) => !allowed.some((o) => sameId(o.id, c)))) return `${label} has a choice that is no longer offered`
104
+ return null
105
+ }
93
106
  if (value === undefined || value === null || value === '') {
94
107
  return p.required ? `${label} is required` : null
95
108
  }
@@ -119,8 +132,18 @@ export function fieldError(node, value, loadedOptions) {
119
132
  if (v.max && day > v.max) return `${label} must be on or before ${v.max}`
120
133
  return null
121
134
  }
122
- case 'dropdown': {
123
- const opts = p.data?.source === 'static' ? p.data.options : loadedOptions
135
+ case 'datetime': {
136
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) return `${label} must be a date and time`
137
+ // ISO strings compare correctly as text, and comparing text keeps a
138
+ // timezone from shifting the moment that was typed in.
139
+ const at = value.slice(0, 16)
140
+ if (v.min && at < v.min.slice(0, 16)) return `${label} must be at or after ${v.min.replace('T', ' ')}`
141
+ if (v.max && at > v.max.slice(0, 16)) return `${label} must be at or before ${v.max.replace('T', ' ')}`
142
+ return null
143
+ }
144
+ case 'dropdown':
145
+ case 'radio': {
146
+ const opts = chooseable(node, loadedOptions)
124
147
  if (Array.isArray(opts) && !opts.some((o) => sameId(o.id, value))) return `${label} must be one of the options`
125
148
  return null
126
149
  }
@@ -129,6 +152,13 @@ export function fieldError(node, value, loadedOptions) {
129
152
  }
130
153
  }
131
154
 
155
+ /** The options a choice field offers: its own list, or the loaded rows. */
156
+ export function chooseable(node, loadedOptions) {
157
+ const data = node.props.data || {}
158
+ const opts = data.source === 'static' ? data.options : loadedOptions
159
+ return Array.isArray(opts) ? opts : null
160
+ }
161
+
132
162
  /**
133
163
  * <select> hands back a string, while a table's ids may be numbers. The id is
134
164
  * matched loosely and then saved in the OPTION's own type — see optionValue.
@@ -176,8 +206,9 @@ export function recordValues(doc, record, controls = CONTROLS) {
176
206
  inputNodes(doc, controls).forEach((node) => {
177
207
  const name = node.props.name
178
208
  const v = record ? record[name] : undefined
179
- if (v !== undefined && v !== null) out[name] = node.type === 'date' && typeof v === 'string' ? v.slice(0, 10) : v
209
+ if (v !== undefined && v !== null) out[name] = fromDbValue(node, v)
180
210
  else if (node.type === 'checkbox') out[name] = false
211
+ else if (node.type === 'multiselect') out[name] = []
181
212
  })
182
213
  return out
183
214
  }
@@ -200,10 +231,58 @@ export function displayValue(node, value, options) {
200
231
  if (value === undefined || value === null || value === '') return ''
201
232
  if (!node) return typeof value === 'object' ? JSON.stringify(value) : value
202
233
  if (node.type === 'checkbox') return value ? 'Yes' : 'No'
203
- if (node.type === 'dropdown') {
204
- const opts = node.props.data?.source === 'static' ? node.props.data.options : options
205
- const hit = (opts || []).find((o) => sameId(o.id, value))
206
- return hit ? hit.name : String(value)
234
+ if (node.type === 'file') return fileLabel(value)
235
+ if (node.type === 'datetime') return String(value).replace('T', ' ').slice(0, 16)
236
+ if (node.type === 'dropdown' || node.type === 'radio') return optionName(node, value, options)
237
+ if (node.type === 'multiselect') {
238
+ return (fromDbValue(node, value) || []).map((v) => optionName(node, v, options)).join(', ')
239
+ }
240
+ return value
241
+ }
242
+
243
+ function optionName(node, value, options) {
244
+ const opts = node.props.data?.source === 'static' ? node.props.data.options : options
245
+ const hit = (opts || []).find((o) => sameId(o.id, value))
246
+ return hit ? hit.name : String(value)
247
+ }
248
+
249
+ /** The name at the end of a stored file path, without the id that keeps it apart. */
250
+ export function fileLabel(path) {
251
+ const s = String(path)
252
+ const cut = s.slice(s.lastIndexOf('/') + 1)
253
+ const sep = cut.indexOf('__')
254
+ return sep === -1 ? cut : cut.slice(sep + 2)
255
+ }
256
+
257
+ // ── the database boundary ────────────────────────────────────────────────
258
+ // Two types do not go into their column as they are read: a multi-select is
259
+ // several ids in one text column, and a date-and-time comes back as the
260
+ // database wrote it. Both sides of the wire use these, so the conversion is
261
+ // written once.
262
+
263
+ /** A screen value → what its column stores. */
264
+ export function toDbValue(node, value) {
265
+ if (value === undefined || value === null) return value
266
+ if (node.type === 'multiselect') {
267
+ const list = Array.isArray(value) ? value : [value]
268
+ return list.length ? list.map((v) => String(v)).join(MULTI_SEPARATOR) : null
269
+ }
270
+ return value
271
+ }
272
+
273
+ /** What a column holds → the screen's value. */
274
+ export function fromDbValue(node, value) {
275
+ if (value === undefined || value === null) return value
276
+ if (node.type === 'multiselect') {
277
+ if (Array.isArray(value)) return value
278
+ const s = String(value)
279
+ return s === '' ? [] : s.split(MULTI_SEPARATOR).filter((x) => x !== '')
280
+ }
281
+ if (node.type === 'date') return typeof value === 'string' ? value.slice(0, 10) : value
282
+ if (node.type === 'datetime') {
283
+ // "2026-09-16 14:30:00" or an ISO string → what <input type="datetime-local"> shows.
284
+ const s = value instanceof Date ? value.toISOString() : String(value)
285
+ return s.replace(' ', 'T').slice(0, 16)
207
286
  }
208
287
  return value
209
288
  }