Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
2 changes: 2 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
166 changes: 166 additions & 0 deletions docs/FORM_MODEL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
<!--
SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
SPDX-License-Identifier: AGPL-3.0-or-later
-->

# 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<string, unknown>` | 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<string, unknown>` | 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.
32 changes: 32 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -13,6 +36,15 @@ export type {
PDFElementsAddingEndedPlacedPayload,
PDFElementsAddingEndedReason,
PDFElementsPublicApi,
PDFFormField,
PDFFormFieldId,
PDFFormFieldKnownType,
PDFFormFieldOption,
PDFFormFieldType,
PDFFormFieldValue,
PDFFormModel,
PDFFormWidget,
PDFFormWidgetId,
} from './types'

const install = (app: App) => {
Expand Down
102 changes: 102 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>
}

/**
* 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<string, unknown>
}

/**
* 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[]
}
Loading
Loading