@gct-paas/word 1.0.2 → 1.0.3-beta.1

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.
Files changed (170) hide show
  1. package/README.md +27 -13
  2. package/dist/browser.js +1 -1
  3. package/dist/chunks/{ModelEditor-CXoezurC.js → ModelEditor-DqavEAJg.js} +113 -4
  4. package/dist/chunks/ModelEditor-DqavEAJg.js.map +1 -0
  5. package/dist/chunks/NodeFactory-DzFnWaWf.js +500 -0
  6. package/dist/chunks/NodeFactory-DzFnWaWf.js.map +1 -0
  7. package/dist/chunks/QuickFillPanel-BNZwXlnL.js +336 -0
  8. package/dist/chunks/QuickFillPanel-BNZwXlnL.js.map +1 -0
  9. package/dist/chunks/{browser-DY0wE3Uz.js → browser-DkEIriBA.js} +1462 -772
  10. package/dist/chunks/browser-DkEIriBA.js.map +1 -0
  11. package/dist/chunks/legacy-template-converter-DFsd-elN.js +125 -0
  12. package/dist/chunks/legacy-template-converter-DFsd-elN.js.map +1 -0
  13. package/dist/chunks/migrate-YJTylIpz.js +5193 -0
  14. package/dist/chunks/migrate-YJTylIpz.js.map +1 -0
  15. package/dist/chunks/{sdk-Dz96Ca_-.js → sdk-D9n5KeaD.js} +1284 -660
  16. package/dist/chunks/sdk-D9n5KeaD.js.map +1 -0
  17. package/dist/chunks/src-BFXPGLus.js +3338 -0
  18. package/dist/chunks/src-BFXPGLus.js.map +1 -0
  19. package/dist/chunks/{table-borders-Dwuj7lFp.js → table-borders-B9bZMj5o.js} +2 -2
  20. package/dist/chunks/{table-borders-Dwuj7lFp.js.map → table-borders-B9bZMj5o.js.map} +1 -1
  21. package/dist/chunks/templates-Djcl21k4.js.map +1 -1
  22. package/dist/chunks/{types-Bq4hbWKT.js → types-CzOaf1gP.js} +90 -56
  23. package/dist/chunks/types-CzOaf1gP.js.map +1 -0
  24. package/dist/chunks/{NodeFactory-D9gVGSok.js → validation-DkCy8wHI.js} +10 -495
  25. package/dist/chunks/validation-DkCy8wHI.js.map +1 -0
  26. package/dist/docx.js +3 -2
  27. package/dist/docx.js.map +1 -1
  28. package/dist/index.js +6 -5
  29. package/dist/legacy.js +1 -0
  30. package/dist/platform.js +2 -2
  31. package/dist/style.css +1066 -679
  32. package/dist/types/adapters/browser/canvas/CanvasPages.d.ts +1 -1
  33. package/dist/types/adapters/browser/canvas/paint-context.d.ts +4 -0
  34. package/dist/types/adapters/browser/canvas/paint-signature.d.ts +4 -0
  35. package/dist/types/adapters/browser/index.d.ts +1 -0
  36. package/dist/types/adapters/browser/input/CanvasFieldBrackets.d.ts +10 -0
  37. package/dist/types/adapters/browser/input/CanvasTextInput.d.ts +5 -2
  38. package/dist/types/adapters/browser/input/ChoiceFieldInput.d.ts +7 -2
  39. package/dist/types/adapters/browser/input/FieldInputValidation.d.ts +1 -1
  40. package/dist/types/adapters/browser/input/InlineFieldInput.d.ts +1 -1
  41. package/dist/types/adapters/browser/input/SignatureFieldInput.d.ts +10 -1
  42. package/dist/types/adapters/browser/input/business/FieldPopover.d.ts +6 -0
  43. package/dist/types/adapters/browser/input/business/materials/CanvasMaterialTableActions.d.ts +3 -0
  44. package/dist/types/adapters/browser/input/business/materials/attach-canvas-materials.d.ts +3 -1
  45. package/dist/types/adapters/browser/input/business/tables/CanvasBusinessTableActions.d.ts +3 -0
  46. package/dist/types/adapters/browser/input/business/tables/CanvasBusinessTablePanel.d.ts +4 -0
  47. package/dist/types/adapters/browser/input/business/tables/CanvasQuickFillDialog.d.ts +9 -8
  48. package/dist/types/adapters/browser/input/business/tables/attach-canvas-business-table.d.ts +4 -1
  49. package/dist/types/adapters/browser/input/business/tables/quick-fill-panel.d.ts +22 -0
  50. package/dist/types/adapters/browser/input/business/tables/table-action-anchors.d.ts +3 -3
  51. package/dist/types/adapters/browser/input/business/tables/table-action-pages.d.ts +26 -0
  52. package/dist/types/adapters/browser/input/business/tables/table-actions-renderer.d.ts +4 -0
  53. package/dist/types/adapters/browser/input/field-panel-geometry.d.ts +12 -0
  54. package/dist/types/adapters/browser/input/signature-panel.d.ts +6 -0
  55. package/dist/types/adapters/browser/input/types.d.ts +4 -4
  56. package/dist/types/adapters/browser/input/validation/CanvasValidationComments.d.ts +19 -0
  57. package/dist/types/adapters/browser/input/validation/CanvasValidationPanel.d.ts +12 -8
  58. package/dist/types/adapters/browser/input/validation/validation-issue-key.d.ts +3 -0
  59. package/dist/types/adapters/browser/input/word-error-text.d.ts +12 -2
  60. package/dist/types/adapters/document/types.d.ts +2 -1
  61. package/dist/types/adapters/platform/field-catalog/field-business-rules.d.ts +1 -1
  62. package/dist/types/adapters/platform/index.d.ts +1 -0
  63. package/dist/types/adapters/platform/template-reference-migration.d.ts +6 -0
  64. package/dist/types/adapters/platform/templates.d.ts +13 -1
  65. package/dist/types/adapters/vue/GctWordPrintRenderer.vue.d.ts +1 -1
  66. package/dist/types/adapters/vue/GctWordTemplateDesigner.vue.d.ts +3 -0
  67. package/dist/types/adapters/vue/QuickFillPanel.vue.d.ts +12 -0
  68. package/dist/types/adapters/vue/SignatureCardReader.vue.d.ts +1 -0
  69. package/dist/types/adapters/vue/SignatureFieldPanel.vue.d.ts +0 -1
  70. package/dist/types/adapters/vue/SignatureVisual.vue.d.ts +12 -0
  71. package/dist/types/adapters/vue/WordFeedback.vue.d.ts +11 -0
  72. package/dist/types/adapters/vue/WordLayoutNotices.vue.d.ts +8 -0
  73. package/dist/types/adapters/vue/WordOperationError.vue.d.ts +11 -0
  74. package/dist/types/adapters/vue/field-properties/dependency-strategies.d.ts +7 -0
  75. package/dist/types/adapters/vue/index.d.ts +2 -0
  76. package/dist/types/adapters/vue/layout-notices.d.ts +15 -0
  77. package/dist/types/adapters/vue/legacy-template-converter.d.ts +14 -0
  78. package/dist/types/adapters/vue/quick-fill-container.d.ts +2 -0
  79. package/dist/types/adapters/vue/quick-fill-data.d.ts +8 -0
  80. package/dist/types/adapters/vue/quick-fill-merge.d.ts +49 -0
  81. package/dist/types/adapters/vue/quick-fill-panel.d.ts +4 -0
  82. package/dist/types/adapters/vue/region-properties/WordBusinessRegion.vue.d.ts +3 -0
  83. package/dist/types/adapters/vue/region-properties/WordDataLockConfig.vue.d.ts +16 -0
  84. package/dist/types/adapters/vue/useWordWorkspace.d.ts +6 -3
  85. package/dist/types/adapters/vue/word-feedback.d.ts +21 -0
  86. package/dist/types/data/DataManager.d.ts +2 -2
  87. package/dist/types/data/rows/copy-row.d.ts +5 -0
  88. package/dist/types/data/services/DataDependencies.d.ts +2 -2
  89. package/dist/types/data/types/manager.d.ts +2 -0
  90. package/dist/types/data/types/rules.d.ts +8 -1
  91. package/dist/types/import/legacy/autofill.d.ts +3 -0
  92. package/dist/types/import/legacy/bindings.d.ts +9 -0
  93. package/dist/types/import/legacy/boundary.d.ts +10 -0
  94. package/dist/types/import/legacy/business-fields.d.ts +25 -0
  95. package/dist/types/import/legacy/context.d.ts +61 -0
  96. package/dist/types/import/legacy/data-sources.d.ts +29 -0
  97. package/dist/types/import/legacy/document-rules.d.ts +38 -0
  98. package/dist/types/import/legacy/document-signature.d.ts +16 -0
  99. package/dist/types/import/legacy/fields.d.ts +34 -0
  100. package/dist/types/import/legacy/index.d.ts +3 -0
  101. package/dist/types/import/legacy/initialization.d.ts +34 -0
  102. package/dist/types/import/legacy/json-data.d.ts +25 -0
  103. package/dist/types/import/legacy/materials.d.ts +40 -0
  104. package/dist/types/import/legacy/media.d.ts +18 -0
  105. package/dist/types/import/legacy/metadata.d.ts +23 -0
  106. package/dist/types/import/legacy/migrate.d.ts +9 -0
  107. package/dist/types/import/legacy/page-widgets.d.ts +30 -0
  108. package/dist/types/import/legacy/relations.d.ts +25 -0
  109. package/dist/types/import/legacy/scalar-fields.d.ts +7 -0
  110. package/dist/types/import/legacy/styles.d.ts +52 -0
  111. package/dist/types/import/legacy/table-variants.d.ts +18 -0
  112. package/dist/types/import/legacy/tables.d.ts +27 -0
  113. package/dist/types/import/legacy/trace-fields.d.ts +21 -0
  114. package/dist/types/import/legacy/types.d.ts +141 -0
  115. package/dist/types/import/legacy/widget-presentation.d.ts +10 -0
  116. package/dist/types/layout/engine/atoms/control-text.d.ts +16 -0
  117. package/dist/types/layout/engine/atoms/field-control.d.ts +2 -13
  118. package/dist/types/layout/engine/atoms/fit-atomic.d.ts +1 -1
  119. package/dist/types/layout/engine/atoms/signatures.d.ts +2 -2
  120. package/dist/types/layout/engine/blocks/placement-types.d.ts +7 -0
  121. package/dist/types/layout/engine/pagination/content-flow.d.ts +8 -0
  122. package/dist/types/layout/engine/tables/place-table-window.d.ts +3 -2
  123. package/dist/types/layout/engine/tables/row-flow.d.ts +3 -2
  124. package/dist/types/layout/engine/tables/table-flow.d.ts +3 -1
  125. package/dist/types/layout/geometry/control-brackets.d.ts +4 -0
  126. package/dist/types/layout/types/presentation/controls.d.ts +13 -0
  127. package/dist/types/layout/types/presentation/images.d.ts +8 -0
  128. package/dist/types/layout/types/presentation/signatures.d.ts +6 -0
  129. package/dist/types/model/business/business-types.d.ts +9 -1
  130. package/dist/types/model/business/data-lock-config.d.ts +27 -0
  131. package/dist/types/runtime/form/business/signatures/NativeSignatures.d.ts +3 -1
  132. package/dist/types/runtime/form/business/signatures/device-signature-lock.d.ts +2 -0
  133. package/dist/types/runtime/form/business/tables/row-fields.d.ts +1 -1
  134. package/dist/types/runtime/form/copy-field-paths.d.ts +3 -0
  135. package/dist/types/runtime/form/fields/core/declaration-changes.d.ts +2 -2
  136. package/dist/types/runtime/form/fields/core/rules/CommonFieldRules.d.ts +5 -1
  137. package/dist/types/runtime/form/validation/NativeFieldValidation.d.ts +16 -2
  138. package/dist/types/runtime/form/validation/description.d.ts +8 -4
  139. package/dist/types/runtime/form/validation/targets.d.ts +1 -1
  140. package/dist/types/runtime/form/validation/types.d.ts +2 -0
  141. package/dist/types/runtime/interaction/EditorController.d.ts +5 -1
  142. package/dist/types/runtime/interaction/browse/types.d.ts +1 -1
  143. package/dist/types/runtime/interaction/design/format/EditorFormat.d.ts +2 -2
  144. package/dist/types/runtime/interaction/design/format/summary.d.ts +1 -2
  145. package/dist/types/runtime/interaction/design/format/targets.d.ts +11 -0
  146. package/dist/types/runtime/interaction/design/format/types.d.ts +3 -3
  147. package/dist/types/runtime/interaction/design/tables/regions/EditorTableRegions.d.ts +3 -1
  148. package/dist/types/runtime/interaction/design/tables/regions/definitions.d.ts +7 -0
  149. package/dist/types/runtime/interaction/field-signature.d.ts +3 -0
  150. package/dist/types/runtime/interaction/field-text.d.ts +5 -5
  151. package/dist/types/runtime/interaction/validation/types.d.ts +2 -0
  152. package/dist/types/runtime/presentation/fields/signatures.d.ts +5 -2
  153. package/dist/types/shared/platform-gct/form-credentials.d.ts +0 -1
  154. package/dist/types/shared/platform-gct/templates.d.ts +2 -0
  155. package/dist/types/shared/signature-graphic.d.ts +27 -0
  156. package/dist/types/shared/text/shading.d.ts +12 -0
  157. package/dist/types/shared/text/word-navigation.d.ts +1 -0
  158. package/dist/types/shared/ui/select/src/select.types.d.ts +2 -0
  159. package/dist/types/shared/ui/tree-select/src/unified-tree-select.vue.d.ts +1 -1
  160. package/dist/types/shared/word-shortcuts.d.ts +28 -0
  161. package/dist/vue.js +2482 -4573
  162. package/dist/vue.js.map +1 -1
  163. package/package.json +10 -3
  164. package/dist/chunks/ModelEditor-CXoezurC.js.map +0 -1
  165. package/dist/chunks/NodeFactory-D9gVGSok.js.map +0 -1
  166. package/dist/chunks/browser-DY0wE3Uz.js.map +0 -1
  167. package/dist/chunks/sdk-Dz96Ca_-.js.map +0 -1
  168. package/dist/chunks/types-Bq4hbWKT.js.map +0 -1
  169. package/dist/types/adapters/browser/input/business/tables/fixed-quick-fill-grid.d.ts +0 -19
  170. package/dist/types/adapters/browser/input/validation/CanvasValidationMarks.d.ts +0 -15
@@ -1,17 +1,18 @@
1
- import { $ as rectDistance, $t as assertDataNumberPrecision, A as selectionFallbacks, An as sameLayoutIdentity, At as nativeObjectKey, B as fieldBehaviorLabel, Bt as normalizeResourceValue, Cn as isRequiredDataValueMissing, Ct as referenceContext, Dn as formatTsv, Dt as isReferenceScanField, E as snapshotFieldDragDefinition, Et as referenceValueIds, F as editingAllowed, Fn as assertFiniteLayoutNumber, Ft as nativeSelectedReferenceValue, G as afterFieldSettlement, H as systemDate, Ht as resourceContext, I as designRegionTypes, In as assertLayoutSize, It as referenceInputIdentity, J as writeFieldValue, Jt as commonFieldDeclaration, K as readFieldTarget, Kt as resourceValues, L as designRegionVariants, Ln as assertLayoutTextMeasureRequest, Lt as authenticatedSignature, M as assertAdaptiveImageCellWritable, Mn as snapshotLayoutVersion, Mt as isMaterialLotBinding, N as hasAdaptiveImageCell, Nn as layoutImageSourceKey, Nt as isNamedLotBinding, O as freezeSelection, On as parseTsv, Ot as referenceScanPaths, P as assertOwnedEditingAllowed, Pn as LayoutContractError, Pt as lotReference, Q as positionX, Qt as nativeFieldBehavior, R as choiceSelection, Rn as assertLayoutTextMeasurement, Rt as signatureText, S as EditorObjects, St as referenceBehavior, T as resolveFieldDrop, Tn as readDataValueInput, Tt as referenceOptions, U as readBusinessField, Ut as resourceLimits, V as resolveBooleanOptionLabel, Vt as resourceBehavior, W as sameBusinessField, Wt as resourceName, X as TextFlowError, Xt as isCommonField, Y as TextFlow, Yt as fieldBehavior, Z as hitPosition, Zt as isFieldTextInput, _ as readFieldOptionInput, _n as invalidDataNumberText, _t as sealStampKeys, a as writeGuardedFieldText, an as readDataBoolean, at as sameTextSource, b as toggledFieldOptionIds, bn as isClosedDataContainer, bt as normalizeReferenceValue, c as fieldNumberSettings, d as isIncompleteFieldNumber, dn as resolveDataValueUpdate, en as dataParameterNumberKind, et as sourceBoundaryIndex, f as validateFieldNumber, fn as shouldInitializeDataValue, ft as millimetersToLayoutPx, g as readFieldChoiceInput, gn as findInvalidDataNumbers, gt as nativeSealValueKind, hn as dataValueIssuesFromError, ht as nativeSealText, i as validateFieldTextDraft, in as normalizeDataParameterNumber, it as samePosition, j as adaptiveImageCellMessage, jn as sameLayoutVersion, jt as nativeObjectRootField, k as mapSelection, kn as tsvClipboardLimits, kt as referenceScanUpdates, l as fieldNumberText, ln as resolveDataDefaultFrom, m as readFieldSignatureInput, mn as assertValidDataValue, mt as authenticatedSeal, n as readFieldTextInput, nn as encodeDataFieldValue, nt as positionSourceId, o as fieldValidationDescription, on as encodeDataCollection, ot as textSourceId, p as assertFieldSignatureInput, pn as DataValueError, pt as pointsToLayoutPx, q as resolveFieldTarget, qt as validateResourceFiles, r as sameFieldTextInput, rn as normalizeDataBoolean, rt as sameDomain, s as FieldNumberError, sn as emptyDataValue, t as nativeTableRowBatchLimit, tn as encodeDataChoice, tt as visualAffinity, u as fieldNumberValue, un as resolveDataDisplay, ut as layoutPxToMillimeters, vt as isSealPosition, w as designFieldDefaults, wn as isUninitializedDataValue, wt as referenceIds, x as writeGuardedFieldChoice, xn as isEmptyDataValue, xt as recordReference, yn as dataValueState, yt as parseSealValue, z as fieldBehaviorDefault, zt as signatureValues } from "./types-Bq4hbWKT.js";
1
+ import { $ as TextFlow, $t as isFieldTextInput, An as parseTsv, At as referenceOptions, B as designRegionTypes, Bn as assertLayoutTextMeasurement, Bt as nativeSelectedReferenceValue, C as toggledFieldOptionIds, Cn as isEmptyDataValue, Ct as isSealPosition, D as designFieldDefaults, Dn as readDataValueInput, Dt as referenceBehavior, En as isUninitializedDataValue, Et as recordReference, F as assertAdaptiveImageCellWritable, Fn as layoutImageSourceKey, Ft as nativeObjectKey, G as resolveBooleanOptionLabel, Gt as resourceLimits, H as choiceSelection, Ht as normalizeResourceValue, I as hasAdaptiveImageCell, In as LayoutContractError, It as nativeObjectRootField, J as sameBusinessField, Jt as resourceValues, K as systemDate, Kt as resourceName, L as assertOwnedEditingAllowed, Ln as assertFiniteLayoutNumber, Lt as isMaterialLotBinding, M as mapSelection, Mn as sameLayoutIdentity, Mt as isReferenceScanField, N as selectionFallbacks, Nn as sameLayoutVersion, Nt as referenceScanPaths, O as resolveFieldDrop, Ot as referenceContext, P as adaptiveImageCellMessage, Pn as snapshotLayoutVersion, Pt as referenceScanUpdates, Q as writeFieldValue, Qt as isCommonField, R as editingAllowed, Rn as assertLayoutSize, Rt as isNamedLotBinding, Sn as isClosedDataContainer, St as sealStampKeys, T as EditorObjects, Tn as isRequiredDataValueMissing, Tt as normalizeReferenceValue, U as fieldBehaviorDefault, Ut as resourceBehavior, V as designRegionVariants, Vt as referenceInputIdentity, W as fieldBehaviorLabel, Wt as resourceContext, X as readFieldTarget, Xt as commonFieldDeclaration, Y as afterFieldSettlement, Yt as validateResourceFiles, Z as resolveFieldTarget, Zt as fieldBehavior, _ as signatureText, _n as dataValueIssuesFromError, _t as millimetersToLayoutPx, a as writeGuardedFieldText, an as normalizeDataBoolean, at as sourceBoundaryIndex, b as readFieldOptionInput, bt as nativeSealText, c as fieldNumberSettings, cn as encodeDataCollection, ct as sameDomain, d as isIncompleteFieldNumber, dn as resolveDataDefaultFrom, dt as textSourceId, en as nativeFieldBehavior, et as TextFlowError, f as validateFieldNumber, fn as resolveDataDisplay, g as authenticatedSignature, gn as assertValidDataValue, hn as DataValueError, ht as layoutPxToMillimeters, i as validateFieldTextDraft, in as encodeDataFieldValue, it as rectDistance, j as freezeSelection, jn as tsvClipboardLimits, jt as referenceValueIds, k as snapshotFieldDragDefinition, kn as formatTsv, kt as referenceIds, l as fieldNumberText, ln as emptyDataValue, lt as samePosition, m as readFieldSignatureInput, mn as shouldInitializeDataValue, n as readFieldTextInput, nn as dataParameterNumberKind, nt as hitPosition, o as fieldValidationDescription, on as normalizeDataParameterNumber, ot as visualAffinity, p as assertFieldSignatureInput, pn as resolveDataValueUpdate, q as readBusinessField, r as sameFieldTextInput, rn as encodeDataChoice, rt as positionX, s as FieldNumberError, sn as readDataBoolean, st as positionSourceId, t as nativeTableRowBatchLimit, tn as assertDataNumberPrecision, u as fieldNumberValue, ut as sameTextSource, v as signatureValues, vn as findInvalidDataNumbers, vt as pointsToLayoutPx, w as writeGuardedFieldChoice, wt as parseSealValue, xn as dataValueState, xt as nativeSealValueKind, y as readFieldChoiceInput, yn as invalidDataNumberText, yt as authenticatedSeal, zn as assertLayoutTextMeasureRequest, zt as lotReference } from "./types-CzOaf1gP.js";
2
2
  import { a as contentBlockLeaves, s as contentLeaves, u as createUuid } from "./change-set-DgfKTJ6d.js";
3
3
  import { t as waitForAbortable } from "./abortable-D4G3Ib7H.js";
4
- import { D as equalData, E as copyInputData, O as freezeData, S as repeatingTableVariants, n as commonFieldWidgets, o as readFieldBinding, t as NodeFactory, w as cloneJsonData, x as repeatingTableSettings } from "./NodeFactory-D9gVGSok.js";
5
- import { a as readTextFormatUpdate, c as intersectsRectangle, g as replacePathIndexPlaceholders, h as parseValuePath, i as readParagraphFormatUpdate, l as isOrdinaryTable, m as mergeStyle, n as resolveKeepExceptionHighlight, o as containsRectangle, r as patchTextDeclaration, s as indexTablePositions, t as ModelEditor, u as rectangleFromPositions } from "./ModelEditor-CXoezurC.js";
6
- import { n as tableBorderWidthsPx, t as defaultTableBorderColor } from "./table-borders-Dwuj7lFp.js";
4
+ import { _ as equalData, d as repeatingTableSettings, f as repeatingTableVariants, g as copyInputData, m as cloneJsonData, v as freezeData } from "./validation-DkCy8wHI.js";
5
+ import { _ as replacePathIndexPlaceholders, a as readParagraphFormatUpdate, c as indexTablePositions, d as rectangleFromPositions, g as parseValuePath, h as mergeStyle, i as patchTextDeclaration, l as intersectsRectangle, n as resolveKeepExceptionHighlight, o as readTextFormatUpdate, s as containsRectangle, t as ModelEditor, u as isOrdinaryTable } from "./ModelEditor-DqavEAJg.js";
6
+ import { n as commonFieldWidgets, o as readFieldBinding, t as NodeFactory } from "./NodeFactory-DzFnWaWf.js";
7
+ import { n as tableBorderWidthsPx, t as defaultTableBorderColor } from "./table-borders-B9bZMj5o.js";
7
8
  import { groupBy, maxBy, sortBy, uniq } from "es-toolkit/array";
8
9
  import { isEqual, isPlainObject } from "es-toolkit/predicate";
9
10
  import { cloneDeep, escapeRegExp, groupBy as groupBy$1, isEqual as isEqual$1, isPlainObject as isPlainObject$1, isPromise, omit, sortBy as sortBy$1, uniq as uniq$1 } from "es-toolkit";
10
11
  import BigNumber from "bignumber.js";
11
12
  import { cloneDeep as cloneDeep$1, omit as omit$1, pick } from "es-toolkit/object";
12
- import { sum, sumBy } from "es-toolkit/math";
13
13
  import sortedIndex from "es-toolkit/compat/sortedIndex";
14
14
  import sortBy$2 from "es-toolkit/compat/sortBy";
15
+ import { sum, sumBy } from "es-toolkit/math";
15
16
  import sortedLastIndex from "es-toolkit/compat/sortedLastIndex";
16
17
  import sortedIndexBy from "es-toolkit/compat/sortedIndexBy";
17
18
  import { escapeRegExp as escapeRegExp$1 } from "es-toolkit/string";
@@ -19,6 +20,7 @@ import dayjs from "dayjs";
19
20
  import get from "es-toolkit/compat/get";
20
21
  import set from "es-toolkit/compat/set";
21
22
  import toPath from "es-toolkit/compat/toPath";
23
+ import { sha256 } from "js-sha256";
22
24
  // src/runtime/interaction/browse/media-preview.ts
23
25
  /** @file 预览只读取已有资源,打印与只读模式不走可编辑输入接口。 */
24
26
  function mediaPreview(options, snapshot, fieldId, instanceKey) {
@@ -30,17 +32,9 @@ function mediaPreview(options, snapshot, fieldId, instanceKey) {
30
32
  ].includes(mode)) return;
31
33
  const target = form.presentation.fields.target(fieldId, instance), field = fieldBehavior(target.declaration);
32
34
  if (!target.valuePath || !target.state.visible || mode === "fill" && target.state.editable) return;
33
- if (![
34
- "image",
35
- "file",
36
- "signature"
37
- ].includes(field.widget)) return;
35
+ if (field.widget !== "image" && field.widget !== "file") return;
38
36
  try {
39
- const entries = field.widget === "signature" ? signatureValues(target.value).map((record) => ({
40
- reference: record.url ?? "",
41
- name: record.username || "签名",
42
- url: record.url ? form.services.fields.signatureUrl(fieldId, target.valuePath, record.url) : void 0
43
- })) : resourceValues(target.value).map((reference) => ({
37
+ const entries = resourceValues(target.value).map((reference) => ({
44
38
  reference,
45
39
  name: resourceName(reference),
46
40
  url: form.services.fields.resourceUrl(fieldId, target.valuePath, reference)
@@ -402,6 +396,21 @@ var UnsupportedLayoutError = class extends Error {
402
396
  this.nodeId = nodeId;
403
397
  }
404
398
  };
399
+ // src/shared/text/shading.ts
400
+ /** clear 只显示底色,nil 明确取消底纹,solid 使用前景色。 */
401
+ function textShadingColor(shading) {
402
+ if (shading?.pattern === "nil") return "transparent";
403
+ if (shading?.pattern === "solid") return shading.color ?? "#000000";
404
+ return shading?.fill;
405
+ }
406
+ /** 纯色与明确取消底纹都已支持,只有实际图案需要报告外观差异。 */
407
+ function hasTextShadingPattern(shading) {
408
+ return !!shading?.pattern && ![
409
+ "clear",
410
+ "nil",
411
+ "solid"
412
+ ].includes(shading.pattern);
413
+ }
405
414
  // src/layout/styles/resolve-text-style.ts
406
415
  /** @file 业务字段与原生文字共用有效绘制样式解释,不保存任何文档。 */
407
416
  /** 按 Unicode 脚本选择实际字体,保持同脚本连续片段合并。 */
@@ -429,7 +438,7 @@ function resolvePaint(style, defaults, sample = "", fonts) {
429
438
  fontStyle,
430
439
  color: style.color ?? defaults.color,
431
440
  letterSpacingPx: style.letterSpacingPx ?? defaults.letterSpacingPx,
432
- backgroundColor: style.highlightColor ?? style.shading?.fill ?? defaults.backgroundColor,
441
+ backgroundColor: style.highlightColor ?? textShadingColor(style.shading) ?? defaults.backgroundColor,
433
442
  underline: style.underline ?? defaults.underline,
434
443
  strike: style.strike ?? defaults.strike,
435
444
  doubleStrike: style.doubleStrike ?? defaults.doubleStrike,
@@ -438,9 +447,357 @@ function resolvePaint(style, defaults, sample = "", fonts) {
438
447
  ...style.kerningMinSizePt === void 0 ? {} : { kerning: size >= pointsToLayoutPx(style.kerningMinSizePt) ? "normal" : "none" }
439
448
  };
440
449
  }
450
+ // src/layout/engine/atoms/control-text.ts
451
+ /** 字素算法只持有分割器,不保留字段或文字。 */
452
+ var segments = new Intl.Segmenter(void 0, { granularity: "grapheme" });
453
+ /** 字段内按合法字素换行,空行保留;不创建字符节点或内部模型地址。 */
454
+ function wrapTextRanges(text, width, presentation, measurer) {
455
+ const lines = [];
456
+ for (const match of text.matchAll(/([^\r\n]*)(\r\n|[\r\n]|$)/g)) {
457
+ if (match.index === text.length && text.length > 0 && !/[\r\n]$/.test(text)) break;
458
+ const part = match[1];
459
+ const source = match.index;
460
+ if (!part.length) {
461
+ lines.push({
462
+ text: "",
463
+ from: source,
464
+ to: source
465
+ });
466
+ continue;
467
+ }
468
+ const boundaries = [0, ...Array.from(segments.segment(part), (item) => item.index + item.segment.length)];
469
+ let begin = 0;
470
+ while (begin < boundaries.length - 1) {
471
+ let low = begin, high = boundaries.length - 1;
472
+ while (low < high) {
473
+ const middle = Math.ceil((low + high) / 2);
474
+ const advance = measurer.measureWidth({
475
+ text: part.slice(boundaries[begin], boundaries[middle]),
476
+ style: presentation.style,
477
+ direction: "ltr"
478
+ });
479
+ if (!Number.isFinite(advance) || advance < 0) throw new Error("字段文字度量返回无效宽度");
480
+ if (advance <= width) low = middle;
481
+ else high = middle - 1;
482
+ }
483
+ const end = Math.max(begin + 1, low);
484
+ lines.push({
485
+ text: part.slice(boundaries[begin], boundaries[end]),
486
+ from: source + boundaries[begin],
487
+ to: source + boundaries[end]
488
+ });
489
+ begin = end;
490
+ }
491
+ }
492
+ return lines;
493
+ }
494
+ /** 通用标签继续使用相同断行算法,字段额外保留原文区间供活动输入定位。 */
495
+ function wrapText(text, width, presentation, measurer) {
496
+ return wrapTextRanges(text, width, presentation, measurer).map((line) => line.text);
497
+ }
498
+ // src/layout/engine/atoms/diagonal.ts
499
+ /** @file 斜线表头的纯几何;两栏/四种三栏顶点共用最终尺寸与分区裁剪。 */
500
+ /** 整格斜线只用于唯一图形的单元格,不挤占或伸缩其他正文。 */
501
+ function isDiagonalCell(blocks) {
502
+ const block = blocks.length === 1 ? blocks[0] : void 0;
503
+ if (!block || typeof block !== "object" || !("kind" in block) || block.kind !== "paragraph" || !("content" in block) || !Array.isArray(block.content)) return false;
504
+ const content = block.content, node = content.length === 1 ? content[0] : void 0;
505
+ return !!node && typeof node === "object" && "kind" in node && node.kind === "pageWidget" && "widget" in node && node.widget === "diagonal";
506
+ }
507
+ /** 整格图形在行高最终分配后取真实尺寸,不把配置尺寸强行变成行高。 */
508
+ function fillCellDiagonal(blocks, width, height) {
509
+ const block = blocks.length === 1 ? blocks[0] : void 0, line = block?.kind === "paragraph" && block.lines.length === 1 ? block.lines[0] : void 0, piece = line?.pieces.length === 1 ? line.pieces[0] : void 0;
510
+ if (!block || block.kind !== "paragraph" || !line || piece?.kind !== "pageWidget" || piece.widget.content.kind !== "diagonal" || !piece.widget.content.fillCell) return blocks;
511
+ const widget = {
512
+ ...piece.widget,
513
+ width,
514
+ height,
515
+ baseline: height
516
+ };
517
+ return [{
518
+ ...block,
519
+ width,
520
+ height,
521
+ lines: [{
522
+ ...line,
523
+ width,
524
+ availableWidth: width,
525
+ height,
526
+ baseline: height,
527
+ indent: 0,
528
+ pieces: [{
529
+ ...piece,
530
+ widget
531
+ }]
532
+ }]
533
+ }];
534
+ }
535
+ /** 镜像角点名称与几何使用同一规则,避免文字分区与线条错位。 */
536
+ function cornerName(x, y) {
537
+ return `${y ? "bottom" : "top"}-${x ? "right" : "left"}`;
538
+ }
539
+ /** 按当前真实尺寸一次性计算线、文字和对应分区,绘制不重新解释配置。 */
540
+ function layoutDiagonal(content, width, height, paintStyleKey, paint, measurer) {
541
+ const w = width, h = height, three = content.columns === 3, flipX = three ? content.vertex.endsWith("right") : content.direction === "backward", flipY = three && content.vertex.startsWith("bottom");
542
+ /** 线条与分区顶点都从同一坐标变换得到。 */
543
+ function point(x, y) {
544
+ return {
545
+ x: flipX ? w - x : x,
546
+ y: flipY ? h - y : y
547
+ };
548
+ }
549
+ const origin = point(0, 0), endA = point(w, three ? h * .4 : h), endB = point(w * .4, h);
550
+ /** 统一的已解析线条,不借用旧 ImageWidget。 */
551
+ function line(end) {
552
+ return {
553
+ kind: "line",
554
+ x1: origin.x,
555
+ y1: origin.y,
556
+ x2: end.x,
557
+ y2: end.y,
558
+ widthPx: 1,
559
+ color: "#808080",
560
+ style: "solid"
561
+ };
562
+ }
563
+ const regions = /* @__PURE__ */ new Map();
564
+ regions.set(cornerName(!flipX, flipY), [
565
+ origin,
566
+ point(w, 0),
567
+ endA
568
+ ]);
569
+ if (three) {
570
+ regions.set(cornerName(!flipX, !flipY), [
571
+ origin,
572
+ endA,
573
+ point(w, h),
574
+ endB
575
+ ]);
576
+ regions.set(cornerName(flipX, !flipY), [
577
+ origin,
578
+ endB,
579
+ point(0, h)
580
+ ]);
581
+ } else regions.set(cornerName(flipX, !flipY), [
582
+ origin,
583
+ endA,
584
+ point(0, h)
585
+ ]);
586
+ const corners = three ? {
587
+ "top-left": [
588
+ "top-right",
589
+ "bottom-right",
590
+ "bottom-left"
591
+ ],
592
+ "top-right": [
593
+ "top-left",
594
+ "bottom-left",
595
+ "bottom-right"
596
+ ],
597
+ "bottom-left": [
598
+ "top-left",
599
+ "top-right",
600
+ "bottom-right"
601
+ ],
602
+ "bottom-right": [
603
+ "top-right",
604
+ "top-left",
605
+ "bottom-left"
606
+ ]
607
+ }[content.vertex] : flipX ? ["top-left", "bottom-right"] : ["top-right", "bottom-left"];
608
+ const metrics = measurer.measure({
609
+ text: "",
610
+ style: paint,
611
+ direction: "ltr"
612
+ }), lineHeight = (metrics.ascent + metrics.descent) * 1.2, boxWidth = Math.max(1, Math.min(w * .5, w - 8));
613
+ return {
614
+ kind: "diagonal",
615
+ paintStyleKey,
616
+ lines: three ? [line(endA), line(endB)] : [line(endA)],
617
+ slots: corners.map((corner, index) => {
618
+ const rows = wrapText(content.labels[three ? index : index === 0 ? 0 : 2] ?? "", boxWidth, { style: paint }, measurer), right = corner.endsWith("right"), x = right ? w - 4 - boxWidth : 4, y = corner.startsWith("bottom") ? Math.max(4, h - 4 - rows.length * lineHeight) : 4;
619
+ return {
620
+ clip: regions.get(corner),
621
+ texts: rows.map((text, row) => {
622
+ const advance = measurer.measureWidth({
623
+ text,
624
+ style: paint,
625
+ direction: "ltr"
626
+ });
627
+ return {
628
+ text,
629
+ width: advance,
630
+ x: x + (right ? Math.max(0, boxWidth - advance) : 0),
631
+ baseline: y + metrics.ascent + row * lineHeight
632
+ };
633
+ })
634
+ };
635
+ })
636
+ };
637
+ }
638
+ // src/layout/engine/paragraph/justify-line.ts
639
+ /** @file 断行后的间距扩展;源字素、原子尺寸和结果片段保持,绘制与停靠共用最终几何。 */
640
+ /** 只扩展普通及全角空白,不把不换行空格当作可丢弃的尾随空白。 */
641
+ var space = (text) => /^[ \t\u3000]+$/u.test(text);
642
+ /** 东亚文本提供字间机会;连写脚本仅使用词间空白,不切断连接。 */
643
+ var eastAsian = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
644
+ /** 当前可识别的连写脚本不能被分散对齐拆出字内空隙。 */
645
+ var cursive = /[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Nko}\p{Script=Mandaic}\p{Script=Mongolian}\p{Script=Phags_Pa}]/u;
646
+ /** 一行的自然片段推进,不把对齐间隔写进控件或图片尺寸。 */
647
+ function width(piece) {
648
+ return piece.kind === "text" ? piece.metrics.advanceWidth : piece.kind === "control" ? piece.control.width : piece.kind === "image" ? piece.image.frame.width : piece.kind === "pageWidget" ? piece.widget.width : piece.advanceWidth ?? 0;
649
+ }
650
+ /** 普通文字直接借用源相对偏移,只有长度变换才使用额外的展示映射。 */
651
+ function displayOffset(piece, boundary) {
652
+ return piece.displayOffsets?.[boundary] ?? piece.metrics.caretMap.offsets[boundary] - piece.source.from;
653
+ }
654
+ /** 收集临时排版单位,段落内零宽锚点不引入额外分散机会。 */
655
+ function units$2(line) {
656
+ const result = [];
657
+ for (const [index, piece] of line.pieces.entries()) if (piece.kind === "text") for (let at = 1; at < piece.metrics.caretMap.offsets.length; at++) {
658
+ const text = piece.text.slice(displayOffset(piece, at - 1), displayOffset(piece, at));
659
+ if (text) result.push({
660
+ piece: index,
661
+ boundary: at,
662
+ text
663
+ });
664
+ }
665
+ else if (piece.kind === "anchor") {
666
+ if (width(piece)) result.push({
667
+ piece: index,
668
+ text: " "
669
+ });
670
+ } else result.push({
671
+ piece: index,
672
+ text: ""
673
+ });
674
+ return result;
675
+ }
676
+ /** 不在源字素内部、连接控制符或开闭标点禁止边界扩展;样式节点边界不改变机会。 */
677
+ function opportunity(a, b, distribute) {
678
+ if (/[\u00a0\u202f\u2060\ufeff]/u.test(a.text + b.text)) return false;
679
+ if ("([{([{《〈「『【〔〖“‘".includes(a.text) || ")]})]}》〉」』】〕〗”’、。,;:!?,.!?;:".includes(b.text)) return false;
680
+ if (a.text === " " || a.text === " ") return true;
681
+ if (space(a.text) || space(b.text)) return distribute;
682
+ if (cursive.test(a.text) || cursive.test(b.text)) return false;
683
+ return distribute || eastAsian.test(a.text) || eastAsian.test(b.text);
684
+ }
685
+ /** 按最终绘制段度量自然宽度,并把展示偏移映射回原合法源边界;不持有新文字节点。 */
686
+ function naturalText(piece, gaps, trim, measurer) {
687
+ const count = piece.metrics.caretMap.offsets.length - 1, cuts = sortBy$2(uniq([
688
+ 0,
689
+ ...gaps.keys(),
690
+ count
691
+ ]), (value) => value), advances = [];
692
+ let advance = 0;
693
+ for (let index = 0; index < cuts.length - 1; index++) {
694
+ const from = cuts[index], to = cuts[index + 1], start = displayOffset(piece, from), measurement = measurer.measure({
695
+ text: piece.text.slice(start, displayOffset(piece, to)),
696
+ style: piece.paint,
697
+ direction: piece.direction
698
+ });
699
+ if (!Number.isFinite(measurement.advanceWidth) || measurement.advanceWidth < 0) throw new Error("对齐度量返回无效推进宽度");
700
+ for (let boundary = from; boundary <= to; boundary++) {
701
+ const offset = displayOffset(piece, boundary) - start, at = sortedIndex(measurement.caretMap.offsets, offset);
702
+ if (measurement.caretMap.offsets[at] !== offset) throw new Error("对齐度量缺少合法展示边界");
703
+ advances[boundary] = advance + (piece.direction === "rtl" ? measurement.advanceWidth - measurement.caretMap.x[at] : measurement.caretMap.x[at]);
704
+ }
705
+ advance += measurement.advanceWidth;
706
+ }
707
+ const naturalWidth = trim === void 0 ? advance : advances[trim];
708
+ return {
709
+ width: naturalWidth,
710
+ x: advances.map((value) => piece.direction === "rtl" ? naturalWidth - Math.min(value, naturalWidth) : Math.min(value, naturalWidth)),
711
+ starts: cuts.slice(0, -1)
712
+ };
713
+ }
714
+ /** 普通两端对齐只处理软换行;分散对齐也处理段末,无法扩展时居中,空白行原样保留。 */
715
+ function justifyFlowLine(line, alignment, measurer) {
716
+ if (alignment !== "justify" && alignment !== "distribute") return line;
717
+ if (alignment === "justify" && line.ending !== "wrap") return line;
718
+ const all = units$2(line);
719
+ let first = 0, last = all.length - 1;
720
+ while (first <= last && space(all[first].text)) first++;
721
+ while (last >= first && space(all[last].text)) last--;
722
+ if (first > last) return line;
723
+ const textGaps = /* @__PURE__ */ new Map(), atomicGaps = /* @__PURE__ */ new Map(), trims = /* @__PURE__ */ new Map(), trimmedAnchors = /* @__PURE__ */ new Set();
724
+ let count = 0;
725
+ for (let at = first; at < last; at++) {
726
+ const current = all[at];
727
+ if (!opportunity(current, all[at + 1], alignment === "distribute")) continue;
728
+ count++;
729
+ if (current.boundary !== void 0) {
730
+ let gaps = textGaps.get(current.piece);
731
+ if (!gaps) textGaps.set(current.piece, gaps = /* @__PURE__ */ new Map());
732
+ gaps.set(current.boundary, (gaps.get(current.boundary) ?? 0) + 1);
733
+ } else atomicGaps.set(current.piece, (atomicGaps.get(current.piece) ?? 0) + 1);
734
+ }
735
+ for (let at = last + 1; at < all.length; at++) {
736
+ const unit = all[at];
737
+ if (unit.boundary !== void 0 && !trims.has(unit.piece)) trims.set(unit.piece, unit.boundary - 1);
738
+ else if (unit.boundary === void 0) trimmedAnchors.add(unit.piece);
739
+ }
740
+ const plans = /* @__PURE__ */ new Map(), original = line.pieces.map((piece, index) => trimmedAnchors.has(index) && piece.kind === "anchor" ? {
741
+ ...piece,
742
+ advanceWidth: 0
743
+ } : piece);
744
+ for (const [index, piece] of original.entries()) if (piece.kind === "text" && (textGaps.has(index) || trims.has(index))) plans.set(index, naturalText(piece, textGaps.get(index) ?? /* @__PURE__ */ new Map(), trims.get(index), measurer));
745
+ const naturalWidth = original.reduce((total, piece, index) => total + (plans.get(index)?.width ?? width(piece)), 0), free = line.availableWidth - naturalWidth;
746
+ if (!Number.isFinite(free) || free < 0) return line;
747
+ const step = count ? free / count : 0, pieces = original.map((piece, index) => {
748
+ const plan = plans.get(index);
749
+ if (piece.kind !== "text" || !plan) return piece;
750
+ const gaps = textGaps.get(index), extra = sumBy([...gaps?.values() ?? []], (value) => value) * step;
751
+ let addedGaps = 0;
752
+ const x = plan.x.map((value, boundary) => {
753
+ addedGaps += gaps?.get(boundary) ?? 0;
754
+ const added = addedGaps * step;
755
+ return value + (piece.direction === "rtl" ? extra - added : added);
756
+ });
757
+ return {
758
+ ...piece,
759
+ metrics: {
760
+ ...piece.metrics,
761
+ advanceWidth: plan.width + extra,
762
+ caretMap: {
763
+ offsets: piece.metrics.caretMap.offsets,
764
+ x
765
+ }
766
+ },
767
+ ...plan.starts.length > 1 ? { expansion: {
768
+ offsets: plan.starts.map((boundary) => displayOffset(piece, boundary)),
769
+ x: plan.starts.map((boundary) => x[boundary])
770
+ } } : {}
771
+ };
772
+ });
773
+ let alignedPieceOffsets;
774
+ if (atomicGaps.size) {
775
+ alignedPieceOffsets = [];
776
+ let advance = 0;
777
+ for (const [index, piece] of pieces.entries()) {
778
+ alignedPieceOffsets.push(advance);
779
+ advance += width(piece) + (atomicGaps.get(index) ?? 0) * step;
780
+ }
781
+ }
782
+ return {
783
+ ...line,
784
+ pieces,
785
+ width: count ? line.availableWidth : naturalWidth,
786
+ ...alignedPieceOffsets ? { alignedPieceOffsets } : {},
787
+ ...!count && alignment === "distribute" ? { alignmentOffsetPx: free / 2 } : {}
788
+ };
789
+ }
441
790
  // src/layout/engine/atoms/control-decoration.ts
442
791
  /** 在内容度量外分配括号空间;实际填写文字仍保留原值,不把括号混入编辑地址。 */
443
792
  function measureDecoratedControl(presentation, availableWidth, measurer, calculate) {
793
+ if (presentation.signatureGallery?.items.length && presentation.preferredSizePx) presentation = {
794
+ ...presentation,
795
+ signatureGallery: {
796
+ ...presentation.signatureGallery,
797
+ imageSize: presentation.signatureGallery.imageSize ?? presentation.preferredSizePx
798
+ },
799
+ preferredSizePx: void 0
800
+ };
444
801
  const decoration = presentation.decoration;
445
802
  if (!decoration) return calculate(presentation, availableWidth);
446
803
  const style = {
@@ -480,6 +837,15 @@ function measureDecoratedControl(presentation, availableWidth, measurer, calcula
480
837
  baseline: control.layout.texts.at(-1)?.baseline ?? control.baseline,
481
838
  width: right - 3
482
839
  });
840
+ const bracketFrames = presentation.signatureGallery?.items.length ? bracketTexts.map((text) => ({
841
+ side: text.text === "[" ? "start" : "end",
842
+ frame: {
843
+ x: text.x,
844
+ y: 0,
845
+ width: text.width,
846
+ height: control.height
847
+ }
848
+ })) : void 0;
483
849
  return {
484
850
  ...control,
485
851
  width: control.width + left + right,
@@ -512,7 +878,7 @@ function measureDecoratedControl(presentation, availableWidth, measurer, calcula
512
878
  x: image.frame.x + left
513
879
  }
514
880
  })) } : {},
515
- ...bracketTexts.length ? { bracketTexts } : {}
881
+ ...bracketFrames?.length ? { bracketFrames } : bracketTexts.length ? { bracketTexts } : {}
516
882
  }
517
883
  };
518
884
  }
@@ -658,94 +1024,217 @@ function measureSeal(presentation, measurer, assets) {
658
1024
  }
659
1025
  };
660
1026
  }
1027
+ // src/shared/signature-graphic.ts
1028
+ /** 与旧版 68b981c 的姓名字号、两行拆分、8px 留白和日期栏保持一致。 */
1029
+ function signatureGraphic(name, date, appearance, measure) {
1030
+ const fontSize = Array.from(name).length >= 6 ? 16 : 26;
1031
+ const height = appearance.vertical ? appearance.width ?? 120 : appearance.height ?? 68;
1032
+ const texts = [];
1033
+ const add = (text, x, y, size, weight, max = Infinity) => {
1034
+ const naturalWidth = measure(text, size, weight);
1035
+ texts.push({
1036
+ text,
1037
+ x,
1038
+ y,
1039
+ fontSize: size,
1040
+ fontWeight: weight,
1041
+ naturalWidth,
1042
+ width: Math.min(max, naturalWidth)
1043
+ });
1044
+ };
1045
+ if (appearance.vertical) {
1046
+ const width = appearance.height ?? 68;
1047
+ const characters = Array.from(name), rowHeight = fontSize * 1.15;
1048
+ const rows = Math.max(1, Math.floor(height * .84 / rowHeight));
1049
+ const columns = Math.max(1, Math.ceil(characters.length / rows));
1050
+ const columnWidth = Math.min(fontSize * 1.15, width * .8 / columns);
1051
+ const left = (width - columns * columnWidth) / 2;
1052
+ for (let column = 0; column < columns; column++) {
1053
+ const charactersInColumn = characters.slice(column * rows, (column + 1) * rows);
1054
+ const top = (height - charactersInColumn.length * rowHeight) / 2;
1055
+ for (const [row, character] of charactersInColumn.entries()) {
1056
+ const actualWidth = Math.min(columnWidth, measure(character, fontSize, 600));
1057
+ add(character, left + (columns - column - .5) * columnWidth - actualWidth / 2, top + (row + .5) * rowHeight, fontSize, 600, columnWidth);
1058
+ }
1059
+ }
1060
+ return {
1061
+ width,
1062
+ height,
1063
+ texts
1064
+ };
1065
+ }
1066
+ const nameWidth = (text) => measure(text, fontSize, 600);
1067
+ const ellipsis = (text, max, size, weight) => {
1068
+ if (measure(text, size, weight) <= max) return text;
1069
+ let result = "";
1070
+ for (const character of Array.from(text)) {
1071
+ if (measure(result + character + "…", size, weight) > max) break;
1072
+ result += character;
1073
+ }
1074
+ return result + "…";
1075
+ };
1076
+ let lines, metaLines = [];
1077
+ if (appearance.fallback === "name-and-date") {
1078
+ const max = fontSize === 16 ? Math.min(nameWidth(name), 120) : nameWidth(name);
1079
+ const remaining = Array.from(name);
1080
+ lines = [];
1081
+ for (let index = 0; index < 2 && remaining.length; index++) {
1082
+ let line = "";
1083
+ while (remaining.length && nameWidth(line + remaining[0]) <= max) line += remaining.shift();
1084
+ if (!line) line = remaining.shift();
1085
+ if (index === 1 && remaining.length) line = ellipsis(line + remaining.join(""), max, fontSize, 600);
1086
+ lines.push(line);
1087
+ }
1088
+ metaLines = [`电子签名:${name}`, ...date ? [`日期:${date}`] : []];
1089
+ } else {
1090
+ const characters = Array.from(name);
1091
+ let split = Math.ceil(characters.length / 2);
1092
+ while (split > 1 && nameWidth(characters.slice(0, split).join("")) > 344) split--;
1093
+ lines = characters.length < 6 ? [name] : [characters.slice(0, split).join(""), ellipsis(characters.slice(split).join(""), 344, fontSize, 600)];
1094
+ }
1095
+ const nameMax = Math.max(0, ...lines.map(nameWidth));
1096
+ const metaNatural = Math.max(0, ...metaLines.map((line) => measure(line, 12, 400)));
1097
+ const metaMax = Math.min(360, Math.ceil(16 + nameMax + 8 + metaNatural)) - 16 - nameMax - 8;
1098
+ metaLines = metaLines.map((line) => ellipsis(line, metaMax, 12, 400));
1099
+ const metaWidth = Math.max(0, ...metaLines.map((line) => measure(line, 12, 400)));
1100
+ const width = Math.min(360, Math.ceil(16 + nameMax + (metaLines.length ? 8 + metaWidth : 0)));
1101
+ const nameLineHeight = fontSize * 1.2;
1102
+ lines.forEach((line, index) => add(line, 8, (height - lines.length * nameLineHeight) / 2 + (index + .5) * nameLineHeight, fontSize, 600));
1103
+ metaLines.forEach((line, index) => add(line, 8 + nameMax + 8, (height - metaLines.length * 16.2) / 2 + (index + .5) * 16.2, 12, 400));
1104
+ return {
1105
+ width,
1106
+ height,
1107
+ texts
1108
+ };
1109
+ }
1110
+ /** 被动 SVG 来源可供预览和第三方消费者使用;正式画布直接绘制同一份几何。 */
1111
+ function signatureGraphicUrl(graphic) {
1112
+ const escape = (value) => value.replace(/[&<>"']/g, (character) => ({
1113
+ "&": "&amp;",
1114
+ "<": "&lt;",
1115
+ ">": "&gt;",
1116
+ "\"": "&quot;",
1117
+ "'": "&apos;"
1118
+ })[character]);
1119
+ const texts = graphic.texts.map((text) => `<text x="${text.x}" y="${text.y}" font-size="${text.fontSize}" font-weight="${text.fontWeight}"${text.width < text.naturalWidth ? ` textLength="${text.width}" lengthAdjust="spacingAndGlyphs"` : ""}>${escape(text.text)}</text>`).join("");
1120
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="${graphic.width}" height="${graphic.height}" viewBox="0 0 ${graphic.width} ${graphic.height}"><rect width="100%" height="100%" fill="white"/><g fill="black" font-family="Arial, sans-serif" dominant-baseline="central">${texts}</g></svg>`)}`;
1121
+ }
661
1122
  // src/layout/engine/atoms/signatures.ts
662
- /** @file 签名组合的纯同步排版,图片、姓名和时间最终都落入现有绘制描述。 */
663
- /** 多人签名逐份组合并按可用宽度换行,文字按行度量,不保存字符对象。 */
1123
+ /** @file 签名沿旧版图片尺寸及日期几何排版;内部姓名图形仍由新绘制协议承载。 */
1124
+ /** 多人签名按整张图与跟随日期共同换行、分页,不把姓名降级成普通字段文字。 */
664
1125
  function measureSignatures(presentation, availableWidth, measurer, assets) {
665
- const gallery = presentation.signatureGallery, style = presentation.style;
1126
+ const gallery = presentation.signatureGallery;
1127
+ const style = {
1128
+ fontFamily: "Arial",
1129
+ fontSizePx: presentation.style.fontSizePx,
1130
+ fontWeight: 400,
1131
+ fontStyle: "normal",
1132
+ letterSpacingPx: 0,
1133
+ color: "#000000",
1134
+ kerning: "normal"
1135
+ };
666
1136
  const metrics = measurer.measure({
667
1137
  text: "",
668
1138
  style,
669
1139
  direction: "ltr"
670
1140
  });
671
- const lineHeight = (metrics.ascent + metrics.descent) * 1.2, padding = presentation.appearance === "text" ? 0 : 4;
672
- const width = Math.max(1, Math.min(availableWidth, presentation.preferredSizePx?.width ?? availableWidth)), inner = Math.max(1, width - padding * 2);
673
1141
  const texts = [], images = [], rowFlow = [];
1142
+ const configured = gallery.imageSize ?? presentation.preferredSizePx;
1143
+ const inner = Math.max(1, availableWidth);
674
1144
  let x = 0, y = 0, rowHeight = 0, usedWidth = 0, rowStart = 0;
675
- /** 文字快照只记录完整行与推进宽度,渲染端不再做签名布局。 */
676
- const addText = (text, left, top, textWidth) => {
677
- const lines = wrapText(text, Math.max(1, textWidth), presentation, measurer);
678
- lines.forEach((line, index) => texts.push({
679
- text: line,
680
- x: padding + left,
681
- baseline: padding + top + index * lineHeight + metrics.ascent,
682
- width: measurer.measureWidth({
683
- text: line,
684
- style,
685
- direction: "ltr"
686
- })
687
- }));
688
- return lines.length * lineHeight;
689
- };
1145
+ const finishRow = () => rowFlow.push({
1146
+ start: rowStart,
1147
+ end: y + rowHeight,
1148
+ textTo: texts.length,
1149
+ markerTo: 0,
1150
+ imageTo: images.length
1151
+ });
690
1152
  for (const item of gallery.items) {
691
- const imageWidth = Math.min(inner, item.vertical ? 68 : 120), imageHeight = item.vertical ? 120 : 68;
692
- const timeNatural = item.timeText ? measurer.measureWidth({
1153
+ const graphic = item.image ? void 0 : signatureGraphic(item.text, item.fallbackDate ?? "", {
1154
+ ...configured,
1155
+ vertical: item.vertical,
1156
+ fallback: item.fallback
1157
+ }, (text, size, weight) => measurer.measureWidth({
1158
+ text,
1159
+ direction: "ltr",
1160
+ style: {
1161
+ fontFamily: "Arial",
1162
+ fontSizePx: size,
1163
+ fontWeight: weight,
1164
+ fontStyle: "normal",
1165
+ letterSpacingPx: 0,
1166
+ kerning: "normal"
1167
+ }
1168
+ }));
1169
+ const naturalWidth = graphic?.width ?? (item.vertical ? configured?.height ?? 68 : configured?.width ?? 120);
1170
+ const naturalHeight = graphic?.height ?? (item.vertical ? configured?.width ?? 120 : configured?.height ?? 68);
1171
+ const timeWidth = item.timeText ? measurer.measureWidth({
693
1172
  text: item.timeText,
694
1173
  style,
695
1174
  direction: "ltr"
696
1175
  }) : 0;
697
- const textNatural = measurer.measureWidth({
698
- text: item.text,
699
- style,
700
- direction: "ltr"
701
- });
702
- const beside = gallery.timePlacement === "inline" && !!item.timeText && inner >= (item.image ? imageWidth : Math.min(textNatural, inner)) + 24;
703
- const primaryWidth = item.image ? imageWidth : Math.max(1, Math.min(inner, textNatural));
704
- const itemWidth = Math.min(inner, beside ? primaryWidth + 4 + timeNatural : Math.max(primaryWidth, timeNatural));
1176
+ const timeHeight = item.timeText ? metrics.ascent + metrics.descent : 0;
1177
+ const beside = gallery.timePlacement === "inline" && !!item.timeText;
1178
+ const gap = item.timeText ? 2 : 0;
1179
+ const primaryWidth = naturalWidth, primaryHeight = naturalHeight;
1180
+ const itemWidth = beside ? primaryWidth + gap + timeWidth : Math.max(primaryWidth, timeWidth);
1181
+ const itemHeight = beside ? Math.max(primaryHeight, timeHeight) : primaryHeight + gap + timeHeight;
705
1182
  if (x && x + itemWidth > inner) {
706
- rowFlow.push({
707
- start: rowStart,
708
- end: padding + y + rowHeight,
709
- textTo: texts.length,
710
- markerTo: 0,
711
- imageTo: images.length
712
- });
1183
+ finishRow();
713
1184
  x = 0;
714
- y += rowHeight + 8;
715
- rowStart = padding + y;
1185
+ y += rowHeight;
1186
+ rowStart = y;
716
1187
  rowHeight = 0;
717
1188
  }
718
- let itemHeight;
719
- if (item.image) {
720
- images.push(imageSnapshot(item.image, assets, {
721
- x: padding + x,
722
- y: padding + y,
723
- width: primaryWidth,
724
- height: imageHeight
725
- }, "contain"));
726
- itemHeight = imageHeight;
727
- } else itemHeight = addText(item.text, x, y, primaryWidth);
728
- if (item.timeText) {
729
- if (beside) itemHeight = Math.max(itemHeight, addText(item.timeText, x + primaryWidth + 4, y, itemWidth - primaryWidth - 4));
730
- else itemHeight += 4 + addText(item.timeText, x, y + itemHeight + 4, itemWidth);
731
- }
1189
+ const frame = {
1190
+ x: x + (beside ? 0 : Math.max(0, (timeWidth - primaryWidth) / 2)),
1191
+ y,
1192
+ width: primaryWidth,
1193
+ height: primaryHeight
1194
+ };
1195
+ images.push(graphic ? {
1196
+ source: {
1197
+ kind: "url",
1198
+ url: signatureGraphicUrl(graphic)
1199
+ },
1200
+ alt: item.text,
1201
+ state: "ready",
1202
+ revision: 0,
1203
+ fit: "contain",
1204
+ frame,
1205
+ graphic
1206
+ } : {
1207
+ ...imageSnapshot(item.image, assets, frame, "contain"),
1208
+ placeholder: { backgroundColor: "#f3f3f3" }
1209
+ });
1210
+ if (item.timeText) texts.push({
1211
+ text: item.timeText,
1212
+ imageDecoration: {
1213
+ imageIndex: images.length - 1,
1214
+ placement: beside ? "right" : "bottom",
1215
+ gapPx: gap
1216
+ },
1217
+ style,
1218
+ fontMetrics: {
1219
+ ascent: metrics.ascent,
1220
+ descent: metrics.descent
1221
+ },
1222
+ x: x + (beside ? primaryWidth + gap : Math.max(0, (primaryWidth - timeWidth) / 2)),
1223
+ baseline: y + (beside ? (primaryHeight - timeHeight) / 2 : primaryHeight + gap) + metrics.ascent,
1224
+ width: timeWidth
1225
+ });
732
1226
  usedWidth = Math.max(usedWidth, x + itemWidth);
733
1227
  rowHeight = Math.max(rowHeight, itemHeight);
734
- x += itemWidth + 8;
1228
+ x += itemWidth;
735
1229
  }
736
- const height = Math.max(presentation.preferredSizePx?.height ?? 0, padding * 2 + y + rowHeight);
737
- rowFlow.push({
738
- start: rowStart,
739
- end: height,
740
- textTo: texts.length,
741
- markerTo: 0,
742
- imageTo: images.length
743
- });
1230
+ finishRow();
1231
+ const height = y + rowHeight;
744
1232
  return {
1233
+ preserveImageSize: true,
745
1234
  rowFlow,
746
- width: presentation.preferredSizePx ? width : Math.min(width, Math.max(1, usedWidth + padding * 2)),
1235
+ width: Math.max(1, usedWidth),
747
1236
  height,
748
- baseline: Math.min(height, padding + metrics.ascent),
1237
+ baseline: Math.max(metrics.ascent, rowHeight - metrics.descent),
749
1238
  layout: {
750
1239
  appearance: presentation.appearance,
751
1240
  design: presentation.design,
@@ -760,53 +1249,6 @@ function measureSignatures(presentation, availableWidth, measurer, assets) {
760
1249
  }
761
1250
  // src/layout/engine/atoms/field-control.ts
762
1251
  /** @file 纯同步控件度量,控件作为整体参与正文断行,内部文字只生成行片段。 */
763
- /** 字素算法只持有分割器,不保留字段或文字。 */
764
- var segments = new Intl.Segmenter(void 0, { granularity: "grapheme" });
765
- /** 字段内按合法字素换行,空行保留;不创建字符节点或内部模型地址。 */
766
- function wrapTextRanges(text, width, presentation, measurer) {
767
- const lines = [];
768
- for (const match of text.matchAll(/([^\r\n]*)(\r\n|[\r\n]|$)/g)) {
769
- if (match.index === text.length && text.length > 0 && !/[\r\n]$/.test(text)) break;
770
- const part = match[1];
771
- const source = match.index;
772
- if (!part.length) {
773
- lines.push({
774
- text: "",
775
- from: source,
776
- to: source
777
- });
778
- continue;
779
- }
780
- const boundaries = [0, ...Array.from(segments.segment(part), (item) => item.index + item.segment.length)];
781
- let begin = 0;
782
- while (begin < boundaries.length - 1) {
783
- let low = begin, high = boundaries.length - 1;
784
- while (low < high) {
785
- const middle = Math.ceil((low + high) / 2);
786
- const advance = measurer.measureWidth({
787
- text: part.slice(boundaries[begin], boundaries[middle]),
788
- style: presentation.style,
789
- direction: "ltr"
790
- });
791
- if (!Number.isFinite(advance) || advance < 0) throw new Error("字段文字度量返回无效宽度");
792
- if (advance <= width) low = middle;
793
- else high = middle - 1;
794
- }
795
- const end = Math.max(begin + 1, low);
796
- lines.push({
797
- text: part.slice(boundaries[begin], boundaries[end]),
798
- from: source + boundaries[begin],
799
- to: source + boundaries[end]
800
- });
801
- begin = end;
802
- }
803
- }
804
- return lines;
805
- }
806
- /** 通用标签继续使用相同断行算法,字段额外保留原文区间供活动输入定位。 */
807
- function wrapText(text, width, presentation, measurer) {
808
- return wrapTextRanges(text, width, presentation, measurer).map((line) => line.text);
809
- }
810
1252
  /** 控件尺寸和所有内部坐标在排版时决定,绘制阶段不读取业务数据或重新断行。 */
811
1253
  function measureFieldControl(presentation, availableWidth, measurer, assets, cache) {
812
1254
  return cache ? cache.measure(presentation, availableWidth, assets, (snapshot) => measureFieldControlFresh(presentation, availableWidth, measurer, snapshot)) : measureFieldControlFresh(presentation, availableWidth, measurer, assets);
@@ -826,7 +1268,7 @@ function measureFieldControlFresh(presentation, availableWidth, measurer, assets
826
1268
  ...control.layout,
827
1269
  texts: control.layout.texts.map((text) => ({
828
1270
  ...text,
829
- fontMetrics: {
1271
+ fontMetrics: text.fontMetrics ?? {
830
1272
  ascent,
831
1273
  descent
832
1274
  }
@@ -1046,298 +1488,6 @@ function measureFieldContent(presentation, availableWidth, measurer, assets) {
1046
1488
  }
1047
1489
  };
1048
1490
  }
1049
- // src/layout/engine/atoms/diagonal.ts
1050
- /** @file 斜线表头的纯几何;两栏/四种三栏顶点共用最终尺寸与分区裁剪。 */
1051
- /** 整格斜线只用于唯一图形的单元格,不挤占或伸缩其他正文。 */
1052
- function isDiagonalCell(blocks) {
1053
- const block = blocks.length === 1 ? blocks[0] : void 0;
1054
- if (!block || typeof block !== "object" || !("kind" in block) || block.kind !== "paragraph" || !("content" in block) || !Array.isArray(block.content)) return false;
1055
- const content = block.content, node = content.length === 1 ? content[0] : void 0;
1056
- return !!node && typeof node === "object" && "kind" in node && node.kind === "pageWidget" && "widget" in node && node.widget === "diagonal";
1057
- }
1058
- /** 整格图形在行高最终分配后取真实尺寸,不把配置尺寸强行变成行高。 */
1059
- function fillCellDiagonal(blocks, width, height) {
1060
- const block = blocks.length === 1 ? blocks[0] : void 0, line = block?.kind === "paragraph" && block.lines.length === 1 ? block.lines[0] : void 0, piece = line?.pieces.length === 1 ? line.pieces[0] : void 0;
1061
- if (!block || block.kind !== "paragraph" || !line || piece?.kind !== "pageWidget" || piece.widget.content.kind !== "diagonal" || !piece.widget.content.fillCell) return blocks;
1062
- const widget = {
1063
- ...piece.widget,
1064
- width,
1065
- height,
1066
- baseline: height
1067
- };
1068
- return [{
1069
- ...block,
1070
- width,
1071
- height,
1072
- lines: [{
1073
- ...line,
1074
- width,
1075
- availableWidth: width,
1076
- height,
1077
- baseline: height,
1078
- indent: 0,
1079
- pieces: [{
1080
- ...piece,
1081
- widget
1082
- }]
1083
- }]
1084
- }];
1085
- }
1086
- /** 镜像角点名称与几何使用同一规则,避免文字分区与线条错位。 */
1087
- function cornerName(x, y) {
1088
- return `${y ? "bottom" : "top"}-${x ? "right" : "left"}`;
1089
- }
1090
- /** 按当前真实尺寸一次性计算线、文字和对应分区,绘制不重新解释配置。 */
1091
- function layoutDiagonal(content, width, height, paintStyleKey, paint, measurer) {
1092
- const w = width, h = height, three = content.columns === 3, flipX = three ? content.vertex.endsWith("right") : content.direction === "backward", flipY = three && content.vertex.startsWith("bottom");
1093
- /** 线条与分区顶点都从同一坐标变换得到。 */
1094
- function point(x, y) {
1095
- return {
1096
- x: flipX ? w - x : x,
1097
- y: flipY ? h - y : y
1098
- };
1099
- }
1100
- const origin = point(0, 0), endA = point(w, three ? h * .4 : h), endB = point(w * .4, h);
1101
- /** 统一的已解析线条,不借用旧 ImageWidget。 */
1102
- function line(end) {
1103
- return {
1104
- kind: "line",
1105
- x1: origin.x,
1106
- y1: origin.y,
1107
- x2: end.x,
1108
- y2: end.y,
1109
- widthPx: 1,
1110
- color: "#808080",
1111
- style: "solid"
1112
- };
1113
- }
1114
- const regions = /* @__PURE__ */ new Map();
1115
- regions.set(cornerName(!flipX, flipY), [
1116
- origin,
1117
- point(w, 0),
1118
- endA
1119
- ]);
1120
- if (three) {
1121
- regions.set(cornerName(!flipX, !flipY), [
1122
- origin,
1123
- endA,
1124
- point(w, h),
1125
- endB
1126
- ]);
1127
- regions.set(cornerName(flipX, !flipY), [
1128
- origin,
1129
- endB,
1130
- point(0, h)
1131
- ]);
1132
- } else regions.set(cornerName(flipX, !flipY), [
1133
- origin,
1134
- endA,
1135
- point(0, h)
1136
- ]);
1137
- const corners = three ? {
1138
- "top-left": [
1139
- "top-right",
1140
- "bottom-right",
1141
- "bottom-left"
1142
- ],
1143
- "top-right": [
1144
- "top-left",
1145
- "bottom-left",
1146
- "bottom-right"
1147
- ],
1148
- "bottom-left": [
1149
- "top-left",
1150
- "top-right",
1151
- "bottom-right"
1152
- ],
1153
- "bottom-right": [
1154
- "top-right",
1155
- "top-left",
1156
- "bottom-left"
1157
- ]
1158
- }[content.vertex] : flipX ? ["top-left", "bottom-right"] : ["top-right", "bottom-left"];
1159
- const metrics = measurer.measure({
1160
- text: "",
1161
- style: paint,
1162
- direction: "ltr"
1163
- }), lineHeight = (metrics.ascent + metrics.descent) * 1.2, boxWidth = Math.max(1, Math.min(w * .5, w - 8));
1164
- return {
1165
- kind: "diagonal",
1166
- paintStyleKey,
1167
- lines: three ? [line(endA), line(endB)] : [line(endA)],
1168
- slots: corners.map((corner, index) => {
1169
- const rows = wrapText(content.labels[three ? index : index === 0 ? 0 : 2] ?? "", boxWidth, { style: paint }, measurer), right = corner.endsWith("right"), x = right ? w - 4 - boxWidth : 4, y = corner.startsWith("bottom") ? Math.max(4, h - 4 - rows.length * lineHeight) : 4;
1170
- return {
1171
- clip: regions.get(corner),
1172
- texts: rows.map((text, row) => {
1173
- const advance = measurer.measureWidth({
1174
- text,
1175
- style: paint,
1176
- direction: "ltr"
1177
- });
1178
- return {
1179
- text,
1180
- width: advance,
1181
- x: x + (right ? Math.max(0, boxWidth - advance) : 0),
1182
- baseline: y + metrics.ascent + row * lineHeight
1183
- };
1184
- })
1185
- };
1186
- })
1187
- };
1188
- }
1189
- // src/layout/engine/paragraph/justify-line.ts
1190
- /** @file 断行后的间距扩展;源字素、原子尺寸和结果片段保持,绘制与停靠共用最终几何。 */
1191
- /** 只扩展普通及全角空白,不把不换行空格当作可丢弃的尾随空白。 */
1192
- var space = (text) => /^[ \t\u3000]+$/u.test(text);
1193
- /** 东亚文本提供字间机会;连写脚本仅使用词间空白,不切断连接。 */
1194
- var eastAsian = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
1195
- /** 当前可识别的连写脚本不能被分散对齐拆出字内空隙。 */
1196
- var cursive = /[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Nko}\p{Script=Mandaic}\p{Script=Mongolian}\p{Script=Phags_Pa}]/u;
1197
- /** 一行的自然片段推进,不把对齐间隔写进控件或图片尺寸。 */
1198
- function width(piece) {
1199
- return piece.kind === "text" ? piece.metrics.advanceWidth : piece.kind === "control" ? piece.control.width : piece.kind === "image" ? piece.image.frame.width : piece.kind === "pageWidget" ? piece.widget.width : piece.advanceWidth ?? 0;
1200
- }
1201
- /** 普通文字直接借用源相对偏移,只有长度变换才使用额外的展示映射。 */
1202
- function displayOffset(piece, boundary) {
1203
- return piece.displayOffsets?.[boundary] ?? piece.metrics.caretMap.offsets[boundary] - piece.source.from;
1204
- }
1205
- /** 收集临时排版单位,段落内零宽锚点不引入额外分散机会。 */
1206
- function units$2(line) {
1207
- const result = [];
1208
- for (const [index, piece] of line.pieces.entries()) if (piece.kind === "text") for (let at = 1; at < piece.metrics.caretMap.offsets.length; at++) {
1209
- const text = piece.text.slice(displayOffset(piece, at - 1), displayOffset(piece, at));
1210
- if (text) result.push({
1211
- piece: index,
1212
- boundary: at,
1213
- text
1214
- });
1215
- }
1216
- else if (piece.kind === "anchor") {
1217
- if (width(piece)) result.push({
1218
- piece: index,
1219
- text: " "
1220
- });
1221
- } else result.push({
1222
- piece: index,
1223
- text: ""
1224
- });
1225
- return result;
1226
- }
1227
- /** 不在源字素内部、连接控制符或开闭标点禁止边界扩展;样式节点边界不改变机会。 */
1228
- function opportunity(a, b, distribute) {
1229
- if (/[\u00a0\u202f\u2060\ufeff]/u.test(a.text + b.text)) return false;
1230
- if ("([{([{《〈「『【〔〖“‘".includes(a.text) || ")]})]}》〉」』】〕〗”’、。,;:!?,.!?;:".includes(b.text)) return false;
1231
- if (a.text === " " || a.text === " ") return true;
1232
- if (space(a.text) || space(b.text)) return distribute;
1233
- if (cursive.test(a.text) || cursive.test(b.text)) return false;
1234
- return distribute || eastAsian.test(a.text) || eastAsian.test(b.text);
1235
- }
1236
- /** 按最终绘制段度量自然宽度,并把展示偏移映射回原合法源边界;不持有新文字节点。 */
1237
- function naturalText(piece, gaps, trim, measurer) {
1238
- const count = piece.metrics.caretMap.offsets.length - 1, cuts = sortBy$2(uniq([
1239
- 0,
1240
- ...gaps.keys(),
1241
- count
1242
- ]), (value) => value), advances = [];
1243
- let advance = 0;
1244
- for (let index = 0; index < cuts.length - 1; index++) {
1245
- const from = cuts[index], to = cuts[index + 1], start = displayOffset(piece, from), measurement = measurer.measure({
1246
- text: piece.text.slice(start, displayOffset(piece, to)),
1247
- style: piece.paint,
1248
- direction: piece.direction
1249
- });
1250
- if (!Number.isFinite(measurement.advanceWidth) || measurement.advanceWidth < 0) throw new Error("对齐度量返回无效推进宽度");
1251
- for (let boundary = from; boundary <= to; boundary++) {
1252
- const offset = displayOffset(piece, boundary) - start, at = sortedIndex(measurement.caretMap.offsets, offset);
1253
- if (measurement.caretMap.offsets[at] !== offset) throw new Error("对齐度量缺少合法展示边界");
1254
- advances[boundary] = advance + (piece.direction === "rtl" ? measurement.advanceWidth - measurement.caretMap.x[at] : measurement.caretMap.x[at]);
1255
- }
1256
- advance += measurement.advanceWidth;
1257
- }
1258
- const naturalWidth = trim === void 0 ? advance : advances[trim];
1259
- return {
1260
- width: naturalWidth,
1261
- x: advances.map((value) => piece.direction === "rtl" ? naturalWidth - Math.min(value, naturalWidth) : Math.min(value, naturalWidth)),
1262
- starts: cuts.slice(0, -1)
1263
- };
1264
- }
1265
- /** 普通两端对齐只处理软换行;分散对齐也处理段末,无法扩展时居中,空白行原样保留。 */
1266
- function justifyFlowLine(line, alignment, measurer) {
1267
- if (alignment !== "justify" && alignment !== "distribute") return line;
1268
- if (alignment === "justify" && line.ending !== "wrap") return line;
1269
- const all = units$2(line);
1270
- let first = 0, last = all.length - 1;
1271
- while (first <= last && space(all[first].text)) first++;
1272
- while (last >= first && space(all[last].text)) last--;
1273
- if (first > last) return line;
1274
- const textGaps = /* @__PURE__ */ new Map(), atomicGaps = /* @__PURE__ */ new Map(), trims = /* @__PURE__ */ new Map(), trimmedAnchors = /* @__PURE__ */ new Set();
1275
- let count = 0;
1276
- for (let at = first; at < last; at++) {
1277
- const current = all[at];
1278
- if (!opportunity(current, all[at + 1], alignment === "distribute")) continue;
1279
- count++;
1280
- if (current.boundary !== void 0) {
1281
- let gaps = textGaps.get(current.piece);
1282
- if (!gaps) textGaps.set(current.piece, gaps = /* @__PURE__ */ new Map());
1283
- gaps.set(current.boundary, (gaps.get(current.boundary) ?? 0) + 1);
1284
- } else atomicGaps.set(current.piece, (atomicGaps.get(current.piece) ?? 0) + 1);
1285
- }
1286
- for (let at = last + 1; at < all.length; at++) {
1287
- const unit = all[at];
1288
- if (unit.boundary !== void 0 && !trims.has(unit.piece)) trims.set(unit.piece, unit.boundary - 1);
1289
- else if (unit.boundary === void 0) trimmedAnchors.add(unit.piece);
1290
- }
1291
- const plans = /* @__PURE__ */ new Map(), original = line.pieces.map((piece, index) => trimmedAnchors.has(index) && piece.kind === "anchor" ? {
1292
- ...piece,
1293
- advanceWidth: 0
1294
- } : piece);
1295
- for (const [index, piece] of original.entries()) if (piece.kind === "text" && (textGaps.has(index) || trims.has(index))) plans.set(index, naturalText(piece, textGaps.get(index) ?? /* @__PURE__ */ new Map(), trims.get(index), measurer));
1296
- const naturalWidth = original.reduce((total, piece, index) => total + (plans.get(index)?.width ?? width(piece)), 0), free = line.availableWidth - naturalWidth;
1297
- if (!Number.isFinite(free) || free < 0) return line;
1298
- const step = count ? free / count : 0, pieces = original.map((piece, index) => {
1299
- const plan = plans.get(index);
1300
- if (piece.kind !== "text" || !plan) return piece;
1301
- const gaps = textGaps.get(index), extra = sumBy([...gaps?.values() ?? []], (value) => value) * step;
1302
- let addedGaps = 0;
1303
- const x = plan.x.map((value, boundary) => {
1304
- addedGaps += gaps?.get(boundary) ?? 0;
1305
- const added = addedGaps * step;
1306
- return value + (piece.direction === "rtl" ? extra - added : added);
1307
- });
1308
- return {
1309
- ...piece,
1310
- metrics: {
1311
- ...piece.metrics,
1312
- advanceWidth: plan.width + extra,
1313
- caretMap: {
1314
- offsets: piece.metrics.caretMap.offsets,
1315
- x
1316
- }
1317
- },
1318
- ...plan.starts.length > 1 ? { expansion: {
1319
- offsets: plan.starts.map((boundary) => displayOffset(piece, boundary)),
1320
- x: plan.starts.map((boundary) => x[boundary])
1321
- } } : {}
1322
- };
1323
- });
1324
- let alignedPieceOffsets;
1325
- if (atomicGaps.size) {
1326
- alignedPieceOffsets = [];
1327
- let advance = 0;
1328
- for (const [index, piece] of pieces.entries()) {
1329
- alignedPieceOffsets.push(advance);
1330
- advance += width(piece) + (atomicGaps.get(index) ?? 0) * step;
1331
- }
1332
- }
1333
- return {
1334
- ...line,
1335
- pieces,
1336
- width: count ? line.availableWidth : naturalWidth,
1337
- ...alignedPieceOffsets ? { alignedPieceOffsets } : {},
1338
- ...!count && alignment === "distribute" ? { alignmentOffsetPx: free / 2 } : {}
1339
- };
1340
- }
1341
1491
  // src/layout/engine/atoms/code-widgets.ts
1342
1492
  /** @file 条码的最终占位与静区几何;不执行公式或编码,不拉伸二维码模块。 */
1343
1493
  /** 计算带静区的图形框。二维矩阵等比利用可用空间,一维条码沿用整数模块。 */
@@ -1590,6 +1740,7 @@ function prepareParagraph(paragraph, model, defaults, fields) {
1590
1740
  const spans = [];
1591
1741
  const parts = [];
1592
1742
  const pendingFeatures = /* @__PURE__ */ new Set();
1743
+ const joinedBoundaries = /* @__PURE__ */ new Set();
1593
1744
  let length = 0;
1594
1745
  /** 打印字段留白仍是段落空间,不能混入文字源偏移或整组底色。 */
1595
1746
  function appendFieldGap(nodeId, widthPx, side) {
@@ -1665,6 +1816,7 @@ function prepareParagraph(paragraph, model, defaults, fields) {
1665
1816
  appendFieldGap(nodeId, after, "after");
1666
1817
  return;
1667
1818
  }
1819
+ if (pad) joinedBoundaries.add(length);
1668
1820
  spans.push({
1669
1821
  kind: "control",
1670
1822
  start: length,
@@ -1676,6 +1828,7 @@ function prepareParagraph(paragraph, model, defaults, fields) {
1676
1828
  });
1677
1829
  parts.push("");
1678
1830
  length++;
1831
+ if (after) joinedBoundaries.add(length);
1679
1832
  appendFieldGap(nodeId, after, "after");
1680
1833
  }
1681
1834
  const native = [];
@@ -1880,8 +2033,8 @@ function prepareParagraph(paragraph, model, defaults, fields) {
1880
2033
  }
1881
2034
  const textNode = node;
1882
2035
  const effective = model.query.resolveTextStyle(node.id);
1883
- if (effective.smallCaps) pendingFeatures.add("小型大写");
1884
- if (effective.shading?.pattern) pendingFeatures.add("文字图案底纹");
2036
+ if (effective.smallCaps && effective.textCase !== "uppercase" && /\p{Lowercase_Letter}/u.test(node.text)) pendingFeatures.add("小型大写");
2037
+ if (node.text.length && hasTextShadingPattern(effective.shading)) pendingFeatures.add("文字图案底纹");
1885
2038
  let begin = 0;
1886
2039
  let selected;
1887
2040
  const paints = {
@@ -1939,7 +2092,7 @@ function prepareParagraph(paragraph, model, defaults, fields) {
1939
2092
  const opportunities = /* @__PURE__ */ new Set();
1940
2093
  for (const item of graphemes.segment(text)) {
1941
2094
  const end = item.index + item.segment.length;
1942
- boundaries.push(end);
2095
+ if (!joinedBoundaries.has(end)) boundaries.push(end);
1943
2096
  if (/\s|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(item.segment)) opportunities.add(end);
1944
2097
  }
1945
2098
  for (const item of words.segment(text)) opportunities.add(item.index + item.segment.length);
@@ -3525,7 +3678,7 @@ function windowRange(offsets, origin, window) {
3525
3678
  // src/layout/engine/tables/place-table-window.ts
3526
3679
  /** @file 原测量网格的几何窗口,只放置可见行/主格,不改变固定高度或重新排版。 */
3527
3680
  /** 保留完整格中的图片尺寸、垂直对齐和内边距,续页仅平移原坐标并裁剪。 */
3528
- function placeCellWindow(cell, originX, originY, visible, key, context, occurrence) {
3681
+ function placeCellWindow(cell, originX, originY, visible, key, context, placeBlocks, occurrence) {
3529
3682
  const x = originX + cell.padding.left, fullTop = originY + cell.padding.top, top = Math.max(visible.y, fullTop), bottom = Math.min(visible.y + visible.height, originY + cell.height - cell.padding.bottom), contentFrame = {
3530
3683
  x,
3531
3684
  y: Math.min(visible.y + visible.height, Math.max(visible.y, top)),
@@ -3539,7 +3692,7 @@ function placeCellWindow(cell, originX, originY, visible, key, context, occurren
3539
3692
  const fitted = context.fitCell(cell);
3540
3693
  return {
3541
3694
  contentFrame,
3542
- blocks: placeMeasuredBlocks(fitted.blocks, x, fullTop + fitted.shift, context, occurrence, {
3695
+ blocks: placeBlocks(fitted.blocks, x, fullTop + fitted.shift, context, occurrence, {
3543
3696
  top,
3544
3697
  bottom,
3545
3698
  key
@@ -3547,7 +3700,7 @@ function placeCellWindow(cell, originX, originY, visible, key, context, occurren
3547
3700
  };
3548
3701
  }
3549
3702
  /** 嵌套表沿原几何截取,可见跨度按当前窗口重算,合并主格仍使用原实例和来源。 */
3550
- function placeTableWindow(table, originX, y, window, context, occurrence) {
3703
+ function placeTableWindow(table, originX, y, window, context, placeBlocks, occurrence) {
3551
3704
  const free = Math.max(0, table.availableWidth - table.width), x = originX + (table.alignment === "center" ? free / 2 : table.alignment === "right" ? free : table.indent), [from, to] = windowRange(table.rowOffsets, y, window), cellRows = Array.from({ length: to - from }, () => []), rows = table.rows.slice(from, to).map((row, index) => {
3552
3705
  const actual = from + index, top = Math.max(window.top, y + table.rowOffsets[actual]), bottom = Math.min(window.bottom, y + table.rowOffsets[actual + 1]);
3553
3706
  return {
@@ -3575,7 +3728,7 @@ function placeTableWindow(table, originX, y, window, context, occurrence) {
3575
3728
  y: top,
3576
3729
  width: cell.width,
3577
3730
  height: bottom - top
3578
- }, host = Math.max(row, from) - from, content = placeCellWindow(cell, frame.x, fullY, frame, window.key, context, occurrence), instance = occurrence?.(cell.instance) ?? cell.instance;
3731
+ }, host = Math.max(row, from) - from, content = placeCellWindow(cell, frame.x, fullY, frame, window.key, context, placeBlocks, occurrence), instance = occurrence?.(cell.instance) ?? cell.instance;
3579
3732
  cellRows[host].push({
3580
3733
  kind: "cell",
3581
3734
  id: layoutIdentity(context.identityScope, "cell", instance.key, table.nodeId, "window", window.key),
@@ -3797,7 +3950,7 @@ function placeMeasuredBlocks(blocks, x, y, context, occurrence, window) {
3797
3950
  }
3798
3951
  /** 将一段连续显示行放在当前页;跨行主格已由分页组保证完整。 */
3799
3952
  function placeTableRange(table, from, to, originX, y, context, options = {}) {
3800
- if (options.window) return placeTableWindow(table, originX, y, options.window, context, options.occurrence);
3953
+ if (options.window) return placeTableWindow(table, originX, y, options.window, context, placeMeasuredBlocks, options.occurrence);
3801
3954
  const session = context.identityScope, free = Math.max(0, table.availableWidth - table.width);
3802
3955
  const x = originX + (table.alignment === "center" ? free / 2 : table.alignment === "right" ? free : table.indent), baseY = table.rowOffsets[from];
3803
3956
  const rows = [];
@@ -4396,11 +4549,20 @@ function sliceControl(control, from, to) {
4396
4549
  if (!from && to === controlFlowCount(control)) return control;
4397
4550
  const start = controlFlowOffset(control, from), end = controlFlowOffset(control, to, "end"), height = end - start, first = control.rowFlow?.[from - 1], last = control.rowFlow?.[to - 1];
4398
4551
  return {
4552
+ ...control.preserveImageSize ? { preserveImageSize: true } : {},
4399
4553
  width: control.width,
4400
4554
  height,
4401
4555
  baseline: Math.min(height, control.baseline),
4402
4556
  layout: {
4403
4557
  ...control.layout,
4558
+ ...control.layout.bracketFrames ? { bracketFrames: control.layout.bracketFrames.map((bracket) => ({
4559
+ ...bracket,
4560
+ frame: {
4561
+ ...bracket.frame,
4562
+ y: 0,
4563
+ height
4564
+ }
4565
+ })) } : {},
4404
4566
  ...control.layout.textBox ? { textBox: {
4405
4567
  ...control.layout.textBox,
4406
4568
  y: control.layout.textBox.y - start
@@ -4416,7 +4578,11 @@ function sliceControl(control, from, to) {
4416
4578
  })) } : {},
4417
4579
  texts: control.layout.texts.slice(first?.textTo ?? (control.rowFlow ? 0 : from), last?.textTo ?? to).map((text) => ({
4418
4580
  ...text,
4419
- baseline: text.baseline - start
4581
+ baseline: text.baseline - start,
4582
+ ...text.imageDecoration ? { imageDecoration: {
4583
+ ...text.imageDecoration,
4584
+ imageIndex: text.imageDecoration.imageIndex - (first?.imageTo ?? 0)
4585
+ } } : {}
4420
4586
  })),
4421
4587
  markers: control.layout.markers.slice(first?.markerTo ?? 0, last?.markerTo ?? control.layout.markers.length).map((marker) => ({
4422
4588
  ...marker,
@@ -4441,9 +4607,9 @@ function sliceControl(control, from, to) {
4441
4607
  }
4442
4608
  // src/layout/engine/atoms/fit-atomic.ts
4443
4609
  /** @file 完整可用页中的原子图形适配,保留来源、文字字号及条码模块比例。 */
4444
- /** 印章直径有实际业务含义,不按普通附件图片缩放。 */
4610
+ /** 印章及声明保留尺寸的图形不按普通附件图片缩放。 */
4445
4611
  function canFitAtomic(piece) {
4446
- return piece.kind === "image" || piece.kind === "pageWidget" && piece.widget.content.kind === "code" || piece.kind === "control" && !piece.control.layout.seal && !!piece.control.layout.images?.length;
4612
+ return piece.kind === "image" || piece.kind === "pageWidget" && piece.widget.content.kind === "code" || piece.kind === "control" && !piece.control.layout.seal && !piece.control.preserveImageSize && !!piece.control.layout.images?.length;
4447
4613
  }
4448
4614
  /** 图片排压缩后文字和标记的实际占位,不在二分试算中复制数组。 */
4449
4615
  function graphicEnvelope(control, paint, context) {
@@ -4451,14 +4617,29 @@ function graphicEnvelope(control, paint, context) {
4451
4617
  text: "",
4452
4618
  style: paint,
4453
4619
  direction: "ltr"
4454
- }), top = Math.min(...images.map((image) => image.frame.y)), bottom = Math.max(...images.map((image) => image.frame.y + image.frame.height)), band = bottom - top, originalBottom = Math.max(bottom, ...control.layout.texts.map((text) => text.baseline + metrics.descent), ...control.layout.markers.map((marker) => marker.frame.y + marker.frame.height)), padding = Math.min(control.layout.appearance === "text" ? 0 : 4, Math.max(0, control.height - originalBottom));
4455
- /** 只有图形下方的文字随图片压缩上移,旁排日期保留原字号和纵坐标。 */
4620
+ }), top = Math.min(...images.map((image) => image.frame.y)), bottom = Math.max(...images.map((image) => image.frame.y + image.frame.height)), band = bottom - top, originalBottom = Math.max(bottom, ...control.layout.texts.map((text) => text.baseline + (text.fontMetrics ?? metrics).descent), ...control.layout.markers.map((marker) => marker.frame.y + marker.frame.height)), padding = Math.min(control.layout.appearance === "text" ? 0 : 4, Math.max(0, control.height - originalBottom));
4621
+ /** 无显式图片锚点的普通标签只在图形下方随图片上移。 */
4456
4622
  function shift(y, scale) {
4457
4623
  return y >= bottom - 1e-7 ? band * (1 - scale) : 0;
4458
4624
  }
4625
+ /** 日期依赖实际图片框,缩图时重新居中,字形及 2px 跟随间距不缩放。 */
4626
+ function position(text, scale) {
4627
+ const decoration = text.imageDecoration, image = decoration && images[decoration.imageIndex];
4628
+ const font = text.fontMetrics ?? metrics;
4629
+ if (!image || !decoration) return {
4630
+ x: text.x,
4631
+ baseline: text.baseline - shift(text.baseline - font.ascent, scale)
4632
+ };
4633
+ const frame = image.frame, width = frame.width * scale, height = frame.height * scale;
4634
+ const x = frame.x + (frame.width - width) / 2, y = top + (frame.y - top) * scale;
4635
+ return {
4636
+ x: decoration.placement === "right" ? x + width + decoration.gapPx : x + (width - text.width) / 2,
4637
+ baseline: y + (decoration.placement === "right" ? (height - font.ascent - font.descent) / 2 : height + decoration.gapPx) + font.ascent
4638
+ };
4639
+ }
4459
4640
  /** 当前比例下保留全部标签和图形所需的最小高度。 */
4460
4641
  function height(scale) {
4461
- return Math.max(top + band * scale, ...control.layout.texts.map((text) => text.baseline - shift(text.baseline - metrics.ascent, scale) + metrics.descent), ...control.layout.markers.map((marker) => marker.frame.y - shift(marker.frame.y, scale) + marker.frame.height)) + padding;
4642
+ return Math.max(top + band * scale, ...control.layout.texts.map((text) => position(text, scale).baseline + (text.fontMetrics ?? metrics).descent), ...control.layout.markers.map((marker) => marker.frame.y - shift(marker.frame.y, scale) + marker.frame.height)) + padding;
4462
4643
  }
4463
4644
  const minimumScale = Math.min(1, 1 / Math.min(...images.flatMap((image) => [image.frame.width, image.frame.height])));
4464
4645
  return {
@@ -4466,6 +4647,7 @@ function graphicEnvelope(control, paint, context) {
4466
4647
  band,
4467
4648
  shift,
4468
4649
  height,
4650
+ position,
4469
4651
  ascent: metrics.ascent,
4470
4652
  minimumScale
4471
4653
  };
@@ -4491,29 +4673,38 @@ function fitControl(control, paint, maximum, context) {
4491
4673
  else high = scale;
4492
4674
  }
4493
4675
  const scale = low, height = envelope.height(scale);
4676
+ const fittedImages = control.layout.images.map((image) => ({
4677
+ ...image,
4678
+ frame: {
4679
+ ...image.frame,
4680
+ x: image.frame.x + image.frame.width * (1 - scale) / 2,
4681
+ y: envelope.top + (image.frame.y - envelope.top) * scale,
4682
+ width: image.frame.width * scale,
4683
+ height: image.frame.height * scale
4684
+ }
4685
+ }));
4494
4686
  return {
4495
4687
  ...control,
4496
4688
  height,
4497
4689
  baseline: Math.min(control.baseline, height),
4498
4690
  layout: {
4499
4691
  ...control.layout,
4500
- images: control.layout.images.map((image) => ({
4501
- ...image,
4692
+ images: fittedImages,
4693
+ ...control.layout.bracketFrames ? { bracketFrames: control.layout.bracketFrames.map((bracket) => ({
4694
+ ...bracket,
4502
4695
  frame: {
4503
- ...image.frame,
4504
- x: image.frame.x + image.frame.width * (1 - scale) / 2,
4505
- y: envelope.top + (image.frame.y - envelope.top) * scale,
4506
- width: image.frame.width * scale,
4507
- height: image.frame.height * scale
4696
+ ...bracket.frame,
4697
+ y: 0,
4698
+ height
4508
4699
  }
4509
- })),
4700
+ })) } : {},
4510
4701
  ...control.layout.bracketTexts ? { bracketTexts: control.layout.bracketTexts.map((text) => ({
4511
4702
  ...text,
4512
4703
  baseline: text.baseline - envelope.shift(text.baseline - envelope.ascent, scale)
4513
4704
  })) } : {},
4514
4705
  texts: control.layout.texts.map((text) => ({
4515
4706
  ...text,
4516
- baseline: text.baseline - envelope.shift(text.baseline - envelope.ascent, scale)
4707
+ ...envelope.position(text, scale)
4517
4708
  })),
4518
4709
  markers: control.layout.markers.map((marker) => ({
4519
4710
  ...marker,
@@ -4777,7 +4968,8 @@ var LineFlow = class {
4777
4968
  return parts.map((part, index) => {
4778
4969
  const piece = units[index];
4779
4970
  if (!canFitAtomic(piece)) return part;
4780
- const fit = fitAtomic(piece, piece.kind === "control" ? frameHeight - baseline + piece.control.baseline + (piece.paint.baselineShiftPx ?? 0) : piece.kind === "pageWidget" ? baseline - (piece.widget.paint.baselineShiftPx ?? 0) : baseline, this.context);
4971
+ const controlMaximum = piece.kind === "control" ? piece.control.baseline > frameHeight - descent - (piece.paint.baselineShiftPx ?? 0) ? frameHeight - descent - (piece.paint.baselineShiftPx ?? 0) : frameHeight - baseline + piece.control.baseline + (piece.paint.baselineShiftPx ?? 0) : void 0;
4972
+ const fit = fitAtomic(piece, piece.kind === "control" ? controlMaximum : piece.kind === "pageWidget" ? baseline - (piece.widget.paint.baselineShiftPx ?? 0) : baseline, this.context);
4781
4973
  return fit.issue ? {
4782
4974
  ...part,
4783
4975
  piece: fit.piece,
@@ -4961,6 +5153,7 @@ var RowFlow = class {
4961
5153
  table;
4962
5154
  group;
4963
5155
  context;
5156
+ contentFlow;
4964
5157
  /** 当前源显示行。 */
4965
5158
  index;
4966
5159
  /** 物理页片段序号,不写入 model。 */
@@ -4974,10 +5167,11 @@ var RowFlow = class {
4974
5167
  /** 每个合并主格只注册一次进度。 */
4975
5168
  cells;
4976
5169
  /** 借用本轮测量结果,不创建新原生网格或业务值副本。 */
4977
- constructor(table, group, context) {
5170
+ constructor(table, group, context, contentFlow) {
4978
5171
  this.table = table;
4979
5172
  this.group = group;
4980
5173
  this.context = context;
5174
+ this.contentFlow = contentFlow;
4981
5175
  this.index = group.from;
4982
5176
  for (let row = group.from; row < group.to; row++) {
4983
5177
  this.remaining.set(row, table.rowOffsets[row + 1] - table.rowOffsets[row]);
@@ -4995,7 +5189,7 @@ var RowFlow = class {
4995
5189
  to,
4996
5190
  deadline,
4997
5191
  flexible: deadline >= 0,
4998
- ...deadline >= 0 ? { cursor: new ContentFlowCursor(cell, context) } : {},
5192
+ ...deadline >= 0 ? { cursor: this.contentFlow.create(cell, context) } : {},
4999
5193
  started: false
5000
5194
  });
5001
5195
  }
@@ -5058,7 +5252,7 @@ var RowFlow = class {
5058
5252
  to,
5059
5253
  top,
5060
5254
  ending,
5061
- slice: state.cursor ? previewContentFlow(state.cursor, Math.max(0, height - top - state.cell.padding.bottom), forceFirst, Math.max(1, frameHeight - top - state.cell.padding.bottom)) : FIXED_GEOMETRY_SLICE
5255
+ slice: state.cursor ? this.contentFlow.preview(state.cursor, Math.max(0, height - top - state.cell.padding.bottom), forceFirst, Math.max(1, frameHeight - top - state.cell.padding.bottom)) : FIXED_GEOMETRY_SLICE
5062
5256
  });
5063
5257
  }
5064
5258
  return result;
@@ -5176,7 +5370,7 @@ var RowFlow = class {
5176
5370
  height: Math.max(0, cellHeight - plan.top - bottom)
5177
5371
  };
5178
5372
  const sourceOffset = table.rowOffsets[rows[plan.from].index] - table.rowOffsets[plan.state.from] + (table.rowOffsets[rows[plan.from].index + 1] - table.rowOffsets[rows[plan.from].index] - this.remaining.get(rows[plan.from].index));
5179
- const fixed = plan.state.flexible ? void 0 : placeCellWindow(cell, frame.x, cellY - sourceOffset, frame, pageId, context);
5373
+ const fixed = plan.state.flexible ? void 0 : placeCellWindow(cell, frame.x, cellY - sourceOffset, frame, pageId, context, placeMeasuredBlocks);
5180
5374
  const fragment = {
5181
5375
  kind: "cell",
5182
5376
  id: layoutIdentity(context.identityScope, "cell", cell.instance.key, table.nodeId, "continuation", this.part),
@@ -5190,7 +5384,7 @@ var RowFlow = class {
5190
5384
  backgroundColor: cell.backgroundColor,
5191
5385
  frame,
5192
5386
  contentFrame: fixed?.contentFrame ?? contentFrame,
5193
- blocks: plan.state.flexible ? placeContentFlow(plan.slice, contentFrame.x, contentFrame.y, pageId, context) : fixed.blocks
5387
+ blocks: plan.state.flexible ? this.contentFlow.place(plan.slice, contentFrame.x, contentFrame.y, pageId, context) : fixed.blocks
5194
5388
  };
5195
5389
  cellRows[plan.from].push(fragment);
5196
5390
  }
@@ -5404,6 +5598,7 @@ var NO_TABLE_HEADERS = Object.freeze([]);
5404
5598
  var TableFlow = class {
5405
5599
  table;
5406
5600
  context;
5601
+ contentFlow;
5407
5602
  /** 当前测量独占的表头与显式分页索引,完成后随游标释放。 */
5408
5603
  indexed;
5409
5604
  /** 当前尚未完成的行组下标。 */
@@ -5413,9 +5608,10 @@ var TableFlow = class {
5413
5608
  /** 只保留当前候选涉及的行组进度,完成即释放。 */
5414
5609
  flows = /* @__PURE__ */ new Map();
5415
5610
  /** 借用同一次构建的测量及来源注册器,不创建全局状态。 */
5416
- constructor(table, context) {
5611
+ constructor(table, context, contentFlow) {
5417
5612
  this.table = table;
5418
5613
  this.context = context;
5614
+ this.contentFlow = contentFlow;
5419
5615
  }
5420
5616
  /** 首次实际查询才建立规则,构造游标本身不创建中间索引。 */
5421
5617
  get rules() {
@@ -5449,7 +5645,7 @@ var TableFlow = class {
5449
5645
  if (existing) return existing;
5450
5646
  const group = this.table.groups[index];
5451
5647
  if (!group || !(this.table.hasPageBreak ? this.rules.needsFlow(index, frameHeight) : this.rangeHeight(group) > frameHeight)) return void 0;
5452
- const flow = new RowFlow(this.table, group, this.context);
5648
+ const flow = new RowFlow(this.table, group, this.context, this.contentFlow);
5453
5649
  this.flows.set(index, flow);
5454
5650
  return flow;
5455
5651
  }
@@ -5680,7 +5876,7 @@ var ContentFlowCursor = class {
5680
5876
  tableFlow(table) {
5681
5877
  let flow = this.tables.get(table);
5682
5878
  if (!flow) {
5683
- flow = new TableFlow(table, this.context);
5879
+ flow = new TableFlow(table, this.context, contentFlowOperations);
5684
5880
  this.tables.set(table, flow);
5685
5881
  }
5686
5882
  return flow;
@@ -5827,6 +6023,12 @@ function placeContentFlow(slice, x, y, pageId, context) {
5827
6023
  }
5828
6024
  return result;
5829
6025
  }
6026
+ /** 仅包含无状态函数,游标、候选和上下文仍由本轮分页拥有。 */
6027
+ var contentFlowOperations = {
6028
+ create: (source, context) => new ContentFlowCursor(source, context),
6029
+ preview: previewContentFlow,
6030
+ place: placeContentFlow
6031
+ };
5830
6032
  // src/layout/engine/pagination/paragraph-pagination.ts
5831
6033
  /** @file 正文段落直接消费统一内容流,文字、长控件和混排行共用分页进度。 */
5832
6034
  /** 两种分页路径共用最终放置与诊断,始终使用本轮源块和实例。 */
@@ -5873,7 +6075,7 @@ function paginateParagraph(block, current, nextPage, context) {
5873
6075
  /** @file 正文级表格分页:整行快路径与内容连续流共用页、表头和最终共享边。 */
5874
6076
  /** 表头超过容量时优先推进实际内容,最终表格每页只发布一份组合结果。 */
5875
6077
  function paginateTable(table, current, nextPage, context, reuse) {
5876
- const flow = new TableFlow(table, context);
6078
+ const flow = new TableFlow(table, context, contentFlowOperations);
5877
6079
  while (!flow.done) {
5878
6080
  /** 本页段未命中时使用原分页推进,候选不被提前消费。 */
5879
6081
  const calculate = () => {
@@ -7829,6 +8031,10 @@ function indexResult(result, reuse) {
7829
8031
  if (box.lineHeightPx <= 0 || box.width <= 0 || box.height <= 0) throw new LayoutContractError("invalid_geometry", "字段输入内容框不能保证编辑进度");
7830
8032
  }
7831
8033
  for (const image of fragment.fieldControl.images ?? []) validateImage(image);
8034
+ for (const bracket of fragment.fieldControl.bracketFrames ?? []) {
8035
+ validateRect(bracket.frame);
8036
+ if (bracket.side !== "start" && bracket.side !== "end") throw new LayoutContractError("invalid_geometry", "字段括号方向无效");
8037
+ }
7832
8038
  if (fragment.role !== "field") throw new LayoutContractError("invalid_geometry", "控件绘制描述必须属于字段");
7833
8039
  validateFragmentStyles(fragment, result);
7834
8040
  for (const text of [...fragment.fieldControl.texts, ...fragment.fieldControl.bracketTexts ?? []]) {
@@ -10692,7 +10898,7 @@ var EditorBusinessTables = class {
10692
10898
  if (node?.kind !== "cell") continue;
10693
10899
  const quickFill = this.require(source).tables.quickFill;
10694
10900
  const current = quickFill.readMatrix(source.regionId, source.slotIndex);
10695
- if (!current?.enabled) throw new TextFlowError("当前业务区域不允许矩形粘贴");
10901
+ if (!current?.enabled) throw new TextFlowError("当前表格区域不允许矩形粘贴");
10696
10902
  if (!isEqual(source.version, current.version)) throw new TextFlowError("当前业务格已变化,请重新粘贴");
10697
10903
  this.require(source);
10698
10904
  return quickFill.applyMatrix(current, {
@@ -10918,7 +11124,7 @@ function matrixTableProjection(query, table) {
10918
11124
  const cell = grid.cells[row][column];
10919
11125
  if (!cell.merge || cell.merge.isMaster) {
10920
11126
  const previous = cells.get(cell.cellId);
10921
- if (previous.regionId && previous.regionId !== region.id) throw new Error("二维主体与其他业务区域的关联行带重叠");
11127
+ if (previous.regionId && previous.regionId !== region.id) throw new Error("二维主体与其他表格区域的关联行带重叠");
10922
11128
  cells.set(cell.cellId, {
10923
11129
  sourceCellId: cell.cellId,
10924
11130
  regionId: region.id,
@@ -10935,7 +11141,7 @@ function matrixTableProjection(query, table) {
10935
11141
  const target = grid.cells[mapping.row][mapping.column];
10936
11142
  if (target.merge && !target.merge.isMaster) continue;
10937
11143
  const previous = cells.get(target.cellId);
10938
- if (previous.regionId && previous.regionId !== region.id) throw new Error("二维关联行带与其他业务区域发生重叠");
11144
+ if (previous.regionId && previous.regionId !== region.id) throw new Error("二维关联行带与其他表格区域发生重叠");
10939
11145
  const source = grid.cells[mapping.sourceRow][mapping.sourceColumn];
10940
11146
  cells.set(target.cellId, {
10941
11147
  sourceCellId: source.merge?.masterCellId ?? source.cellId,
@@ -11008,7 +11214,7 @@ function assertClipboardBindings(fragment, blocks, inherited) {
11008
11214
  const path = fragment.bindings[node.bindingId]?.pathTemplate;
11009
11215
  if (path?.includes("[n")) {
11010
11216
  const binding = parseValuePath(path);
11011
- if (!inherited.has(binding.parentFieldPath) || binding.isLink && !inherited.has(binding.linkFieldPath)) throw new TextFlowError("剪贴字段的子表绑定与目标业务区域不匹配");
11217
+ if (!inherited.has(binding.parentFieldPath) || binding.isLink && !inherited.has(binding.linkFieldPath)) throw new TextFlowError("剪贴字段的子表绑定与目标表格区域不匹配");
11012
11218
  }
11013
11219
  for (const attachment of node.attachments ?? []) assertClipboardBindings(fragment, attachment.blocks, inherited);
11014
11220
  }
@@ -12192,6 +12398,65 @@ function inputTextStyle(model, flow, selection, format) {
12192
12398
  const patched = format ? patchTextDeclaration(declaration, format) : declaration;
12193
12399
  return id ? model.query.resolveTextStyle(id, patched) : model.query.resolveDefaultTextStyle(patched);
12194
12400
  }
12401
+ // src/runtime/interaction/design/format/targets.ts
12402
+ /** @file 文字与单元格选区共用格式目标;只借用真实内容,不把矩形伪造成连续文字范围。 */
12403
+ /** 格选择覆盖可见合并主格内的所有段落,空格仅在明确设置格式时由调用方物化。 */
12404
+ function* formatTargets(context, selection) {
12405
+ if (selection.kind === "text") {
12406
+ yield* context.flow().formatTargets(selection);
12407
+ return;
12408
+ }
12409
+ const model = context.handle().readModel(), { table, rectangle } = resolveCellSelection(model, selection), visited = /* @__PURE__ */ new Set();
12410
+ function* cell(id) {
12411
+ const master = model.query.getCellInfo(id).merge?.masterCellId ?? id;
12412
+ if (visited.has(master)) return;
12413
+ visited.add(master);
12414
+ yield* blocks(master, model.query.getEntity(master, "cell").blocks);
12415
+ }
12416
+ function* blocks(ownerId, content) {
12417
+ if (!content.length) yield {
12418
+ kind: "blockGap",
12419
+ parentId: ownerId,
12420
+ index: 0
12421
+ };
12422
+ for (const block of content) if (block.kind === "paragraph") yield {
12423
+ from: {
12424
+ paragraphId: block.id,
12425
+ index: 0
12426
+ },
12427
+ to: {
12428
+ paragraphId: block.id,
12429
+ index: block.content.length
12430
+ }
12431
+ };
12432
+ else for (const row of block.rows) for (const nested of row.cells) yield* cell(nested.id);
12433
+ }
12434
+ for (let row = rectangle.top; row <= rectangle.bottom; row++) for (let column = rectangle.left; column <= rectangle.right; column++) yield* cell(table.rows[row].cells[column].id);
12435
+ }
12436
+ /** 文字范围沿用原生投影;格选择只返回选中主格内的模板文字和原子声明。 */
12437
+ function formatInlines(context, selection) {
12438
+ if (selection.kind === "text") {
12439
+ const projection = context.flow().projection(selection);
12440
+ return [...projection.spans.map(({ source }) => {
12441
+ if (source.kind !== "modelText") throw new TextFlowError("格式不能修改字段填写值");
12442
+ return {
12443
+ id: source.nodeId,
12444
+ from: source.from,
12445
+ to: source.to
12446
+ };
12447
+ }), ...projection.nodes.map(({ nodeId }) => ({
12448
+ id: nodeId,
12449
+ from: 0,
12450
+ to: 1
12451
+ }))];
12452
+ }
12453
+ const query = context.handle().readModel().query;
12454
+ return [...formatTargets(context, selection)].flatMap((range) => "kind" in range ? [] : query.getEntity(range.from.paragraphId, "paragraph").content.map((node) => ({
12455
+ id: node.id,
12456
+ from: 0,
12457
+ to: node.kind === "text" ? node.text.length : 1
12458
+ })));
12459
+ }
12195
12460
  // src/runtime/interaction/design/format/property-format.ts
12196
12461
  /** @file 嵌套样式单属性更新,保留不同目标的相邻直接声明,不写入有效样式。 */
12197
12462
  /** 单个对象属性覆盖/恢复继承,只隔离其所属小对象,绝不修改模型或输入调用者。 */
@@ -12227,12 +12492,12 @@ function setTextProperty(context, path, value) {
12227
12492
  checkTextPath(path);
12228
12493
  const model = context.handle().readModel(), flow = context.flow(), selection = context.selection();
12229
12494
  readTextFormatUpdate(model.document, patch({}, path, value));
12230
- if (flow.ordered(selection).collapsed) {
12495
+ if (selection.kind === "text" && flow.ordered(selection).collapsed) {
12231
12496
  const update = patch(patchTextDeclaration(inputDeclaration(model, flow, selection).declaration, context.inputFormat() ?? {}).textStyle, path, value);
12232
12497
  context.setInputFormat(mergeInputFormat(model, context.inputFormat(), update));
12233
12498
  return null;
12234
12499
  }
12235
- const ranges = [...flow.formatTargets(selection)];
12500
+ const ranges = [...formatTargets(context, selection)];
12236
12501
  const emptyParagraphs = ranges.flatMap((range) => {
12237
12502
  if ("kind" in range) return [];
12238
12503
  const paragraph = model.query.getEntity(range.from.paragraphId, "paragraph");
@@ -12242,21 +12507,10 @@ function setTextProperty(context, path, value) {
12242
12507
  next: patchTextDeclaration(paragraph, patch(paragraph.textStyle, path, value))
12243
12508
  }];
12244
12509
  });
12245
- const projection = flow.projection(selection), targets = [...projection.spans.map((span) => {
12246
- if (span.source.kind !== "modelText") throw new TextFlowError("格式不能修改字段填写值");
12247
- return {
12248
- id: span.source.nodeId,
12249
- from: span.source.from,
12250
- to: span.source.to
12251
- };
12252
- }), ...projection.nodes.filter((node) => {
12253
- const entity = model.query.getEntity(node.nodeId);
12254
- return entity && "kind" in entity && (entity.kind === "field" || entity.kind === "pageWidget");
12255
- }).map((node) => ({
12256
- id: node.nodeId,
12257
- from: 0,
12258
- to: 1
12259
- }))];
12510
+ const targets = formatInlines(context, selection).filter((target) => {
12511
+ const entity = model.query.getEntity(target.id);
12512
+ return entity && "kind" in entity && (entity.kind === "text" || entity.kind === "field" || entity.kind === "pageWidget");
12513
+ });
12260
12514
  for (const target of targets) if (model.query.getEntity(target.id, "field")?.config?.designLocked === true) throw new TextFlowError("所选字段配置已锁定");
12261
12515
  const order = /* @__PURE__ */ new Map();
12262
12516
  let index = 0;
@@ -12320,7 +12574,7 @@ function setParagraphProperty(context, path, value) {
12320
12574
  ]
12321
12575
  }[path[0]]?.includes(path[1])) throw new TextFlowError("未知段落格式属性");
12322
12576
  readParagraphFormatUpdate(context.handle().readModel().document, patch({}, path, value));
12323
- const targets = [...context.flow().formatTargets(context.selection())];
12577
+ const targets = [...formatTargets(context, context.selection())];
12324
12578
  const model = context.handle().readModel();
12325
12579
  const commands = targets.map((target) => ({
12326
12580
  target,
@@ -12365,11 +12619,11 @@ function common(styles) {
12365
12619
  }
12366
12620
  /** 读取选择触达的真实文字/字段/页组件;下一段起点不串入当前格式摘要。 */
12367
12621
  function readFormat(context, selection) {
12368
- const handle = context.handle(), model = handle.readModel(), flow = context.flow(), typing = flow.ordered(selection).collapsed;
12622
+ const handle = context.handle(), model = handle.readModel(), flow = context.flow(), typing = selection.kind === "text" && flow.ordered(selection).collapsed;
12369
12623
  const texts = [], paragraphs = [];
12370
12624
  const inputFormat = context.inputFormat();
12371
- if (typing) texts.push(inputTextStyle(model, flow, selection, inputFormat));
12372
- for (const target of flow.formatTargets(selection)) {
12625
+ if (typing && selection.kind === "text") texts.push(inputTextStyle(model, flow, selection, inputFormat));
12626
+ for (const target of formatTargets(context, selection)) {
12373
12627
  if ("kind" in target) {
12374
12628
  paragraphs.push(model.query.resolveDefaultParagraphStyle());
12375
12629
  if (!typing) texts.push(model.query.resolveDefaultTextStyle());
@@ -12414,22 +12668,22 @@ var EditorFormat = class {
12414
12668
  constructor(context) {
12415
12669
  this.context = context;
12416
12670
  }
12417
- /** 按当前正文/声明选区读取小份格式,填报值不作为模板文字处理。 */
12671
+ /** 按当前文字或格选区读取小份格式,填报值不作为模板文字处理。 */
12418
12672
  read() {
12419
12673
  const selection = this.context?.selection();
12420
- return selection?.kind === "text" ? readFormat(this.context, selection) : void 0;
12674
+ return selection?.kind === "text" || selection?.kind === "cells" ? readFormat(this.context, selection) : void 0;
12421
12675
  }
12422
- /** 折叠光标只发布输入意图;展开范围由原生范围 API 修改选中来源并保留方向。 */
12676
+ /** 折叠光标只发布输入意图;文字范围或格内内容通过原生 API 修改并保留选区。 */
12423
12677
  applyText(expected, update) {
12424
- const context = this.require(expected), model = context.handle().readModel(), flow = context.flow(), selection = context.selection();
12678
+ const context = this.require(expected), model = context.handle().readModel(), flow = context.flow(), selection = expected.selection;
12425
12679
  const patch = readTextFormatUpdate(model.document, update);
12426
- if (flow.ordered(selection).collapsed) {
12680
+ if (selection.kind === "text" && flow.ordered(selection).collapsed) {
12427
12681
  const merged = mergeInputFormat(model, context.inputFormat(), patch);
12428
12682
  if (!isEqual(merged, context.inputFormat() ?? {})) context.setInputFormat(merged);
12429
12683
  return null;
12430
12684
  }
12431
- for (const selected of flow.projection(selection).nodes) if (model.query.getEntity(selected.nodeId, "field")?.config?.designLocked === true) throw new TextFlowError("所选字段配置已锁定");
12432
- const targets = [...flow.formatTargets(selection)], empty = /* @__PURE__ */ new Map();
12685
+ for (const selected of formatInlines(context, selection)) if (model.query.getEntity(selected.id, "field")?.config?.designLocked === true) throw new TextFlowError("所选字段配置已锁定");
12686
+ const targets = [...formatTargets(context, selection)], empty = /* @__PURE__ */ new Map();
12433
12687
  for (const target of targets) if (!("kind" in target)) {
12434
12688
  const paragraph = model.query.getEntity(target.from.paragraphId, "paragraph");
12435
12689
  if (!paragraph.content.length) empty.set(paragraph.id, {
@@ -12457,7 +12711,7 @@ var EditorFormat = class {
12457
12711
  /** 段落格式作用于真实触达段落;空集合只有明确设置时才物化一个段落。 */
12458
12712
  applyParagraph(expected, update) {
12459
12713
  const context = this.require(expected), patch = readParagraphFormatUpdate(context.handle().readModel().document, update);
12460
- const targets = [...context.flow().formatTargets(context.selection())];
12714
+ const targets = [...formatTargets(context, expected.selection)];
12461
12715
  return context.execute("修改段落格式", (editor) => {
12462
12716
  for (const target of targets) if (!("kind" in target)) editor.ranges.formatParagraphs(target, patch);
12463
12717
  else if (Object.keys(patch.set ?? {}).length || patch.paragraphStyleId != null) {
@@ -12741,7 +12995,7 @@ var EditorTableRegions = class {
12741
12995
  assertRegionOwner(this.context.handle().readModel(), expected.selection.tableId);
12742
12996
  this.assertCanCreate(options.type, options.variant?.name);
12743
12997
  let id = "";
12744
- this.context.execute("创建业务区域", (editor) => {
12998
+ this.context.execute("创建表格区域", (editor) => {
12745
12999
  id = editor.tables.addRegion(expected.selection.tableId, {
12746
13000
  ...options,
12747
13001
  range: options.range === void 0 ? expected.range : options.range
@@ -12794,7 +13048,7 @@ var EditorTableRegions = class {
12794
13048
  assertRegionOwner(this.context.handle().readModel(), expected.selection.tableId);
12795
13049
  this.assertCanCreate(type, variantName);
12796
13050
  }
12797
- return this.context.execute("修改业务区域", (editor) => {
13051
+ return this.context.execute("修改表格区域", (editor) => {
12798
13052
  editor.tables.updateRegion(expected.regionId, update);
12799
13053
  });
12800
13054
  }
@@ -12805,11 +13059,19 @@ var EditorTableRegions = class {
12805
13059
  if (expected.selection.tableId !== table.selection.tableId || expected.selection.instanceKey !== table.selection.instanceKey) throw new TextFlowError("区域范围不能跨表或发生");
12806
13060
  return this.update(expected, { set: { range: table.range } });
12807
13061
  }
12808
- /** 只删除区域声明;依赖默认拒绝,明确 remove 才级联,格内容始终由原生表格拥有。 */
13062
+ /** 删除业务/数据表或分组时联删其字段;独立删除表头只移除声明,普通格内容保留。 */
12809
13063
  remove(expected, options = {}) {
12810
- this.require(expected);
12811
- return this.context.execute("删除业务区域", (editor) => {
13064
+ const region = this.require(expected);
13065
+ const fields = dataRegionTypes.has(region.type) || region.type === "bounded-item" || region.type === "data-group-2d" ? this.removalFields(expected, options.dependents === "remove") : [];
13066
+ const model = this.context.handle().readModel();
13067
+ for (const id of fields) assertOwnedEditingAllowed(model, id, "removable");
13068
+ const { removeUnusedBindings, removeUnusedAssets } = options;
13069
+ return this.context.execute("删除表格区域", (editor) => {
12812
13070
  editor.tables.removeRegion(expected.regionId, options);
13071
+ for (const id of fields) editor.removeField(id, {
13072
+ removeUnusedBindings,
13073
+ removeUnusedAssets
13074
+ });
12813
13075
  });
12814
13076
  }
12815
13077
  /** 高亮当前区域的实际范围,不分配模型身份或历史。 */
@@ -12826,6 +13088,27 @@ var EditorTableRegions = class {
12826
13088
  dispose() {
12827
13089
  this.context = void 0;
12828
13090
  }
13091
+ /** 按物理格收集主体及级联分组/表头的字段根;附属子树随所属字段一次删除。 */
13092
+ removalFields(expected, cascade) {
13093
+ const { query } = this.context.handle().readModel();
13094
+ const table = query.getEntity(expected.selection.tableId, "table");
13095
+ const regions = /* @__PURE__ */ new Set([expected.regionId]);
13096
+ if (cascade) {
13097
+ for (const id of regions) for (const region of table.regions) if (region.parentRegionId === id || region.targetRegionId === id) regions.add(region.id);
13098
+ }
13099
+ const cells = /* @__PURE__ */ new Set();
13100
+ for (const id of regions) {
13101
+ const { top, bottom, left, right } = query.getRegionInfo(id).rectangle;
13102
+ for (let row = top; row <= bottom; row++) for (let column = left; column <= right; column++) cells.add(table.rows[row].cells[column].id);
13103
+ }
13104
+ const fields = [];
13105
+ const visit = (blocks) => {
13106
+ for (const block of blocks) if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) visit(cell.blocks);
13107
+ else for (const node of block.content) if (node.kind === "field") fields.push(node.id);
13108
+ };
13109
+ for (const id of cells) visit(query.getEntity(id, "cell").blocks);
13110
+ return fields;
13111
+ }
12829
13112
  /** 读取只检查打开及模型版本;不会为只读查看要求可写权限。 */
12830
13113
  readTarget(expected) {
12831
13114
  const context = this.context;
@@ -13585,7 +13868,7 @@ var EditorPageWidgets = class {
13585
13868
  if (binding?.pathTemplate.includes("[n")) {
13586
13869
  const path = parseValuePath(binding.pathTemplate);
13587
13870
  const axes = destinationAxes(this.context.handle().readModel(), node.id);
13588
- if (!axes.has(path.parentFieldPath) || path.isLink && !axes.has(path.linkFieldPath)) throw new TextFlowError("该字段和当前组件所在业务区域不匹配");
13871
+ if (!axes.has(path.parentFieldPath) || path.isLink && !axes.has(path.linkFieldPath)) throw new TextFlowError("该字段和当前组件所在表格区域不匹配");
13589
13872
  }
13590
13873
  return this.context.execute("绑定组件字段", (editor) => {
13591
13874
  const bindingId = binding ? editor.ensureBinding({ binding }) : null;
@@ -14120,7 +14403,7 @@ function validationPlacements(handle, snapshot, fields, issues) {
14120
14403
  }
14121
14404
  const field = model.getEntity(fieldId, "field");
14122
14405
  if (field?.widget !== "seal" || handle.readModel().document.bindings[field.bindingId]?.pathTemplate !== issue.valuePath) continue;
14123
- const overlay = model.getAncestors(fieldId).find((node) => "kind" in node && node.kind === "overlay");
14406
+ const overlay = model.getAncestors(fieldId).find((node) => node.kind === "overlay");
14124
14407
  if (overlay) result.set(issue, query.findBySource({ nodeId: overlay.id }).filter((item) => item.kind === "overlay").flatMap((item) => placement(item)));
14125
14408
  }
14126
14409
  }
@@ -14331,7 +14614,7 @@ var EditorController = class {
14331
14614
  this.desiredX = void 0;
14332
14615
  this.setSelection(selected);
14333
14616
  }
14334
- /** 查询相邻可填写字段;规则准备期间由浏览器等待,文档边界交还原生 Tab。 */
14617
+ /** 查询相邻可填写字段;规则准备期间由浏览器等待,文档边界返回 undefined。 */
14335
14618
  getFieldTabStop(direction) {
14336
14619
  const options = this.requireOptions(), form = options.form;
14337
14620
  if (!form || options.environment().mode !== "fill" || this.state.composition) return;
@@ -14783,9 +15066,9 @@ var EditorController = class {
14783
15066
  ...options.style,
14784
15067
  cellPaddingPx: options.style?.cellPaddingPx ?? {
14785
15068
  top: 5,
14786
- right: 5,
15069
+ right: 8,
14787
15070
  bottom: 5,
14788
- left: 5
15071
+ left: 8
14789
15072
  },
14790
15073
  borders: options.style?.borders ?? {
14791
15074
  top: edge,
@@ -15055,6 +15338,10 @@ var EditorController = class {
15055
15338
  }
15056
15339
  /** 数值输入中的短期校验复用正式字段规则,取消不影响已提交值或提交门禁。 */
15057
15340
  validateFieldText(text, expected, signal) {
15341
+ return this.validateFieldTextMessages(text, expected, signal).then((messages) => messages?.join(";"));
15342
+ }
15343
+ /** 列表展示复用同一草稿校验,保留每条规则的文案边界。 */
15344
+ validateFieldTextMessages(text, expected, signal) {
15058
15345
  const options = this.requireOptions();
15059
15346
  return validateFieldTextDraft(this.requireHandle(), options, () => this.options === options ? this.state.selection : null, expected, text, signal);
15060
15347
  }
@@ -15105,6 +15392,19 @@ var EditorController = class {
15105
15392
  const options = this.requireOptions(), selection = this.state.selection;
15106
15393
  return selection?.kind === "field" && options.form ? readFieldSignatureInput(this.requireHandle(), options, selection) : void 0;
15107
15394
  }
15395
+ /** 弹框前预检查,不认证;无校验需求时保持同步。 */
15396
+ validateFieldSignature(expected, signal) {
15397
+ const options = this.requireOptions();
15398
+ const handle = this.requireHandle();
15399
+ assertFieldSignatureInput(handle, options, this.state.selection, expected);
15400
+ if (signal.aborted) throw new TextFlowError("签名前检查已取消");
15401
+ const checking = options.form.services.signatures.validateBeforeOpen(expected.selection.fieldId, expected.valuePath, signal);
15402
+ if (!checking) return;
15403
+ return checking.then(() => {
15404
+ if (signal.aborted || this.handle !== handle || this.options !== options) throw new TextFlowError("签名前检查已取消");
15405
+ assertFieldSignatureInput(this.requireHandle(), this.requireOptions(), this.state.selection, expected);
15406
+ });
15407
+ }
15108
15408
  /** 用户明确认证后取得原业务服务的不透明预览;取消和过期结果不写入。 */
15109
15409
  async prepareFieldSignature(expected, signal, authorization) {
15110
15410
  const options = this.requireOptions();
@@ -15530,6 +15830,55 @@ function isCompanionIdPath(path) {
15530
15830
  function isDerivedDataPath(path) {
15531
15831
  return path.endsWith("_lb_") || path.endsWith("_href_") || isCompanionIdPath(path);
15532
15832
  }
15833
+ // src/data/rows/copy-row.ts
15834
+ /** @file 复制载荷的字段清理,不读取业务模型或修改源行。 */
15835
+ /** 只清理已有属性,缺失嵌套对象不会因复制被创建。 */
15836
+ function clearCopiedFields(row, paths, emptyValue) {
15837
+ const dataPaths = new JsonDataPaths();
15838
+ for (const relative of paths) {
15839
+ const path = "$." + relative;
15840
+ const parts = dataPaths.parse(path);
15841
+ const leaf = parts.pop();
15842
+ const parent = dataPaths.read(row, formatPath(parts));
15843
+ if (parent !== null && typeof parent === "object" && Object.hasOwn(parent, leaf)) dataPaths.setProperty(parent, leaf, emptyValue ? emptyValue(relative) : null);
15844
+ for (const companion of [
15845
+ getLabelPath(path),
15846
+ getHrefPath(path),
15847
+ getIdPath(path)
15848
+ ]) dataPaths.delete(row, companion);
15849
+ }
15850
+ }
15851
+ /** 克隆后清理,源行的值和派生属性保持原状。 */
15852
+ function cloneCopiedRow(source, paths) {
15853
+ const row = cloneDeep(source);
15854
+ clearCopiedFields(row, paths);
15855
+ return row;
15856
+ }
15857
+ // src/runtime/form/copy-field-paths.ts
15858
+ var nonCopyableTypes = /* @__PURE__ */ new Set([
15859
+ "signature",
15860
+ "electronic_signature",
15861
+ "reporter",
15862
+ "warehouse_manager"
15863
+ ]);
15864
+ /** tableKey 不带 $.;二维交叉区直接使用 yKey:xKey。 */
15865
+ function collectNonCopyableFieldPaths(model, tableKey) {
15866
+ const result = /* @__PURE__ */ new Set();
15867
+ const collect = (binding, widget) => {
15868
+ if (!binding) return;
15869
+ const match = /^\$\.([^.[\]]+)(?:\[[^\]]+\])*\.(.+)$/.exec(binding.pathTemplate);
15870
+ if (match?.[1] !== tableKey || !match[2]) return;
15871
+ if (widget === "signature" || nonCopyableTypes.has(binding.source.fieldType) || nonCopyableTypes.has(binding.source.businessType ?? "")) result.add(match[2]);
15872
+ };
15873
+ for (const binding of Object.values(model.document.bindings)) collect(binding);
15874
+ for (const node of model.query.findEntities({ roles: ["field"] })) if ("kind" in node && node.kind === "field") collect(model.document.bindings[node.bindingId], node.widget);
15875
+ for (const { id } of model.query.findEntities({ roles: ["region"] })) {
15876
+ const region = model.query.getEntity(id, "region");
15877
+ const control = region?.config?.dataLockControlField;
15878
+ if ((region?.type === "bounded" || region?.type === "repeating" && !region.variant?.name) && region.binding?.pathTemplate === "$." + tableKey && typeof control === "string" && control.length > 0) result.add(control);
15879
+ }
15880
+ return result;
15881
+ }
15533
15882
  // src/runtime/form/business/authentication-value.ts
15534
15883
  /** @file 普通业务表与物耗行共用认证值保护,解释现有协议而不改写历史值。 */
15535
15884
  /** 优先实际控件类型,业务源明确认证类型时同样参与保护。 */
@@ -15554,7 +15903,7 @@ function tableFieldInputAllowed(options, fieldId, path, existing) {
15554
15903
  const field = options.fields.declaration(fieldId, path);
15555
15904
  if (!field) return false;
15556
15905
  const state = options.fields.state(fieldId, path);
15557
- return existing ? state.editable : !state.readonly && !state.disabled && !state.pending && !field.field.config?.dependencies?.some((rule) => rule.effect === "assignment" && rule.strategy === "alwaysCover" && !!rule.expression);
15906
+ return existing ? state.editable : !state.readonly && !state.disabled && !state.pending && !field.field.config?.dependencies?.some((rule) => rule.effect === "assignment" && rule.assignmentType !== "clear" && (rule.strategy ?? "alwaysCover") === "alwaysCover" && !!rule.expression);
15558
15907
  }
15559
15908
  /** 借用当前真实字段引用,不缓存字段树或展开运行行。 */
15560
15909
  function tableRowFields(options, tableId, regionId, axis) {
@@ -15582,16 +15931,24 @@ function authenticatedRow(options, fields, axis, index) {
15582
15931
  }
15583
15932
  /** 只修改隔离的复制载荷;认证为空用统一字段编码器,不展开未声明属性或默认值。 */
15584
15933
  function clearCopiedAuthentication(options, fields, axis, index, row) {
15585
- const root = `${axis}[${index}]`, paths = new JsonDataPaths();
15586
- for (const declaration of fields) if (authenticationKind(declaration.field.widget, declaration.binding.source.fieldType)) {
15587
- const path = rowFieldPath(declaration, axis, index), relative = "$" + path.slice(root.length);
15588
- paths.write(row, relative, options.runtime.encodeBoundValue(path, null));
15589
- for (const derived of [
15590
- getIdPath(path),
15591
- getLabelPath(path),
15592
- getHrefPath(path)
15593
- ]) paths.delete(row, "$" + derived.slice(root.length));
15934
+ const root = `${axis}[${index}]`, paths = new JsonDataPaths(), additional = collectNonCopyableFieldPaths(options.handle.readModel(), axis.slice(2));
15935
+ for (const declaration of fields) {
15936
+ const kind = authenticationKind(declaration.field.widget, declaration.binding.source.fieldType);
15937
+ if (kind) {
15938
+ const path = rowFieldPath(declaration, axis, index), relative = "$" + path.slice(root.length);
15939
+ if (kind === "signature") clearCopiedFields(row, [relative.slice(2)], () => options.runtime.encodeBoundValue(path, null));
15940
+ else {
15941
+ paths.write(row, relative, options.runtime.encodeBoundValue(path, null));
15942
+ for (const derived of [
15943
+ getIdPath(path),
15944
+ getLabelPath(path),
15945
+ getHrefPath(path)
15946
+ ]) paths.delete(row, "$" + derived.slice(root.length));
15947
+ }
15948
+ additional.delete(relative.slice(2));
15949
+ }
15594
15950
  }
15951
+ clearCopiedFields(row, additional, (relative) => options.runtime.encodeBoundValue(`${root}.${relative}`, null));
15595
15952
  }
15596
15953
  /** 按真实槽位及附属条件筛选本行字段,新行只用空标记投影活动坐标。 */
15597
15954
  function tableRowTargets(options, axis, index, fields, prospective = false, readAxis) {
@@ -15613,13 +15970,13 @@ function tableRowTargets(options, axis, index, fields, prospective = false, read
15613
15970
  });
15614
15971
  }
15615
15972
  /** 轴复制会连带复制该轴全部交叉格,认证检查包含隐藏、超容量及其他关联区。 */
15616
- function authenticatedMatrixRow(options, axis, index) {
15973
+ function authenticatedMatrixRow(options, axis, index, onlyKind) {
15617
15974
  const data = options.runtime.dataManager, uid = data.getStoredValue(`${axis}[${index}].__gw_y_uid`);
15618
15975
  if (typeof uid !== "string" || !uid) return false;
15619
15976
  const records = /* @__PURE__ */ new Map(), paths = new JsonDataPaths();
15620
15977
  for (const { field, binding } of options.runtime.query.structuralFields()) {
15621
15978
  const kind = authenticationKind(field.widget, binding.source.fieldType);
15622
- if (!kind || !binding.pathTemplate.startsWith(axis + ":")) continue;
15979
+ if (!kind || onlyKind && kind !== onlyKind || !binding.pathTemplate.startsWith(axis + ":")) continue;
15623
15980
  const match = /^([^.[\]:]+)\[n_y\]\[n_x\](\..+)$/.exec(binding.pathTemplate.slice(axis.length + 1));
15624
15981
  if (!match) continue;
15625
15982
  const key = axis + ":" + match[1];
@@ -15694,7 +16051,7 @@ function planQuickFillMatrix(options, state, origin, matrix, indexes) {
15694
16051
  const rows = /* @__PURE__ */ new Map();
15695
16052
  for (const [y, values] of matrix.entries()) for (const [x, value] of values.entries()) {
15696
16053
  const physicalRow = cell.rowIndex + (fixed ? y : 0), physicalColumn = cell.columnIndex + x, target = grid.cells[physicalRow]?.[physicalColumn];
15697
- if (!target || physicalRow > region.bottom || physicalColumn > region.right || target.merge) throw Error("粘贴超出业务区域或触及合并格");
16054
+ if (!target || physicalRow > region.bottom || physicalColumn > region.right || target.merge) throw Error("粘贴超出表格区域或触及合并格");
15698
16055
  const placement = projection?.cells.get(target.cellId), slot = fixed ? placement?.slot : start + y;
15699
16056
  if (slot === void 0 || fixed && placement?.regionId !== state.regionId) throw Error("粘贴位置没有实际业务槽位");
15700
16057
  const cells = rows.get(slot) ?? [];
@@ -15746,6 +16103,92 @@ function quickFillInput(column, value) {
15746
16103
  if (column.kind === "choice" && column.multiple) return (Array.isArray(value) ? value : typeof value === "string" ? value.split(/[;,]/).map((token) => token.trim()).filter(Boolean) : [value]).map((token) => optionValue(column, token));
15747
16104
  return optionValue(column, value);
15748
16105
  }
16106
+ // src/runtime/form/business/signatures/device-signature-lock.ts
16107
+ /** @file 固定表与普通动态表签名锁由当前模型配置和权威填写值派生。 */
16108
+ /** 按模型版本缓存声明;权限每次从当前行读取,签名确认和撤销立即可见。 */
16109
+ function createDeviceSignatureLocks(handle, data, environment) {
16110
+ let revision = -1;
16111
+ let rules = [];
16112
+ function current() {
16113
+ const next = handle.getModelRevision();
16114
+ if (revision === next) return rules;
16115
+ const { query } = handle.readModel();
16116
+ rules = query.findEntities({ roles: ["region"] }).flatMap(({ id }) => {
16117
+ const region = query.getEntity(id, "region");
16118
+ const axis = region?.binding?.pathTemplate;
16119
+ const control = region?.config?.dataLockControlField;
16120
+ if (region?.type !== "bounded" && (region?.type !== "repeating" || !!region.variant?.name) || !axis || !/^\$\.[^.[\]:]+$/.test(axis) || typeof control !== "string" || !control || region.type === "bounded" && control !== "inspector_" && control !== "reviewer_") return [];
16121
+ const fields = region.type === "bounded" ? region.config?.mainFieldBindings : void 0;
16122
+ const excluded = region.config?.excludedFields;
16123
+ return [{
16124
+ axis,
16125
+ control,
16126
+ mainFields: Array.isArray(fields) ? fields.filter((key) => typeof key === "string") : [],
16127
+ excludedFields: Array.isArray(excluded) ? excluded.filter((key) => typeof key === "string") : []
16128
+ }];
16129
+ });
16130
+ revision = next;
16131
+ return rules;
16132
+ }
16133
+ function withinRow(path) {
16134
+ const match = /^(\$\.[^.[\]:]+)\[(\d+)\]\.(.+)$/.exec(path);
16135
+ if (!match) return;
16136
+ const matches = current().filter(({ axis }) => axis === match[1]);
16137
+ return matches.length ? {
16138
+ rules: matches,
16139
+ row: match[1] + "[" + match[2] + "]",
16140
+ field: match[3]
16141
+ } : void 0;
16142
+ }
16143
+ function signed(rule, row) {
16144
+ if (data.getStoredValue(row + ".deleted_")) return false;
16145
+ const value = data.getStoredValue(row + "." + rule.control);
16146
+ return hasAuthenticationValue("signature", typeof value === "string" ? value.trim() : value);
16147
+ }
16148
+ return {
16149
+ /** 例外字段不解除整行锁;菜单和执行入口共用同一判断。 */
16150
+ rowLocked(axis, index) {
16151
+ if (environment().formChangeEditing || !Number.isSafeInteger(index) || index < 0) return false;
16152
+ return current().some((rule) => rule.axis === axis && signed(rule, `${axis}[${index}]`));
16153
+ },
16154
+ /** 给公共字段状态提供强制只读和禁用标记。 */
16155
+ flags(path) {
16156
+ if (environment().formChangeEditing) return {};
16157
+ const target = withinRow(path);
16158
+ if (target) {
16159
+ let readonly = false;
16160
+ let disabled = false;
16161
+ for (const rule of target.rules) {
16162
+ if (!signed(rule, target.row)) continue;
16163
+ if (target.field === rule.control) readonly = true;
16164
+ else disabled ||= !rule.excludedFields.includes(target.field);
16165
+ }
16166
+ return {
16167
+ readonly,
16168
+ disabled
16169
+ };
16170
+ }
16171
+ const mainKey = /^\$\.([^.[\]:]+)$/.exec(path)?.[1];
16172
+ if (mainKey && current().some((rule) => rule.mainFields.includes(mainKey) && data.getActiveSubtableRowIndexes(rule.axis).some((index) => signed(rule, rule.axis + "[" + index + "]")))) return { disabled: true };
16173
+ return {};
16174
+ },
16175
+ /** 第一次控制签名前检查参与校验的绑定主字段和同行路径。 */
16176
+ validationPaths(path, candidates) {
16177
+ if (environment().formChangeEditing) return [];
16178
+ const target = withinRow(path);
16179
+ if (!target || data.getStoredValue(target.row + ".deleted_")) return [];
16180
+ const rules = target.rules.filter((rule) => target.field === rule.control && !signed(rule, target.row));
16181
+ if (!rules.length) return [];
16182
+ const paths = /* @__PURE__ */ new Set();
16183
+ const allCandidates = [...candidates()];
16184
+ for (const rule of rules) {
16185
+ for (const key of rule.mainFields) if (key) paths.add("$." + key);
16186
+ for (const candidate of allCandidates) if (candidate !== path && candidate.startsWith(target.row + ".") && !rule.excludedFields.includes(candidate.slice(target.row.length + 1))) paths.add(candidate);
16187
+ }
16188
+ return [...paths];
16189
+ }
16190
+ };
16191
+ }
15749
16192
  // src/runtime/form/business/tables/NativeTableQuickFill.ts
15750
16193
  /** @file 动态表从当前行、固定表按实际组编辑的原生批量输入;不创建第二份 model 或仓库。 */
15751
16194
  /** 读取仅投影列与数量;提交预检整批,再一次进入唯一 DataManager。 */
@@ -15787,6 +16230,7 @@ var NativeTableQuickFill = class {
15787
16230
  columns.push(column);
15788
16231
  }
15789
16232
  const limit = table.type === "bounded" ? table.capacity ?? 0 : 200, configured = region.config?.quickFill === true;
16233
+ const signatureLocked = region.type === "repeating" && !region.variant?.name && table.rowIndex !== void 0 && createDeviceSignatureLocks(options.handle, options.runtime.dataManager, options.environment).rowLocked(table.axisPath, table.rowIndex);
15790
16234
  const allowed = options.permission?.({
15791
16235
  operation: "quick-fill",
15792
16236
  regionId,
@@ -15801,7 +16245,7 @@ var NativeTableQuickFill = class {
15801
16245
  ...layout ? { layout } : {},
15802
16246
  columns,
15803
16247
  limit,
15804
- enabled: configured && entryEditable && columns.length > 0 && limit > 0 && allowed !== false && (table.type === "bounded" || table.rowCount === 0 || table.rowIndex !== void 0) && isEqual(table.version, options.handle.getVersions())
16248
+ enabled: configured && !signatureLocked && entryEditable && columns.length > 0 && limit > 0 && allowed !== false && (table.type === "bounded" || table.rowCount === 0 || table.rowIndex !== void 0) && isEqual(table.version, options.handle.getVersions())
15805
16249
  };
15806
16250
  const result = copyInputData(state);
15807
16251
  freezeData(result);
@@ -15867,7 +16311,11 @@ var NativeTableQuickFill = class {
15867
16311
  /** 将原有表级授权、字段规范化、后端编码和一次轴写入供两个入口共用。 */
15868
16312
  commit(options, state, declarations, activeCount, plan) {
15869
16313
  const data = options.runtime.dataManager, patches = [], append = [], paths = new JsonDataPaths(), columns = new Map(state.columns.map((column) => [column.key, column])), model = options.handle.readModel().query, cellIds = /* @__PURE__ */ new Map();
16314
+ const region = model.getEntity(state.regionId, "region");
16315
+ const ordinaryDynamic = region?.type === "repeating" && !region.variant?.name;
16316
+ const locks = createDeviceSignatureLocks(options.handle, data, options.environment);
15870
16317
  for (const [rowOrdinal, { index, existing, values: entries }] of plan.entries()) {
16318
+ if (existing && ordinaryDynamic && locks.rowLocked(state.axisPath, index)) continue;
15871
16319
  const values = {}, rowPath = `${state.axisPath}[${index}]`;
15872
16320
  if (data.getStoredValue(`${state.axisPath}[${index}].deleted_`) === true && existing) throw Error("已删除行不能快速填写");
15873
16321
  const grant = options.permission?.({
@@ -15919,11 +16367,11 @@ var NativeTableQuickFill = class {
15919
16367
  }
15920
16368
  if (state.capacity !== void 0 && activeCount + append.length > state.capacity) throw Error("本次填报超过固定区域容量");
15921
16369
  if (this.options !== options || options.handle.status === "closed" || options.environment().mode !== "fill" || !isEqual(state.version, options.handle.getVersions())) throw Error("快速填报来源已变化,请重新打开");
15922
- data.applySubtableRows(state.axisPath, patches, append);
16370
+ if (patches.length || append.length) data.applySubtableRows(state.axisPath, patches, append);
15923
16371
  return Object.freeze({
15924
16372
  operation: "quick-fill",
15925
16373
  regionId: state.regionId,
15926
- count: plan.length,
16374
+ count: patches.length + append.length,
15927
16375
  updatedRows: patches.length,
15928
16376
  insertedRows: append.length
15929
16377
  });
@@ -16687,7 +17135,7 @@ var NativeBusinessTables = class {
16687
17135
  if (!declaration) return;
16688
17136
  const matrix = region.type === "2d-table" ? matrixAxes(region) : void 0;
16689
17137
  const axisPath = matrix?.primary ?? region.binding?.pathTemplate;
16690
- if (!axisPath || !/^\$\.[^.[\]:]+$/.test(axisPath)) throw Error("业务区域没有有效的单轴路径");
17138
+ if (!axisPath || !/^\$\.[^.[\]:]+$/.test(axisPath)) throw Error("表格区域没有有效的单轴路径");
16691
17139
  if (index !== void 0 && (!Number.isSafeInteger(index) || index < 0)) throw Error("业务行下标无效");
16692
17140
  const version = handle.getVersions(), data = runtime.dataManager, indexes = data.getActiveSubtableRowIndexes(axisPath), rowOrdinal = index === void 0 ? -1 : indexes.indexOf(index), rowIndex = rowOrdinal < 0 ? void 0 : index, rowPath = rowIndex === void 0 ? void 0 : `${axisPath}[${rowIndex}]`, fields = tableRowFields(options, declaration.tableId, regionId, axisPath), pending = !runtime.isSettled();
16693
17141
  const probe = index ?? indexes[0] ?? 0;
@@ -16708,10 +17156,13 @@ var NativeBusinessTables = class {
16708
17156
  }));
16709
17157
  }) : [];
16710
17158
  const editable = options.environment().mode === "fill" && !pending && participation && data.getStoredValue(`${axisPath}[${probe}].deleted_`) !== true && (fields.some((field) => options.fields.state(field.field.id, rowFieldPath(field, axisPath, probe)).editable) || matrixFields.some(({ field, path }) => options.fields.state(field.field.id, path).editable));
17159
+ const signatureLocked = region.type === "repeating" && !region.variant?.name && rowIndex !== void 0 && createDeviceSignatureLocks(handle, data, options.environment).rowLocked(axisPath, rowIndex);
17160
+ const prospectiveIndex = (indexes.at(-1) ?? -1) + 1;
17161
+ const increasable = editable || signatureLocked && options.environment().mode === "fill" && !pending && participation && fields.some((field) => tableFieldInputAllowed(options, field.field.id, rowFieldPath(field, axisPath, prospectiveIndex), false));
16711
17162
  const capacity = region.type === "bounded" ? runtime.query.boundedTable(declaration.tableId)?.capacities.get(region.id) : void 0;
16712
17163
  const room = capacity === void 0 || indexes.length < capacity;
16713
17164
  const matrixAuthenticated = !!matrix && rowIndex !== void 0 && authenticatedMatrixRow(options, axisPath, rowIndex);
16714
- const removalBlockedReason = rowIndex !== void 0 && (authenticatedRow(options, fields, axisPath, rowIndex) || matrixAuthenticated || matrixFields.some(({ field, path }) => {
17165
+ const removalBlockedReason = rowIndex !== void 0 && (signatureLocked || authenticatedRow(options, fields, axisPath, rowIndex) || matrixAuthenticated || matrixFields.some(({ field, path }) => {
16715
17166
  const kind = authenticationKind(field.field.widget, field.binding.source.fieldType);
16716
17167
  return !!kind && hasAuthenticationValue(kind, data.getStoredValue(path));
16717
17168
  })) ? "当前行已有签名或印章认证,请先按认证规则处理" : void 0;
@@ -16729,8 +17180,8 @@ var NativeBusinessTables = class {
16729
17180
  };
16730
17181
  const allowed = {
16731
17182
  ...region.variant?.name === "edhr:material-substitution" ? { batchInsert: false } : {},
16732
- insert: editable && room && permit("insert"),
16733
- copy: editable && !matrixAuthenticated && room && rowIndex !== void 0 && tableRowCopyAllowed(region.variant?.name) && permit("copy"),
17183
+ insert: increasable && room && permit("insert"),
17184
+ copy: increasable && !(matrixAuthenticated && authenticatedMatrixRow(options, axisPath, rowIndex, "seal")) && room && rowIndex !== void 0 && tableRowCopyAllowed(region.variant?.name) && permit("copy"),
16734
17185
  remove: editable && rowIndex !== void 0 && !removalBlockedReason && permit("remove")
16735
17186
  };
16736
17187
  if (!isEqual(version, handle.getVersions())) {
@@ -17320,7 +17771,7 @@ var DataDependencies = class {
17320
17771
  return activeRowIndexes(rows).map((index) => this.services.paths.read(rows[index], `$.${table[2]}`));
17321
17772
  }
17322
17773
  /** 注册一代可释放的规则,首次计算与后续依赖使用同一写回机制。 */
17323
- register(path, expression, scope, callback, signal) {
17774
+ register(path, expression, scope, callback, signal, options) {
17324
17775
  this.services.paths.parse(path);
17325
17776
  if (!scope) throw new Error("依赖注册必须指定所有者身份");
17326
17777
  if (!this.formula) throw new Error("未配置公式引擎");
@@ -17336,6 +17787,7 @@ var DataDependencies = class {
17336
17787
  controller: new AbortController(),
17337
17788
  evaluated: false,
17338
17789
  lastValue: void 0,
17790
+ compare: options?.compare,
17339
17791
  owner: this
17340
17792
  };
17341
17793
  /** 释放函数仅保留可清空槽,移除后不再持有数据模块。 */
@@ -17362,6 +17814,7 @@ var DataDependencies = class {
17362
17814
  node.owner = void 0;
17363
17815
  node.callback = void 0;
17364
17816
  node.lastValue = void 0;
17817
+ node.lastInputs = void 0;
17365
17818
  node.controller.abort("dependency-disposed");
17366
17819
  node.releaseSignal?.();
17367
17820
  node.releaseSignal = void 0;
@@ -17372,6 +17825,8 @@ var DataDependencies = class {
17372
17825
  const dep = this.resolve(variable, node.path);
17373
17826
  return path === "$" || dep === "$" || areRelatedDataPaths(path, dep);
17374
17827
  })) {
17828
+ node.controller.abort("dependency-input-changed");
17829
+ node.controller = new AbortController();
17375
17830
  this.pending.add(node);
17376
17831
  if (!this.pendingSources.has(node) || source !== "hydrate") this.pendingSources.set(node, source);
17377
17832
  }
@@ -17404,12 +17859,13 @@ var DataDependencies = class {
17404
17859
  const value = await cancellable(Promise.resolve(formula.calculate(node.expression, cloneDeep(variables), signal)), signal);
17405
17860
  if (!current()) return;
17406
17861
  assertValidDataValue(value, path);
17407
- if (node.evaluated && isEqual$1(node.lastValue, value)) return;
17408
- const updates = await cancellable(Promise.resolve(node.callback?.(cloneDeep(value), path)), signal);
17862
+ if (node.evaluated && node.compare !== "none" && (node.compare === "inputs" ? isEqual$1(node.lastInputs, variables) : isEqual$1(node.lastValue, value))) return;
17863
+ const updates = await cancellable(Promise.resolve(node.callback?.(cloneDeep(value), path, cloneDeep(variables))), signal);
17409
17864
  if (!current()) return;
17410
17865
  if (updates) assertValidDataValue(updates);
17411
17866
  node.evaluated = true;
17412
17867
  node.lastValue = cloneDeep(value);
17868
+ if (node.compare === "inputs") node.lastInputs = cloneDeep(variables);
17413
17869
  if (updates) this.services.values.setMany(updates, source === "hydrate" ? "hydrate" : "dependency");
17414
17870
  } catch (error) {
17415
17871
  if (!(error instanceof DataCancelled) && current()) throw error;
@@ -17441,6 +17897,7 @@ var DataDependencies = class {
17441
17897
  node.controller = new AbortController();
17442
17898
  node.evaluated = false;
17443
17899
  node.lastValue = void 0;
17900
+ node.lastInputs = void 0;
17444
17901
  }
17445
17902
  this.pending.clear();
17446
17903
  this.pendingSources.clear();
@@ -17710,8 +18167,9 @@ var DataMatrix = class {
17710
18167
  for (const entry of this.crossKeys(tableKey).filter((entry) => entry.axis === axis)) {
17711
18168
  const cells = this.services.values.raw[entry.key];
17712
18169
  if (!Array.isArray(cells)) continue;
18170
+ const paths = this.services.lifetime.host?.collectNonCopyableFieldPaths?.(entry.key) ?? [];
17713
18171
  const copies = cells.filter((cell) => isRecord(cell) && cell[uidField] === oldUid).map((cell) => {
17714
- const copy = cloneDeep(cell);
18172
+ const copy = cloneCopiedRow(cell, paths);
17715
18173
  copy[uidField] = newUid;
17716
18174
  delete copy.id_;
17717
18175
  delete copy.front_row_key_;
@@ -18582,8 +19040,8 @@ var DataManager = class {
18582
19040
  await services.changes.whenSettled();
18583
19041
  }
18584
19042
  /** 注册可等待、可取消的公式,回调收到移动后的目标路径。 */
18585
- registerScopedFieldDependency(path, expression, scope, callback, signal) {
18586
- return this.active().dependencies.register(canonicalPath(path), expression, scope, callback, signal);
19043
+ registerScopedFieldDependency(path, expression, scope, callback, signal, options) {
19044
+ return this.active().dependencies.register(canonicalPath(path), expression, scope, callback, signal, options);
18587
19045
  }
18588
19046
  /** 重新计算所有已注册公式,并等待其产生的数据批次。 */
18589
19047
  async flushAllFieldDependencies() {
@@ -18621,6 +19079,45 @@ var DataManager = class {
18621
19079
  }
18622
19080
  };
18623
19081
  // src/runtime/form/fields/core/declaration-changes.ts
19082
+ /** @file 判断原生事务是否改变数据声明,普通文字和绘制样式不重建规则或重跑请求。 */
19083
+ /** 只影响绘制或输入提示;默认值、权限、校验、选项标签及未知配置仍重建业务规则。 */
19084
+ var appearanceKeys = /* @__PURE__ */ new Set([
19085
+ "viewState",
19086
+ "showMode",
19087
+ "placeholder",
19088
+ "designPlaceholder",
19089
+ "emptySymbol",
19090
+ "keepExceptionHighlight"
19091
+ ]);
19092
+ var presentationKeys = /* @__PURE__ */ new Set([
19093
+ "renderAs",
19094
+ "direction",
19095
+ "labelPosition",
19096
+ "iconLabelSpacePx",
19097
+ "optionSpacingPx"
19098
+ ]);
19099
+ function configObject(value) {
19100
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
19101
+ }
19102
+ /** 只比较事务携带的局部前后值;不扫描文档,也不把 null/false/缺省合并。 */
19103
+ function sameDataConfig(before, after, visualKeys) {
19104
+ return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].every((key) => {
19105
+ if (visualKeys.has(key)) return true;
19106
+ if (key === "presentation" && visualKeys === appearanceKeys) {
19107
+ const left = before[key] === void 0 ? {} : configObject(before[key]);
19108
+ const right = after[key] === void 0 ? {} : configObject(after[key]);
19109
+ if (left && right) return sameDataConfig(left, right, presentationKeys);
19110
+ }
19111
+ return Object.hasOwn(before, key) === Object.hasOwn(after, key) && isEqual(before[key], after[key]);
19112
+ });
19113
+ }
19114
+ function appearanceOnly(operation, query) {
19115
+ const field = query?.getEntity(operation.nodeId, "field");
19116
+ if (!field || !commonFieldWidgets.some((widget) => widget === field.widget)) return false;
19117
+ const before = operation.before.present ? configObject(operation.before.value) : {};
19118
+ const after = operation.after.present ? configObject(operation.after.value) : {};
19119
+ return !!before && !!after && sameDataConfig(before, after, appearanceKeys);
19120
+ }
18624
19121
  /** 检查结构日志中的局部子树,不读取或复制整份文档。 */
18625
19122
  function containsDataDeclaration(value) {
18626
19123
  if (!value || typeof value !== "object") return false;
@@ -18631,30 +19128,32 @@ function containsDataDeclaration(value) {
18631
19128
  return Object.values(object).some(containsDataDeclaration);
18632
19129
  }
18633
19130
  /** 绑定、业务配置和表格结构需要刷新,文字及绘制属性沿用当前数据规则。 */
18634
- function affectsNativeDataDeclarations(change) {
19131
+ function affectsNativeDataDeclarations(change, query) {
18635
19132
  return change.operations.some((operation) => {
18636
19133
  switch (operation.kind) {
18637
19134
  case "text": return false;
18638
19135
  case "dictionary": return operation.dictionary === "bindings";
18639
19136
  case "business": return true;
18640
- case "set": return [
18641
- "bindingId",
18642
- "binding",
18643
- "widget",
18644
- "config",
18645
- "configVersion",
18646
- "variant",
18647
- "policy",
18648
- "type",
18649
- "range",
18650
- "parentRegionId",
18651
- "targetRegionId",
18652
- "when",
18653
- "headerSlots",
18654
- "footerSlots",
18655
- "page",
18656
- "settings"
18657
- ].includes(operation.key);
19137
+ case "set":
19138
+ if (operation.key === "config" && appearanceOnly(operation, query)) return false;
19139
+ return [
19140
+ "bindingId",
19141
+ "binding",
19142
+ "widget",
19143
+ "config",
19144
+ "configVersion",
19145
+ "variant",
19146
+ "policy",
19147
+ "type",
19148
+ "range",
19149
+ "parentRegionId",
19150
+ "targetRegionId",
19151
+ "when",
19152
+ "headerSlots",
19153
+ "footerSlots",
19154
+ "page",
19155
+ "settings"
19156
+ ].includes(operation.key);
18658
19157
  case "splice": {
18659
19158
  const payload = operation;
18660
19159
  return [
@@ -18952,7 +19451,7 @@ var NativeDataQuery = class {
18952
19451
  this.matrixTables.clear();
18953
19452
  this.matrixDesignSlots.clear();
18954
19453
  this.matrixSources.clear();
18955
- if (affectsNativeDataDeclarations(change)) this.policies = void 0;
19454
+ if (affectsNativeDataDeclarations(change, handle.readModel().query)) this.policies = void 0;
18956
19455
  });
18957
19456
  }
18958
19457
  /** 枚举静态字段,覆盖正文、共享部件、浮层和附属内容;不等同于当前可见实例。 */
@@ -19405,8 +19904,10 @@ var CommonFieldRules = class {
19405
19904
  generation = 0;
19406
19905
  /** 系统默认值按字段及配置缓存,避免普通输入导致时钟变化。 */
19407
19906
  systemDefaults = /* @__PURE__ */ new Map();
19408
- /** 以稳定业务行身份保存赋值所有权,插行或换序不会套用到其他行。 */
19907
+ /** 以稳定业务行身份保存手填保护,插行或换序不会套用到其他行。 */
19409
19908
  assignmentMarks = /* @__PURE__ */ new Map();
19909
+ /** 仅缓存实际公式输入,规则重建继续沿用;整份数据恢复时清除。 */
19910
+ assignmentEvaluations = /* @__PURE__ */ new Map();
19410
19911
  /** 只保存注入能力。 */
19411
19912
  constructor(options) {
19412
19913
  this.options = options;
@@ -19439,18 +19940,22 @@ var CommonFieldRules = class {
19439
19940
  }
19440
19941
  /** 当前普通输入不重建全部字段,根/行身份/控制值变化才失效目标集合。 */
19441
19942
  dataChanged(path, source) {
19943
+ if (path === "$") {
19944
+ this.assignmentMarks.clear();
19945
+ this.assignmentEvaluations.clear();
19946
+ }
19442
19947
  const scope = this.scope;
19443
19948
  if (!scope) return path === "$";
19444
- if (source === "user" && scope.assignments.has(path)) {
19445
- const key = this.assignmentIdentity(path);
19446
- const previous = this.assignmentMarks.get(key) ?? {};
19447
- this.assignmentMarks.set(key, {
19448
- ...previous,
19449
- userEdited: true
19450
- });
19451
- }
19949
+ if (source === "user" && scope.assignments.has(path)) this.markAssignmentEdit(path, this.requireOptions().dataManager.getStoredValue(path));
19452
19950
  return path === "$" || [...scope.controls].some((control) => isSameOrDescendantPath(control, path)) || [...scope.axes].some((axis) => nativeAxisChanged(path, axis));
19453
19951
  }
19952
+ /** 所有用户写入共用空值语义,0 和 false 不解除保护。 */
19953
+ markAssignmentEdit(path, value) {
19954
+ this.assignmentMarks.set(this.assignmentIdentity(path), {
19955
+ userEdited: !isEmptyDataValue(value, { whitespace: "empty" }),
19956
+ permanentlyEdited: true
19957
+ });
19958
+ }
19454
19959
  /** 主表按路径、行字段按稳定行键识别赋值所有权。 */
19455
19960
  assignmentIdentity(path) {
19456
19961
  const options = this.requireOptions();
@@ -19488,17 +19993,23 @@ var CommonFieldRules = class {
19488
19993
  try {
19489
19994
  const declarations = sortBy$1(options.query.structuralFields(), [(item) => options.query.attachmentConditions(item.field.id).length]);
19490
19995
  const retained = /* @__PURE__ */ new Set();
19996
+ const retainedRules = /* @__PURE__ */ new Set();
19491
19997
  const dateKeys = /* @__PURE__ */ new Set();
19492
19998
  for (const declaration of declarations) {
19493
19999
  for (const path of options.query.fieldTargets(declaration.field.id, {
19494
20000
  readValue: (key) => options.dataManager.get(key),
19495
20001
  readAxis: (key) => options.dataManager.getStoredValue(key),
19496
20002
  includeInactive: true
19497
- }).paths) retained.add(this.assignmentIdentity(path));
20003
+ }).paths) {
20004
+ const identity = this.assignmentIdentity(path);
20005
+ retained.add(identity);
20006
+ if (fieldConfig(declaration).dependencies?.some((rule) => rule.effect === "assignment" && rule.assignmentType !== "clear")) retainedRules.add(targetKey(declaration.field.id, identity));
20007
+ }
19498
20008
  const dateKey = this.systemKey(declaration);
19499
20009
  if (dateKey) dateKeys.add(dateKey);
19500
20010
  }
19501
20011
  for (const key of this.assignmentMarks.keys()) if (!retained.has(key)) this.assignmentMarks.delete(key);
20012
+ for (const key of this.assignmentEvaluations.keys()) if (!retainedRules.has(key)) this.assignmentEvaluations.delete(key);
19502
20013
  for (const key of this.systemDefaults.keys()) if (!dateKeys.has(key)) this.systemDefaults.delete(key);
19503
20014
  const groups = groupBy$1(declarations, (item) => options.query.attachmentConditions(item.field.id).length);
19504
20015
  for (const group of Object.values(groups)) {
@@ -19579,9 +20090,9 @@ var CommonFieldRules = class {
19579
20090
  if (!dependency.expression || dependency.effect !== "assignment" && dependency.value !== true || mode === "edit" || (mode === "print" || mode === "readonly") && dependency.effect === "assignment") continue;
19580
20091
  if (dependency.effect === "required" && config.required === true || dependency.effect === "disabled" && config.disabled === true) continue;
19581
20092
  if (dependency.effect === "assignment" && ["seal", "signature"].includes(declaration.field.widget)) continue;
19582
- if (dependency.effect === "assignment") {
20093
+ if (dependency.effect === "assignment" && dependency.assignmentType !== "clear") {
19583
20094
  scope.assignments.add(path);
19584
- if (dependency.strategy === "alwaysCover") scope.assigned.add(path);
20095
+ if ((dependency.strategy ?? "alwaysCover") === "alwaysCover") scope.assigned.add(path);
19585
20096
  }
19586
20097
  const registration = options.dataManager.registerScopedFieldDependency(path, dependency.expression, JSON.stringify([
19587
20098
  "field",
@@ -19589,27 +20100,57 @@ var CommonFieldRules = class {
19589
20100
  declaration.field.id,
19590
20101
  path,
19591
20102
  index
19592
- ]), (value, currentPath) => this.apply(declaration, dependency, currentPath, value, scope, options), scope.signal);
20103
+ ]), (value, currentPath, variables) => this.apply(declaration, dependency, currentPath, value, scope, options, variables), scope.signal, dependency.effect === "assignment" ? { compare: dependency.assignmentType === "clear" ? "none" : "inputs" } : void 0);
19593
20104
  scope.registrations.push(registration);
19594
20105
  await registration.ready;
19595
20106
  }
19596
20107
  }
19597
20108
  /** 赋值写回唯一数据仓库;显示联动按字段实例隔离,避免共享绑定串状态。 */
19598
- apply(declaration, dependency, path, value, scope, options) {
20109
+ apply(declaration, dependency, path, value, scope, options, variables) {
19599
20110
  if (!this.current(scope)) return;
19600
20111
  if (dependency.effect === "assignment") {
20112
+ if (dependency.assignmentType === "clear") {
20113
+ if (!(readDataBoolean(value) ?? !!value)) return;
20114
+ return { [path]: this.normalize(declaration, emptyDataValue(), path) };
20115
+ }
20116
+ const key = this.assignmentIdentity(path);
20117
+ const ruleKey = targetKey(declaration.field.id, key);
20118
+ const previous = this.assignmentEvaluations.get(ruleKey);
20119
+ const initial = !previous || previous.expression !== dependency.expression || previous.strategy !== dependency.strategy;
20120
+ const next = {
20121
+ expression: dependency.expression,
20122
+ strategy: dependency.strategy,
20123
+ inputs: cloneDeep(variables)
20124
+ };
20125
+ const stored = options.dataManager.getStoredValue(path);
20126
+ if (initial) {
20127
+ if (dependency.strategy === "notCoveredForever" && !isEmptyDataValue(stored, { whitespace: "empty" })) {
20128
+ const mark = this.assignmentMarks.get(key);
20129
+ this.assignmentMarks.set(key, {
20130
+ ...mark,
20131
+ permanentlyEdited: true
20132
+ });
20133
+ }
20134
+ if (!isUninitializedDataValue(stored)) {
20135
+ this.assignmentEvaluations.set(ruleKey, next);
20136
+ return;
20137
+ }
20138
+ } else if (isEqual$1(previous.inputs, variables)) return;
19601
20139
  if (resolveDataValueUpdate({
19602
20140
  present: true,
19603
20141
  value
19604
- }, options.dataManager.getStoredValue(path), { intent: "patch" }, path).action === "skip") return;
19605
- const key = this.assignmentIdentity(path);
20142
+ }, stored, { intent: "patch" }, path).action === "skip") {
20143
+ this.assignmentEvaluations.set(ruleKey, next);
20144
+ return;
20145
+ }
19606
20146
  const mark = this.assignmentMarks.get(key);
19607
- if (dependency.strategy === "notCovered" && (mark?.userEdited || !isUninitializedDataValue(options.dataManager.getStoredValue(path)) && mark?.owner !== declaration.field.id)) return;
19608
- this.assignmentMarks.set(key, {
19609
- ...mark,
19610
- owner: declaration.field.id
19611
- });
19612
- return { [path]: this.normalize(declaration, value, path) };
20147
+ if (dependency.strategy === "notCovered" && mark?.userEdited || dependency.strategy === "notCoveredForever" && mark?.permanentlyEdited) {
20148
+ this.assignmentEvaluations.set(ruleKey, next);
20149
+ return;
20150
+ }
20151
+ const normalized = this.normalize(declaration, value, path);
20152
+ this.assignmentEvaluations.set(ruleKey, next);
20153
+ return { [path]: normalized };
19613
20154
  }
19614
20155
  const key = targetKey(declaration.field.id, path);
19615
20156
  const previous = scope.flags.get(key) ?? {};
@@ -19655,7 +20196,9 @@ var CommonFieldRules = class {
19655
20196
  present: true,
19656
20197
  value
19657
20198
  }, options.dataManager.getStoredValue(path), { intent: "patch" }, path).action === "skip") return false;
19658
- return options.dataManager.set(path, this.normalize(declaration, value, path), "user");
20199
+ const normalized = this.normalize(declaration, value, path);
20200
+ if (this.scope?.assignments.has(path)) this.markAssignmentEdit(path, normalized);
20201
+ return options.dataManager.set(path, normalized, "user");
19659
20202
  }
19660
20203
  /** 是否已有完整可发布的字段规则。 */
19661
20204
  isReady() {
@@ -19667,6 +20210,7 @@ var CommonFieldRules = class {
19667
20210
  this.options = void 0;
19668
20211
  this.systemDefaults.clear();
19669
20212
  this.assignmentMarks.clear();
20213
+ this.assignmentEvaluations.clear();
19670
20214
  }
19671
20215
  /** 关闭后拒绝旧业务门面的读写。 */
19672
20216
  requireOptions() {
@@ -19709,12 +20253,18 @@ function buildFieldEnrichers(query, data) {
19709
20253
  if (!isEmptyDataValue(change.newValue) || !isEqual$1(data.get(change.path), change.newValue)) return;
19710
20254
  const updates = companionUpdates(data, { [change.path]: change.newValue }, query);
19711
20255
  delete updates[change.path];
20256
+ const labelPath = data.getLabelPath(change.path);
20257
+ if (change.source === "hydrate" && isEqual$1(change.oldValue, change.newValue) && data.getStoredValue(labelPath) === null && Object.hasOwn(updates, labelPath) && updates[labelPath] === void 0 && query.valueBindings(change.path).some(({ fields }) => fields.some(({ field }) => (field.widget === "checkbox" || field.widget === "choice") && query.fieldTargets(field.id, {
20258
+ readValue: (path) => data.get(path),
20259
+ readAxis: (path) => data.getStoredValue(path),
20260
+ valuePath: change.path
20261
+ }).paths.length > 0))) delete updates[labelPath];
19712
20262
  return updates;
19713
20263
  }
19714
20264
  }, ...query.structuralFields().filter(({ field }) => field.widget === "choice" || field.widget === "checkbox").map((declaration) => ({
19715
20265
  id: `field-label:${declaration.field.id}`,
19716
20266
  /** 按实际路径约束坐标,不为每次单字段补全重新展开整轴。 */
19717
- matches: (path) => query.fieldTargets(declaration.field.id, {
20267
+ matches: (path) => (declaration.binding.pathTemplate.includes("[n") || declaration.binding.pathTemplate === path) && query.fieldTargets(declaration.field.id, {
19718
20268
  readValue: (key) => data.get(key),
19719
20269
  readAxis: (key) => data.getStoredValue(key),
19720
20270
  valuePath: path
@@ -19976,7 +20526,7 @@ var NativeDataRuntime = class {
19976
20526
  else if (!state.preparing) watchSettlement(reference, state);
19977
20527
  }));
19978
20528
  state.cleanups.push(state.handle.subscribeModel((change) => {
19979
- if (active(reference, state) && affectsNativeDataDeclarations(change)) refresh(reference, state);
20529
+ if (active(reference, state) && affectsNativeDataDeclarations(change, state.handle.readModel().query)) refresh(reference, state);
19980
20530
  }));
19981
20531
  state.cleanups.push(state.handle.subscribeChanges((change) => {
19982
20532
  if (active(reference, state) && change.kind === "environment" && change.reason === "mode") refresh(reference, state);
@@ -21728,7 +22278,7 @@ function protectedFillPaths(options, config) {
21728
22278
  for (const query of config.queries ?? []) for (const mapping of query.mappings ?? []) for (const field of mapping.fields ?? []) protect(mapping.modelKey || options.modelKey, mapping.subFieldKey, field.fieldKey);
21729
22279
  for (const declaration of options.runtime.query.structuralFields()) {
21730
22280
  const { field, binding } = declaration;
21731
- if (field.widget === "signature" || field.widget === "seal" || fieldConfig(declaration).dependencies?.some((rule) => rule.effect === "assignment" && rule.expression)) protectedPaths.add(logicalFillPath(binding.pathTemplate));
22281
+ if (field.widget === "signature" || field.widget === "seal" || fieldConfig(declaration).dependencies?.some((rule) => rule.effect === "assignment" && rule.assignmentType !== "clear" && rule.expression)) protectedPaths.add(logicalFillPath(binding.pathTemplate));
21732
22282
  if ((field.widget === "relation" || field.widget === "rdo-relation") && field.config?.autofill?.enabled) for (const rule of field.config.autofill.rules) protect(rule.target.modelKey || options.modelKey, rule.target.subFieldKey, rule.target.fieldKey);
21733
22283
  if (field.widget === "signature" && field.config?.autofill?.enabled) for (const rule of field.config.autofill.rules) protect(rule.target.modelKey || options.modelKey, rule.target.subFieldKey, rule.target.fieldKey);
21734
22284
  }
@@ -22055,7 +22605,7 @@ var NativeFieldFills = class {
22055
22605
  }));
22056
22606
  this.cleanups.push(options.runtime.dataManager.subscribeWrites((path) => this.formChanged(path)));
22057
22607
  this.cleanups.push(options.handle.subscribeModel((change) => {
22058
- if (affectsNativeDataDeclarations(change)) this.reconcile();
22608
+ if (affectsNativeDataDeclarations(change, options.handle.readModel().query)) this.reconcile();
22059
22609
  }));
22060
22610
  this.reconcile();
22061
22611
  }
@@ -26734,8 +27284,7 @@ var NativeReferences = class {
26734
27284
  } catch (error) {
26735
27285
  input = ["configuration", error instanceof Error ? error.message : String(error)];
26736
27286
  }
26737
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(input)));
26738
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
27287
+ return sha256(JSON.stringify(input));
26739
27288
  }
26740
27289
  /** 完整字段检查才调用当前记录来源;不写值,迟到结果仍受规则、实际行和调用方版本保护。 */
26741
27290
  async validateReference(fieldId, path, signal, withinBatch = false) {
@@ -27251,6 +27800,36 @@ var NativeSignatures = class {
27251
27800
  for (const attempt of this.attempts) this.release(attempt);
27252
27801
  });
27253
27802
  }
27803
+ /** 打开签名框前只校验字段;无校验路径时保持同步返回。 */
27804
+ validateBeforeOpen(fieldId, instance, signal) {
27805
+ signal.throwIfAborted();
27806
+ const options = this.requireOptions();
27807
+ const before = businessTarget(options.handle, options.rules, fieldId, instance);
27808
+ if (before.declaration.field.widget !== "signature" || !before.state.editable) throw new Error("当前签名不可编辑");
27809
+ const paths = options.validationPaths?.(before.valuePath) ?? [];
27810
+ if (!paths.length) return;
27811
+ if (!options.validatePaths) throw new Error("尚未接入签名前字段校验");
27812
+ const controller = new AbortController();
27813
+ const abort = () => this.release(attempt);
27814
+ const attempt = {
27815
+ before,
27816
+ instance,
27817
+ owners: recordTargetOwners(instance, options.runtime.dataManager),
27818
+ controller,
27819
+ validationPaths: paths,
27820
+ unlink: () => signal.removeEventListener("abort", abort)
27821
+ };
27822
+ this.attempts.add(attempt);
27823
+ if (signal.aborted) this.release(attempt);
27824
+ else signal.addEventListener("abort", abort, { once: true });
27825
+ return scopedDataRequest([controller.signal], async (currentSignal) => {
27826
+ await options.validatePaths(paths, currentSignal, before.valuePath);
27827
+ if (!this.current(attempt)) throw new Error("签名目标已经变化,请重新操作");
27828
+ }).catch((error) => {
27829
+ if (controller.signal.aborted) throw new Error("签名前检查已取消或数据已变化,请重新点击签名");
27830
+ throw error;
27831
+ }).finally(() => this.release(attempt));
27832
+ }
27254
27833
  /** 手动认证得到当前会话的不透明预览凭据,确认之前不写任何业务值。 */
27255
27834
  async prepare(fieldId, instance, signal, authorization) {
27256
27835
  const options = this.requireOptions(), before = businessTarget(options.handle, options.rules, fieldId, instance), field = before.declaration.field;
@@ -27274,7 +27853,7 @@ var NativeSignatures = class {
27274
27853
  else signal.addEventListener("abort", abort, { once: true });
27275
27854
  try {
27276
27855
  controller.signal.throwIfAborted();
27277
- if (attempt.validationPaths.length) await options.validatePaths?.(attempt.validationPaths, controller.signal);
27856
+ if (attempt.validationPaths.length) await options.validatePaths?.(attempt.validationPaths, controller.signal, before.valuePath);
27278
27857
  controller.signal.throwIfAborted();
27279
27858
  const result = await options.rules.authorizeSignature(fieldId, before.valuePath, controller.signal, ...authorization ? [authorization] : []);
27280
27859
  if (!this.current(attempt)) throw new Error("签署目标已经变化");
@@ -28671,7 +29250,7 @@ function resolveValidationAdmission(input) {
28671
29250
  // src/runtime/form/validation/targets.ts
28672
29251
  /** @file 校验目标直接从原生结构、条件和运行权限求得,不读取 pages 或构造 WidgetMeta。 */
28673
29252
  /** 展示沿用异常保留覆盖;其他模式沿用只读/禁用不进入校验门禁的既有规则。 */
28674
- function nativeValidationTargets(options, mode, paths, widgets, blockedOnly = false, includeRequired = false) {
29253
+ function nativeValidationTargets(options, mode, paths, widgets, blockedOnly = false, includeRequired = false, requiredPaths) {
28675
29254
  const entries = [];
28676
29255
  if (options.environment().mode === "edit") return { entries };
28677
29256
  const browsing = mode === "display";
@@ -28710,11 +29289,12 @@ function nativeValidationTargets(options, mode, paths, widgets, blockedOnly = fa
28710
29289
  if (!state.active || !state.visible || state.pending) continue;
28711
29290
  const effective = rules.declaration(declaration.field.id, path) ?? declaration, behavior = fieldBehavior(effective);
28712
29291
  if (widgets && !widgets.has(behavior.widget)) continue;
29292
+ const continueRequired = includeRequired || requiredPaths?.has(path) === true;
28713
29293
  const blocked = state.readonly || state.disabled;
28714
29294
  if (blockedOnly && !blocked) continue;
28715
29295
  const access = rules.accessState(declaration.field.id, path);
28716
29296
  if (!browsing && (access.readonly || access.disabled)) continue;
28717
- if (blocked && (mode === "change" || mode === "blur") && !includeRequired) continue;
29297
+ if (blocked && (mode === "change" || mode === "blur") && !continueRequired) continue;
28718
29298
  if (!browsing && recordReference(behavior) && !rules.referenceAvailable(declaration.field.id, path)) {
28719
29299
  entries.push({
28720
29300
  fieldId: declaration.field.id,
@@ -28781,7 +29361,7 @@ function nativeValidationTargets(options, mode, paths, widgets, blockedOnly = fa
28781
29361
  valuePath: path,
28782
29362
  value: data.get(path),
28783
29363
  state,
28784
- checkRequired: includeRequired || mode === "all" || mode === "manual" || mode === "display" && blocked,
29364
+ checkRequired: continueRequired || mode === "all" || mode === "manual" || mode === "display" && blocked,
28785
29365
  checkValue: mode !== "manual"
28786
29366
  });
28787
29367
  }
@@ -28814,6 +29394,8 @@ var NativeValidator = class {
28814
29394
  ].includes(mode)) throw new Error("原生校验模式无效");
28815
29395
  if (request.blockedOnly && mode !== "display") throw new Error("只读字段筛选仅用于展示校验");
28816
29396
  if (request.includeRequired !== void 0 && mode !== "change" && mode !== "blur") throw new Error("持续必填检查只能用于输入或失焦校验");
29397
+ if (request.requiredPaths !== void 0 && mode !== "change" && mode !== "blur") throw new Error("局部持续必填检查只能用于输入或失焦校验");
29398
+ const requiredPaths = request.requiredPaths === void 0 ? void 0 : new Set(request.requiredPaths);
28817
29399
  const draft = request.draft;
28818
29400
  if (draft && mode !== "change" && mode !== "blur") throw new Error("字段草稿只能用于输入或失焦校验");
28819
29401
  const paths = draft ? /* @__PURE__ */ new Set([draft.valuePath]) : request.paths === void 0 ? void 0 : new Set(request.paths);
@@ -28844,6 +29426,7 @@ var NativeValidator = class {
28844
29426
  draft ? [draft.fieldId, draft.valuePath] : "stored",
28845
29427
  request.blockedOnly,
28846
29428
  request.includeRequired,
29429
+ requiredPaths && [...requiredPaths].sort(),
28847
29430
  paths && [...paths].sort()
28848
29431
  ]), async (task) => {
28849
29432
  const controller = new AbortController();
@@ -28854,7 +29437,7 @@ var NativeValidator = class {
28854
29437
  request.signal?.addEventListener("abort", abort, { once: true });
28855
29438
  if (task.signal.aborted || this.lifetime.signal.aborted || request.signal?.aborted) abort();
28856
29439
  try {
28857
- const selection = nativeValidationTargets(options, mode, paths, draft ? /* @__PURE__ */ new Set(["number", "input"]) : request.widgets && new Set(request.widgets), request.blockedOnly, request.includeRequired), issues = [];
29440
+ const selection = nativeValidationTargets(options, mode, paths, draft ? /* @__PURE__ */ new Set(["number", "input"]) : request.widgets && new Set(request.widgets), request.blockedOnly, request.includeRequired, requiredPaths), issues = [];
28858
29441
  let targetCount = 0;
28859
29442
  for (const target of selection.entries) {
28860
29443
  if (controller.signal.aborted) throw new Error("原生校验已取消");
@@ -28956,6 +29539,7 @@ function attachSessionData(context, options = {}) {
28956
29539
  ...options,
28957
29540
  host: {
28958
29541
  ...host,
29542
+ collectNonCopyableFieldPaths: (tableKey) => [.../* @__PURE__ */ new Set([...collectNonCopyableFieldPaths(handle.readModel(), tableKey), ...host?.collectNonCopyableFieldPaths?.(tableKey) ?? []])],
28959
29543
  isActive: () => handle.status !== "closed" && (host?.isActive?.() ?? true),
28960
29544
  dataWritten: (path, source) => {
28961
29545
  handle.notifyData(source, [path]);
@@ -30461,68 +31045,6 @@ function referenceIdentityChanges(query, data, changes) {
30461
31045
  }
30462
31046
  return [...expanded.values()];
30463
31047
  }
30464
- // src/runtime/form/business/signatures/device-signature-lock.ts
30465
- /** @file 设备固定表签名锁由当前模型配置和权威填写值派生。 */
30466
- /** 按模型版本缓存声明;权限每次从当前行读取,签名确认和撤销立即可见。 */
30467
- function createDeviceSignatureLocks(handle, data, environment) {
30468
- let revision = -1;
30469
- let rules = [];
30470
- function current() {
30471
- const next = handle.getModelRevision();
30472
- if (revision === next) return rules;
30473
- const { query } = handle.readModel();
30474
- rules = query.findEntities({ roles: ["region"] }).flatMap(({ id }) => {
30475
- const region = query.getEntity(id, "region");
30476
- const axis = region?.binding?.pathTemplate;
30477
- const control = region?.config?.dataLockControlField;
30478
- if (region?.type !== "bounded" || !axis || !/^\$\.[^.[\]:]+$/.test(axis) || control !== "inspector_" && control !== "reviewer_") return [];
30479
- const fields = region.config?.mainFieldBindings;
30480
- return [{
30481
- axis,
30482
- control,
30483
- mainFields: Array.isArray(fields) ? fields.filter((key) => typeof key === "string") : []
30484
- }];
30485
- });
30486
- revision = next;
30487
- return rules;
30488
- }
30489
- function withinRow(path) {
30490
- const match = /^(\$\.[^.[\]:]+)\[(\d+)\]\.([^.[\]:]+)/.exec(path);
30491
- if (!match) return;
30492
- const rule = current().find(({ axis }) => axis === match[1]);
30493
- return rule ? {
30494
- rule,
30495
- row: match[1] + "[" + match[2] + "]",
30496
- field: match[3]
30497
- } : void 0;
30498
- }
30499
- function signed(rule, row) {
30500
- return hasAuthenticationValue("signature", data.getStoredValue(row + "." + rule.control));
30501
- }
30502
- return {
30503
- /** 给公共字段状态提供强制只读和禁用标记。 */
30504
- flags(path) {
30505
- if (environment().formChangeEditing) return {};
30506
- const target = withinRow(path);
30507
- if (target && signed(target.rule, target.row)) {
30508
- if (target.field !== target.rule.control) return { disabled: true };
30509
- const id = data.getStoredValue(target.row + ".id_");
30510
- return { readonly: typeof id === "string" && id.trim() !== "" || typeof id === "number" };
30511
- }
30512
- const mainKey = /^\$\.([^.[\]:]+)$/.exec(path)?.[1];
30513
- if (mainKey && current().some((rule) => rule.mainFields.includes(mainKey) && data.getActiveSubtableRowIndexes(rule.axis).some((index) => signed(rule, rule.axis + "[" + index + "]")))) return { disabled: true };
30514
- return {};
30515
- },
30516
- /** 第一次控制签名前检查参与校验的绑定主字段和同行路径。 */
30517
- validationPaths(path, candidates) {
30518
- const target = withinRow(path);
30519
- if (!target || target.field !== target.rule.control || signed(target.rule, target.row)) return [];
30520
- const paths = new Set(target.rule.mainFields.map((key) => "$." + key));
30521
- for (const candidate of candidates()) if (candidate !== path && candidate.startsWith(target.row + ".")) paths.add(candidate);
30522
- return [...paths];
30523
- }
30524
- };
30525
- }
30526
31048
  // src/runtime/form/business/tables/enrichers.ts
30527
31049
  /** @file 业务表派生接入现有数据队列,不在画布、组件或保存时另建计算。 */
30528
31050
  /** 只为原生物料/备件盘点区域注册规则;同名字段、普通表和其他业务变体不会被套用。 */
@@ -30955,6 +31477,8 @@ var NativeFieldValidation = class {
30955
31477
  failure;
30956
31478
  versions;
30957
31479
  listeners = /* @__PURE__ */ new Set();
31480
+ scopedRequired = /* @__PURE__ */ new Set();
31481
+ requiredScopes = /* @__PURE__ */ new Map();
30958
31482
  required = false;
30959
31483
  constructor(options) {
30960
31484
  this.options = options;
@@ -30970,10 +31494,13 @@ var NativeFieldValidation = class {
30970
31494
  this.stop = options.handle.subscribeChanges((change) => {
30971
31495
  if (change.kind === "environment" && change.reason !== "mode") return;
30972
31496
  if (change.kind === "model") {
31497
+ this.clearScopedRequired();
30973
31498
  this.referenceIssues = [];
30974
31499
  this.referenceKeys.clear();
30975
31500
  this.referenceVersions = void 0;
30976
- }
31501
+ } else if (change.kind === "environment") this.clearScopedRequired();
31502
+ else if (change.paths.includes("$")) this.clearScopedRequired();
31503
+ else this.pruneScopedRequired(change);
30977
31504
  this.request();
30978
31505
  });
30979
31506
  this.request();
@@ -30981,12 +31508,93 @@ var NativeFieldValidation = class {
30981
31508
  /** 明确完整检查后继续保留必填诊断,后续编辑自动清除已修正的问题。 */
30982
31509
  revealRequired() {
30983
31510
  this.required = true;
31511
+ this.clearScopedRequired();
30984
31512
  if (this.stop) this.request();
30985
31513
  }
30986
31514
  /** 活动草稿沿用已经启动的完整检查必填策略。 */
30987
31515
  get checksRequired() {
30988
31516
  return this.required;
30989
31517
  }
31518
+ checksRequiredFor(path) {
31519
+ return this.required || this.scopedRequired.has(path);
31520
+ }
31521
+ /** 主字段和同行字段共用触发签名所在行的生命周期。 */
31522
+ rememberScopedRequired(sourcePath, paths) {
31523
+ const data = this.options?.runtime.dataManager;
31524
+ const rowPath = /^(\$\.[^.[\]:]+\[\d+\])\./.exec(sourcePath)?.[1];
31525
+ if (!data || !rowPath || data.getStoredValue(rowPath + ".deleted_")) return;
31526
+ this.requiredScopes.set(sourcePath, {
31527
+ rowPath,
31528
+ owner: data.getValueIdentity(rowPath),
31529
+ paths: [...new Set(paths)]
31530
+ });
31531
+ this.pruneScopedRequired();
31532
+ }
31533
+ /** 行换位、替换或软删后丢弃旧范围,普通字段修改继续保留提示。 */
31534
+ pruneScopedRequired(change) {
31535
+ const data = this.options?.runtime.dataManager;
31536
+ if (!data) return;
31537
+ const previous = new Set(this.scopedRequired);
31538
+ this.scopedRequired.clear();
31539
+ for (const [source, scope] of this.requiredScopes) {
31540
+ if (change && !change.paths.some((path) => areRelatedDataPaths(path, scope.rowPath))) {
31541
+ for (const path of scope.paths) this.scopedRequired.add(path);
31542
+ continue;
31543
+ }
31544
+ const owner = data.getValueIdentity(scope.rowPath);
31545
+ const replacesRow = change?.paths.some((path) => isSameOrDescendantPath(scope.rowPath, path));
31546
+ const materializing = scope.owner === void 0 && owner !== void 0 && !replacesRow && change?.source === "user" && change.paths.some((path) => path.startsWith(scope.rowPath + ".") && ![
31547
+ "id_",
31548
+ "front_row_key_",
31549
+ "deleted_"
31550
+ ].includes(path.slice(scope.rowPath.length + 1)));
31551
+ if (scope.owner === void 0 && replacesRow || owner !== scope.owner && !materializing || data.getStoredValue(scope.rowPath + ".deleted_")) {
31552
+ this.requiredScopes.delete(source);
31553
+ continue;
31554
+ }
31555
+ if (materializing) this.requiredScopes.set(source, {
31556
+ ...scope,
31557
+ owner
31558
+ });
31559
+ for (const path of scope.paths) this.scopedRequired.add(path);
31560
+ }
31561
+ this.dropScopedReferences(new Set([...previous].filter((path) => !this.scopedRequired.has(path))));
31562
+ }
31563
+ dropScopedReferences(paths) {
31564
+ if (this.required || !paths.size) return;
31565
+ this.referenceIssues = this.referenceIssues.filter((issue) => {
31566
+ if (!paths.has(issue.valuePath)) return true;
31567
+ this.referenceKeys.delete(referenceKey(issue));
31568
+ return false;
31569
+ });
31570
+ this.referenceVersions = void 0;
31571
+ }
31572
+ clearScopedRequired() {
31573
+ this.dropScopedReferences(this.scopedRequired);
31574
+ this.requiredScopes.clear();
31575
+ this.scopedRequired.clear();
31576
+ }
31577
+ /** 接收本轮完整字段结果,只保存路径和诊断,不保存填写值。 */
31578
+ followScopedCheck(sourcePath, paths, result, versions) {
31579
+ const options = this.options;
31580
+ const current = options?.handle.getVersions();
31581
+ if (!options || options.handle.status === "closed" || options.environment().mode !== "fill" || result.mode !== "all" || result.status === "stale" || result.modelRevision !== versions.model || current?.model !== versions.model || current.data !== versions.data || current.environment !== versions.environment) return false;
31582
+ if (!this.required) this.rememberScopedRequired(sourcePath, paths);
31583
+ this.controller?.abort();
31584
+ const scope = new Set(paths);
31585
+ const incoming = result.issues.filter((issue) => scope.has(issue.valuePath));
31586
+ for (const issue of this.referenceIssues) if (scope.has(issue.valuePath)) this.referenceKeys.delete(referenceKey(issue));
31587
+ const references = incoming.filter((issue) => issue.referenceCheck);
31588
+ this.referenceIssues = [...this.referenceIssues.filter((issue) => !scope.has(issue.valuePath)), ...references];
31589
+ for (const issue of references) this.referenceKeys.set(referenceKey(issue), options.rules.references.validationFingerprint(issue.fieldId, issue.valuePath));
31590
+ this.referenceVersions = void 0;
31591
+ this.issues = [...this.isCurrent() ? this.issues.filter((issue) => !scope.has(issue.valuePath)) : [], ...incoming];
31592
+ this.failure = void 0;
31593
+ this.versions = versions;
31594
+ this.publish(result.status === "valid" ? void 0 : "check");
31595
+ this.request();
31596
+ return true;
31597
+ }
30990
31598
  /** 只接受同一代次真正执行过的完整字段检查;草稿、提前终止和取消不启用必填续查。 */
30991
31599
  followCompleteCheck(result) {
30992
31600
  const current = this.options?.handle.getVersions(), fields = result.checks.fields;
@@ -31038,6 +31646,7 @@ var NativeFieldValidation = class {
31038
31646
  if (!options) return;
31039
31647
  if (options.environment().mode === "edit") {
31040
31648
  this.required = false;
31649
+ this.clearScopedRequired();
31041
31650
  this.referenceIssues = [];
31042
31651
  this.referenceKeys.clear();
31043
31652
  this.referenceVersions = void 0;
@@ -31051,6 +31660,7 @@ var NativeFieldValidation = class {
31051
31660
  const [result, display] = await Promise.all([options.validator.validate({
31052
31661
  mode,
31053
31662
  includeRequired: this.required,
31663
+ requiredPaths: this.scopedRequired,
31054
31664
  signal: controller.signal
31055
31665
  }), options.validator.validate({
31056
31666
  mode: "display",
@@ -31143,14 +31753,18 @@ var NativeFieldValidation = class {
31143
31753
  }
31144
31754
  }
31145
31755
  }
31146
- publish() {
31147
- for (const listener of this.listeners) listener();
31756
+ publish(reason) {
31757
+ for (const listener of this.listeners) listener(reason);
31148
31758
  }
31149
31759
  /** 环境变化可重排,但模型或填写值换代后不能显示旧错误。 */
31150
31760
  message(fieldId, valuePath) {
31761
+ return this.messages(fieldId, valuePath).join(";") || void 0;
31762
+ }
31763
+ /** 每条诊断保持独立,界面不从文案中的标点反推规则边界。 */
31764
+ messages(fieldId, valuePath) {
31151
31765
  const options = this.options, versions = options?.handle.getVersions();
31152
- if (!options || !this.versions || versions?.data !== this.versions.data || versions.model !== this.versions.model) return;
31153
- return this.failure ?? (this.issues.filter((issue) => issue.fieldId === fieldId && issue.valuePath === valuePath).map((issue) => issue.message).join(";") || void 0);
31766
+ if (!options || !this.versions || versions?.data !== this.versions.data || versions.model !== this.versions.model) return [];
31767
+ return this.failure ? [this.failure] : this.issues.filter((issue) => issue.fieldId === fieldId && issue.valuePath === valuePath).map((issue) => issue.message);
31154
31768
  }
31155
31769
  async whenSettled() {
31156
31770
  await Promise.resolve();
@@ -31158,6 +31772,7 @@ var NativeFieldValidation = class {
31158
31772
  else await Promise.resolve();
31159
31773
  }
31160
31774
  dispose() {
31775
+ this.clearScopedRequired();
31161
31776
  this.options = void 0;
31162
31777
  this.stop?.();
31163
31778
  this.stop = void 0;
@@ -31394,13 +32009,16 @@ var NativeDataServices = class {
31394
32009
  const [_, axis, index] = row;
31395
32010
  return this.runtime.query.structuralFields().flatMap(({ binding }) => binding.pathTemplate.startsWith(axis + "[n].") ? [binding.pathTemplate.replace("[n]", "[" + index + "]")] : []);
31396
32011
  }),
31397
- validatePaths: async (paths, signal) => {
32012
+ validatePaths: async (paths, signal, sourcePath) => {
32013
+ await runtimeRequest(this.runtime.whenSettled(), signal);
32014
+ signal.throwIfAborted();
32015
+ const versions = handle.getVersions();
31398
32016
  const result = await this.validator.validate({
31399
32017
  paths,
31400
32018
  signal,
31401
32019
  mode: "all"
31402
32020
  });
31403
- if (result.status === "stale") throw new Error("相关字段已变化,请重新签名");
32021
+ if (signal.aborted || !this.fieldValidation.followScopedCheck(sourcePath, paths, result, versions)) throw new Error("相关字段已变化,请重新签名");
31404
32022
  if (result.status !== "valid") throw new Error(result.issues[0]?.message ?? "请先完成签名前的字段校验");
31405
32023
  }
31406
32024
  });
@@ -31721,6 +32339,7 @@ function fieldDecoration(state, printing, placeholder, textColor, optionLabel, v
31721
32339
  backgroundColor = optionLabel ? void 0 : colors.editable.background;
31722
32340
  }
31723
32341
  if (visual.hyperlink && !disabled) color = visual.validationError ? colors.validation.color : "#0000ff";
32342
+ if (optionLabel) color = disabled ? colors.disabled.color : textColor;
31724
32343
  const markerColor = printing ? colors.marker.default : disabled ? colors.marker.disabled : readonly && required ? colors.requiredReadonly.placeholderColor : readonly ? colors.marker.readonly : required ? colors.required.placeholderColor : colors.marker.default;
31725
32344
  return {
31726
32345
  color,
@@ -31760,16 +32379,16 @@ function optionPaint(state, selected) {
31760
32379
  var attachmentIconUrl = "data:image/svg+xml;base64,PHN2ZyB0PSIxNzg2MDkyOTgzMzc1IiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjM0MDM2IiB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48cGF0aCBkPSJNNjc1LjY5MzcxNCAxNjMuNjkzNzE0YTE4NC4zOTMxNDMgMTg0LjM5MzE0MyAwIDAgMSAyNjAuNzU0Mjg2IDI2MC44Mjc0MjlMNTAxLjAyODU3MSA4NjAuMDEzNzE0YTI1OC4zNDA1NzEgMjU4LjM0MDU3MSAwIDAgMS0zNjUuMjc1NDI4LTM2NS4yNzU0MjhsMzY1Ljg2MDU3MS0zNjUuODYwNTcyYTM2LjU3MTQyOSAzNi41NzE0MjkgMCAwIDEgNTEuNzEyIDUxLjcxMkwxODcuMzkyIDU0Ni4zNzcxNDNhMTg1LjE5NzcxNCAxODUuMTk3NzE0IDAgMCAwIDI2MS44NTE0MjkgMjYxLjg1MTQyOGw0MzUuNDkyNTcxLTQzNS40OTI1NzFhMTExLjI1MDI4NiAxMTEuMjUwMjg2IDAgMCAwLTE1Ny4zMzAyODYtMTU3LjQwMzQyOUwyOTEuODQgNjUwLjk3MTQyOWEzNy4zMDI4NTcgMzcuMzAyODU3IDAgMCAwIDUyLjg4MjI4NiA1Mi44MDkxNDJsMzY1LjcxNDI4NS0zNjUuNzE0Mjg1YTM2LjU3MTQyOSAzNi41NzE0MjkgMCAxIDEgNTEuNzEyIDUxLjYzODg1N2wtMzY1LjcxNDI4NSAzNjUuNzg3NDI4YTExMC41MTg4NTcgMTEwLjUxODg1NyAwIDAgMS0xNTYuMzA2Mjg2LTE1Ni4yMzMxNDJsNDM1LjQ5MjU3MS00MzUuNDkyNTcyeiIgcC1pZD0iMzQwMzciIGZpbGw9IiMwMjZBQzgiPjwvcGF0aD48L3N2Zz4=";
31761
32380
  // src/runtime/presentation/fields/signatures.ts
31762
32381
  /** @file 读取签名的显示声明,不认证、不改值、不创建姓名位图缓存。 */
31763
- /** 显示采用姓名文字回退;日期格式与旧签名展示规则保持一致。 */
31764
- function signatureGallery(config, value, url) {
32382
+ /** 先解析姓名图形和跟随日期的声明,度量与绘制共用旧版显示规则。 */
32383
+ function signatureGallery(config, value, url, imageSize) {
31765
32384
  try {
31766
32385
  return {
32386
+ imageSize,
31767
32387
  timePlacement: config?.displayDirection === "horizontal" ? "inline" : "below",
31768
32388
  items: signatureValues(value).map((record) => {
31769
32389
  const imageUrl = record.url ? url(record.url) : void 0;
31770
32390
  const time = typeof record.time === "number" ? dayjs(record.time) : void 0;
31771
- const displayTime = config?.format && config.format !== "name" && config.autofill?.enabled !== true;
31772
- const timeText = displayTime && time?.isValid() ? time.format(config.format === "date-time" ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD") : "";
32391
+ const timeText = config?.format && config.format !== "name" && config.autofill?.enabled !== true && time?.isValid() ? time.format(config.format === "date-time" ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD") : "";
31773
32392
  const fallbackDate = config?.fallback === "name-and-date" && time?.isValid() ? time.format("YYYY-MM-DD") : "";
31774
32393
  return {
31775
32394
  image: imageUrl ? {
@@ -31779,9 +32398,11 @@ function signatureGallery(config, value, url) {
31779
32398
  },
31780
32399
  alt: record.username || "签名"
31781
32400
  } : void 0,
31782
- text: [record.username || "签名图片不可用", !displayTime ? fallbackDate : ""].filter(Boolean).join(" "),
32401
+ text: record.username || "签名图片不可用",
32402
+ fallback: config?.fallback ?? "name",
32403
+ fallbackDate,
31783
32404
  timeText,
31784
- vertical: (record.signatureImageDirection ?? config?.imageDirection) === "vertical"
32405
+ vertical: config?.imageDirection === "vertical"
31785
32406
  };
31786
32407
  })
31787
32408
  };
@@ -31906,6 +32527,7 @@ var NativeFieldPresenter = class {
31906
32527
  if (target.state.display === "readonly-text" && !design) appearance = "text";
31907
32528
  else if (choice) appearance = renderAs === "select" ? "select" : "options";
31908
32529
  else if (reference) appearance = "select";
32530
+ if (!design && (printing || browse) && empty && config?.emptySymbol?.trim()) appearance = "text";
31909
32531
  if (design && (!choice && empty || field.widget === "choice" && renderAs === "select")) {
31910
32532
  text = config?.placeholder || config?.designPlaceholder || config?.label || target.declaration.binding.source.fieldLink || "--";
31911
32533
  placeholder = true;
@@ -31945,11 +32567,12 @@ var NativeFieldPresenter = class {
31945
32567
  selected: readDataBoolean(target.value) === value,
31946
32568
  paint: optionPaint(target.state, readDataBoolean(target.value) === value)
31947
32569
  })) : [];
32570
+ const preferredSizePx = field.widget === "signature" || field.widget === "image" ? void 0 : source.preferredSizePx;
31948
32571
  let control = {
31949
32572
  kind: "control",
31950
32573
  displayKey: "control",
31951
32574
  appearance,
31952
- inlineText: !design && appearance !== "options" && !source.preferredSizePx,
32575
+ inlineText: !design && appearance !== "options" && !preferredSizePx,
31953
32576
  text,
31954
32577
  placeholder,
31955
32578
  design,
@@ -31957,7 +32580,7 @@ var NativeFieldPresenter = class {
31957
32580
  required: !printing && !browse && target.state.required,
31958
32581
  multiline: appearance !== "options",
31959
32582
  style: resolvePaint(options.handle.readModel().query.resolveTextStyle(fieldId), options.defaultTextStyle(), text, options.fonts),
31960
- preferredSizePx: source.preferredSizePx,
32583
+ preferredSizePx,
31961
32584
  marker: renderAs === "checkbox" ? "checkbox" : "radio",
31962
32585
  options: choices,
31963
32586
  optionDirection: presentation?.direction ?? "landscape",
@@ -31987,7 +32610,7 @@ var NativeFieldPresenter = class {
31987
32610
  imageGallery,
31988
32611
  text: "",
31989
32612
  placeholder: false,
31990
- preferredSizePx: cell ? control.preferredSizePx : void 0
32613
+ preferredSizePx: cell ? source.preferredSizePx : void 0
31991
32614
  };
31992
32615
  }
31993
32616
  }
@@ -32007,7 +32630,7 @@ var NativeFieldPresenter = class {
32007
32630
  };
32008
32631
  } catch {}
32009
32632
  if (field.widget === "signature" && !design && target.valuePath) {
32010
- const gallery = signatureGallery(field.config, target.value, (value) => options.rules.signatureUrl(fieldId, target.valuePath, value));
32633
+ const gallery = signatureGallery(field.config, target.value, (value) => options.rules.signatureUrl(fieldId, target.valuePath, value), source.preferredSizePx);
32011
32634
  if (gallery?.items.length) control = {
32012
32635
  ...control,
32013
32636
  signatureGallery: gallery,
@@ -32028,10 +32651,11 @@ var NativeFieldPresenter = class {
32028
32651
  };
32029
32652
  if (plainView && !control.text && !control.imageGallery?.items.length && !control.signatureGallery?.items.length && !control.seal && control.appearance !== "options") control = {
32030
32653
  ...control,
32654
+ appearance: "text",
32031
32655
  inlineText: false,
32032
32656
  preferredSizePx: {
32033
32657
  width: 21,
32034
- height: 21
32658
+ height: control.style.fontSizePx * 1.1
32035
32659
  }
32036
32660
  };
32037
32661
  const decoration = fieldDecoration(target.state, plainView, control.placeholder, control.style.color, appearance === "options", linked ? {
@@ -32404,7 +33028,7 @@ var AxisOccurrenceIndex = class {
32404
33028
  this.options = options;
32405
33029
  try {
32406
33030
  this.resources.add(options.handle.subscribeModel((change) => {
32407
- if (affectsNativeDataDeclarations(change)) {
33031
+ if (affectsNativeDataDeclarations(change, options.handle.readModel().query)) {
32408
33032
  this.identities.clearBlanks();
32409
33033
  this.rowsByAxis.clear();
32410
33034
  }
@@ -33880,6 +34504,6 @@ function attachNativeLayout(context, options) {
33880
34504
  throw error;
33881
34505
  }
33882
34506
  }
33883
- export { shouldInitializeDocumentData as $, NativeMaterialSelection as A, clippedFrame as At, logicalFillPath as B, NativeReferenceScopeError as C, compareFieldConfigurations as Ct, materialAutofillRegions as D, LayoutSessionError as Dt, tableSelectionKind as E, LayoutSession as Et, nativeProductReference as F, viewportRectToPage as Ft, attachNativeDataSources as G, nativeSourceWorkerCode as H, NativeInspectionInitialization as I, runtimeRequest as It, sourceParameters as J, copySourceValue as K, NativeResources as L, NativeMaterialObjects as M, pagePointToViewport as Mt, NativeMaterialInitialization as N, pageRectToViewport as Nt, productAutofillDetails as O, LayoutQuery as Ot, materialProductMatches as P, viewportPointToPage as Pt, isUninitialized as Q, NativeFieldFills as R, NativeReferences as S, compareDocumentContent as St, inventorySelection as T, isRecord as Tt, runNativeSourceScript as U, subtableFillColumn as V, NativeDataSources as W, NativeSourceError as X, sourceProperty as Y, hasPersistedDocumentData as Z, CHECK_TABLE_TYPE_TO_VALUE_FIELD as _, resizedDesignColumnWidth as _t, NativeDataServices as a, NativeDataRuntime as at, NativeSignatures as b, combineSessionSignals as bt, businessNumberMinimum as c, DataManager as ct, NativeValidator as d, NativeTableQuickFill as dt, NativeDataInitializer as et, attachNativeValidator as f, nativeQuickFillLimit as ft, createNativeSubmissionData as g, NestedTableInsertionError as gt, allocationNotices as h, EditorController as ht, attachSessionLayout as i, attachNativeParameterInitializer as it, getInvalidMaterialLotReason as j, UnsupportedLayoutError as jt, NativeMaterials as k, DocumentLayoutBuilder as kt, businessTableFieldDefaults as l, NativeBusinessTables as lt, attachNativeSubmissionCoordinator as m, attachNativeInteraction as mt, NativeLayoutPresentation as n, attachNativeDataInitializer as nt, attachNativeDataServices as o, attachNativeDataRuntime as ot, NativeSubmissionCoordinator as p, isDerivedDataPath as pt, sourceResult as q, choiceSpacingDefaults as r, NativeParameterInitializer as rt, NativeBusinessFields as s, NativeDataQuery as st, attachNativeLayout as t, NativeInitializationQueryError as tt, attachSessionData as u, NativeTableScan as ut, isSubmitExcludedKey as v, MissingSubTableHeaderTargetError as vt, validateNativeReference as w, validateTemplateSave as wt, NativeSeals as x, DocumentSession as xt, validateNativeSignatures as y, FieldPlacementError as yt, attachNativeFieldFills as z };
34507
+ export { shouldInitializeDocumentData as $, NativeMaterialSelection as A, clippedFrame as At, logicalFillPath as B, NativeReferenceScopeError as C, compareFieldConfigurations as Ct, materialAutofillRegions as D, LayoutSessionError as Dt, tableSelectionKind as E, LayoutSession as Et, nativeProductReference as F, viewportPointToPage as Ft, attachNativeDataSources as G, nativeSourceWorkerCode as H, NativeInspectionInitialization as I, viewportRectToPage as It, sourceParameters as J, copySourceValue as K, NativeResources as L, runtimeRequest as Lt, NativeMaterialObjects as M, UnsupportedLayoutError as Mt, NativeMaterialInitialization as N, pagePointToViewport as Nt, productAutofillDetails as O, LayoutQuery as Ot, materialProductMatches as P, pageRectToViewport as Pt, isUninitialized as Q, NativeFieldFills as R, NativeReferences as S, compareDocumentContent as St, inventorySelection as T, isRecord as Tt, runNativeSourceScript as U, subtableFillColumn as V, NativeDataSources as W, NativeSourceError as X, sourceProperty as Y, hasPersistedDocumentData as Z, CHECK_TABLE_TYPE_TO_VALUE_FIELD as _, resizedDesignColumnWidth as _t, NativeDataServices as a, NativeDataRuntime as at, NativeSignatures as b, combineSessionSignals as bt, businessNumberMinimum as c, DataManager as ct, NativeValidator as d, NativeTableQuickFill as dt, NativeDataInitializer as et, attachNativeValidator as f, nativeQuickFillLimit as ft, createNativeSubmissionData as g, NestedTableInsertionError as gt, allocationNotices as h, EditorController as ht, attachSessionLayout as i, attachNativeParameterInitializer as it, getInvalidMaterialLotReason as j, signatureGraphic as jt, NativeMaterials as k, DocumentLayoutBuilder as kt, businessTableFieldDefaults as l, NativeBusinessTables as lt, attachNativeSubmissionCoordinator as m, attachNativeInteraction as mt, NativeLayoutPresentation as n, attachNativeDataInitializer as nt, attachNativeDataServices as o, attachNativeDataRuntime as ot, NativeSubmissionCoordinator as p, isDerivedDataPath as pt, sourceResult as q, choiceSpacingDefaults as r, NativeParameterInitializer as rt, NativeBusinessFields as s, NativeDataQuery as st, attachNativeLayout as t, NativeInitializationQueryError as tt, attachSessionData as u, NativeTableScan as ut, isSubmitExcludedKey as v, MissingSubTableHeaderTargetError as vt, validateNativeReference as w, validateTemplateSave as wt, NativeSeals as x, DocumentSession as xt, validateNativeSignatures as y, FieldPlacementError as yt, attachNativeFieldFills as z };
33884
34508
 
33885
- //# sourceMappingURL=sdk-Dz96Ca_-.js.map
34509
+ //# sourceMappingURL=sdk-D9n5KeaD.js.map