@hmg-report-editor/core 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/editor/ReportEditorCore.d.ts +137 -0
- package/dist/editor/createReportEditor.d.ts +3 -0
- package/dist/extensions/DropdownFieldNode.d.ts +15 -0
- package/dist/extensions/FontSizeExtension.d.ts +11 -0
- package/dist/extensions/HiddenParagraphExtension.d.ts +11 -0
- package/dist/extensions/IndentationExtension.d.ts +13 -0
- package/dist/extensions/LineHeightExtension.d.ts +12 -0
- package/dist/extensions/PageBreakNode.d.ts +11 -0
- package/dist/extensions/ReportNumberedBlockNode.d.ts +10 -0
- package/dist/extensions/StructuredFieldNode.d.ts +15 -0
- package/dist/extensions/TextColorExtension.d.ts +11 -0
- package/dist/extensions/VisibilityGroupMark.d.ts +6 -0
- package/dist/extensions/index.d.ts +29 -0
- package/dist/group/ReportEditorGroupManager.d.ts +45 -0
- package/dist/history/SharedHistoryManager.d.ts +96 -0
- package/dist/identity/ControlIdentityService.d.ts +48 -0
- package/dist/identity/PageBreakIdentityService.d.ts +29 -0
- package/dist/identity/VisibilityGroupIdentityService.d.ts +24 -0
- package/dist/index.cjs +5 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +5326 -0
- package/dist/nodeViews/BaseControlNodeView.d.ts +82 -0
- package/dist/nodeViews/ControlClipboard.d.ts +10 -0
- package/dist/nodeViews/ControlInputAutosize.d.ts +2 -0
- package/dist/nodeViews/DropdownFieldNodeView.d.ts +57 -0
- package/dist/nodeViews/FieldNodeViews.d.ts +4 -0
- package/dist/nodeViews/PageBreakNodeView.d.ts +20 -0
- package/dist/nodeViews/StructuredFieldNodeView.d.ts +24 -0
- package/dist/plugins/ControlGapCursor.d.ts +21 -0
- package/dist/plugins/ControlSelectionLifecycle.d.ts +3 -0
- package/dist/plugins/ControlShortcuts.d.ts +40 -0
- package/dist/plugins/ControlTransactionMeta.d.ts +10 -0
- package/dist/plugins/NumberingPlugin.d.ts +15 -0
- package/dist/plugins/NumberingService.d.ts +29 -0
- package/dist/plugins/PasteSanitizer.d.ts +32 -0
- package/dist/registry/ReportFeatureRegistry.d.ts +16 -0
- package/dist/registry/builtinReportNodes.d.ts +19 -0
- package/dist/selection/SelectionManager.d.ts +18 -0
- package/dist/serializer/ReportSerializer.d.ts +57 -0
- package/dist/serializer/VisibilityGroupResolver.d.ts +20 -0
- package/dist/template/ReportTemplateEngine.d.ts +41 -0
- package/dist/types/index.d.ts +401 -0
- package/dist/utils/ReportErrorDispatcher.d.ts +13 -0
- package/dist/utils/controlAttrs.d.ts +10 -0
- package/dist/utils/controlTextSegments.d.ts +15 -0
- package/dist/utils/html.d.ts +33 -0
- package/dist/utils/reportDocument.d.ts +11 -0
- package/dist/utils/reportDocumentValidation.d.ts +16 -0
- package/package.json +37 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var Ee=Object.defineProperty;var we=(r,t,e)=>t in r?Ee(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var p=(r,t,e)=>we(r,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@tiptap/core"),Ne=require("@tiptap/pm/history"),L=require("@tiptap/pm/model"),y=require("@tiptap/pm/state"),F=require("@tiptap/pm/view"),_t=require("@tiptap/pm/transform"),ve=require("@tiptap/starter-kit"),Te=require("@tiptap/extension-font-family"),Ae=require("@tiptap/extension-text-style"),Me=require("@tiptap/extension-underline");class S{static text(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}static attr(t){return S.text(t).replace(/"/g,""").replace(/'/g,"'")}}class gt{constructor(){p(this,"declarations",[])}add(t,e){return typeof e=="string"&&e.trim()&&this.declarations.push(`${t}: ${e.trim()}`),typeof e=="number"&&Number.isFinite(e)&&this.declarations.push(`${t}: ${e}`),this}addSafe(t,e){const n=k.sanitize(t,e);return n&&this.declarations.push(`${t}: ${n}`),this}toAttribute(){return this.declarations.length===0?"":` style="${S.attr(this.declarations.join("; "))}"`}}class k{static sanitize(t,e){if(typeof e=="number")return Number.isFinite(e)?String(e):void 0;if(typeof e!="string")return;const n=t.trim().toLowerCase(),o=e.trim();if(!(!o||this.hasUnsafeSyntax(o)))switch(n){case"color":return this.isSafeColor(o)?o:void 0;case"font-size":return this.isSafeLength(o)?o:void 0;case"line-height":return this.isSafeNumber(o)||this.isSafeLength(o)?o:void 0;case"font-family":return this.isSafeFontFamily(o)?o:void 0;case"font-weight":return/^(normal|bold|bolder|lighter|[1-9]00)$/.test(o)?o:void 0;case"font-style":return/^(normal|italic|oblique)$/.test(o)?o:void 0;case"text-decoration":return/^(none|underline|line-through|overline)$/.test(o)?o:void 0;default:return}}static hasUnsafeSyntax(t){return/[;\u0000-\u001f\u007f]/.test(t)||/(?:url|expression)\s*\(|javascript:/i.test(t)}static isSafeColor(t){return/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(t)||/^[a-z]+$/i.test(t)||/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?(?:\s*,\s*(?:0|1|0?\.\d+|\d{1,3}%))?\s*\)$/i.test(t)?!0:/^hsla?\(\s*\d{1,3}(?:deg)?\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(?:\s*,\s*(?:0|1|0?\.\d+|\d{1,3}%))?\s*\)$/i.test(t)}static isSafeLength(t){return/^(?:0|[1-9]\d*)(?:\.\d+)?(?:px|em|rem|%|pt)$/.test(t)}static isSafeNumber(t){return/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(t)}static isSafeFontFamily(t){return t.split(",").map(e=>e.trim()).every(e=>/^["'][^"'\r\n();\\]+["']$/.test(e)||/^[a-zA-Z0-9 _.-]+$/.test(e))}}class ${static isEmpty(t){return t==null?!0:typeof t=="string"?t.trim().length===0:!1}}const w="visibilityGroup",X="all-controls-empty";function at(r){if(typeof r.groupId!="string"||!r.groupId.trim())throw new Error("Visibility group requires a non-empty groupId.");if(r.condition!==X)throw new Error(`Unsupported visibility group condition: ${String(r.condition??"")}.`)}function Ht(){const r=globalThis.crypto;return r!=null&&r.randomUUID?`visibility_group_${r.randomUUID()}`:`visibility_group_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}class Gt{assignFreshIdsToSlice(t){const e=new Map;return new L.Slice(this.mapFragment(t.content,n=>this.refreshMarks(n,e)),t.openStart,t.openEnd)}removeMarksFromSlice(t,e){return new L.Slice(this.mapFragment(t.content,n=>n.filter(o=>o.type.name!==w?!0:e?!e.has(String(o.attrs.groupId??"")):!1)),t.openStart,t.openEnd)}static withoutVisibilityGroupMarks(t){return t.filter(e=>e.type.name!==w)}refreshMarks(t,e){return t.map(n=>{if(n.type.name!==w)return n;at(n.attrs);const o=String(n.attrs.groupId);let s=e.get(o);return s||(s=Ht(),e.set(o,s)),n.type.create({...n.attrs,groupId:s})})}mapFragment(t,e){const n=[];return t.forEach(o=>{n.push(this.mapNode(o,e))}),L.Fragment.fromArray(n)}mapNode(t,e){const n=e(t.marks);if(t.isText)return It(n,t.marks)?t:t.mark(n);const o=t.content.size>0?this.mapFragment(t.content,e):t.content;return o===t.content&&It(n,t.marks)?t:t.type.create(t.attrs,o,n)}}function It(r,t){return r.length===t.length&&r.every((e,n)=>e.eq(t[n]))}const et="[data-report-node][data-control-id]",Et="hmg-control-gap-caret",M=new y.PluginKey("reportControlGapCursor");function ke(r=[]){const t=tr(r);let e=null;const n=o=>{if(!e||e.finishScheduled)return;e.ending=!0,e.finishScheduled=!0;const s=e.sessionId;setTimeout(()=>{(e==null?void 0:e.sessionId)===s&&(e=je(o,e,t))})};return C.Extension.create({name:"reportControlGapCursor",priority:1e3,addProseMirrorPlugins(){return[new y.Plugin({key:M,state:{init:()=>Y(),apply(o,s,i,a){const l=o.getMeta(M);if(e&&o.docChanged){const c=o.getMeta("composition");e=(l==null?void 0:l.type)==="compositionInput"&&l.sessionId===e.sessionId||e.compositionId!==void 0&&c===e.compositionId?Ue(e,o):qe(e,o)}if((l==null?void 0:l.type)==="clear")return Y();if((l==null?void 0:l.type)==="showBoundaryCaret")return Nt(a,l.pos);if(s.boundaryCaretPos!==null)return o.docChanged?Y():Nt(a,s.boundaryCaretPos);let d=(l==null?void 0:l.type)==="activate"?l.active:s.active;return d&&o.docChanged&&(l==null?void 0:l.type)!=="activate"&&(d=rt(d,o.mapping)),$e(a,d,t)}},props:{decorations(o){var s;return(s=M.getState(o))==null?void 0:s.decorations},handleClick(o,s,i){return xe(o,s,i,t)},handleTextInput(o,s,i,a,l){return!e&&o.composing&&(e=vt(o)),e?(e.awaitingInput={from:s,text:a},o.dispatch(Ut(l(),s,a.length).setMeta(M,{type:"compositionInput",sessionId:e.sessionId})),!0):De(o,a,l,t)},handleDOMEvents:{compositionstart(o){return e!=null&&e.ending&&(e=Ge(o.state,e)?He(e):null),e??(e=vt(o)),!1},compositionend(o){return n(o),!1},blur(o){return n(o),Je(o),!1}}},view(){return{destroy(){e=null}}}})]}})}function xe(r,t,e,n){if(e.button!==0||!r.editable||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return!1;const o=e.target;if(!(o instanceof Element)||!r.dom.contains(o)||o.closest(et))return!1;const s=Ke(r.state.doc,t,n);for(const i of s){const a=At(r,i.left),l=At(r,i.right);if(!a||!l||!Pe(e,a,l))continue;const d=r.state.tr.setSelection(y.TextSelection.create(r.state.doc,i.cursorPos)).setMeta(M,{type:"activate",active:_e(i)});return d.setMeta("addToHistory",!1),r.dispatch(d),r.focus(),e.preventDefault(),!0}return!1}function De(r,t,e,n){const{selection:o}=r.state,s=M.getState(r.state);if(!r.editable||!t||!(s!=null&&s.active)||!(o instanceof y.TextSelection)||!o.empty||o.from!==s.active.pos)return!1;const i=Wt(r.state.doc,s.active,n);if(!i)return!1;const l=e().getMeta("composition"),d=Ut(r.state.tr.insertText(t,i.cursorPos,i.cursorPos),i.cursorPos,t.length).setMeta("applyInputRules",{from:i.cursorPos,text:t}).scrollIntoView();return l!==void 0&&d.setMeta("composition",l),r.dispatch(d),!0}function Pe(r,t,e){const n=t.getBoundingClientRect(),o=e.getBoundingClientRect(),s=Math.max(n.top,o.top),i=Math.min(n.bottom,o.bottom);let a,l;if(s>=i)return!1;if(n.right<o.left)a=n.right,l=o.left;else if(o.right<n.left)a=o.right,l=n.left;else return!1;return r.clientX>=a&&r.clientX<=l&&r.clientY>=s&&r.clientY<=i}function Y(){return{active:null,boundaryCaretPos:null,decorations:F.DecorationSet.empty}}function Be(r,t){return r.setMeta(M,{type:"showBoundaryCaret",pos:t})}function Oe(r){var t;return((t=M.getState(r))==null?void 0:t.boundaryCaretPos)??null}function Fe(r){return r.setMeta(M,{type:"clear"})}function Le(r,t,e,n,o){const s=M.get(r.state),i=s==null?void 0:s.props.handleTextInput;if(!s||!i)return!1;if(i.call(s,r,t,e,n,o)===!0)return!0;if(!r.editable||!n)return!1;const a=o();if(!Re(a.doc,t,t+n.length))return!1;const l=()=>qt(o()),d=Ve(r);for(const c of r.state.plugins)if(!(c===s||!c.props.handleTextInput)&&c.props.handleTextInput.call(c,d,t,e,n,l)===!0)return!0;return d.dispatch(l()),!0}function Ut(r,t,e){const n=r.doc.type.schema.marks[w],o=Math.min(r.doc.content.size,t+e);return n&&e>0&&t>=0&&t<o&&r.removeMark(t,o,n),r}function Re(r,t,e){const n=r.type.schema.marks[w],o=Math.max(0,t),s=Math.min(r.content.size,e);return!!(n&&o<s&&r.rangeHasMark(o,s,n))}function Ve(r){const t=Object.create(r);return Object.defineProperty(t,"dispatch",{configurable:!0,value:e=>{r.dispatch(qt(e))}}),t}function qt(r){const t=r.doc.type.schema.marks[w];if(!t||r.steps.length===0)return r;const e=r.mapping.maps.length,n=[];r.mapping.maps.slice(0,e).forEach((o,s)=>{const i=r.mapping.slice(s+1,e);o.forEach((a,l,d,c)=>{if(d>=c)return;const h=i.map(d,-1),f=i.map(c,1),u=Math.max(0,Math.min(r.doc.content.size,h)),g=Math.max(0,Math.min(r.doc.content.size,f));u<g&&r.doc.rangeHasMark(u,g,t)&&n.push({from:u,to:g})})});for(const o of ze(n))r.removeMark(o.from,o.to,t);return r}function ze(r){const t=[...r].sort((n,o)=>n.from-o.from||n.to-o.to),e=[];for(const n of t){const o=e[e.length-1];if(o&&n.from<=o.to){o.to=Math.max(o.to,n.to);continue}e.push({...n})}return e}function wt(r,t){const e=M.get(r.state),n=e==null?void 0:e.props.handleDOMEvents,o=n==null?void 0:n[t.type];return!e||!o?!1:o.call(e,r,t)===!0}function $e(r,t,e){const{selection:n}=r;return!t||!(n instanceof y.TextSelection)||!n.empty||n.from!==t.pos||!Wt(r.doc,t,e)?Y():{active:t,boundaryCaretPos:null,decorations:jt(r,t.pos)}}function Nt(r,t){const{selection:e}=r;return!(e instanceof y.TextSelection)||!e.empty||e.from!==t||t<0||t>r.doc.content.size||!r.doc.resolve(t).parent.inlineContent?Y():{active:null,boundaryCaretPos:t,decorations:jt(r,t)}}function jt(r,t){const e=F.Decoration.widget(t,n=>{const o=n.dom.ownerDocument.createElement("span");return o.className=Et,o.setAttribute("aria-hidden","true"),o.setAttribute("contenteditable","false"),o},{key:Et,side:-1,ignoreSelection:!0});return F.DecorationSet.create(r.doc,[e])}function _e(r){return{pos:r.cursorPos,leftPos:r.left.pos,rightPos:r.right.pos,leftControlId:r.left.node.attrs.controlId,rightControlId:r.right.node.attrs.controlId}}function Wt(r,t,e){const n=Kt(r,t.pos,e);if(!(!n||n.cursorPos!==t.pos||n.left.pos!==t.leftPos||n.right.pos!==t.rightPos||n.left.node.attrs.controlId!==t.leftControlId||n.right.node.attrs.controlId!==t.rightControlId))return n}function rt(r,t){return{...r,pos:t.map(r.pos,-1),leftPos:t.map(r.leftPos,1),rightPos:t.map(r.rightPos,1)}}function vt(r){var e;const t=(e=M.getState(r.state))==null?void 0:e.active;return t?{sessionId:Symbol("control-gap-composition"),active:{...t},marks:Gt.withoutVisibilityGroupMarks(r.state.storedMarks??r.state.doc.resolve(t.pos).marks()),text:"",range:null,awaitingInput:null,compositionId:void 0,ending:!1,finishScheduled:!1}:null}function He(r){return{...r,sessionId:Symbol("control-gap-composition"),awaitingInput:null,compositionId:void 0,ending:!1,finishScheduled:!1}}function Ge(r,t){const{selection:e}=r;return!!(t.range&&e.from>=t.range.from&&e.to<=t.range.to||e.empty&&e.from===t.active.pos)}function Ue(r,t){const e=rt(r.active,t.mapping),n=t.getMeta("composition")??r.compositionId,o=r.range?{from:t.mapping.map(r.range.from,-1),to:t.mapping.map(r.range.to,1)}:null;if(r.awaitingInput){const s=t.mapping.map(r.awaitingInput.from,-1),i=s+r.awaitingInput.text.length,a={from:o?Math.min(o.from,s):s,to:o?Math.max(o.to,i):i};return{...r,active:e,text:t.doc.textBetween(a.from,a.to,"",""),range:a,awaitingInput:null,compositionId:n}}return{...r,active:e,text:o?t.doc.textBetween(o.from,o.to,"",""):r.text,range:o,compositionId:n}}function qe(r,t){if(t.getMeta("addToHistory")!==!1)return null;if(!r.range)return{...r,active:rt(r.active,t.mapping)};const e=r.range.from,n=r.range.to;let{from:o,to:s}=r.range;for(const i of t.mapping.maps){let a=!1;if(i.forEach((l,d)=>{(l===d?l>=o&&l<=s:l<s&&d>o)&&(a=!0)}),a)return null;o=i.map(o,1),s=i.map(s,-1)}return t.before.slice(e,n).eq(t.doc.slice(o,s))?{...r,active:rt(r.active,t.mapping),text:t.doc.textBetween(o,s,"",""),range:{from:o,to:s}}:null}function je(r,t,e){if(!t||!t.ending||r.isDestroyed||!t.range||!t.text)return null;const{from:n,to:o}=t.range,s=r.state.selection.from>=n&&r.state.selection.to<=o||r.state.selection.empty&&r.state.selection.from===t.active.pos;if(n<0||o>r.state.doc.content.size||n>=o||r.state.doc.textBetween(n,o,"","")!==t.text||We(r.state.doc,n,o))return null;const i=r.state.tr.delete(n,o),a=i.mapping.map(t.active.leftPos,1),l=i.mapping.map(t.active.rightPos,1),d=i.doc.nodeAt(a),c=i.doc.nodeAt(l);if(!d||!c||!e(d)||!e(c)||d.attrs.controlId!==t.active.leftControlId||c.attrs.controlId!==t.active.rightControlId)return null;const h=Jt(i.doc,{node:d,pos:a},{node:c,pos:l});return h&&(i.insert(h.cursorPos,i.doc.type.schema.text(t.text,t.marks)).scrollIntoView(),s&&i.setSelection(y.TextSelection.create(i.doc,h.cursorPos+t.text.length)),t.compositionId!==void 0&&i.setMeta("composition",t.compositionId),r.dispatch(i)),null}function We(r,t,e){let n=!1;return r.nodesBetween(t,e,(o,s)=>{if((o.isLeaf||o.isAtom)&&!o.isText&&s<e&&s+o.nodeSize>t)return n=!0,!1}),n}function Je(r){const t=M.getState(r.state);if(!(t!=null&&t.active)&&(t==null?void 0:t.boundaryCaretPos)===null)return;const e=r.state.tr.setMeta(M,{type:"clear"}).setMeta("addToHistory",!1);r.dispatch(e)}function Ke(r,t,e){const n=Xe(r,t),o=[],s=new Set;for(const i of n){const a=Kt(r,i,e);if(a){const l=`${a.left.pos}:${a.right.pos}`;if(s.has(l))continue;s.add(l),o.push(a)}}return o.sort((i,a)=>Tt(t,i.from,i.to)-Tt(t,a.from,a.to))}function Xe(r,t){const e=r.resolve(t),n=new Set([t]);for(let o=e.depth;o>=0;o-=1){const s=e.node(o);if(!s.inlineContent)continue;const i=e.index(o),a=Math.max(0,i-1),l=Math.min(s.childCount,i+1);for(let d=a;d<=l;d+=1)n.add(e.posAtIndex(d,o))}return Array.from(n)}function Tt(r,t,e){return r<t?t-r:r>e?r-e:0}function Jt(r,t,e){const n=t.pos+t.node.nodeSize,o=e.pos;if(n>o||Ye(r,n,o))return;const s=r.resolve(t.pos),i=r.resolve(e.pos),a=s.sharedDepth(e.pos);if(!s.node(a).inlineContent)return;const l=a===i.depth?e.pos:i.before(a+1);if(!(l<n||l>o||!r.resolve(l).parent.inlineContent))return{left:t,right:e,from:n,to:o,cursorPos:l}}function Ye(r,t,e){let n=!1;return r.nodesBetween(t,e,(o,s)=>{if((o.isLeaf||o.isAtom)&&s<e&&s+o.nodeSize>t)return n=!0,!1}),n}function Kt(r,t,e){const n=r.resolve(t);if(!n.parent.inlineContent||n.textOffset)return;for(let a=1;a<=n.depth;a+=1)if(n.node(a).isAtom)return;const o=Ze(n),s=Qe(n);if(!o||!s||!e(o.node)||!e(s.node))return;const i=Jt(r,o,s);return i&&t>=i.from&&t<=i.to?i:void 0}function Ze(r){for(let t=r.depth;t>=0;t-=1){const e=r.node(t),n=r.index(t);for(let o=n-1;o>=0;o-=1){const s=yt(e.child(o),r.posAtIndex(o,t),"last");if(s)return s}if(t===0||!r.node(t).isInline)break}}function Qe(r){const t=r.depth;for(let e=t;e>=0;e-=1){const n=r.node(e),o=r.index(e)+(e<t?1:0);for(let s=o;s<n.childCount;s+=1){const i=yt(n.child(s),r.posAtIndex(s,e),"first");if(i)return i}if(e===0||!r.node(e).isInline)break}}function yt(r,t,e){if(r.isLeaf||r.isAtom||!r.isInline)return{node:r,pos:t};const n=[];r.forEach((o,s)=>{n.push({node:o,pos:t+1+s})}),e==="last"&&n.reverse();for(const o of n){const s=yt(o.node,o.pos,e);if(s)return s}}function At(r,t){const e=t.node.attrs.controlId,n=r.nodeDOM(t.pos);if(n instanceof HTMLElement){if(ht(n,e))return n;const o=Array.from(n.querySelectorAll(et)).find(s=>ht(s,e));if(o)return o}return Array.from(r.dom.querySelectorAll(et)).find(o=>ht(o,e))}function ht(r,t){return r.matches(et)&&r.dataset.controlId===t}function tr(r){const t=new Set(r);return e=>!!(t.has(e.type.name)&&e.isAtom&&typeof e.attrs.controlId=="string"&&e.attrs.controlId)}const er=new y.PluginKey("reportControlShortcuts"),B={nextControl:"ArrowRight",previousControl:"ArrowLeft",openDropdown:"Enter",closeDropdown:"Escape",nextDropdownOption:"ArrowDown",previousDropdownOption:"ArrowUp",selectDropdownOption:"Enter",submitInput:"Enter"},rr={Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Down:"ArrowDown",Esc:"Escape"};function lt(r,t=["structuredField","dropdownField"],e=t.map(ar),n){return{shortcuts:nr(r),controlNodeNames:t,controlReportNodeNames:e,editorGroup:n}}function nr(r={}){return{enabled:r.enabled!==!1,nextControl:D(r.nextControl)??B.nextControl,previousControl:D(r.previousControl)??B.previousControl,openDropdown:D(r.openDropdown)??B.openDropdown,closeDropdown:D(r.closeDropdown)??B.closeDropdown,nextDropdownOption:D(r.nextDropdownOption)??B.nextDropdownOption,previousDropdownOption:D(r.previousDropdownOption)??B.previousDropdownOption,selectDropdownOption:D(r.selectDropdownOption)??B.selectDropdownOption,submitInput:D(r.submitInput)??B.submitInput,autoFocusNextOnEnter:r.autoFocusNextOnEnter!==!1}}function Xt(r,t){if(t.enabled){if(P(r,t.nextControl))return"next";if(P(r,t.previousControl))return"previous"}}function P(r,t){return r.defaultPrevented||r.isComposing||r.altKey||r.ctrlKey||r.metaKey||r.shiftKey?!1:D(r.key)===t}function or(r){const t=D(r.key);return t==="ArrowLeft"||t==="ArrowRight"}function Yt(r,t,e,n,o=!1){if(!e.shortcuts.enabled||!r.editable)return!1;const s=r.nodeDOM(t);if(!(s instanceof HTMLElement))return!1;const i=te(s,e),a=Qt(s.ownerDocument,e.controlReportNodeNames,i),l=a.findIndex(d=>d.element===s);if(l<0||a.length<2)return!1;for(const d of lr(a,l,n))return ee(r,d.element,e.controlNodeNames),d.focusTarget.focus(),re(d.focusTarget,n,o),!0;return!1}function sr(r,t,e,n,o=!1){if(!e.shortcuts.enabled||!r.editable)return!1;const s=te(r.dom,e),i=Qt(r.dom.ownerDocument,e.controlReportNodeNames,s),l=Zt(r.state.doc,e.controlNodeNames).flatMap(f=>{const u=r.nodeDOM(f.pos),g=u instanceof HTMLElement?i.findIndex(m=>m.element===u):-1;return g>=0?[{...f,navigationIndex:g}]:[]}),d=n==="next"?l.find(f=>f.pos>=t):[...l].reverse().find(f=>f.pos+f.node.nodeSize<=t);if(d)return kt(r),Mt(r,i[d.navigationIndex],e,n,o);if(i.length<1||l.length<1)return!1;const c=n==="next"?l[l.length-1].navigationIndex:l[0].navigationIndex,h=n==="next"?(c+1)%i.length:(c-1+i.length)%i.length;return kt(r),Mt(r,i[h],e,n,o)}function ir(r){return C.Extension.create({name:"reportControlShortcuts",addProseMirrorPlugins(){return r.shortcuts.enabled?[new y.Plugin({key:er,props:{handleKeyDown(t,e){const{selection:n}=t.state,o=Xt(e,r.shortcuts);if(!o)return!1;if(n instanceof y.NodeSelection&&r.controlNodeNames.includes(n.node.type.name))return Yt(t,n.from,r,o,!0)?(e.preventDefault(),!0):!1;const s=Oe(t.state);return s===null||!(n instanceof y.TextSelection)||!n.empty||n.from!==s||!sr(t,s,r,o,!0)?!1:(e.preventDefault(),!0)}}})]:[]}})}function D(r){const t=r==null?void 0:r.trim();if(t)return rr[t]??t}function ar(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Zt(r,t){const e=[];return r.descendants((n,o)=>{t.includes(n.type.name)&&e.push({node:n,pos:o})}),e}function Qt(r,t,e){const n=[],o=t.map(i=>`[data-report-node="${i.replace(/"/g,'\\"')}"]`).join(",");if(!o)return n;const s=Array.from(r.querySelectorAll(o));for(const i of s){if(e&&!e.some(l=>l.contains(i)||l===i))continue;const a=dr(i);a&&n.push({element:i,focusTarget:a})}return n}function te(r,t){const e=t.editorGroup;if(!e)return;const n=e.getEditorElements().filter(o=>o.ownerDocument===r.ownerDocument);return n.some(o=>o.contains(r)||o===r)?n:[]}function lr(r,t,e){const n=[],o=e==="next"?1:-1;for(let s=1;s<r.length;s+=1){const i=(t+o*s+r.length)%r.length;n.push(r[i])}return n}function ee(r,t,e){if(!r.dom.contains(t))return;const n=Zt(r.state.doc,e).find(o=>r.nodeDOM(o.pos)===t);n&&cr(r,n)}function dr(r){return r.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")}function Mt(r,t,e,n,o){return ee(r,t.element,e.controlNodeNames),t.focusTarget.focus(),re(t.focusTarget,n,o),!0}function kt(r){const t=Fe(r.state.tr);t.setMeta("addToHistory",!1),r.dispatch(t)}function cr(r,t){const e=Math.min(t.pos+t.node.nodeSize,r.state.doc.content.size),n=r.state.tr.setSelection(y.TextSelection.near(r.state.doc.resolve(e),1));n.setMeta("addToHistory",!1),r.dispatch(n)}function re(r,t,e){if(r instanceof HTMLSelectElement)return;const n=e||t==="next"?0:r.value.length,o=e?r.value.length:n;try{r.setSelectionRange(n,o)}catch{}}const ne=new WeakMap;function pt(r,t){const e=dt(r),n=new Set((e==null?void 0:e.controlIds)??[]);for(const o of t)o.trim()&&n.add(o);return n.size===0||ne.set(r,{controlIds:Array.from(n)}),r}function dt(r){return ne.get(r)}function oe(r){const t=r.filter(e=>e.docChanged);return t.length>0&&t.every(e=>!!dt(e))}function ur(r){return r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)}function R(r){return r==null?"null":typeof r=="number"?"number":typeof r=="boolean"?"boolean":"string"}function nt(r,t){if(r===null||t==="null")return null;if(t==="number"){const e=Number(r);return Number.isFinite(e)?e:r}if(t==="boolean"){if(r==="true")return!0;if(r==="false")return!1}return r}function _(r){return Array.isArray(r)?r.filter(t=>!!t&&typeof t=="object").map(t=>({label:String(t.label??t.value??""),value:String(t.value??t.label??"")})):[]}class ot{static hasSelectedInputText(t){return t instanceof HTMLInputElement?(t.selectionStart??0)!==(t.selectionEnd??0):!1}static write(t,e,n){return t.defaultPrevented||!t.clipboardData||ot.hasSelectedInputText(t.target)?!1:(t.clipboardData.setData("text/html",e.outerHTML),t.clipboardData.setData("text/plain",n),t.preventDefault(),!0)}static createElement(t,e,n,o){const s=document.createElement("span"),i=t.value;return s.className=e,s.setAttribute("data-report-node",n),s.setAttribute("data-control-id",String(t.controlId??"")),s.setAttribute("data-batch-id",String(t.batchId??"")),s.setAttribute("data-template-id",String(t.templateId??"")),s.setAttribute("data-widget-number",String(t.widgetNumber??"")),s.setAttribute("data-field-id",String(t.fieldId??"")),s.setAttribute("data-field-name",String(t.fieldName??"")),s.setAttribute("data-value",i==null?"":String(i)),s.setAttribute("data-value-type",R(i)),s.setAttribute("data-default-value",t.defaultValue===null||t.defaultValue===void 0?"":String(t.defaultValue)),s.setAttribute("data-default-value-type",R(t.defaultValue)),s.setAttribute("data-placeholder",t.placeholder??""),s.setAttribute("data-required",String(!!t.required)),s.setAttribute("data-hide-when-empty",String(!!t.hideWhenEmpty)),s.setAttribute("data-no-match-default",String(!!t.noMatchDefault)),s.setAttribute("data-rules",JSON.stringify(t.rules??[])),s.setAttribute("data-next-widget-number",String(t.nextWidgetNumber??"")),s.setAttribute("data-rule-style-color",String(t.ruleStyleColor??"")),s.style.color=t.ruleStyleColor?String(t.ruleStyleColor):"",s.textContent=o,s}}class se{constructor(t,e,n=lt()){p(this,"dom");p(this,"node");p(this,"selected",!1);p(this,"editable");this.props=t,this.nodeName=e,this.controlShortcutRuntime=n,this.node=t.node,this.editable=t.editor.isEditable,this.dom=document.createElement("span"),this.dom.className=this.rootClassName(),this.dom.setAttribute("data-report-node",this.reportNodeName()),this.dom.setAttribute("data-control-id",String(this.attrs.controlId??"")),this.dom.setAttribute("data-batch-id",String(this.attrs.batchId??"")),this.dom.setAttribute("data-template-id",String(this.attrs.templateId??"")),this.dom.setAttribute("data-widget-number",String(this.attrs.widgetNumber??"")),this.dom.setAttribute("data-field-id",String(this.attrs.fieldId??"")),this.dom.setAttribute("data-field-name",String(this.attrs.fieldName??"")),this.dom.setAttribute("contenteditable","false"),this.dom.addEventListener("mousedown",o=>this.handleMouseDown(o)),this.dom.addEventListener("focusin",o=>this.handleFocusIn(o)),this.dom.addEventListener("focusout",()=>this.setFocused(!1)),this.dom.addEventListener("copy",o=>this.copyControl(o)),this.dom.addEventListener("cut",o=>this.cutControl(o)),this.dom.addEventListener("keydown",o=>this.handleShortcutKeyDown(o))}update(t){if(t.type.name!==this.nodeName)return!1;const e=this.props.editor.isEditable;return t.eq(this.node)&&e===this.editable?(this.node=t,!0):(this.node=t,this.editable=e,this.syncRootAttributes(),this.renderControl(),!0)}selectNode(){this.selected=!0,this.dom.classList.add(this.selectedClassName()),this.dom.setAttribute("data-selected","true"),this.syncRootAttributes()}deselectNode(){this.selected=!1,this.dom.classList.remove(this.selectedClassName()),this.dom.removeAttribute("data-selected"),this.dom.contains(this.dom.ownerDocument.activeElement)||this.setFocused(!1),this.syncRootAttributes()}stopEvent(t){return this.selected&&this.isDragEvent(t)?!1:this.isInteractiveTarget(t.target)}ignoreMutation(){return!0}get attrs(){return this.node.attrs}setFocused(t){this.dom.classList.toggle(this.focusedClassName(),t),this.dom.toggleAttribute("data-focused",t)}commitValue(t){if(!this.props.editor.isEditable)return;const e=this.props.getPos(),n=String(this.node.attrs.controlId??""),o=String(this.node.attrs.batchId??"");let s=this.props.view.state.tr.setNodeMarkup(e,void 0,{...this.node.attrs,value:t},this.node.marks);n.trim()&&o.trim()&&(s=pt(s,[n])),this.props.view.dispatch(s)}completeInputAndMaybeFocusNext(t){const e=this.controlShortcutRuntime.shortcuts;return t.defaultPrevented||!this.props.editor.isEditable||!e.enabled||!this.isInteractiveTarget(t.target)||!P(t,e.submitInput)?!1:(t.preventDefault(),e.autoFocusNextOnEnter&&this.focusAdjacentControlFromCurrent("next"),!0)}focusAdjacentControlFromCurrent(t,e=!1){const n=this.props.getPos();return typeof n!="number"?!1:Yt(this.props.view,n,this.controlShortcutRuntime,t,e)}syncRootAttributes(){const t=this.props.editor.isEditable;this.dom.setAttribute("data-control-id",String(this.attrs.controlId??"")),this.dom.setAttribute("data-batch-id",String(this.attrs.batchId??"")),this.dom.setAttribute("data-template-id",String(this.attrs.templateId??"")),this.dom.setAttribute("data-widget-number",String(this.attrs.widgetNumber??"")),this.dom.setAttribute("data-field-id",String(this.attrs.fieldId??"")),this.dom.setAttribute("data-field-name",String(this.attrs.fieldName??"")),this.dom.setAttribute("data-rule-style-color",String(this.attrs.ruleStyleColor??"")),this.dom.style.color=this.attrs.ruleStyleColor?String(this.attrs.ruleStyleColor):"",this.dom.classList.toggle(`${this.rootClassName()}--empty`,this.isValueEmpty(this.attrs.value)),this.dom.classList.toggle(`${this.rootClassName()}--readonly`,!t),this.dom.draggable=t&&this.selected}isValueEmpty(t){return t==null||typeof t=="string"&&t.trim().length===0}handleShortcutKeyDown(t){if(t.defaultPrevented||!this.props.editor.isEditable||!this.isInteractiveTarget(t.target)||this.deleteEmptyControlFromInput(t))return;const e=Xt(t,this.controlShortcutRuntime.shortcuts);!e||!this.shouldNavigateFromInteractiveTarget(t)||this.focusAdjacentControlFromCurrent(e,!0)&&t.preventDefault()}copyControl(t){this.writeControlToClipboard(t)}cutControl(t){if(!this.props.editor.isEditable||!this.writeControlToClipboard(t))return;const e=this.props.getPos();typeof e=="number"&&this.props.view.dispatch(this.props.view.state.tr.delete(e,e+this.node.nodeSize).scrollIntoView())}handleMouseDown(t){if(this.isInteractiveTarget(t.target)){this.setFocused(!0),this.releaseNodeSelectionForControlEditing();return}this.setFocused(!1),this.shouldSelectNodeFromEvent(t)&&this.selectNodeForDrag()}handleFocusIn(t){this.setFocused(!0),this.isInteractiveTarget(t.target)&&this.releaseNodeSelectionForControlEditing()}selectNodeForDrag(){if(!this.props.editor.isEditable)return;const t=this.props.getPos();if(typeof t!="number")return;const{state:e}=this.props.view,n=e.tr.setSelection(y.NodeSelection.create(e.doc,t));n.setMeta("addToHistory",!1),this.props.view.dispatch(n),this.props.view.focus()}releaseNodeSelectionForControlEditing(){this.selected&&(this.selected=!1,this.dom.classList.remove(this.selectedClassName()),this.dom.removeAttribute("data-selected"),this.syncRootAttributes());const t=this.props.getPos();if(typeof t!="number")return;const{state:e}=this.props.view;if(e.selection.empty&&!(e.selection instanceof y.NodeSelection))return;const n=Math.min(t+this.node.nodeSize,e.doc.content.size),o=e.tr.setSelection(y.TextSelection.near(e.doc.resolve(n),1));o.setMeta("addToHistory",!1),this.props.view.dispatch(o)}shouldSelectNodeFromEvent(t){return t.button!==0||t.defaultPrevented?!1:!this.isInteractiveTarget(t.target)}shouldNavigateFromInteractiveTarget(t){if(!or(t))return!0;const e=t.target;if(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement))return!0;const n=e.selectionStart,o=e.selectionEnd;return n===null||o===null?!1:n!==o?n===0&&o===e.value.length:t.key==="ArrowLeft"||t.key==="Left"?n===0:t.key==="ArrowRight"||t.key==="Right"?o===e.value.length:!0}isInteractiveTarget(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLButtonElement}isDragEvent(t){return t.type.startsWith("drag")||t.type==="drop"}writeControlToClipboard(t){const e=this.clipboardText(),n=L.DOMSerializer.fromSchema(this.node.type.schema).serializeNode(this.node,{document:this.dom.ownerDocument});let o;if(n.nodeType===Node.ELEMENT_NODE)o=n;else{const s=ot.createElement(this.attrs,this.rootClassName(),this.reportNodeName(),e);this.decorateClipboardElement(s),o=s}return ot.write(t,o,e)}deleteEmptyControlFromInput(t){if(t.isComposing||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||t.key!=="Backspace"&&t.key!=="Delete")return!1;const e=t.target;if(!(e instanceof HTMLInputElement)||e.value.length!==0||e.selectionStart!==0||e.selectionEnd!==0)return!1;const n=this.props.getPos();if(typeof n!="number")return!1;t.preventDefault(),t.stopPropagation();const o=this.props.view.state.tr.delete(n,n+this.node.nodeSize),s=Math.min(n,o.doc.content.size),i=o.doc.resolve(s),a=i.parent.inlineContent?y.TextSelection.create(o.doc,s):y.TextSelection.near(i,1);return o.setSelection(a).scrollIntoView(),i.parent.inlineContent&&[i.nodeBefore,i.nodeAfter].some(l=>l?this.controlShortcutRuntime.controlNodeNames.includes(l.type.name):!1)&&Be(o,s),this.props.view.dispatch(o),this.props.view.focus(),!0}decorateClipboardElement(t){}}const xt="--hmg-report-editor-control-auto-width",hr=1,pr=1,Dt=2,fr=["font","font-family","font-feature-settings","font-kerning","font-optical-sizing","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-variation-settings","font-weight","letter-spacing","text-rendering","text-transform","word-spacing"];function ie(r,t){const e=r.value||" ",n=mr(r,e),o=n===null?`calc(${Math.max(gr(e),hr)}ch + ${Dt}px)`:`${Math.ceil(Math.max(n,pr)+Dt)}px`;t.style.getPropertyValue(xt)!==o&&t.style.setProperty(xt,o)}function mr(r,t){const e=r.ownerDocument,n=e.body;if(!n)return null;const o=e.createElement("span"),s=e.defaultView,i=s==null?void 0:s.getComputedStyle(r);if(i)for(const l of fr){const d=i.getPropertyValue(l);d&&o.style.setProperty(l,d)}o.textContent=t,o.style.position="absolute",o.style.left="-10000px",o.style.top="0",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.whiteSpace="pre",o.style.boxSizing="content-box",o.style.width="auto",o.style.minWidth="0",o.style.maxWidth="none",o.style.margin="0",o.style.padding="0",o.style.border="0",n.append(o);const a=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(a)&&a>0?a:null}function gr(r){let t=0;for(const e of r){const n=e.codePointAt(0)??0;t+=n>255?2:1}return t}class yr extends se{constructor(e,n){super(e,"dropdownField",n);p(this,"combo");p(this,"input");p(this,"menu");p(this,"open",!1);p(this,"activeOptionIndex",-1);p(this,"menuPortaled",!1);p(this,"handleViewportChange",()=>{this.open&&this.positionMenu()});this.combo=document.createElement("span"),this.combo.className="hmg-dropdown-field__combo",this.input=document.createElement("input"),this.input.className="hmg-dropdown-field__input",this.input.type="text",this.input.setAttribute("role","combobox"),this.input.setAttribute("aria-haspopup","listbox"),this.input.setAttribute("aria-expanded","false"),this.input.addEventListener("input",()=>{this.commitValue(this.input.value),this.setOpen(!0)}),this.input.addEventListener("mousedown",()=>this.setOpen(!0)),this.input.addEventListener("focus",()=>{this.setFocused(!0),this.setOpen(!0)}),this.input.addEventListener("blur",()=>this.setFocused(!1)),this.input.addEventListener("keydown",o=>this.handleDropdownShortcut(o)),this.menu=document.createElement("span"),this.menu.className="hmg-dropdown-field__menu",this.menu.setAttribute("role","listbox"),this.menu.addEventListener("mousedown",o=>o.preventDefault()),this.dom.addEventListener("focusout",()=>{var o;(o=this.dom.ownerDocument.defaultView)==null||o.setTimeout(()=>{this.dom.contains(this.dom.ownerDocument.activeElement)||this.setOpen(!1)},0)}),this.combo.append(this.input),this.dom.append(this.combo,this.menu),this.renderControl()}destroy(){this.unmountMenu(),this.menu.remove()}rootClassName(){return"hmg-dropdown-field"}focusedClassName(){return"hmg-dropdown-field--focused"}selectedClassName(){return"hmg-dropdown-field--selected"}reportNodeName(){return"dropdown-field"}clipboardText(){const e=this.attrs,n=e.value,o=n==null?"":String(n),s=this.normalizeOptions(e.options).find(i=>i.value===o);return s?s.label:this.isValueEmpty(n)?e.placeholder??"":o}decorateClipboardElement(e){const n=this.attrs;e.setAttribute("data-options",JSON.stringify(this.normalizeOptions(n.options))),e.setAttribute("data-allow-custom-text",String(n.allowCustomText!==!1))}renderControl(){this.syncRootAttributes();const e=this.attrs,n=this.normalizeOptions(e.options),o=e.value===null||e.value===void 0?"":String(e.value),s=n.find(l=>l.value===o),i=n.findIndex(l=>l.value===o),a=(s==null?void 0:s.label)??o;this.activeOptionIndex=this.open?i:-1,this.input.value=a,this.input.placeholder=e.placeholder??"",this.input.disabled=!this.props.editor.isEditable,this.input.required=!!e.required,this.input.setAttribute("aria-label",e.fieldName||e.fieldId||"editable dropdown text"),this.input.setAttribute("aria-expanded",String(this.open)),this.syncAutoWidth(),this.renderMenu(n,s==null?void 0:s.value),this.open&&this.positionMenu()}renderMenu(e,n){this.menu.innerHTML="";for(const[o,s]of e.entries()){const i=document.createElement("button");i.type="button",i.className="hmg-dropdown-field__option",i.textContent=s.label,i.setAttribute("role","option"),i.setAttribute("data-value",s.value),i.setAttribute("aria-selected",String(s.value===n)),i.toggleAttribute("data-active",this.activeOptionIndex===o),i.addEventListener("mousedown",a=>{a.preventDefault(),this.commitValue(s.value),this.input.focus(),this.setOpen(!1)}),this.menu.append(i)}this.menu.classList.toggle("hmg-dropdown-field__menu--empty",e.length===0),this.syncActiveOptionState()}setOpen(e){const n=e&&this.props.editor.isEditable,o=this.open;this.open=n,this.open&&!o&&this.syncActiveOptionFromValue(),this.open||(this.activeOptionIndex=-1),this.dom.classList.toggle("hmg-dropdown-field--open",this.open),this.dom.toggleAttribute("data-open",this.open),this.input.setAttribute("aria-expanded",String(this.open)),this.menu.classList.toggle("hmg-dropdown-field__menu--open",this.open),this.open?this.mountMenu():this.unmountMenu(),this.syncActiveOptionState()}mountMenu(){const e=this.dom.ownerDocument,n=e.body,o=e.defaultView;if(!n||!o)return;this.menuPortaled||(n.append(this.menu),e.addEventListener("scroll",this.handleViewportChange,!0),o.addEventListener("resize",this.handleViewportChange),this.menuPortaled=!0);const s=o.getComputedStyle(this.dom),i=s.getPropertyValue("--hmg-report-editor-dropdown-menu-z-index").trim();this.menu.style.font=s.font,this.menu.style.color=s.color,this.menu.style.zIndex=i||"2147483647",this.positionMenu()}unmountMenu(){if(!this.menuPortaled)return;const e=this.dom.ownerDocument,n=e.defaultView;e.removeEventListener("scroll",this.handleViewportChange,!0),n==null||n.removeEventListener("resize",this.handleViewportChange),this.menu.removeAttribute("style"),this.dom.isConnected?this.dom.append(this.menu):this.menu.remove(),this.menuPortaled=!1}positionMenu(){if(!this.menuPortaled)return;const e=this.dom.ownerDocument.defaultView;if(!e)return;const n=this.combo.getBoundingClientRect(),o=8,s=4;this.menu.style.position="fixed",this.menu.style.minWidth=`${Math.ceil(n.width)}px`,this.menu.style.left=`${Math.max(o,n.left)}px`,this.menu.style.top=`${n.bottom+s}px`;const i=this.menu.getBoundingClientRect(),a=Math.max(o,e.innerWidth-i.width-o),l=Math.min(Math.max(o,n.left),a),c=n.bottom+s+i.height<=e.innerHeight-o?n.bottom+s:Math.max(o,n.top-s-i.height);this.menu.style.left=`${Math.round(l)}px`,this.menu.style.top=`${Math.round(c)}px`}handleDropdownShortcut(e){if(e.defaultPrevented||!this.props.editor.isEditable||!this.controlShortcutRuntime.shortcuts.enabled)return;const{openDropdown:n,closeDropdown:o,nextDropdownOption:s,previousDropdownOption:i,selectDropdownOption:a}=this.controlShortcutRuntime.shortcuts;if(this.open&&P(e,o)){e.preventDefault(),this.setOpen(!1);return}if(P(e,s)){this.moveActiveOption("next")&&e.preventDefault();return}if(P(e,i)){this.moveActiveOption("previous")&&e.preventDefault();return}if(P(e,a)){if(this.open){if(this.selectActiveOptionFromKeyboard()){e.preventDefault();return}this.completeInputAndMaybeFocusNext(e);return}if(!this.open&&P(e,n)){e.preventDefault(),this.setOpen(!0);return}}if(P(e,n)){e.preventDefault(),this.setOpen(!0);return}this.completeInputAndMaybeFocusNext(e)}moveActiveOption(e){const n=this.normalizeOptions(this.attrs.options);if(n.length===0)return!1;this.open||this.setOpen(!0);const o=e==="next"?1:-1;return this.activeOptionIndex<0?this.activeOptionIndex=e==="next"?0:n.length-1:this.activeOptionIndex=(this.activeOptionIndex+o+n.length)%n.length,this.syncActiveOptionState(),!0}selectActiveOptionFromKeyboard(){const n=this.normalizeOptions(this.attrs.options)[this.activeOptionIndex];return n?(this.commitValue(n.value),this.input.value=n.label,this.syncAutoWidth(),this.setOpen(!1),this.controlShortcutRuntime.shortcuts.autoFocusNextOnEnter?this.focusAdjacentControlFromCurrent("next"):this.input.focus(),!0):!1}syncActiveOptionFromValue(){const e=this.attrs.value===null||this.attrs.value===void 0?"":String(this.attrs.value),n=this.normalizeOptions(this.attrs.options);this.activeOptionIndex=n.findIndex(o=>o.value===e)}syncActiveOptionState(){var n;const e=Array.from(this.menu.querySelectorAll(".hmg-dropdown-field__option"));for(const[o,s]of e.entries()){const i=this.open&&o===this.activeOptionIndex;s.toggleAttribute("data-active",i),i&&((n=s.scrollIntoView)==null||n.call(s,{block:"nearest"}))}}syncAutoWidth(){ie(this.input,this.dom)}normalizeOptions(e){if(typeof e=="string"&&e.trim())try{return _(JSON.parse(e))}catch{return[]}return _(e)}}class br extends se{constructor(e,n){super(e,"structuredField",n);p(this,"input");this.input=document.createElement("input"),this.input.className="hmg-structured-field__input",this.input.type="text",this.input.addEventListener("input",()=>this.commitValue(this.input.value)),this.input.addEventListener("focus",()=>this.setFocused(!0)),this.input.addEventListener("blur",()=>this.setFocused(!1)),this.input.addEventListener("keydown",o=>this.completeInputAndMaybeFocusNext(o)),this.dom.append(this.input),this.renderControl()}rootClassName(){return"hmg-structured-field"}focusedClassName(){return"hmg-structured-field--focused"}selectedClassName(){return"hmg-structured-field--selected"}reportNodeName(){return"structured-field"}clipboardText(){const e=this.attrs.value;return this.isValueEmpty(e)?this.attrs.placeholder??"":String(e)}renderControl(){this.syncRootAttributes();const e=this.attrs.value;this.input.value=e==null?"":String(e),this.input.placeholder=this.attrs.placeholder??"",this.input.disabled=!this.props.editor.isEditable,this.input.required=!!this.attrs.required,this.input.setAttribute("aria-label",this.attrs.fieldName||this.attrs.fieldId||"structured field"),this.syncAutoWidth()}syncAutoWidth(){ie(this.input,this.dom)}}function Pt(r){if(Array.isArray(r))return _(r);if(typeof r!="string"||!r.trim())return[];try{const t=JSON.parse(r);return Array.isArray(t)?_(t):[]}catch{return[]}}function Sr(r){if(Array.isArray(r))return r;if(typeof r!="string"||!r.trim())return[];try{const t=JSON.parse(r);return Array.isArray(t)?t:[]}catch{return[]}}const Cr=C.Node.create({name:"dropdownField",group:"inline",inline:!0,atom:!0,selectable:!0,addOptions(){return{controlShortcutRuntime:lt()}},addAttributes(){return{controlId:{default:null,parseHTML:r=>r.getAttribute("data-control-id")},batchId:{default:null,parseHTML:r=>r.getAttribute("data-batch-id")},templateId:{default:"",parseHTML:r=>r.getAttribute("data-template-id")??""},widgetNumber:{default:"",parseHTML:r=>r.getAttribute("data-widget-number")??""},fieldId:{default:"",parseHTML:r=>r.getAttribute("data-field-id")??""},fieldName:{default:"",parseHTML:r=>r.getAttribute("data-field-name")??""},value:{default:null,parseHTML:r=>nt(r.getAttribute("data-value"),r.getAttribute("data-value-type"))},defaultValue:{default:null,parseHTML:r=>nt(r.getAttribute("data-default-value"),r.getAttribute("data-default-value-type"))},placeholder:{default:"",parseHTML:r=>r.getAttribute("data-placeholder")??""},required:{default:!1,parseHTML:r=>r.getAttribute("data-required")==="true"},hideWhenEmpty:{default:!1,parseHTML:r=>r.getAttribute("data-hide-when-empty")==="true"},noMatchDefault:{default:!1,parseHTML:r=>r.getAttribute("data-no-match-default")==="true"},rules:{default:[],parseHTML:r=>Sr(r.getAttribute("data-rules")),renderHTML:r=>({"data-rules":JSON.stringify(r.rules??[])})},nextWidgetNumber:{default:"",parseHTML:r=>r.getAttribute("data-next-widget-number")??""},ruleStyleColor:{default:null,parseHTML:r=>r.getAttribute("data-rule-style-color")},allowCustomText:{default:!0,parseHTML:r=>r.getAttribute("data-allow-custom-text")!=="false"},options:{default:[],parseHTML:r=>Pt(r.getAttribute("data-options")),renderHTML:r=>({"data-options":JSON.stringify(r.options??[])})}}},parseHTML(){return[{tag:'span[data-report-node="dropdown-field"]',priority:1e3}]},renderHTML({HTMLAttributes:r}){const e=Pt(r.options??r["data-options"]).find(s=>s.value===String(r.value??"")),n=(e==null?void 0:e.label)??($.isEmpty(r.value)?r.placeholder:r.value),o=k.sanitize("color",r.ruleStyleColor);return["span",C.mergeAttributes(r,{"data-report-node":"dropdown-field","data-control-id":r.controlId,"data-batch-id":r.batchId,"data-template-id":r.templateId,"data-widget-number":r.widgetNumber,"data-field-id":r.fieldId,"data-field-name":r.fieldName,"data-value":r.value,"data-value-type":R(r.value),"data-default-value":r.defaultValue,"data-default-value-type":R(r.defaultValue),"data-placeholder":r.placeholder,"data-required":String(!!r.required),"data-hide-when-empty":String(!!r.hideWhenEmpty),"data-no-match-default":String(!!r.noMatchDefault),"data-rules":JSON.stringify(r.rules??[]),"data-next-widget-number":r.nextWidgetNumber,"data-rule-style-color":o,"data-allow-custom-text":String(r.allowCustomText!==!1),style:o?`color: ${o}`:void 0,class:"hmg-dropdown-field"}),String(n??"")]},addNodeView(){return r=>new yr(r,this.options.controlShortcutRuntime)},addCommands(){return{insertDropdownField:r=>({commands:t})=>t.insertContent({type:this.name,attrs:r})}}}),Ir=C.Extension.create({name:"fontSize",addGlobalAttributes(){return[{types:["textStyle"],attributes:{fontSize:{default:null,parseHTML:r=>k.sanitize("font-size",r.style.fontSize)??null,renderHTML:r=>{const t=k.sanitize("font-size",r.fontSize);return t?{style:`font-size: ${t}`}:{}}}}}]},addCommands(){return{setFontSize:r=>({chain:t})=>k.sanitize("font-size",r)?t().setMark("textStyle",{fontSize:r}).run():!1,unsetFontSize:()=>({chain:r})=>r().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),Er=C.Extension.create({name:"hiddenParagraph",addGlobalAttributes(){return[{types:["paragraph"],attributes:{hidden:{default:!1,parseHTML:r=>r.getAttribute("data-hidden")==="true",renderHTML:r=>r.hidden?{"data-hidden":"true",class:"hmg-hidden-paragraph"}:{}}}}]},addCommands(){return{toggleHiddenParagraph:()=>({state:r,dispatch:t})=>{const{$from:e}=r.selection;for(let n=e.depth;n>0;n-=1){const o=e.node(n);if(o.type.name==="paragraph"){const s=e.before(n),i=!!o.attrs.hidden;return t&&t(r.tr.setNodeMarkup(s,void 0,{...o.attrs,hidden:!i})),!0}}return!1},setParagraphHidden:r=>({state:t,dispatch:e})=>{const{$from:n}=t.selection;for(let o=n.depth;o>0;o-=1){const s=n.node(o);if(s.type.name==="paragraph"){const i=n.before(o);return e&&e(t.tr.setNodeMarkup(i,void 0,{...s.attrs,hidden:r})),!0}}return!1}}}}),wr=0,Nr=8,vr=["paragraph","listItem","reportNumberedBlock"];function Tr(r){return Math.max(wr,Math.min(Nr,r))}function ae(r=vr){const t=Array.from(new Set(r));return C.Extension.create({name:"indentation",addGlobalAttributes(){return[{types:t,attributes:{indent:{default:0,parseHTML:e=>Number(e.getAttribute("data-indent")??0),renderHTML:e=>{const n=Number(e.indent??0);return n<=0?{}:{"data-indent":String(n),style:`margin-left: ${n*2}em`}}}}}]},addCommands(){const e=n=>({state:o,dispatch:s})=>{const i=o.tr;let a=!1;return o.doc.nodesBetween(o.selection.from,o.selection.to,(l,d)=>{if(t.includes(l.type.name)){const c=Number(l.attrs.indent??0),h=Tr(n(c));i.setNodeMarkup(d,void 0,{...l.attrs,indent:h}),a=!0}}),a&&s&&s(i),a};return{increaseIndent:()=>e(n=>n+1),decreaseIndent:()=>e(n=>n-1),setIndent:n=>e(()=>n)}}})}ae();const Ar=["paragraph","listItem","reportNumberedBlock"];function le(r=Ar){const t=Array.from(new Set(r));return C.Extension.create({name:"lineHeight",addGlobalAttributes(){return[{types:t,attributes:{lineHeight:{default:null,parseHTML:e=>k.sanitize("line-height",e.style.lineHeight)??null,renderHTML:e=>{const n=k.sanitize("line-height",e.lineHeight);return n?{style:`line-height: ${n}`}:{}}}}}]},addCommands(){const e=n=>({state:o,dispatch:s})=>{if(n!==null&&!k.sanitize("line-height",n))return!1;const i=o.tr;let a=!1;const l=(d,c)=>{t.includes(d.type.name)&&(i.setNodeMarkup(c,void 0,{...d.attrs,lineHeight:n}),a=!0)};return o.selection.empty||o.doc.nodesBetween(o.selection.from,o.selection.to,l),a&&s&&s(i),a};return{setLineHeight:n=>e(n),unsetLineHeight:()=>e(null)}}})}le();const x="pageBreak";function j(r=new Set){let t=Bt();for(;r.has(t);)t=Bt();return r.add(t),t}class de{normalizeDocument(t){const e=new Set;return{...t,content:this.normalizeReportNodes(t.content??[],e)}}collectTransactionUpdates(t){const e=new Set,n=[];return t.descendants((o,s)=>{if(o.type.name!==x)return;const i=this.getId(o.attrs);if(!i||e.has(i)){n.push({pos:s,id:j(e)});return}e.add(i)}),n}assignFreshIdsToSlice(t){return new L.Slice(this.assignFreshIdsToFragment(t.content),t.openStart,t.openEnd)}applyToEditor(t){const e=this.collectTransactionUpdates(t.state.doc);if(e.length===0)return!1;const n=t.state.tr;n.setMeta("addToHistory",!1);for(const o of e){const s=n.doc.nodeAt(o.pos);(s==null?void 0:s.type.name)===x&&n.setNodeMarkup(o.pos,void 0,{...s.attrs,id:o.id},s.marks)}return t.view.dispatch(n),!0}normalizeReportNodes(t,e){return t.map(n=>{const o=n.content?this.normalizeReportNodes(n.content,e):void 0;if(n.type!==x)return{...n,...o?{content:o}:{}};const s={...n.attrs??{}},i=this.getId(s);return!i||e.has(i)?s.id=j(e):(s.id=i,e.add(i)),{...n,attrs:s}})}assignFreshIdsToFragment(t){const e=[];return t.forEach(n=>{e.push(this.assignFreshIdsToNode(n))}),L.Fragment.fromArray(e)}assignFreshIdsToNode(t){if(t.isText)return t;const e=t.content.size>0?this.assignFreshIdsToFragment(t.content):t.content;return t.type.name===x?t.type.create({...t.attrs,id:j()},e,t.marks):e===t.content?t:t.copy(e)}getId(t){const e=t==null?void 0:t.id;return typeof e=="string"&&e.trim()?e:void 0}}function Bt(){const r=globalThis.crypto;return r!=null&&r.randomUUID?`page_break_${r.randomUUID()}`:`page_break_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}class Mr{constructor(t){p(this,"dom");p(this,"node");p(this,"selected",!1);this.node=t.node,this.dom=document.createElement("span"),this.dom.contentEditable="false",this.dom.draggable=!0,this.dom.setAttribute("role","separator"),this.dom.setAttribute("aria-label","报告将在此处分页"),this.render()}update(t){return t.type.name!==this.node.type.name?!1:(this.node=t,this.render(),!0)}selectNode(){this.selected=!0,this.dom.classList.add("hmg-page-break--selected")}deselectNode(){this.selected=!1,this.dom.classList.remove("hmg-page-break--selected")}ignoreMutation(){return!0}render(){const t=String(this.node.attrs.id??"");this.dom.className="split-line editor2-item hmg-page-break",this.dom.id=t,this.dom.dataset.editor2Id=t,this.dom.innerHTML='<span class="hmg-page-break__label">报告将在此处分页</span>',this.dom.classList.toggle("hmg-page-break--selected",this.selected)}}const kr=C.Node.create({name:x,group:"inline",inline:!0,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{id:{default:null,parseHTML:r=>r.getAttribute("data-editor2-id")??r.getAttribute("id")}}},parseHTML(){return[{tag:"span.split-line.editor2-item"}]},renderHTML({node:r}){const t=String(r.attrs.id??"");return["span",{class:"split-line editor2-item",id:t,"data-editor2-id":t}]},addNodeView(){return r=>new Mr(r)},addCommands(){return{insertPageBreak:()=>({editor:r,state:t,tr:e,commands:n,dispatch:o})=>{var c;if(!r.isEditable)return!1;const{selection:s}=t;if(!(s instanceof y.NodeSelection))return n.insertContent({type:this.name,attrs:{id:j()}});const i=(c=t.schema.nodes[this.name])==null?void 0:c.create({id:j()});if(!i)return!1;if(s.node.isInline){const h=s.to;return s.$to.parent.canReplaceWith(s.$to.index(),s.$to.index(),i.type)?(o&&(e.insert(h,i),e.setSelection(y.Selection.near(e.doc.resolve(h+i.nodeSize),1)),e.scrollIntoView()),!0):!1}const a=t.schema.nodes.paragraph;if(!a)return!1;const l=a.create(null,i),d=_t.insertPoint(t.doc,s.to,a);if(d===null)return!1;if(o){e.insert(d,l);const h=Math.min(d+2,e.doc.content.size);e.setSelection(y.Selection.near(e.doc.resolve(h),1)),e.scrollIntoView()}return!0},deletePageBreak:r=>({editor:t,tr:e,dispatch:n})=>{if(!t.isEditable)return!1;const o=ce(t,r);return o===void 0?!1:ue(t,e,o,-1,!!n)}}},addKeyboardShortcuts(){return{Backspace:()=>Ot(this.editor,-1),Delete:()=>Ot(this.editor,1)}}});function ce(r,t,e){var o,s;if(t){let i;return r.state.doc.descendants((a,l)=>{i===void 0&&a.type.name===x&&a.attrs.id===t&&(i=l)}),i}const{selection:n}=r.state;if(n instanceof y.NodeSelection&&n.node.type.name===x)return n.from;if(!(!n.empty||e===void 0)){if(e<0&&((o=n.$from.nodeBefore)==null?void 0:o.type.name)===x)return n.from-n.$from.nodeBefore.nodeSize;if(e>0&&((s=n.$from.nodeAfter)==null?void 0:s.type.name)===x)return n.from}}function Ot(r,t){if(!r.isEditable)return!1;const e=ce(r,void 0,t);if(e===void 0)return!1;const n=r.state.tr;return ue(r,n,e,t,!0)?(r.view.dispatch(n),!0):!1}function ue(r,t,e,n,o){const{state:s}=r,i=t.doc.nodeAt(e);if((i==null?void 0:i.type.name)!==x)return!1;if(!o)return!0;const a=t.doc.resolve(e),l=a.parent,d=a.depth===1&&l.type.name==="paragraph"&&l.childCount===1&&s.doc.childCount>1;let c=e;if(d){const h=a.before(1);t.delete(h,h+l.nodeSize),c=h}else t.delete(e,e+i.nodeSize);return c=Math.max(0,Math.min(c,t.doc.content.size)),t.setSelection(y.Selection.near(t.doc.resolve(c),n)),t.scrollIntoView(),!0}const xr=C.Node.create({name:"reportNumberedBlock",group:"block",content:"inline*",draggable:!0,addAttributes(){return{number:{default:null,parseHTML:r=>r.getAttribute("data-number")},manualNumber:{default:!1,parseHTML:r=>r.getAttribute("data-manual-number")==="true"}}},parseHTML(){return[{tag:'div[data-report-node="numbered-block"]',contentElement:r=>r.querySelector(".hmg-numbered-block__content")??r}]},renderHTML({HTMLAttributes:r}){const t=r.number??"";return["div",C.mergeAttributes(r,{"data-report-node":"numbered-block","data-number":t,"data-manual-number":String(!!r.manualNumber),class:"hmg-numbered-block"}),["span",{class:"hmg-numbered-block__number"},t?`${t}.`:""],["span",{class:"hmg-numbered-block__content"},0]]},addCommands(){return{insertNumberedBlock:(r="")=>({commands:t})=>t.insertContent({type:this.name,attrs:{number:null,manualNumber:!1},content:r?[{type:"text",text:r}]:[]})}}});function Dr(r){if(Array.isArray(r))return r;if(typeof r!="string"||!r.trim())return[];try{const t=JSON.parse(r);return Array.isArray(t)?t:[]}catch{return[]}}const Pr=C.Node.create({name:"structuredField",group:"inline",inline:!0,atom:!0,selectable:!0,addOptions(){return{controlShortcutRuntime:lt()}},addAttributes(){return{controlId:{default:null,parseHTML:r=>r.getAttribute("data-control-id")},batchId:{default:null,parseHTML:r=>r.getAttribute("data-batch-id")},templateId:{default:"",parseHTML:r=>r.getAttribute("data-template-id")??""},widgetNumber:{default:"",parseHTML:r=>r.getAttribute("data-widget-number")??""},fieldId:{default:"",parseHTML:r=>r.getAttribute("data-field-id")??""},fieldName:{default:"",parseHTML:r=>r.getAttribute("data-field-name")??""},value:{default:null,parseHTML:r=>nt(r.getAttribute("data-value"),r.getAttribute("data-value-type"))},defaultValue:{default:null,parseHTML:r=>nt(r.getAttribute("data-default-value"),r.getAttribute("data-default-value-type"))},placeholder:{default:"",parseHTML:r=>r.getAttribute("data-placeholder")??""},required:{default:!1,parseHTML:r=>r.getAttribute("data-required")==="true"},hideWhenEmpty:{default:!1,parseHTML:r=>r.getAttribute("data-hide-when-empty")==="true"},noMatchDefault:{default:!1,parseHTML:r=>r.getAttribute("data-no-match-default")==="true"},rules:{default:[],parseHTML:r=>Dr(r.getAttribute("data-rules")),renderHTML:r=>({"data-rules":JSON.stringify(r.rules??[])})},nextWidgetNumber:{default:"",parseHTML:r=>r.getAttribute("data-next-widget-number")??""},ruleStyleColor:{default:null,parseHTML:r=>r.getAttribute("data-rule-style-color")}}},parseHTML(){return[{tag:'span[data-report-node="structured-field"]',priority:1e3}]},renderHTML({HTMLAttributes:r}){const t=$.isEmpty(r.value)?r.placeholder:r.value,e=k.sanitize("color",r.ruleStyleColor);return["span",C.mergeAttributes(r,{"data-report-node":"structured-field","data-control-id":r.controlId,"data-batch-id":r.batchId,"data-template-id":r.templateId,"data-widget-number":r.widgetNumber,"data-field-id":r.fieldId,"data-field-name":r.fieldName,"data-value":r.value,"data-value-type":R(r.value),"data-default-value":r.defaultValue,"data-default-value-type":R(r.defaultValue),"data-placeholder":r.placeholder,"data-required":String(!!r.required),"data-hide-when-empty":String(!!r.hideWhenEmpty),"data-no-match-default":String(!!r.noMatchDefault),"data-rules":JSON.stringify(r.rules??[]),"data-next-widget-number":r.nextWidgetNumber,"data-rule-style-color":e,style:e?`color: ${e}`:void 0,class:"hmg-structured-field"}),String(t??"")]},addNodeView(){return r=>new br(r,this.options.controlShortcutRuntime)},addCommands(){return{insertStructuredField:r=>({commands:t})=>t.insertContent({type:this.name,attrs:r})}}}),Br=C.Mark.create({name:w,inclusive:!1,keepOnSplit:!1,spanning:!0,exitable:!0,excludes:w,addAttributes(){return{groupId:{default:null,parseHTML:r=>r.getAttribute("data-visibility-group-id"),renderHTML:r=>({"data-visibility-group-id":r.groupId})},condition:{default:null,parseHTML:r=>r.getAttribute("data-visibility-condition"),renderHTML:r=>({"data-visibility-condition":r.condition})}}},parseHTML(){return[{tag:'span[data-report-mark="visibility-group"]'}]},renderHTML({HTMLAttributes:r}){return["span",C.mergeAttributes(r,{class:"hmg-visibility-group","data-report-mark":"visibility-group"}),0]}}),W=new y.PluginKey("reportControlSelectionLifecycle"),Or="hmg-control-range-selected";function Fr(r){const t=new Set(r);return C.Extension.create({name:"reportControlSelectionLifecycle",addProseMirrorPlugins(){return[new y.Plugin({key:W,state:{init:(e,n)=>({focused:!0,decorations:Ft(n,t)}),apply:(e,n,o,s)=>{const a=e.getMeta(W)??n.focused;return{focused:a,decorations:a?Ft(s,t):F.DecorationSet.empty}}},props:{decorations(e){var n;return(n=W.getState(e))==null?void 0:n.decorations},handleDOMEvents:{focus(e){return Rr(e,!0),!1},blur(e){return Lr(e,t,!1),!1}}}})]}})}function Lr(r,t,e){const{selection:n}=r.state,o=r.state.tr;if(n instanceof y.NodeSelection&&t.has(n.node.type.name)){const s=Math.min(n.to,r.state.doc.content.size);o.setSelection(y.TextSelection.near(r.state.doc.resolve(s),1))}o.setMeta(W,e),o.setMeta("addToHistory",!1),r.dispatch(o)}function Rr(r,t){const e=W.getState(r.state);if((e==null?void 0:e.focused)===t)return;const n=r.state.tr.setMeta(W,t);n.setMeta("addToHistory",!1),r.dispatch(n)}function Ft(r,t){const{selection:e}=r;if(e.empty||e instanceof y.NodeSelection)return F.DecorationSet.empty;const n=[];return r.doc.nodesBetween(e.from,e.to,(o,s)=>{t.has(o.type.name)&&s>=e.from&&s+o.nodeSize<=e.to&&n.push(F.Decoration.node(s,s+o.nodeSize,{class:Or,"data-range-selected":"true"}))}),n.length>0?F.DecorationSet.create(r.doc,n):F.DecorationSet.empty}class he{constructor(t="reportNumberedBlock"){this.nodeName=t}collectBlocks(t){const e=[];return t.descendants((n,o)=>{n.type.name===this.nodeName&&e.push({node:n,pos:o})}),e}collectUpdates(t){const e=[];let n=1;return t.descendants((o,s)=>{if(o.type.name===this.nodeName){if(!o.attrs.manualNumber){const i=String(n);o.attrs.number!==i&&e.push({pos:s,number:i})}n+=1}}),e}applyToTransaction(t){for(const e of this.collectUpdates(t.doc)){const n=t.doc.nodeAt(e.pos);(n==null?void 0:n.type.name)===this.nodeName&&t.setNodeMarkup(e.pos,void 0,{...n.attrs,number:e.number,manualNumber:!1})}return t}applyToEditor(t,e=!1){const n=this.collectUpdates(t.state.doc);if(n.length===0)return!1;const o=t.state.tr;o.setMeta("addToHistory",e);for(const s of n){const i=o.doc.nodeAt(s.pos);(i==null?void 0:i.type.name)===this.nodeName&&o.setNodeMarkup(s.pos,void 0,{...i.attrs,number:s.number,manualNumber:!1})}return t.view.dispatch(o),!0}moveBlock(t,e,n){const o=this.collectBlocks(t.state.doc),s=o[e],i=o[n];if(!s||!i||e===n)return!1;const a=t.state.tr,l=s.node.nodeSize,d=s.pos+l,c=n>e?i.pos-l+i.node.nodeSize:i.pos;return a.delete(s.pos,d),a.insert(c,s.node),this.applyToTransaction(a),t.view.dispatch(a.scrollIntoView()),!0}}class Vr{constructor(t="reportNumberedBlock",e=new he(t)){this.nodeName=t,this.service=e}create(){return new y.Plugin({appendTransaction:(t,e,n)=>{if(!t.some(i=>i.docChanged)||oe(t))return null;const o=this.service.collectUpdates(n.doc);if(o.length===0)return null;const s=n.tr;s.setMeta("addToHistory",!1);for(const i of o){const a=s.doc.nodeAt(i.pos);(a==null?void 0:a.type.name)===this.nodeName&&s.setNodeMarkup(i.pos,void 0,{...a.attrs,number:i.number,manualNumber:!1})}return s}})}}function pe(r="reportNumberedBlock"){return C.Extension.create({name:"numbering",addProseMirrorPlugins(){return[new Vr(r).create()]}})}pe();const zr=C.Extension.create({name:"textColor",addGlobalAttributes(){return[{types:["textStyle"],attributes:{color:{default:null,parseHTML:r=>k.sanitize("color",r.style.color)??null,renderHTML:r=>{const t=k.sanitize("color",r.color);return t?{style:`color: ${t}`}:{}}}}}]},addCommands(){return{setTextColor:r=>({chain:t})=>k.sanitize("color",r)?t().setMark("textStyle",{color:r}).run():!1,unsetTextColor:()=>({chain:r})=>r().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}});function st(r){return r.attrs??{}}function J(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function V(r,t,e,n=!1){const o=r[t];if(!(o===void 0||n&&o===null)&&typeof o!="string")throw new Error(`${e} ${t} must be a string.`)}function tt(r,t,e){const n=r[t];if(n!==void 0&&typeof n!="boolean")throw new Error(`${e} ${t} must be a boolean.`)}function Lt(r,t,e,n=!1){const o=r[t];if(!(o===void 0&&!n)&&!ur(o))throw new Error(`${e} ${t} must be string, finite number, boolean or null.`)}function $r(r){if(r!==void 0){if(!Array.isArray(r))throw new Error("Control rules must be an array.");for(const t of r){if(!J(t))throw new Error("Control rule must be an object.");if(typeof t.title!="string")throw new Error("Control rule requires title.");const e=t.contents??t.list;e!==void 0&&_r(e)}}}function _r(r){if(!Array.isArray(r))throw new Error("Control rule contents must be an array.");for(const t of r){if(!J(t))throw new Error("Control rule content must be an object.");const e=t.premises??t.premiss;if(e!==void 0&&Hr(e),!J(t.result))throw new Error("Control rule content requires result.");Ur(t.result)}}function Hr(r){if(!Array.isArray(r))throw new Error("Control rule premises must be an array.");for(const t of r){if(!J(t))throw new Error("Control rule premise must be an object.");if(typeof t.condition!="string")throw new Error("Control rule premise requires condition.");if(t.entryType!=="input"&&t.entryType!=="math")throw new Error("Control rule premise entryType must be input or math.");if(typeof t.inputSerialMath!="string")throw new Error("Control rule premise requires inputSerialMath.");t.conditionRange!==void 0&&Gr(t.conditionRange)}}function Gr(r){if(!J(r))throw new Error("Control rule conditionRange must be an object.");for(const t of["symbol1","symbol2"]){const e=r[t];if(e!==void 0&&typeof e!="string")throw new Error(`Control rule conditionRange ${t} must be a string.`)}for(const t of["number1","number2"]){const e=r[t];if(e!==void 0&&typeof e!="string"&&typeof e!="number")throw new Error(`Control rule conditionRange ${t} must be a string or number.`)}}function Ur(r){if(typeof r.type!="string")throw new Error("Control rule result requires type.");if(typeof r.value!="string")throw new Error("Control rule result requires value.");for(const t of["style","bStyle","exact"]){const e=r[t];if(e!==void 0&&typeof e!="boolean")throw new Error(`Control rule result ${t} must be a boolean.`)}if(r.styleValue!==void 0&&typeof r.styleValue!="string")throw new Error("Control rule result styleValue must be a string.");if(r.exactNum!==void 0&&typeof r.exactNum!="number")throw new Error("Control rule result exactNum must be a number.");if(r.exactType!==void 0&&typeof r.exactType!="string")throw new Error("Control rule result exactType must be a string.")}function ft(r){if(typeof r.fieldId!="string"||!r.fieldId.trim()||typeof r.fieldName!="string"||!r.fieldName.trim())throw new Error("Structured field requires fieldId and fieldName.");V(r,"controlId","Structured field",!0),V(r,"batchId","Structured field",!0),V(r,"templateId","Structured field"),V(r,"widgetNumber","Structured field"),Lt(r,"value","Structured field",!0),Lt(r,"defaultValue","Structured field"),V(r,"placeholder","Structured field"),tt(r,"required","Structured field"),tt(r,"hideWhenEmpty","Structured field"),tt(r,"noMatchDefault","Structured field"),$r(r.rules),V(r,"nextWidgetNumber","Structured field"),V(r,"ruleStyleColor","Structured field",!0)}function Rt(r){if(ft(r),!Array.isArray(r.options))throw new Error("Dropdown field requires options.");for(const t of r.options)if(!J(t)||typeof t.label!="string"||typeof t.value!="string")throw new Error("Dropdown option requires string label and value.");tt(r,"allowCustomText","Dropdown field")}function fe(r,t=!1){const e=[` data-control-id="${S.attr(r.controlId??"")}"`,` data-field-id="${S.attr(r.fieldId)}"`,` data-field-name="${S.attr(r.fieldName)}"`];return t&&r.value!==null&&r.value!==void 0&&(e.push(` data-value="${S.attr(r.value)}"`),e.push(` data-value-type="${R(r.value)}"`)),t&&(e.push(` data-batch-id="${S.attr(r.batchId??"")}"`),e.push(` data-template-id="${S.attr(r.templateId??"")}"`),e.push(` data-widget-number="${S.attr(r.widgetNumber??"")}"`),r.defaultValue!==null&&r.defaultValue!==void 0&&(e.push(` data-default-value="${S.attr(r.defaultValue)}"`),e.push(` data-default-value-type="${R(r.defaultValue)}"`)),e.push(` data-placeholder="${S.attr(r.placeholder??"")}"`),e.push(` data-no-match-default="${String(!!r.noMatchDefault)}"`),e.push(` data-rules="${S.attr(JSON.stringify(r.rules??[]))}"`),e.push(` data-next-widget-number="${S.attr(r.nextWidgetNumber??"")}"`),e.push(` data-rule-style-color="${S.attr(k.sanitize("color",r.ruleStyleColor)??"")}"`)),e.push(` data-required="${String(!!r.required)}"`),e.push(` data-hide-when-empty="${String(!!r.hideWhenEmpty)}"`),e}function me(r){return new gt().addSafe("color",r.ruleStyleColor).toAttribute()}function qr(r,t=!1){const e=fe(r,t),n=_(r.options);return t&&(e.push(` data-options="${S.attr(JSON.stringify(n))}"`),e.push(` data-allow-custom-text="${String(r.allowCustomText!==!1)}"`)),e}function jr(r,t){var n,o,s;return`<span${new gt().addSafe("font-family",(n=r.attrs)==null?void 0:n.fontFamily).addSafe("font-size",(o=r.attrs)==null?void 0:o.fontSize).addSafe("color",(s=r.attrs)==null?void 0:s.color).toAttribute()}>${t}</span>`}function Q(r){return(t,e)=>`<${r}>${e}</${r}>`}function G(){return(r,t)=>t}function Wr(r){at(r)}const Jr=[{markName:w,validateAttrs:Wr,renderHTML:(r,t,e)=>{var s,i;if(e.mode!=="edit")return t;const n=S.attr((s=r.attrs)==null?void 0:s.groupId),o=S.attr((i=r.attrs)==null?void 0:i.condition);return['<span class="hmg-visibility-group"',' data-report-mark="visibility-group"',` data-visibility-group-id="${n}"`,` data-visibility-condition="${o}">`,t,"</span>"].join("")},renderText:G()},{markName:"bold",renderHTML:Q("strong"),renderText:G()},{markName:"italic",renderHTML:Q("em"),renderText:G()},{markName:"underline",renderHTML:Q("u"),renderText:G()},{markName:"strike",renderHTML:Q("s"),renderText:G()},{markName:"textStyle",renderHTML:(r,t,e)=>jr(r,t),renderText:G()}],Kr={nodeName:"structuredField",templateType:"structuredField",dataNode:"structured-field",extension:Pr,isInline:!0,isControl:!0,validateAttrs:ft,validateTemplate(r){ft(st(r))},toProseMirrorNode(r,t){return{type:"structuredField",attrs:t.withFreshControlId(st(r))}},renderHTML(r,t){const e=r.attrs??{fieldId:"",fieldName:"",value:null},n=$.isEmpty(e.value);if(t.mode!=="edit"&&e.hideWhenEmpty&&n)return"";const o=n?e.placeholder??"":e.value;return t.mode!=="edit"?S.text(o):[`<span class="hmg-structured-field${n?" hmg-structured-field--empty":""}"`,' data-report-node="structured-field"',...fe(e,t.mode==="edit"),me(e),">",S.text(o),"</span>"].join("")},renderText(r){const t=r.attrs??{value:null},n=$.isEmpty(t.value)?t.placeholder??"":t.value;return String(n??"")}},Xr={nodeName:"dropdownField",templateType:"dropdownField",dataNode:"dropdown-field",extension:Cr,isInline:!0,isControl:!0,validateAttrs:Rt,validateTemplate(r){Rt(st(r))},toProseMirrorNode(r,t){return{type:"dropdownField",attrs:t.withFreshControlId(st(r))}},renderHTML(r,t){const e=r.attrs??{fieldId:"",fieldName:"",value:null,options:[]},n=$.isEmpty(e.value);if(t.mode!=="edit"&&e.hideWhenEmpty&&n)return"";const s=_(e.options).find(l=>l.value===String(e.value??""));!n&&!s&&e.allowCustomText===!1&&t.warn("DROPDOWN_OPTION_NOT_FOUND",`Dropdown option not found: ${e.fieldId}.`,e);const i=(s==null?void 0:s.label)??(n?e.placeholder??"":e.value);return t.mode!=="edit"?S.text(i):[`<span class="hmg-dropdown-field${n?" hmg-dropdown-field--empty":""}"`,' data-report-node="dropdown-field"',...qr(e,t.mode==="edit"),me(e),">",S.text(i),"</span>"].join("")},renderText(r,t){const e=r.attrs??{fieldId:"",fieldName:"",value:null,options:[]},n=$.isEmpty(e.value),s=_(e.options).find(a=>a.value===String(e.value??""));!n&&!s&&e.allowCustomText===!1&&t.warn("DROPDOWN_OPTION_NOT_FOUND",`Dropdown option not found: ${e.fieldId}.`,e);const i=(s==null?void 0:s.label)??(n?e.placeholder??"":e.value);return String(i??"")}},Yr={nodeName:"reportNumberedBlock",templateType:"numberedBlock",dataNode:"numbered-block",extension:xr,supportsBlockFormatting:!0,isNumberedBlock:!0,validateTemplate(r,t){t.validateChildren(r.content)},toProseMirrorNode(r,t){var e,n;return{type:"reportNumberedBlock",attrs:{number:String(((e=r.attrs)==null?void 0:e.number)??"")||null,manualNumber:!!((n=r.attrs)!=null&&n.manualNumber)},content:t.toContent(r.content)}},renderHTML(r,t){var s,i;const e=String(((s=r.attrs)==null?void 0:s.number)??""),n=!!((i=r.attrs)!=null&&i.manualNumber),o=t.renderContent(r.content);return t.mode!=="edit"&&!o.trim()&&ge(r.content,"pageBreak")?"":[`<div${t.renderBlockAttrs(r,"hmg-numbered-block")}`,' data-report-node="numbered-block"',` data-number="${S.attr(e)}"`,` data-manual-number="${String(n)}"`,">",`<span class="hmg-numbered-block__number">${S.text(e?`${e}.`:"")}</span>`,`<span class="hmg-numbered-block__content">${o}</span>`,"</div>"].join("")},renderText(r,t){var o;const e=String(((o=r.attrs)==null?void 0:o.number)??""),n=t.renderContent(r.content);return e?n?`${e}. ${n}`:`${e}.`:n}};function ge(r,t){return(r??[]).some(e=>e.type===t||ge(e.content,t))}const Zr={nodeName:"pageBreak",templateType:"pageBreak",dataNode:"page-break",extension:kr,isInline:!0,toProseMirrorNode(){return{type:"pageBreak",attrs:{id:j()}}},renderHTML(r){const t=r.attrs??{id:""},e=S.attr(t.id);return`<span class="split-line editor2-item" id="${e}" data-editor2-id="${e}"></span>`},renderText(){return""}},Qr=[Kr,Xr,Yr,Zr],tn={name:"hmg-base",extensions:[Br,ve,Ae,Te,Ir,zr,Me,Er],marks:Jr},en={name:"hmg-report-nodes",nodes:Qr},rn=[tn,en];class nn{constructor(t){p(this,"featureList",[]);p(this,"byFeatureName",new Map);p(this,"byNodeName",new Map);p(this,"byTemplateType",new Map);p(this,"byMarkName",new Map);for(const e of t)this.registerFeature(e)}features(){return[...this.featureList]}descriptors(){return Array.from(this.byNodeName.values())}markDescriptors(){return Array.from(this.byMarkName.values())}extensions(){return[...this.featureList.flatMap(t=>t.extensions??[]),...this.descriptors().map(t=>t.extension)]}getByNodeName(t){return this.byNodeName.get(t)}getByTemplateType(t){return this.byTemplateType.get(t)}getMarkDescriptor(t){return this.byMarkName.get(t)}isControlNode(t){var e;return!!((e=this.byNodeName.get(t))!=null&&e.isControl)}isNumberedBlockNode(t){var e;return!!((e=this.byNodeName.get(t))!=null&&e.isNumberedBlock)}controlNodeNames(){return this.descriptors().filter(t=>t.isControl).map(t=>t.nodeName)}blockFormattingNodeNames(){return this.descriptors().filter(t=>t.supportsBlockFormatting).map(t=>t.nodeName)}numberedBlockNodeNames(){return this.descriptors().filter(t=>t.isNumberedBlock).map(t=>t.nodeName)}registerFeature(t){if(this.byFeatureName.has(t.name))throw new Error(`Duplicate report feature name: ${t.name}.`);this.byFeatureName.set(t.name,t),this.featureList.push(t);for(const e of t.nodes??[])this.registerNode(e);for(const e of t.marks??[])this.registerMark(e)}registerNode(t){if(this.byNodeName.has(t.nodeName))throw new Error(`Duplicate report node name: ${t.nodeName}.`);if(this.byTemplateType.has(t.templateType))throw new Error(`Duplicate report template type: ${t.templateType}.`);this.byNodeName.set(t.nodeName,t),this.byTemplateType.set(t.templateType,t)}registerMark(t){if(this.byMarkName.has(t.markName))throw new Error(`Duplicate report mark name: ${t.markName}.`);this.byMarkName.set(t.markName,t)}}function on(r){return r}function sn(r){return{...r,isControl:!0,isInline:r.isInline??!0}}function an(r){return r}function ln(r){return r}function H(r=[]){return new nn([...rn,...r])}class bt{constructor(t=H()){this.registry=t}createId(t=new Set){let e=this.createRawId();for(;t.has(e);)e=this.createRawId();return t.add(e),e}createBatchId(){return this.createRawId("batch")}withFreshControlId(t,e,n){return{...t,controlId:this.createId(e),batchId:this.resolveBatchId(t,n)}}normalizeDocument(t,e=this.createBatchId()){const n=new Set;return{...t,content:this.normalizeReportNodes(t.content??[],n,e)}}collectIds(t){const e=new Set;return this.visitReportNodes(t.content??[],n=>{const o=this.getControlId(n.attrs);this.isControlNode(n.type)&&o&&e.add(o)}),e}collectTransactionUpdates(t,e=this.createBatchId()){const n=new Set,o=[];return t.descendants((s,i)=>{if(!this.isControlNode(s.type.name))return;const a=this.getControlId(s.attrs),l=this.getBatchId(s.attrs);if(!a||n.has(a)){o.push({pos:i,controlId:this.createId(n),batchId:l??e});return}n.add(a),l||o.push({pos:i,controlId:a,batchId:e})}),o}assignFreshControlIdsToSlice(t,e=this.createBatchId()){return new L.Slice(this.assignFreshControlIdsToFragment(t.content,e),t.openStart,t.openEnd)}assignFreshControlIdsToFragment(t,e){const n=[];return t.forEach(o=>{n.push(this.assignFreshControlIdsToNode(o,e))}),L.Fragment.fromArray(n)}assignFreshControlIdsToNode(t,e){if(t.isText)return t;const n=t.content.size>0?this.assignFreshControlIdsToFragment(t.content,e):t.content;return this.isControlNode(t.type.name)?t.type.create({...t.attrs,controlId:this.createId(),batchId:e},n,t.marks):n===t.content?t:t.copy(n)}normalizeReportNodes(t,e,n){return t.map(o=>this.normalizeReportNode(o,e,n))}normalizeReportNode(t,e,n){const o=t.content?this.normalizeReportNodes(t.content,e,n):void 0;if(!this.isControlNode(t.type))return{...t,...o?{content:o}:{}};const s={...t.attrs??{}},i=this.getControlId(s),a=this.getBatchId(s);return!i||e.has(i)?s.controlId=this.createId(e):e.add(i),a||(s.batchId=n),{...t,attrs:s,...o?{content:o}:{}}}visitReportNodes(t,e){for(const n of t)e(n),n.content&&this.visitReportNodes(n.content,e)}isControlNode(t){return this.registry.isControlNode(t)}getControlId(t){const e=t==null?void 0:t.controlId;return typeof e=="string"&&e.trim()?e:void 0}getBatchId(t){const e=t==null?void 0:t.batchId;return typeof e=="string"&&e.trim()?e:void 0}resolveBatchId(t,e){return this.getBatchId(t)??e??this.createBatchId()}createRawId(t="ctrl"){const e=globalThis.crypto;if(e!=null&&e.randomUUID)return`${t}_${e.randomUUID()}`;const n=Math.random().toString(36).slice(2);return`${t}_${Date.now().toString(36)}_${n}`}}const dn=new Set(["P","DIV","BR","STRONG","B","EM","I","U","S","DEL","UL","OL","LI","SPAN"]),cn=new Set(["color","font-weight","font-style","text-decoration","font-size","font-family","line-height"]),un=new Set(["SCRIPT","STYLE","IFRAME","OBJECT","EMBED","LINK","META"]),z=new WeakMap;class ye{sanitize(t){if(this.assertSupportedReportMarkup(t),typeof DOMParser>"u")return this.regexFallback(t);const n=new DOMParser().parseFromString(t,"text/html");return this.sanitizeChildren(n.body),n.body.innerHTML}assertSupportedReportMarkup(t){var o,s;if(/data-report-node\s*=\s*(?:"sub-paragraph"|'sub-paragraph'|sub-paragraph)(?:\s|>|\/)/i.test(t))throw new Error("Legacy sub-paragraph edit HTML is not supported.");if(typeof DOMParser>"u")return;const e=new DOMParser().parseFromString(t,"text/html"),n=Array.from(e.querySelectorAll('[data-report-mark="visibility-group"]'));for(const i of n){const a=(o=i.getAttribute("data-visibility-group-id"))==null?void 0:o.trim(),l=i.getAttribute("data-visibility-condition");if(!a||l!=="all-controls-empty")throw new Error("Visibility-group edit HTML requires a non-empty ID and a supported condition.");if((s=i.parentElement)!=null&&s.closest('[data-report-mark="visibility-group"]'))throw new Error("Nested visibility-group edit HTML is not supported.")}}sanitizeChildren(t){for(const e of Array.from(t.children)){if(un.has(e.tagName)){e.remove();continue}if(!dn.has(e.tagName)){this.sanitizeChildren(e),e.replaceWith(...Array.from(e.childNodes));continue}this.sanitizeAttributes(e),this.sanitizeChildren(e)}}sanitizeAttributes(t){for(const e of Array.from(t.attributes)){const n=e.name.toLowerCase();if(n.startsWith("on")){t.removeAttribute(e.name);continue}if(n==="style"){this.sanitizeStyle(t);continue}if(!n.startsWith("data-")){if(t.tagName==="OL"&&n==="start"){/^-?\d+$/.test(e.value.trim())||t.removeAttribute(e.name);continue}n!=="class"&&t.removeAttribute(e.name)}}}sanitizeStyle(t){var o;const e=[],n=((o=t.getAttribute("style"))==null?void 0:o.split(";"))??[];for(const s of n){const[i,...a]=s.split(":"),l=i==null?void 0:i.trim().toLowerCase(),d=a.join(":").trim();if(!l||!d||!cn.has(l))continue;const c=k.sanitize(l,d);c&&e.push(`${l}: ${c}`)}if(e.length===0){t.removeAttribute("style");return}t.setAttribute("style",e.join("; "))}regexFallback(t){return S.text(t.replace(/<(script|style|iframe|object|embed|link|meta)[\s\S]*?>[\s\S]*?<\/\1>/gi,""))}}function be(r=H(),t,e,n,o){return C.Extension.create({name:"pasteSanitizer",addProseMirrorPlugins(){const s=new ye,i=new bt(r),a=new de,l=new Gt;let d=null,c=null;const h=()=>(t==null?void 0:t())??i.createBatchId(),f=(u,g)=>{let m;return u.someProp("dragCopies",I=>{m=m||I(g)}),m!==void 0?m:hn()?g.altKey:g.ctrlKey};return[new y.Plugin({filterTransaction(u){if(!u.docChanged||dt(u))return!0;const g=fn(u.doc);return g?(n==null||n(g),!1):!0},props:{handleDOMEvents:{dragstart(u,g){if(g.target instanceof Node&&u.dom.contains(g.target)){const m=u.state.selection;d={copy:f(u,g),groups:Vt(u.state.doc,m.from,m.to)},o&&!m.empty?z.set(o,{...d,sourceDoc:u.state.doc,sourceFrom:m.from,sourceTo:m.to,sourceView:u}):o&&z.delete(o)}return!1},drop(u,g){var I,T;const m=o?z.get(o):void 0;if(m&&m.sourceView!==u){const A=f(u,g);return m.copy=A,c=m,d={copy:A,crossEditor:!0,groups:m.groups,dropPos:(I=u.posAtCoords({left:g.clientX,top:g.clientY}))==null?void 0:I.pos},!1}if(d){const A=u.dragging,N=(A==null?void 0:A.node)??u.state.selection;d.copy=f(u,g),d.groups=Vt(u.state.doc,N.from,N.to),d.dropPos=(T=u.posAtCoords({left:g.clientX,top:g.clientY}))==null?void 0:T.pos}return!1},dragend(u){const g=o?z.get(o):void 0;return window.setTimeout(()=>{d=null,o&&(g==null?void 0:g.sourceView)===u&&z.delete(o)},0),!1}},transformPastedHTML(u){return s.sanitize(u)},transformPasted(u,g,m){if(d){const T=d;if(d=null,T.copy)return l.assignFreshIdsToSlice(a.assignFreshIdsToSlice(i.assignFreshControlIdsToSlice(u,h())));const A=new Set(T.groups.filter(N=>!N.complete&&(T.crossEditor||T.dropPos!==void 0&&(T.dropPos<N.from||T.dropPos>N.to))).map(N=>N.groupId));return A.size>0?l.removeMarksFromSlice(u,A):u}const I=m?l.removeMarksFromSlice(u):l.assignFreshIdsToSlice(u);return a.assignFreshIdsToSlice(i.assignFreshControlIdsToSlice(I,h()))},handleDrop(u,g,m){var Ct;const I=c;if(!I)return!1;c=null;const T=()=>{o&&z.get(o)===I&&z.delete(o)};if(!I.copy&&!I.sourceView.state.doc.eq(I.sourceDoc))return T(),!0;const A=u.posAtCoords({left:g.clientX,top:g.clientY});if(!A)return T(),!0;const N=_t.dropPoint(u.state.doc,A.pos,m)??A.pos,b=u.state.tr,v=b.mapping.map(N),Z=m.openStart===0&&m.openEnd===0&&m.content.childCount===1,Ie=b.doc;if(Z?b.replaceRangeWith(v,v,m.content.firstChild):b.replaceRange(v,v,m),b.doc.eq(Ie))return T(),!0;if(Z&&y.NodeSelection.isSelectable(m.content.firstChild)&&((Ct=b.doc.resolve(v).nodeAfter)!=null&&Ct.sameMarkup(m.content.firstChild)))b.setSelection(y.NodeSelection.create(b.doc,v));else{const ut=Math.min(b.mapping.map(N),b.doc.content.size);b.setSelection(y.Selection.near(b.doc.resolve(ut),-1))}if(u.focus(),u.dispatch(b.setMeta("uiEvent","drop").scrollIntoView()),!I.copy){const ut=I.sourceView.state.tr.delete(I.sourceFrom,I.sourceTo);I.sourceView.dispatch(ut.setMeta("uiEvent","drop").scrollIntoView())}return T(),!0}},appendTransaction(u,g,m){if(oe(u))return null;const I=i.collectTransactionUpdates(m.doc,h()),T=a.collectTransactionUpdates(m.doc),A=pn(m.doc,r);if(I.length===0&&T.length===0&&A.length===0)return null;const N=m.tr;N.setMeta("addToHistory",!1);for(const b of I){const v=N.doc.nodeAt(b.pos);v&&r.isControlNode(v.type.name)&&N.setNodeMarkup(b.pos,void 0,{...v.attrs,controlId:b.controlId,batchId:b.batchId},v.marks)}for(const b of T){const v=N.doc.nodeAt(b.pos);(v==null?void 0:v.type.name)===x&&N.setNodeMarkup(b.pos,void 0,{...v.attrs,id:b.id},v.marks)}for(const b of[...A].sort((v,Z)=>Z.pos-v.pos))e==null||e({nodeName:b.nodeName,attrs:b.attrs,error:b.error}),N.delete(b.pos,b.pos+b.nodeSize);return N}})]}})}be();function hn(){return typeof navigator>"u"?!1:/Mac|iP(?:hone|ad|od)/.test(`${navigator.platform} ${navigator.userAgent}`)}function Vt(r,t,e){const n=new Map;return r.descendants((o,s)=>{const i=o.marks.find(u=>u.type.name===w);if(!i)return;const a=String(i.attrs.groupId??""),l=s,d=s+o.nodeSize,c=t<d&&e>l,h=t<=l&&e>=d,f=n.get(a);if(f){f.from=Math.min(f.from,l),f.to=Math.max(f.to,d),f.complete=f.complete&&h,f.intersects=f.intersects||c;return}n.set(a,{groupId:a,from:l,to:d,complete:h,intersects:c})}),Array.from(n.values()).filter(o=>o.intersects).map(({intersects:o,...s})=>s)}function pn(r,t){const e=[];return r.descendants((n,o)=>{if(!t.isControlNode(n.type.name))return;const s=t.getByNodeName(n.type.name);if(s!=null&&s.validateAttrs)try{s.validateAttrs(n.attrs)}catch(i){e.push({pos:o,nodeSize:n.nodeSize,nodeName:n.type.name,attrs:n.attrs,error:i})}}),e}function fn(r){let t;const e=(n,o)=>{var a;if(t)return;const s=n.marks.filter(l=>l.type.name===w);if(s.length>1){t={nodeName:n.type.name,attrs:((a=s[0])==null?void 0:a.attrs)??{},error:new Error("A node cannot carry multiple visibilityGroup marks.")};return}const i=s[0];if(i){if(o){t={nodeName:n.type.name,attrs:i.attrs,error:new Error("Visibility groups cannot be nested.")};return}try{at(i.attrs)}catch(l){t={nodeName:n.type.name,attrs:i.attrs,error:l};return}}n.forEach(l=>{e(l,o||!!i)})};return e(r,!1),t}class St{constructor(t=H(),e,n,o,s,i){this.registry=t,this.controlShortcuts=e,this.editorGroup=n,this.getCurrentBatchId=o,this.onInvalidControlAttrs=s,this.onInvalidVisibilityGroup=i}create(){const t=this.registry.descriptors().filter(i=>i.isControl),e=lt(this.controlShortcuts,t.map(i=>i.nodeName),t.map(i=>i.dataNode??i.nodeName),this.editorGroup),n=["paragraph","listItem",...this.registry.blockFormattingNodeNames()],o=this.registry.numberedBlockNodeNames()[0]??"reportNumberedBlock";return[...this.registry.extensions().map(i=>i.name==="structuredField"||i.name==="dropdownField"?i.configure({controlShortcutRuntime:e}):i),le(n),ae(n),pe(o),be(this.registry,this.getCurrentBatchId,this.onInvalidControlAttrs,this.onInvalidVisibilityGroup,this.editorGroup),ke(t.map(i=>i.nodeName)),Fr(t.map(i=>i.nodeName)),ir(e)]}createDefault(){return new St().create()}}const K="1.0.3";class O{static toTiptapContent(t){return!t||typeof t=="string"?t:{type:"doc",content:t.content??[]}}static fromTiptapJSON(t,e=K){return{version:e,type:"doc",content:t.content??[]}}static empty(t=K){return{version:t,type:"doc",content:[{type:"paragraph",content:[]}]}}}class ct{constructor(t){this.listener=t}warning(t,e,n){this.emit({code:t,level:"warning",message:e,detail:n})}error(t,e,n){this.emit({code:t,level:"error",message:e,detail:n})}emit(t){var e;(e=this.listener)==null||e.call(this,t)}}class zt{constructor(t,e){p(this,"hiddenGroupIds",new Set);this.registry=e;const n=new Map;this.scan(t,n);for(const[o,s]of n)s.condition===X&&(s.controlValues.length>0?s.controlValues.every(i=>$.isEmpty(i)):!s.hasRawContent)&&this.hiddenGroupIds.add(o)}isNodeHidden(t){return this.groupMarks(t).some(e=>{var n;return this.hiddenGroupIds.has(String(((n=e.attrs)==null?void 0:n.groupId)??""))})}isGrouped(t){return this.groupMarks(t).length>0}hiddenGroups(){return this.hiddenGroupIds}scan(t,e,n=[]){var o,s,i,a;for(const l of t??[]){const d=this.groupMarks(l);if(d.length>1)throw new Error("A node cannot carry multiple visibilityGroup marks.");if(n.length>0&&d.length>0)throw new Error("Visibility groups cannot be nested.");const c=d.length>0?d:n;for(const h of c){at(h.attrs??{});const f=String((o=h.attrs)==null?void 0:o.groupId);let u=e.get(f);u||(u={condition:String((s=h.attrs)==null?void 0:s.condition),controlValues:[],hasRawContent:!1},e.set(f,u)),this.registry.isControlNode(l.type)?u.controlValues.push((i=l.attrs)==null?void 0:i.value):this.isRawContent(l)&&(u.hasRawContent=!0)}(a=l.content)!=null&&a.length&&this.scan(l.content,e,c)}}groupMarks(t){return(t.marks??[]).filter(e=>e.type===w)}isRawContent(t){var e,n;return t.type==="text"?!!((e=t.text)!=null&&e.trim()):(n=t.content)!=null&&n.length?!1:!["pageBreak","hardBreak"].includes(t.type)}}class mn{constructor(t="1.0.3",e=new ct,n=H()){this.documentVersion=t,this.errors=e,this.registry=n}toJSON(t){return O.fromTiptapJSON(t.getJSON(),this.documentVersion)}toHTML(t,e="edit"){return this.toHTMLFromJSON(this.toJSON(t),e)}toHTMLFromJSON(t,e="edit"){const n=["hmg-report",`hmg-report--${e}`],o=new Set,s=new zt(t.content,this.registry),i=e==="edit"?void 0:this.collectRetainedPageBreakIds(t.content,e,s);return e==="print"&&n.push("hmg-report-print"),`<div class="${n.join(" ")}" data-report-mode="${e}">${this.renderContent(t.content,e,o,s,i)}</div>`}toPlainText(t,e={}){const n=this.toJSON(t),o=new Set,s=new zt(n.content,this.registry);return this.renderTextContent(n.content,this.normalizePlainTextOptions(e),o,s,`
|
|
2
|
+
`)}renderContent(t,e,n,o,s){const i=t??[],a=[];for(let l=0;l<i.length;){const d=i[l],c=this.getVisibilityGroupMark(d);if(!c){a.push(this.renderNode(d,e,n,o,s)),l+=1;continue}const h=[d];let f=l+1;for(;f<i.length&&this.isSameVisibilityGroup(c,this.getVisibilityGroupMark(i[f]));)h.push(i[f]),f+=1;const u=e!=="edit"&&o.isNodeHidden(d),g=h.map(m=>u?m.type==="pageBreak"?this.renderNode(m,e,n,o,s):this.renderPageBreaksOnly(m.content,e,n,o,s):this.renderNode(m,e,n,o,s)).join("");a.push(e==="edit"?this.applyMark(c,g,e,n,o,s):g),l=f}return a.join("")}renderNode(t,e,n,o,s){var a;if(t.type==="pageBreak"&&s&&!s.has(String(((a=t.attrs)==null?void 0:a.id)??"")))return"";let i;switch(t.type){case"doc":i=this.renderContent(t.content,e,n,o,s);break;case"paragraph":i=this.renderParagraph(t,e,n,o,s);break;case"text":i=S.text(t.text??"");break;case"bulletList":i=this.renderStructuralContainer("ul",t,e,n,o,s);break;case"orderedList":i=this.renderStructuralContainer("ol",t,e,n,o,s);break;case"listItem":i=this.renderStructuralContainer("li",t,e,n,o,s);break;case"hardBreak":i="<br>";break;default:{const l=this.registry.getByNodeName(t.type);if(l!=null&&l.renderHTML){i=l.renderHTML(t,{mode:e,renderContent:(d,c=e)=>this.renderContent(d,c,n,o,s),renderBlockAttrs:(d,c)=>this.renderBlockAttrs(d,c),warn:(d,c,h)=>this.errors.warning(d,c,h)});break}this.warnUnsupported(n,"node",t.type,{mode:e,node:t}),i=this.renderContent(t.content,e,n,o,s)}}for(const l of t.marks??[])l.type!==w&&(i=this.applyMark(l,i,e,n,o,s));return i}renderParagraph(t,e,n,o,s){var c,h,f;if(e!=="edit"&&((c=t.attrs)!=null&&c.hidden))return this.renderPageBreaksOnly(t.content,e,n,o,s);const i=(h=t.attrs)!=null&&h.hidden?" hmg-hidden-paragraph":"",a=(f=t.attrs)!=null&&f.hidden?' data-hidden="true"':"",l=this.renderContent(t.content,e,n,o,s);return e!=="edit"&&!l.trim()&&(t.content??[]).some(u=>o.isGrouped(u)&&o.isNodeHidden(u))||e!=="edit"&&!l.trim()&&this.containsPageBreak(t.content)?"":`<p${this.renderBlockAttrs(t,`hmg-paragraph${i}`)}${a}>${l}</p>`}applyMark(t,e,n,o,s,i){const a=this.registry.getMarkDescriptor(t.type);return a!=null&&a.renderHTML?a.renderHTML(t,e,{mode:n,renderContent:(l,d=n)=>this.renderContent(l,d,o,s,i),renderBlockAttrs:(l,d)=>this.renderBlockAttrs(l,d),warn:(l,d,c)=>this.errors.warning(l,d,c)}):(this.warnUnsupported(o,"mark",t.type,{mode:n,mark:t}),e)}getVisibilityGroupMark(t){return(t.marks??[]).find(e=>e.type===w)}isSameVisibilityGroup(t,e){var n,o,s,i;return!!(e&&((n=t.attrs)==null?void 0:n.groupId)===((o=e.attrs)==null?void 0:o.groupId)&&((s=t.attrs)==null?void 0:s.condition)===((i=e.attrs)==null?void 0:i.condition))}renderBlockAttrs(t,e){var s,i,a;const n=new gt().addSafe("line-height",(s=t.attrs)==null?void 0:s.lineHeight).add("margin-left",typeof((i=t.attrs)==null?void 0:i.indent)=="number"&&t.attrs.indent>0?`${t.attrs.indent*2}em`:void 0).toAttribute(),o=typeof((a=t.attrs)==null?void 0:a.indent)=="number"&&t.attrs.indent>0?` data-indent="${t.attrs.indent}"`:"";return` class="${S.attr(e)}"${o}${n}`}renderStructuralContainer(t,e,n,o,s,i){var d,c,h;const a=this.renderContent(e.content,n,o,s,i);if(n!=="edit"&&!a.trim()&&(this.containsPageBreak(e.content)||this.containsHiddenVisibilityMember(e.content,s)))return"";const l=t==="li"?this.renderBlockAttrs(e,"hmg-list-item"):t==="ol"&&Number.isInteger((d=e.attrs)==null?void 0:d.start)&&((c=e.attrs)==null?void 0:c.start)!==1?` start="${String((h=e.attrs)==null?void 0:h.start)}"`:"";return`<${t}${l}>${a}</${t}>`}containsPageBreak(t){return(t??[]).some(e=>e.type==="pageBreak"||this.containsPageBreak(e.content))}containsHiddenVisibilityMember(t,e){return(t??[]).some(n=>e.isGrouped(n)&&e.isNodeHidden(n)||this.containsHiddenVisibilityMember(n.content,e))}renderPageBreaksOnly(t,e,n,o,s){return(t??[]).map(i=>i.type==="pageBreak"?this.renderNode(i,e,n,o,s):this.renderPageBreaksOnly(i.content,e,n,o,s)).join("")}collectRetainedPageBreakIds(t,e,n){const o=[];this.collectOutputTokens(t,!0,o,n,e);const s=new Set;let i=!1,a;for(const l of o){if(l.kind==="pageBreak"){i&&a===void 0&&(a=l.id);continue}a!==void 0&&(s.add(a),a=void 0),i=!0}return s}collectOutputTokens(t,e,n,o,s){var i,a,l;for(const d of t??[]){if(d.type==="pageBreak"){const h=String(((i=d.attrs)==null?void 0:i.id)??"");h&&n.push({kind:"pageBreak",id:h});continue}const c=e&&!(d.type==="paragraph"&&((a=d.attrs)!=null&&a.hidden))&&!o.isNodeHidden(d);if(d.type==="text"){c&&(d.text??"").trim()&&n.push({kind:"content"});continue}if(this.registry.isControlNode(d.type)){c&&this.rendersVisibleControlContent(d,s,o)&&n.push({kind:"content"});continue}if((l=d.content)!=null&&l.length){this.collectOutputTokens(d.content,c,n,o,s);continue}c&&!["paragraph","bulletList","orderedList","listItem","hardBreak","reportNumberedBlock"].includes(d.type)&&n.push({kind:"content"})}}rendersVisibleControlContent(t,e,n){const o=this.registry.getByNodeName(t.type);return o!=null&&o.renderHTML?o.renderHTML(t,{mode:e,renderContent:(i,a=e)=>this.renderContent(i,a,new Set,n),renderBlockAttrs:(i,a)=>this.renderBlockAttrs(i,a),warn:()=>{}}).trim().length>0:!1}normalizePlainTextOptions(t){return{hideVisibilityGroups:!!t.hideVisibilityGroups}}renderTextContent(t,e,n,o,s=""){return(t??[]).map(i=>this.renderTextNode(i,e,n,o)).join(s)}renderTextNode(t,e,n,o){if(e.hideVisibilityGroups&&t.type!=="pageBreak"&&o.isNodeHidden(t))return"";switch(t.type){case"doc":return this.renderTextContent(t.content,e,n,o,`
|
|
3
|
+
`);case"paragraph":return this.renderTextContent(t.content,e,n,o);case"text":return this.renderTextMarks(t.text??"",t.marks??[],e,n,o);case"bulletList":case"orderedList":case"listItem":return this.renderTextContent(t.content,e,n,o,`
|
|
4
|
+
`);case"hardBreak":return`
|
|
5
|
+
`;default:{const s=this.registry.getByNodeName(t.type);return s!=null&&s.renderText?s.renderText(t,{hideVisibilityGroups:e.hideVisibilityGroups,renderContent:i=>this.renderTextContent(i,e,n,o),warn:(i,a,l)=>this.errors.warning(i,a,l)}):(this.warnUnsupported(n,"node",t.type,{node:t,output:"text"}),this.renderTextContent(t.content,e,n,o))}}}renderTextMarks(t,e,n,o,s){let i=t;for(const a of e){if(a.type===w)continue;const l=this.registry.getMarkDescriptor(a.type);if(!l){this.warnUnsupported(o,"mark",a.type,{mark:a,output:"text"});continue}l.renderText&&(i=l.renderText(a,i,{hideVisibilityGroups:n.hideVisibilityGroups,renderContent:d=>this.renderTextContent(d,n,o,s),warn:(d,c,h)=>this.errors.warning(d,c,h)}))}return i}warnUnsupported(t,e,n,o){const s=`${e}:${n}`;t.has(s)||(t.add(s),this.errors.warning("UNSUPPORTED_SERIALIZATION",`Unsupported ${e} serialization: ${n}.`,o))}}class gn{constructor(t=new ct){p(this,"savedSelection",null);this.errors=t}save(t){const{from:e,to:n,anchor:o,head:s}=t.state.selection;return this.savedSelection={from:e,to:n,anchor:o,head:s,timestamp:Date.now()},this.savedSelection}restore(t,e=this.savedSelection){if(!e)return!1;const n=t.state.doc,o=n.content.size,s=this.clamp(e.from,0,o),i=this.clamp(e.to,s,o);try{const a=y.TextSelection.create(n,s,i);return t.view.dispatch(t.state.tr.setSelection(a).scrollIntoView()),!0}catch(a){try{const l=n.resolve(s),d=y.Selection.near(l,1);return t.view.dispatch(t.state.tr.setSelection(d).scrollIntoView()),this.errors.warning("SELECTION_RESTORE_FAILED","Selection restored to nearest valid position.",a),!0}catch(l){return this.errors.warning("SELECTION_RESTORE_FAILED","Selection restore failed.",l),!1}}}restoreToDocumentEnd(t){const e=t.state.doc.content.size;try{const n=y.Selection.near(t.state.doc.resolve(e),-1);return t.view.dispatch(t.state.tr.setSelection(n).scrollIntoView()),!0}catch(n){return this.errors.warning("SELECTION_RESTORE_FAILED","Unable to restore selection to document end.",n),!1}}clamp(t,e,n){return Math.max(e,Math.min(n,t))}}class yn{constructor(t=new ct,e=new bt,n=H()){this.errors=t,this.identity=e,this.registry=n}validate(t){if(!t||typeof t!="object")throw new Error("Template must be an object.");if(!t.version)throw new Error("Template version is required.");if(t.version!==K)throw new Error(`Unsupported report template version: ${t.version}.`);if(!Array.isArray(t.content))throw new Error("Template content must be an array.");for(const e of t.content)this.validateNode(e)}toDocument(t,e){this.validate(t);const n=new Set;return{version:K,type:"doc",content:t.content.map(o=>this.toProseMirrorNode(o,e,n))}}applyTemplate(t,e,n){try{const o=this.toDocument(e,n),s=t.schema.nodeFromJSON({type:"doc",content:o.content}),i=t.state.tr.replaceWith(0,t.state.doc.content.size,s.content);return t.view.dispatch(i.scrollIntoView()),!0}catch(o){return this.errors.error("TEMPLATE_PARSE_FAILED","Template apply failed.",o),!1}}appendTemplate(t,e,n){try{const o=this.toDocument(e,n);return o.content.length===0?!0:t.commands.insertContentAt(this.resolveAppendPosition(t),o.content,{updateSelection:!0,errorOnInvalidContent:!0})}catch(o){return this.errors.error("TEMPLATE_PARSE_FAILED","Template append failed.",o),!1}}resolveAppendPosition(t){var o;const e=t.state.doc.content.size,n=(o=t.state.selection)==null?void 0:o.to;if(n===void 0||!Number.isSafeInteger(n)||n<0||n>e)return e;try{return t.state.doc.resolve(n),n}catch{return e}}validateNode(t,e){var n;switch(this.validateTemplateMarks(t),t.type){case"paragraph":for(const o of t.content??[])this.validateNode(o,"paragraph");return;case"text":if(typeof t.text!="string")throw new Error("Text node requires text.");return;case"visibilityGroup":this.validateVisibilityGroup(t,e);return;default:{const o=this.registry.getByTemplateType(t.type);if(!o){const s=t;throw new Error(`Unsupported template node type: ${s.type??"unknown"}.`)}(n=o.validateTemplate)==null||n.call(o,t,{validateChildren:s=>{for(const i of s??[])this.validateNode(i,t.type)}});return}}}validateVisibilityGroup(t,e){var o;if(e!=="paragraph")throw new Error("Visibility group must be inside paragraph.");if(t.attrs!==void 0&&(!t.attrs||typeof t.attrs!="object"||Array.isArray(t.attrs)))throw new Error("Visibility group attrs must be an object.");if(t.attrs&&Object.keys(t.attrs).some(s=>s!=="condition"))throw new Error("Visibility group only supports the condition template attribute.");if(!Array.isArray(t.content)||t.content.length===0)throw new Error("Visibility group requires at least one child node.");const n=((o=t.attrs)==null?void 0:o.condition)??X;if(n!==X)throw new Error(`Unsupported visibility group condition: ${String(n)}.`);for(const s of t.content){if(s.type==="visibilityGroup")throw new Error("Visibility groups cannot be nested.");if(this.validateNode(s,"visibilityGroup"),!this.isInlineTemplateNode(s))throw new Error("Visibility group only supports inline content nodes.")}}isInlineTemplateNode(t){var e;return t.type==="text"?!0:!!((e=this.registry.getByTemplateType(t.type))!=null&&e.isInline)}toProseMirrorNode(t,e,n){switch(t.type){case"paragraph":const o=t;return{type:"paragraph",attrs:{hidden:!!o.hidden},content:this.toContent(o.content,e,n)};case"text":return{type:"text",text:t.text,marks:t.marks};default:{const s=this.registry.getByTemplateType(t.type);if(!(s!=null&&s.toProseMirrorNode)){const a=t;throw new Error(`Unsupported template node type: ${a.type??"unknown"}.`)}const i=s.toProseMirrorNode(t,{toContent:a=>this.toContent(a,e,n),withFreshControlId:a=>this.identity.withFreshControlId(a,n,e)});return this.assertNoRuntimeVisibilityMarks(i),i}}}validateTemplateMarks(t){var n,o;const e=t.marks;if(e!==void 0){if(!Array.isArray(e))throw new Error("Template node marks must be an array.");for(const s of e){if(!s||typeof s!="object"||typeof s.type!="string"||!s.type.trim())throw new Error("Template mark requires a type.");if(s.attrs!==void 0&&(!s.attrs||typeof s.attrs!="object"||Array.isArray(s.attrs)))throw new Error(`Template mark attrs must be an object: ${s.type}.`);if(s.type===w)throw new Error("Template nodes cannot carry a runtime visibilityGroup mark.");(o=(n=this.registry.getMarkDescriptor(s.type))==null?void 0:n.validateAttrs)==null||o.call(n,s.attrs??{})}}}assertNoRuntimeVisibilityMarks(t){if((t.marks??[]).some(e=>e.type===w))throw new Error("Template conversion cannot create a runtime visibilityGroup mark directly.");for(const e of t.content??[])this.assertNoRuntimeVisibilityMarks(e)}toContent(t,e,n){return(t??[]).flatMap(o=>{var a;if(o.type!=="visibilityGroup")return[this.toProseMirrorNode(o,e,n)];const s=((a=o.attrs)==null?void 0:a.condition)??X,i={type:w,attrs:{groupId:Ht(),condition:s}};return this.toContent(o.content,e,n).map(l=>{if((l.marks??[]).some(d=>d.type===w))throw new Error("Visibility group content cannot already carry a visibilityGroup mark.");return{...l,marks:[i,...l.marks??[]]}})})}}class E extends Error{constructor(t,e,n){super(e),this.code=t,this.detail=n,this.name="ReportDocumentValidationError"}}function bn(r,t){if(!r||typeof r!="object"||Array.isArray(r))throw new E("INVALID_DOCUMENT","Report document must be an object.",r);const e=r;if(e.type!=="doc")throw new E("INVALID_DOCUMENT","Report document type must be doc.",r);if(e.version!==t)throw new E("INVALID_DOCUMENT",`Unsupported report document version: ${String(e.version??"")}.`,{expectedVersion:t,actualVersion:e.version});if(!Array.isArray(e.content))throw new E("INVALID_DOCUMENT","Report document content must be an array.",r)}function Sn(r,t){for(const e of r.content)Se(e,t)}function Cn(r,t){try{const e=O.toTiptapContent(r);if(!e||typeof e=="string")throw new Error("Report document could not be mapped to Tiptap content.");C.createDocument(e,t,{},{errorOnInvalidContent:!0})}catch(e){throw new E("INVALID_DOCUMENT","Report document does not match the editor schema.",e)}}function $t(r,t,e){Sn(r,t),Cn(r,e)}function it(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Se(r,t,e=!1){if(!it(r))throw new E("INVALID_DOCUMENT","Report node must be an object.",r);if(typeof r.type!="string"||!r.type.trim())throw new E("INVALID_DOCUMENT","Report node requires a type.",r);if(r.attrs!==void 0&&!it(r.attrs))throw new E("INVALID_DOCUMENT",`Report node attrs must be an object: ${r.type}.`,r);if(r.content!==void 0&&!Array.isArray(r.content))throw new E("INVALID_DOCUMENT",`Report node content must be an array: ${r.type}.`,r);if(r.type==="text"&&typeof r.text!="string")throw new E("INVALID_DOCUMENT","Text node requires string text.",r);const n=r.marks!==void 0?In(r,t):!1;if(e&&n)throw new E("INVALID_DOCUMENT","Visibility groups cannot be nested.",r);t.isControlNode(r.type)&&En(r,t);for(const o of r.content??[])Se(o,t,e||n)}function In(r,t){if(!Array.isArray(r.marks))throw new E("INVALID_DOCUMENT",`Report node marks must be an array: ${r.type}.`,r);let e=0;for(const n of r.marks){if(!it(n)||typeof n.type!="string"||!n.type.trim())throw new E("INVALID_DOCUMENT",`Report mark requires a type: ${r.type}.`,n);if(n.attrs!==void 0&&!it(n.attrs))throw new E("INVALID_DOCUMENT",`Report mark attrs must be an object: ${n.type}.`,n);n.type===w&&(e+=1);const o=t.getMarkDescriptor(n.type);if(o!=null&&o.validateAttrs)try{o.validateAttrs(n.attrs??{})}catch(s){throw new E("INVALID_DOCUMENT",`Invalid report mark attrs: ${n.type}.`,{mark:n,error:s})}}if(e>1)throw new E("INVALID_DOCUMENT","A node cannot carry multiple visibilityGroup marks.",r);return e===1}function En(r,t){const e=t.getByNodeName(r.type);if(e!=null&&e.validateAttrs)try{e.validateAttrs(r.attrs??{})}catch(n){throw new E("INVALID_FIELD_CONFIG",`Invalid control attrs for ${r.type}.`,{node:r,error:n})}}class wn{constructor(t={}){p(this,"editor");p(this,"registry");p(this,"errors");p(this,"serializer");p(this,"templateEngine");p(this,"selectionManager");p(this,"identity");p(this,"pageBreakIdentity");p(this,"pasteSanitizer");p(this,"numberingService");p(this,"editorId");p(this,"controlPlugins");p(this,"controlPluginContext");p(this,"documentVersion");p(this,"controlSnapshots",new Map);p(this,"controlSnapshotsDirty",!1);p(this,"currentOperationBatchId");p(this,"initializing",!0);p(this,"handleControlTransaction",({transaction:t})=>{if(!t.docChanged)return;if(this.initializing){this.controlSnapshotsDirty=!0;return}if(this.controlPlugins.length===0){this.controlSnapshotsDirty=!0;return}const e=dt(t);if(e){this.syncChangedControlSnapshots(e.controlIds);return}this.syncControlPlugins()});var i;if(this.options=t,t.documentVersion!==void 0&&t.documentVersion!==K)throw new E("INVALID_DOCUMENT",`Unsupported report document version: ${t.documentVersion}.`);this.editorId=t.editorId??this.createEditorId(),this.controlPlugins=t.controlPlugins??[],this.documentVersion=t.documentVersion??K,this.registry=H(t.features),this.errors=new ct(t.onError),this.identity=new bt(this.registry),this.pageBreakIdentity=new de,this.pasteSanitizer=new ye,this.serializer=new mn(this.documentVersion,this.errors,this.registry),this.templateEngine=new yn(this.errors,this.identity,this.registry),this.selectionManager=new gn(this.errors),this.numberingService=new he(this.registry.numberedBlockNodeNames()[0]??"reportNumberedBlock");const e=this.createOperationBatchId();this.currentOperationBatchId=e;const n=this.resolveInitialContent(t,e),o=new St(this.registry,t.controlShortcuts,t.editorGroup,()=>this.currentOperationBatchId??this.getPluginBatchId(),a=>this.errors.warning("INVALID_FIELD_CONFIG",`Invalid control attrs removed from transaction: ${a.nodeName}.`,a),a=>this.errors.error("INVALID_DOCUMENT",`Invalid visibilityGroup mark rejected from transaction: ${a.nodeName}.`,a)).create(),s=C.getSchema(o);this.editor=new C.Editor({element:t.element,extensions:o,content:this.resolveInitialTiptapContent(n,e,s),editable:!t.readonly,enableContentCheck:!0,editorProps:{handleTextInput:Le,handleDOMEvents:{compositionstart:wt,compositionend:wt}},onUpdate:({editor:a})=>this.handleEditorUpdate(a),onSelectionUpdate:({editor:a})=>{var h;const{from:l,to:d,empty:c}=a.state.selection;(h=t.onSelectionChange)==null||h.call(t,{from:l,to:d,empty:c})}}),this.currentOperationBatchId=void 0,this.pageBreakIdentity.applyToEditor(this.editor),this.controlPluginContext=this.createControlPluginContext(),this.editor.on("transaction",this.handleControlTransaction),this.numberingService.applyToEditor(this.editor,!1),this.initializeControlPlugins(),this.initializing=!1,t.emitInitialContent&&this.emitChange(this.editor),(i=t.onReady)==null||i.call(t,this)}getTiptapEditor(){return this.editor}focus(){this.editor.commands.focus()}destroy(){this.editor.off("transaction",this.handleControlTransaction),this.destroyControlPlugins(),this.editor.destroy()}undo(){return this.editor.commands.undo()}redo(){return this.editor.commands.redo()}getJSON(){return this.serializer.toJSON(this.editor)}getHTML(t="edit"){return this.serializer.toHTML(this.editor,t)}getPlainText(t={}){return this.serializer.toPlainText(this.editor,t)}setContent(t){this.runWithOperationBatch(e=>{const n=this.resolveTiptapContent(t,e,this.editor.schema,"Content update rejected.");if(!n)return;if(this.closeLocalHistoryEvent(),!this.editor.commands.setContent(n,!1,{},{errorOnInvalidContent:!0})){this.errors.error("INVALID_DOCUMENT","Content update rejected.",{content:t});return}this.closeLocalHistoryEvent(),this.emitChange(this.editor)})}clearContent(){this.setContent(O.empty(this.documentVersion))}applyTemplate(t){return this.ensureEditable()?this.runWithOperationBatch(e=>{this.selectionManager.save(this.editor),this.closeLocalHistoryEvent();const n=this.templateEngine.applyTemplate(this.editor,t,e);return n&&(this.selectionManager.restoreToDocumentEnd(this.editor),this.closeLocalHistoryEvent()),n}):!1}appendTemplate(t){return this.ensureEditable()?this.runWithOperationBatch(e=>{this.closeLocalHistoryEvent();const n=this.templateEngine.appendTemplate(this.editor,t,e);return n&&this.closeLocalHistoryEvent(),n}):!1}insertControl(t,e){if(!this.ensureEditable())return!1;const n=this.registry.getByNodeName(t);return n!=null&&n.isControl?this.validateControlAttrs(n.nodeName,e)?this.runWithOperationBatch(o=>this.editor.commands.insertContent({type:n.nodeName,attrs:this.identity.withFreshControlId(e,this.identity.collectIds(this.getJSON()),o)})):!1:(this.errors.error("INVALID_FIELD_CONFIG",`Control node is not registered: ${t}.`,{nodeType:t,attrs:e}),!1)}updateControlAttrs(t,e){return this.ensureEditable()?this.updateNodeAttrsByControlId(t,e):!1}getEditorId(){return this.editorId}getControls(){return Array.from(this.ensureControlSnapshots().values())}getControl(t){return this.ensureControlSnapshots().get(t)}updateControlValue(t,e){return this.ensureEditable()?this.updateNodeAttrsByControlId(t,{value:e}):!1}updateControlValueByFieldName(t,e){return this.ensureEditable()?this.updateNodeAttrsByFieldName(t,{value:e}):!1}insertPageBreak(){return this.ensureEditable()?this.editor.commands.insertPageBreak():!1}deletePageBreak(t){return this.ensureEditable()?this.editor.commands.deletePageBreak(t):!1}getPageBreaks(){const t=[];return this.editor.state.doc.descendants((e,n)=>{if(e.type.name!==x)return;const o=e.attrs.id;typeof o=="string"&&o.trim()&&t.push({id:o,pos:n})}),t}toggleHiddenParagraph(){return this.ensureEditable()?this.editor.commands.toggleHiddenParagraph():!1}setParagraphHidden(t){return this.ensureEditable()?this.editor.commands.setParagraphHidden(t):!1}moveNumberedBlock(t,e){return this.ensureEditable()?this.numberingService.moveBlock(this.editor,t,e):!1}setEditable(t){this.editor.setEditable(t)}createControlPluginContext(){return{editorId:this.editorId,editor:this.editor,getControl:t=>this.ensureControlSnapshots().get(t),getControls:()=>Array.from(this.ensureControlSnapshots().values()),updateControlAttrs:(t,e)=>this.updateNodeAttrsByControlId(t,e),warn:(t,e,n)=>this.errors.warning(t,e,n)}}initializeControlPlugins(){if(this.controlPlugins.length===0){this.controlSnapshotsDirty=!0;return}this.controlSnapshots=this.collectControlSnapshots(),this.controlSnapshotsDirty=!1;for(const t of this.controlPlugins)this.notifyControlPlugin(t,"onEditorReady",()=>{var e;return(e=t.onEditorReady)==null?void 0:e.call(t,this.controlPluginContext)});this.controlSnapshots=this.collectControlSnapshots(),this.controlSnapshotsDirty=!1;for(const t of this.controlSnapshots.values())for(const e of this.controlPlugins)this.notifyControlPlugin(e,"onControlAdded",()=>{var n;return(n=e.onControlAdded)==null?void 0:n.call(e,t,this.controlPluginContext)})}destroyControlPlugins(){const t=this.controlPlugins.length===0?[]:Array.from(this.ensureControlSnapshots().values());for(const e of t)for(const n of this.controlPlugins)this.notifyControlPlugin(n,"onControlRemoved",()=>{var o;return(o=n.onControlRemoved)==null?void 0:o.call(n,e,this.controlPluginContext)});for(const e of this.controlPlugins)this.notifyControlPlugin(e,"onEditorDestroyed",()=>{var n;return(n=e.onEditorDestroyed)==null?void 0:n.call(e,this.controlPluginContext)});this.controlSnapshots=new Map,this.controlSnapshotsDirty=!1}syncControlPlugins(){if(this.controlPlugins.length===0){this.controlSnapshotsDirty=!0;return}const t=this.controlSnapshots,e=this.collectControlSnapshots();this.controlSnapshots=e,this.controlSnapshotsDirty=!1;for(const n of t.values())if(!e.has(n.controlId))for(const o of this.controlPlugins)this.notifyControlPlugin(o,"onControlRemoved",()=>{var s;return(s=o.onControlRemoved)==null?void 0:s.call(o,n,this.controlPluginContext)});for(const n of e.values()){const o=t.get(n.controlId);if(!o){for(const i of this.controlPlugins)this.notifyControlPlugin(i,"onControlAdded",()=>{var a;return(a=i.onControlAdded)==null?void 0:a.call(i,n,this.controlPluginContext)});continue}const s={previous:o,current:n};if(!this.isSameValue(o.attrs.value,n.attrs.value))for(const i of this.controlPlugins)this.notifyControlPlugin(i,"onControlValueChanged",()=>{var a;return(a=i.onControlValueChanged)==null?void 0:a.call(i,s,this.controlPluginContext)});if(!this.isSameControlMetadata(o,n))for(const i of this.controlPlugins)this.notifyControlPlugin(i,"onControlMetadataChanged",()=>{var a;return(a=i.onControlMetadataChanged)==null?void 0:a.call(i,s,this.controlPluginContext)})}}syncChangedControlSnapshots(t){const e=new Map,n=new Map,o=new Map(this.controlSnapshots);for(const s of t){const i=this.controlSnapshots.get(s);if(!i){this.syncControlPlugins();return}const a=this.editor.state.doc.nodeAt(i.pos);if(!a||!this.registry.isControlNode(a.type.name)||a.attrs.controlId!==s){this.syncControlPlugins();return}const l={editorId:this.editorId,nodeType:a.type.name,controlId:s,attrs:a.attrs,pos:i.pos};e.set(s,i),n.set(s,l),o.set(s,l)}this.controlSnapshots=o,this.controlSnapshotsDirty=!1;for(const[s,i]of n){const a=e.get(s),l={previous:a,current:i};if(!this.isSameValue(a.attrs.value,i.attrs.value))for(const d of this.controlPlugins)this.notifyControlPlugin(d,"onControlValueChanged",()=>{var c;return(c=d.onControlValueChanged)==null?void 0:c.call(d,l,this.controlPluginContext)});if(!this.isSameControlMetadata(a,i))for(const d of this.controlPlugins)this.notifyControlPlugin(d,"onControlMetadataChanged",()=>{var c;return(c=d.onControlMetadataChanged)==null?void 0:c.call(d,l,this.controlPluginContext)})}}ensureControlSnapshots(){return this.controlSnapshotsDirty&&(this.controlSnapshots=this.collectControlSnapshots(),this.controlSnapshotsDirty=!1),this.controlSnapshots}collectControlSnapshots(){const t=new Map;return this.editor.state.doc.descendants((e,n)=>{if(!this.registry.isControlNode(e.type.name))return;const o=e.attrs.controlId;typeof o!="string"||!o.trim()||t.set(o,{editorId:this.editorId,nodeType:e.type.name,controlId:o,attrs:e.attrs,pos:n})}),t}isSameControlMetadata(t,e){return["batchId","templateId","widgetNumber","defaultValue","noMatchDefault","rules","nextWidgetNumber","ruleStyleColor"].every(o=>this.isSameValue(t.attrs[o],e.attrs[o]))}notifyControlPlugin(t,e,n){try{n()}catch(o){this.errors.warning("CONTROL_PLUGIN_FAILED",`Control plugin ${t.name??"anonymous"} failed in ${e}.`,o)}}runWithOperationBatch(t){const e=this.currentOperationBatchId,n=e??this.createOperationBatchId();this.currentOperationBatchId=n;try{return t(n)}finally{this.currentOperationBatchId=e}}closeLocalHistoryEvent(){const t=Ne.closeHistory(this.editor.state.tr).setMeta("addToHistory",!1);this.editor.view.dispatch(t)}getPluginBatchId(){var t;for(const e of this.controlPlugins){const n=(t=e.getCurrentBatchId)==null?void 0:t.call(e);if(n!=null&&n.trim())return n}}createOperationBatchId(){return this.getPluginBatchId()??this.identity.createBatchId()}createEditorId(){const t=globalThis.crypto;return t!=null&&t.randomUUID?`editor_${t.randomUUID()}`:`editor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}isSameValue(t,e){return Object.is(t,e)?!0:typeof t=="object"||typeof e=="object"?JSON.stringify(t??null)===JSON.stringify(e??null):!1}resolveInitialContent(t,e){if(t.content)return t.content;if(t.template)try{return this.templateEngine.toDocument(t.template,e)}catch(n){this.errors.error("TEMPLATE_PARSE_FAILED","Initial template parse failed.",n)}return O.empty(this.documentVersion)}resolveInitialTiptapContent(t,e,n){return this.resolveTiptapContent(t,e,n,"Initial content rejected.")??O.toTiptapContent(O.empty(this.documentVersion))}resolveTiptapContent(t,e,n,o){try{const s=this.normalizeContent(t,e,n);return O.toTiptapContent(s)}catch(s){this.reportContentError(o,s);return}}normalizeContent(t,e,n){if(typeof t=="string"){const s=this.parseHTMLContent(t,n),i=this.pageBreakIdentity.normalizeDocument(this.identity.normalizeDocument(s,e));return $t(i,this.registry,n),i}bn(t,this.documentVersion);const o=this.pageBreakIdentity.normalizeDocument(this.identity.normalizeDocument(t,e));return $t(o,this.registry,n),o}parseHTMLContent(t,e){try{const n=this.pasteSanitizer.sanitize(t),o=C.createDocument(n,e,{},{errorOnInvalidContent:!1});return O.fromTiptapJSON(o.toJSON(),this.documentVersion)}catch(n){throw new E("INVALID_DOCUMENT","HTML content could not be parsed.",n)}}reportContentError(t,e){if(e instanceof E){this.errors.error(e.code,t,e);return}this.errors.error("INVALID_DOCUMENT",t,e)}handleEditorUpdate(t){this.initializing||this.emitChange(t)}emitChange(t){if(!this.options.onChange)return;const e=this.serializer.toJSON(t);this.options.onChange({json:e,html:this.serializer.toHTMLFromJSON(e,"edit"),tiptapEditor:t})}ensureEditable(){return this.editor.isEditable?!0:(this.errors.warning("COMMAND_FAILED","Command ignored because editor is readonly."),!1)}validateControlAttrs(t,e){const n=this.registry.getByNodeName(t);if(!(n!=null&&n.validateAttrs))return!0;try{return n.validateAttrs(e),!0}catch(o){return this.errors.error("INVALID_FIELD_CONFIG",`Invalid control attrs for ${t}.`,o),!1}}updateNodeAttrsByControlId(t,e){let n=!1,o=!1,s=!0,i=!1,a=this.editor.state.tr;return this.editor.state.doc.descendants((l,d)=>{if(n||!this.registry.isControlNode(l.type.name)||l.attrs.controlId!==t)return;const c={...l.attrs,...e};if(o=Object.entries(e).some(([h,f])=>!this.isSameValue(l.attrs[h],f)),!o){n=!0;return}if(!this.validateControlAttrs(l.type.name,c)){n=!0,s=!1;return}a.setNodeMarkup(d,void 0,{...c},l.marks),i=this.isStableControlIdentity(l.attrs,c),n=!0}),n?s?(o&&(i&&(a=pt(a,[t])),this.editor.view.dispatch(a)),!0):!1:(this.errors.warning("INVALID_FIELD_CONFIG",`Control not found: ${t}.`,{controlId:t}),!1)}updateNodeAttrsByFieldName(t,e){let n=!1,o=!1,s=!0;const i=[];if(this.editor.state.doc.descendants((l,d)=>{if(!this.registry.isControlNode(l.type.name)||l.attrs.fieldName!==t)return;n=!0;const c={...l.attrs,...e};if(Object.entries(e).some(([f,u])=>!this.isSameValue(l.attrs[f],u))){if(!this.validateControlAttrs(l.type.name,c)){s=!1;return}o=!0,i.push({pos:d,attrs:c,stableIdentity:this.isStableControlIdentity(l.attrs,c)})}}),!n)return this.errors.warning("INVALID_FIELD_CONFIG",`Control not found: ${t}.`,{fieldName:t}),!1;if(!s)return!1;if(!o)return!0;let a=this.editor.state.tr;for(const l of i){const d=a.doc.nodeAt(l.pos);a.setNodeMarkup(l.pos,void 0,l.attrs,d==null?void 0:d.marks)}return i.every(l=>l.stableIdentity)&&(a=pt(a,i.map(l=>String(l.attrs.controlId??"")))),this.editor.view.dispatch(a),!0}isStableControlIdentity(t,e){return typeof e.controlId=="string"&&e.controlId.trim().length>0&&e.controlId===t.controlId&&typeof e.batchId=="string"&&e.batchId.trim().length>0}}function Nn(r={}){return new wn(r)}class Ce{constructor(t={}){p(this,"editors",new Map);p(this,"activeEditorId");this.options=t}register(t,e){this.editors.set(t,e),this.activeEditorId=t,this.emitChange()}unregister(t){this.editors.delete(t)&&(this.activeEditorId===t&&(this.activeEditorId=void 0),this.emitChange())}has(t){return this.editors.has(t)}get(t){return this.editors.get(t)}entries(){return Array.from(this.editors.entries()).map(([t,e])=>({editorId:t,editor:e}))}getEditorIds(){return Array.from(this.editors.keys())}getEditorElements(){return this.entries().map(({editor:t})=>t.getTiptapEditor().view.dom)}setActiveEditor(t){return this.editors.has(t)?(this.activeEditorId=t,this.emitChange(),!0):!1}getActiveEditorId(){return this.activeEditorId}getState(){return{editorIds:this.getEditorIds(),activeEditorId:this.activeEditorId}}emitChange(){var t,e;(e=(t=this.options).onChange)==null||e.call(t,this.getState())}}const q=class q{constructor(t={}){p(this,"editorGroup");p(this,"registeredEditors",new Map);p(this,"undoStack",[]);p(this,"redoStack",[]);p(this,"maxDepth");p(this,"isCaptureSuppressed",!1);p(this,"pendingCaptureEditorIds",new Set);p(this,"pendingCaptureActiveEditorIdBefore");p(this,"pendingCaptureScheduled",!1);p(this,"pendingCaptureToken",0);this.options=t,this.maxDepth=Math.min(Math.max(1,t.maxDepth??q.DEFAULT_MAX_DEPTH),q.MAX_DEPTH_LIMIT),this.editorGroup=t.editorGroup??new Ce}register(t,e){var s;this.flushPendingCaptures();const n=this.editorGroup.get(t),o=this.registeredEditors.get(t);(s=o==null?void 0:o.unsubscribe)==null||s.call(o),o&&n!==e&&this.removeEntriesForEditor(t),this.registeredEditors.set(t,{lastSnapshot:this.snapshotFromEditor(e)}),this.editorGroup.register(t,e),this.emitChange()}unregister(t){var n;this.flushPendingCaptures();const e=this.registeredEditors.get(t);(n=e==null?void 0:e.unsubscribe)==null||n.call(e),this.registeredEditors.delete(t),this.editorGroup.unregister(t),this.removeEntriesForEditor(t),this.emitChange()}setActiveEditor(t){return this.flushPendingCaptures(),this.editorGroup.setActiveEditor(t)?(this.emitChange(),!0):!1}getEditorGroup(){return this.editorGroup}track(t,e){this.register(t,e);const n=()=>{this.isCaptureSuppressed||this.queueCapture(t)},o=()=>{this.editorGroup.setActiveEditor(t),this.emitChange()},s=e.getTiptapEditor();s.on("update",n),s.on("focus",o);const i=()=>{s.off("update",n),s.off("focus",o)},a=()=>{i();const d=this.registeredEditors.get(t);(d==null?void 0:d.unsubscribe)===a&&(d.unsubscribe=void 0)},l=this.registeredEditors.get(t);return l&&(l.unsubscribe=a),a}capture(t,e){if(this.flushPendingCaptures(e).has(t))return!0;const o=this.registeredEditors.get(t),s=this.editorGroup.get(t);if(!o||!s||this.isCaptureSuppressed)return!1;const i=o.lastSnapshot,a=this.snapshotFromEditor(s);return this.isSameSnapshot(i,a)?!1:(o.lastSnapshot=a,this.pushSingleEntry({editorId:t,before:i,after:a,timestamp:Date.now(),label:e}))}run(t,e,n){this.flushPendingCaptures();const o=this.registeredEditors.get(t),s=this.editorGroup.get(t);if(!o||!s){const u=e();if(U(u))throw new Error("SharedHistoryManager.run requires a synchronous operation.");return!1}if(this.isCaptureSuppressed){const u=e();if(U(u))throw new Error("SharedHistoryManager.run requires a synchronous operation.");return u!==!1}const i=this.editorGroup.getActiveEditorId(),a=this.snapshotAllRegisteredEditors();this.isCaptureSuppressed=!0;let l,d,c=!1;try{l=e()}catch(u){c=!0,d=u}finally{this.isCaptureSuppressed=!1}!c&&U(l)&&(c=!0,d=new Error("SharedHistoryManager.run requires a synchronous operation."));const h=this.collectChangedEntries(a,n),f=l!==!1&&h.length>0?this.pushOperationEntries(h,i,this.editorGroup.getActiveEditorId(),n):!1;if(c)throw d;return!!f}runBatch(t,e,n){var f;if(this.flushPendingCaptures(),this.collectRegisteredTargets(t).length===0){const u=e();if(U(u))throw new Error("SharedHistoryManager.runBatch requires a synchronous operation.");return!1}if(this.isCaptureSuppressed){const u=e();if(U(u))throw new Error("SharedHistoryManager.runBatch requires a synchronous operation.");return u!==!1}const s=this.editorGroup.getActiveEditorId(),i=this.snapshotAllRegisteredEditors();this.isCaptureSuppressed=!0;let a,l,d=!1;try{a=e()}catch(u){d=!0,l=u}finally{this.isCaptureSuppressed=!1}!d&&U(a)&&(d=!0,l=new Error("SharedHistoryManager.runBatch requires a synchronous operation."));const c=this.collectChangedEntries(i,n),h=a!==!1&&c.length>0?this.pushBatchEntry({kind:"batch",entries:c,activeEditorIdBefore:s,activeEditorIdAfter:this.editorGroup.getActiveEditorId(),timestamp:((f=c[0])==null?void 0:f.timestamp)??Date.now(),label:n}):!1;if(d)throw l;return h}record(t){if(this.flushPendingCaptures(t.label),this.isCaptureSuppressed)return!1;const e=this.registeredEditors.get(t.editorId),n=this.editorGroup.get(t.editorId);if(!e||!n)return!1;const o=this.createSnapshot(t.before),s=this.createSnapshot(t.after);if(this.latestEntryMatches(t.editorId,o,s))return this.synchronizeRegisteredSnapshot(t.editorId),!0;if(this.isSameSnapshot(o,s))return!1;const i=this.pushSingleEntry({...t,before:o,after:s,timestamp:t.timestamp??Date.now()});return i&&this.synchronizeRegisteredSnapshot(t.editorId),i}undo(){this.flushPendingCaptures();const t=this.undoStack.pop();if(!t)return!1;try{if(!this.restore(t,"undo"))return this.undoStack.push(t),!1}catch(e){throw this.undoStack.push(t),e}return this.redoStack.push(t),this.trimStack(this.redoStack),this.emitChange(),this.notifyRestore(t,"undo"),!0}redo(){this.flushPendingCaptures();const t=this.redoStack.pop();if(!t)return!1;try{if(!this.restore(t,"redo"))return this.redoStack.push(t),!1}catch(e){throw this.redoStack.push(t),e}return this.undoStack.push(t),this.trimStack(this.undoStack),this.emitChange(),this.notifyRestore(t,"redo"),!0}clear(t){this.flushPendingCaptures(),t?this.removeEntriesForEditor(t):(this.undoStack.length=0,this.redoStack.length=0),this.emitChange()}canUndo(){return this.flushPendingCaptures(),this.undoStack.length>0}canRedo(){return this.flushPendingCaptures(),this.redoStack.length>0}getUndoDepth(){return this.flushPendingCaptures(),this.undoStack.length}getRedoDepth(){return this.flushPendingCaptures(),this.redoStack.length}getActiveEditorId(){return this.editorGroup.getActiveEditorId()}getState(){return this.flushPendingCaptures(),this.createStatePayload()}queueCapture(t){if(this.pendingCaptureEditorIds.size===0&&(this.pendingCaptureActiveEditorIdBefore=this.editorGroup.getActiveEditorId()),this.pendingCaptureEditorIds.add(t),this.pendingCaptureScheduled)return;this.pendingCaptureScheduled=!0;const e=++this.pendingCaptureToken;queueMicrotask(()=>{this.pendingCaptureScheduled&&this.pendingCaptureToken===e&&this.flushPendingCaptures()})}flushPendingCaptures(t){if(this.pendingCaptureEditorIds.size===0||this.isCaptureSuppressed)return new Set;const e=new Set(this.pendingCaptureEditorIds),n=this.pendingCaptureActiveEditorIdBefore;this.pendingCaptureEditorIds.clear(),this.pendingCaptureActiveEditorIdBefore=void 0,this.pendingCaptureScheduled=!1,this.pendingCaptureToken+=1;const o=new Map;for(const i of e){const a=this.registeredEditors.get(i);a&&o.set(i,a.lastSnapshot)}const s=this.collectChangedEntries(o,t,e);return s.length>0&&this.pushOperationEntries(s,n,this.editorGroup.getActiveEditorId(),t),new Set(s.map(i=>i.editorId))}snapshotAllRegisteredEditors(){const t=new Map;for(const[e]of this.registeredEditors){const n=this.editorGroup.get(e);n&&t.set(e,this.snapshotFromEditor(n))}return t}collectChangedEntries(t,e,n){const o=Date.now(),s=[];for(const[i,a]of this.registeredEditors){if(n&&!n.has(i))continue;const l=this.editorGroup.get(i);if(!l)continue;const d=t.get(i)??a.lastSnapshot,c=this.snapshotFromEditor(l);a.lastSnapshot=c,!this.isSameSnapshot(d,c)&&s.push({editorId:i,before:d,after:c,timestamp:o,label:e})}return s}pushOperationEntries(t,e,n,o){var s;return t.length===1?this.pushSingleEntry(t[0]):this.pushBatchEntry({kind:"batch",entries:t,activeEditorIdBefore:e,activeEditorIdAfter:n,timestamp:((s=t[0])==null?void 0:s.timestamp)??Date.now(),label:o})}pushSingleEntry(t){return this.undoStack.push({kind:"single",entry:t}),this.trimStack(this.undoStack),this.redoStack.length=0,this.setActiveEditorIfAvailable(t.editorId),this.emitChange(),!0}pushBatchEntry(t){const e=t.entries[t.entries.length-1];return this.undoStack.push(t),this.trimStack(this.undoStack),this.redoStack.length=0,this.setActiveEditorIfAvailable(t.activeEditorIdAfter??(e==null?void 0:e.editorId)),this.emitChange(),!0}restore(t,e){return t.kind==="single"?this.restoreSingle(t.entry,e):this.restoreBatch(t,e)}restoreSingle(t,e){const n=this.registeredEditors.get(t.editorId),o=this.editorGroup.get(t.editorId);if(!n||!o)return!1;const s=e==="undo"?t.before:t.after,i=this.snapshotFromEditor(o),a=this.editorGroup.getActiveEditorId();this.isCaptureSuppressed=!0;try{o.setContent(this.cloneSnapshotDocument(s)),n.lastSnapshot=s,this.synchronizeRegisteredSnapshots()}catch(l){try{o.setContent(this.cloneSnapshotDocument(i))}catch{}throw this.synchronizeRegisteredSnapshots(),this.setActiveEditorIfAvailable(a),l}finally{this.isCaptureSuppressed=!1}return this.setActiveEditorIfAvailable(t.editorId),!0}restoreBatch(t,e){const n=[],o=this.editorGroup.getActiveEditorId();for(const a of t.entries){const l=this.registeredEditors.get(a.editorId),d=this.editorGroup.get(a.editorId);if(!l||!d)return!1;n.push({editorId:a.editorId,editor:d,registered:l,document:e==="undo"?a.before:a.after,previousDocument:this.snapshotFromEditor(d)})}this.isCaptureSuppressed=!0;try{for(const a of n)a.editor.setContent(this.cloneSnapshotDocument(a.document)),a.registered.lastSnapshot=a.document;this.synchronizeRegisteredSnapshots()}catch(a){for(const l of[...n].reverse())try{l.editor.setContent(this.cloneSnapshotDocument(l.previousDocument))}catch{}throw this.synchronizeRegisteredSnapshots(),this.setActiveEditorIfAvailable(o),a}finally{this.isCaptureSuppressed=!1}const s=e==="undo"?t.activeEditorIdBefore:t.activeEditorIdAfter,i=n[n.length-1];return this.setActiveEditorIfAvailable(s??(i==null?void 0:i.editorId)),!0}notifyRestore(t,e){if(!this.options.onRestore)return;const n=t.kind==="single"?[t.entry]:t.entries;let o;for(const s of n)try{this.options.onRestore(this.toPublicEntry(s),e)}catch(i){o??(o=i)}if(o!==void 0)throw o}collectRegisteredTargets(t){const e=[],n=new Set;for(const o of t){if(n.has(o))continue;n.add(o);const s=this.registeredEditors.get(o),i=this.editorGroup.get(o);s&&i&&e.push({editorId:o,editor:i,registered:s})}return e}setActiveEditorIfAvailable(t){t&&this.editorGroup.has(t)&&this.editorGroup.setActiveEditor(t)}removeEntriesForEditor(t){this.removeFromStack(this.undoStack,t),this.removeFromStack(this.redoStack,t)}removeFromStack(t,e){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.kind==="single"){o.entry.editorId===e&&t.splice(n,1);continue}o.entries.some(s=>s.editorId===e)&&t.splice(n,1)}}trimStack(t){for(;t.length>this.maxDepth;)t.shift()}emitChange(){var t,e;(e=(t=this.options).onChange)==null||e.call(t,this.createStatePayload())}createStatePayload(){return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,activeEditorId:this.editorGroup.getActiveEditorId()}}latestEntryMatches(t,e,n){const o=this.undoStack[this.undoStack.length-1];if(!o)return!1;const s=o.kind==="single"?o.entry.editorId===t?o.entry:void 0:o.entries.find(i=>i.editorId===t);return!!(s&&this.isSameSnapshot(s.before,e)&&this.isSameSnapshot(s.after,n))}synchronizeRegisteredSnapshot(t){const e=this.registeredEditors.get(t),n=this.editorGroup.get(t);e&&n&&(e.lastSnapshot=this.snapshotFromEditor(n))}synchronizeRegisteredSnapshots(){for(const[t,e]of this.registeredEditors){const n=this.editorGroup.get(t);n&&(e.lastSnapshot=this.snapshotFromEditor(n))}}snapshotFromEditor(t){return this.createSnapshot(t.getJSON())}createSnapshot(t){return{serialized:JSON.stringify(t)}}cloneSnapshotDocument(t){return JSON.parse(t.serialized)}isSameSnapshot(t,e){return t.serialized===e.serialized}toPublicEntry(t){return{editorId:t.editorId,before:this.cloneSnapshotDocument(t.before),after:this.cloneSnapshotDocument(t.after),timestamp:t.timestamp,label:t.label}}};p(q,"DEFAULT_MAX_DEPTH",30),p(q,"MAX_DEPTH_LIMIT",30);let mt=q;function U(r){return(typeof r=="object"||typeof r=="function")&&r!==null&&"then"in r&&typeof r.then=="function"}exports.ReportEditorGroupManager=Ce;exports.SharedHistoryManager=mt;exports.createReportEditor=Nn;exports.createReportFeatureRegistry=H;exports.defineReportControl=sn;exports.defineReportFeature=ln;exports.defineReportMark=an;exports.defineReportNode=on;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** core 包公共出口,集中暴露编辑器、分组、历史和扩展注册 API。 */
|
|
2
|
+
export { createReportEditor } from './editor/createReportEditor.js';
|
|
3
|
+
export { ReportEditorGroupManager } from './group/ReportEditorGroupManager.js';
|
|
4
|
+
export { SharedHistoryManager } from './history/SharedHistoryManager.js';
|
|
5
|
+
export { createReportFeatureRegistry, defineReportControl, defineReportFeature, defineReportMark, defineReportNode } from './registry/ReportFeatureRegistry.js';
|
|
6
|
+
export type { ReportEditorGroupChangePayload, ReportEditorGroupEntry, ReportEditorGroupManagerOptions } from './group/ReportEditorGroupManager.js';
|
|
7
|
+
export type * from './types/index.js';
|