@embedpdf/plugin-form 3.0.0-next.19 → 3.0.0-next.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as FormRepairResult, B as FormValidationRejectedEvent, C as FormImportDrop, D as FormKind, E as FormImportResult, F as FormSettings, G as WidgetAnnotation, H as FormWidgetAddResult, I as FormSnapshot, J as FormWidgetItem, K as toFieldRef, L as FormTransfer, M as FormResyncedEvent, N as FormSetValueResult, O as FormPlainValue, P as FormSetValueStatus, Q as WidgetHit, R as FormUiEffect, S as FormFilter, T as FormImportOptions, U as WidgetActivationResult, V as FormValueChangedEvent, W as WidgetAddress, X as FormWidgetLook, Y as Box, _ as FormFieldResult, a as FormCommitResult, b as FormFieldUpdatedEvent, c as FormExportSelection, d as FormFieldDeletedEvent, f as FormFieldDraft, g as FormFieldRef, h as FormFieldPatch, i as FormCapability, j as FormResetResult, k as FormRepairOptions, l as FormFieldCreatedEvent, m as FormFieldFlagSetting, n as FillableFields, o as FormCommitStatus, p as FormFieldFamily, q as FormToken, r as FormBundle, s as FormConfig, t as FORM_DEFAULTS, u as FormFieldDTO, v as FormFieldSetting, w as FormImportDropReason, x as FormFieldValue, y as FormFieldSettings, z as FormValidation } from "./contract-D-yQxw3H.cjs";
2
- import { t as FormHostCapability } from "./host-contract-1epLfK1S.cjs";
1
+ import { $ as FormModel, A as FormKind, B as FormTransfer, C as FormFocusChangedEvent, D as FormImportDropReason, E as FormImportDrop, F as FormResyncedEvent, G as FormWidgetAddResult, H as FormValidation, I as FormSetValueResult, J as WidgetAnnotation, K as WidgetActivationResult, L as FormSetValueStatus, M as FormRepairOptions, N as FormRepairResult, O as FormImportOptions, P as FormResetResult, Q as Box, R as FormSettings, S as FormFilter, T as FormFocusOptions, U as FormValidationRejectedEvent, V as FormUiEffect, W as FormValueChangedEvent, X as FormToken, Y as toFieldRef, Z as FormWidgetItem, _ as FormFieldResult, a as FormCommitResult, b as FormFieldUpdatedEvent, c as FormExportSelection, d as FormFieldDeletedEvent, et as FormWidgetLook, f as FormFieldDraft, g as FormFieldRef, h as FormFieldPatch, i as FormCapability, j as FormPlainValue, k as FormImportResult, l as FormFieldCreatedEvent, m as FormFieldFlagSetting, n as FillableFields, nt as WidgetHit, o as FormCommitStatus, p as FormFieldFamily, q as WidgetAddress, r as FormBundle, s as FormConfig, t as FORM_DEFAULTS, u as FormFieldDTO, v as FormFieldSetting, w as FormFocusNextOptions, x as FormFieldValue, y as FormFieldSettings, z as FormSnapshot } from "./contract-c_wuhKk1.cjs";
2
+ import { n as FormHostCapability } from "./host-contract-DaauiYfw.cjs";
3
3
  import { FormScriptingController, createFormScriptingController } from "./scripting.cjs";
4
4
  import { ResourceStatus } from "@embedpdf/core";
5
5
  import { FormFieldDTO as FormFieldDTO$1, FormFieldFamily as FormFieldFamily$1, FormKind as FormKind$1, WidgetAppearance } from "@embedpdf/engine-core/runtime";
@@ -14,13 +14,14 @@ import { ClickCreate } from "@embedpdf/plugin-annotation/contract";
14
14
  * fills every widget. Design mode is the 'form-edit' and palette tools: with
15
15
  * the annotation plugin present, the form lends it the widgets, which its
16
16
  * tools then select, move, restyle and delete. The render plugin draws the
17
- * widgets' pictures in both modes. `config` is the settings the app
17
+ * widgets' pictures in both modes. With the fonts plugin, a text field in a
18
+ * font of its own is edited in that font's program. `config` is the settings the app
18
19
  * registers, over {@link FORM_DEFAULTS}.
19
20
  */
20
- declare const formPlugin: (config?: FormConfig) => import("@embedpdf/core").PluginDef<Readonly<Record<string, never>>, FormHostCapability, FormSettings>;
21
+ declare const formPlugin: (config?: FormConfig) => import("@embedpdf/core").PluginDef<FormModel, FormHostCapability, FormSettings>;
21
22
  //#endregion
22
23
  //#region src/state.d.ts
23
- /** Every field, whether the form is read, what kind of form it is, and the selected widget's field. */
24
+ /** Every field, whether the form is read, what kind of form it is, the selected widget's field, and the field the cursor is in. */
24
25
  interface FormState {
25
26
  /** Every field. The same array while nothing changes. */
26
27
  readonly fields: readonly FormFieldDTO$1[];
@@ -30,6 +31,8 @@ interface FormState {
30
31
  readonly formKind: FormKind$1;
31
32
  /** The field of the selected widget while one widget is selected (in design mode), or `null`. */
32
33
  readonly selectedField: FormFieldDTO$1 | null;
34
+ /** The field the cursor is in, or `null`. */
35
+ readonly focusedField: FormFieldDTO$1 | null;
33
36
  }
34
37
  declare const formState: import("@embedpdf/core").StateDeclaration<FormCapability, FormState>;
35
38
  //#endregion
@@ -56,5 +59,5 @@ interface FormToolDef {
56
59
  declare const FORM_TOOLS: readonly FormToolDef[];
57
60
  declare const FORM_TOOL_BY_ID: ReadonlyMap<string, FormToolDef>;
58
61
  //#endregion
59
- export { type AuthorableFormFamily, type Box, FORM_DEFAULTS, FORM_TOOLS, FORM_TOOL_BY_ID, FillableFields, type FormBundle, FormCapability, FormCommitResult, FormCommitStatus, FormConfig, FormExportSelection, FormFieldCreatedEvent, type FormFieldDTO, FormFieldDeletedEvent, type FormFieldDraft, type FormFieldFamily, FormFieldFlagSetting, type FormFieldPatch, type FormFieldRef, FormFieldResult, FormFieldSetting, FormFieldSettings, FormFieldUpdatedEvent, type FormFieldValue, FormFilter, type FormImportDrop, type FormImportDropReason, type FormImportOptions, FormImportResult, type FormKind, FormPlainValue, type FormRepairOptions, type FormRepairResult, FormResetResult, FormResyncedEvent, FormScriptingController, FormSetValueResult, FormSetValueStatus, FormSettings, type FormSnapshot, type FormState, FormToken, type FormToolDef, FormTransfer, FormUiEffect, FormValidation, FormValidationRejectedEvent, FormValueChangedEvent, FormWidgetAddResult, type FormWidgetItem, type FormWidgetLook, WidgetActivationResult, WidgetAddress, type WidgetAnnotation, type WidgetHit, createFormScriptingController, formPlugin, formState, toFieldRef };
62
+ export { type AuthorableFormFamily, type Box, FORM_DEFAULTS, FORM_TOOLS, FORM_TOOL_BY_ID, FillableFields, type FormBundle, FormCapability, FormCommitResult, FormCommitStatus, FormConfig, FormExportSelection, FormFieldCreatedEvent, type FormFieldDTO, FormFieldDeletedEvent, type FormFieldDraft, type FormFieldFamily, FormFieldFlagSetting, type FormFieldPatch, type FormFieldRef, FormFieldResult, FormFieldSetting, FormFieldSettings, FormFieldUpdatedEvent, type FormFieldValue, FormFilter, FormFocusChangedEvent, FormFocusNextOptions, FormFocusOptions, type FormImportDrop, type FormImportDropReason, type FormImportOptions, FormImportResult, type FormKind, FormPlainValue, type FormRepairOptions, type FormRepairResult, FormResetResult, FormResyncedEvent, FormScriptingController, FormSetValueResult, FormSetValueStatus, FormSettings, type FormSnapshot, type FormState, FormToken, type FormToolDef, FormTransfer, FormUiEffect, FormValidation, FormValidationRejectedEvent, FormValueChangedEvent, FormWidgetAddResult, type FormWidgetItem, type FormWidgetLook, WidgetActivationResult, WidgetAddress, type WidgetAnnotation, type WidgetHit, createFormScriptingController, formPlugin, formState, toFieldRef };
60
63
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as FormRepairResult, B as FormValidationRejectedEvent, C as FormImportDrop, D as FormKind, E as FormImportResult, F as FormSettings, G as WidgetAnnotation, H as FormWidgetAddResult, I as FormSnapshot, J as FormWidgetItem, K as toFieldRef, L as FormTransfer, M as FormResyncedEvent, N as FormSetValueResult, O as FormPlainValue, P as FormSetValueStatus, Q as WidgetHit, R as FormUiEffect, S as FormFilter, T as FormImportOptions, U as WidgetActivationResult, V as FormValueChangedEvent, W as WidgetAddress, X as FormWidgetLook, Y as Box, _ as FormFieldResult, a as FormCommitResult, b as FormFieldUpdatedEvent, c as FormExportSelection, d as FormFieldDeletedEvent, f as FormFieldDraft, g as FormFieldRef, h as FormFieldPatch, i as FormCapability, j as FormResetResult, k as FormRepairOptions, l as FormFieldCreatedEvent, m as FormFieldFlagSetting, n as FillableFields, o as FormCommitStatus, p as FormFieldFamily, q as FormToken, r as FormBundle, s as FormConfig, t as FORM_DEFAULTS, u as FormFieldDTO, v as FormFieldSetting, w as FormImportDropReason, x as FormFieldValue, y as FormFieldSettings, z as FormValidation } from "./contract-BwcgtCOD.js";
2
- import { t as FormHostCapability } from "./host-contract-BRYUbpT_.js";
1
+ import { $ as FormModel, A as FormKind, B as FormTransfer, C as FormFocusChangedEvent, D as FormImportDropReason, E as FormImportDrop, F as FormResyncedEvent, G as FormWidgetAddResult, H as FormValidation, I as FormSetValueResult, J as WidgetAnnotation, K as WidgetActivationResult, L as FormSetValueStatus, M as FormRepairOptions, N as FormRepairResult, O as FormImportOptions, P as FormResetResult, Q as Box, R as FormSettings, S as FormFilter, T as FormFocusOptions, U as FormValidationRejectedEvent, V as FormUiEffect, W as FormValueChangedEvent, X as FormToken, Y as toFieldRef, Z as FormWidgetItem, _ as FormFieldResult, a as FormCommitResult, b as FormFieldUpdatedEvent, c as FormExportSelection, d as FormFieldDeletedEvent, et as FormWidgetLook, f as FormFieldDraft, g as FormFieldRef, h as FormFieldPatch, i as FormCapability, j as FormPlainValue, k as FormImportResult, l as FormFieldCreatedEvent, m as FormFieldFlagSetting, n as FillableFields, nt as WidgetHit, o as FormCommitStatus, p as FormFieldFamily, q as WidgetAddress, r as FormBundle, s as FormConfig, t as FORM_DEFAULTS, u as FormFieldDTO, v as FormFieldSetting, w as FormFocusNextOptions, x as FormFieldValue, y as FormFieldSettings, z as FormSnapshot } from "./contract-D_9fiTkd.js";
2
+ import { n as FormHostCapability } from "./host-contract-DdOsYM83.js";
3
3
  import { FormScriptingController, createFormScriptingController } from "./scripting.js";
4
4
  import { ResourceStatus } from "@embedpdf/core";
5
5
  import { ClickCreate } from "@embedpdf/plugin-annotation/contract";
@@ -14,13 +14,14 @@ import { FormFieldDTO as FormFieldDTO$1, FormFieldFamily as FormFieldFamily$1, F
14
14
  * fills every widget. Design mode is the 'form-edit' and palette tools: with
15
15
  * the annotation plugin present, the form lends it the widgets, which its
16
16
  * tools then select, move, restyle and delete. The render plugin draws the
17
- * widgets' pictures in both modes. `config` is the settings the app
17
+ * widgets' pictures in both modes. With the fonts plugin, a text field in a
18
+ * font of its own is edited in that font's program. `config` is the settings the app
18
19
  * registers, over {@link FORM_DEFAULTS}.
19
20
  */
20
- declare const formPlugin: (config?: FormConfig) => import("@embedpdf/core").PluginDef<Readonly<Record<string, never>>, FormHostCapability, FormSettings>;
21
+ declare const formPlugin: (config?: FormConfig) => import("@embedpdf/core").PluginDef<FormModel, FormHostCapability, FormSettings>;
21
22
  //#endregion
22
23
  //#region src/state.d.ts
23
- /** Every field, whether the form is read, what kind of form it is, and the selected widget's field. */
24
+ /** Every field, whether the form is read, what kind of form it is, the selected widget's field, and the field the cursor is in. */
24
25
  interface FormState {
25
26
  /** Every field. The same array while nothing changes. */
26
27
  readonly fields: readonly FormFieldDTO$1[];
@@ -30,6 +31,8 @@ interface FormState {
30
31
  readonly formKind: FormKind$1;
31
32
  /** The field of the selected widget while one widget is selected (in design mode), or `null`. */
32
33
  readonly selectedField: FormFieldDTO$1 | null;
34
+ /** The field the cursor is in, or `null`. */
35
+ readonly focusedField: FormFieldDTO$1 | null;
33
36
  }
34
37
  declare const formState: import("@embedpdf/core").StateDeclaration<FormCapability, FormState>;
35
38
  //#endregion
@@ -56,5 +59,5 @@ interface FormToolDef {
56
59
  declare const FORM_TOOLS: readonly FormToolDef[];
57
60
  declare const FORM_TOOL_BY_ID: ReadonlyMap<string, FormToolDef>;
58
61
  //#endregion
59
- export { type AuthorableFormFamily, type Box, FORM_DEFAULTS, FORM_TOOLS, FORM_TOOL_BY_ID, FillableFields, type FormBundle, FormCapability, FormCommitResult, FormCommitStatus, FormConfig, FormExportSelection, FormFieldCreatedEvent, type FormFieldDTO, FormFieldDeletedEvent, type FormFieldDraft, type FormFieldFamily, FormFieldFlagSetting, type FormFieldPatch, type FormFieldRef, FormFieldResult, FormFieldSetting, FormFieldSettings, FormFieldUpdatedEvent, type FormFieldValue, FormFilter, type FormImportDrop, type FormImportDropReason, type FormImportOptions, FormImportResult, type FormKind, FormPlainValue, type FormRepairOptions, type FormRepairResult, FormResetResult, FormResyncedEvent, FormScriptingController, FormSetValueResult, FormSetValueStatus, FormSettings, type FormSnapshot, type FormState, FormToken, type FormToolDef, FormTransfer, FormUiEffect, FormValidation, FormValidationRejectedEvent, FormValueChangedEvent, FormWidgetAddResult, type FormWidgetItem, type FormWidgetLook, WidgetActivationResult, WidgetAddress, type WidgetAnnotation, type WidgetHit, createFormScriptingController, formPlugin, formState, toFieldRef };
62
+ export { type AuthorableFormFamily, type Box, FORM_DEFAULTS, FORM_TOOLS, FORM_TOOL_BY_ID, FillableFields, type FormBundle, FormCapability, FormCommitResult, FormCommitStatus, FormConfig, FormExportSelection, FormFieldCreatedEvent, type FormFieldDTO, FormFieldDeletedEvent, type FormFieldDraft, type FormFieldFamily, FormFieldFlagSetting, type FormFieldPatch, type FormFieldRef, FormFieldResult, FormFieldSetting, FormFieldSettings, FormFieldUpdatedEvent, type FormFieldValue, FormFilter, FormFocusChangedEvent, FormFocusNextOptions, FormFocusOptions, type FormImportDrop, type FormImportDropReason, type FormImportOptions, FormImportResult, type FormKind, FormPlainValue, type FormRepairOptions, type FormRepairResult, FormResetResult, FormResyncedEvent, FormScriptingController, FormSetValueResult, FormSetValueStatus, FormSettings, type FormSnapshot, type FormState, FormToken, type FormToolDef, FormTransfer, FormUiEffect, FormValidation, FormValidationRejectedEvent, FormValueChangedEvent, FormWidgetAddResult, type FormWidgetItem, type FormWidgetLook, WidgetActivationResult, WidgetAddress, type WidgetAnnotation, type WidgetHit, createFormScriptingController, formPlugin, formState, toFieldRef };
60
63
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,16 +1,19 @@
1
- import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-DcncvPcF.js";
1
+ import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-BdEaLXUK.js";
2
2
  import { n as createFormScriptingController, r as scriptError, t as FormScriptingController } from "./controller-Sr5M_8G8.js";
3
3
  import { FormToken as FormToken$1 } from "./contract/host.js";
4
4
  import { PluginError, composeApi, definePlugin, defineState, memo, memoByKey, reload, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
5
5
  import { ActionsToken, createHoverPump } from "@embedpdf/plugin-actions/contract";
6
6
  import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
7
+ import { FontsToken } from "@embedpdf/plugin-fonts/contract";
7
8
  import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction/contract/host";
8
9
  import { RenderToken } from "@embedpdf/plugin-render/contract";
9
- import { annotationKey, draftWritesScripts, fieldAfterReset, fieldAfterValue, fieldValueOf, fieldValueWriteOf, formEffectOps, formFieldAfter, formFieldOfDraft, pageRefsEqual, reorderPart, reorderedList, serializeError, widgetAfterPatch, widgetsAfterDisplay, writesScripts } from "@embedpdf/engine-core/runtime";
10
+ import { annotationKey, draftWritesScripts, fieldAfterReset, fieldAfterValue, fieldValueOf, fieldValueWriteOf, formEffectOps, formFieldAfter, formFieldOfDraft, isStandardFontName, pageRefsEqual, reorderPart, reorderedList, serializeError, tabOrderOf, toFieldRef as toFieldRef$1, widgetAfterPatch, widgetsAfterDisplay, writesScripts } from "@embedpdf/engine-core/runtime";
10
11
  import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
11
12
  import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
12
13
  import { gesturePlacement, refOf, widgetAppearanceOf } from "@embedpdf/core-annotation";
13
- import { paints, textEditorLayout, widgetDrawing, widgetScene } from "@embedpdf/core-form";
14
+ import { StageToken } from "@embedpdf/plugin-stage/contract";
15
+ import { paints, textEditorLayout, widgetDrawing, widgetScene, widgetText } from "@embedpdf/core-form";
16
+ import { standardFontCss, standardFontOf } from "@embedpdf/core-fonts";
14
17
  import { RenderToken as RenderToken$1 } from "@embedpdf/plugin-render/contract/host";
15
18
  //#region src/tools/definitions.ts
16
19
  /** Palette tools keep widgets editable right after placement. */
@@ -311,6 +314,7 @@ function connectForm(ctx, form, lender) {
311
314
  if (!actions) return;
312
315
  ctx.cleanup(actions.registerFormCommitSink((effects) => form.commitScriptFormEffects(effects)));
313
316
  ctx.cleanup(actions.registerFormReader(() => form.getSnapshot()));
317
+ ctx.cleanup(actions.registerFormFocus((name) => form.focus(toFieldRef$1(name))));
314
318
  ctx.cleanup(actions.registerSubmitResolver((intent, actionContext, diagnose) => form.resolveSubmitDataset(intent, actionContext, diagnose)));
315
319
  ctx.cleanup(actions.registerExecutor("reset-form", async (node, actionContext) => {
316
320
  if (node.type !== "reset-form") return {
@@ -642,7 +646,7 @@ function widgetAt(index, widgets, point) {
642
646
  }
643
647
  return best;
644
648
  }
645
- const initialFormModel = () => ({});
649
+ const initialFormModel = () => ({ focused: null });
646
650
  //#endregion
647
651
  //#region src/read/fields.ts
648
652
  /**
@@ -1030,8 +1034,6 @@ function fillItems(index, pageObjectNumber, widgets, mayFill) {
1030
1034
  * folded in, and the widget hit test.
1031
1035
  */
1032
1036
  const NO_WIDGETS = Object.freeze([]);
1033
- /** Whether the `fillable` setting lets people fill in a field of this family by hand. */
1034
- const isFillableByHand = (fillable, family) => typeof fillable === "boolean" ? fillable : fillable.includes(family);
1035
1037
  const NOTHING_SHOWN$1 = Object.freeze([]);
1036
1038
  function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1037
1039
  /** Every page's widgets come with the form: one read for the document. */
@@ -1043,14 +1045,12 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1043
1045
  if (!page) return null;
1044
1046
  return widgetAt(fields.view(), widgetsOn(page.objectNumber), point);
1045
1047
  };
1046
- const fillable = () => ctx.settings().get().fillable;
1047
- const mayWrite = (field) => isFillableByHand(fillable(), field.family) && (field.family === "signature" ? rights.maySign(field) : rights.mayFill(field));
1048
1048
  const widgetsOfPage = memoByKey((pageObjectNumber) => [
1049
1049
  fields.view(),
1050
1050
  widgetsOn(pageObjectNumber),
1051
1051
  rights.key(),
1052
- fillable()
1053
- ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, mayWrite));
1052
+ ctx.settings().get().fillable
1053
+ ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, rights.mayFillByHand));
1054
1054
  /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */
1055
1055
  const getPageBox = (page) => {
1056
1056
  const size = ctx.getPage(page)?.size;
@@ -1076,6 +1076,7 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1076
1076
  renderAppearances: pictures.render,
1077
1077
  getWidgetPainting: looks.getWidgetPainting,
1078
1078
  getTextEditorLayout: looks.getTextEditorLayout,
1079
+ getWidgetFontCss: looks.getWidgetFontCss,
1079
1080
  ensureLoaded: loadWidgets,
1080
1081
  getWidgetAt,
1081
1082
  getPageBox
@@ -1381,6 +1382,90 @@ function createFieldsMirror(ctx, events) {
1381
1382
  return fields;
1382
1383
  }
1383
1384
  //#endregion
1385
+ //#region src/services/cursor.ts
1386
+ /** How long a box asked for keeps its claim on the cursor while its page comes in. */
1387
+ const PENDING_MS = 2e3;
1388
+ function createCursor(ctx, fields, events) {
1389
+ const targets = /* @__PURE__ */ new Map();
1390
+ let pending = null;
1391
+ let leaving = null;
1392
+ let last = null;
1393
+ const setFocused = (next) => {
1394
+ const previous = ctx.state.get().focused;
1395
+ if (previous?.widget === next?.widget && previous?.field === next?.field) return;
1396
+ ctx.state.update((state) => ({
1397
+ ...state,
1398
+ focused: next
1399
+ }));
1400
+ const field = next ? fieldByKey(fields.view(), next.field) : null;
1401
+ const row = next ? widgetRowOf(fields.view(), next.widget) : null;
1402
+ events.focusChanged.emit({
1403
+ field,
1404
+ widget: row?.ref ?? null
1405
+ });
1406
+ };
1407
+ const clearPending = () => {
1408
+ pending?.expire();
1409
+ pending = null;
1410
+ };
1411
+ return {
1412
+ focused: () => ctx.state.get().focused,
1413
+ last: () => last,
1414
+ note(event, fieldRef, widgetRef) {
1415
+ const widget = widgetObjectOf(widgetRef);
1416
+ if (event === "focus") {
1417
+ leaving?.();
1418
+ leaving = null;
1419
+ if (pending && pending.widget !== widget) clearPending();
1420
+ const field = fieldByRef(fields.view(), fieldRef);
1421
+ last = widget;
1422
+ setFocused(field ? {
1423
+ field: fieldKeyOf(field),
1424
+ widget
1425
+ } : null);
1426
+ } else if (ctx.state.get().focused?.widget === widget) {
1427
+ leaving?.();
1428
+ leaving = ctx.clock.after(0, () => {
1429
+ leaving = null;
1430
+ setFocused(null);
1431
+ });
1432
+ }
1433
+ },
1434
+ goTo(row, select) {
1435
+ const widget = widgetObjectOf(row.ref);
1436
+ const stage = ctx.tryGet(StageToken);
1437
+ stage?.reveal(row.page, { rect: row.rect });
1438
+ clearPending();
1439
+ const target = targets.get(widget);
1440
+ if (target) {
1441
+ target.focus({ select });
1442
+ return true;
1443
+ }
1444
+ if (!stage) return false;
1445
+ pending = {
1446
+ widget,
1447
+ select,
1448
+ expire: ctx.clock.after(PENDING_MS, () => {
1449
+ if (pending?.widget === widget) pending = null;
1450
+ })
1451
+ };
1452
+ return true;
1453
+ },
1454
+ attach(widgetRef, target) {
1455
+ const widget = widgetObjectOf(widgetRef);
1456
+ targets.set(widget, target);
1457
+ if (pending?.widget === widget) {
1458
+ const { select } = pending;
1459
+ clearPending();
1460
+ target.focus({ select });
1461
+ }
1462
+ return () => {
1463
+ if (targets.get(widget) === target) targets.delete(widget);
1464
+ };
1465
+ }
1466
+ };
1467
+ }
1468
+ //#endregion
1384
1469
  //#region src/services/design.ts
1385
1470
  /**
1386
1471
  * Whether the form's widgets are lent to the annotation plugin now
@@ -1401,7 +1486,8 @@ function createEvents(ctx) {
1401
1486
  fieldUpdated: ctx.events.source(),
1402
1487
  fieldDeleted: ctx.events.source(),
1403
1488
  validationRejected: ctx.events.source(),
1404
- resynced: ctx.events.source()
1489
+ resynced: ctx.events.source(),
1490
+ focusChanged: ctx.events.source()
1405
1491
  };
1406
1492
  }
1407
1493
  //#endregion
@@ -1412,14 +1498,19 @@ function createEvents(ctx) {
1412
1498
  * write. A field's group decides: a `fields:fill` (`fields:sign`) permission
1413
1499
  * for its group, or `doc.forms.fill` (`doc.sign`) for every field.
1414
1500
  */
1501
+ /** Whether the `fillable` setting lets people fill in a field of this family by hand. */
1502
+ const isFillableByHand = (fillable, family) => typeof fillable === "boolean" ? fillable : fillable.includes(family);
1415
1503
  function createFillRights(ctx, fields) {
1416
1504
  const mayFill = (field) => ctx.allowsField("fill", field);
1417
1505
  const maySign = (field) => ctx.allowsField("sign", field);
1506
+ const mayFillByHand = (field) => isFillableByHand(ctx.settings().get().fillable, field.family) && (field.family === "signature" ? maySign(field) : mayFill(field));
1418
1507
  /** The form's groups, `null` (no group) among them. */
1419
1508
  const groups = memo(() => [fields.view()], (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))]);
1420
1509
  return {
1421
1510
  mayFill,
1422
1511
  maySign,
1512
+ mayFillByHand,
1513
+ takesInput: (field) => !field.readOnly && mayFillByHand(field),
1423
1514
  assertMayFill: (field, operation) => ctx.assertAllowedField("fill", field, operation),
1424
1515
  key: () => groups().map((groupId) => `${mayFill({ groupId }) ? 1 : 0}${maySign({ groupId }) ? 1 : 0}`).join("")
1425
1516
  };
@@ -1472,7 +1563,14 @@ function createFormattedTexts(ctx, fields) {
1472
1563
  */
1473
1564
  const NOTHING_SHOWN = Object.freeze([]);
1474
1565
  const numberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
1475
- function createWidgetLooks({ fields, formatted, design }) {
1566
+ function createWidgetLooks({ fields, formatted, design, fonts }) {
1567
+ /** Moves when the fonts plugin may draw a widget's text differently. */
1568
+ const fontsEpoch = () => fonts()?.getPaintFontsEpoch() ?? 0;
1569
+ /**
1570
+ * The fonts `row` draws `text` in: the fonts plugin's (`null` while it finds them), else
1571
+ * `undefined`, the widget's standard font.
1572
+ */
1573
+ const paintFontsOf = (row, text) => fonts()?.getPaintFonts(row.fontFamily ?? "helvetica", text);
1476
1574
  /** What the widget's picture depends on, as one string. */
1477
1575
  const lookKeyOf = (row, field) => {
1478
1576
  const box = row.box ?? row.rect;
@@ -1516,7 +1614,8 @@ function createWidgetLooks({ fields, formatted, design }) {
1516
1614
  fields.view(),
1517
1615
  fields.get(),
1518
1616
  formatted.version(),
1519
- design.lending()
1617
+ design.lending(),
1618
+ fontsEpoch()
1520
1619
  ], (pageObjectNumber, view, truth, _formatted, lent) => lent ? NOTHING_SHOWN : shownWidgetsOf(view, pageObjectNumber, (row) => {
1521
1620
  const number = numberOf(row.ref);
1522
1621
  return {
@@ -1524,15 +1623,22 @@ function createWidgetLooks({ fields, formatted, design }) {
1524
1623
  pictureVersion: pictureVersionOf(truth, number)
1525
1624
  };
1526
1625
  }));
1527
- /** The painter's drawing of `row` (in the view's field, as this session formatted it) at `box`, turned. */
1528
- const paint = (row, box, rotation) => {
1626
+ /**
1627
+ * The painter's drawing of `row` (in the view's field, as this session formatted it) at `box`,
1628
+ * turned. While the fonts its text needs are found, `null`, so the engine's picture stays;
1629
+ * unless `now`, then in the widget's standard font.
1630
+ */
1631
+ const paint = (row, box, rotation, now = false) => {
1529
1632
  const field = fieldForWidget(fields.view(), numberOf(row.ref));
1530
1633
  if (!field) return null;
1531
1634
  const text = formatted.textOf(field);
1635
+ const shown = text === null ? {} : { text };
1636
+ const painted = paintFontsOf(row, widgetText(row, field, shown));
1637
+ if (painted === null && !now) return null;
1532
1638
  const drawing = widgetDrawing({
1533
1639
  ...row,
1534
1640
  box
1535
- }, field, text === null ? {} : { text });
1641
+ }, field, shown, painted ?? void 0);
1536
1642
  return drawing && widgetScene(drawing, {
1537
1643
  box,
1538
1644
  rotation
@@ -1546,12 +1652,36 @@ function createWidgetLooks({ fields, formatted, design }) {
1546
1652
  return [
1547
1653
  row,
1548
1654
  field,
1549
- field ? formatted.textOf(field) : null
1655
+ field ? formatted.textOf(field) : null,
1656
+ fontsEpoch()
1550
1657
  ];
1551
1658
  }, (_number, row) => {
1552
1659
  const scene = row && paint(row, row.box ?? row.rect, row.rotation);
1553
1660
  return scene ? { scene } : null;
1554
1661
  });
1662
+ /**
1663
+ * How a browser draws text in a widget's font: the fonts plugin's CSS for
1664
+ * it (the first widget in a font that isn't standard reads the document's
1665
+ * fonts); without the plugin, the standard font the engine falls back to.
1666
+ */
1667
+ const fontCssOf = (font) => fonts()?.getFontCss(font) ?? standardFontCss(standardFontOf(font));
1668
+ /**
1669
+ * Until the fonts plugin has found a field's fonts, the layout in its own
1670
+ * font, when it isn't a standard one: its program, the fallbacks and the
1671
+ * last resort, as the fonts plugin draws it. The layout's numbers stay the
1672
+ * standard face's until then.
1673
+ */
1674
+ const inItsFont = (layout, font) => {
1675
+ if (!fonts() || !font || isStandardFontName(font)) return layout;
1676
+ const css = fontCssOf(font);
1677
+ return {
1678
+ ...layout,
1679
+ programs: css.programs,
1680
+ fontFamily: css.fontFamily,
1681
+ fontWeight: css.fontWeight,
1682
+ fontStyle: css.fontStyle
1683
+ };
1684
+ };
1555
1685
  return {
1556
1686
  listShownWidgets: (pageObjectNumber) => shownOn(pageObjectNumber),
1557
1687
  getWidgetPainting: (ref) => sceneOf(numberOf(ref)),
@@ -1566,14 +1696,21 @@ function createWidgetLooks({ fields, formatted, design }) {
1566
1696
  */
1567
1697
  painterOf: (row) => {
1568
1698
  const field = fieldForWidget(fields.view(), numberOf(row.ref));
1569
- return field && paints(field) ? (box) => paint(row, box, 0) ?? [] : null;
1699
+ return field && paints(field) ? (box) => paint(row, box, 0, true) ?? [] : null;
1570
1700
  },
1571
1701
  getTextEditorLayout: (ref, text) => {
1572
1702
  const view = fields.view();
1573
1703
  const number = numberOf(ref);
1574
1704
  const row = widgetRowOf(view, number);
1575
1705
  const field = row ? fieldForWidget(view, number) : null;
1576
- return row && field ? textEditorLayout(row, field, text) : null;
1706
+ if (!row || !field) return null;
1707
+ const painted = paintFontsOf(row, widgetText(row, field, { text }));
1708
+ const layout = textEditorLayout(row, field, text, painted ?? void 0);
1709
+ return layout && (painted ? layout : inItsFont(layout, row.fontFamily ?? null));
1710
+ },
1711
+ getWidgetFontCss: (ref) => {
1712
+ const row = widgetRowOf(fields.view(), numberOf(ref));
1713
+ return row ? fontCssOf(row.fontFamily ?? "helvetica") : null;
1577
1714
  }
1578
1715
  };
1579
1716
  }
@@ -1688,6 +1825,7 @@ function createServices(ctx) {
1688
1825
  fields,
1689
1826
  rights: createFillRights(ctx, fields),
1690
1827
  events,
1828
+ cursor: createCursor(ctx, fields, events),
1691
1829
  siblings,
1692
1830
  scripting: createScriptingSeam(ctx, siblings),
1693
1831
  design,
@@ -1696,7 +1834,8 @@ function createServices(ctx) {
1696
1834
  looks: createWidgetLooks({
1697
1835
  fields,
1698
1836
  formatted,
1699
- design
1837
+ design,
1838
+ fonts: () => ctx.tryGet(FontsToken)
1700
1839
  }),
1701
1840
  enqueue: ctx.serialQueue("writes"),
1702
1841
  keyOf: (ref) => canonicalKey(fields.view(), ref)
@@ -1710,7 +1849,7 @@ function createServices(ctx) {
1710
1849
  * tree-less widget falls back to the form's own scripted activation.
1711
1850
  */
1712
1851
  function createActivation(ctx, services, { fill }) {
1713
- const { fields, scripting } = services;
1852
+ const { fields, scripting, cursor } = services;
1714
1853
  /** The widget's activation action, from its row in the form. */
1715
1854
  const annotationActivation = async (ref) => {
1716
1855
  await fields.settled();
@@ -1788,6 +1927,7 @@ function createActivation(ctx, services, { fill }) {
1788
1927
  };
1789
1928
  },
1790
1929
  notifyWidgetEvent: (fieldRef, annotationRef, event) => {
1930
+ if (event === "focus" || event === "blur") cursor.note(event, fieldRef, annotationRef);
1791
1931
  const actions = ctx.tryGet(ActionsToken);
1792
1932
  if (!actions) return;
1793
1933
  const source = widgetSource(fieldRef, annotationRef);
@@ -2366,6 +2506,115 @@ function failedFill(result) {
2366
2506
  return new PluginError("operation-failed", "form", result.error?.message ?? result.diagnostics[0]?.message ?? "the write failed");
2367
2507
  }
2368
2508
  //#endregion
2509
+ //#region src/write/focus.ts
2510
+ /**
2511
+ * Moving the cursor between fields: `focus()`, `focusNext()` (what Tab does), the arrow keys in a
2512
+ * radio group, and the field the cursor is in. This area decides where the cursor goes: which
2513
+ * field, which of its boxes, in Tab's order (the engine's `tabOrderOf()`); the cursor service
2514
+ * (`services/cursor.ts`) brings the box into view and hands it to its control.
2515
+ */
2516
+ /** A radio button as its field lists it: whether it's the checked one, and the value it picks. */
2517
+ const radioButtonOf = (field, widget) => field.family === "radio" ? field.widgets.find((candidate) => candidate.objectNumber === widget) ?? null : null;
2518
+ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
2519
+ /** Every box that shows, in Tab's order, and the ones Tab stops at. */
2520
+ const order = memo(() => [
2521
+ fields.view(),
2522
+ ctx.document()?.pages,
2523
+ rights.key(),
2524
+ ctx.settings().get().fillable
2525
+ ], (index, pages) => {
2526
+ const rows = tabOrderOf((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []);
2527
+ const position = /* @__PURE__ */ new Map();
2528
+ const stops = [];
2529
+ const groups = /* @__PURE__ */ new Set();
2530
+ rows.forEach((row, at) => {
2531
+ const widget = widgetObjectOf(row.ref);
2532
+ position.set(widget, at);
2533
+ const field = fieldForWidget(index, widget);
2534
+ if (!field || !rights.takesInput(field)) return;
2535
+ if (field.family === "radio") {
2536
+ const group = `${fieldKeyOf(field)}@${row.page.objectNumber}`;
2537
+ if (groups.has(group)) return;
2538
+ groups.add(group);
2539
+ }
2540
+ stops.push({
2541
+ row,
2542
+ field,
2543
+ at
2544
+ });
2545
+ });
2546
+ return {
2547
+ rows,
2548
+ position,
2549
+ stops
2550
+ };
2551
+ });
2552
+ /** The buttons of a radio group, in Tab's order; on one page, with `page`. */
2553
+ const buttonsOf = (field, page) => order().rows.filter((row) => (page === void 0 || row.page.objectNumber === page) && fieldForWidget(fields.view(), widgetObjectOf(row.ref)) === field);
2554
+ /**
2555
+ * The box that takes the cursor at a stop: a radio group's checked button on that page, else
2556
+ * its first, or its last when Shift+Tab comes to it from after it.
2557
+ */
2558
+ const boxAt = (stop, backward) => {
2559
+ if (stop.field.family !== "radio") return stop.row;
2560
+ const buttons = buttonsOf(stop.field, stop.row.page.objectNumber);
2561
+ return buttons.find((button) => radioButtonOf(stop.field, widgetObjectOf(button.ref))?.checked) ?? (backward ? buttons.at(-1) ?? stop.row : stop.row);
2562
+ };
2563
+ const focus = (ref, options = {}) => {
2564
+ const index = fields.view();
2565
+ const field = fieldByRef(index, ref);
2566
+ if (!field || !rights.takesInput(field)) return false;
2567
+ let row;
2568
+ if (options.widget) {
2569
+ const widget = widgetObjectOf(options.widget);
2570
+ if (fieldForWidget(index, widget) !== field) return false;
2571
+ row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
2572
+ } else {
2573
+ const stop = order().stops.find((candidate) => candidate.field === field);
2574
+ row = stop && boxAt(stop, false);
2575
+ }
2576
+ return row ? cursor.goTo(row, options.select ?? false) : false;
2577
+ };
2578
+ const focusNext = (options = {}) => {
2579
+ const index = fields.view();
2580
+ const { position, stops } = order();
2581
+ const backward = options.backward ?? false;
2582
+ const fromField = options.from ? fieldByRef(index, options.from) : null;
2583
+ const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
2584
+ const at = from === null ? null : position.get(from) ?? null;
2585
+ const field = from === null ? null : fieldForWidget(index, from);
2586
+ const page = from === null ? null : widgetRowOf(index, from)?.page.objectNumber;
2587
+ const candidates = stops.filter((stop) => (!options.empty || isEmpty(stop.field)) && !(stop.field === field && field.family === "radio" && stop.row.page.objectNumber === page));
2588
+ const ahead = candidates.filter((stop) => at === null ? true : backward ? stop.at < at : stop.at > at);
2589
+ const next = (backward ? ahead.at(-1) : ahead[0]) ?? (options.wrap ? backward ? candidates.at(-1) : candidates[0] : void 0);
2590
+ return next ? cursor.goTo(boxAt(next, backward), true) : false;
2591
+ };
2592
+ const moveInGroup = (ref, backward) => {
2593
+ const widget = widgetObjectOf(ref);
2594
+ const field = fieldForWidget(fields.view(), widget);
2595
+ if (!field || field.family !== "radio" || !rights.takesInput(field)) return false;
2596
+ const buttons = buttonsOf(field);
2597
+ const here = buttons.findIndex((row) => widgetObjectOf(row.ref) === widget);
2598
+ if (here < 0 || buttons.length < 2) return false;
2599
+ const next = buttons[(here + (backward ? buttons.length - 1 : 1)) % buttons.length];
2600
+ if (!cursor.goTo(next, false)) return false;
2601
+ const button = radioButtonOf(field, widgetObjectOf(next.ref));
2602
+ if (button) {
2603
+ const activate = () => void fill.activateWidget(next.ref).catch(() => {});
2604
+ fill.setValue(field.ref, { value: button.exportValue }).then(activate, activate);
2605
+ }
2606
+ return true;
2607
+ };
2608
+ return { api: {
2609
+ focus,
2610
+ focusNext,
2611
+ getFocusedField: memo(() => [fields.view(), cursor.focused()], (index, focused) => focused ? fieldByKey(index, focused.field) : null),
2612
+ onFocusChanged: events.focusChanged.on,
2613
+ moveInGroup,
2614
+ attachFocusTarget: cursor.attach
2615
+ } };
2616
+ }
2617
+ //#endregion
2369
2618
  //#region src/write/interchange.ts
2370
2619
  function createInterchange(ctx, services) {
2371
2620
  const { enqueue, siblings } = services;
@@ -2937,6 +3186,10 @@ function createFormController(ctx) {
2937
3186
  const interchange = createInterchange(ctx, services);
2938
3187
  const activation = createActivation(ctx, services, fills);
2939
3188
  const scripts = createScriptEffects(ctx, services, fills);
3189
+ const focus = createFocus(ctx, services, {
3190
+ setValue: values.api.setValue,
3191
+ activateWidget: activation.api.activateWidget
3192
+ });
2940
3193
  const api = composeApi("form", [
2941
3194
  settings.api,
2942
3195
  fields.api,
@@ -2949,6 +3202,7 @@ function createFormController(ctx) {
2949
3202
  interchange.api,
2950
3203
  activation.api,
2951
3204
  scripts.api,
3205
+ focus.api,
2952
3206
  {
2953
3207
  canRead: () => ctx.allows("doc.forms.read"),
2954
3208
  canFill: (ref) => {
@@ -2982,7 +3236,8 @@ function createFormController(ctx) {
2982
3236
  * fills every widget. Design mode is the 'form-edit' and palette tools: with
2983
3237
  * the annotation plugin present, the form lends it the widgets, which its
2984
3238
  * tools then select, move, restyle and delete. The render plugin draws the
2985
- * widgets' pictures in both modes. `config` is the settings the app
3239
+ * widgets' pictures in both modes. With the fonts plugin, a text field in a
3240
+ * font of its own is edited in that font's program. `config` is the settings the app
2986
3241
  * registers, over {@link FORM_DEFAULTS}.
2987
3242
  */
2988
3243
  const formPlugin = (config) => definePlugin({
@@ -2993,7 +3248,8 @@ const formPlugin = (config) => definePlugin({
2993
3248
  optional: [
2994
3249
  AnnotationToken,
2995
3250
  ActionsToken,
2996
- RenderToken
3251
+ RenderToken,
3252
+ FontsToken
2997
3253
  ],
2998
3254
  state: initialFormModel,
2999
3255
  settings: {
@@ -3007,13 +3263,15 @@ const formState = defineState(FormToken, {
3007
3263
  fields: form.list(),
3008
3264
  status: form.getStatus(),
3009
3265
  formKind: form.getFormKind(),
3010
- selectedField: form.getSelectedField()
3266
+ selectedField: form.getSelectedField(),
3267
+ focusedField: form.getFocusedField()
3011
3268
  }),
3012
3269
  empty: {
3013
3270
  fields: Object.freeze([]),
3014
3271
  status: "idle",
3015
3272
  formKind: "none",
3016
- selectedField: null
3273
+ selectedField: null,
3274
+ focusedField: null
3017
3275
  }
3018
3276
  });
3019
3277
  //#endregion