import { describe, expect, test } from 'vitest'; import { widgetActionsAfter, type PdfActionNode, type PdfActionTree, } from '../../src/dto/PdfAction'; import { EngineErrorCode } from '../../src/errors/EngineErrorCode'; import { withButtonImage } from '../../src/forms/buttonImage'; import { draftWritesScripts, type FormFieldDraft } from '../../src/forms/draft'; import type { FormField } from '../../src/forms/field'; import { formFieldAfter, formFieldOfDraft, type FieldWithWidgets } from '../../src/forms/predict'; import { FormFieldDraftSchema, FormFieldDTOSchema, FormFieldPatchSchema, } from '../../src/forms/schema'; import { assertTakesImage, assertTakesImageDraft, IMPORT_ICON_SCRIPT, imageFieldWidgetActions, importIconAction, isImportIconScript, pressHasAction, pressImportsIcon, pressPatchOf, pressWriteOf, takesImageOf, takesImageWriteOf, } from '../../src/forms/takesImage'; import { annotationOfDraft } from '../../src/pageSpace/helpers'; import { completeFormBundle } from '../../src/transfer/FormBundle'; import { BUTTON_IMAGE_AND_LAYOUT_SINCE } from '../../src/wire/apiVersion'; import { ChangeOpWireSchema } from '../../src/wire/changeSchemas'; const PAGE = { kind: 'objectNumber', objectNumber: 3 } as const; /** A tree as a read gives it: `node`, and what runs after it. */ const tree = (node: Record, next: Record[] = []): PdfActionTree => ({ root: { subtype: '', ...node, next: next.map((child) => ({ subtype: '', next: [], ...child })), } as unknown as PdfActionNode, incomplete: false, warnings: [], }) as PdfActionTree; const scriptOf = (script: string) => tree({ type: 'javascript', script }); const IMPORTS = scriptOf(IMPORT_ICON_SCRIPT); const BEEPS = scriptOf('app.beep(0);'); const NEXT_PAGE = tree({ type: 'named', name: 'NextPage' }); const refused = (run: () => unknown) => { try { run(); return null; } catch (error) { const { code, details } = error as { code?: string; details?: { field?: string } }; return [code, details?.field]; } }; const OVER_THE_FACT = [EngineErrorCode.InvalidArg, 'takesImage']; describe("Acrobat's import-icon script", () => { test('is the call and nothing else, as Acrobat writes it', () => { expect(IMPORT_ICON_SCRIPT).toBe('event.target.buttonImportIcon();'); expect(isImportIconScript(IMPORT_ICON_SCRIPT)).toBe(true); expect(importIconAction()).toEqual({ type: 'javascript', script: IMPORT_ICON_SCRIPT }); }); test('with white space wherever a script allows it, and with or without the semicolon', () => { for (const script of [ 'event.target.buttonImportIcon()', ' event.target.buttonImportIcon(); ', 'event.target.buttonImportIcon ( ) ;', 'event . target . buttonImportIcon()', 'event\n .target\n .buttonImportIcon(\n);\n', '\tevent.target.buttonImportIcon()\r\n', ]) { expect([script, isImportIconScript(script)]).toEqual([script, true]); } }); test('and no near miss', () => { for (const script of [ '', 'event.target.buttonImportIcon', 'event.target.buttonImportIcon();;', 'event.target.buttonImportIcon(); app.beep(0);', 'app.beep(0); event.target.buttonImportIcon();', 'event.target.buttonImportIcon("photo.png");', 'event.target.buttonImportIcon(0);', 'this.getField("photo").buttonImportIcon();', 'event.source.buttonImportIcon();', 'event.target.buttonimporticon();', 'event.target.buttonImportIcon2();', 'xevent.target.buttonImportIcon();', 'event.target.button ImportIcon();', 'if (true) event.target.buttonImportIcon();', '(event.target.buttonImportIcon());', 'event.target.buttonImportIcon(); // ask for a picture', '/* ask */ event.target.buttonImportIcon();', 'var r = event.target.buttonImportIcon();', ]) { expect([script, isImportIconScript(script)]).toEqual([script, false]); } }); test('a long script from a file is read in one pass', () => { // A pattern that lets two runs of white space share one run of spaces takes minutes here. const spaces = ' '.repeat(200_000); const started = performance.now(); for (const [script, expected] of [ [`${spaces}event.target.buttonImportIcon()${spaces}`, true], [`event${spaces}.target.buttonImportIcon(${spaces});${spaces}`, true], [`event.target.buttonImportIcon()${spaces}x`, false], [`event.target.buttonImportIcon();${spaces}x`, false], [`event.target.buttonImportIcon(${spaces})${spaces};${spaces};`, false], [`${spaces}x`, false], ] as const) { expect(isImportIconScript(script)).toBe(expected); } expect(performance.now() - started).toBeLessThan(2_000); }); }); describe("a widget's press", () => { test('is the import script on one of its two events, and nothing on the other', () => { expect(pressImportsIcon({ activate: IMPORTS })).toBe(true); expect(pressImportsIcon({ mouseUp: IMPORTS })).toBe(true); expect( pressImportsIcon({ activate: scriptOf(' event . target . buttonImportIcon ( ) ') }), ).toBe(true); }); test("other events of the widget don't count either way", () => { const others = { cursorEnter: BEEPS, cursorExit: BEEPS, focus: BEEPS, blur: BEEPS }; expect(pressImportsIcon({ activate: IMPORTS, ...others, mouseDown: BEEPS } as never)).toBe( true, ); expect(pressImportsIcon({ ...others, mouseDown: IMPORTS } as never)).toBe(false); expect(pressHasAction({ ...others, mouseDown: BEEPS } as never)).toBe(false); }); test('anything else is none', () => { const none: (Parameters[0] | unknown)[] = [ null, undefined, {}, { activate: BEEPS }, { activate: NEXT_PAGE }, // The script on both events. { activate: IMPORTS, mouseUp: IMPORTS }, { activate: IMPORTS, mouseUp: BEEPS }, // The script with more statements, and with an action after it. { activate: scriptOf('event.target.buttonImportIcon(); app.beep(0);') }, { activate: tree({ type: 'javascript', script: IMPORT_ICON_SCRIPT }, [ { type: 'named', name: 'NextPage' }, ]), }, // After another action. { activate: tree({ type: 'named', name: 'NextPage' }, [ { type: 'javascript', script: IMPORT_ICON_SCRIPT }, ]), }, // A tree the read could not finish is never taken for it. { activate: { ...IMPORTS, incomplete: true } }, { activate: { root: null, incomplete: true, warnings: ['incomplete'] } }, // A body not yet checked. { activate: 'event.target.buttonImportIcon();' }, { activate: { root: { type: 'javascript', script: 7, next: [] }, incomplete: false } }, { activate: { root: { type: 'javascript', script: IMPORT_ICON_SCRIPT }, incomplete: false } }, ]; for (const press of none) { expect([press, pressImportsIcon(press as never)]).toEqual([press, false]); } }); test('has an action when one of its two events holds one', () => { expect(pressHasAction(null)).toBe(false); expect(pressHasAction({})).toBe(false); expect(pressHasAction({ activate: BEEPS })).toBe(true); expect(pressHasAction({ mouseUp: NEXT_PAGE })).toBe(true); }); }); describe('a push button takes an image', () => { test('when it has a widget and every widget has the script', () => { expect(takesImageOf([{ activate: IMPORTS }])).toBe(true); expect(takesImageOf([{ activate: IMPORTS }, { mouseUp: IMPORTS }])).toBe(true); }); test('and not with no widget, a widget without it, or a widget that could not be read', () => { expect(takesImageOf([])).toBe(false); expect(takesImageOf([{ activate: IMPORTS }, {}])).toBe(false); expect(takesImageOf([{ activate: IMPORTS }, null])).toBe(false); expect(takesImageOf([{ activate: IMPORTS }, { activate: BEEPS }])).toBe(false); }); }); describe('a write of the fact', () => { test('names true or false on a push button, and is none when left out', () => { expect(takesImageWriteOf({ takesImage: true }, 'pushbutton')).toBe(true); expect(takesImageWriteOf({ takesImage: false }, 'pushbutton')).toBe(false); expect(takesImageWriteOf({}, 'pushbutton')).toBe(undefined); expect(takesImageWriteOf({}, 'text')).toBe(undefined); }); test('is refused on another kind, and with a value that is no yes or no', () => { for (const kind of ['text', 'checkbox', 'radio', 'combobox', 'listbox', 'signature'] as const) { for (const takesImage of [true, false]) { expect(refused(() => takesImageWriteOf({ takesImage }, kind))).toEqual(OVER_THE_FACT); } } for (const takesImage of [null, 'yes', 1, {}]) { expect(refused(() => takesImageWriteOf({ takesImage }, 'pushbutton'))).toEqual(OVER_THE_FACT); } }); test('on a create, goes beside no press action of a widget, and true needs a widget', () => { const action = { type: 'named', name: 'NextPage' } as const; expect( refused(() => assertTakesImageDraft(undefined, [{ actions: { activate: action } }])), ).toBe(null); expect(refused(() => assertTakesImageDraft(true, [{}, { actions: { focus: action } }]))).toBe( null, ); expect(refused(() => assertTakesImageDraft(false, []))).toBe(null); for (const takesImage of [true, false]) { for (const actions of [ { activate: action }, { mouseUp: action }, { activate: null }, { mouseUp: null }, { activate: importIconAction() }, ]) { expect(refused(() => assertTakesImageDraft(takesImage, [{}, { actions }]))).toEqual( OVER_THE_FACT, ); } } expect(refused(() => assertTakesImageDraft(true, []))).toEqual(OVER_THE_FACT); }); test("true writes the script where the press is free, keeps it where it is, and never overwrites an author's", () => { expect(pressWriteOf(null, true)).toEqual({ kind: 'write' }); expect(pressWriteOf({}, true)).toEqual({ kind: 'write' }); expect(pressWriteOf({ activate: IMPORTS }, true)).toEqual({ kind: 'keep' }); expect(pressWriteOf({ mouseUp: IMPORTS }, true)).toEqual({ kind: 'keep' }); for (const press of [ { activate: BEEPS }, { mouseUp: NEXT_PAGE }, { activate: IMPORTS, mouseUp: IMPORTS }, { activate: scriptOf('event.target.buttonImportIcon(); app.beep(0);') }, { activate: { root: null, incomplete: true, warnings: ['incomplete'] } }, ]) { expect(refused(() => pressWriteOf(press as never, true))).toEqual(OVER_THE_FACT); } }); test('false takes the script off the event that holds it, and leaves any other press alone', () => { expect(pressWriteOf({ activate: IMPORTS }, false)).toEqual({ kind: 'remove', event: 'activate', }); expect(pressWriteOf({ mouseUp: IMPORTS }, false)).toEqual({ kind: 'remove', event: 'mouseUp' }); for (const press of [ null, {}, { activate: BEEPS }, { activate: IMPORTS, mouseUp: IMPORTS }, { activate: scriptOf('event.target.buttonImportIcon(); app.beep(0);') }, ]) { expect(pressWriteOf(press as never, false)).toEqual({ kind: 'keep' }); } }); test('true is checked against every widget before one is written', () => { expect(refused(() => assertTakesImage([{}, { activate: IMPORTS }, null]))).toBe(null); expect(refused(() => assertTakesImage([]))).toEqual(OVER_THE_FACT); expect(refused(() => assertTakesImage([{}, { activate: BEEPS }]))).toEqual(OVER_THE_FACT); // A widget on no page can't be written. expect(refused(() => assertTakesImage([{}], 1))).toEqual(OVER_THE_FACT); expect(refused(() => assertTakesImage([], 1))).toEqual(OVER_THE_FACT); }); test("the write is a patch of the widget's actions, which the engine writes and a prediction reads", () => { expect(pressPatchOf({ kind: 'write' })).toEqual({ activate: importIconAction() }); expect(pressPatchOf({ kind: 'remove', event: 'mouseUp' })).toEqual({ mouseUp: null }); expect(pressPatchOf({ kind: 'keep' })).toEqual({}); /** A widget's actions after the write, as a read gives them. */ const after = (actions: Parameters[0], takesImage: boolean) => widgetActionsAfter(actions as never, pressPatchOf(pressWriteOf(actions, takesImage))); expect(after(null, true)).toEqual({ activate: IMPORTS_AS_READ }); expect(after({ focus: BEEPS } as never, true)).toEqual({ focus: BEEPS, activate: IMPORTS_AS_READ, }); const has = { mouseUp: IMPORTS, focus: BEEPS }; expect(after(has as never, true)).toBe(has); expect(after(has as never, false)).toEqual({ focus: BEEPS }); // No event left reads as a widget without actions. expect(after({ activate: IMPORTS }, false)).toBe(null); const other = { activate: BEEPS }; expect(after(other, false)).toBe(other); expect(after(undefined, false)).toBe(null); }); test('a widget added to an image field gets the script, unless its placement names a press', () => { expect(imageFieldWidgetActions(undefined)).toEqual({ activate: importIconAction() }); const focus = { focus: { type: 'named', name: 'NextPage' } } as const; expect(imageFieldWidgetActions(focus)).toEqual({ ...focus, activate: importIconAction() }); for (const actions of [ { activate: { type: 'named', name: 'NextPage' } }, { mouseUp: { type: 'named', name: 'NextPage' } }, { activate: null }, ] as const) { expect(imageFieldWidgetActions(actions)).toBe(actions); } }); test('takes no right to write scripts: the draft names no script', () => { const draft: FormFieldDraft = { kind: 'pushbutton', name: 'photo', takesImage: true, widgets: [{ page: PAGE, rect: { x: 10, y: 10, width: 90, height: 30 } }], }; expect(draftWritesScripts(draft)).toBe(false); }); }); /** The script's tree as a read gives it once the engine wrote it. */ const IMPORTS_AS_READ = { root: { type: 'javascript', subtype: 'JavaScript', script: IMPORT_ICON_SCRIPT, next: [] }, incomplete: false, warnings: [], }; const BUTTON = { ref: { kind: 'objectNumber', objectNumber: 20 }, name: 'photo', kind: 'pushbutton', origin: 'acroform', readOnly: false, required: false, noExport: false, alternateName: null, mappingName: null, valueEntry: { kind: 'none' }, defaultValueEntry: { kind: 'none' }, groupId: null, assignment: { kind: 'unassigned' }, lockedBy: null, purpose: null, placeholder: null, createdBy: null, createdAt: null, filledBy: null, filledByName: null, filledAt: null, importedBy: null, hasImage: false, takesImage: true, widgets: [], } as const; describe('the schemas', () => { test('a push button reads the fact, and one from an older side reads false', () => { expect(FormFieldDTOSchema.parse(BUTTON)).toMatchObject({ takesImage: true }); const { takesImage: _takesImage, ...older } = BUTTON; expect(FormFieldDTOSchema.parse(older)).toMatchObject({ kind: 'pushbutton', takesImage: false, }); expect(withButtonImage(older)).toEqual({ ...older, takesImage: false }); // Older than the picture too: both, each on its own. const { hasImage: _hasImage, ...oldest } = older; expect(withButtonImage(oldest)).toEqual({ ...oldest, hasImage: false, takesImage: false }); expect(withButtonImage({ ...oldest, takesImage: true })).toEqual({ ...oldest, hasImage: false, takesImage: true, }); expect(withButtonImage(BUTTON)).toBe(BUTTON); const text = { kind: 'text', name: 'a' }; expect(withButtonImage(text)).toBe(text); expect(FormFieldDTOSchema.safeParse({ ...BUTTON, takesImage: 'yes' }).success).toBe(false); }); test('a bundle written before the fact is completed, and one that has it comes back as it is', () => { const { takesImage: _takesImage, ...older } = BUTTON; const whole = completeFormBundle({ fields: [{ data: older }] }); expect(whole.fields[0]!.data).toMatchObject({ takesImage: false }); const current = { fields: [{ data: BUTTON }] }; expect(completeFormBundle(current)).toBe(current); }); test("a push button's draft takes it, and another kind's refuses it", () => { const draft = { kind: 'pushbutton', name: 'photo', takesImage: true }; expect(FormFieldDraftSchema.parse(draft)).toEqual(draft); expect(FormFieldDraftSchema.parse({ ...draft, takesImage: false })).toMatchObject({ takesImage: false, }); expect(FormFieldDraftSchema.safeParse({ ...draft, takesImage: null }).success).toBe(false); expect(FormFieldDraftSchema.safeParse({ ...draft, takesImage: 'yes' }).success).toBe(false); for (const kind of ['text', 'checkbox', 'radio', 'combobox', 'listbox', 'signature']) { expect(FormFieldDraftSchema.safeParse({ ...draft, kind }).success).toBe(false); } }); test('a patch takes it as true or false', () => { expect(FormFieldPatchSchema.parse({ takesImage: true })).toEqual({ takesImage: true }); expect(FormFieldPatchSchema.parse({ takesImage: false })).toEqual({ takesImage: false }); expect(FormFieldPatchSchema.safeParse({ takesImage: null }).success).toBe(false); }); test('the change ops carry it: a create, an update and what it expects', () => { const create = { type: 'forms.create', draft: { kind: 'pushbutton', name: 'photo', takesImage: true }, }; expect(ChangeOpWireSchema.parse(create)).toEqual(create); const update = { type: 'forms.update', field: { kind: 'fqn', name: 'photo' }, patch: { takesImage: false }, expect: { takesImage: true }, }; expect(ChangeOpWireSchema.parse(update)).toEqual(update); }); test('it arrived with the picture, in its version', () => { expect(BUTTON_IMAGE_AND_LAYOUT_SINCE).toBe('3.5'); }); }); describe('predicting a write of the fact', () => { const context = { objectNumber: 20, widgets: [ { kind: 'objectNumber', page: PAGE, objectNumber: 21 }, { kind: 'objectNumber', page: PAGE, objectNumber: 22 }, ], } as const; const placement = (row: number, extra: Record = {}) => ({ page: PAGE, rect: { x: 10, y: 10 + row * 40, width: 90, height: 30 }, layout: 'image' as const, ...extra, }); const pressesOf = (predicted: FieldWithWidgets) => predicted.widgets.map((row) => row.actions); test('a create gives every widget the script, and the field the fact', () => { const made = formFieldOfDraft( { kind: 'pushbutton', name: 'photo', takesImage: true, widgets: [placement(0), placement(1)], }, context, ); expect(made.field).toMatchObject({ kind: 'pushbutton', hasImage: false, takesImage: true }); expect(pressesOf(made)).toEqual([{ activate: IMPORTS_AS_READ }, { activate: IMPORTS_AS_READ }]); }); test('left out or false, a created button is a button', () => { for (const takesImage of [undefined, false]) { const made = formFieldOfDraft( { kind: 'pushbutton', name: 'go', ...(takesImage === undefined ? {} : { takesImage }), widgets: [placement(0)], }, context, ); expect(made.field).toMatchObject({ takesImage: false }); expect(made.widgets[0]!.actions ?? null).toBe(null); } }); test('a create refuses what the engine refuses', () => { const draft = (extra: Record) => ({ kind: 'pushbutton', name: 'photo', ...extra }) as FormFieldDraft; expect(refused(() => formFieldOfDraft(draft({ takesImage: true }), context))).toEqual( OVER_THE_FACT, ); const pressed = placement(0, { actions: { activate: { type: 'named', name: 'NextPage' } } }); expect( refused(() => formFieldOfDraft(draft({ takesImage: true, widgets: [pressed] }), context)), ).toEqual(OVER_THE_FACT); expect( refused(() => formFieldOfDraft( { kind: 'text', name: 'a', takesImage: true } as unknown as FormFieldDraft, context, ), ), ).toEqual(OVER_THE_FACT); }); /** A push button as a read gives it, with a row per press given. */ const button = (presses: readonly (Record | null)[]): FieldWithWidgets => { const widgets = presses.map((actions, at) => ({ ...(annotationOfDraft( { subtype: 'widget', box: { x: 10, y: 10 + at * 40, width: 90, height: 30 } } as never, { ref: { kind: 'objectNumber', page: PAGE, objectNumber: 21 + at } }, ) as Record), field: { kind: 'objectNumber', objectNumber: 20 }, fieldKind: 'pushbutton', actions, })); const field = { ...BUTTON, takesImage: takesImageOf(presses as never), widgets: presses.map((_, at) => ({ ref: { kind: 'objectNumber', page: PAGE, objectNumber: 21 + at }, objectNumber: 21 + at, page: PAGE, })), }; return { field, widgets } as unknown as FieldWithWidgets; }; test('an update writes the script where the press is free, and keeps a widget that has it', () => { const before = button([null, { mouseUp: IMPORTS }, { focus: BEEPS }]); const after = formFieldAfter(before, { takesImage: true }); expect(after.field).toMatchObject({ takesImage: true }); expect(pressesOf(after)).toEqual([ { activate: IMPORTS_AS_READ }, { mouseUp: IMPORTS }, { focus: BEEPS, activate: IMPORTS_AS_READ }, ]); // A widget that keeps what it has keeps its row. expect(after.widgets[1]).toBe(before.widgets[1]); }); test('false takes it off where the press is exactly it', () => { const before = button([{ activate: IMPORTS }, { mouseUp: IMPORTS, focus: BEEPS }]); const after = formFieldAfter(before, { takesImage: false }); expect(after.field).toMatchObject({ takesImage: false }); expect(pressesOf(after)).toEqual([null, { focus: BEEPS }]); const other = button([{ activate: BEEPS }]); expect(pressesOf(formFieldAfter(other, { takesImage: false }))).toEqual([{ activate: BEEPS }]); }); test('an update refuses what the engine refuses, and a patch without the fact leaves it', () => { expect( refused(() => formFieldAfter(button([null, { activate: BEEPS }]), { takesImage: true })), ).toEqual(OVER_THE_FACT); expect(refused(() => formFieldAfter(button([]), { takesImage: true }))).toEqual(OVER_THE_FACT); // A widget of the field no page shows has no row. const unplaced = button([null]); expect( refused(() => formFieldAfter({ ...unplaced, widgets: [] }, { takesImage: true })), ).toEqual(OVER_THE_FACT); const image = button([{ activate: IMPORTS }]); const renamed = formFieldAfter(image, { required: true }); expect(renamed.field).toMatchObject({ takesImage: true, required: true }); expect(renamed.widgets).toBe(image.widgets); const text = { field: { ...BUTTON, kind: 'text' } as unknown as FormField, widgets: [] }; expect(refused(() => formFieldAfter(text, { takesImage: true } as never))).toEqual( OVER_THE_FACT, ); }); });