Skip to content
Draft
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) Β· [Form model](docs/FORM_MODEL.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) Β· [Form editing](docs/FORM_EDITING.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 @@ -51,5 +51,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)
- [Form field editing](docs/FORM_EDITING.md)
- [Basic example](examples/basic/)
- [Contributing](CONTRIBUTING.md)
9 changes: 9 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later

For the logical field / visual widget data model (plain serializable types, relationships and overlay coexistence), see [Form field and widget model](./FORM_MODEL.md).

For generic form-field editing on top of that model (create/place/select/update, multi-widget fields, overlay sync), see [Form field editing](./FORM_EDITING.md).

## Props

| Prop | Type | Default | Description |
Expand Down Expand Up @@ -49,6 +51,13 @@ For the logical field / visual widget data model (plain serializable types, rela

- `startAddingElement(templateObject)` - Starts interactive placement mode.
- `cancelAdding()` - Cancels the current placement session and emits `pdf-elements:adding-ended` with `{ reason: 'cancelled' }` when a session was active.
- `addObjectToPage(object, pageIndex?, docIndex?)` - Places an overlay object programmatically.
- `getAllObjects(docIndex?)` - Returns overlay objects for a document.
- `updateObject(docIndex, objectId, payload)` - Updates overlay geometry or properties.
- `moveObjectToPage(docIndex, objectId, pageIndex, payload?)` - Moves an object between pages without emitting `pdf-elements:delete-object`.
- `deleteObject(docIndex, objectId)` / `duplicateObject(docIndex, objectId)` - Overlay lifecycle helpers.

Form-field editing is not stored inside the Vue component. Use `createFormEditor({ overlay })` from the package entry and pass these methods through a `FormEditorOverlayAdapter`. See [Form field editing](./FORM_EDITING.md).

## Slots

Expand Down
156 changes: 156 additions & 0 deletions docs/FORM_EDITING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<!--
SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
SPDX-License-Identifier: AGPL-3.0-or-later
-->

# Form field editing

Generic editing behavior for the [field/widget model](./FORM_MODEL.md). The editor is a plain TypeScript session: it owns a `PDFFormModel`, tracks logical selection, and optionally syncs visuals through the existing overlay API. It does not read Vue component internals.

Concrete per-type controls (text input UX, checkbox toggling, radio exclusive selection UI, dropdown pickers) are out of scope here. Hosts reuse this foundation when adding those types.

## Concepts

| Concern | Owner |
|---------|--------|
| Shared field data (`value`, `required`, `options`, …) | `PDFFormField` via `createField` / `updateField` |
| Placement and widget-only data (`exportValue`, geometry) | `PDFFormWidget` via `placeWidget` / `updateWidget` |
| Visual rectangles | Optional `FormEditorOverlayAdapter` β†’ `PDFElements` methods |
| Logical selection | `selectField` / `selectWidget` on the editor session |

One field may have many widgets. Selecting a widget also selects its field. Non-form overlays continue to use `PDFElementObject` alone.

## Quick start

```ts
import {
createFormEditor,
createFormEditorOverlayAdapter,
type PDFElementsPublicApi,
} from '@libresign/pdf-elements'

const overlay = pdfRef.value as PDFElementsPublicApi
const editor = createFormEditor({
// Prefer the helper: it recovers rewritten ids after addObjectToPage collisions.
overlay: createFormEditorOverlayAdapter(overlay),
})

const field = editor.createField({
type: 'radio',
name: 'color',
options: [
{ value: 'red', label: 'Red' },
{ value: 'blue', label: 'Blue' },
],
required: true,
})

editor.placeWidget({
fieldId: field.id,
pageIndex: 0,
x: 40,
y: 80,
width: 18,
height: 18,
exportValue: 'red',
})

editor.placeWidget({
fieldId: field.id,
pageIndex: 1,
x: 40,
y: 120,
width: 18,
height: 18,
exportValue: 'blue',
})

editor.selectWidget(editor.getWidgetsForField(field.id)[0].id)
editor.updateField(field.id, { value: 'red' })
```

## Interactive placement

1. `editor.beginPlaceWidget({ fieldId, width, height, exportValue })` starts overlay placement when an adapter with `startAddingElement` is configured.
2. Listen for `pdf-elements:adding-ended`.
3. On `{ reason: 'placed', object, pageIndex, docIndex }`, call `editor.completeWidgetPlacement({ object, pageIndex, docIndex })`.
4. On cancel, call `editor.cancelPlaceWidget()` (also used if the host cancels placement).

`completeWidgetPlacement` only updates the form model and links `widget.elementId` to the placed overlay id. It does not add a second overlay rectangle.

`loadModel` and a second `beginPlaceWidget` cancel any in-progress overlay adding session before replacing editor state.

## Move / resize

Supported foundation path: programmatic `updateWidget` (optionally synced to the overlay) and host-driven `syncFromOverlay` when the host already knows the new geometry.

`PDFElements` drag/resize currently updates overlays internally without a dedicated public geometry event. Until such an event exists, hosts that need canvas drag to update the form model must observe their own integration points and call:

```ts
editor.syncFromOverlay(object, { pageIndex, docIndex })
```

Matching uses `widget.elementId`. `widget.id` is used only when `elementId` is absent.

When deleting from the overlay UI, listen for `pdf-elements:delete-object` and call `editor.removeWidget(...)` (or `removeField`) so the model stays aligned. Skip that removal while `overlay.isInternalMutation?.()` is true: spill rollback may restore page membership without a user delete. Prefer `createFormEditorOverlayAdapter`, which uses `moveObjectToPage` (no delete event) for that restore.

### Page / document changes

With overlay sync enabled, `updateWidget` **rejects** `pageIndex` / `docIndex` / `elementId` changes. Relocate by removing and re-placing the widget, or pass `{ syncOverlay: false }` and update visuals yourself.

Programmatic geometry updates that would make `PDFElements` move the rectangle to another page are treated as failure by `createFormEditorOverlayAdapter`: the helper restores the object on the original page via `moveObjectToPage` (without emitting `pdf-elements:delete-object`), then returns `false` so the editor rolls the widget back.

`loadModel` and editor construction reject models that reuse the same `elementId` inside one document. Changing `docIndex` with `{ syncOverlay: false }` also re-checks that invariant.

## Model access

| Method | Meaning |
|--------|---------|
| `getModel()` | Live session store. Mutating it bypasses overlay sync and editor invariants. |
| `getSnapshot()` | Deep JSON clone for persistence / transport. |
| `loadModel(...)` | Replaces the session via `parseFormModel` (relationship checks included) and cancels placement. |

`createField` does not accept pre-filled `widgetIds`. Attach visuals with `placeWidget`.

## Overlay adapter notes

- Prefer `createFormEditorOverlayAdapter(pdf)` so rewritten ids after collisions are recovered.
- That helper also re-reads overlay geometry after `updateObject`. If `PDFElements` drops or relocates the write, the helper restores the previous geometry when possible and returns `false`, so the editor can roll the widget back.
- If you hand-roll an adapter, return the **stored** object from `addObjectToPage` whenever ids may change. Returning bare `true` is only safe when the submitted id was kept.
- Optional `hasObject(docIndex, objectId, pageIndex?)` lets the editor link to an existing rectangle without inserting a duplicate.
- An `elementId` may be linked to only one widget. `syncFromOverlay` / `getWidgetByElementId` accept `docIndex` when the same id appears in more than one document.
- Optional `updateObject` may return `false` to reject geometry; the editor then rolls the widget back.
- If `updateObject` / `deleteObject` are omitted, model edits still succeed and overlay cleanup is skipped (orphan overlays possible).

Session `bridgeOptions` and per-`placeWidget` / `beginPlaceWidget` `bridgeOptions` (`type` / `label`) are remembered for appearance sync after `updateField`.

## Public surface

```ts
import {
createFormEditor,
createFormEditorOverlayAdapter,
} from '@libresign/pdf-elements'
import type {
FormEditorOverlayAdapter,
FormEditorSelection,
FormFieldUpdate,
FormWidgetUpdate,
PDFFormEditor,
} from '@libresign/pdf-elements'
```

| Method | Role |
|--------|------|
| `createField` / `updateField` / `removeField` | Field lifecycle and shared properties |
| `placeWidget` / `updateWidget` / `removeWidget` | Widget lifecycle and placement |
| `beginPlaceWidget` / `completeWidgetPlacement` / `cancelPlaceWidget` | Interactive placement |
| `selectField` / `selectWidget` / `getSelection` | Logical selection |
| `syncFromOverlay` | Copy overlay geometry onto the linked widget |
| `getModel` / `getSnapshot` / `loadModel` | Live store vs persistence |

## Compatibility

- Generic signature/annotation overlays keep using `PDFElements` as before.
- Form editing is additive: omit the overlay adapter for model-only editing.
- Do not store LibreSign/Nextcloud workflow concepts on fields or widgets; use `metadata` or host state outside this package.
6 changes: 3 additions & 3 deletions docs/FORM_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ If a host previously encoded form semantics only on overlay objects (for example

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).
3. Optionally set `elementId` to the existing overlay object id so the editor can keep using `PDFElementObject` while adopting form editing ([Form field editing](./FORM_EDITING.md)).
4. Stop duplicating field-level properties onto each overlay object once the form model is the source of truth.

## Out of scope
Expand All @@ -154,9 +154,9 @@ This package model does **not** implement:

- PDF AcroForm parsing or writing
- PDF mutation or cryptographic signing
- Full per-type editor behavior (tracked separately)
- Full per-type editor behavior (text/checkbox/radio/dropdown UX)

Those belong outside this issue and, for editor behavior, in follow-up work that builds on this model.
Generic create/place/select/update editing that reuses this model lives in [Form field editing](./FORM_EDITING.md). Per-type controls remain follow-up work.

Parsing validates required properties, finite geometry, non-negative integer page/document
indices, non-negative sizes and plain JSON data (including metadata). Runtime objects,
Expand Down
46 changes: 46 additions & 0 deletions src/components/PDFElements.vue
Original file line number Diff line number Diff line change
Expand Up @@ -1196,6 +1196,52 @@ export default defineComponent({
this.updateObjectInPage(docIndex, currentPageIndex, objectId, payload)
},

moveObjectToPage(docIndex, objectId, pageIndex, payload = {}) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return false
const doc = this.pdfDocuments[docIndex]
if (pageIndex < 0 || pageIndex >= doc.pages.length) return false

const cacheKey = `${docIndex}-${objectId}`
let currentPageIndex = this.objectIndexCache[cacheKey]
if (currentPageIndex === undefined) {
currentPageIndex = findObjectPageIndex(doc, objectId)
if (currentPageIndex !== undefined) {
this.objectIndexCache[cacheKey] = currentPageIndex
}
}
if (currentPageIndex === undefined) return false

const currentObjects = doc.allObjects[currentPageIndex]
const objectIndex = currentObjects?.findIndex((object) => object.id === objectId) ?? -1
if (!currentObjects || objectIndex === -1) return false

const currentObject = currentObjects[objectIndex]
const nextObject = {
...currentObject,
...payload,
id: objectId,
}
const { width: pageWidth, height: pageHeight } = this.getPageSize(docIndex, pageIndex)
if (
nextObject.x < 0
|| nextObject.y < 0
|| nextObject.x + nextObject.width > pageWidth
|| nextObject.y + nextObject.height > pageHeight
) {
return false
}

if (currentPageIndex === pageIndex) {
currentObjects.splice(objectIndex, 1, nextObject)
return true
}

currentObjects.splice(objectIndex, 1)
doc.allObjects[pageIndex].push(nextObject)
this.objectIndexCache[cacheKey] = pageIndex
return true
},

deleteObject(docIndex, objectId) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return
const doc = this.pdfDocuments[docIndex]
Expand Down
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,28 @@ export {
serializeFormModel,
validateFormModelRelationships,
} from './utils/formModel'
export {
createFormEditor,
createFormEditorOverlayAdapter,
} from './utils/formEditing'
export type {
CreateFormFieldInput,
CreateFormWidgetInput,
FormModelRelationshipIssue,
FormWidgetToElementOptions,
} from './utils/formModel'
export type {
BeginPlaceWidgetInput,
CompleteWidgetPlacementInput,
CreateFormEditorOptions,
FormEditorAddObjectResult,
FormEditorOverlayAdapter,
FormEditorSelection,
FormFieldUpdate,
FormWidgetUpdate,
PDFFormEditor,
PlaceFormWidgetOptions,
} from './utils/formEditing'
export type {
PDFDocumentEntry,
PDFElementObject,
Expand Down
12 changes: 12 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ export interface PDFElementsPublicApi {
addObjectToPage: (object: PDFElementObject, pageIndex?: number, docIndex?: number) => boolean
getAllObjects: (docIndex?: number) => PDFElementObject[]
updateObject: (docIndex: number, objectId: string, payload: Partial<PDFElementObject>) => void
/**
* Moves an overlay object to another page in the same document without emitting
* `pdf-elements:delete-object`. Used for internal restoration (for example form
* editor spill rollback) so hosts do not treat the move as a user delete.
* Optional for 1.x typed wrappers; {@link PDFElements} implements it.
*/
moveObjectToPage?: (
docIndex: number,
objectId: string,
pageIndex: number,
payload?: Partial<PDFElementObject>
) => boolean
deleteObject: (docIndex: number, objectId: string) => void
duplicateObject: (docIndex: number, objectId: string) => void
cancelAdding: () => void
Expand Down
Loading
Loading