/** * What this session asked for and the engine hasn't answered, on top of the * form: `predictFormOp`, the fields mirror's `predict` (the view replays it * op by op), and `undoLookOf`, what undoing a change looks like. Both follow * the engine's own rules (engine-core's form prediction helpers). Pure. */ import type { PredictedOp } from '@embedpdf/core'; import { annotationKey, fieldAfterReset, fieldAfterValue, formFieldAfter, formFieldOfDraft, planFormCopies, reorderedList, widgetAfterPatch, widgetsAfterDisplay, type AnnotationRef, type FieldWithWidgets, type FormField, type FormFieldDraft, type FormFieldRef, type FormWidget, type PlannedFieldCopy, type WidgetAnnotation, } from '@embedpdf/engine-core/runtime'; import { fieldByKey, fieldByRef, fieldForWidget, fieldKeyOf, fieldKeyOfRef, indexFields, removeField, removeWidgets, reorderWidgetRows, upsertFields, upsertWidgets, widgetRowOf, withCalculationOrder, type FieldIndex, type FieldKey, } from '../model'; const widgetNumber = (widget: WidgetAnnotation): number => widget.ref.kind === 'objectNumber' ? widget.ref.objectNumber : 0; /** The rows of a field's widgets, in its widget order. */ function rowsOfField(index: FieldIndex, field: FormField): WidgetAnnotation[] { return field.widgets.flatMap((widget) => { const row = widgetRowOf(index, widget.objectNumber); return row ? [row] : []; }); } /** A field and the rows of its widgets, as the index holds them. */ const withRows = (index: FieldIndex, field: FormField): FieldWithWidgets => ({ field, widgets: rowsOfField(index, field), }); /** Fields and their widget rows put into the index, all at once. */ function withFields(index: FieldIndex, parts: readonly FieldWithWidgets[]): FieldIndex { if (parts.length === 0) return index; return upsertWidgets( upsertFields( index, parts.map((part) => part.field), ), parts.flatMap((part) => part.widgets), ); } /** What a prediction takes from the session the change is staged in. */ export interface PredictionContext { /** The session's own group, where a new field goes when its draft names none; `null` for none. */ readonly groupId: string | null; } /** No session: a new field whose draft names no group shows in none. */ const NO_SESSION: PredictionContext = { groupId: null }; /** The fields a reset of the whole form puts back: the ones that hold a value. */ const resetTargets = (index: FieldIndex): FormField[] => (index.snapshot?.fields ?? []).filter((field) => RESET_FAMILIES.has(field.kind)); const RESET_FAMILIES = new Set(['text', 'checkbox', 'radio', 'combobox', 'listbox']); /** * One op of a change this session staged, shown before the engine answers, * by the engine's own rules (`fieldAfterValue`, `fieldAfterReset`, * `widgetsAfterDisplay`, `formFieldOfDraft`, `formFieldAfter`, * `widgetAfterPatch`): what the fields and their widgets hold after it. An op * those rules refuse shows nothing; one whose values only the engine's schemas * refuse shows until the engine's refusal takes the change away. * A create, a copy and a new widget show once they name their numbers; taking * a widget out of its field shows once the engine answers. * * The view replays every pending change each time any change is staged; the * same op over the same form gives the same form, so a field keeps its object * while nothing about it changed. */ export function predictFormOp( index: FieldIndex, op: PredictedOp, context: PredictionContext = NO_SESSION, ): FieldIndex { let byOp = predictions.get(index); const known = byOp?.get(op); if (known) return known; const next = predictOnce(index, op, context); if (!byOp) predictions.set(index, (byOp = new WeakMap())); byOp.set(op, next); return next; } // Kept by form and op alone. Both belong to one session, whose context never changes, so every // prediction of a session has to be made with that session's context: `createFormPredictor`. const predictions = new WeakMap>(); function predictOnce(index: FieldIndex, op: PredictedOp, context: PredictionContext): FieldIndex { try { switch (op.type) { case 'forms.setValue': { const field = fieldByRef(index, op.field); return field ? withFields(index, [fieldAfterValue(withRows(index, field), op.value)]) : index; } case 'forms.reset': { const targets = op.fields ? op.fields.flatMap((ref) => fieldByRef(index, ref) ?? []) : resetTargets(index); return withFields( index, targets.map((field) => fieldAfterReset(withRows(index, field))), ); } case 'forms.setDisplay': { const field = fieldByRef(index, op.field); if (!field) return index; return upsertWidgets(index, widgetsAfterDisplay(rowsOfField(index, field), op.display)); } case 'forms.restore': return withFields(index, [op]); case 'forms.restoreWidget': { const restored = upsertWidgets(index, [op.widget]); return op.field ? upsertFields(restored, [op.field]) : restored; } case 'forms.create': return createdField(index, op, context); case 'forms.copy': return copiedFields(index, op, context); case 'forms.addWidget': return addedWidget(index, op); case 'forms.update': { const field = fieldByRef(index, op.field); return field ? withFields(index, [formFieldAfter(withRows(index, field), op.patch)]) : index; } case 'forms.delete': { const field = fieldByRef(index, op.field); if (!field || !index.snapshot) return index; const gone = removeWidgets(removeField(index, field.ref), field.widgets); return withCalculationOrder( gone, index.snapshot.calculationOrder.filter((ref) => !sameField(ref, field.ref)), ); } case 'forms.updateWidget': { const row = rowOfRef(index, op.widget); return row ? upsertWidgets(index, [widgetAfterPatch(row, op.patch)]) : index; } case 'forms.deleteWidget': { const row = rowOfRef(index, op.widget); if (!row) return index; const number = widgetNumber(row); const field = fieldForWidget(index, number); const gone = removeWidgets(index, [{ objectNumber: number, page: row.page } as FormWidget]); if (!field) return gone; const widgets = field.widgets.filter((widget) => widget.objectNumber !== number); return upsertFields(gone, [{ ...field, widgets } as FormField]); } case 'forms.reorderWidgets': { if (!index.snapshot) return index; const onPage = index.snapshot.widgets .filter((row) => row.page.objectNumber === op.page.objectNumber) .map((row) => row.ref); const order = reorderedList(onPage, op.widgets, op.position, annotationKey); return reorderWidgetRows(index, op.page, order); } case 'forms.reorderCalculations': { if (!index.snapshot) return index; const order = index.snapshot.calculationOrder.filter( (ref): ref is FormFieldRef => ref !== null, ); return withCalculationOrder( index, reorderedList(order, op.fields, op.position, fieldKeyOfRef), ); } default: return index; } } catch { return index; } } /** A widget's row, by its annotation ref. */ const rowOfRef = (index: FieldIndex, ref: AnnotationRef): WidgetAnnotation | null => ref.kind === 'objectNumber' ? widgetRowOf(index, ref.objectNumber) : null; const sameField = (left: FormFieldRef | null, right: FormFieldRef): boolean => left !== null && fieldKeyOfRef(left) === fieldKeyOfRef(right); /** * `forms.create`, once it names the numbers it takes: the field and its * widgets as a read of them returns them, last in the form, and last in the * calculation order when it calculates. */ function createdField( index: FieldIndex, op: Extract, context: PredictionContext, ): FieldIndex { const placements = op.draft.widgets ?? []; const numbers = op.widgetObjectNumbers ?? []; if (op.objectNumber === undefined || numbers.length !== placements.length) return index; const snapshot = index.snapshot; if (!snapshot || fieldByRef(index, { kind: 'objectNumber', objectNumber: op.objectNumber })) { return index; } const created = formFieldOfDraft(op.draft, { objectNumber: op.objectNumber, widgets: placements.map((placement, at) => ({ kind: 'objectNumber' as const, page: placement.page, objectNumber: numbers[at]!, })), // A draft that names no group goes in the session's own, as the engine puts it. groupId: context.groupId, }); // The first field of a document without a form creates its /AcroForm. const formed = snapshot.formKind === 'none' ? indexFields({ ...snapshot, formKind: 'acroform' }, index.pictureVersions) : index; const next = withFields(formed, [created]); return op.draft.actions?.calculate ? withCalculationOrder(next, [...snapshot.calculationOrder, created.field.ref]) : next; } /** One field a `forms.copy` makes, with the numbers the op names for it. */ interface FieldCopy extends PlannedFieldCopy { readonly objectNumber: number; readonly widgetObjectNumbers: readonly number[]; } /** * The fields a `forms.copy` makes, by the engine's own rule * (`planFormCopies`), each with the object numbers the op names: its own, * then its widgets'. None for a copy that doesn't name them all, which * shows when the engine answers, and none for one the engine would refuse. * What a script right leaves out is the engine's to say: nothing of it shows. */ function copiesOf( index: FieldIndex, op: Extract, ): FieldCopy[] { const { snapshot } = index; if (!snapshot || !op.objectNumbers) return []; let creates: readonly PlannedFieldCopy[]; try { creates = planFormCopies({ form: snapshot, fields: op.fields, ...(op.widgets ? { widgets: op.widgets } : {}), placement: { ...(op.page ? { page: op.page } : {}), ...(op.offset ? { offset: op.offset } : {}), }, values: op.values ?? true, mayScript: true, }).creates; } catch { return []; } const needed = creates.reduce((count, create) => count + 1 + create.widgets.length, 0); if (op.objectNumbers.length !== needed) return []; let at = 0; return creates.map((create) => { const [objectNumber, ...widgetObjectNumbers] = op.objectNumbers!.slice( at, at + 1 + create.widgets.length, ); at += 1 + create.widgets.length; return { ...create, objectNumber: objectNumber!, widgetObjectNumbers }; }); } /** * `forms.copy`: each copy as a create of the same field shows (`createdField`), * then its widgets' flags, which a create writes none of, and its value. */ function copiedFields( index: FieldIndex, op: Extract, context: PredictionContext, ): FieldIndex { let next = index; for (const copy of copiesOf(index, op)) { const ref: FormFieldRef = { kind: 'objectNumber', objectNumber: copy.objectNumber }; if (fieldByRef(next, ref)) continue; next = createdField( next, { type: 'forms.create', draft: copy.draft, objectNumber: copy.objectNumber, widgetObjectNumbers: copy.widgetObjectNumbers, }, context, ); const made = fieldByRef(next, ref); if (!made) continue; next = upsertWidgets( next, rowsOfField(next, made).map((row, at) => widgetAfterPatch(row, copy.flags[at] ?? {})), ); if (copy.value) next = withFields(next, [fieldAfterValue(withRows(next, made), copy.value)]); } return next; } /** * `forms.addWidget`, once it names its widget's number: the widget as a * create of a field of that kind places it, last among the field's. One that * splits a merged field (the field's own widget moves to a new number) shows * when the engine answers. */ function addedWidget( index: FieldIndex, op: Extract, ): FieldIndex { if (op.objectNumber === undefined || op.splitObjectNumber !== undefined) return index; const field = fieldByRef(index, op.field); if (!field || field.kind === 'unknown' || field.ref.kind !== 'objectNumber') return index; if (widgetRowOf(index, op.objectNumber)) return index; const options = 'options' in field ? { options: field.options.map(({ label, value }) => ({ label, value })) } : {}; const made = formFieldOfDraft( { kind: field.kind, name: field.name, ...options, widgets: [op.placement] } as FormFieldDraft, { objectNumber: field.ref.objectNumber, widgets: [{ kind: 'objectNumber', page: op.placement.page, objectNumber: op.objectNumber }], }, ); const [widget] = made.field.widgets; const [row] = made.widgets; if (!widget || !row) return index; return upsertWidgets( upsertFields(index, [{ ...field, widgets: [...field.widgets, widget] } as FormField]), [row], ); } /** The fields a change's ops write a value or a look to, each once, in op order. */ export function fieldsNamedBy(index: FieldIndex, ops: readonly PredictedOp[]): FormField[] { const named = new Map(); const add = (field: FormField | null): void => { if (field && !named.has(fieldKeyOf(field))) named.set(fieldKeyOf(field), field); }; for (const op of ops) { switch (op.type) { case 'forms.setValue': case 'forms.setDisplay': case 'forms.setAppearanceText': add(fieldByRef(index, op.field)); break; case 'forms.reset': for (const field of op.fields ? op.fields.map((ref) => fieldByRef(index, ref)) : resetTargets(index)) { add(field); } break; default: break; } } return [...named.values()]; } /** `index` with these fields, and their widget rows, as `source` holds them. */ export function withFieldsFrom( index: FieldIndex, source: FieldIndex, fields: readonly FormField[], ): FieldIndex { return withFields( index, fields.flatMap((field) => { const held = fieldByKey(source, fieldKeyOf(field)); return held ? [withRows(source, held)] : []; }), ); } /** A field and its widgets back as `index` holds them. */ const restoreOf = (index: FieldIndex, field: FormField): PredictedOp => ({ type: 'forms.restore', field, widgets: rowsOfField(index, field), }); /** A widget's row back as `index` holds it, with its field as it is there. */ const restoreWidgetOf = (index: FieldIndex, row: WidgetAnnotation): PredictedOp => ({ type: 'forms.restoreWidget', widget: row, field: fieldForWidget(index, widgetNumber(row)), }); /** What undoing one op looks like, over the form it applies to. */ function undoOfOp(index: FieldIndex, op: PredictedOp): PredictedOp[] { switch (op.type) { case 'forms.create': return op.objectNumber === undefined ? [] : [ { type: 'forms.delete', field: { kind: 'objectNumber', objectNumber: op.objectNumber }, }, ]; case 'forms.copy': // The copies go, the last made first. return copiesOf(index, op) .map( (copy): PredictedOp => ({ type: 'forms.delete', field: { kind: 'objectNumber', objectNumber: copy.objectNumber }, }), ) .reverse(); case 'forms.addWidget': return op.objectNumber === undefined ? [] : [ { type: 'forms.deleteWidget', widget: { kind: 'objectNumber', page: op.placement.page, objectNumber: op.objectNumber, }, }, ]; case 'forms.update': case 'forms.delete': { const field = fieldByRef(index, op.field); return field ? [restoreOf(index, field)] : []; } case 'forms.updateWidget': case 'forms.deleteWidget': { const row = rowOfRef(index, op.widget); return row ? [restoreWidgetOf(index, row)] : []; } case 'forms.removeWidget': { const field = fieldByRef(index, op.field); const row = rowOfRef(index, op.widget); return [ ...(row ? [restoreWidgetOf(index, row)] : []), ...(field ? [restoreOf(index, field)] : []), ]; } case 'forms.reorderWidgets': { // The page's whole order as it was. const widgets = (index.snapshot?.widgets ?? []) .filter((row) => row.page.objectNumber === op.page.objectNumber) .map((row) => row.ref); return [{ type: 'forms.reorderWidgets', page: op.page, widgets, position: 'start' }]; } case 'forms.reorderCalculations': { const fields = (index.snapshot?.calculationOrder ?? []).filter( (ref): ref is FormFieldRef => ref !== null, ); return [{ type: 'forms.reorderCalculations', fields, position: 'start' }]; } default: return fieldsNamedBy(index, [op]).map((field) => restoreOf(index, field)); } } /** * What undoing `ops` looks like, read off the form they apply to, each over * what the ones before it left: the ops that bring the form back, the last * op's first. Drawing only: the engine undoes a change by its own record of * it. */ export function undoLookOf( before: FieldIndex, ops: readonly PredictedOp[], context: PredictionContext = NO_SESSION, ): PredictedOp[] { const undo: PredictedOp[][] = []; let current = before; for (const op of ops) { undo.push(undoOfOp(current, op)); current = predictFormOp(current, op, context); } return undo.reverse().flat(); } /** The predictions of one session. */ export interface FormPredictor { /** {@link predictFormOp}, as this session's change shows. */ readonly predict: (index: FieldIndex, op: PredictedOp) => FieldIndex; /** {@link undoLookOf}, over this session's changes. */ readonly undoLook: (before: FieldIndex, ops: readonly PredictedOp[]) => PredictedOp[]; } /** * The predictions of one session, whose context `session` reads. Everything in the plugin that * predicts goes through it: a prediction is kept by its form and op, so one made without the * session's context would be the one the view then shows. */ export function createFormPredictor(session: () => PredictionContext): FormPredictor { return { predict: (index, op) => predictFormOp(index, op, session()), undoLook: (before, ops) => undoLookOf(before, ops, session()), }; }