refactor(form-schema): extract schema types and schema-driven behaviors to shared package
Moves formBuilder types, formValidation, useConditionalLogic, useFormSteps, and formatFieldValue from apps/portal/src to packages/form-schema/src. Adds @form-schema path alias to both apps/portal and apps/app. Vue field components remain per-app to allow independent visual evolution. Behavior-neutral: all 35 Vitest tests green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
137
packages/form-schema/src/composables/formatFieldValue.ts
Normal file
137
packages/form-schema/src/composables/formatFieldValue.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { FormFieldType } from '../types/formBuilder'
|
||||
import type {
|
||||
PublicFormField,
|
||||
PublicFormSectionOption,
|
||||
PublicFormTimeSlot,
|
||||
SectionPriorityValue,
|
||||
} from '../types/formBuilder'
|
||||
|
||||
const EMPTY = '—'
|
||||
const LOADING = 'Laden…'
|
||||
const UNKNOWN_TAG = '(onbekende tag)'
|
||||
const UNKNOWN_TIME_SLOT = '(onbekend tijdslot)'
|
||||
const UNKNOWN_SECTION = '(onbekende sectie)'
|
||||
|
||||
// Single source of truth for how a submitted value is rendered on the
|
||||
// review step and the post-submit confirmation page. Shared so the
|
||||
// stringified-id / [object Object] bugs fixed in S3a PR 2.2 can't
|
||||
// regress via a naive caller.
|
||||
//
|
||||
// `timeSlots` / `sections` are intentionally accepted as raw arrays (or
|
||||
// undefined when the underlying TanStack Query is still fetching).
|
||||
// Callers pass the cached `.data.value` from usePublicFormTimeSlots /
|
||||
// usePublicFormSections; this keeps the formatter side-effect-free and
|
||||
// trivial to unit-test.
|
||||
export function formatFieldValue(
|
||||
field: PublicFormField,
|
||||
value: unknown,
|
||||
timeSlots: readonly PublicFormTimeSlot[] | undefined,
|
||||
sections: readonly PublicFormSectionOption[] | undefined,
|
||||
): string {
|
||||
if (isEmptyValue(value)) return EMPTY
|
||||
|
||||
switch (field.field_type) {
|
||||
case FormFieldType.TAG_PICKER:
|
||||
return formatTagPicker(field, value)
|
||||
case FormFieldType.AVAILABILITY_PICKER:
|
||||
return formatAvailabilityPicker(value, timeSlots)
|
||||
case FormFieldType.SECTION_PRIORITY:
|
||||
return formatSectionPriority(value, sections)
|
||||
case FormFieldType.BOOLEAN:
|
||||
return value ? 'Ja' : 'Nee'
|
||||
default:
|
||||
return formatScalarOrList(value)
|
||||
}
|
||||
}
|
||||
|
||||
function isEmptyValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined || value === '') return true
|
||||
if (Array.isArray(value) && value.length === 0) return true
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function formatTagPicker(field: PublicFormField, value: unknown): string {
|
||||
if (!Array.isArray(value)) return EMPTY
|
||||
|
||||
const byId = new Map<string, string>()
|
||||
for (const tag of field.available_tags ?? []) byId.set(tag.id, tag.name)
|
||||
|
||||
const parts = value
|
||||
.map(v => (typeof v === 'string' ? v : String(v)))
|
||||
.map(id => byId.get(id) ?? UNKNOWN_TAG)
|
||||
|
||||
return parts.length > 0 ? parts.join(', ') : EMPTY
|
||||
}
|
||||
|
||||
function formatAvailabilityPicker(
|
||||
value: unknown,
|
||||
timeSlots: readonly PublicFormTimeSlot[] | undefined,
|
||||
): string {
|
||||
if (!Array.isArray(value)) return EMPTY
|
||||
if (timeSlots === undefined) return LOADING
|
||||
|
||||
const byId = new Map<string, PublicFormTimeSlot>()
|
||||
for (const slot of timeSlots) byId.set(slot.id, slot)
|
||||
|
||||
const parts = value
|
||||
.map(v => (typeof v === 'string' ? v : String(v)))
|
||||
.map(id => {
|
||||
const slot = byId.get(id)
|
||||
if (!slot) return UNKNOWN_TIME_SLOT
|
||||
|
||||
return `${slot.name} (${stripSeconds(slot.start_time)}–${stripSeconds(slot.end_time)})`
|
||||
})
|
||||
|
||||
return parts.length > 0 ? parts.join(', ') : EMPTY
|
||||
}
|
||||
|
||||
function formatSectionPriority(
|
||||
value: unknown,
|
||||
sections: readonly PublicFormSectionOption[] | undefined,
|
||||
): string {
|
||||
// Defensive shape-guard: if the value isn't {section_id, priority}[],
|
||||
// fall back to EMPTY rather than leaking `[object Object]`.
|
||||
if (!Array.isArray(value)) return EMPTY
|
||||
|
||||
const entries: SectionPriorityValue[] = []
|
||||
for (const entry of value) {
|
||||
if (!entry || typeof entry !== 'object') return EMPTY
|
||||
const obj = entry as Record<string, unknown>
|
||||
if (typeof obj.section_id !== 'string' || typeof obj.priority !== 'number') {
|
||||
return EMPTY
|
||||
}
|
||||
entries.push({ section_id: obj.section_id, priority: obj.priority })
|
||||
}
|
||||
if (entries.length === 0) return EMPTY
|
||||
if (sections === undefined) return LOADING
|
||||
|
||||
const byId = new Map<string, PublicFormSectionOption>()
|
||||
for (const section of sections) byId.set(section.id, section)
|
||||
|
||||
// Input may be out of order; the review/confirmation copy is "1. Foo,
|
||||
// 2. Bar" so sort by priority ascending before rendering.
|
||||
const sorted = [...entries].sort((a, b) => a.priority - b.priority)
|
||||
|
||||
return sorted
|
||||
.map(({ section_id, priority }) => {
|
||||
const name = byId.get(section_id)?.name ?? UNKNOWN_SECTION
|
||||
|
||||
return `${priority}. ${name}`
|
||||
})
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
function formatScalarOrList(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return value.length > 0 ? value.map(v => String(v)).join(', ') : EMPTY
|
||||
}
|
||||
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function stripSeconds(t: string): string {
|
||||
const parts = t.split(':')
|
||||
|
||||
return parts.length >= 2 ? `${parts[0]}:${parts[1]}` : t
|
||||
}
|
||||
127
packages/form-schema/src/composables/useConditionalLogic.ts
Normal file
127
packages/form-schema/src/composables/useConditionalLogic.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import type {
|
||||
ConditionalGroup,
|
||||
ConditionalLogic,
|
||||
ConditionalOperator,
|
||||
ConditionalRule,
|
||||
FormValues,
|
||||
} from '../types/formBuilder'
|
||||
|
||||
function isEmptyValue(v: unknown): boolean {
|
||||
if (v === null || v === undefined) return true
|
||||
if (typeof v === 'string') return v.length === 0
|
||||
if (Array.isArray(v)) return v.length === 0
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function toComparable(v: unknown): string | number | boolean {
|
||||
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') return v
|
||||
|
||||
return String(v ?? '')
|
||||
}
|
||||
|
||||
function evaluateRule(rule: ConditionalRule, values: FormValues): boolean {
|
||||
const op = rule.operator as ConditionalOperator
|
||||
const actual = values[rule.field_slug]
|
||||
const expected = rule.value
|
||||
|
||||
switch (op) {
|
||||
case 'empty':
|
||||
return isEmptyValue(actual)
|
||||
case 'not_empty':
|
||||
return !isEmptyValue(actual)
|
||||
case 'equals':
|
||||
if (isEmptyValue(actual) && !isEmptyValue(expected)) return false
|
||||
|
||||
return toComparable(actual) === toComparable(expected)
|
||||
case 'not_equals':
|
||||
if (isEmptyValue(actual) && !isEmptyValue(expected)) return true
|
||||
|
||||
return toComparable(actual) !== toComparable(expected)
|
||||
case 'contains': {
|
||||
if (isEmptyValue(actual)) return false
|
||||
if (Array.isArray(actual)) return actual.map(toComparable).includes(toComparable(expected))
|
||||
|
||||
return String(actual).includes(String(expected ?? ''))
|
||||
}
|
||||
case 'not_contains': {
|
||||
if (isEmptyValue(actual)) return true
|
||||
if (Array.isArray(actual)) return !actual.map(toComparable).includes(toComparable(expected))
|
||||
|
||||
return !String(actual).includes(String(expected ?? ''))
|
||||
}
|
||||
case 'in': {
|
||||
if (isEmptyValue(actual)) return false
|
||||
if (!Array.isArray(expected)) return false
|
||||
const exp = expected.map(toComparable)
|
||||
if (Array.isArray(actual)) return actual.some(a => exp.includes(toComparable(a)))
|
||||
|
||||
return exp.includes(toComparable(actual))
|
||||
}
|
||||
case 'not_in': {
|
||||
if (isEmptyValue(actual)) return true
|
||||
if (!Array.isArray(expected)) return true
|
||||
const exp = expected.map(toComparable)
|
||||
if (Array.isArray(actual)) return !actual.some(a => exp.includes(toComparable(a)))
|
||||
|
||||
return !exp.includes(toComparable(actual))
|
||||
}
|
||||
case 'greater_than': {
|
||||
if (isEmptyValue(actual)) return false
|
||||
const a = Number(actual)
|
||||
const e = Number(expected)
|
||||
if (Number.isNaN(a) || Number.isNaN(e)) return false
|
||||
|
||||
return a > e
|
||||
}
|
||||
case 'less_than': {
|
||||
if (isEmptyValue(actual)) return false
|
||||
const a = Number(actual)
|
||||
const e = Number(expected)
|
||||
if (Number.isNaN(a) || Number.isNaN(e)) return false
|
||||
|
||||
return a < e
|
||||
}
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
function isGroup(node: ConditionalRule | ConditionalGroup): node is ConditionalGroup {
|
||||
return typeof node === 'object' && node !== null && (('all' in node) || ('any' in node))
|
||||
}
|
||||
|
||||
function evaluateGroup(group: ConditionalGroup, values: FormValues): boolean {
|
||||
if (Array.isArray(group.all) && group.all.length > 0) {
|
||||
for (const node of group.all) {
|
||||
const ok = isGroup(node) ? evaluateGroup(node, values) : evaluateRule(node, values)
|
||||
if (!ok) return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
if (Array.isArray(group.any) && group.any.length > 0) {
|
||||
for (const node of group.any) {
|
||||
const ok = isGroup(node) ? evaluateGroup(node, values) : evaluateRule(node, values)
|
||||
if (ok) return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a conditional logic block against the current form values.
|
||||
* Returns true when the field/group should be visible; defaults to true
|
||||
* when the logic is absent or malformed.
|
||||
*/
|
||||
export function evaluateConditionalLogic(
|
||||
logic: ConditionalLogic | null | undefined,
|
||||
values: FormValues,
|
||||
): boolean {
|
||||
if (!logic || !logic.show_when) return true
|
||||
|
||||
return evaluateGroup(logic.show_when, values)
|
||||
}
|
||||
138
packages/form-schema/src/composables/useFormSteps.ts
Normal file
138
packages/form-schema/src/composables/useFormSteps.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { computed } from 'vue'
|
||||
import type { ComputedRef, Ref } from 'vue'
|
||||
import { evaluateConditionalLogic } from './useConditionalLogic'
|
||||
import { FormFieldType } from '../types/formBuilder'
|
||||
import type { FormValues, PublicFormField, PublicFormSchema } from '../types/formBuilder'
|
||||
import { isFieldValueEmpty } from '../utils/formValidation'
|
||||
|
||||
export type StepKind = 'submitter' | 'section' | 'heading_group' | 'flat' | 'review'
|
||||
|
||||
export interface FormStep {
|
||||
key: string
|
||||
kind: StepKind
|
||||
title: string
|
||||
subtitle?: string
|
||||
fields: PublicFormField[]
|
||||
}
|
||||
|
||||
function partitionByHeading(fields: PublicFormField[]): FormStep[] {
|
||||
if (fields.length === 0) return []
|
||||
|
||||
const out: FormStep[] = []
|
||||
let current: FormStep | null = null
|
||||
let index = 0
|
||||
|
||||
for (const field of fields) {
|
||||
if (field.field_type === FormFieldType.HEADING) {
|
||||
current = {
|
||||
key: `heading-${field.id}`,
|
||||
kind: 'heading_group',
|
||||
title: field.label,
|
||||
fields: [field],
|
||||
}
|
||||
out.push(current)
|
||||
index++
|
||||
continue
|
||||
}
|
||||
if (!current) {
|
||||
current = {
|
||||
key: `group-${index}`,
|
||||
kind: 'heading_group',
|
||||
title: 'Vragen',
|
||||
fields: [],
|
||||
}
|
||||
out.push(current)
|
||||
index++
|
||||
}
|
||||
current.fields.push(field)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
export function useFormSteps(schema: Ref<PublicFormSchema | null | undefined>): ComputedRef<FormStep[]> {
|
||||
return computed<FormStep[]>(() => {
|
||||
const s = schema.value
|
||||
const submitterStep: FormStep = {
|
||||
key: 'submitter',
|
||||
kind: 'submitter',
|
||||
title: 'Contactgegevens',
|
||||
subtitle: 'Zo kunnen we contact met je opnemen',
|
||||
fields: [],
|
||||
}
|
||||
const reviewStep: FormStep = {
|
||||
key: 'review',
|
||||
kind: 'review',
|
||||
title: 'Controleer en versturen',
|
||||
subtitle: 'Check je antwoorden en verstuur het formulier',
|
||||
fields: [],
|
||||
}
|
||||
|
||||
if (!s) return [submitterStep, reviewStep]
|
||||
|
||||
const sorted = [...s.fields].sort((a, b) => a.sort_order - b.sort_order)
|
||||
|
||||
const steps: FormStep[] = [submitterStep]
|
||||
|
||||
if (s.sections.length > 0 && s.section_level_submit === false) {
|
||||
const sectionsSorted = [...s.sections].sort((a, b) => a.sort_order - b.sort_order)
|
||||
for (const section of sectionsSorted) {
|
||||
const fields = sorted.filter(f => f.form_schema_section_id === section.id)
|
||||
steps.push({
|
||||
key: `section-${section.id}`,
|
||||
kind: 'section',
|
||||
title: section.name,
|
||||
subtitle: section.description ?? undefined,
|
||||
fields,
|
||||
})
|
||||
}
|
||||
const loose = sorted.filter(f => f.form_schema_section_id === null)
|
||||
if (loose.length > 0) {
|
||||
steps.push({
|
||||
key: 'section-loose',
|
||||
kind: 'section',
|
||||
title: 'Overig',
|
||||
fields: loose,
|
||||
})
|
||||
}
|
||||
}
|
||||
else if (sorted.some(f => f.field_type === FormFieldType.HEADING)) {
|
||||
steps.push(...partitionByHeading(sorted))
|
||||
}
|
||||
else {
|
||||
steps.push({
|
||||
key: 'all-fields',
|
||||
kind: 'flat',
|
||||
title: 'Vragen',
|
||||
fields: sorted,
|
||||
})
|
||||
}
|
||||
|
||||
steps.push(reviewStep)
|
||||
|
||||
return steps
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when all visible required fields in `step` have a
|
||||
* non-empty value. Hidden fields (failing conditional logic) are
|
||||
* skipped. HEADING/PARAGRAPH fields carry no value and are skipped.
|
||||
*/
|
||||
export function isStepValid(
|
||||
step: FormStep,
|
||||
values: FormValues,
|
||||
submitterValid: boolean,
|
||||
): boolean {
|
||||
if (step.kind === 'submitter') return submitterValid
|
||||
if (step.kind === 'review') return true
|
||||
|
||||
for (const field of step.fields) {
|
||||
if (field.field_type === FormFieldType.HEADING || field.field_type === FormFieldType.PARAGRAPH) continue
|
||||
if (!field.is_required) continue
|
||||
if (!evaluateConditionalLogic(field.conditional_logic, values)) continue
|
||||
if (isFieldValueEmpty(values[field.slug])) return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user