@stll/folio-core 0.70.0 → 0.71.0

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.
@@ -434,6 +434,12 @@ declare class CanonicalSession {
434
434
  prepareOps: (state: EditorState, compiled: readonly DocumentOp[], postSelection: CanonicalSelection) => Result<CanonicalCommit, CanonicalSessionError>;
435
435
  };
436
436
  private prepareJournalledOps;
437
+ /**
438
+ * Bring derived content (a host's derived fields) in line with the edit
439
+ * just published: one commit that joins that edit's undo step, so undoing
440
+ * the edit undoes both. Refused when no local edit is open.
441
+ */
442
+ prepareDerivedUpdate(state: EditorState, ops: readonly DocumentOp[]): Result<CanonicalCommit, CanonicalSessionError>;
437
443
  prepareSplit(state: EditorState): Result<CanonicalCommit, CanonicalSessionError>;
438
444
  prepareJoin(state: EditorState, direction: "backward" | "forward"): Result<CanonicalCommit, CanonicalSessionError>;
439
445
  prepareResolve(state: EditorState, { revisionIds, resolution, before }: {
@@ -2008,6 +2008,48 @@ var CanonicalSession = class {
2008
2008
  }
2009
2009
  });
2010
2010
  }
2011
+ /**
2012
+ * Bring derived content (a host's derived fields) in line with the edit
2013
+ * just published: one commit that joins that edit's undo step, so undoing
2014
+ * the edit undoes both. Refused when no local edit is open.
2015
+ */
2016
+ prepareDerivedUpdate(state, ops) {
2017
+ const group = this.applied.at(-1);
2018
+ if (group === void 0) return noChange("A derived update joins a local edit.");
2019
+ if (ops.length === 0) return noChange("The derived content is already current.");
2020
+ const selection = group.postSelection;
2021
+ const story = selection.anchor.story;
2022
+ const projected = this.projectStory(story);
2023
+ if (projected.isErr()) return projected;
2024
+ const preDocument = this.currentDocument;
2025
+ return this.stage({
2026
+ state,
2027
+ story,
2028
+ ops,
2029
+ selection,
2030
+ origin: "input",
2031
+ history: "joined",
2032
+ onPublish: (inverse, version, shown) => {
2033
+ group.entries.push({
2034
+ type: "applied",
2035
+ ops,
2036
+ inverse,
2037
+ preSelection: selection,
2038
+ postSelection: shown,
2039
+ preDocument,
2040
+ postDocument: this.currentDocument,
2041
+ version,
2042
+ origin: "input",
2043
+ semantic: "structure",
2044
+ grouping: "isolated",
2045
+ time: Date.now(),
2046
+ boundary: this.groupingBoundary
2047
+ });
2048
+ group.postSelection = shown;
2049
+ this.undone.length = 0;
2050
+ }
2051
+ });
2052
+ }
2011
2053
  prepareSplit(state) {
2012
2054
  const from = this.projection.inputAddressAt(state.selection.from);
2013
2055
  if (from.isErr()) return from;
@@ -0,0 +1,12 @@
1
+ import { document_d_exports } from "../types/document.js";
2
+ import { FolioDerivedFields, FolioFieldInsertion } from "../types/fields.js";
3
+ import { ReplaceInlineOp } from "@stll/docx-core/ops";
4
+ /**
5
+ * The operations that bring the owned fields of a document's main story to
6
+ * the display texts the host derives for them: one whole-paragraph
7
+ * replacement per paragraph a field of which shows something else. None when
8
+ * every field already shows its text.
9
+ */
10
+ export declare const derivedFieldOps: (document: document_d_exports.Document, { owns, displayTexts }: FolioDerivedFields) => ReplaceInlineOp[];
11
+ /** The paragraph fragment an inserted field goes in as: the field alone. */
12
+ export declare const fieldInsertionParagraph: ({ instruction, displayText, locked }: FolioFieldInsertion) => document_d_exports.Paragraph;
@@ -0,0 +1,111 @@
1
+ import { parseFieldType } from "../docx/fieldParser.js";
2
+ import { withInlineContentRewritten } from "../docx/paragraphTraversal.js";
3
+ import { panic } from "better-result";
4
+ import { DOCUMENT_OP_TYPES, OP_STORIES, paragraphsThroughTextBoxes } from "@stll/docx-core/ops";
5
+ // src/canonical/derivedFields.ts
6
+ const isField = (item) => item.type === "simpleField" || item.type === "complexField";
7
+ /** Records whose content the final document leaves out. */
8
+ const isRemoval = (item) => item.type === "deletion" || item.type === "moveFrom";
9
+ /** The text `content` shows, through hyperlinks and other wrappers. */
10
+ const runsText = (content) => content.map(itemText).join("");
11
+ const itemText = (item) => {
12
+ if (item.type === "run") return item.content.map((child) => child.type === "text" ? child.text : "").join("");
13
+ if (isRemoval(item)) return "";
14
+ const texts = [];
15
+ withInlineContentRewritten(item, (children) => {
16
+ texts.push(runsText(children));
17
+ return children;
18
+ });
19
+ return texts.join("");
20
+ };
21
+ /** What a field shows: its cached result. */
22
+ const displayTextOf = (field) => field.type === "simpleField" ? runsText(field.content) : runsText(field.fieldResult);
23
+ /** The result run of a field showing `text`, formatted as its first result run. */
24
+ const resultRun = (field, text) => {
25
+ const first = (field.type === "simpleField" ? field.content : field.fieldResult).find((item) => item.type === "run");
26
+ return {
27
+ type: "run",
28
+ ...first?.formatting === void 0 ? {} : { formatting: first.formatting },
29
+ content: [{
30
+ type: "text",
31
+ text
32
+ }]
33
+ };
34
+ };
35
+ const withDisplayText = (field, text) => field.type === "simpleField" ? {
36
+ ...field,
37
+ content: [resultRun(field, text)]
38
+ } : {
39
+ ...field,
40
+ fieldResult: [resultRun(field, text)]
41
+ };
42
+ const mapOwnedFields = (content, owns, replace, removed = false) => {
43
+ let changed = false;
44
+ const mapped = content.map((item) => {
45
+ if (isField(item) && owns(item.instruction)) {
46
+ const next = replace(item, removed);
47
+ if (next !== item) changed = true;
48
+ return next;
49
+ }
50
+ const next = withInlineContentRewritten(item, (children) => mapOwnedFields(children, owns, replace, removed || isRemoval(item)));
51
+ if (next !== item) changed = true;
52
+ return next;
53
+ });
54
+ return changed ? mapped : content;
55
+ };
56
+ /**
57
+ * The operations that bring the owned fields of a document's main story to
58
+ * the display texts the host derives for them: one whole-paragraph
59
+ * replacement per paragraph a field of which shows something else. None when
60
+ * every field already shows its text.
61
+ */
62
+ const derivedFieldOps = (document, { owns, displayTexts }) => {
63
+ const paragraphs = paragraphsThroughTextBoxes(document, OP_STORIES.MAIN).map(({ paragraph }) => paragraph);
64
+ const instructions = [];
65
+ for (const paragraph of paragraphs) mapOwnedFields(paragraph.content, owns, (field, removed) => {
66
+ if (!removed) instructions.push(field.instruction);
67
+ return field;
68
+ });
69
+ if (instructions.length === 0) return [];
70
+ const texts = displayTexts(instructions);
71
+ if (texts.length !== instructions.length) panic(`derivedFields.displayTexts returned ${texts.length} texts for ${instructions.length} fields.`);
72
+ const pending = texts.values();
73
+ const assign = (field, removed) => {
74
+ if (removed) return field;
75
+ const text = pending.next();
76
+ if (text.done === true) return panic("A derived field text is missing.");
77
+ return displayTextOf(field) === text.value ? field : withDisplayText(field, text.value);
78
+ };
79
+ const ops = [];
80
+ for (const paragraph of paragraphs) {
81
+ const content = mapOwnedFields(paragraph.content, owns, assign);
82
+ if (content === paragraph.content) continue;
83
+ if (paragraph.paraId === void 0) panic("A canonical paragraph holding a field has no paraId.");
84
+ ops.push({
85
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
86
+ story: OP_STORIES.MAIN,
87
+ blockId: paragraph.paraId,
88
+ expected: paragraph.content,
89
+ content
90
+ });
91
+ }
92
+ return ops;
93
+ };
94
+ /** The paragraph fragment an inserted field goes in as: the field alone. */
95
+ const fieldInsertionParagraph = ({ instruction, displayText, locked }) => ({
96
+ type: "paragraph",
97
+ content: [{
98
+ type: "simpleField",
99
+ instruction,
100
+ fieldType: parseFieldType(instruction),
101
+ content: [{
102
+ type: "run",
103
+ content: [{
104
+ type: "text",
105
+ text: displayText
106
+ }]
107
+ }],
108
+ ...locked === void 0 ? {} : { fldLock: locked }
109
+ }]
110
+ });
111
+ export { derivedFieldOps, fieldInsertionParagraph };
@@ -39,10 +39,11 @@ import { FolioAnonymizationMatch, FolioAnonymizationTerm } from "../types/anonym
39
39
  import { FolioAutocompleteApi, FolioAutocompleteState } from "../types/autocomplete.js";
40
40
  import { DeriveBlockIdInput, FolioBlockId, currentFolioBlockId, deriveBlockId, getFolioParaIdFromBlockId, isFolioBlockId, isSequentialFolioBlockId } from "../types/block-id.js";
41
41
  import { document_d_exports } from "../types/document.js";
42
+ import { FolioDerivedFields, FolioFieldInsertion } from "../types/fields.js";
42
43
  import { CreateEmptyDocumentOptions, createEmptyDocument } from "../utils/createDocument.js";
43
44
  import { getGoogleFontsEnabled, setGoogleFontsEnabled } from "../utils/fontResolver.js";
44
45
  import { mergeDocumentContent } from "../utils/mergeDocumentContent.js";
45
46
  import { DEFAULT_OUTLINE_DEPTH, OutlineDepth, filterHeadingsByDepth } from "../utils/outlineDepth.js";
46
47
  type Document = document_d_exports.Document;
47
48
  type DocxConformanceClass = document_d_exports.DocxConformanceClass;
48
- export { type AIBarStatus, type AIChatMode, type AICitation, type AICitationRange, type AICitationSource, type AIGenerateInput, type AISuggestion, type AISuggestionApplyMode, type AISuggestionPreset, type AISuggestionSeverity, type AISuggestionStatus, type ApplyFolioDocumentOperationsOptions, type ApplyResult, type BlockRect, COMPARE_REVISION_FORMATS, COMPARE_UNSUPPORTED_REASONS, COMPARE_VERIFICATION_CAUSES, COMPARE_VERIFICATION_INVARIANTS, type CompareChange, type CompareChangeLocation, type CompareCompatibility, type CompareContentOptions, CompareDocxApplyError, type CompareDocxError, CompareDocxFinalParagraphMarkError, CompareDocxOperationLimitError, type CompareDocxOptions, CompareDocxParseError, CompareDocxRoundTripError, CompareDocxSerializeError, type CompareFolioRequirement, type CompareResult, type CompareRevisionFormat, type CompareUnsupportedPart, type CompareUnsupportedReason, type CompareVerification, type CompareVerificationCause, type CompareVerificationFailure, type CompareVerificationInvariant, type CreateEmptyDocumentOptions, DEFAULT_AI_SUGGESTION_PRESETS, DEFAULT_OUTLINE_DEPTH, DOCUMENT_PRESET_VERSION, DOCUMENT_STYLE_SET_VERSION, DOCX_CONFORMANCE_CLASSES, DRAWING_SAFETY_CLASSES, type DeriveBlockIdInput, type DirectiveKind, type DirectiveRange, type Document, type DocumentPreset, type DocumentPropertiesOptions, type DocumentStyleCatalog, type DocumentStyleCatalogEntry, type DocumentStyleSet, type DocxCompatibility, type DocxCompatibilityContext, type DocxCompatibilityIssue, type DocxCompatibilityLocation, type DocxCompatibilityPart, type DocxConformanceClass, type DocxDrawingClassification, type DrawingSafetyClass, type EditorReadOnlyReason, type EmbeddedFont, type EmbeddedFontParts, type ExtractDocumentStyleSetOptions, FOLIO_CONTENT_COMPARISON_LIMITS, FOLIO_DOCUMENT_OPERATION_BATCH_MODES, FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_MODES, FOLIO_DOCUMENT_OPERATION_MODES_BY_TYPE, FOLIO_DOCUMENT_OPERATION_PRECONDITIONS, FOLIO_DOCUMENT_OPERATION_STORIES, FOLIO_DOCUMENT_OPERATION_TYPES, FOLIO_HIGHLIGHT_COLOR_VALUES, FOLIO_LINE_SPACING_RULE_VALUES, FOLIO_PARAGRAPH_ALIGNMENT_VALUES, FOLIO_YJS_ATTR_SCHEMA_VERSION, type FinalParagraphMarkRevision, type FolioAIBlock, type FolioAIBlockAnchor, type FolioAIBlockKind, type FolioAIBlockPreviewRun, type FolioAIBlockStructuralBoundary, type FolioAIBlockTableLocation, type FolioAIComment, type FolioAIDiagnosticBlock, type FolioAIEditAppliedOperation, type FolioAIEditApplyMode, type FolioAIEditApplyOutcome, type FolioAIEditApplyResult, type FolioAIEditNormalization, type FolioAIEditNormalizationCode, type FolioAIEditOperation, type FolioAIEditParagraphIdentity, type FolioAIEditPrecondition, type FolioAIEditReviewMeta, type FolioAIEditSeverity, type FolioAIEditSkipReason, type FolioAIEditSkippedOperation, type FolioAIEditSnapshot, type FolioAIInlineBooleanProperty, type FolioAIInlineFormatting, type FolioAIInlineFormattingPatch, type FolioAIParagraphBlock, type FolioAIParagraphSpacing, type FolioAISignatureParty, type FolioAnonymizationMatch, type FolioAnonymizationTerm, type FolioAutocompleteApi, type FolioAutocompleteState, type FolioBlockId, type FolioContentBlock, type FolioContentBlockProperty, type FolioContentComparison, type FolioContentComparisonError, type FolioContentComparisonEvent, type FolioContentComparisonLimit, FolioContentComparisonLimitError, type FolioContentContainerPathEntry, type FolioContentFormatRange, type FolioContentFormattingChange, type FolioContentIdStability, type FolioContentInlineBooleanProperty, type FolioContentInlineComparisonResult, type FolioContentInlineFormatting, type FolioContentInlineFormattingPatch, FolioContentInlinePresentationProjectionError, type FolioContentLineSpacingRule, type FolioContentParagraphAlignment, type FolioContentParagraphFormattingPatch, type FolioContentParagraphKind, type FolioContentParagraphSpacing, type FolioContentRun, type FolioContentSnapshot, type FolioContentStatedNumbering, type FolioContentStructuralChange, type FolioContentTableLocation, type FolioContentTextSegment, type FolioDocumentOperation, type FolioDocumentOperationAffectedTarget, type FolioDocumentOperationBatch, type FolioDocumentOperationBatchInput, type FolioDocumentOperationCapabilities, type FolioDocumentOperationIssue, type FolioDocumentOperationMode, type FolioDocumentOperationPrecondition, type FolioDocumentOperationReceipt, type FolioDocumentOperationRecovery, type FolioDocumentOperationResult, type FolioDocumentOperationResultBase, type FolioDocumentOperationStatus, type FolioDocumentOperationStory, type FolioDocumentOperationType, type FolioDocumentOperationUndoFailureReason, type FolioDocumentOperationUndoHandle, type FolioDocumentOperationUndoResult, type FolioDocxCompatibilityHost, type FolioDocxCompatibilityProfile, type FolioRevisionStamp, type FolioUndefinedReferencePolicy, type FolioWordDiffOptions, type FolioYjsAttrSchemaVersion, FolioYjsAttrSchemaVersionError, type ImageMeta, type ImageRef, type InspectDocxCompatibilityOptions, InvalidCompareDocxOptionsError, InvalidFolioContentComparisonError, InvalidFolioDocumentOperationBatchError, MAX_COMPARE_OPERATIONS, type MarkdownOptions, type MarkdownResult, OP_STORIES, type OpStory, type OutlineDepth, type PositionalText, type ResolvedAnchor, type ReviewDisplayMode, STELLA_STYLE_SET_NAME, type TemplatePreviewHiddenRange, type TemplatePreviewSpan, type TemplatePreviewValue, type TemplatePreviewValues, type TemplateSlashMenuKeyAction, type TemplateSlashMenuState, type TextPosition, UnsupportedFolioDocumentOperationVersionError, WORD_DIFF_GRANULARITIES, type WordDiffGranularity, type WordDiffNormalization, type WordDiffOptions, type WordDiffSegment, applyFolioAIEditOperations, applyFolioDocumentOperations, applySuggestions, assertSupportedFolioDocumentOperationVersion, buildEmbeddedFontFamilyMap, buildPositionalText, clearTemplateSlashMenu, compareContent, compareDocx, consumeTemplateSlashQuery, createAICitationDecorationsPlugin, createDocx, createEmptyDocument, createFolioAIEditSnapshot, createStellaStyleDocumentPreset, createStellaStyleSet, currentFolioBlockId, deriveBlockId, diffWordSegments, extractDocumentStyleSet, extractDocumentStyleSetFromDocx, extractEmbeddedFonts, filterHeadingsByDepth, fromMarkdown, getEmbeddedFontFaces, getFolioCaretViewportRect, getFolioDocumentOperationCapabilities, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts, getFolioParaIdFromBlockId, getFolioSelectionViewportRect, getGoogleFontsEnabled, getTemplateDirectives, getTemplateSlashMenu, hashFolioAIBlockText, inspectDocumentStyles, inspectDocumentStylesFromDocx, inspectDocxCompatibility, isFolioAIContentBlock, isFolioBlockId, isFolioDocumentOperationModeSupported, isSequentialFolioBlockId, isSuggestionStale, isSupportedFolioDocumentOperationVersion, mergeDocumentContent, normalizeFolioAIBlockText, parseFolioDocumentOperationBatch, resetTemplateSlashQuery, resolveSuggestionAnchor, scanDirectives, scopeEmbeddedFontFamily, scrollFolioPositionIntoView, setAICitationsMeta, setAISuggestionsMeta, setActiveCitationMeta, setFocusedSuggestionMeta, setGoogleFontsEnabled, setTemplatePreviewValues, templateSlashMenuKey, toMarkdown, toMarkdownResult };
49
+ export { type AIBarStatus, type AIChatMode, type AICitation, type AICitationRange, type AICitationSource, type AIGenerateInput, type AISuggestion, type AISuggestionApplyMode, type AISuggestionPreset, type AISuggestionSeverity, type AISuggestionStatus, type ApplyFolioDocumentOperationsOptions, type ApplyResult, type BlockRect, COMPARE_REVISION_FORMATS, COMPARE_UNSUPPORTED_REASONS, COMPARE_VERIFICATION_CAUSES, COMPARE_VERIFICATION_INVARIANTS, type CompareChange, type CompareChangeLocation, type CompareCompatibility, type CompareContentOptions, CompareDocxApplyError, type CompareDocxError, CompareDocxFinalParagraphMarkError, CompareDocxOperationLimitError, type CompareDocxOptions, CompareDocxParseError, CompareDocxRoundTripError, CompareDocxSerializeError, type CompareFolioRequirement, type CompareResult, type CompareRevisionFormat, type CompareUnsupportedPart, type CompareUnsupportedReason, type CompareVerification, type CompareVerificationCause, type CompareVerificationFailure, type CompareVerificationInvariant, type CreateEmptyDocumentOptions, DEFAULT_AI_SUGGESTION_PRESETS, DEFAULT_OUTLINE_DEPTH, DOCUMENT_PRESET_VERSION, DOCUMENT_STYLE_SET_VERSION, DOCX_CONFORMANCE_CLASSES, DRAWING_SAFETY_CLASSES, type DeriveBlockIdInput, type DirectiveKind, type DirectiveRange, type Document, type DocumentPreset, type DocumentPropertiesOptions, type DocumentStyleCatalog, type DocumentStyleCatalogEntry, type DocumentStyleSet, type DocxCompatibility, type DocxCompatibilityContext, type DocxCompatibilityIssue, type DocxCompatibilityLocation, type DocxCompatibilityPart, type DocxConformanceClass, type DocxDrawingClassification, type DrawingSafetyClass, type EditorReadOnlyReason, type EmbeddedFont, type EmbeddedFontParts, type ExtractDocumentStyleSetOptions, FOLIO_CONTENT_COMPARISON_LIMITS, FOLIO_DOCUMENT_OPERATION_BATCH_MODES, FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_MODES, FOLIO_DOCUMENT_OPERATION_MODES_BY_TYPE, FOLIO_DOCUMENT_OPERATION_PRECONDITIONS, FOLIO_DOCUMENT_OPERATION_STORIES, FOLIO_DOCUMENT_OPERATION_TYPES, FOLIO_HIGHLIGHT_COLOR_VALUES, FOLIO_LINE_SPACING_RULE_VALUES, FOLIO_PARAGRAPH_ALIGNMENT_VALUES, FOLIO_YJS_ATTR_SCHEMA_VERSION, type FinalParagraphMarkRevision, type FolioAIBlock, type FolioAIBlockAnchor, type FolioAIBlockKind, type FolioAIBlockPreviewRun, type FolioAIBlockStructuralBoundary, type FolioAIBlockTableLocation, type FolioAIComment, type FolioAIDiagnosticBlock, type FolioAIEditAppliedOperation, type FolioAIEditApplyMode, type FolioAIEditApplyOutcome, type FolioAIEditApplyResult, type FolioAIEditNormalization, type FolioAIEditNormalizationCode, type FolioAIEditOperation, type FolioAIEditParagraphIdentity, type FolioAIEditPrecondition, type FolioAIEditReviewMeta, type FolioAIEditSeverity, type FolioAIEditSkipReason, type FolioAIEditSkippedOperation, type FolioAIEditSnapshot, type FolioAIInlineBooleanProperty, type FolioAIInlineFormatting, type FolioAIInlineFormattingPatch, type FolioAIParagraphBlock, type FolioAIParagraphSpacing, type FolioAISignatureParty, type FolioAnonymizationMatch, type FolioAnonymizationTerm, type FolioAutocompleteApi, type FolioAutocompleteState, type FolioBlockId, type FolioContentBlock, type FolioContentBlockProperty, type FolioContentComparison, type FolioContentComparisonError, type FolioContentComparisonEvent, type FolioContentComparisonLimit, FolioContentComparisonLimitError, type FolioContentContainerPathEntry, type FolioContentFormatRange, type FolioContentFormattingChange, type FolioContentIdStability, type FolioContentInlineBooleanProperty, type FolioContentInlineComparisonResult, type FolioContentInlineFormatting, type FolioContentInlineFormattingPatch, FolioContentInlinePresentationProjectionError, type FolioContentLineSpacingRule, type FolioContentParagraphAlignment, type FolioContentParagraphFormattingPatch, type FolioContentParagraphKind, type FolioContentParagraphSpacing, type FolioContentRun, type FolioContentSnapshot, type FolioContentStatedNumbering, type FolioContentStructuralChange, type FolioContentTableLocation, type FolioContentTextSegment, type FolioDerivedFields, type FolioDocumentOperation, type FolioDocumentOperationAffectedTarget, type FolioDocumentOperationBatch, type FolioDocumentOperationBatchInput, type FolioDocumentOperationCapabilities, type FolioDocumentOperationIssue, type FolioDocumentOperationMode, type FolioDocumentOperationPrecondition, type FolioDocumentOperationReceipt, type FolioDocumentOperationRecovery, type FolioDocumentOperationResult, type FolioDocumentOperationResultBase, type FolioDocumentOperationStatus, type FolioDocumentOperationStory, type FolioDocumentOperationType, type FolioDocumentOperationUndoFailureReason, type FolioDocumentOperationUndoHandle, type FolioDocumentOperationUndoResult, type FolioDocxCompatibilityHost, type FolioDocxCompatibilityProfile, type FolioFieldInsertion, type FolioRevisionStamp, type FolioUndefinedReferencePolicy, type FolioWordDiffOptions, type FolioYjsAttrSchemaVersion, FolioYjsAttrSchemaVersionError, type ImageMeta, type ImageRef, type InspectDocxCompatibilityOptions, InvalidCompareDocxOptionsError, InvalidFolioContentComparisonError, InvalidFolioDocumentOperationBatchError, MAX_COMPARE_OPERATIONS, type MarkdownOptions, type MarkdownResult, OP_STORIES, type OpStory, type OutlineDepth, type PositionalText, type ResolvedAnchor, type ReviewDisplayMode, STELLA_STYLE_SET_NAME, type TemplatePreviewHiddenRange, type TemplatePreviewSpan, type TemplatePreviewValue, type TemplatePreviewValues, type TemplateSlashMenuKeyAction, type TemplateSlashMenuState, type TextPosition, UnsupportedFolioDocumentOperationVersionError, WORD_DIFF_GRANULARITIES, type WordDiffGranularity, type WordDiffNormalization, type WordDiffOptions, type WordDiffSegment, applyFolioAIEditOperations, applyFolioDocumentOperations, applySuggestions, assertSupportedFolioDocumentOperationVersion, buildEmbeddedFontFamilyMap, buildPositionalText, clearTemplateSlashMenu, compareContent, compareDocx, consumeTemplateSlashQuery, createAICitationDecorationsPlugin, createDocx, createEmptyDocument, createFolioAIEditSnapshot, createStellaStyleDocumentPreset, createStellaStyleSet, currentFolioBlockId, deriveBlockId, diffWordSegments, extractDocumentStyleSet, extractDocumentStyleSetFromDocx, extractEmbeddedFonts, filterHeadingsByDepth, fromMarkdown, getEmbeddedFontFaces, getFolioCaretViewportRect, getFolioDocumentOperationCapabilities, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts, getFolioParaIdFromBlockId, getFolioSelectionViewportRect, getGoogleFontsEnabled, getTemplateDirectives, getTemplateSlashMenu, hashFolioAIBlockText, inspectDocumentStyles, inspectDocumentStylesFromDocx, inspectDocxCompatibility, isFolioAIContentBlock, isFolioBlockId, isFolioDocumentOperationModeSupported, isSequentialFolioBlockId, isSuggestionStale, isSupportedFolioDocumentOperationVersion, mergeDocumentContent, normalizeFolioAIBlockText, parseFolioDocumentOperationBatch, resetTemplateSlashQuery, resolveSuggestionAnchor, scanDirectives, scopeEmbeddedFontFamily, scrollFolioPositionIntoView, setAICitationsMeta, setAISuggestionsMeta, setActiveCitationMeta, setFocusedSuggestionMeta, setGoogleFontsEnabled, setTemplatePreviewValues, templateSlashMenuKey, toMarkdown, toMarkdownResult };
@@ -65,6 +65,7 @@ const createFolioEditor = (deps) => {
65
65
  scrollToSelection: () => deps.getEditorApi()?.scrollToSelection(),
66
66
  editorPositionAt: (position) => deps.getEditorApi()?.editorPositionAt(position) ?? null,
67
67
  getAnonymizationHighlights: () => deps.getEditorApi()?.getAnonymizationHighlights() ?? NO_ANONYMIZATION_HIGHLIGHTS,
68
+ insertField: (field) => deps.getEditorApi()?.insertField(field) ?? false,
68
69
  autocomplete: delegateAutocomplete(() => deps.getEditorApi()?.autocomplete ?? NO_AUTOCOMPLETE),
69
70
  getLayout: () => deps.getLayout(),
70
71
  getPositionPage: (position) => {
@@ -17,6 +17,7 @@ import { Comment } from "../types/content.js";
17
17
  import { document_d_exports } from "../types/document.js";
18
18
  import { ReadonlyDocument } from "../types/documentModel.js";
19
19
  import { FolioDocxSerializationPath } from "../types/docxSerialization.js";
20
+ import { FolioFieldInsertion } from "../types/fields.js";
20
21
  import { AnonymizationHighlightsView } from "./anonymizationHighlights.js";
21
22
  import { createCanonicalInputBoundary } from "./canonicalInput.js";
22
23
  import { Node } from "prosemirror-model";
@@ -160,6 +161,11 @@ export type HiddenEditorApi = {
160
161
  * Where the host's anonymization terms occur in every story the editor
161
162
  * shows, read from the current text; nothing before the editor exists.
162
163
  */
164
+ /**
165
+ * Insert a field in place of the selection: one undo step, a tracked
166
+ * insertion when suggesting. False when nothing was inserted.
167
+ */
168
+ insertField: (field: FolioFieldInsertion) => boolean;
163
169
  getAnonymizationHighlights: () => AnonymizationHighlightsView;
164
170
  /** The inline autocomplete suggestion. */
165
171
  autocomplete: HiddenEditorAutocomplete;
@@ -176,6 +182,7 @@ export type HiddenEditorApiDeps = {
176
182
  */
177
183
  canonicalEditorPositionAt?: (position: TextPosition) => number | null | undefined;
178
184
  getAnonymizationHighlights?: () => AnonymizationHighlightsView;
185
+ insertField?: (field: FolioFieldInsertion) => boolean;
179
186
  autocomplete?: HiddenEditorAutocomplete;
180
187
  captureCanonicalSave?: HiddenEditorApi["captureCanonicalSave"];
181
188
  isCanonicalSaveCurrent?: HiddenEditorApi["isCanonicalSaveCurrent"];
@@ -80,6 +80,7 @@ const createHiddenEditorApi = (deps) => {
80
80
  return canonical === void 0 ? legacyEditorPositionAt(view.state.doc, position) : canonical;
81
81
  },
82
82
  getAnonymizationHighlights: () => deps.getAnonymizationHighlights?.() ?? NO_ANONYMIZATION_HIGHLIGHTS,
83
+ insertField: (field) => deps.insertField?.(field) ?? false,
83
84
  autocomplete: deps.autocomplete ?? NO_AUTOCOMPLETE,
84
85
  getDocument: () => {
85
86
  const canonical = deps.getCanonicalDocument?.();
@@ -7,6 +7,7 @@ import { FolioAnonymizationTerm } from "../types/anonymization.js";
7
7
  import { CanonicalRefusalGround, EditorSession } from "../types/canonicalCapabilities.js";
8
8
  import { document_d_exports } from "../types/document.js";
9
9
  import { DeepReadonly, ReadonlyDocument } from "../types/documentModel.js";
10
+ import { FolioDerivedFields } from "../types/fields.js";
10
11
  import { RemoteSelection } from "../types/remote-selection.js";
11
12
  import "./anonymizationHighlights.js";
12
13
  import { CanonicalRoomCollaboration } from "./canonicalRoomEditor.js";
@@ -82,6 +83,8 @@ export type HiddenEditorManagerDeps = {
82
83
  getExperimentalSession?: () => EditorSession | undefined;
83
84
  /** The terms the host wants highlighted; none when unset. */
84
85
  getAnonymizationTerms?: () => readonly FolioAnonymizationTerm[];
86
+ /** The fields whose display text the host derives; none when unset. */
87
+ getDerivedFields?: () => FolioDerivedFields | undefined;
85
88
  /**
86
89
  * Who answers the undo and redo keys in a canonical session; the editor's
87
90
  * when unset. With `"host"`, the keys change nothing in any story's view and
@@ -3,12 +3,15 @@ import { createCanonicalSectionPropertiesOperation } from "../canonical/canonica
3
3
  import { CanonicalPublicOperations } from "../canonical/canonicalPublicOperations.js";
4
4
  import { restoreCanonicalSelection } from "../canonical/canonicalSelection.js";
5
5
  import { CanonicalSessionError, createCanonicalSession, publishCanonicalProjection } from "../canonical/canonicalSession.js";
6
+ import { derivedFieldOps, fieldInsertionParagraph } from "../canonical/derivedFields.js";
7
+ import { parseFieldType } from "../docx/fieldParser.js";
6
8
  import { parseDocx } from "../docx/parser.js";
7
9
  import { editingFontContextOf, editingFontFamily } from "../layout-bridge/convert/editingFont.js";
8
10
  import { recordHiddenEditorPhase, recordHiddenEditorStateCreate } from "../layout-engine/layoutInstrumentation.js";
9
11
  import { suppressHiddenEditorScrollToSelection } from "../paged-layout/hiddenEditorScroll.js";
10
12
  import { isReadOnlyEditKey } from "../paged-layout/readOnlyEditAttempt.js";
11
13
  import { getCanonicalCommandIntents, getCanonicalHistoryDirection } from "../prosemirror/canonicalCommands.js";
14
+ import { canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.js";
12
15
  import { registerClipboardIntentHandler } from "../prosemirror/clipboardIntent.js";
13
16
  import { pasteWithoutFormatting } from "../prosemirror/commands/pastePlainText.js";
14
17
  import { createCommentRecordsPlugin, isCommentRecordsSync } from "../prosemirror/commentRecords.js";
@@ -368,7 +371,13 @@ const createHiddenEditorManager = (hostDeps) => {
368
371
  ]
369
372
  });
370
373
  };
374
+ /** Publish an edit, then bring the host's derived fields in line with it. */
371
375
  const publishCommit = (commit, reportRefusal = refuse) => {
376
+ if (!publishCanonical(commit, reportRefusal)) return false;
377
+ if (commit.history === "opened" || commit.history === "joined") deriveFields();
378
+ return true;
379
+ };
380
+ const publishCanonical = (commit, reportRefusal) => {
372
381
  if (!view || deps.getReadOnly() || editorSession.type !== "canonical") return false;
373
382
  const session = editorSession.session;
374
383
  const result = publishCanonicalProjection({
@@ -391,6 +400,91 @@ const createHiddenEditorManager = (hostDeps) => {
391
400
  deps.onCanonicalHistory?.(commit.history);
392
401
  return true;
393
402
  };
403
+ /** An edit published during a pass asks for another once that pass returns. */
404
+ let derivation = "idle";
405
+ const derivationRequested = () => derivation === "requested";
406
+ const deriveFields = () => {
407
+ if (derivation !== "idle") {
408
+ derivation = "requested";
409
+ return;
410
+ }
411
+ try {
412
+ do {
413
+ derivation = "running";
414
+ deriveFieldsOnce();
415
+ } while (derivationRequested());
416
+ } finally {
417
+ derivation = "idle";
418
+ }
419
+ };
420
+ const deriveFieldsOnce = () => {
421
+ const derived = deps.getDerivedFields?.();
422
+ if (derived === void 0 || !view || editorSession.type !== "canonical") return;
423
+ const { session } = editorSession;
424
+ const prepared = session.prepareDerivedUpdate(view.state, derivedFieldOps(readModel(session.document), derived));
425
+ if (prepared.isErr()) {
426
+ if (prepared.error.reason !== "noChange") refuse(prepared.error.message, prepared.error.ground);
427
+ return;
428
+ }
429
+ publishCanonical(prepared.value, refuse);
430
+ };
431
+ /** Insert a field in place of the selection, in either session. */
432
+ const insertField = (field) => {
433
+ if (!view || isDestroying || deps.getReadOnly()) return false;
434
+ const { state } = view;
435
+ switch (editorSession.type) {
436
+ case "canonical": {
437
+ const { session } = editorSession;
438
+ if (state.selection instanceof CellSelection) {
439
+ refuse("A field goes in at a text selection, not over cells.");
440
+ return false;
441
+ }
442
+ const range = canonicalSelectionRange(state);
443
+ const from = session.projection.addressAt(range.from);
444
+ if (from.isErr()) {
445
+ refuse(from.error.message, from.error.ground);
446
+ return false;
447
+ }
448
+ const to = session.projection.addressAt(range.to);
449
+ if (to.isErr()) {
450
+ refuse(to.error.message, to.error.ground);
451
+ return false;
452
+ }
453
+ syncCanonicalMode();
454
+ const prepared = session.prepareIntents(state, {
455
+ intents: [{
456
+ type: "replaceFragment",
457
+ from: from.value,
458
+ to: to.value,
459
+ paragraphs: [fieldInsertionParagraph(field)],
460
+ openStart: 1,
461
+ openEnd: 1
462
+ }],
463
+ semantic: "paste"
464
+ });
465
+ if (prepared.isErr()) {
466
+ refuse(prepared.error.message, prepared.error.ground);
467
+ return false;
468
+ }
469
+ return publishCommit(prepared.value);
470
+ }
471
+ case "prosemirror": {
472
+ const fieldType = state.schema.nodes["field"];
473
+ if (fieldType === void 0) return false;
474
+ const insertion = state.tr.replaceSelectionWith(fieldType.create({
475
+ fieldType: parseFieldType(field.instruction),
476
+ instruction: field.instruction,
477
+ displayText: field.displayText,
478
+ fieldKind: "simple",
479
+ ...field.locked === void 0 ? {} : { fldLock: field.locked }
480
+ }), false).scrollIntoView();
481
+ view.dispatch(closeHistory(insertion));
482
+ return true;
483
+ }
484
+ case "refused": return false;
485
+ default: return panic("Unhandled editor session");
486
+ }
487
+ };
394
488
  /**
395
489
  * Show a peer's edit the room sequenced: the same publication as a local
396
490
  * commit, whether or not the editor takes local edits.
@@ -1263,6 +1357,7 @@ const createHiddenEditorManager = (hostDeps) => {
1263
1357
  captureCanonicalSave: () => editorSession.type === "canonical" ? editorSession.session.captureSaveSnapshot() : null,
1264
1358
  getCanonicalDocument: () => editorSession.type === "canonical" ? editorSession.session.document : null,
1265
1359
  autocomplete: autocompleteApi,
1360
+ insertField,
1266
1361
  getAnonymizationHighlights: () => anonymization.read(deps.getAnonymizationTerms?.() ?? NO_ANONYMIZATION_TERMS, anonymizationSources),
1267
1362
  canonicalEditorPositionAt: (position) => {
1268
1363
  if (editorSession.type !== "canonical") return void 0;
package/dist/index.d.ts CHANGED
@@ -39,6 +39,7 @@ import { FolioAnonymizationMatch, FolioAnonymizationTerm } from "./types/anonymi
39
39
  import { FolioAutocompleteApi, FolioAutocompleteState } from "./types/autocomplete.js";
40
40
  import { DeriveBlockIdInput, FolioBlockId, currentFolioBlockId, deriveBlockId, getFolioParaIdFromBlockId, isFolioBlockId, isSequentialFolioBlockId } from "./types/block-id.js";
41
41
  import { document_d_exports } from "./types/document.js";
42
+ import { FolioDerivedFields, FolioFieldInsertion } from "./types/fields.js";
42
43
  import { CreateEmptyDocumentOptions, createEmptyDocument } from "./utils/createDocument.js";
43
44
  import { getGoogleFontsEnabled, setGoogleFontsEnabled } from "./utils/fontResolver.js";
44
45
  import { mergeDocumentContent } from "./utils/mergeDocumentContent.js";
@@ -47,4 +48,4 @@ import { DOCX_CONFORMANCE_CLASSES } from "@stll/docx-core/model";
47
48
  import { OP_STORIES, OpStory, TextPosition } from "@stll/docx-core/ops";
48
49
  type Document = document_d_exports.Document;
49
50
  type DocxConformanceClass = document_d_exports.DocxConformanceClass;
50
- export { type AIBarStatus, type AIChatMode, type AICitation, type AICitationRange, type AICitationSource, type AIGenerateInput, type AISuggestion, type AISuggestionApplyMode, type AISuggestionPreset, type AISuggestionSeverity, type AISuggestionStatus, type ApplyFolioDocumentOperationsOptions, type ApplyResult, type BlockRect, COMPARE_REVISION_FORMATS, COMPARE_UNSUPPORTED_REASONS, COMPARE_VERIFICATION_CAUSES, COMPARE_VERIFICATION_INVARIANTS, type CompareChange, type CompareChangeLocation, type CompareCompatibility, type CompareContentOptions, CompareDocxApplyError, type CompareDocxError, CompareDocxFinalParagraphMarkError, CompareDocxOperationLimitError, type CompareDocxOptions, CompareDocxParseError, CompareDocxRoundTripError, CompareDocxSerializeError, type CompareFolioRequirement, type CompareResult, type CompareRevisionFormat, type CompareUnsupportedPart, type CompareUnsupportedReason, type CompareVerification, type CompareVerificationCause, type CompareVerificationFailure, type CompareVerificationInvariant, type CreateEmptyDocumentOptions, DEFAULT_AI_SUGGESTION_PRESETS, DEFAULT_OUTLINE_DEPTH, DOCUMENT_PRESET_VERSION, DOCUMENT_STYLE_SET_VERSION, DOCX_CONFORMANCE_CLASSES, DRAWING_SAFETY_CLASSES, type DeriveBlockIdInput, type DirectiveKind, type DirectiveRange, type Document, type DocumentPreset, type DocumentPropertiesOptions, type DocumentStyleCatalog, type DocumentStyleCatalogEntry, type DocumentStyleSet, type DocxCompatibility, type DocxCompatibilityContext, type DocxCompatibilityIssue, type DocxCompatibilityLocation, type DocxCompatibilityPart, type DocxConformanceClass, type DocxDrawingClassification, type DrawingSafetyClass, type EditorReadOnlyReason, type EmbeddedFont, type EmbeddedFontParts, type ExtractDocumentStyleSetOptions, FOLIO_CONTENT_COMPARISON_LIMITS, FOLIO_DOCUMENT_OPERATION_BATCH_MODES, FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_MODES, FOLIO_DOCUMENT_OPERATION_MODES_BY_TYPE, FOLIO_DOCUMENT_OPERATION_PRECONDITIONS, FOLIO_DOCUMENT_OPERATION_STORIES, FOLIO_DOCUMENT_OPERATION_TYPES, FOLIO_HIGHLIGHT_COLOR_VALUES, FOLIO_LINE_SPACING_RULE_VALUES, FOLIO_PARAGRAPH_ALIGNMENT_VALUES, FOLIO_YJS_ATTR_SCHEMA_VERSION, type FinalParagraphMarkRevision, type FolioAIBlock, type FolioAIBlockAnchor, type FolioAIBlockKind, type FolioAIBlockPreviewRun, type FolioAIBlockStructuralBoundary, type FolioAIBlockTableLocation, type FolioAIComment, type FolioAIDiagnosticBlock, type FolioAIEditAppliedOperation, type FolioAIEditApplyMode, type FolioAIEditApplyOutcome, type FolioAIEditApplyResult, type FolioAIEditNormalization, type FolioAIEditNormalizationCode, type FolioAIEditOperation, type FolioAIEditParagraphIdentity, type FolioAIEditPrecondition, type FolioAIEditReviewMeta, type FolioAIEditSeverity, type FolioAIEditSkipReason, type FolioAIEditSkippedOperation, type FolioAIEditSnapshot, type FolioAIInlineBooleanProperty, type FolioAIInlineFormatting, type FolioAIInlineFormattingPatch, type FolioAIParagraphBlock, type FolioAIParagraphSpacing, type FolioAISignatureParty, type FolioAnonymizationMatch, type FolioAnonymizationTerm, type FolioAutocompleteApi, type FolioAutocompleteState, type FolioBlockId, type FolioContentBlock, type FolioContentBlockProperty, type FolioContentComparison, type FolioContentComparisonError, type FolioContentComparisonEvent, type FolioContentComparisonLimit, FolioContentComparisonLimitError, type FolioContentContainerPathEntry, type FolioContentFormatRange, type FolioContentFormattingChange, type FolioContentIdStability, type FolioContentInlineBooleanProperty, type FolioContentInlineComparisonResult, type FolioContentInlineFormatting, type FolioContentInlineFormattingPatch, FolioContentInlinePresentationProjectionError, type FolioContentLineSpacingRule, type FolioContentParagraphAlignment, type FolioContentParagraphFormattingPatch, type FolioContentParagraphKind, type FolioContentParagraphSpacing, type FolioContentRun, type FolioContentSnapshot, type FolioContentStatedNumbering, type FolioContentStructuralChange, type FolioContentTableLocation, type FolioContentTextSegment, type FolioDocumentOperation, type FolioDocumentOperationAffectedTarget, type FolioDocumentOperationBatch, type FolioDocumentOperationBatchInput, type FolioDocumentOperationCapabilities, type FolioDocumentOperationIssue, type FolioDocumentOperationMode, type FolioDocumentOperationPrecondition, type FolioDocumentOperationReceipt, type FolioDocumentOperationRecovery, type FolioDocumentOperationResult, type FolioDocumentOperationResultBase, type FolioDocumentOperationStatus, type FolioDocumentOperationStory, type FolioDocumentOperationType, type FolioDocumentOperationUndoFailureReason, type FolioDocumentOperationUndoHandle, type FolioDocumentOperationUndoResult, type FolioDocxCompatibilityHost, type FolioDocxCompatibilityProfile, type FolioRevisionStamp, type FolioUndefinedReferencePolicy, type FolioWordDiffOptions, type FolioYjsAttrSchemaVersion, FolioYjsAttrSchemaVersionError, type ImageMeta, type ImageRef, type InspectDocxCompatibilityOptions, InvalidCompareDocxOptionsError, InvalidFolioContentComparisonError, InvalidFolioDocumentOperationBatchError, MAX_COMPARE_OPERATIONS, type MarkdownOptions, type MarkdownResult, OP_STORIES, type OpStory, type OutlineDepth, type PositionalText, type ResolvedAnchor, type ReviewDisplayMode, STELLA_STYLE_SET_NAME, type TemplatePreviewHiddenRange, type TemplatePreviewSpan, type TemplatePreviewValue, type TemplatePreviewValues, type TemplateSlashMenuKeyAction, type TemplateSlashMenuState, type TextPosition, UnsupportedFolioDocumentOperationVersionError, WORD_DIFF_GRANULARITIES, type WordDiffGranularity, type WordDiffNormalization, type WordDiffOptions, type WordDiffSegment, applyFolioAIEditOperations, applyFolioDocumentOperations, applySuggestions, assertSupportedFolioDocumentOperationVersion, buildEmbeddedFontFamilyMap, buildPositionalText, clearTemplateSlashMenu, compareContent, compareDocx, consumeTemplateSlashQuery, createAICitationDecorationsPlugin, createDocx, createEmptyDocument, createFolioAIEditSnapshot, createStellaStyleDocumentPreset, createStellaStyleSet, currentFolioBlockId, deriveBlockId, diffWordSegments, extractDocumentStyleSet, extractDocumentStyleSetFromDocx, extractEmbeddedFonts, filterHeadingsByDepth, fromMarkdown, getEmbeddedFontFaces, getFolioCaretViewportRect, getFolioDocumentOperationCapabilities, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts, getFolioParaIdFromBlockId, getFolioSelectionViewportRect, getGoogleFontsEnabled, getTemplateDirectives, getTemplateSlashMenu, hashFolioAIBlockText, inspectDocumentStyles, inspectDocumentStylesFromDocx, inspectDocxCompatibility, isFolioAIContentBlock, isFolioBlockId, isFolioDocumentOperationModeSupported, isSequentialFolioBlockId, isSuggestionStale, isSupportedFolioDocumentOperationVersion, mergeDocumentContent, normalizeFolioAIBlockText, parseFolioDocumentOperationBatch, resetTemplateSlashQuery, resolveSuggestionAnchor, scanDirectives, scopeEmbeddedFontFamily, scrollFolioPositionIntoView, setAICitationsMeta, setAISuggestionsMeta, setActiveCitationMeta, setFocusedSuggestionMeta, setGoogleFontsEnabled, setTemplatePreviewValues, templateSlashMenuKey, toMarkdown, toMarkdownResult };
51
+ export { type AIBarStatus, type AIChatMode, type AICitation, type AICitationRange, type AICitationSource, type AIGenerateInput, type AISuggestion, type AISuggestionApplyMode, type AISuggestionPreset, type AISuggestionSeverity, type AISuggestionStatus, type ApplyFolioDocumentOperationsOptions, type ApplyResult, type BlockRect, COMPARE_REVISION_FORMATS, COMPARE_UNSUPPORTED_REASONS, COMPARE_VERIFICATION_CAUSES, COMPARE_VERIFICATION_INVARIANTS, type CompareChange, type CompareChangeLocation, type CompareCompatibility, type CompareContentOptions, CompareDocxApplyError, type CompareDocxError, CompareDocxFinalParagraphMarkError, CompareDocxOperationLimitError, type CompareDocxOptions, CompareDocxParseError, CompareDocxRoundTripError, CompareDocxSerializeError, type CompareFolioRequirement, type CompareResult, type CompareRevisionFormat, type CompareUnsupportedPart, type CompareUnsupportedReason, type CompareVerification, type CompareVerificationCause, type CompareVerificationFailure, type CompareVerificationInvariant, type CreateEmptyDocumentOptions, DEFAULT_AI_SUGGESTION_PRESETS, DEFAULT_OUTLINE_DEPTH, DOCUMENT_PRESET_VERSION, DOCUMENT_STYLE_SET_VERSION, DOCX_CONFORMANCE_CLASSES, DRAWING_SAFETY_CLASSES, type DeriveBlockIdInput, type DirectiveKind, type DirectiveRange, type Document, type DocumentPreset, type DocumentPropertiesOptions, type DocumentStyleCatalog, type DocumentStyleCatalogEntry, type DocumentStyleSet, type DocxCompatibility, type DocxCompatibilityContext, type DocxCompatibilityIssue, type DocxCompatibilityLocation, type DocxCompatibilityPart, type DocxConformanceClass, type DocxDrawingClassification, type DrawingSafetyClass, type EditorReadOnlyReason, type EmbeddedFont, type EmbeddedFontParts, type ExtractDocumentStyleSetOptions, FOLIO_CONTENT_COMPARISON_LIMITS, FOLIO_DOCUMENT_OPERATION_BATCH_MODES, FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_MODES, FOLIO_DOCUMENT_OPERATION_MODES_BY_TYPE, FOLIO_DOCUMENT_OPERATION_PRECONDITIONS, FOLIO_DOCUMENT_OPERATION_STORIES, FOLIO_DOCUMENT_OPERATION_TYPES, FOLIO_HIGHLIGHT_COLOR_VALUES, FOLIO_LINE_SPACING_RULE_VALUES, FOLIO_PARAGRAPH_ALIGNMENT_VALUES, FOLIO_YJS_ATTR_SCHEMA_VERSION, type FinalParagraphMarkRevision, type FolioAIBlock, type FolioAIBlockAnchor, type FolioAIBlockKind, type FolioAIBlockPreviewRun, type FolioAIBlockStructuralBoundary, type FolioAIBlockTableLocation, type FolioAIComment, type FolioAIDiagnosticBlock, type FolioAIEditAppliedOperation, type FolioAIEditApplyMode, type FolioAIEditApplyOutcome, type FolioAIEditApplyResult, type FolioAIEditNormalization, type FolioAIEditNormalizationCode, type FolioAIEditOperation, type FolioAIEditParagraphIdentity, type FolioAIEditPrecondition, type FolioAIEditReviewMeta, type FolioAIEditSeverity, type FolioAIEditSkipReason, type FolioAIEditSkippedOperation, type FolioAIEditSnapshot, type FolioAIInlineBooleanProperty, type FolioAIInlineFormatting, type FolioAIInlineFormattingPatch, type FolioAIParagraphBlock, type FolioAIParagraphSpacing, type FolioAISignatureParty, type FolioAnonymizationMatch, type FolioAnonymizationTerm, type FolioAutocompleteApi, type FolioAutocompleteState, type FolioBlockId, type FolioContentBlock, type FolioContentBlockProperty, type FolioContentComparison, type FolioContentComparisonError, type FolioContentComparisonEvent, type FolioContentComparisonLimit, FolioContentComparisonLimitError, type FolioContentContainerPathEntry, type FolioContentFormatRange, type FolioContentFormattingChange, type FolioContentIdStability, type FolioContentInlineBooleanProperty, type FolioContentInlineComparisonResult, type FolioContentInlineFormatting, type FolioContentInlineFormattingPatch, FolioContentInlinePresentationProjectionError, type FolioContentLineSpacingRule, type FolioContentParagraphAlignment, type FolioContentParagraphFormattingPatch, type FolioContentParagraphKind, type FolioContentParagraphSpacing, type FolioContentRun, type FolioContentSnapshot, type FolioContentStatedNumbering, type FolioContentStructuralChange, type FolioContentTableLocation, type FolioContentTextSegment, type FolioDerivedFields, type FolioDocumentOperation, type FolioDocumentOperationAffectedTarget, type FolioDocumentOperationBatch, type FolioDocumentOperationBatchInput, type FolioDocumentOperationCapabilities, type FolioDocumentOperationIssue, type FolioDocumentOperationMode, type FolioDocumentOperationPrecondition, type FolioDocumentOperationReceipt, type FolioDocumentOperationRecovery, type FolioDocumentOperationResult, type FolioDocumentOperationResultBase, type FolioDocumentOperationStatus, type FolioDocumentOperationStory, type FolioDocumentOperationType, type FolioDocumentOperationUndoFailureReason, type FolioDocumentOperationUndoHandle, type FolioDocumentOperationUndoResult, type FolioDocxCompatibilityHost, type FolioDocxCompatibilityProfile, type FolioFieldInsertion, type FolioRevisionStamp, type FolioUndefinedReferencePolicy, type FolioWordDiffOptions, type FolioYjsAttrSchemaVersion, FolioYjsAttrSchemaVersionError, type ImageMeta, type ImageRef, type InspectDocxCompatibilityOptions, InvalidCompareDocxOptionsError, InvalidFolioContentComparisonError, InvalidFolioDocumentOperationBatchError, MAX_COMPARE_OPERATIONS, type MarkdownOptions, type MarkdownResult, OP_STORIES, type OpStory, type OutlineDepth, type PositionalText, type ResolvedAnchor, type ReviewDisplayMode, STELLA_STYLE_SET_NAME, type TemplatePreviewHiddenRange, type TemplatePreviewSpan, type TemplatePreviewValue, type TemplatePreviewValues, type TemplateSlashMenuKeyAction, type TemplateSlashMenuState, type TextPosition, UnsupportedFolioDocumentOperationVersionError, WORD_DIFF_GRANULARITIES, type WordDiffGranularity, type WordDiffNormalization, type WordDiffOptions, type WordDiffSegment, applyFolioAIEditOperations, applyFolioDocumentOperations, applySuggestions, assertSupportedFolioDocumentOperationVersion, buildEmbeddedFontFamilyMap, buildPositionalText, clearTemplateSlashMenu, compareContent, compareDocx, consumeTemplateSlashQuery, createAICitationDecorationsPlugin, createDocx, createEmptyDocument, createFolioAIEditSnapshot, createStellaStyleDocumentPreset, createStellaStyleSet, currentFolioBlockId, deriveBlockId, diffWordSegments, extractDocumentStyleSet, extractDocumentStyleSetFromDocx, extractEmbeddedFonts, filterHeadingsByDepth, fromMarkdown, getEmbeddedFontFaces, getFolioCaretViewportRect, getFolioDocumentOperationCapabilities, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts, getFolioParaIdFromBlockId, getFolioSelectionViewportRect, getGoogleFontsEnabled, getTemplateDirectives, getTemplateSlashMenu, hashFolioAIBlockText, inspectDocumentStyles, inspectDocumentStylesFromDocx, inspectDocxCompatibility, isFolioAIContentBlock, isFolioBlockId, isFolioDocumentOperationModeSupported, isSequentialFolioBlockId, isSuggestionStale, isSupportedFolioDocumentOperationVersion, mergeDocumentContent, normalizeFolioAIBlockText, parseFolioDocumentOperationBatch, resetTemplateSlashQuery, resolveSuggestionAnchor, scanDirectives, scopeEmbeddedFontFamily, scrollFolioPositionIntoView, setAICitationsMeta, setAISuggestionsMeta, setActiveCitationMeta, setFocusedSuggestionMeta, setGoogleFontsEnabled, setTemplatePreviewValues, templateSlashMenuKey, toMarkdown, toMarkdownResult };
@@ -0,0 +1,8 @@
1
+ import { FolioDerivedFields } from "../../types/fields.js";
2
+ import { Plugin } from "prosemirror-state";
3
+ /**
4
+ * The default session's derived fields: after each transaction that changes
5
+ * the document, the owned fields outside tracked deletions show the texts the
6
+ * host derives for them, in the same transaction as the edit.
7
+ */
8
+ export declare const createDerivedFieldsPlugin: (getDerivedFields: () => FolioDerivedFields | undefined) => Plugin;
@@ -0,0 +1,52 @@
1
+ import { panic } from "better-result";
2
+ import { Plugin, PluginKey, Transaction } from "prosemirror-state";
3
+ import { isHistoryTransaction } from "prosemirror-history";
4
+ // src/prosemirror/plugins/derivedFields.ts
5
+ const REMOVAL_MARKS = /* @__PURE__ */ new Set(["deletion", "moveFrom"]);
6
+ /** The y-prosemirror binding's meta key; its peer derived the texts it syncs. */
7
+ const Y_SYNC_META = "y-sync$";
8
+ /**
9
+ * A local edit, not an undo or redo (which restores fields as they stood) or
10
+ * a room update, judged by the transaction that started the dispatch.
11
+ */
12
+ const derivesFields = (transaction) => {
13
+ if (!transaction.docChanged) return false;
14
+ const appendedTo = transaction.getMeta("appendedTransaction");
15
+ const root = appendedTo instanceof Transaction ? appendedTo : transaction;
16
+ return !isHistoryTransaction(root) && root.getMeta(Y_SYNC_META) === void 0;
17
+ };
18
+ /**
19
+ * The default session's derived fields: after each transaction that changes
20
+ * the document, the owned fields outside tracked deletions show the texts the
21
+ * host derives for them, in the same transaction as the edit.
22
+ */
23
+ const createDerivedFieldsPlugin = (getDerivedFields) => new Plugin({
24
+ key: new PluginKey("folioDerivedFields"),
25
+ appendTransaction(transactions, _previous, state) {
26
+ const derived = getDerivedFields();
27
+ if (derived === void 0 || !transactions.some(derivesFields)) return null;
28
+ const owned = [];
29
+ const instructions = [];
30
+ state.doc.descendants((node, position) => {
31
+ if (node.type.name !== "field") return true;
32
+ const { instruction, displayText } = node.attrs;
33
+ if (typeof instruction !== "string" || typeof displayText !== "string" || !derived.owns(instruction) || node.marks.some((mark) => REMOVAL_MARKS.has(mark.type.name))) return false;
34
+ owned.push({
35
+ position,
36
+ displayText
37
+ });
38
+ instructions.push(instruction);
39
+ return false;
40
+ });
41
+ if (owned.length === 0) return null;
42
+ const texts = derived.displayTexts(instructions);
43
+ if (texts.length !== owned.length) panic(`derivedFields.displayTexts returned ${texts.length} texts for ${owned.length} fields.`);
44
+ const transaction = state.tr;
45
+ for (const [index, { position, displayText }] of owned.entries()) {
46
+ const text = texts[index];
47
+ if (text !== void 0 && text !== displayText) transaction.setNodeAttribute(position, "displayText", text);
48
+ }
49
+ return transaction.docChanged ? transaction : null;
50
+ }
51
+ });
52
+ export { createDerivedFieldsPlugin };
@@ -0,0 +1,25 @@
1
+ /** A field a host inserts: a `w:fldSimple` showing a fixed text. */
2
+ export type FolioFieldInsertion = {
3
+ /** The field instruction, written as `w:fldSimple/@w:instr`. */
4
+ instruction: string;
5
+ /** What the field shows until something updates it. */
6
+ displayText: string;
7
+ /** Whether the field's result is locked against recomputation (`@w:fldLock`). */
8
+ locked?: boolean;
9
+ };
10
+ /**
11
+ * Fields whose display text the host derives from the document, kept current
12
+ * with every local edit: each edit that changes what they should show updates
13
+ * them in the same undo step, and a peer in a shared room receives the update
14
+ * with the edit.
15
+ */
16
+ export type FolioDerivedFields = {
17
+ /** Whether the host derives the field with this instruction. */
18
+ owns: (instruction: string) => boolean;
19
+ /**
20
+ * What each owned field shows, from the instructions of the owned fields
21
+ * of the main story outside tracked deletions, in document order: one text
22
+ * per instruction.
23
+ */
24
+ displayTexts: (instructions: readonly string[]) => readonly string[];
25
+ };
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/folio-core",
3
- "version": "0.70.0",
3
+ "version": "0.71.0",
4
4
  "description": "Headless, framework-neutral core of folio: the OOXML (.docx) parser, document model, ProseMirror integration, and page-layout engine. No React.",
5
5
  "keywords": [
6
6
  "document-model",