@embedpdf/plugin-annotation 3.0.0-next.20 → 3.0.0-next.22

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,6 +1,6 @@
1
1
  import { widgetAppearanceOf } from "./authoring.cjs";
2
- import { $ as Color, A as AnnotationResources, At as AnnotationState, B as AnnotationTool, Bt as ResolvedGhost, C as AnnotationPatch, Ct as StampPlacement, D as AnnotationRef, Dt as ThreadDeleteResult, E as AnnotationProperty, Et as TextItem, F as AnnotationSelectionChangedEvent, Ft as AnnotationToolInput, G as ArmedStampInfo, Gt as ToolDefaultsFor, H as AnnotationTransfer, Ht as SelectionAuthoring, I as AnnotationSettings, It as DEFAULT_TOOLS, J as AttachmentFileSource, Jt as TextSelection, K as ArmedStampPreview, Kt as Face, L as AnnotationStampsApi, Lt as GhostPolicy, M as AnnotationRotationAnchor, Mt as AnnotationToken, N as AnnotationSelectionAnchor, Nt as ARMED_STAMP_TOOL_ID, O as AnnotationReorderedEvent, Ot as ToolDefaults, P as AnnotationSelectionApi, Pt as AnnotationToolDef, Q as ClickCreate, R as AnnotationSubtype, Rt as InkAuthoringOptions, S as AnnotationOption, St as StampInput, T as AnnotationProperties, Tt as TextAlign, U as AnnotationUpdatedEvent, Ut as StampSourceSpec, V as AnnotationToolsApi, Vt as ResolvedTool, W as AnnotationWriteFailedEvent, Wt as ToolAuthoringKind, X as BlendMode, Y as Behavior, Z as ChromeSettings, _ as AnnotationHoverChangedEvent, _t as MarkupSubtype, a as AnnotationBundle, at as EditableKind, b as AnnotationImportResult, bt as ReviewStatus, c as AnnotationCreatedEvent, ct as FilePickerProvider, d as AnnotationDraftApi, dt as HandleRole, et as CommentThread, f as AnnotationDraftChangedEvent, ft as ImageGhost, g as AnnotationFlags, gt as LinkNavItem, h as AnnotationFilter, ht as LineStyle, i as AnnotationAnchor, it as CreationDraft, j as AnnotationResyncedEvent, jt as annotationState, k as AnnotationResourceRole, kt as ToolDefaultsChangedEvent, l as AnnotationDeletedEvent, lt as FilePromptRequest, m as AnnotationExportSelection, mt as LineEndings, n as AfterCreateSettings, nt as CommentThreadReview, o as AnnotationCapability, ot as EditableKinds, p as AnnotationEditingChangedEvent, pt as LineEnding, q as AttachmentContent, qt as TextFormat, r as Annotation, rt as CommentsApi, s as AnnotationConfig, st as FieldValues, t as ANNOTATION_DEFAULTS, tt as CommentThreadChangedEvent, u as AnnotationDraft, ut as FlagKey, v as AnnotationImportDrop, vt as MeasurementIntent, w as AnnotationPosition, wt as StampPreviewProvider, x as AnnotationLinksApi, xt as SnapSettings, y as AnnotationImportOptions, yt as PdfLinkTarget, z as AnnotationTextApi, zt as PromptSourceSpec } from "./contract-Cm0cfAzG.cjs";
3
- import { f as AnnotationModel, n as AnnotationHostCapability } from "./host-contract-BDwyBNrs.cjs";
2
+ import { $ as Color, A as AnnotationResources, At as AnnotationState, B as AnnotationTool, Bt as ResolvedGhost, C as AnnotationPatch, Ct as StampPlacement, D as AnnotationRef, Dt as ThreadDeleteResult, E as AnnotationProperty, Et as TextItem, F as AnnotationSelectionChangedEvent, Ft as AnnotationToolInput, G as ArmedStampInfo, Gt as ToolDefaultsFor, H as AnnotationTransfer, Ht as SelectionAuthoring, I as AnnotationSettings, It as DEFAULT_TOOLS, J as AttachmentFileSource, Jt as TextFormat, K as ArmedStampPreview, L as AnnotationStampsApi, Lt as GhostPolicy, M as AnnotationRotationAnchor, Mt as AnnotationToken, N as AnnotationSelectionAnchor, Nt as ARMED_STAMP_TOOL_ID, O as AnnotationReorderedEvent, Ot as ToolDefaults, P as AnnotationSelectionApi, Pt as AnnotationToolDef, Q as ClickCreate, R as AnnotationSubtype, Rt as InkAuthoringOptions, S as AnnotationOption, St as StampInput, T as AnnotationProperties, Tt as TextAlign, U as AnnotationUpdatedEvent, Ut as StampSourceSpec, V as AnnotationToolsApi, Vt as ResolvedTool, W as AnnotationWriteFailedEvent, Wt as ToolAuthoringKind, X as BlendMode, Y as Behavior, Yt as TextSelection, Z as ChromeSettings, _ as AnnotationHoverChangedEvent, _t as MarkupSubtype, a as AnnotationBundle, at as EditableKind, b as AnnotationImportResult, bt as ReviewStatus, c as AnnotationCreatedEvent, ct as FilePickerProvider, d as AnnotationDraftApi, dt as HandleRole, et as CommentThread, f as AnnotationDraftChangedEvent, ft as ImageGhost, g as AnnotationFlags, gt as LinkNavItem, h as AnnotationFilter, ht as LineStyle, i as AnnotationAnchor, it as CreationDraft, j as AnnotationResyncedEvent, jt as annotationState, k as AnnotationResourceRole, kt as ToolDefaultsChangedEvent, l as AnnotationDeletedEvent, lt as FilePromptRequest, m as AnnotationExportSelection, mt as LineEndings, n as AfterCreateSettings, nt as CommentThreadReview, o as AnnotationCapability, ot as EditableKinds, p as AnnotationEditingChangedEvent, pt as LineEnding, q as AttachmentContent, qt as Face, r as Annotation, rt as CommentsApi, s as AnnotationConfig, st as FieldValues, t as ANNOTATION_DEFAULTS, tt as CommentThreadChangedEvent, u as AnnotationDraft, ut as FlagKey, v as AnnotationImportDrop, vt as MeasurementIntent, w as AnnotationPosition, wt as StampPreviewProvider, x as AnnotationLinksApi, xt as SnapSettings, y as AnnotationImportOptions, yt as PdfLinkTarget, z as AnnotationTextApi, zt as PromptSourceSpec } from "./contract-BzsydV7F.cjs";
3
+ import { f as AnnotationModel, n as AnnotationHostCapability } from "./host-contract-CYPNi49b.cjs";
4
4
  import { MIN_DRAG, Placement, gesturePlacement, kindNamed, propertiesOf, resolveClickPlacement } from "@embedpdf/core-annotation";
5
5
  import { annotationKey } from "@embedpdf/core";
6
6
  //#region src/annotation.plugin.d.ts
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { widgetAppearanceOf } from "./authoring.js";
2
- import { $ as Color, A as AnnotationResources, At as AnnotationState, B as AnnotationTool, Bt as ResolvedGhost, C as AnnotationPatch, Ct as StampPlacement, D as AnnotationRef, Dt as ThreadDeleteResult, E as AnnotationProperty, Et as TextItem, F as AnnotationSelectionChangedEvent, Ft as AnnotationToolInput, G as ArmedStampInfo, Gt as ToolDefaultsFor, H as AnnotationTransfer, Ht as SelectionAuthoring, I as AnnotationSettings, It as DEFAULT_TOOLS, J as AttachmentFileSource, Jt as TextSelection, K as ArmedStampPreview, Kt as Face, L as AnnotationStampsApi, Lt as GhostPolicy, M as AnnotationRotationAnchor, Mt as AnnotationToken, N as AnnotationSelectionAnchor, Nt as ARMED_STAMP_TOOL_ID, O as AnnotationReorderedEvent, Ot as ToolDefaults, P as AnnotationSelectionApi, Pt as AnnotationToolDef, Q as ClickCreate, R as AnnotationSubtype, Rt as InkAuthoringOptions, S as AnnotationOption, St as StampInput, T as AnnotationProperties, Tt as TextAlign, U as AnnotationUpdatedEvent, Ut as StampSourceSpec, V as AnnotationToolsApi, Vt as ResolvedTool, W as AnnotationWriteFailedEvent, Wt as ToolAuthoringKind, X as BlendMode, Y as Behavior, Z as ChromeSettings, _ as AnnotationHoverChangedEvent, _t as MarkupSubtype, a as AnnotationBundle, at as EditableKind, b as AnnotationImportResult, bt as ReviewStatus, c as AnnotationCreatedEvent, ct as FilePickerProvider, d as AnnotationDraftApi, dt as HandleRole, et as CommentThread, f as AnnotationDraftChangedEvent, ft as ImageGhost, g as AnnotationFlags, gt as LinkNavItem, h as AnnotationFilter, ht as LineStyle, i as AnnotationAnchor, it as CreationDraft, j as AnnotationResyncedEvent, jt as annotationState, k as AnnotationResourceRole, kt as ToolDefaultsChangedEvent, l as AnnotationDeletedEvent, lt as FilePromptRequest, m as AnnotationExportSelection, mt as LineEndings, n as AfterCreateSettings, nt as CommentThreadReview, o as AnnotationCapability, ot as EditableKinds, p as AnnotationEditingChangedEvent, pt as LineEnding, q as AttachmentContent, qt as TextFormat, r as Annotation, rt as CommentsApi, s as AnnotationConfig, st as FieldValues, t as ANNOTATION_DEFAULTS, tt as CommentThreadChangedEvent, u as AnnotationDraft, ut as FlagKey, v as AnnotationImportDrop, vt as MeasurementIntent, w as AnnotationPosition, wt as StampPreviewProvider, x as AnnotationLinksApi, xt as SnapSettings, y as AnnotationImportOptions, yt as PdfLinkTarget, z as AnnotationTextApi, zt as PromptSourceSpec } from "./contract-QAvnfm2b.js";
3
- import { f as AnnotationModel, n as AnnotationHostCapability } from "./host-contract-BUub1Un-.js";
2
+ import { $ as Color, A as AnnotationResources, At as AnnotationState, B as AnnotationTool, Bt as ResolvedGhost, C as AnnotationPatch, Ct as StampPlacement, D as AnnotationRef, Dt as ThreadDeleteResult, E as AnnotationProperty, Et as TextItem, F as AnnotationSelectionChangedEvent, Ft as AnnotationToolInput, G as ArmedStampInfo, Gt as ToolDefaultsFor, H as AnnotationTransfer, Ht as SelectionAuthoring, I as AnnotationSettings, It as DEFAULT_TOOLS, J as AttachmentFileSource, Jt as TextFormat, K as ArmedStampPreview, L as AnnotationStampsApi, Lt as GhostPolicy, M as AnnotationRotationAnchor, Mt as AnnotationToken, N as AnnotationSelectionAnchor, Nt as ARMED_STAMP_TOOL_ID, O as AnnotationReorderedEvent, Ot as ToolDefaults, P as AnnotationSelectionApi, Pt as AnnotationToolDef, Q as ClickCreate, R as AnnotationSubtype, Rt as InkAuthoringOptions, S as AnnotationOption, St as StampInput, T as AnnotationProperties, Tt as TextAlign, U as AnnotationUpdatedEvent, Ut as StampSourceSpec, V as AnnotationToolsApi, Vt as ResolvedTool, W as AnnotationWriteFailedEvent, Wt as ToolAuthoringKind, X as BlendMode, Y as Behavior, Yt as TextSelection, Z as ChromeSettings, _ as AnnotationHoverChangedEvent, _t as MarkupSubtype, a as AnnotationBundle, at as EditableKind, b as AnnotationImportResult, bt as ReviewStatus, c as AnnotationCreatedEvent, ct as FilePickerProvider, d as AnnotationDraftApi, dt as HandleRole, et as CommentThread, f as AnnotationDraftChangedEvent, ft as ImageGhost, g as AnnotationFlags, gt as LinkNavItem, h as AnnotationFilter, ht as LineStyle, i as AnnotationAnchor, it as CreationDraft, j as AnnotationResyncedEvent, jt as annotationState, k as AnnotationResourceRole, kt as ToolDefaultsChangedEvent, l as AnnotationDeletedEvent, lt as FilePromptRequest, m as AnnotationExportSelection, mt as LineEndings, n as AfterCreateSettings, nt as CommentThreadReview, o as AnnotationCapability, ot as EditableKinds, p as AnnotationEditingChangedEvent, pt as LineEnding, q as AttachmentContent, qt as Face, r as Annotation, rt as CommentsApi, s as AnnotationConfig, st as FieldValues, t as ANNOTATION_DEFAULTS, tt as CommentThreadChangedEvent, u as AnnotationDraft, ut as FlagKey, v as AnnotationImportDrop, vt as MeasurementIntent, w as AnnotationPosition, wt as StampPreviewProvider, x as AnnotationLinksApi, xt as SnapSettings, y as AnnotationImportOptions, yt as PdfLinkTarget, z as AnnotationTextApi, zt as PromptSourceSpec } from "./contract-DnQUGmxG.js";
3
+ import { f as AnnotationModel, n as AnnotationHostCapability } from "./host-contract-BMliTeaD.js";
4
4
  import { annotationKey } from "@embedpdf/core";
5
5
  import { MIN_DRAG, Placement, gesturePlacement, kindNamed, propertiesOf, resolveClickPlacement } from "@embedpdf/core-annotation";
6
6
  //#region src/annotation.plugin.d.ts
package/dist/index.js CHANGED
@@ -7,11 +7,11 @@ import { FontsToken } from "@embedpdf/plugin-fonts/contract";
7
7
  import { InteractionToken } from "@embedpdf/plugin-interaction/contract/host";
8
8
  import { RenderToken } from "@embedpdf/plugin-render/contract";
9
9
  import { SelectionToken } from "@embedpdf/plugin-selection/contract/host";
10
- import { ANNOTATION_FIELD_NAMES, STANDARD_FACES, anchorOf, annotationKey as annotationKey$1, annotationPatchBetween, buildCommentThreads, colorOf, compareIsoDateTime, deletedWith, faceForFontName, familyKey, fontNameForFace, imageSourceOfBytes, isDimension, isLocalEngine, isReadout, measurementReadout, pageBoxOf, reorderPart, reorderedList, resolveAnnotationPatch, resolveBinarySource, serializeError, sniffBinaryMetadata, toPageRef, viewportForPoint } from "@embedpdf/engine-core/runtime";
11
- import { MIN_DRAG, anchorModeOf, anchoredGeom, annotContentsEditable, annotDeletable, annotTransformable, annotationAfter, annotationAnchor, annotationOfNew, applyStyleToRange, canMove, chrome, creationDraftAnchor, cursorAt, defaultsFor, drawnAfter, expandGroups, faceForFont, fitStampBox, fromDTO, gesturePlacement, gesturePlacement as gesturePlacement$1, groupKeyOf, groupOf, hitTest, initialSession, initialTextStyle, isContentsEditableByHand, isDrag, isEditableByHand, isOnTextBox, isSelectable, isSubstrateOnly, isTransformableByHand, kindNamed, kindNamed as kindNamed$1, kindOf, linkChildRects, linkChildrenOf, linkOf, locateOffset, newRecordsAtMost, pageItems, placedShape, propertiesOf, propertiesOf as propertiesOf$1, readOfDefaults, refOf, resolveClickPlacement, resolveClickPlacement as resolveClickPlacement$1, richDocOf, rotationAnchor, sameSession, selectionAnchor, selectionInBox, shapeOf, sharedProperties, sourceOfConfirmed, sourceOfNew, styleOf, textBoxOf, textBoxes, textOf, textPlateInset, toolAnnotation, unanchoredGeom, unmadeItem, update, uprightRotation, viewable, writableTarget } from "@embedpdf/core-annotation";
10
+ import { ANNOTATION_FIELD_NAMES, STANDARD_FACES, anchorOf, annotationKey as annotationKey$1, annotationPatchBetween, buildCommentThreads, colorOf, compareIsoDateTime, deletedWith, faceForFontName, familyKey, fontNameForFace, imageSourceOfBytes, isDimension, isLocalEngine, isReadout, measurementReadout, pageBoxOf, reorderPart, reorderedList, resolveAnnotationPatch, resolveBinarySource, serializeError, sniffBinaryMetadata, standardFontForFace, toPageRef, viewportForPoint } from "@embedpdf/engine-core/runtime";
11
+ import { MIN_DRAG, anchorModeOf, anchoredGeom, annotContentsEditable, annotDeletable, annotTransformable, annotationAfter, annotationAnchor, annotationOfNew, applyStyleToRange, canMove, chrome, creationDraftAnchor, cursorAt, defaultsFor, drawnAfter, expandGroups, faceForFont, fitStampBox, fromDTO, gesturePlacement, gesturePlacement as gesturePlacement$1, groupKeyOf, groupOf, hitTest, initialSession, initialTextStyle, isContentsEditableByHand, isDrag, isEditableByHand, isOnTextBox, isSelectable, isSubstrateOnly, isTransformableByHand, kindNamed, kindNamed as kindNamed$1, kindOf, linkChildRects, linkChildrenOf, linkOf, locateOffset, newRecordsAtMost, pageItems, placedShape, propertiesOf, propertiesOf as propertiesOf$1, readOfDefaults, refOf, resolveClickPlacement, resolveClickPlacement as resolveClickPlacement$1, richDocOf, richTextLength, rotationAnchor, sameSession, selectionAnchor, selectionInBox, selectionProperties, shapeOf, sourceOfConfirmed, sourceOfNew, styleAt, styleOf, textBoxOf, textBoxes, textOf, textPlateInset, toolAnnotation, typeWithStyle, unanchoredGeom, unmadeItem, update, uprightRotation, viewable, writableTarget } from "@embedpdf/core-annotation";
12
12
  import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
13
13
  import { RenderToken as RenderToken$1 } from "@embedpdf/plugin-render/contract/host";
14
- import { standardFontCss, standardFontForFace, standardFontOf, standardFontOfProgramFamily } from "@embedpdf/core-fonts";
14
+ import { standardFontCss, standardFontOf, standardFontOfProgramFamily } from "@embedpdf/core-fonts";
15
15
  import { InteractionToken as InteractionToken$1 } from "@embedpdf/plugin-interaction/contract";
16
16
  import { SelectionToken as SelectionToken$1 } from "@embedpdf/plugin-selection/contract";
17
17
  import { scriptColorToRgb } from "@embedpdf/core-acrojs";
@@ -1136,7 +1136,8 @@ function createChromeReads(ctx, { store, geometry, behaviors, settings }) {
1136
1136
  *
1137
1137
  * • a flat props patch → the run delta it means for a text range (font,
1138
1138
  * size, colour, bold/italic/underline) and the keys left for the body
1139
- * • what a range reads back for those keys (agree → the value, else mixed)
1139
+ * • what a range reads back for those keys (agree → the value, else mixed),
1140
+ * and a caret: the text typed there next
1140
1141
  * • faces: the DTO font a face names
1141
1142
  * • the commit rule: a document nothing overrides on a plain annotation
1142
1143
  * commits as `contents`; anything else as `richText`
@@ -1264,11 +1265,24 @@ function runsInRange(doc, range) {
1264
1265
  }
1265
1266
  return out;
1266
1267
  }
1267
- /** The values a range reads back for the range keys — resolved against the
1268
- * body, one value where every run agrees, `mixed` where they don't. */
1268
+ /** The values a range reads back for the range keys: the runs it covers (`runProps`). */
1269
1269
  function rangeProps(doc, range, fonts) {
1270
- const runs = runsInRange(doc, range);
1271
- const body = doc.body;
1270
+ return runProps(doc.body, runsInRange(doc, range), fonts);
1271
+ }
1272
+ /**
1273
+ * The values a caret reads back for the range keys: the text typed there
1274
+ * next, in the style of the text before it (`styleAt`) with the style chosen
1275
+ * at the caret over it.
1276
+ */
1277
+ function caretProps(doc, at, typing, fonts) {
1278
+ return runProps(doc.body, [{
1279
+ ...styleAt(doc, at),
1280
+ ...typing
1281
+ }], fonts);
1282
+ }
1283
+ /** The values runs read back for the range keys: resolved against the
1284
+ * body, one value where every run agrees, `mixed` where they don't. */
1285
+ function runProps(body, runs, fonts) {
1272
1286
  const resolve = (delta) => ({
1273
1287
  family: delta.family ?? body.family,
1274
1288
  weight: delta.weight ?? body.weight,
@@ -1347,12 +1361,24 @@ function propertyValues(properties, sources) {
1347
1361
  * selection of frozen annotations has nothing to restyle.
1348
1362
  */
1349
1363
  function createPropertyReads(ctx, { store, fonts }) {
1364
+ /** The editor's selection inside the annotation being edited, or null (no
1365
+ * editor selection, or one left behind by a previous edit). */
1366
+ const editorSelection = (model) => {
1367
+ const ts = ctx.state.get().textSelection;
1368
+ return ts && model.editing === ts.id && model.byId[ts.id] ? ts : null;
1369
+ };
1350
1370
  /** The editor's text range inside the annotation being edited, or null
1351
- * (no editor selection, a bare caret, or a selection left behind by a
1352
- * previous edit). The one condition that routes the range properties to runs. */
1371
+ * (no editor selection, or a bare caret). The one condition that routes
1372
+ * the range properties to runs. */
1353
1373
  const activeTextRange = (model) => {
1354
- const ts = ctx.state.get().textSelection;
1355
- return ts && model.editing === ts.id && ts.end > ts.start && model.byId[ts.id] ? ts : null;
1374
+ const ts = editorSelection(model);
1375
+ return ts && ts.end > ts.start ? ts : null;
1376
+ };
1377
+ /** The editor's caret inside the annotation being edited, or null. The
1378
+ * range properties there are the text typed next. */
1379
+ const activeCaret = (model) => {
1380
+ const ts = editorSelection(model);
1381
+ return ts && ts.end === ts.start ? ts : null;
1356
1382
  };
1357
1383
  /** What a panel reads of one member: its fields, its text as shown, and its link. */
1358
1384
  const sourcesOf = (model, record) => {
@@ -1364,29 +1390,42 @@ function createPropertyReads(ctx, { store, fonts }) {
1364
1390
  link: annotation.subtype === "link" ? annotation.target ?? null : linkOf(model, record.id)
1365
1391
  };
1366
1392
  };
1393
+ /**
1394
+ * What a free text's range properties read: the text the next change
1395
+ * styles. The editor's range, the text typed next at its caret, else all of
1396
+ * the box's text. `null` for any other kind.
1397
+ */
1398
+ const textPropsOf = (model, record) => {
1399
+ if (record.annotation.subtype !== "free-text") return null;
1400
+ const doc = richDocOf(record.annotation, fonts);
1401
+ const ts = editorSelection(model);
1402
+ if (ts?.id !== record.id) return rangeProps(doc, {
1403
+ start: 0,
1404
+ end: richTextLength(doc)
1405
+ }, fonts);
1406
+ if (ts.end > ts.start) return rangeProps(doc, ts, fonts);
1407
+ return caretProps(doc, ts.start, ts.typing, fonts);
1408
+ };
1367
1409
  let cache = null;
1368
1410
  const selectionPropertiesOf = () => {
1369
1411
  const model = store.model();
1370
- const range = activeTextRange(model);
1371
- if (cache && cache.model === model && cache.range === range) return cache.v;
1412
+ const selection = editorSelection(model);
1413
+ if (cache && cache.model === model && cache.selection === selection) return cache.v;
1372
1414
  const members = model.selected.map((id) => model.byId[id]).filter((record) => !!record && isEditableByHand(model, record.annotation));
1373
- const properties = sharedProperties(members.map((record) => kindOf(record.annotation)));
1415
+ const properties = selectionProperties(model, members.map((record) => record.annotation));
1374
1416
  const sources = members.map((record) => sourcesOf(model, record));
1417
+ const texts = members.map((record) => textPropsOf(model, record));
1418
+ const valueOf = (spec, index) => {
1419
+ const text = texts[index];
1420
+ return text && RANGE_KEYS.includes(spec.key) ? text.values[spec.key] : propertyValue(spec, sources[index]);
1421
+ };
1375
1422
  const values = sources.length ? propertyValues(properties, sources[0]) : {};
1376
1423
  const mixed = [];
1377
1424
  for (const spec of properties) {
1378
- const first = JSON.stringify(propertyValue(spec, sources[0]));
1379
- if (sources.some((source) => JSON.stringify(propertyValue(spec, source)) !== first)) mixed.push(spec.key);
1380
- }
1381
- if (range && members.length === 1 && members[0].id === range.id) {
1382
- const rp = rangeProps(richDocOf(members[0].annotation, fonts), range, fonts);
1383
- for (const spec of properties) {
1384
- if (!RANGE_KEYS.includes(spec.key)) continue;
1385
- values[spec.key] = rp.values[spec.key];
1386
- const index = mixed.indexOf(spec.key);
1387
- if (index >= 0) mixed.splice(index, 1);
1388
- if (rp.mixed.includes(spec.key)) mixed.push(spec.key);
1389
- }
1425
+ const ofText = RANGE_KEYS.includes(spec.key);
1426
+ if (ofText && texts[0]) values[spec.key] = texts[0].values[spec.key];
1427
+ const first = JSON.stringify(valueOf(spec, 0));
1428
+ if (sources.some((_, index) => JSON.stringify(valueOf(spec, index)) !== first) || ofText && texts.some((text) => text?.mixed.includes(spec.key))) mixed.push(spec.key);
1390
1429
  }
1391
1430
  const result = {
1392
1431
  properties,
@@ -1395,13 +1434,14 @@ function createPropertyReads(ctx, { store, fonts }) {
1395
1434
  };
1396
1435
  cache = {
1397
1436
  model,
1398
- range,
1437
+ selection,
1399
1438
  v: result
1400
1439
  };
1401
1440
  return result;
1402
1441
  };
1403
1442
  return {
1404
1443
  activeTextRange,
1444
+ activeCaret,
1405
1445
  selectionPropertiesOf
1406
1446
  };
1407
1447
  }
@@ -3082,8 +3122,10 @@ function createStore(ctx, view, records, events, lending) {
3082
3122
  * program the engine writes with. A box someone types in is resolved the way
3083
3123
  * its write will be (the fonts plugin's `resolve`, with the box, so its own
3084
3124
  * font counts): when the edit starts, and again after a pause in typing once
3085
- * the text has a character it wasn't resolved with. Any other box is drawn in
3086
- * the fonts its names say. Without the fonts plugin, a box is drawn in the
3125
+ * the text has a character it wasn't resolved with. An answer holds for the
3126
+ * faces it was asked about: a box restyled since (another font, a bold word)
3127
+ * is asked again, and drawn in the fonts its names say until it is answered.
3128
+ * Any other box is drawn in the fonts its names say. Without the fonts plugin, a box is drawn in the
3087
3129
  * standard font the engine falls back to for its font or face, in that
3088
3130
  * font's built-in program (`@embedpdf/core-fonts`).
3089
3131
  */
@@ -3097,13 +3139,16 @@ const codePointsOf = (text) => Array.from(text, (char) => char.codePointAt(0));
3097
3139
  function createTextFonts(ctx, store, lookup) {
3098
3140
  const fonts = () => ctx.tryGet(FontsToken);
3099
3141
  /**
3100
- * What the engine answered per box: the run each face its text was resolved with drew in, its
3101
- * CSS asked for on each read (it changes as the programs reach the browser).
3142
+ * What the engine answered per box: the faces it was asked about, the record it was asked for
3143
+ * (a newer one with the same faces keeps the answer), and the run each face drew in, its CSS
3144
+ * asked for on each read (it changes as the programs reach the browser).
3102
3145
  */
3103
3146
  const answers = /* @__PURE__ */ new Map();
3104
3147
  /** The box being typed in, and the characters its last resolve asked about. */
3148
+ let editing = null;
3105
3149
  let asked = null;
3106
- let resolving = null;
3150
+ /** Each box's resolve in flight: a newer one for the same box replaces it. */
3151
+ const resolving = /* @__PURE__ */ new Map();
3107
3152
  let cancelPause = () => {};
3108
3153
  let answered = 0;
3109
3154
  let token = {
@@ -3116,13 +3161,13 @@ function createTextFonts(ctx, store, lookup) {
3116
3161
  const face = faceForFontName(style.fontFamily, (key) => lookup().find((font) => font.key === key));
3117
3162
  return (face.weight ?? 400) === body.weight && (face.italic ?? false) === body.italic;
3118
3163
  };
3119
- /** Ask the engine what the box's text will be drawn in, and keep the answer. */
3120
- const resolveBox = async (id) => {
3121
- const api = fonts();
3122
- const record = store.model().byId[id];
3123
- const style = record && textOf(record.annotation);
3124
- if (!api || !record || !style || record.annotation.subtype !== "free-text") return;
3125
- const ref = refOf(record) ?? void 0;
3164
+ /**
3165
+ * What the engine is asked about a box's text: the body first, then every run, unstyled ones by
3166
+ * the box's font, the rest by face; `faces` names the faces asked, whatever the text.
3167
+ */
3168
+ const questionOf = (record) => {
3169
+ const style = textOf(record.annotation);
3170
+ if (!style || record.annotation.subtype !== "free-text") return null;
3126
3171
  const doc = richDocOf(record.annotation, lookup);
3127
3172
  const body = doc.body;
3128
3173
  const faces = [BODY];
@@ -3150,32 +3195,85 @@ function createTextFonts(ctx, store, lookup) {
3150
3195
  ...face
3151
3196
  });
3152
3197
  }
3153
- asked = {
3198
+ const key = JSON.stringify({
3199
+ body: runs[0],
3200
+ faces: [...new Set(faces)].sort()
3201
+ });
3202
+ return {
3203
+ body,
3204
+ runs,
3205
+ faces,
3206
+ text,
3207
+ key
3208
+ };
3209
+ };
3210
+ /** Ask the engine what the box's text will be drawn in, and keep the answer. */
3211
+ const resolveBox = async (id) => {
3212
+ const api = fonts();
3213
+ const record = store.model().byId[id];
3214
+ const question = api && record && questionOf(record);
3215
+ if (!api || !record || !question) return;
3216
+ const { body, runs, faces, text, key } = question;
3217
+ const ref = refOf(record) ?? void 0;
3218
+ if (id === editing) asked = {
3154
3219
  id,
3155
3220
  codePoints: new Set(codePointsOf(text))
3156
3221
  };
3157
- resolving?.abort();
3222
+ resolving.get(id)?.abort();
3158
3223
  const request = new AbortController();
3159
- resolving = request;
3224
+ resolving.set(id, request);
3160
3225
  try {
3161
3226
  await api.ensureLoaded();
3162
3227
  const answer = await api.resolve({
3163
3228
  ...ref ? { annotation: ref } : {},
3164
3229
  runs
3165
3230
  }, { signal: request.signal });
3166
- if (resolving !== request) return;
3231
+ if (resolving.get(id) !== request) return;
3232
+ resolving.delete(id);
3167
3233
  const byFace = /* @__PURE__ */ new Map();
3168
3234
  answer.runs.forEach((run, index) => {
3169
3235
  const face = faces[index];
3170
3236
  if (!byFace.has(face)) byFace.set(face, run);
3171
3237
  });
3172
3238
  if (!byFace.has(faceKey(body))) byFace.set(faceKey(body), byFace.get(BODY));
3173
- answers.set(id, byFace);
3239
+ answers.set(id, {
3240
+ faces: key,
3241
+ record,
3242
+ byFace
3243
+ });
3174
3244
  answered++;
3175
3245
  ctx.notify();
3176
3246
  } catch {}
3177
3247
  };
3178
- let editing = null;
3248
+ /**
3249
+ * Drop the answers the model moved on from: a box deleted, or restyled so its faces aren't the
3250
+ * ones asked about, which is asked again (typing keeps the faces, and the answer). The model is
3251
+ * watched, not this plugin's state: a change that shows before the engine answers it, as a
3252
+ * format on a whole box does, changes the view alone.
3253
+ */
3254
+ const dropStaleAnswers = (model) => {
3255
+ let dropped = false;
3256
+ for (const [id, answer] of answers) {
3257
+ const record = model.byId[id];
3258
+ if (record === answer.record) continue;
3259
+ const question = record && questionOf(record);
3260
+ if (question && question.key === answer.faces) {
3261
+ answers.set(id, {
3262
+ ...answer,
3263
+ record
3264
+ });
3265
+ continue;
3266
+ }
3267
+ answers.delete(id);
3268
+ dropped = true;
3269
+ if (question) resolveBox(id);
3270
+ }
3271
+ if (dropped) {
3272
+ answered++;
3273
+ ctx.notify();
3274
+ }
3275
+ };
3276
+ ctx.watch(store.model, dropStaleAnswers);
3179
3277
  ctx.state.onChange(() => {
3180
3278
  const next = store.model().editing;
3181
3279
  if (next === editing) return;
@@ -3189,14 +3287,14 @@ function createTextFonts(ctx, store, lookup) {
3189
3287
  const api = fonts();
3190
3288
  const byFont = bodyIsItsFont(style, body);
3191
3289
  if (!api) return standardFontCss(byFont ? standardFontOf(style.fontFamily) : standardFontForFace(body));
3192
- const run = answers.get(id)?.get(BODY);
3290
+ const run = answers.get(id)?.byFace.get(BODY);
3193
3291
  if (run) return api.getRunCss(run);
3194
3292
  return byFont ? api.getFontCss(style.fontFamily) : api.getFaceCss(body);
3195
3293
  },
3196
3294
  faceCss: (id, face) => {
3197
3295
  const api = fonts();
3198
3296
  if (!api) return standardFontCss(standardFontForFace(face));
3199
- const run = id !== null ? answers.get(id)?.get(faceKey(face)) : void 0;
3297
+ const run = id !== null ? answers.get(id)?.byFace.get(faceKey(face)) : void 0;
3200
3298
  return run ? api.getRunCss(run) : api.getFaceCss(face);
3201
3299
  },
3202
3300
  familyOfCss: (cssFamily) => {
@@ -4760,26 +4858,28 @@ function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lendin
4760
4858
  * member takes the fields its kind has, and the change shows at once, as
4761
4859
  * one change. While the text editor holds a range, the font, size, colour
4762
4860
  * and formats restyle the runs it covers (a delta over the body, through
4763
- * the pure run algebra) as part of the typing, and the rest goes to the
4764
- * annotation: its change sends the typing first, so the body it writes is
4765
- * the latest.
4861
+ * the pure run algebra) as part of the typing; at its caret they are the
4862
+ * style of the text typed next, and nothing is written. The rest goes to
4863
+ * the annotation: its change sends the typing first, so the body it writes
4864
+ * is the latest.
4766
4865
  */
4767
4866
  const restyle = (patch) => {
4768
4867
  const model = store.model();
4769
- const range = properties.activeTextRange(model);
4868
+ const editor = properties.activeTextRange(model) ?? properties.activeCaret(model);
4770
4869
  const commits = [];
4771
4870
  const patches = {};
4772
4871
  for (const id of model.selected) {
4773
4872
  const record = model.byId[id];
4774
4873
  if (!record) continue;
4775
4874
  const own = typeof patch === "function" ? patch(record.annotation) : patch;
4776
- if (range?.id !== id) {
4875
+ if (editor?.id !== id) {
4777
4876
  patches[id] = own;
4778
4877
  continue;
4779
4878
  }
4780
4879
  const { delta, rest } = runDeltaForFields(own, fonts);
4781
- if (Object.keys(delta).length) {
4782
- const next = applyStyleToRange({ paragraphs: richDocOf(record.annotation, fonts).paragraphs }, range, delta);
4880
+ if (Object.keys(delta).length && editor.start === editor.end) text.styleTyping(id, delta);
4881
+ else if (Object.keys(delta).length) {
4882
+ const next = applyStyleToRange({ paragraphs: richDocOf(record.annotation, fonts).paragraphs }, editor, delta);
4783
4883
  commits.push(text.type(id, {
4784
4884
  type: "setRichText",
4785
4885
  id,
@@ -4803,12 +4903,15 @@ function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lendin
4803
4903
  });
4804
4904
  };
4805
4905
  /**
4806
- * Bold, italic or underline on or off: the words selected while typing, or
4807
- * the whole of each selected text box once the text being typed has landed.
4906
+ * Bold, italic or underline on or off: the words selected while typing, the
4907
+ * text typed next at the caret, or all the text of each selected box once
4908
+ * the text being typed has landed. On, unless all of it already has it.
4808
4909
  */
4809
4910
  const toggleFormat = async (format, options = {}) => {
4810
- const on = properties.selectionPropertiesOf().values[format] !== true;
4811
- const commits = properties.activeTextRange(store.model()) ? restyle({ [format]: on }) : [store.commit({
4911
+ const { values, mixed } = properties.selectionPropertiesOf();
4912
+ const on = values[format] !== true || mixed.includes(format);
4913
+ const model = store.model();
4914
+ const commits = properties.activeTextRange(model) ?? properties.activeCaret(model) ? restyle({ [format]: on }) : [store.commit({
4812
4915
  type: "setTextFormat",
4813
4916
  format,
4814
4917
  on
@@ -5184,7 +5287,8 @@ function createStamps(ctx, { store, geometry, tools, filePicker, afterCreate })
5184
5287
  * hold): the view shows the text at once, and the change keeps its place in
5185
5288
  * line holding the latest text. It is sent after a pause in typing, when
5186
5289
  * editing ends, when anything else is staged, and before a download; what is
5187
- * typed after that goes into a new one.
5290
+ * typed after that goes into a new one. A style chosen at the caret waits in
5291
+ * the editor's selection for the text typed there next.
5188
5292
  */
5189
5293
  const TEXT_WRITE_DELAY_MS = 250;
5190
5294
  function createTextEditing(ctx, { store, fonts, textFonts }, chrome) {
@@ -5221,6 +5325,44 @@ function createTextEditing(ctx, { store, fonts, textFonts }, chrome) {
5221
5325
  });
5222
5326
  return commit;
5223
5327
  };
5328
+ /**
5329
+ * The style the text typed next at the caret in box `id` takes, over what
5330
+ * was chosen there already. Nothing is written until it is typed.
5331
+ */
5332
+ const styleTyping = (id, style) => {
5333
+ const selection = ctx.state.get().textSelection;
5334
+ if (selection?.id !== id || selection.start !== selection.end) return;
5335
+ ctx.state.update(setTextSelection, {
5336
+ ...selection,
5337
+ typing: {
5338
+ ...selection.typing,
5339
+ ...style
5340
+ }
5341
+ });
5342
+ };
5343
+ /**
5344
+ * The paragraphs typed into box `id`, the text typed at the caret in the
5345
+ * style chosen there (`typeWithStyle`), and the caret where the typing
5346
+ * leaves it. Any other edit drops the style.
5347
+ */
5348
+ const typedInStyle = (id, paragraphs) => {
5349
+ const selection = ctx.state.get().textSelection;
5350
+ const record = store.model().byId[id];
5351
+ if (!selection?.typing || selection.id !== id || !record) return paragraphs;
5352
+ const typed = typeWithStyle(richDocOf(record.annotation, fonts), { paragraphs }, selection.start, selection.typing);
5353
+ const caret = typed ? {
5354
+ id,
5355
+ start: typed.caret,
5356
+ end: typed.caret,
5357
+ ...typed.style && { typing: typed.style }
5358
+ } : {
5359
+ id,
5360
+ start: selection.start,
5361
+ end: selection.end
5362
+ };
5363
+ ctx.state.update(setTextSelection, caret);
5364
+ return typed?.doc.paragraphs ?? paragraphs;
5365
+ };
5224
5366
  store.onEffect("text", (effect, model) => {
5225
5367
  const record = model.byId[effect.id];
5226
5368
  const ref = refOf(record);
@@ -5236,6 +5378,7 @@ function createTextEditing(ctx, { store, fonts, textFonts }, chrome) {
5236
5378
  });
5237
5379
  return {
5238
5380
  type,
5381
+ styleTyping,
5239
5382
  sendTyping,
5240
5383
  text: {
5241
5384
  begin: (ref) => {
@@ -5278,11 +5421,13 @@ function createTextEditing(ctx, { store, fonts, textFonts }, chrome) {
5278
5421
  },
5279
5422
  draftRichText: (ref, doc) => {
5280
5423
  const id = annotationKey$1(ref);
5424
+ const kept = { paragraphs: typedInStyle(id, doc.paragraphs) };
5281
5425
  type(id, {
5282
5426
  type: "setRichText",
5283
5427
  id,
5284
- doc: { paragraphs: doc.paragraphs }
5428
+ doc: kept
5285
5429
  });
5430
+ return kept;
5286
5431
  },
5287
5432
  setTextSelection: (ref, range) => {
5288
5433
  const id = annotationKey$1(ref);