diff --git a/README.md b/README.md index 93b6adb..d110698 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ A Vue 3 PDF viewer for building interactive document workflows with draggable, r Use it to build signature placement, form-field positioning, annotations, review tools, document preparation flows and other PDF experiences where users need to place or manipulate elements on top of a document. -**[Try the live demo](https://libresign.github.io/pdf-elements/)** · [Getting started](docs/GETTING_STARTED.md) · [API](docs/API.md) · [Examples](examples/) · [Contributing](CONTRIBUTING.md) +**[Try the live demo](https://libresign.github.io/pdf-elements/)** · [Getting started](docs/GETTING_STARTED.md) · [API](docs/API.md) · [Form model](docs/FORM_MODEL.md) · [Examples](examples/) · [Contributing](CONTRIBUTING.md) ![The pdf-elements demo with a sample PDF loaded and a signature element placed on the first page](img/screenshot/demo.png) @@ -50,5 +50,6 @@ PDF Elements can be used for: - [Getting started](docs/GETTING_STARTED.md) - [API reference](docs/API.md) +- [Form field and widget model](docs/FORM_MODEL.md) - [Basic example](examples/basic/) - [Contributing](CONTRIBUTING.md) diff --git a/docs/API.md b/docs/API.md index caa0a14..6e3fe7e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5,6 +5,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later # PDF Elements API +For the logical field / visual widget data model (plain serializable types, relationships and overlay coexistence), see [Form field and widget model](./FORM_MODEL.md). + ## Props | Prop | Type | Default | Description | diff --git a/docs/FORM_MODEL.md b/docs/FORM_MODEL.md new file mode 100644 index 0000000..e188b89 --- /dev/null +++ b/docs/FORM_MODEL.md @@ -0,0 +1,166 @@ + + +# Form field and widget model + +This document describes the public form data model introduced for logical fields and visual widgets. The model is plain, serializable data and does not depend on Vue instances, DOM nodes or PDF.js runtime objects. + +Generic overlay editing continues to use [`PDFElementObject`](./API.md). Form support is additive. + +## Concepts + +| Concept | Responsibility | +|---------|----------------| +| **Field** (`PDFFormField`) | Logical form control: type, name, value, default, required, read-only, options, metadata, and the list of widget ids. | +| **Widget** (`PDFFormWidget`) | One visual appearance of a field: page, optional document index, coordinates, size, optional export value, optional overlay `elementId`, metadata. | +| **Model** (`PDFFormModel`) | `{ fields, widgets }` document snapshot that can be persisted and restored. | + +Relationships: + +- One field → zero or more widgets. +- Each widget belongs to exactly one field (`widget.fieldId`). +- Widgets may live on different pages (and optionally different documents via `docIndex`). +- Radio groups are one field with several widgets; each widget may carry an `exportValue`. + +Coordinates and page placement stay on the widget. Shared field properties are not duplicated as placement properties. + +## Public types + +```ts +import type { + PDFFormField, + PDFFormModel, + PDFFormWidget, +} from '@libresign/pdf-elements' +``` + +### `PDFFormField` + +| Property | Type | Notes | +|----------|------|--------| +| `id` | `string` | Stable field id | +| `type` | `PDFFormFieldType` | Known values: `text`, `checkbox`, `radio`, `dropdown`, `listbox`, `signature`, `button`. Any other string is allowed for unknown/future types. | +| `name` | `string` | Field name | +| `value` | `string \| number \| boolean \| string[] \| null` | Optional current value | +| `defaultValue` | same as `value` | Optional default | +| `required` | `boolean` | Optional | +| `readOnly` | `boolean` | Optional | +| `options` | `PDFFormFieldOption[]` | Choice fields | +| `widgetIds` | `string[]` | Ordered widget references | +| `metadata` | `Record` | Extensible non-core data | + +### `PDFFormWidget` + +| Property | Type | Notes | +|----------|------|--------| +| `id` | `string` | Stable widget id | +| `fieldId` | `string` | Owning field | +| `pageIndex` | `number` | Zero-based page | +| `docIndex` | `number` | Optional document index | +| `x`, `y`, `width`, `height` | `number` | Placement | +| `exportValue` | `string` | Optional on-value for multi-widget fields | +| `elementId` | `string` | Optional link to a `PDFElementObject.id` | +| `metadata` | `Record` | Extensible non-core data | + +Host workflow concepts (recipients, envelopes, signing policies, participant roles, Nextcloud identities, and similar) must not be added to these core types. Put host-specific data in `metadata` or keep it outside this package. + +## Helpers + +```ts +import { + addWidgetToField, + createFormField, + createFormModel, + createFormWidget, + elementObjectToFormWidgetPlacement, + formWidgetToElementObject, + getWidgetsForField, + parseFormModel, + serializeFormModel, + validateFormModelRelationships, +} from '@libresign/pdf-elements' + +const model = createFormModel() +const field = createFormField({ + type: 'radio', + name: 'color', + options: [ + { value: 'red', label: 'Red' }, + { value: 'blue', label: 'Blue' }, + ], + required: true, +}) +model.fields.push(field) + +addWidgetToField(model, { + fieldId: field.id, + pageIndex: 0, + x: 40, + y: 80, + width: 18, + height: 18, + exportValue: 'red', +}) + +addWidgetToField(model, { + fieldId: field.id, + pageIndex: 1, + x: 40, + y: 120, + width: 18, + height: 18, + exportValue: 'blue', +}) + +const widgets = getWidgetsForField(model, field.id) +const snapshot = serializeFormModel(model) +const restored = parseFormModel(JSON.stringify(snapshot)) +``` + +`validateFormModelRelationships(model)` reports missing links, orphans, mismatches and duplicate ids without mutating the model. + +## Serialization + +- Prefer `serializeFormModel` / `parseFormModel` (or `JSON.stringify` / `JSON.parse` on a model that already passed validation). +- Values must remain JSON-serializable primitives (or string arrays / `null`). +- Do not store Vue component instances, DOM nodes, PDF.js `PDFDocumentProxy` objects, Promises or functions on fields, widgets or `metadata`. + +## Compatibility with `PDFElementObject` + +No breaking change is required for existing overlay consumers. + +| Use case | API | +|----------|-----| +| Generic overlays (signatures, annotations, markers) | Keep using `PDFElementObject` and `PDFElements` methods (`startAddingElement`, `getAllObjects`, …). | +| Form-aware consumers | Keep a `PDFFormModel` beside the overlay store. Use `formWidgetToElementObject` to place/edit visuals, and `elementObjectToFormWidgetPlacement` to copy moved/resized geometry back onto widgets. | +| Bridge | Set `widget.elementId` to the overlay object `id` when both representations exist. | + +### Migration + +Existing integrations that only use `PDFElementObject` need no migration. + +If a host previously encoded form semantics only on overlay objects (for example custom keys on `[key: string]: unknown`), migrate gradually: + +1. Create `PDFFormField` entries for shared properties (`type`, `name`, value, required, options). +2. Create one `PDFFormWidget` per visual rectangle, including `pageIndex` and geometry. +3. Optionally set `elementId` to the existing overlay object id so the editor can keep using `PDFElementObject` until form editing lands (#85). +4. Stop duplicating field-level properties onto each overlay object once the form model is the source of truth. + +## Out of scope + +This package model does **not** implement: + +- PDF AcroForm parsing or writing +- PDF mutation or cryptographic signing +- Full per-type editor behavior (tracked separately) + +Those belong outside this issue and, for editor behavior, in follow-up work that builds on this model. + +Parsing validates required properties, finite geometry, non-negative integer page/document +indices, non-negative sizes and plain JSON data (including metadata). Runtime objects, +functions, cycles and non-finite numbers are rejected before conversion. +By default it also checks both directions of field/widget references and rejects +duplicate IDs or repeated widget references. `{ strict: false }` skips only +relationship checks; property and JSON validation still apply. diff --git a/src/index.ts b/src/index.ts index c23835c..33bd198 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,29 @@ import type { App } from 'vue' import PDFElements from './components/PDFElements.vue' export { ensureWorkerReady, setWorkerPath } from './utils/asyncReader' +export { + addWidgetToField, + createFormField, + createFormFieldId, + createFormModel, + createFormWidget, + createFormWidgetId, + elementObjectToFormWidgetPlacement, + formWidgetToElementObject, + getFieldForWidget, + getFormFieldById, + getFormWidgetById, + getWidgetsForField, + parseFormModel, + serializeFormModel, + validateFormModelRelationships, +} from './utils/formModel' +export type { + CreateFormFieldInput, + CreateFormWidgetInput, + FormModelRelationshipIssue, + FormWidgetToElementOptions, +} from './utils/formModel' export type { PDFDocumentEntry, PDFElementObject, @@ -13,6 +36,15 @@ export type { PDFElementsAddingEndedPlacedPayload, PDFElementsAddingEndedReason, PDFElementsPublicApi, + PDFFormField, + PDFFormFieldId, + PDFFormFieldKnownType, + PDFFormFieldOption, + PDFFormFieldType, + PDFFormFieldValue, + PDFFormModel, + PDFFormWidget, + PDFFormWidgetId, } from './types' const install = (app: App) => { diff --git a/src/types.ts b/src/types.ts index 2e76326..9dbf5fc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -51,3 +51,105 @@ export interface PDFElementsPublicApi { duplicateObject: (docIndex: number, objectId: string) => void cancelAdding: () => void } + +/** + * Stable identifier for a logical form field. + * Fields hold shared properties; visual placement lives on widgets. + */ +export type PDFFormFieldId = string + +/** + * Stable identifier for a visual form widget. + * A widget is one rectangle on one page belonging to a field. + */ +export type PDFFormWidgetId = string + +/** + * Well-known field types. Consumers may also use any other string for + * unknown or future types without losing identity. + */ +export type PDFFormFieldKnownType = + | 'text' + | 'checkbox' + | 'radio' + | 'dropdown' + | 'listbox' + | 'signature' + | 'button' + +/** + * Field type string. Known values are listed in {@link PDFFormFieldKnownType}; + * arbitrary strings remain valid for forward compatibility. + */ +export type PDFFormFieldType = PDFFormFieldKnownType | (string & {}) + +/** + * Plain serializable field value. Prefer primitives and string arrays so the + * model can be persisted without Vue, DOM or PDF.js objects. + */ +export type PDFFormFieldValue = string | number | boolean | string[] | null + +/** + * Choice option for dropdown, listbox, radio and similar fields. + */ +export interface PDFFormFieldOption { + value: string + label?: string + disabled?: boolean +} + +/** + * Logical form field. Shared properties live here; page coordinates do not. + * + * One field may reference many widgets (radio groups, repeated appearances, + * the same field on different pages). + */ +export interface PDFFormField { + id: PDFFormFieldId + type: PDFFormFieldType + name: string + value?: PDFFormFieldValue + defaultValue?: PDFFormFieldValue + required?: boolean + readOnly?: boolean + options?: PDFFormFieldOption[] + /** Ordered widget ids that belong to this field. */ + widgetIds: PDFFormWidgetId[] + /** Extensible bag for non-core data. Keep host-specific workflow data here. */ + metadata?: Record +} + +/** + * Visual widget for a form field. Placement and page belong here only. + */ +export interface PDFFormWidget { + id: PDFFormWidgetId + fieldId: PDFFormFieldId + pageIndex: number + /** Optional when the model is already scoped to a single document. */ + docIndex?: number + x: number + y: number + width: number + height: number + /** + * On-value for this appearance when a field has several widgets + * (for example each radio button in a group). + */ + exportValue?: string + /** + * Optional link to a {@link PDFElementObject} id used by the overlay editor. + * Lets form widgets coexist with generic non-form overlays. + */ + elementId?: string + metadata?: Record +} + +/** + * Plain serializable form document model: logical fields plus visual widgets. + * Independent from Vue component state, DOM nodes and PDF.js runtime objects. + */ +export interface PDFFormModel { + fields: PDFFormField[] + widgets: PDFFormWidget[] +} diff --git a/src/utils/formModel.ts b/src/utils/formModel.ts new file mode 100644 index 0000000..dc2832a --- /dev/null +++ b/src/utils/formModel.ts @@ -0,0 +1,450 @@ +// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { + PDFElementObject, + PDFFormField, + PDFFormFieldId, + PDFFormFieldOption, + PDFFormFieldType, + PDFFormFieldValue, + PDFFormModel, + PDFFormWidget, + PDFFormWidgetId, +} from '../types' + +let fieldIdCounter = 0 +let widgetIdCounter = 0 + +function createRandomSuffix(): string { + return Math.random().toString(36).slice(2, 8) +} + +/** Creates a stable-looking field id suitable for new logical fields. */ +export function createFormFieldId(): PDFFormFieldId { + fieldIdCounter += 1 + return `field-${Date.now()}-${fieldIdCounter}-${createRandomSuffix()}` +} + +/** Creates a stable-looking widget id suitable for new visual widgets. */ +export function createFormWidgetId(): PDFFormWidgetId { + widgetIdCounter += 1 + return `widget-${Date.now()}-${widgetIdCounter}-${createRandomSuffix()}` +} + +export interface CreateFormFieldInput { + id?: PDFFormFieldId + type: PDFFormFieldType + name: string + value?: PDFFormFieldValue + defaultValue?: PDFFormFieldValue + required?: boolean + readOnly?: boolean + options?: PDFFormFieldOption[] + widgetIds?: PDFFormWidgetId[] + metadata?: Record +} + +export interface CreateFormWidgetInput { + id?: PDFFormWidgetId + fieldId: PDFFormFieldId + pageIndex: number + docIndex?: number + x: number + y: number + width: number + height: number + exportValue?: string + elementId?: string + metadata?: Record +} + +/** Builds a plain logical field object. Does not register widgets. */ +export function createFormField(input: CreateFormFieldInput): PDFFormField { + const field: PDFFormField = { + id: input.id ?? createFormFieldId(), + type: input.type, + name: input.name, + widgetIds: input.widgetIds ? [...input.widgetIds] : [], + } + + if (input.value !== undefined) field.value = input.value + if (input.defaultValue !== undefined) field.defaultValue = input.defaultValue + if (input.required !== undefined) field.required = input.required + if (input.readOnly !== undefined) field.readOnly = input.readOnly + if (input.options !== undefined) { + field.options = input.options.map((option) => ({ ...option })) + } + if (input.metadata !== undefined) { + field.metadata = { ...input.metadata } + } + + return field +} + +/** Builds a plain visual widget object. Does not update the parent field. */ +export function createFormWidget(input: CreateFormWidgetInput): PDFFormWidget { + const widget: PDFFormWidget = { + id: input.id ?? createFormWidgetId(), + fieldId: input.fieldId, + pageIndex: input.pageIndex, + x: input.x, + y: input.y, + width: input.width, + height: input.height, + } + + if (input.docIndex !== undefined) widget.docIndex = input.docIndex + if (input.exportValue !== undefined) widget.exportValue = input.exportValue + if (input.elementId !== undefined) widget.elementId = input.elementId + if (input.metadata !== undefined) { + widget.metadata = { ...input.metadata } + } + + return widget +} + +/** Returns an empty serializable form model. */ +export function createFormModel(): PDFFormModel { + return { + fields: [], + widgets: [], + } +} + +export function getFormFieldById( + model: PDFFormModel, + fieldId: PDFFormFieldId +): PDFFormField | undefined { + return model.fields.find((field) => field.id === fieldId) +} + +export function getFormWidgetById( + model: PDFFormModel, + widgetId: PDFFormWidgetId +): PDFFormWidget | undefined { + return model.widgets.find((widget) => widget.id === widgetId) +} + +/** Returns widgets for a field in the order declared by `field.widgetIds`. */ +export function getWidgetsForField( + model: PDFFormModel, + fieldId: PDFFormFieldId +): PDFFormWidget[] { + const field = getFormFieldById(model, fieldId) + if (!field) return [] + + const byId = new Map(model.widgets.map((widget) => [widget.id, widget])) + const ordered: PDFFormWidget[] = [] + + for (const widgetId of field.widgetIds) { + const widget = byId.get(widgetId) + if (widget && widget.fieldId === fieldId) { + ordered.push(widget) + } + } + + return ordered +} + +export function getFieldForWidget( + model: PDFFormModel, + widgetId: PDFFormWidgetId +): PDFFormField | undefined { + const widget = getFormWidgetById(model, widgetId) + if (!widget) return undefined + return getFormFieldById(model, widget.fieldId) +} + +export interface FormModelRelationshipIssue { + code: + | 'unlisted-widget' + | 'duplicate-widget-reference' + | 'missing-widget' + | 'widget-field-mismatch' + | 'orphan-widget' + | 'duplicate-field-id' + | 'duplicate-widget-id' + message: string + fieldId?: PDFFormFieldId + widgetId?: PDFFormWidgetId +} + +/** + * Validates field↔widget relationships without mutating the model. + * Does not require PDF.js, Vue or DOM objects. + */ +export function validateFormModelRelationships( + model: PDFFormModel +): FormModelRelationshipIssue[] { + const issues: FormModelRelationshipIssue[] = [] + const fieldIds = new Set() + const widgetIds = new Set() + + for (const field of model.fields) { + if (fieldIds.has(field.id)) { + issues.push({ + code: 'duplicate-field-id', + message: `Duplicate field id "${field.id}"`, + fieldId: field.id, + }) + } + fieldIds.add(field.id) + } + + for (const widget of model.widgets) { + if (widgetIds.has(widget.id)) { + issues.push({ + code: 'duplicate-widget-id', + message: `Duplicate widget id "${widget.id}"`, + widgetId: widget.id, + }) + } + widgetIds.add(widget.id) + const owner = getFormFieldById(model, widget.fieldId) + if (owner && !owner.widgetIds.includes(widget.id)) { + issues.push({ + code: 'unlisted-widget', + message: `Widget "${widget.id}" is not listed on field "${owner.id}"`, + fieldId: owner.id, + widgetId: widget.id, + }) + } + + if (!fieldIds.has(widget.fieldId)) { + issues.push({ + code: 'orphan-widget', + message: `Widget "${widget.id}" references missing field "${widget.fieldId}"`, + fieldId: widget.fieldId, + widgetId: widget.id, + }) + } + } + + for (const field of model.fields) { + const references = new Set() + for (const widgetId of field.widgetIds) { + if (references.has(widgetId)) { + issues.push({ + code: 'duplicate-widget-reference', + message: `Field "${field.id}" lists widget "${widgetId}" more than once`, + fieldId: field.id, + widgetId, + }) + } + references.add(widgetId) + const widget = getFormWidgetById(model, widgetId) + if (!widget) { + issues.push({ + code: 'missing-widget', + message: `Field "${field.id}" references missing widget "${widgetId}"`, + fieldId: field.id, + widgetId, + }) + continue + } + if (widget.fieldId !== field.id) { + issues.push({ + code: 'widget-field-mismatch', + message: `Widget "${widgetId}" belongs to field "${widget.fieldId}" but is listed on "${field.id}"`, + fieldId: field.id, + widgetId, + }) + } + } + } + + return issues +} + +/** + * Adds a widget to the model and appends its id to the owning field. + * Throws when the field is missing or the widget id already exists. + */ +export function addWidgetToField( + model: PDFFormModel, + widgetInput: CreateFormWidgetInput +): PDFFormWidget { + const field = getFormFieldById(model, widgetInput.fieldId) + if (!field) { + throw new Error(`Cannot add widget: field "${widgetInput.fieldId}" was not found`) + } + + const widget = createFormWidget(widgetInput) + if (getFormWidgetById(model, widget.id)) { + throw new Error(`Cannot add widget: id "${widget.id}" already exists`) + } + + model.widgets.push(widget) + if (!field.widgetIds.includes(widget.id)) { + field.widgetIds.push(widget.id) + } + + return widget +} + +/** + * Deep-clones a form model into plain JSON-safe data. + * Suitable for persistence and transport. + */ +export function serializeFormModel(model: PDFFormModel): PDFFormModel { + return JSON.parse(JSON.stringify(model)) as PDFFormModel +} + +function isPlainRecord(value: unknown): value is Record { + if (!value || typeof value !== 'object') return false + const prototype = Object.getPrototypeOf(value) + return prototype === Object.prototype || prototype === null +} + +function assertJsonData(value: unknown, ancestors = new Set()): void { + if (value === null || typeof value === 'string' || typeof value === 'boolean') return + if (typeof value === 'number' && Number.isFinite(value)) return + if (!Array.isArray(value) && !isPlainRecord(value)) { + throw new Error('Form model must contain only plain JSON data') + } + if (ancestors.has(value)) throw new Error('Form model must not contain cycles') + if (Array.isArray(value)) { + for (let index = 0; index < value.length; index += 1) { + if (!Object.prototype.hasOwnProperty.call(value, index)) { + throw new Error('Form model must not contain sparse arrays') + } + } + } + ancestors.add(value) + for (const entry of Object.values(value)) assertJsonData(entry, ancestors) + ancestors.delete(value) +} + +function assertModelShape(raw: unknown): asserts raw is PDFFormModel { + if (!isPlainRecord(raw)) throw new Error('Form model must be a plain object') + if (!Array.isArray(raw.fields) || !Array.isArray(raw.widgets)) { + throw new Error('Form model must include fields and widgets arrays') + } + const string = (value: unknown) => typeof value === 'string' + const id = (value: unknown) => string(value) && value !== '' + const value = (entry: unknown) => + entry === null || string(entry) || typeof entry === 'boolean' + || (typeof entry === 'number' && Number.isFinite(entry)) + || (Array.isArray(entry) && entry.every(string)) + const optional = (record: Record, key: string, check: (entry: unknown) => boolean) => + record[key] === undefined || check(record[key]) + for (const field of raw.fields) { + if (!isPlainRecord(field) + || !id(field.id) || !string(field.type) || !string(field.name) + || !Array.isArray(field.widgetIds) || !field.widgetIds.every(id) + || !optional(field, 'value', value) || !optional(field, 'defaultValue', value) + || !optional(field, 'required', entry => typeof entry === 'boolean') + || !optional(field, 'readOnly', entry => typeof entry === 'boolean') + || !optional(field, 'metadata', isPlainRecord) + || !optional(field, 'options', entry => Array.isArray(entry) && entry.every(option => + isPlainRecord(option) && string(option.value) + && optional(option, 'label', string) + && optional(option, 'disabled', disabled => typeof disabled === 'boolean')))) { + throw new Error('Invalid form field properties') + } + } + const index = (entry: unknown) => typeof entry === 'number' && Number.isInteger(entry) && entry >= 0 + for (const widget of raw.widgets) { + if (!isPlainRecord(widget) || !id(widget.id) || !id(widget.fieldId) + || !index(widget.pageIndex) || !optional(widget, 'docIndex', index) + || !['x', 'y', 'width', 'height'].every(key => + typeof widget[key] === 'number' && Number.isFinite(widget[key])) + || (widget.width as number) < 0 || (widget.height as number) < 0 + || !optional(widget, 'exportValue', string) || !optional(widget, 'elementId', id) + || !optional(widget, 'metadata', isPlainRecord)) { + throw new Error('Invalid form widget properties') + } + } +} + +/** + * Parses a JSON string or plain object into a {@link PDFFormModel}. + * Rejects non-plain structures and reports relationship issues when `strict`. + */ +export function parseFormModel( + input: string | unknown, + options: { strict?: boolean } = {} +): PDFFormModel { + const raw = typeof input === 'string' ? JSON.parse(input) : input + assertModelShape(raw) + assertJsonData(raw) + const model = serializeFormModel(raw) + + if (options.strict !== false) { + const issues = validateFormModelRelationships(model) + if (issues.length > 0) { + throw new Error( + `Invalid form model relationships: ${issues.map((issue) => issue.message).join('; ')}` + ) + } + } + + return model +} + +export interface FormWidgetToElementOptions { + /** Defaults to the parent field type when provided. */ + type?: string + label?: string + resizable?: boolean + /** Extra overlay properties merged onto the element. */ + extra?: Record +} + +/** + * Bridges a form widget to a generic overlay {@link PDFElementObject}. + * Coordinates come from the widget; shared field props stay on the field. + */ +export function formWidgetToElementObject( + widget: PDFFormWidget, + field?: Pick, + options: FormWidgetToElementOptions = {} +): PDFElementObject { + const element: PDFElementObject = { + id: widget.elementId ?? widget.id, + x: widget.x, + y: widget.y, + width: widget.width, + height: widget.height, + } + + const type = options.type ?? field?.type + if (type !== undefined) element.type = type + if (options.label !== undefined) { + element.label = options.label + } else if (field?.name !== undefined) { + element.label = field.name + } + if (options.resizable !== undefined) element.resizable = options.resizable + if (options.extra) { + Object.assign(element, options.extra) + } + + return element +} + +/** + * Creates a widget placement snapshot from an overlay element. + * Does not invent field-level properties such as value or required. + */ +export function elementObjectToFormWidgetPlacement( + element: PDFElementObject, + location: { pageIndex: number; docIndex?: number } +): Pick { + const placement: Pick< + PDFFormWidget, + 'x' | 'y' | 'width' | 'height' | 'pageIndex' | 'docIndex' | 'elementId' + > = { + x: element.x, + y: element.y, + width: element.width, + height: element.height, + pageIndex: location.pageIndex, + } + + if (location.docIndex !== undefined) placement.docIndex = location.docIndex + if (element.id !== undefined) placement.elementId = element.id + + return placement +} diff --git a/tests/utils/formModel.spec.ts b/tests/utils/formModel.spec.ts new file mode 100644 index 0000000..224ed51 --- /dev/null +++ b/tests/utils/formModel.spec.ts @@ -0,0 +1,293 @@ +// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { describe, expect, it } from 'vitest' +import type { PDFFormModel } from '../../src/types' +import { + addWidgetToField, + createFormField, + createFormModel, + createFormWidget, + elementObjectToFormWidgetPlacement, + formWidgetToElementObject, + getFieldForWidget, + getWidgetsForField, + parseFormModel, + serializeFormModel, + validateFormModelRelationships, +} from '../../src/utils/formModel' + +describe('formModel relationships', () => { + it('keeps logical fields separate from visual widgets', () => { + const model = createFormModel() + const field = createFormField({ + type: 'text', + name: 'full-name', + value: 'Ada', + defaultValue: '', + required: true, + readOnly: false, + }) + model.fields.push(field) + + const widget = addWidgetToField(model, { + fieldId: field.id, + pageIndex: 0, + x: 10, + y: 20, + width: 120, + height: 24, + }) + + expect(field).not.toHaveProperty('x') + expect(field).not.toHaveProperty('pageIndex') + expect(widget).not.toHaveProperty('value') + expect(widget).not.toHaveProperty('required') + expect(widget.fieldId).toBe(field.id) + expect(field.widgetIds).toEqual([widget.id]) + }) + + it('supports one field with multiple widgets on different pages', () => { + const model = createFormModel() + const field = createFormField({ + type: 'radio', + name: 'choice', + options: [ + { value: 'a', label: 'A' }, + { value: 'b', label: 'B' }, + ], + }) + model.fields.push(field) + + addWidgetToField(model, { + fieldId: field.id, + pageIndex: 0, + x: 10, + y: 10, + width: 16, + height: 16, + exportValue: 'a', + }) + addWidgetToField(model, { + fieldId: field.id, + pageIndex: 2, + docIndex: 0, + x: 40, + y: 80, + width: 16, + height: 16, + exportValue: 'b', + }) + + const widgets = getWidgetsForField(model, field.id) + expect(widgets).toHaveLength(2) + expect(widgets.map((widget) => widget.pageIndex)).toEqual([0, 2]) + expect(widgets.map((widget) => widget.exportValue)).toEqual(['a', 'b']) + expect(getFieldForWidget(model, widgets[1].id)?.id).toBe(field.id) + expect(validateFormModelRelationships(model)).toEqual([]) + }) + + it('assigns stable ids to fields and widgets', () => { + const field = createFormField({ type: 'checkbox', name: 'agree' }) + const widget = createFormWidget({ + fieldId: field.id, + pageIndex: 0, + x: 0, + y: 0, + width: 12, + height: 12, + }) + + expect(field.id).toMatch(/^field-/) + expect(widget.id).toMatch(/^widget-/) + expect(field.id).not.toBe(widget.id) + }) + + it('represents unknown future field types without losing identity', () => { + const field = createFormField({ + type: 'custom-barcode', + name: 'parcel', + metadata: { symbology: 'qr' }, + }) + + expect(field.type).toBe('custom-barcode') + expect(field.metadata).toEqual({ symbology: 'qr' }) + }) + + it('reports broken field/widget relationships', () => { + const broken: PDFFormModel = { + fields: [ + createFormField({ + id: 'field-1', + type: 'text', + name: 'a', + widgetIds: ['missing-widget'], + }), + ], + widgets: [ + createFormWidget({ + id: 'orphan', + fieldId: 'missing-field', + pageIndex: 0, + x: 0, + y: 0, + width: 10, + height: 10, + }), + ], + } + + const codes = validateFormModelRelationships(broken).map((issue) => issue.code) + expect(codes).toContain('missing-widget') + expect(codes).toContain('orphan-widget') + }) +}) + +describe('formModel serialization', () => { + it('round-trips through JSON without runtime objects', () => { + const model = createFormModel() + const field = createFormField({ + type: 'dropdown', + name: 'country', + value: 'br', + defaultValue: 'br', + required: true, + options: [{ value: 'br', label: 'Brazil' }], + metadata: { source: 'import' }, + }) + model.fields.push(field) + addWidgetToField(model, { + fieldId: field.id, + pageIndex: 1, + x: 5, + y: 6, + width: 100, + height: 28, + elementId: 'obj-1', + }) + + const json = JSON.stringify(serializeFormModel(model)) + const restored = parseFormModel(json) + + expect(restored).toEqual(model) + expect(validateFormModelRelationships(restored)).toEqual([]) + expect(json).not.toMatch(/\[object /) + }) + + it('rejects invalid payloads and strict relationship failures', () => { + expect(() => parseFormModel(null)).toThrow(/plain object/) + expect(() => parseFormModel({ fields: [] })).toThrow(/fields and widgets/) + expect(() => + parseFormModel({ + fields: [{ id: 'f', type: 'text', name: 'n', widgetIds: ['w'] }], + widgets: [], + }) + ).toThrow(/Invalid form model relationships/) + }) + + it('bridges widgets and overlay elements without copying field values onto placement', () => { + const field = createFormField({ + type: 'signature', + name: 'Signer', + value: null, + required: true, + }) + const widget = createFormWidget({ + fieldId: field.id, + pageIndex: 0, + x: 12, + y: 34, + width: 160, + height: 48, + elementId: 'obj-sig', + }) + + const element = formWidgetToElementObject(widget, field) + expect(element).toEqual({ + id: 'obj-sig', + type: 'signature', + label: 'Signer', + x: 12, + y: 34, + width: 160, + height: 48, + }) + expect(element).not.toHaveProperty('value') + expect(element).not.toHaveProperty('required') + + const placement = elementObjectToFormWidgetPlacement( + { ...element, x: 50, y: 60 }, + { pageIndex: 2, docIndex: 1 } + ) + expect(placement).toEqual({ + x: 50, + y: 60, + width: 160, + height: 48, + pageIndex: 2, + docIndex: 1, + elementId: 'obj-sig', + }) + expect(placement).not.toHaveProperty('value') + }) +}) + +describe('form model validation regressions', () => { + const widget = { + id: 'w', fieldId: 'f', pageIndex: 0, + x: 0, y: 0, width: 10, height: 10, + } + const field = { id: 'f', type: 'text', name: 'name', widgetIds: ['w'] } + + it('rejects missing reverse links and repeated references', () => { + for (const widgetIds of [[], ['w', 'w']]) { + const model = { fields: [{ ...field, widgetIds }], widgets: [widget] } + expect(validateFormModelRelationships(model)).not.toEqual([]) + expect(() => parseFormModel(model)).toThrow(/relationships/) + } + }) + + it.each([ + { fields: [], widgets: [{}] }, + { fields: [{ ...field, required: 'yes' }], widgets: [widget] }, + { fields: [{ ...field, value: {} }], widgets: [widget] }, + { fields: [{ ...field, options: [{}] }], widgets: [widget] }, + { fields: [field], widgets: [{ ...widget, pageIndex: -1 }] }, + { fields: [field], widgets: [{ ...widget, x: Infinity }] }, + { fields: [field], widgets: [{ ...widget, width: -1 }] }, + { fields: [field], widgets: [{ ...widget, id: '' }] }, + ])('rejects malformed properties even with strict disabled: %j', input => { + expect(() => parseFormModel(input)).toThrow() + expect(() => parseFormModel(input, { strict: false })).toThrow() + }) + + it('rejects runtime metadata and cycles before JSON conversion', () => { + for (const metadata of [{ date: new Date() }, { fn: () => {} }, { value: NaN }]) { + expect(() => parseFormModel({ + fields: [{ ...field, metadata }], widgets: [widget], + })).toThrow(/JSON/) + } + const metadata: Record = {} + metadata.self = metadata + expect(() => parseFormModel({ + fields: [{ ...field, metadata }], widgets: [widget], + })).toThrow(/cycles/) + }) + + it('allows strict false to skip only relationship checks', () => { + expect(parseFormModel({ + fields: [{ ...field, widgetIds: [] }], widgets: [widget], + }, { strict: false }).widgets).toEqual([widget]) + }) +}) + +describe('sparse array parsing', () => { + it.each(['value', 'defaultValue', 'options'])('rejects sparse %s arrays', key => { + const input = { + fields: [{ id: 'f', type: 'listbox', name: 'n', widgetIds: [], [key]: new Array(1) }], + widgets: [], + } + expect(() => parseFormModel(input)).toThrow(/sparse/) + expect(() => parseFormModel(input, { strict: false })).toThrow(/sparse/) + }) +})