@univerjs/sheets-formula-ui 0.6.0-alpha.0 → 0.6.0-experimental.20250212-dbe9830

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/lib/cjs/index.js +15 -15
  2. package/lib/es/index.js +1777 -1733
  3. package/lib/types/common/plugin-name.d.ts +1 -1
  4. package/lib/types/common/prompt.d.ts +1 -1
  5. package/lib/types/controllers/formula-process.controller.d.ts +1 -1
  6. package/lib/types/index.d.ts +1 -1
  7. package/lib/types/locale/en-US.d.ts +1 -1
  8. package/lib/types/locale/fa-IR.d.ts +1 -1
  9. package/lib/types/locale/fr-FR.d.ts +1 -1
  10. package/lib/types/locale/function-list/array/en-US.d.ts +1 -1
  11. package/lib/types/locale/function-list/array/fr-FR.d.ts +1 -1
  12. package/lib/types/locale/function-list/array/ja-JP.d.ts +1 -1
  13. package/lib/types/locale/function-list/array/ru-RU.d.ts +1 -1
  14. package/lib/types/locale/function-list/array/vi-VN.d.ts +1 -1
  15. package/lib/types/locale/function-list/array/zh-CN.d.ts +1 -1
  16. package/lib/types/locale/function-list/array/zh-TW.d.ts +1 -1
  17. package/lib/types/locale/function-list/compatibility/en-US.d.ts +1 -1
  18. package/lib/types/locale/function-list/compatibility/fr-FR.d.ts +1 -1
  19. package/lib/types/locale/function-list/compatibility/ja-JP.d.ts +1 -1
  20. package/lib/types/locale/function-list/compatibility/vi-VN.d.ts +1 -1
  21. package/lib/types/locale/function-list/compatibility/zh-CN.d.ts +1 -1
  22. package/lib/types/locale/function-list/compatibility/zh-TW.d.ts +1 -1
  23. package/lib/types/locale/function-list/cube/en-US.d.ts +1 -1
  24. package/lib/types/locale/function-list/cube/fr-FR.d.ts +1 -1
  25. package/lib/types/locale/function-list/cube/ja-JP.d.ts +1 -1
  26. package/lib/types/locale/function-list/cube/ru-RU.d.ts +1 -1
  27. package/lib/types/locale/function-list/cube/vi-VN.d.ts +1 -1
  28. package/lib/types/locale/function-list/cube/zh-CN.d.ts +1 -1
  29. package/lib/types/locale/function-list/cube/zh-TW.d.ts +1 -1
  30. package/lib/types/locale/function-list/database/en-US.d.ts +1 -1
  31. package/lib/types/locale/function-list/database/fr-FR.d.ts +1 -1
  32. package/lib/types/locale/function-list/database/ja-JP.d.ts +1 -1
  33. package/lib/types/locale/function-list/database/ru-RU.d.ts +1 -1
  34. package/lib/types/locale/function-list/database/vi-VN.d.ts +1 -1
  35. package/lib/types/locale/function-list/database/zh-CN.d.ts +1 -1
  36. package/lib/types/locale/function-list/database/zh-TW.d.ts +1 -1
  37. package/lib/types/locale/function-list/date/en-US.d.ts +1 -1
  38. package/lib/types/locale/function-list/date/fr-FR.d.ts +1 -1
  39. package/lib/types/locale/function-list/date/ja-JP.d.ts +1 -1
  40. package/lib/types/locale/function-list/date/vi-VN.d.ts +1 -1
  41. package/lib/types/locale/function-list/date/zh-CN.d.ts +1 -1
  42. package/lib/types/locale/function-list/date/zh-TW.d.ts +1 -1
  43. package/lib/types/locale/function-list/engineering/en-US.d.ts +1 -1
  44. package/lib/types/locale/function-list/engineering/fr-FR.d.ts +1 -1
  45. package/lib/types/locale/function-list/engineering/ja-JP.d.ts +1 -1
  46. package/lib/types/locale/function-list/engineering/vi-VN.d.ts +1 -1
  47. package/lib/types/locale/function-list/engineering/zh-CN.d.ts +1 -1
  48. package/lib/types/locale/function-list/engineering/zh-TW.d.ts +1 -1
  49. package/lib/types/locale/function-list/financial/en-US.d.ts +1 -1
  50. package/lib/types/locale/function-list/financial/fr-FR.d.ts +1 -1
  51. package/lib/types/locale/function-list/financial/ja-JP.d.ts +1 -1
  52. package/lib/types/locale/function-list/financial/vi-VN.d.ts +1 -1
  53. package/lib/types/locale/function-list/financial/zh-CN.d.ts +1 -1
  54. package/lib/types/locale/function-list/financial/zh-TW.d.ts +1 -1
  55. package/lib/types/locale/function-list/information/en-US.d.ts +1 -1
  56. package/lib/types/locale/function-list/information/fr-FR.d.ts +1 -1
  57. package/lib/types/locale/function-list/information/ja-JP.d.ts +1 -1
  58. package/lib/types/locale/function-list/information/vi-VN.d.ts +1 -1
  59. package/lib/types/locale/function-list/information/zh-CN.d.ts +1 -1
  60. package/lib/types/locale/function-list/information/zh-TW.d.ts +1 -1
  61. package/lib/types/locale/function-list/logical/en-US.d.ts +1 -1
  62. package/lib/types/locale/function-list/logical/fr-FR.d.ts +1 -1
  63. package/lib/types/locale/function-list/logical/ja-JP.d.ts +1 -1
  64. package/lib/types/locale/function-list/logical/vi-VN.d.ts +1 -1
  65. package/lib/types/locale/function-list/logical/zh-CN.d.ts +1 -1
  66. package/lib/types/locale/function-list/logical/zh-TW.d.ts +1 -1
  67. package/lib/types/locale/function-list/lookup/en-US.d.ts +1 -1
  68. package/lib/types/locale/function-list/lookup/fr-FR.d.ts +1 -1
  69. package/lib/types/locale/function-list/lookup/ja-JP.d.ts +1 -1
  70. package/lib/types/locale/function-list/lookup/vi-VN.d.ts +1 -1
  71. package/lib/types/locale/function-list/lookup/zh-CN.d.ts +1 -1
  72. package/lib/types/locale/function-list/lookup/zh-TW.d.ts +1 -1
  73. package/lib/types/locale/function-list/math/en-US.d.ts +1 -1
  74. package/lib/types/locale/function-list/math/fr-FR.d.ts +1 -1
  75. package/lib/types/locale/function-list/math/ja-JP.d.ts +1 -1
  76. package/lib/types/locale/function-list/math/vi-VN.d.ts +1 -1
  77. package/lib/types/locale/function-list/math/zh-CN.d.ts +1 -1
  78. package/lib/types/locale/function-list/math/zh-TW.d.ts +1 -1
  79. package/lib/types/locale/function-list/statistical/en-US.d.ts +1 -1
  80. package/lib/types/locale/function-list/statistical/fr-FR.d.ts +1 -1
  81. package/lib/types/locale/function-list/statistical/ja-JP.d.ts +1 -1
  82. package/lib/types/locale/function-list/statistical/vi-VN.d.ts +1 -1
  83. package/lib/types/locale/function-list/statistical/zh-CN.d.ts +1 -1
  84. package/lib/types/locale/function-list/statistical/zh-TW.d.ts +1 -1
  85. package/lib/types/locale/function-list/text/en-US.d.ts +1 -1
  86. package/lib/types/locale/function-list/text/fr-FR.d.ts +1 -1
  87. package/lib/types/locale/function-list/text/ja-JP.d.ts +1 -1
  88. package/lib/types/locale/function-list/text/ru-RU.d.ts +1 -1
  89. package/lib/types/locale/function-list/text/vi-VN.d.ts +1 -1
  90. package/lib/types/locale/function-list/text/zh-CN.d.ts +1 -1
  91. package/lib/types/locale/function-list/text/zh-TW.d.ts +1 -1
  92. package/lib/types/locale/function-list/univer/en-US.d.ts +1 -1
  93. package/lib/types/locale/function-list/univer/fr-FR.d.ts +1 -1
  94. package/lib/types/locale/function-list/univer/ja-JP.d.ts +1 -1
  95. package/lib/types/locale/function-list/univer/ru-RU.d.ts +1 -1
  96. package/lib/types/locale/function-list/univer/vi-VN.d.ts +1 -1
  97. package/lib/types/locale/function-list/univer/zh-CN.d.ts +1 -1
  98. package/lib/types/locale/function-list/univer/zh-TW.d.ts +1 -1
  99. package/lib/types/locale/function-list/web/en-US.d.ts +1 -1
  100. package/lib/types/locale/function-list/web/fr-FR.d.ts +1 -1
  101. package/lib/types/locale/function-list/web/ja-JP.d.ts +1 -1
  102. package/lib/types/locale/function-list/web/ru-RU.d.ts +1 -1
  103. package/lib/types/locale/function-list/web/vi-VN.d.ts +1 -1
  104. package/lib/types/locale/function-list/web/zh-CN.d.ts +1 -1
  105. package/lib/types/locale/function-list/web/zh-TW.d.ts +1 -1
  106. package/lib/types/locale/ru-RU.d.ts +1 -1
  107. package/lib/types/locale/vi-VN.d.ts +1 -1
  108. package/lib/types/locale/zh-CN.d.ts +1 -1
  109. package/lib/types/locale/zh-TW.d.ts +1 -1
  110. package/lib/types/views/FormulaPromptContainer.d.ts +1 -1
  111. package/lib/types/views/formula-editor/hooks/{useEditorPostion.d.ts → use-editor-position.d.ts} +1 -1
  112. package/lib/types/views/formula-editor/hooks/{useFormulaSearch.d.ts → use-formula-search.d.ts} +1 -1
  113. package/lib/types/views/formula-editor/hooks/{useFormulaSelection.d.ts → use-formula-selection.d.ts} +8 -2
  114. package/lib/types/views/formula-editor/hooks/{useResizeScrollObserver.d.ts → use-resize-scroll-observer.d.ts} +1 -1
  115. package/lib/types/views/formula-editor/hooks/{useSheetSelectionChange.d.ts → use-sheet-selection-change.d.ts} +3 -3
  116. package/lib/types/views/formula-editor/hooks/{useStateRef.d.ts → use-state-ref.d.ts} +1 -1
  117. package/lib/types/views/formula-editor/index.d.ts +2 -2
  118. package/lib/types/views/formula-editor/utils/{getFormulaText.d.ts → get-formula-text.d.ts} +1 -1
  119. package/lib/types/views/formula-progress/FormulaProgress.d.ts +1 -1
  120. package/lib/types/views/more-functions/MoreFunctions.d.ts +1 -1
  121. package/lib/types/views/more-functions/interface.d.ts +1 -1
  122. package/lib/types/views/prompt/help-function/HelpFunction.d.ts +1 -1
  123. package/lib/types/views/prompt/resize-scroll-observer.d.ts +1 -1
  124. package/lib/types/views/prompt/search-function/SearchFunction.d.ts +1 -1
  125. package/lib/types/views/range-selector/hooks/{useFirstHighlightDoc.d.ts → use-first-highlight-doc.d.ts} +1 -1
  126. package/lib/types/views/range-selector/hooks/{useHighlight.d.ts → use-highlight.d.ts} +1 -1
  127. package/lib/types/views/range-selector/hooks/{useIsFirstRender.d.ts → use-is-first-render.d.ts} +1 -1
  128. package/lib/types/views/range-selector/hooks/{useKeyboardEvent.d.ts → use-keyboard-event.d.ts} +1 -1
  129. package/lib/types/views/range-selector/hooks/{useLeftAndRightArrow.d.ts → use-left-and-right-arrow.d.ts} +1 -1
  130. package/lib/types/views/range-selector/hooks/{useOnlyOneRange.d.ts → use-only-one-range.d.ts} +1 -1
  131. package/lib/types/views/range-selector/hooks/{useRefactorEffect.d.ts → use-refactor-effect.d.ts} +1 -1
  132. package/lib/types/views/range-selector/hooks/{useRefocus.d.ts → use-refocus.d.ts} +1 -1
  133. package/lib/types/views/range-selector/hooks/{useResetSelection.d.ts → use-reset-selection.d.ts} +1 -1
  134. package/lib/types/views/range-selector/hooks/{useResize.d.ts → use-resize.d.ts} +1 -1
  135. package/lib/types/views/range-selector/hooks/{useSheetSelectionChange.d.ts → use-sheet-selection-change.d.ts} +1 -1
  136. package/lib/types/views/range-selector/hooks/{useSwitchSheet.d.ts → use-switch-sheet.d.ts} +1 -1
  137. package/lib/types/views/range-selector/hooks/{useVerify.d.ts → use-verify.d.ts} +1 -1
  138. package/lib/umd/index.js +14 -14
  139. package/package.json +15 -15
  140. package/LICENSE +0 -176
  141. package/lib/types/views/formula-editor/hooks/useSelectionAdd.d.ts +0 -18
  142. /package/lib/types/views/formula-editor/hooks/{useFormulaDescribe.d.ts → use-formula-describe.d.ts} +0 -0
  143. /package/lib/types/views/formula-editor/hooks/{useVerify.d.ts → use-verify.d.ts} +0 -0
  144. /package/lib/types/views/range-selector/hooks/{useEditorInput.d.ts → use-editor-input.d.ts} +0 -0
  145. /package/lib/types/views/range-selector/hooks/{useFocus.d.ts → use-focus.d.ts} +0 -0
  146. /package/lib/types/views/range-selector/hooks/{useFormulaToken.d.ts → use-formula-token.d.ts} +0 -0
  147. /package/lib/types/views/range-selector/utils/{filterReferenceNode.d.ts → filter-reference-node.d.ts} +0 -0
  148. /package/lib/types/views/range-selector/utils/{findIndexFromSequenceNodes.d.ts → find-index-from-sequence-nodes.d.ts} +0 -0
  149. /package/lib/types/views/range-selector/utils/{getOffsetFromSequenceNodes.d.ts → get-offset-from-sequence-nodes.d.ts} +0 -0
  150. /package/lib/types/views/range-selector/utils/{rangePreProcess.d.ts → range-pre-process.d.ts} +0 -0
  151. /package/lib/types/views/range-selector/utils/{sequenceNodeToText.d.ts → sequence-node-to-text.d.ts} +0 -0
  152. /package/lib/types/views/range-selector/utils/{unitRangesToText.d.ts → unit-ranges-to-text.d.ts} +0 -0
  153. /package/lib/types/views/range-selector/utils/{verifyRange.d.ts → verify-range.d.ts} +0 -0
package/lib/cjs/index.js CHANGED
@@ -1,25 +1,25 @@
1
- "use strict";var pn=Object.defineProperty;var Sn=(e,t,n)=>t in e?pn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ee=(e,t,n)=>Sn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),$=require("@univerjs/sheets-ui"),b=require("@univerjs/engine-formula"),q=require("rxjs"),te=require("@univerjs/docs-ui"),z=require("@univerjs/engine-render"),V=require("@univerjs/sheets"),xe=require("@univerjs/sheets-formula"),E=require("@univerjs/ui"),C=require("react/jsx-runtime"),pe=require("@univerjs/design"),Ct=require("@univerjs/docs"),u=require("react"),Ve=require("rxjs/operators"),nt={id:"sheet.command.paste-formula",type:c.CommandType.COMMAND,handler:async e=>e.get(c.ICommandService).executeCommand($.SheetPasteCommand.id,{value:$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Pe={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(e,t)=>!0};var vn=Object.defineProperty,Cn=Object.getOwnPropertyDescriptor,Rn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Cn(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&vn(t,n,r),r},In=(e,t)=>(n,o)=>t(n,o,e);const $t="FORMULA_PROMPT_ACTIVATED",ze=c.createIdentifier("formula-ui.prompt-service");let gt=class{constructor(e){ee(this,"_search$",new q.Subject);ee(this,"_help$",new q.Subject);ee(this,"_navigate$",new q.Subject);ee(this,"_accept$",new q.Subject);ee(this,"_acceptFormulaName$",new q.Subject);ee(this,"search$",this._search$.asObservable());ee(this,"help$",this._help$.asObservable());ee(this,"navigate$",this._navigate$.asObservable());ee(this,"accept$",this._accept$.asObservable());ee(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());ee(this,"_searching",!1);ee(this,"_helping",!1);ee(this,"_sequenceNodes",[]);ee(this,"_isLockedOnSelectionChangeRefString",!1);ee(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=e}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(e){this._contextService.setContextValue($t,e.visible),this._searching=e.visible,this._search$.next(e)}isSearching(){return this._searching}help(e){this._helping=e.visible,this._help$.next(e)}isHelping(){return this._helping}navigate(e){this._navigate$.next(e)}accept(e){this._accept$.next(e)}acceptFormulaName(e){this._acceptFormulaName$.next(e)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(e){this._sequenceNodes=e}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(e){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(e)]}getCurrentSequenceNodeByIndex(e){return this._sequenceNodes[e]}getCurrentSequenceNodeIndex(e){let t=0;const n=this._sequenceNodes[0];for(let o=0,r=this._sequenceNodes.length;o<r;o++){const i=this._sequenceNodes[o];if(typeof i=="string")t++;else{const{endIndex:s}=i;t=s}if(e<=t)return typeof n=="string"&&e!==0?o+1:o}return this._sequenceNodes.length}updateSequenceRef(e,t){const n=this._sequenceNodes[e];if(typeof n=="string"||n.nodeType!==b.sequenceNodeType.REFERENCE)return;const o=t.length-n.token.length,r={...n};r.token=t,r.endIndex+=o,this._sequenceNodes[e]=r;for(let i=e+1,s=this._sequenceNodes.length;i<s;i++){const a=this._sequenceNodes[i];if(typeof a=="string")continue;const f={...a};f.startIndex+=o,f.endIndex+=o,this._sequenceNodes[i]=f}}insertSequenceRef(e,t){const n=t.length,o=this.getCurrentSequenceNodeIndex(e);this._sequenceNodes.splice(o,0,{token:t,startIndex:e,endIndex:e+n-1,nodeType:b.sequenceNodeType.REFERENCE});for(let r=o+1,i=this._sequenceNodes.length;r<i;r++){const s=this._sequenceNodes[r];if(typeof s=="string")continue;const a={...s};a.startIndex+=n,a.endIndex+=n,this._sequenceNodes[r]=a}}insertSequenceString(e,t){const n=this.getCurrentSequenceNodeIndex(e),o=t.split("");this._sequenceNodes.splice(n,0,...o);const r=o.length;for(let i=n+r,s=this._sequenceNodes.length;i<s;i++){const a=this._sequenceNodes[i];if(typeof a=="string")continue;const f={...a};f.startIndex+=r,f.endIndex+=r,this._sequenceNodes[i]=f}}enableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!0}disableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!1}isLockedSelectionChange(){return this._isLockedOnSelectionChangeRefString}enableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!0}disableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!1}isLockedSelectionInsert(){return this._isLockedOnSelectionInsertRefString}};gt=Rn([In(0,c.IContextService)],gt);const jt={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(e,t)=>(e.get(ze).help(t),!0)},rt={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(e,t)=>{var _,x;const n=e.get(V.SheetsSelectionsService),o=e.get(te.IEditorService),r=n.getCurrentSelections();if(!r||!r.length)return!1;const i=V.getSheetCommandTarget(e.get(c.IUniverInstanceService));if(!i)return!1;const{worksheet:s,unitId:a,subUnitId:f}=i,d=s.getCellMatrix(),{value:h}=t,g=e.get(c.ICommandService),m=e.get($.IEditorBridgeService),v=[],l=[];let S=null,I=0,y=0,R="";if(r.length===1&&(yn(r[0].range)||Tn(r[0].range)&&Ot(d,r[0].range))){const{range:A,primary:O}=r[0],P=(_=O==null?void 0:O.actualRow)!=null?_:A.startRow,k=(x=O==null?void 0:O.actualColumn)!=null?x:A.startColumn;S=A,I=P,y=k;const L=xt(d,P,k);L&&(R=b.serializeRange(L))}else r.some(A=>{var k,L;const{range:O,primary:P}=A;if(Ot(d,O)){const N=(k=P==null?void 0:P.actualRow)!=null?k:O.startRow,F=(L=P==null?void 0:P.actualColumn)!=null?L:O.startColumn,w=xt(d,N,F);if(!w)return S=O,I=N,y=F,!0;const M=b.serializeRange(w),p=`=${h}(${M})`;v.push({range:O,primary:{row:N,column:F},formula:p})}else{const{startRow:N,startColumn:F,endRow:w,endColumn:M}=O;if(N===w){const p=bn(d,N,M,s.getColumnCount()-1),T=p===M?M-1:M,D=b.serializeRange({startRow:N,endRow:w,startColumn:F,endColumn:T}),j=`=${h}(${D})`;l.push({range:O,primary:{row:N,column:p},formula:j})}else{let p=-1;for(let D=F;D<=M;D++){const j=Mn(d,D,w,s.getRowCount()-1);p=Math.max(p,j)}const T=p===w?w-1:w;for(let D=F;D<=M;D++){const j=b.serializeRange({startRow:N,endRow:T,startColumn:D,endColumn:D}),U=`=${h}(${j})`;l.push({range:O,primary:{row:p,column:D},formula:U})}}}return!1});if(S){const A=V.getCellAtRowCol(I,y,s),O={range:c.Rectangle.clone(S),primary:{startRow:A.startRow,startColumn:A.startColumn,endRow:A.endRow,endColumn:A.endColumn,actualRow:I,actualColumn:y,isMerged:A.isMerged,isMergedMainCell:A.startRow===I&&A.startColumn===y}},P={unitId:a,subUnitId:f,selections:[O]};await g.executeCommand(V.SetSelectionsOperation.id,P);const k=o.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),L=o.getEditor(c.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);m.changeVisible({visible:!0,unitId:a,eventType:z.DeviceInputEventType.Dblclick});const N=`=${h}(${R}`;k==null||k.replaceText(N),L==null||L.replaceText(N,!1)}return v.length===0&&l.length===0?!1:g.executeCommand(xe.InsertFunctionCommand.id,{list:v,listOfRangeHasNumber:l})}};function xt(e,t,n){const o=En(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=_n(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function En(e,t,n){let o=!1;if(t===0)return t;for(let r=t-1;r>=0;r--){const i=e.getValue(r,n);if(qe(i)&&!o){if(r===0)return 0;o=!0}else{if(o&&!qe(i))return r+1;if(o&&r===0)return 0}}return t}function _n(e,t,n){let o=!1;if(n===0)return n;for(let r=n-1;r>=0;r--){const i=e.getValue(t,r);if(qe(i)&&!o){if(r===0)return 0;o=!0}else{if(o&&!qe(i))return r+1;if(o&&r===0)return 0}}return n}function qe(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return!1;const n=t.dataStream,r=n.substring(n.length-2,n.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n;return c.isRealNum(r)}return e&&(e.t===c.CellValueType.NUMBER||c.getCellValueType(e)===c.CellValueType.NUMBER)}function yn(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function Tn(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function Ot(e,t){for(let n=t.startRow;n<=t.endRow;n++)for(let o=t.startColumn;o<=t.endColumn;o++)if(qe(e.getValue(n,o)))return!1;return!0}function bn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function Mn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const Ht="SHEET_FORMULA_UI_PLUGIN",Ut=`${Ht}_MORE_FUNCTIONS_COMPONENT`,ot={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async e=>(e.get(E.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:Ut}}),!0)},Rt={id:"formula-ui.operation.change-ref-to-absolute",type:c.CommandType.OPERATION,handler:async e=>!0},Wt={id:"formula-ui.operation.search-function",type:c.CommandType.OPERATION,handler:async(e,t)=>(e.get(ze).search(t),!0)};var ve=function(){return ve=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},ve.apply(this,arguments)},Nn=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);return n},Oe=u.forwardRef(function(e,t){var n=e.icon,o=e.id,r=e.className,i=e.extend,s=Nn(e,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(o," ").concat(r||"").trim(),f=u.useRef("_".concat(On()));return Bt(n,"".concat(o),{defIds:n.defIds,idSuffix:f.current},ve({ref:t,className:a},s),i)});function Bt(e,t,n,o,r){return u.createElement(e.tag,ve(ve({key:t},Fn(e,n,r)),o),(xn(e,n).children||[]).map(function(i,s){return Bt(i,"".concat(t,"-").concat(e.tag,"-").concat(s),n,void 0,r)}))}function Fn(e,t,n){var o=ve({},e.attrs);n!=null&&n.colorChannel1&&o.fill==="colorChannel1"&&(o.fill=n.colorChannel1);var r=t.defIds;return!r||r.length===0||(e.tag==="use"&&o["xlink:href"]&&(o["xlink:href"]=o["xlink:href"]+t.idSuffix),Object.entries(o).forEach(function(i){var s=i[0],a=i[1];typeof a=="string"&&(o[s]=a.replace(/url\(#(.*)\)/,"url(#$1".concat(t.idSuffix,")")))})),o}function xn(e,t){var n,o=t.defIds;return!o||o.length===0?e:e.tag==="defs"&&(!((n=e.children)===null||n===void 0)&&n.length)?ve(ve({},e),{children:e.children.map(function(r){return typeof r.attrs.id=="string"&&o&&o.indexOf(r.attrs.id)>-1?ve(ve({},r),{attrs:ve(ve({},r.attrs),{id:r.attrs.id+t.idSuffix})}):r})}):e}function On(){return Math.random().toString(36).substring(2,8)}Oe.displayName="UniverIcon";var Dn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M14.1544 3.75557C14.3887 3.98988 14.3887 4.36978 14.1544 4.6041L6.51409 12.2444C6.40157 12.3569 6.24896 12.4201 6.08983 12.4201C5.9307 12.4201 5.77808 12.3569 5.66556 12.2444L1.84541 8.42425C1.6111 8.18993 1.6111 7.81003 1.84541 7.57572C2.07973 7.34141 2.45963 7.34141 2.69394 7.57572L6.08983 10.9716L13.3059 3.75557C13.5402 3.52126 13.9201 3.52126 14.1544 3.75557Z",fillRule:"evenodd",clipRule:"evenodd"}}]},Vt=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"check-mark-single",ref:t,icon:Dn}))});Vt.displayName="CheckMarkSingle";var An={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M3.71274 2.86421C3.47843 2.6299 3.09853 2.6299 2.86421 2.86421C2.6299 3.09853 2.6299 3.47843 2.86421 3.71274L7.15154 8.00007L2.86421 12.2874C2.6299 12.5217 2.6299 12.9016 2.86421 13.1359C3.09853 13.3702 3.47843 13.3702 3.71274 13.1359L8.00007 8.84859L12.2874 13.1359C12.5217 13.3702 12.9016 13.3702 13.1359 13.1359C13.3702 12.9016 13.3702 12.5217 13.1359 12.2874L8.84859 8.00007L13.1359 3.71274C13.3702 3.47843 13.3702 3.09853 13.1359 2.86421C12.9016 2.6299 12.5217 2.6299 12.2874 2.86421L8.00007 7.15154L3.71274 2.86421Z"}}]},st=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"close-single",ref:t,icon:An}))});st.displayName="CloseSingle";var Pn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M5.3313 1.4667C5.3313 1.13533 5.59993.866699 5.9313.866699H10.069C10.4004.866699 10.669 1.13533 10.669 1.4667 10.669 1.79807 10.4004 2.0667 10.069 2.0667H5.9313C5.59993 2.0667 5.3313 1.79807 5.3313 1.4667zM1.09985 3.64443C1.09985 3.31306 1.36848 3.04443 1.69985 3.04443H14.2999C14.6312 3.04443 14.8999 3.31306 14.8999 3.64443 14.8999 3.9758 14.6312 4.24443 14.2999 4.24443H1.69985C1.36848 4.24443 1.09985 3.9758 1.09985 3.64443zM6.12398 8.30171C6.35829 8.0674 6.73819 8.0674 6.97251 8.30171L8.00007 9.32928 9.02764 8.30171C9.26195 8.0674 9.64185 8.0674 9.87617 8.30171 10.1105 8.53603 10.1105 8.91593 9.87617 9.15024L8.8486 10.1778 9.87617 11.2054C10.1105 11.4397 10.1105 11.8196 9.87617 12.0539 9.64185 12.2882 9.26195 12.2882 9.02764 12.0539L8.00007 11.0263 6.97251 12.0539C6.73819 12.2882 6.35829 12.2882 6.12398 12.0539 5.88966 11.8196 5.88966 11.4397 6.12398 11.2054L7.15154 10.1778 6.12398 9.15024C5.88966 8.91593 5.88966 8.53603 6.12398 8.30171z"}},{tag:"path",attrs:{fill:"currentColor",d:"M4.75332 5.22217C3.86966 5.22217 3.15332 5.93851 3.15332 6.82217V12.5331C3.15332 13.9691 4.31738 15.1332 5.75332 15.1332H10.2465C11.6825 15.1332 12.8465 13.9691 12.8465 12.5331V6.82217C12.8465 5.93851 12.1302 5.22217 11.2465 5.22217H4.75332ZM4.35332 6.82217C4.35332 6.60125 4.53241 6.42217 4.75332 6.42217H11.2465C11.4674 6.42217 11.6465 6.60125 11.6465 6.82217V12.5331C11.6465 13.3063 11.0197 13.9332 10.2465 13.9332H5.75332C4.98012 13.9332 4.35332 13.3063 4.35332 12.5331V6.82217Z",fillRule:"evenodd",clipRule:"evenodd"}}]},Kt=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"delete-single",ref:t,icon:Pn}))});Kt.displayName="DeleteSingle";var Ln={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M8.75 5.32495C8.75 5.73916 8.41421 6.07495 8 6.07495 7.58579 6.07495 7.25 5.73916 7.25 5.32495 7.25 4.91074 7.58579 4.57495 8 4.57495 8.41421 4.57495 8.75 4.91074 8.75 5.32495zM8.5999 7.52505C8.5999 7.19368 8.33127 6.92505 7.9999 6.92505 7.66853 6.92505 7.3999 7.19368 7.3999 7.52505V11.425C7.3999 11.7564 7.66853 12.025 7.9999 12.025 8.33127 12.025 8.5999 11.7564 8.5999 11.425V7.52505z"}},{tag:"path",attrs:{fill:"currentColor",d:"M0.899902 8.00002C0.899902 4.0788 4.07868 0.900024 7.9999 0.900024C11.9211 0.900024 15.0999 4.0788 15.0999 8.00002C15.0999 11.9212 11.9211 15.1 7.9999 15.1C4.07868 15.1 0.899902 11.9212 0.899902 8.00002ZM7.9999 2.10002C4.74142 2.10002 2.0999 4.74154 2.0999 8.00002C2.0999 11.2585 4.74142 13.9 7.9999 13.9C11.2584 13.9 13.8999 11.2585 13.8999 8.00002C13.8999 4.74154 11.2584 2.10002 7.9999 2.10002Z",fillRule:"evenodd",clipRule:"evenodd"}}]},qt=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"details-single",ref:t,icon:Ln}))});qt.displayName="DetailsSingle";var wn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M8.6 1.99991C8.60001 1.66854 8.33138 1.39991 8.00001 1.3999C7.66864 1.3999 7.40001 1.66853 7.4 1.9999L7.39996 7.3999H1.9999C1.66853 7.3999 1.3999 7.66853 1.3999 7.9999C1.3999 8.33127 1.66853 8.5999 1.9999 8.5999H7.39995L7.3999 13.9999C7.3999 14.3313 7.66853 14.5999 7.9999 14.5999C8.33127 14.5999 8.5999 14.3313 8.5999 13.9999L8.59995 8.5999H13.9999C14.3313 8.5999 14.5999 8.33127 14.5999 7.9999C14.5999 7.66853 14.3313 7.3999 13.9999 7.3999H8.59996L8.6 1.99991Z"}}]},Yt=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"increase-single",ref:t,icon:wn}))});Yt.displayName="IncreaseSingle";var kn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M5.90913 3.57564C6.14345 3.34132 6.52335 3.34132 6.75766 3.57564L10.7577 7.57564C10.992 7.80995 10.992 8.18985 10.7577 8.42417L6.75766 12.4242C6.52335 12.6585 6.14345 12.6585 5.90913 12.4242C5.67482 12.1899 5.67482 11.81 5.90913 11.5756L9.48487 7.9999L5.90913 4.42417C5.67482 4.18985 5.67482 3.80995 5.90913 3.57564Z",fillRule:"evenodd",clipRule:"evenodd"}}]},It=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"more-single",ref:t,icon:kn}))});It.displayName="MoreSingle";var $n={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M12.6185 12.4423C12.5907 12.2749 12.7773 12.15 12.9343 12.2308L15.4242 13.5126C15.6102 13.6084 15.5544 13.8745 15.3439 13.8955L14.2456 14.184L13.4521 15.1286C13.3495 15.2939 13.085 15.2463 13.0534 15.0568L12.6185 12.4423Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M1 3.6C1 2.16406 2.16406 1 3.6 1H12.3C13.7359 1 14.9 2.16406 14.9 3.6V5.81156C14.9003 5.81881 14.9004 5.82609 14.9004 5.8334C14.9004 5.84071 14.9003 5.84799 14.9 5.85524V10.045C14.9003 10.0522 14.9004 10.0595 14.9004 10.0668C14.9004 10.3982 14.6318 10.6668 14.3004 10.6668H11.1668C10.8907 10.6668 10.6668 10.8907 10.6668 11.1668V14.3C10.6668 14.6314 10.3982 14.9 10.0668 14.9L10.05 14.8998L3.6 14.9C2.16406 14.9 1 13.7359 1 12.3V3.6ZM13.2 5.2334C13.4761 5.2334 13.7 5.00954 13.7 4.7334V3.6C13.7 2.8268 13.0732 2.2 12.3 2.2H11.1668C10.8907 2.2 10.6668 2.42386 10.6668 2.7V4.7334C10.6668 5.00954 10.8907 5.2334 11.1668 5.2334H13.2ZM10.6668 6.9334C10.6668 6.65726 10.8907 6.4334 11.1668 6.4334H13.2C13.4761 6.4334 13.7 6.65726 13.7 6.9334V8.9668C13.7 9.24294 13.4761 9.4668 13.2 9.4668H11.1668C10.8907 9.4668 10.6668 9.24294 10.6668 8.9668V6.9334ZM8.9668 5.2334C9.24294 5.2334 9.4668 5.00954 9.4668 4.7334V2.7C9.4668 2.42386 9.24294 2.2 8.9668 2.2H6.9334C6.65726 2.2 6.4334 2.42386 6.4334 2.7V4.7334C6.4334 5.00954 6.65726 5.2334 6.9334 5.2334L8.9668 5.2334ZM6.4334 6.9334C6.4334 6.65726 6.65726 6.4334 6.9334 6.4334L8.9668 6.4334C9.24294 6.4334 9.4668 6.65726 9.4668 6.9334V8.9668C9.4668 9.24294 9.24294 9.4668 8.9668 9.4668L6.9334 9.4668C6.65726 9.4668 6.4334 9.24294 6.4334 8.9668V6.9334ZM4.7334 5.2334C5.00954 5.2334 5.2334 5.00954 5.2334 4.7334V2.7C5.2334 2.42386 5.00954 2.2 4.7334 2.2H3.6C2.8268 2.2 2.2 2.8268 2.2 3.6V4.7334C2.2 5.00954 2.42386 5.2334 2.7 5.2334H4.7334ZM2.2 6.9334C2.2 6.65726 2.42386 6.4334 2.7 6.4334H4.7334C5.00954 6.4334 5.2334 6.65725 5.2334 6.9334V8.9668C5.2334 9.24294 5.00954 9.4668 4.7334 9.4668H2.7C2.42386 9.4668 2.2 9.24294 2.2 8.9668V6.9334ZM5.2334 11.1668C5.2334 10.8907 5.00954 10.6668 4.7334 10.6668H2.7C2.42386 10.6668 2.2 10.8907 2.2 11.1668V12.3C2.2 13.0732 2.8268 13.7 3.6 13.7H4.7334C5.00954 13.7 5.2334 13.4761 5.2334 13.2V11.1668ZM9.4668 11.1668C9.4668 10.8907 9.24294 10.6668 8.9668 10.6668H6.9334C6.65726 10.6668 6.4334 10.8907 6.4334 11.1668V13.2C6.4334 13.4761 6.65726 13.7 6.9334 13.7H8.9668C9.24294 13.7 9.4668 13.4761 9.4668 13.2V11.1668Z",fillRule:"evenodd",clipRule:"evenodd"}}]},zt=u.forwardRef(function(e,t){return u.createElement(Oe,Object.assign({},e,{id:"select-range-single",ref:t,icon:$n}))});zt.displayName="SelectRangeSingle";function Gt(e){var t,n,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(t=0;t<r;t++)e[t]&&(n=Gt(e[t]))&&(o&&(o+=" "),o+=n)}else for(n in e)e[n]&&(o&&(o+=" "),o+=n);return o}function pt(){for(var e,t,n=0,o="",r=arguments.length;n<r;n++)(e=arguments[n])&&(t=Gt(e))&&(o&&(o+=" "),o+=t);return o}var jn=Object.defineProperty,Hn=Object.getOwnPropertyDescriptor,Un=(e,t,n,o)=>{for(var r=o>1?void 0:o?Hn(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&jn(t,n,r),r},$e=(e,t)=>(n,o)=>t(n,o,e);exports.RefSelectionsRenderService=class extends $.BaseSelectionRenderService{constructor(n,o,r,i,s,a,f){super(o,r,i,s,a);ee(this,"_workbookSelections");ee(this,"_eventDisposables");this._context=n,this._contextService=a,this._refSelectionsService=f,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Wn(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(n){this._remainLastEnabled=n}setSkipLastEnabled(n){this._skipLastEnabled=n}clearLastSelection(){const n=this._selectionControls[this._selectionControls.length-1];n&&(n.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),c.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var n;(n=this._eventDisposables)==null||n.dispose(),this._eventDisposables=null}disableSelectionChanging(){this._disableSelectionChanging()}_initCanvasEventListeners(){const n=this._getSheetObject(),{spreadsheetRowHeader:o,spreadsheetColumnHeader:r,spreadsheet:i,spreadsheetLeftTopPlaceholder:s}=n,{scene:a}=this._context,f=new c.DisposableCollection;return f.add(i==null?void 0:i.onPointerDown$.subscribeEvent((d,h)=>{this.inRefSelectionMode()&&(this._onPointerDown(d,i.zIndex+1,c.RANGE_TYPE.NORMAL,this._getActiveViewport(d)),d.button!==2&&h.stopPropagation())})),f.add(o==null?void 0:o.onPointerDown$.subscribeEvent((d,h)=>{if(!this.inRefSelectionMode())return;const g=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:m}=$.getCoordByOffset(d.offsetX,d.offsetY,a,g);$.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),m,c.RANGE_TYPE.ROW)||(this._onPointerDown(d,(i.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(d),z.ScrollTimerType.Y),d.button!==2&&h.stopPropagation())})),f.add(r==null?void 0:r.onPointerDown$.subscribeEvent((d,h)=>{if(!this.inRefSelectionMode())return;const g=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:m}=$.getCoordByOffset(d.offsetX,d.offsetY,a,g);$.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),m,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(d,(i.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(d),z.ScrollTimerType.X),d.button!==2&&h.stopPropagation())})),f.add(s==null?void 0:s.onPointerDown$.subscribeEvent((d,h)=>{if(this._reset(),!this.inRefSelectionMode())return;const g=this._sheetSkeletonManagerService.getCurrent().skeleton,m=$.getAllSelection(g);this._addSelectionControlByModelData(m),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const v=a.onPointerUp$.subscribeEvent(()=>{v.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});d.button!==2&&h.stopPropagation()})),f}_addSelectionControlByModelData(n){var a;const o=this._skeleton,r=(a=n.style)!=null?a:$.genNormalSelectionStyle(this._themeService),i=this._scene;return n.style=r,this.newSelectionControl(i,o,n)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(n=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(n||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(n=>{this._updateSelections(n,V.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(n=>{this._updateSelections(n,V.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(n=>{this._updateSelections(n,V.SelectionMoveType.MOVE_END)}))}_updateSelections(n,o){const i=this._context.unit.getActiveSheet().getSheetId();n.length!==0&&this._workbookSelections.setSelections(i,n.map(s=>V.convertSelectionDataToRange(s)),o)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(n=>{if(!n)return;const{skeleton:o}=n,{scene:r}=this._context,i=r.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&this._skeleton.worksheet.getSheetId()!==o.worksheet.getSheetId()&&this._reset(),this._changeRuntime(o,r,i);const s=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(s)}))}_getActiveViewport(n){const o=this._getSheetObject();return o==null?void 0:o.scene.getActiveViewportByCoord(z.Vector2.FromArray([n.offsetX,n.offsetY]))}_getSheetObject(){return $.getSheetObject(this._context.unit,this._context)}_onPointerDown(n,o=0,r=c.RANGE_TYPE.NORMAL,i,s=z.ScrollTimerType.ALL){var F;this._rangeType=r;const a=this._skeleton,f=this._scene;if(!f||!a)return;i&&(this._activeViewport=i);const{offsetX:d,offsetY:h}=n,g=f.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!g)return;const m=f.getCoordRelativeToViewport(z.Vector2.FromArray([d,h])),{x:v,y:l}=m;this._startViewportPosX=v,this._startViewportPosY=l;const S=f.getScrollXYInfoByViewport(m),{scaleX:I,scaleY:y}=f.getAncestorScale(),R=this._skeleton.getCellByOffset(v,l,I,y,S);if(!R)return;switch(r){case c.RANGE_TYPE.NORMAL:break;case c.RANGE_TYPE.ROW:R.startColumn=0,R.endColumn=this._skeleton.getColumnCount()-1;break;case c.RANGE_TYPE.COLUMN:R.startRow=0,R.endRow=this._skeleton.getRowCount()-1;break;case c.RANGE_TYPE.ALL:R.startRow=0,R.startColumn=0,R.endRow=this._skeleton.getRowCount()-1,R.endColumn=this._skeleton.getColumnCount()-1}const _={range:R,primary:R,style:null};_.range.rangeType=r;const x=$.attachSelectionWithCoord(_,this._skeleton);this._startRangeWhenPointerDown={...x.rangeWithCoord};const A={...x.rangeWithCoord,rangeType:r};let O=this.getActiveSelectionControl();const P=this.getSelectionControls();for(const w of P){if(n.button===2&&w.model.isInclude(A)){O=w;return}if(w.model.isEqual(A)){O=w;break}}this._checkClearPreviousControls(n);const k=O==null?void 0:O.model.currentCell,L=n.shiftKey&&k,N=this._remainLastEnabled&&!n.ctrlKey&&!n.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;L&&k?this._makeSelectionByTwoCells(k,A,a,r,O):N&&O?O.updateRangeBySelectionWithCoord(x):O=this.newSelectionControl(f,a,_);for(let w=0;w<this.getSelectionControls().length-1;w++)this.getSelectionControls()[w].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),f.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(F=f.getTransformer())==null||F.clearSelectedObjects(),this._setupPointerMoveListener(g,O,r,s,v,l),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=f.onPointerUp$.subscribeEvent(()=>{var w;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(w=this._escapeShortcutDisposable)==null||w.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(n,o,r){const i=this.getSelectionControls().length,{rowHeaderWidth:s,columnHeaderHeight:a}=o,f=new $.SelectionControl(n,i,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:s,columnHeaderHeight:a}),d=$.attachSelectionWithCoord(r,o);return f.updateRangeBySelectionWithCoord(d),this._selectionControls.push(f),f.setControlExtension({skeleton:o,scene:n,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),f}};exports.RefSelectionsRenderService=Un([$e(1,c.Inject(c.Injector)),$e(2,c.Inject(c.ThemeService)),$e(3,E.IShortcutService),$e(4,c.Inject($.SheetSkeletonManagerService)),$e(5,c.IContextService),$e(6,V.IRefSelectionsService)],exports.RefSelectionsRenderService);function Wn(e){const t=$.genNormalSelectionStyle(e);return t.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},t}const Bn=(e,t,n)=>{const r=c.useDependency(z.IRenderManagerService).getRenderById(e),i=r==null?void 0:r.with(exports.RefSelectionsRenderService);u.useEffect(()=>{if(n&&i){const s=n.input$.subscribe(a=>{a.content===b.matchToken.COMMA?i.setSkipLastEnabled(!0):i.setSkipLastEnabled(!1)});return()=>{s.unsubscribe()}}},[n,i]),u.useEffect(()=>{i&&(t.endsWith(b.matchToken.COMMA)||i.setSkipLastEnabled(!1))},[t,i])},it=()=>{const e=c.useDependency(b.LexerTreeBuilder);return u.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])},Vn=(e,t,n,o,r,i)=>{const s=it(),a=u.useRef(!0);u.useEffect(()=>{var f,d;if(i){if(a.current){const h=s(e);if(h.length){const g=o(i,h);n&&r(g)}else{const g=i.getDocumentData(),v={dataStream:(d=(f=g.body)==null?void 0:f.dataStream)!=null?d:`${t}\r
2
- `,...g.body};i.setDocumentData({...g,body:v})}a.current=!1}else if(n){const h=s(e),g=o(i,h);r(g)}}},[i,n])},Zt=e=>{const t=c.useDependency(te.IEditorService);return E.useEvent(o=>{var r,i;if(e){t.focus(e.getEditorId());const s=[...e.getSelectionRanges()];if(c.Tools.isDefine(o))e.setSelectionRanges([{startOffset:o,endOffset:o}]);else if(!s.length&&!e.docSelectionRenderService.isOnPointerEvent){const a=(i=(r=e.getDocumentData().body)==null?void 0:r.dataStream)!=null?i:`\r
3
- `,f=Math.max(a.length-2,0);e.setSelectionRanges([{startOffset:f,endOffset:f}])}}})};function Kn(e,t,n){const o=e.getCurrentTheme(),r=new c.ColorKit(t).setAlpha(.05).toRgbString();return{id:n,strokeWidth:1,stroke:t,fill:r,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:o.colorWhite}}function Xt(e){var y,R,_;const{unitId:t,subUnitId:n,refSelections:o,editor:r,refSelectionsService:i,refSelectionsRenderService:s,sheetSkeletonManagerService:a,themeService:f,univerInstanceService:d}=e,h=d.getUnit(t,c.UniverInstanceType.UNIVER_SHEET),g=h==null?void 0:h.getActiveSheet(),m=[];if(!h||!g){i.setSelections(m);return}const v=g.getSheetId(),l=x=>{var A;return(A=h==null?void 0:h.getSheetBySheetName(x))==null?void 0:A.getSheetId()};if(!((y=a==null?void 0:a.getWorksheetSkeleton(v))==null?void 0:y.skeleton))return;const I=[];for(let x=0,A=o.length;x<A;x++){const O=o[x],{themeColor:P,token:k,refIndex:L,endIndex:N}=O,F=b.deserializeRangeWithSheet(k),{unitId:w,sheetName:M,range:p}=F;if(w&&t!==w)continue;const T=l(M);if(T&&T!==v||!T&&v!==n)continue;const D=V.setEndForRange(p,g.getRowCount(),g.getColumnCount());m.push({range:D,primary:null,style:Kn(f,P,L.toString())}),I.push(N)}if(r){const x=(_=(R=r.getSelectionRanges())==null?void 0:R[0])==null?void 0:_.startOffset,A=I.findIndex(O=>O+2===x);A!==-1?s==null||s.setActiveSelectionIndex(A):s==null||s.resetActiveSelectionIndex()}return m}function Et(e,t){const n=c.useDependency(c.IUniverInstanceService),o=c.useDependency(c.ThemeService),r=c.useDependency(V.IRefSelectionsService),s=c.useDependency(z.IRenderManagerService).getRenderById(e),a=s==null?void 0:s.with(exports.RefSelectionsRenderService),f=s==null?void 0:s.with($.SheetSkeletonManagerService),d=u.useCallback((h,g)=>{const m=Xt({unitId:e,subUnitId:t,refSelections:h,editor:g,refSelectionsService:r,refSelectionsRenderService:a,sheetSkeletonManagerService:f,themeService:o,univerInstanceService:n});if(!m)return;((a==null?void 0:a.getSelectionControls())||[]).length===m.length?a==null||a.resetSelectionsByModelData(m):r.setSelections(m)},[a,r,f,o,e,t,n]);return u.useEffect(()=>()=>{a==null||a.resetActiveSelectionIndex()},[a]),d}function Jt(e=""){const t=c.useDependency(xe.IDescriptionService),n=Qt(),o=c.useDependency(c.ICommandService),r=u.useMemo(()=>e.length,[e]);return u.useCallback((s,a,f=!0,d)=>{const h=s.getDocumentData(),g=s.getEditorId();if(!h)return[];const m=h.body;if(!m)return[];const v=m.dataStream.slice(0,m.dataStream.length-2),l={dataStream:"",...h.body};if(!v.startsWith(e))return[];if(a==null||a.length===0)return l.textRuns=[],o.syncExecuteCommand(te.ReplaceTextRunsCommand.id,{unitId:g,body:c.getBodySlice(l,0,l.dataStream.length-2)}),[];{const{textRuns:S,refSelections:I}=en(t,n,a);r&&S.forEach(_=>{_.ed=_.ed+r,_.st=_.st+r}),l.textRuns=[{st:0,ed:1,ts:{fs:11}},...S];const y=a.reduce((_,x)=>typeof x=="string"?`${_}${x}`:`${_}${x.token}`,"");l.dataStream=`${e}${y}\r
4
- `;let R;if(f){R=s.getSelectionRanges();const _=l.dataStream.length-2+r;R.forEach(x=>{x.startOffset=Math.max(0,Math.min(x.startOffset,_)),x.endOffset=Math.max(0,Math.min(x.endOffset,_))})}return o.syncExecuteCommand(te.ReplaceTextRunsCommand.id,{unitId:g,body:c.getBodySlice(l,0,l.dataStream.length-2),textRanges:d!=null?d:R}),I}},[o,t,n,r,e])}function Qt(){const t=c.useDependency(c.ThemeService).getCurrentTheme();return u.useMemo(()=>{const o=[t.loopColor1,t.loopColor2,t.loopColor3,t.loopColor4,t.loopColor5,t.loopColor6,t.loopColor7,t.loopColor8,t.loopColor9,t.loopColor10,t.loopColor11,t.loopColor12],r=t.hyacinth700,i=t.verdancy800,s=t.colorBlack;return{formulaRefColors:o,numberColor:r,stringColor:i,plainTextColor:s}},[t])}function en(e,t,n){const{formulaRefColors:o,numberColor:r,stringColor:i,plainTextColor:s}=t,a=[],f=[],d=new Map;let h=0;for(let g=0,m=n.length;g<m;g++){const v=n[g];if(typeof v=="string"){const _=a[a.length-1],x=_?_.ed:0,A=x+v.length;a.push({st:x,ed:A,ts:{cl:{rgb:s},fs:11}});continue}if(e.hasDefinedNameDescription(v.token.trim())){a.push({st:v.startIndex,ed:v.endIndex+1,ts:{cl:{rgb:s},fs:11}});continue}const{startIndex:l,endIndex:S,nodeType:I,token:y}=v;let R="";if(I===b.sequenceNodeType.REFERENCE){if(d.has(y))R=d.get(y);else{const _=h%o.length;R=o[_],d.set(y,R),h++}f.push({refIndex:g,themeColor:R,token:y,startIndex:v.startIndex,endIndex:v.endIndex,index:f.length})}else I===b.sequenceNodeType.NUMBER?R=r:(I===b.sequenceNodeType.STRING||I===b.sequenceNodeType.ARRAY)&&(R=i);R&&R.length>0?a.push({st:l,ed:S+1,ts:{cl:{rgb:R},fs:11}}):a.push({st:l,ed:S+1,ts:{cl:{rgb:s},fs:11}})}return{textRuns:a,refSelections:f}}function qn(e){var r,i;const n=e.get(c.IUniverInstanceService).getCurrentUniverDocInstance();return n!=null&&n.getBody()?{dataStream:(i=(r=n.getBody())==null?void 0:r.dataStream)!=null?i:"",offset:0}:void 0}var Ze=(e=>(e[e.NOT_SELECT=0]="NOT_SELECT",e[e.NEED_ADD=1]="NEED_ADD",e[e.CAN_EDIT=2]="CAN_EDIT",e))(Ze||{});function Yn(e,t,n){var v;const r=c.useDependency(z.IRenderManagerService).getRenderById(e),i=r==null?void 0:r.with(te.DocSelectionRenderService),s=c.useDependency(Ct.DocSelectionManagerService),a=c.useDependency(c.Injector),[f,d]=u.useState(0),h=c.useDependency(b.LexerTreeBuilder),g=u.useRef(!0),m=u.useRef(f);return m.current=f,u.useEffect(()=>{const l=s.textSelection$.pipe(q.filter(S=>S.unitId===e),q.map(()=>{const S=i==null?void 0:i.getActiveTextRange();return S!=null&&S.collapsed?S.startOffset:-1})).subscribe(S=>{var k,L;const I=qn(a);if(!I)return;const y=(k=I==null?void 0:I.dataStream)==null?void 0:k.slice(0,-2),R=(L=h.sequenceNodesBuilder(y))!=null?L:[],_=y[S-1],x=y[S],A=R.findIndex(N=>typeof N=="object"&&N.nodeType===b.sequenceNodeType.REFERENCE&&S===N.endIndex+2),O=_&&b.matchRefDrawToken(_)&&(!x||b.isFormulaLexerToken(x)&&x!==b.matchToken.OPEN_BRACKET),P=A>-1;if((y==null?void 0:y.substring(0,1))==="="&&(O||P))if(P){if(g.current)return;d(2)}else g.current=!1,d(1);else d(0)});return()=>l.unsubscribe()},[s.textSelection$,i,e,a,h]),u.useEffect(()=>{t||(d(0),g.current=!0)},[t]),u.useEffect(()=>{var S;if(!n)return;const l=(S=r==null?void 0:r.mainComponent)==null?void 0:S.onPointerDown$.subscribeEvent(()=>{d(0),g.current=!0});return()=>l==null?void 0:l.unsubscribe()},[n,(v=r==null?void 0:r.mainComponent)==null?void 0:v.onPointerDown$]),{isSelecting:f}}const tn=(e,t,n,o)=>{const r=c.useDependency(c.ICommandService),i=c.useDependency(E.IShortcutService),s=u.useRef(t);s.current=t;const a=u.useRef(o);a.current=o,u.useEffect(()=>{if(!n||!e)return;const d=`sheet.formula-embedding-editor.${n.getEditorId()}`,h=new c.DisposableCollection,g=(l,S)=>{if(a.current){a.current(l,S);return}let I=c.Direction.LEFT;l===E.KeyCode.ARROW_DOWN?I=c.Direction.DOWN:l===E.KeyCode.ARROW_UP?I=c.Direction.UP:l===E.KeyCode.ARROW_RIGHT&&(I=c.Direction.RIGHT),S===E.MetaKeys.SHIFT?r.executeCommand(te.MoveSelectionOperation.id,{direction:I}):r.executeCommand(te.MoveCursorOperation.id,{direction:I})},m=(l,S)=>{let I=c.Direction.DOWN;l===E.KeyCode.ARROW_DOWN?I=c.Direction.DOWN:l===E.KeyCode.ARROW_UP?I=c.Direction.UP:l===E.KeyCode.ARROW_LEFT?I=c.Direction.LEFT:l===E.KeyCode.ARROW_RIGHT&&(I=c.Direction.RIGHT),s.current?S===E.MetaKeys.CTRL_COMMAND?r.executeCommand($.MoveSelectionCommand.id,{direction:I,jumpOver:$.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:s.current===Ze.NEED_ADD}):S===E.MetaKeys.SHIFT?r.executeCommand($.ExpandSelectionCommand.id,{direction:I,extra:"formula-editor"}):S===(E.MetaKeys.CTRL_COMMAND|E.MetaKeys.SHIFT)?r.executeCommand($.ExpandSelectionCommand.id,{direction:I,jumpOver:$.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand($.MoveSelectionCommand.id,{direction:I,extra:"formula-editor",fromCurrentSelection:s.current===Ze.NEED_ADD}):g(l,S)};return h.add(r.registerCommand({id:d,type:c.CommandType.OPERATION,handler(l,S){const{keyCode:I,metaKey:y}=S;m(I,y)}})),[{keyCode:E.KeyCode.ARROW_DOWN},{keyCode:E.KeyCode.ARROW_LEFT},{keyCode:E.KeyCode.ARROW_RIGHT},{keyCode:E.KeyCode.ARROW_UP},{keyCode:E.KeyCode.ARROW_DOWN,metaKey:E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_LEFT,metaKey:E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_RIGHT,metaKey:E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_UP,metaKey:E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_DOWN,metaKey:E.MetaKeys.CTRL_COMMAND},{keyCode:E.KeyCode.ARROW_LEFT,metaKey:E.MetaKeys.CTRL_COMMAND},{keyCode:E.KeyCode.ARROW_RIGHT,metaKey:E.MetaKeys.CTRL_COMMAND},{keyCode:E.KeyCode.ARROW_UP,metaKey:E.MetaKeys.CTRL_COMMAND},{keyCode:E.KeyCode.ARROW_DOWN,metaKey:E.MetaKeys.CTRL_COMMAND|E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_LEFT,metaKey:E.MetaKeys.CTRL_COMMAND|E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_RIGHT,metaKey:E.MetaKeys.CTRL_COMMAND|E.MetaKeys.SHIFT},{keyCode:E.KeyCode.ARROW_UP,metaKey:E.MetaKeys.CTRL_COMMAND|E.MetaKeys.SHIFT}].map(({keyCode:l,metaKey:S})=>({id:d,binding:S?l|S:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:l,metaKey:S}})).forEach(l=>{h.add(i.registerShortcut(l))}),()=>{h.dispose()}},[r,n,e,i])},nn=(e,t)=>{const o=c.useDependency(z.IRenderManagerService).getRenderById(e),r=o==null?void 0:o.with(exports.RefSelectionsRenderService);u.useEffect(()=>{r&&(t?r==null||r.setRemainLastEnabled(!1):r==null||r.setRemainLastEnabled(!0))},[t,r])},_t=(e,t,n,o=!0)=>{const r=c.useDependency(z.IRenderManagerService),i=c.useDependency(c.IContextService),s=c.useDependency(E.IContextMenuService),a=c.useDependency(V.IRefSelectionsService),f=r.getRenderById(n),d=f==null?void 0:f.with(exports.RefSelectionsRenderService);u.useLayoutEffect(()=>{if(e)return i.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{i.setContextValue(c.EDITOR_ACTIVATED,!1),a.clear()}},[i,e,a]),u.useLayoutEffect(()=>{if(e&&t){const h=d==null?void 0:d.enableSelectionChanging();return i.setContextValue(V.REF_SELECTIONS_ENABLED,!0),()=>{i.setContextValue(V.REF_SELECTIONS_ENABLED,!1),h==null||h.dispose()}}},[i,e,d,t]),u.useEffect(()=>{if(e)return i.setContextValue(c.EDITOR_ACTIVATED,!0),o&&s.disable(),()=>{i.setContextValue(c.EDITOR_ACTIVATED,!1),o&&s.enable()}},[s,i,e,o]),u.useEffect(()=>{e&&(d==null||d.setSkipLastEnabled(!1))},[e,d])},zn=()=>{u.useEffect(()=>()=>{},[])},rn=(e,t,n)=>{const o=c.useDependency(c.IUniverInstanceService),r=c.useDependency(V.SheetsSelectionsService);return u.useCallback(()=>{if(e){const s=[...r.getWorkbookSelections(t).getSelectionsOfWorksheet(n)],a=o.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),f=a==null?void 0:a.getActiveSheet();f&&f.getSheetId()===n&&r.setSelections(s)}},[e,r,n,t,o])},St=e=>typeof e=="string"?e===b.matchToken.COMMA:!1,Gn=e=>{if(typeof e=="object")return e.nodeType===b.sequenceNodeType.REFERENCE},Zn=e=>e.filter(t=>St(t)||Gn(t)),yt=e=>{if(e.endColumn<e.startColumn){const t=e.endColumn;e.endColumn=e.startColumn,e.startColumn=t}if(e.endRow<e.startRow){const t=e.endRow;e.endRow=e.startRow,e.startRow=t}return e},Ee=e=>e.map(t=>typeof t=="string"?t:t.token).join("");function Dt(e,t,n){var o,r;return((r=(o=e.getUnit(t))==null?void 0:o.getSheetBySheetId(n))==null?void 0:r.getName())||""}const Re=(e,t=!1,n="")=>t?e.map(o=>o.sheetName!==""&&o.sheetName!==n?b.serializeRangeWithSheet(o.sheetName,o.range):b.serializeRange(o.range)):e.map(o=>b.serializeRange(o.range)),on=(e,t,n,o,r,i,s)=>{const a=c.useDependency(z.IRenderManagerService),f=c.useDependency(c.IUniverInstanceService),d=u.useRef(!1),h=a.getRenderById(t),g=h==null?void 0:h.with(exports.RefSelectionsRenderService),m=u.useRef([]),v=u.useMemo(()=>{const S=Zn(o),I=m.current;return S.length===I.length?(I.splice(0),I.push(...S),I):S},[o]);m.current=v;const l=u.useRef(void 0);u.useEffect(()=>{if(e&&g){let S=!0;const I=(_,x)=>{var M;if(S||d.current){S=!1;return}const A=[..._],O=f.getUnit(t),P=((M=O==null?void 0:O.getActiveSheet())==null?void 0:M.getName())||"",k=v.map((p,T)=>{if(typeof p=="string"){if(!v[T-1])return null;const j=v[T+1];return St(p)&&(St(j)||T===v.length-1)?null:p}else if(p.nodeType===b.sequenceNodeType.REFERENCE){const D=b.deserializeRangeWithSheet(p.token);D.unitId=D.unitId===""?t:D.unitId,D.sheetName=D.sheetName===""?P:D.sheetName;const{unitId:j,sheetName:U}=D;if(i&&(j!==t||P!==U))return null;if(j===t&&P===U){const G=A.shift();if(G&&Dt(f,t,G.rangeWithCoord.sheetId||"")===U){const Y={...p};return yt(G.rangeWithCoord),r?Y.token=b.serializeRangeWithSheet(P,G.rangeWithCoord):Y.token=b.serializeRange(G.rangeWithCoord),Y}}return p}return null}).filter(p=>!!p),L=Re(A.map(p=>{var T,D,j;return{range:p.rangeWithCoord,unitId:(T=p.rangeWithCoord.unitId)!=null?T:"",sheetName:Dt(f,(D=p.rangeWithCoord.unitId)!=null?D:"",(j=p.rangeWithCoord.sheetId)!=null?j:"")}}),r).join(b.matchToken.COMMA),N=Ee(k),F=`${N}${N&&L?b.matchToken.COMMA:""}${L}`,w=d.current;s(F,w?-1:F.length,x)},y=g.selectionMoveEnd$.subscribe(_=>{if(I(_,!0),d.current=!1,l.current){const{result:x,offset:A}=l.current;s(x,A,!0),l.current=void 0}}),R=g.selectionMoving$.pipe(Ve.throttleTime(50)).subscribe(_=>{I(_,!1)});return()=>{y.unsubscribe(),R.unsubscribe()}}},[e,v,g,r,i,s,f,t]),u.useEffect(()=>{if(e&&g){const S=new c.DisposableCollection,I=(_,x)=>{var w;let A=0,O=0,P=!1;const k=f.getUnit(t),L=((w=k==null?void 0:k.getActiveSheet())==null?void 0:w.getName())||"",N=v.map(M=>{if(typeof M=="string")return P||(O+=M.length),M;if(M.nodeType===b.sequenceNodeType.REFERENCE){const p=b.deserializeRangeWithSheet(_);if(p.unitId=p.unitId===""?t:p.unitId,p.sheetName=p.sheetName===""?L:p.sheetName,A===x){P=!0;const T={...M,token:_};return r?T.token=b.serializeRangeWithSheet(p.sheetName,p.range):T.token=b.serializeRange(p.range),A++,O+=T.token.length,T}return A++,P||(O+=M.token.length),M}return M}),F=Ee(N);l.current={result:F,offset:O},s(F,-1,!1)};let y=0;const R=g.selectionMoveEnd$.subscribe(()=>{y=setTimeout(()=>{S.dispose(),g.getSelectionControls().forEach((x,A)=>{S.add(q.merge(x.selectionMoving$,x.selectionScaling$).pipe(q.map(O=>b.serializeRange(O)),q.distinctUntilChanged()).subscribe(O=>{d.current=!0,I(O,A)}))})},30)});return()=>{R.unsubscribe(),S.dispose(),clearTimeout(y)}}},[e,g,v,s,f,t,r])},Tt=(e,t,n,o,r,i)=>{const s=c.useDependency(c.ICommandService),a=c.useDependency(te.IEditorService),d=c.useDependency(z.IRenderManagerService).getRenderById(t),h=d==null?void 0:d.with(exports.RefSelectionsRenderService);u.useEffect(()=>{if(e&&h)if(n){const g=s.onCommandExecuted(m=>{if(m.id===V.SetWorksheetActiveOperation.id){const v=h.getSelectionControls().length;for(let l=1;l<=v;l++)h.clearLastSelection();setTimeout(()=>{i()},30)}});return()=>{g.dispose()}}else{const g=s.beforeCommandExecuted(m=>{if(m.id===V.SetWorksheetActiveOperation.id){o(!1),r(),i();const v=a.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);v==null||v.focus()}});return()=>{g.dispose()}}},[e,h])},sn=e=>!e.some(n=>{if(typeof n=="string"){if(n!==b.matchToken.COMMA)return!0}else if(n.nodeType!==b.sequenceNodeType.REFERENCE)return!0;return!1}),Xn=(e,t,n)=>{const o=u.useRef(!0);u.useEffect(()=>{if(e){const r=setTimeout(()=>{o.current=!1},500);return()=>{clearTimeout(r)}}},[e]),u.useEffect(()=>{if(!o.current&&t){const r=sn(n);t(r,Ee(n))}},[n,t])},Jn="univer-sheet-range-selector-text-wrap",Qn="univer-sheet-range-selector-placeholder",er="univer-sheet-range-selector-error",tr="univer-sheet-range-selector-error-wrap",nr="univer-sheet-range-selector-text",rr="univer-sheet-range-selector-active",or="univer-sheet-range-selector-icon",sr="univer-sheet-range-selector-dialog-item",ir="univer-sheet-range-selector-dialog-item-delete",Ce={sheetRangeSelectorTextWrap:Jn,sheetRangeSelectorPlaceholder:Qn,sheetRangeSelectorError:er,sheetRangeSelectorErrorWrap:tr,sheetRangeSelectorText:nr,sheetRangeSelectorActive:rr,sheetRangeSelectorIcon:or,sheetRangeSelectorDialogItem:sr,sheetRangeSelectorDialogItemDelete:ir},He=()=>{};function cn(e){const{initValue:t,unitId:n,subUnitId:o,errorText:r,placeholder:i,actions:s,onChange:a=He,onVerify:f=He,onRangeSelectorDialogVisibleChange:d=He,onBlur:h=He,onFocus:g=He,isFocus:m=!0,isOnlyOneRange:v=!1,isSupportAcrossSheet:l=!1}=e,S=E.useEvent(a),I=c.useDependency(te.IEditorService),y=c.useDependency(c.LocaleService),R=c.useDependency(c.ICommandService),_=c.useDependency(b.LexerTreeBuilder),x=u.useRef(null),[A,O]=u.useState(!1),[P,k]=u.useState(m),L=u.useMemo(()=>c.createInternalEditorID(`${$.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),N=u.useRef(void 0),F=N.current,w=u.useRef(null),M=c.useDependency(c.IUniverInstanceService),p=u.useMemo(()=>!A&&P,[A,P]),[T,D]=u.useState(()=>typeof t=="string"?t:Re(t,l).join(b.matchToken.COMMA)),j=u.useMemo(()=>M.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC),[M]),U=c.useObservable(j),G=(U==null?void 0:U.getUnitId())===L,Y=u.useRef([]),W=E.useEvent((H,B)=>{x.current&&!A&&!x.current.contains(H.target)&&B()});s&&(s.handleOutClick=W);const he=u.useMemo(()=>T.split(b.matchToken.COMMA).filter(H=>!!H).map(H=>b.deserializeRangeWithSheet(H)),[T]),J=u.useMemo(()=>r!==void 0,[r]),ne=rn(!A&&P,n,o);u.useMemo(()=>H=>{const B=_.sequenceNodesBuilder(H);if(B){if(sn(B)){const Z=B.map(se=>{if(typeof se=="string")return se;if(se.nodeType===b.sequenceNodeType.REFERENCE){const Le={...se},ye=b.deserializeRangeWithSheet(se.token);return ye.range=yt(ye.range),l||(ye.sheetName="",ye.unitId=""),Le.token=Re([ye],l)[0],Le}return se}),Q=Ee(Z);S(Q)}}else D("")},[l]);const K=Zt(F),{checkScrollBar:re}=te.useResize(F,!0,!0),fe=it(),Se=u.useMemo(()=>fe(T),[T]),oe=Jt(),me=Et(n,o),ce=E.useEvent((H,B=!0,X=!0)=>{if(!N.current)return;const Z=fe(H),Q=oe(N.current,Z,B);Y.current=Q,X&&me(Q,N.current)});u.useEffect(()=>{const H=R.onCommandExecuted(B=>{var X,Z;if(B.id===Ct.RichTextEditingMutation.id){const Q=B.params,{unitId:se}=Q;se===L&&S(c.BuildTextUtils.transform.getPlainText((Z=(X=F==null?void 0:F.getDocumentData().body)==null?void 0:X.dataStream)!=null?Z:""))}});return()=>H.dispose()},[R,F,L,S]);const Ie=E.useEvent((H,B,X)=>{ce(H),D(H),X&&(K(),B!==-1&&setTimeout(()=>{const Z={startOffset:B,endOffset:B};F==null||F.setSelectionRanges([Z]);const Q=F==null?void 0:F.render.with(te.DocBackScrollRenderController);Q==null||Q.scrollToRange({...Z,collapsed:!0})},50),re())});on(p,n,o,Se,l,v,Ie),_t(p,p&&G,n),nn(n,v),Bn(n,T,F),Xn(p,f,Se),tn(p,0,F),zn(),Tt(p,n,l,k,h,()=>{p&&ce(T)}),u.useEffect(()=>{if(F){const H=F.input$.pipe(q.throttleTime(100)).subscribe(B=>{var Z,Q;const X=((Q=(Z=B.data.body)==null?void 0:Z.dataStream)!=null?Q:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");ce(X,!1),D(X)});return()=>{H.unsubscribe()}}},[F]),u.useEffect(()=>{const H=R.onCommandExecuted(B=>{B.id===$.SetCellEditVisibleOperation.id&&(O(!1),d(!1),k(!1),h())});return()=>{H.dispose()}},[l]),u.useLayoutEffect(()=>{let H;if(w.current){H=I.register({autofocus:!0,editorUnitId:L,initialSnapshot:{id:L,body:{dataStream:`${T}\r
5
- `,textRuns:[]},documentStyle:{}}},w.current);const B=I.getEditor(L);N.current=B,ce(T,!1,!1)}return()=>{H==null||H.dispose()}},[]),u.useLayoutEffect(()=>{m?(k(m),K()):(F==null||F.blur(),ne(),k(m))},[m,K]),Vn(T,"",P,oe,me,F);const de=()=>{g(),K(),k(!0)},ge=H=>{const B=Re(H,l).join(b.matchToken.COMMA);B||F==null||F.setDocumentData({...F.getDocumentData(),body:{dataStream:`\r
6
- `,textRuns:[]}}),ce(B),D(B),O(!1),d(!1),setTimeout(()=>{k(!0),F==null||F.setSelectionRanges([{startOffset:B.length,endOffset:B.length}]),K(),re()},30)},Me=()=>{O(!1),d(!1),setTimeout(()=>{k(!0),K()},30)},_e=()=>{J||(K(),setTimeout(()=>{O(!0),d(!0),k(!1)},30))};return C.jsxs("div",{className:Ce.sheetRangeSelector,ref:x,children:[C.jsxs("div",{className:pt(Ce.sheetRangeSelectorTextWrap,{[Ce.sheetRangeSelectorActive]:P&&!J,[Ce.sheetRangeSelectorError]:J}),children:[C.jsx("div",{className:Ce.sheetRangeSelectorText,ref:w,onMouseUp:de}),C.jsx(pe.Tooltip,{title:y.t("rangeSelector.buttonTooltip"),placement:"bottom",children:C.jsx(zt,{className:Ce.sheetRangeSelectorIcon,onClick:_e})}),r!==void 0?C.jsx("div",{className:Ce.sheetRangeSelectorErrorWrap,children:r}):null,i!==void 0&&!T?C.jsx("div",{className:Ce.sheetRangeSelectorPlaceholder,children:i}):null]}),A&&C.jsx(cr,{editorId:L,handleConfirm:ge,handleClose:Me,unitId:n,subUnitId:o,initValue:he,visible:A,isOnlyOneRange:v,isSupportAcrossSheet:l})]})}function cr(e){const{handleConfirm:t,handleClose:n,visible:o,initValue:r,unitId:i,subUnitId:s,isOnlyOneRange:a,isSupportAcrossSheet:f}=e,d=c.useDependency(c.LocaleService),h=c.useDependency(xe.IDescriptionService),g=c.useDependency(b.LexerTreeBuilder),v=c.useDependency(z.IRenderManagerService).getRenderById(i),l=v==null?void 0:v.with(exports.RefSelectionsRenderService),[S,I]=u.useState(()=>{if(a){const p=r[0];return p?Re([p],f):[""]}return Re(r,f)}),[y,R]=u.useState(()=>S.length-1),_=Qt(),x=u.useMemo(()=>S.join(b.matchToken.COMMA),[S]),A=it(),O=u.useMemo(()=>A(x),[x]),P=u.useMemo(()=>en(h,_,O).refSelections,[O]),k=()=>{I([]),setTimeout(()=>{n()},30)},L=(p,T)=>{T?l==null||l.setSkipLastEnabled(!1):l==null||l.setSkipLastEnabled(!0),I(D=>{const j=[...D];return j[p]=T,j})},N=p=>{l==null||l.setSkipLastEnabled(!1),I(T=>{if(T.length===1)return T;const D=[];return T.forEach((j,U)=>{p!==U&&D.push(j)}),D})},F=()=>{l==null||l.setSkipLastEnabled(!0),I(p=>(p.push(""),R(p.length-1),[...p]))},w=E.useEvent(p=>{var D;l==null||l.setSkipLastEnabled(!1);const T=p.split(b.matchToken.COMMA).filter(j=>!!j);I(a?[(D=T[0])!=null?D:""]:T)}),M=Et(i,s);return on(y>=0,i,s,O,f,a,w),_t(y>=0,y>=0,i),nn(i,a),Tt(y>=0,i,f,q.noop,q.noop,()=>M(P)),u.useEffect(()=>{M(P)},[P]),u.useEffect(()=>{(S.length===0||S.length===1&&!S[0])&&(l==null||l.setSkipLastEnabled(!0))},[S]),C.jsx(pe.Dialog,{width:"328px",visible:o,title:d.t("rangeSelector.title"),draggable:!0,closeIcon:C.jsx(st,{}),footer:C.jsxs("footer",{children:[C.jsx(pe.Button,{onClick:k,children:d.t("rangeSelector.cancel")}),C.jsx(pe.Button,{style:{marginLeft:10},onClick:()=>t(S.filter(p=>{const T=g.sequenceNodesBuilder(p);return T&&T.length===1&&typeof T[0]!="string"&&T[0].nodeType===b.sequenceNodeType.REFERENCE}).map(p=>b.deserializeRangeWithSheet(p)).map(p=>({...p,range:yt(p.range)}))),type:"primary",children:d.t("rangeSelector.confirm")})]}),onClose:k,children:C.jsxs("div",{className:Ce.sheetRangeSelectorDialog,children:[S.map((p,T)=>C.jsxs("div",{className:Ce.sheetRangeSelectorDialogItem,children:[C.jsx(pe.Input,{affixWrapperStyle:{width:"100%"},placeholder:d.t("rangeSelector.placeHolder"),onFocus:()=>R(T),value:p,onChange:D=>L(T,D)},`input_${T}`),S.length>1&&!a&&C.jsx(Kt,{className:Ce.sheetRangeSelectorDialogItemDelete,onClick:()=>N(T)})]},`${p}_${T}`)),!a&&C.jsx("div",{children:C.jsxs(pe.Button,{type:"link",size:"small",onClick:F,children:[C.jsx(Yt,{}),C.jsx("span",{children:d.t("rangeSelector.addAnotherRange")})]})})]})})}function ar(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function bt(e){if(!e.require&&!e.repeat)return`[${e.name}]`;if(e.require&&!e.repeat)return e.name;if(!e.require&&e.repeat)return`[${e.name},...]`;if(e.require&&e.repeat)return`${e.name},...`}const lr=(e,t=100)=>{u.useEffect(()=>{let n=null;const o=()=>{n===null&&(n=window.setTimeout(()=>{e(),n=null},t))};return window.addEventListener("scroll",o),window.addEventListener("resize",o),()=>{n!==null&&clearTimeout(n),window.removeEventListener("scroll",o),window.removeEventListener("resize",o)}},[e,t])};function an(e,t,n){const o=c.useDependency(te.IEditorService),r=u.useMemo(()=>new q.BehaviorSubject({left:-999,top:-999,right:-999,bottom:-999}),[]),i=c.useDependency(E.ISidebarService),s=c.useDependency(c.IUniverInstanceService),a=E.useEvent(()=>{const f=o.getEditor(e);if(!f)return;const d=f.getBoundingClientRect(),{left:h,top:g,right:m,bottom:v}=d,l=r.getValue();if(!(l.left===h&&l.top===g&&l.right===m&&l.bottom===v))return r.next({left:h-1,right:m+1,top:g-1,bottom:v+1}),d});return u.useEffect(()=>{t&&a()},[e,o,s.unitAdded$,a,t,...n!=null?n:[]]),lr(a),u.useEffect(()=>{const f=i.scrollEvent$.pipe(q.throttleTime(100)).subscribe(a);return()=>{f.unsubscribe()}},[]),[r,a]}const Ye=e=>{const t=u.useRef(e);return t.current=e,t},ur=(e,t,n)=>{const o=c.useDependency(xe.IDescriptionService),r=c.useDependency(b.LexerTreeBuilder),[i,s]=u.useState(),[a,f]=u.useState(-1),[d,h]=u.useState(!0),g=Ye(d),m=u.useRef(t);m.current=t;const v=()=>{s(void 0),f(-1),h(!1)};return u.useEffect(()=>{if(n&&e){const l=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(I=>{if(I.textRanges.length===1){const[y]=I.textRanges;if(y.collapsed&&g.current){const R=r.getFunctionAndParameter(`${m.current}A`,y.startOffset-1);if(R){const{functionName:_,paramIndex:x}=R,A=o.getFunctionInfo(_);s(A),f(x);return}}}s(void 0),f(-1)}),S=n.selectionChange$.pipe(q.filter(I=>I.isEditing),q.filter(I=>I.textRanges.length===1),q.map(I=>I.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{h(!0)});return()=>{l.unsubscribe(),S.unsubscribe()}}},[n,e]),u.useEffect(()=>{e||v()},[e]),{functionInfo:i,paramIndex:a,reset:v}},fr="univer-formula-help-function",dr="univer-formula-help-function-title",hr="univer-formula-help-function-title-icons",mr="univer-formula-help-function-title-icon",gr="univer-formula-help-function-content",pr="univer-formula-help-function-content-inner",Sr="univer-formula-help-function-content-params",vr="univer-formula-help-function-content-params-title",Cr="univer-formula-help-function-content-params-detail",Rr="univer-formula-help-function-active",Ir="univer-formula-help-decorator",Er="univer-formula-help-param",_r="univer-formula-help-param-prefix",yr="univer-formula-help-param-item",Tr="univer-formula-help-param-active",ue={formulaHelpFunction:fr,formulaHelpFunctionTitle:dr,formulaHelpFunctionTitleIcons:hr,formulaHelpFunctionTitleIcon:mr,formulaHelpFunctionContent:gr,formulaHelpFunctionContentInner:pr,formulaHelpFunctionContentParams:Sr,formulaHelpFunctionContentParamsTitle:vr,formulaHelpFunctionContentParamsDetail:Cr,formulaHelpFunctionActive:Rr,formulaHelpDecorator:Ir,formulaHelpParam:Er,formulaHelpParamPrefix:_r,formulaHelpParamItem:yr,formulaHelpParamActive:Tr},lt=({className:e,title:t,value:n})=>C.jsxs("div",{className:ue.formulaHelpFunctionContentParams,children:[C.jsx("div",{className:`
1
+ "use strict";var pn=Object.defineProperty;var Sn=(e,t,n)=>t in e?pn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ee=(e,t,n)=>Sn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@univerjs/core"),$=require("@univerjs/sheets-ui"),N=require("@univerjs/engine-formula"),q=require("rxjs"),te=require("@univerjs/docs-ui"),z=require("@univerjs/engine-render"),B=require("@univerjs/sheets"),xe=require("@univerjs/sheets-formula"),a=require("@univerjs/ui"),C=require("react/jsx-runtime"),pe=require("@univerjs/design"),Ct=require("@univerjs/docs"),d=require("react"),Be=require("rxjs/operators"),nt={id:"sheet.command.paste-formula",type:l.CommandType.COMMAND,handler:async e=>e.get(l.ICommandService).executeCommand($.SheetPasteCommand.id,{value:$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Pe={id:"formula-ui.operation.select-editor-formula",type:l.CommandType.OPERATION,handler:(e,t)=>!0};var vn=Object.defineProperty,Cn=Object.getOwnPropertyDescriptor,Rn=(e,t,n,r)=>{for(var o=r>1?void 0:r?Cn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&vn(t,n,o),o},In=(e,t)=>(n,r)=>t(n,r,e);const $t="FORMULA_PROMPT_ACTIVATED",ze=l.createIdentifier("formula-ui.prompt-service");let gt=class{constructor(e){ee(this,"_search$",new q.Subject);ee(this,"_help$",new q.Subject);ee(this,"_navigate$",new q.Subject);ee(this,"_accept$",new q.Subject);ee(this,"_acceptFormulaName$",new q.Subject);ee(this,"search$",this._search$.asObservable());ee(this,"help$",this._help$.asObservable());ee(this,"navigate$",this._navigate$.asObservable());ee(this,"accept$",this._accept$.asObservable());ee(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());ee(this,"_searching",!1);ee(this,"_helping",!1);ee(this,"_sequenceNodes",[]);ee(this,"_isLockedOnSelectionChangeRefString",!1);ee(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=e}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(e){this._contextService.setContextValue($t,e.visible),this._searching=e.visible,this._search$.next(e)}isSearching(){return this._searching}help(e){this._helping=e.visible,this._help$.next(e)}isHelping(){return this._helping}navigate(e){this._navigate$.next(e)}accept(e){this._accept$.next(e)}acceptFormulaName(e){this._acceptFormulaName$.next(e)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(e){this._sequenceNodes=e}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(e){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(e)]}getCurrentSequenceNodeByIndex(e){return this._sequenceNodes[e]}getCurrentSequenceNodeIndex(e){let t=0;const n=this._sequenceNodes[0];for(let r=0,o=this._sequenceNodes.length;r<o;r++){const s=this._sequenceNodes[r];if(typeof s=="string")t++;else{const{endIndex:i}=s;t=i}if(e<=t)return typeof n=="string"&&e!==0?r+1:r}return this._sequenceNodes.length}updateSequenceRef(e,t){const n=this._sequenceNodes[e];if(typeof n=="string"||n.nodeType!==N.sequenceNodeType.REFERENCE)return;const r=t.length-n.token.length,o={...n};o.token=t,o.endIndex+=r,this._sequenceNodes[e]=o;for(let s=e+1,i=this._sequenceNodes.length;s<i;s++){const c=this._sequenceNodes[s];if(typeof c=="string")continue;const f={...c};f.startIndex+=r,f.endIndex+=r,this._sequenceNodes[s]=f}}insertSequenceRef(e,t){const n=t.length,r=this.getCurrentSequenceNodeIndex(e);this._sequenceNodes.splice(r,0,{token:t,startIndex:e,endIndex:e+n-1,nodeType:N.sequenceNodeType.REFERENCE});for(let o=r+1,s=this._sequenceNodes.length;o<s;o++){const i=this._sequenceNodes[o];if(typeof i=="string")continue;const c={...i};c.startIndex+=n,c.endIndex+=n,this._sequenceNodes[o]=c}}insertSequenceString(e,t){const n=this.getCurrentSequenceNodeIndex(e),r=t.split("");this._sequenceNodes.splice(n,0,...r);const o=r.length;for(let s=n+o,i=this._sequenceNodes.length;s<i;s++){const c=this._sequenceNodes[s];if(typeof c=="string")continue;const f={...c};f.startIndex+=o,f.endIndex+=o,this._sequenceNodes[s]=f}}enableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!0}disableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!1}isLockedSelectionChange(){return this._isLockedOnSelectionChangeRefString}enableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!0}disableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!1}isLockedSelectionInsert(){return this._isLockedOnSelectionInsertRefString}};gt=Rn([In(0,l.IContextService)],gt);const jt={id:"formula-ui.operation.help-function",type:l.CommandType.OPERATION,handler:async(e,t)=>(e.get(ze).help(t),!0)},rt={id:"formula-ui.operation.insert-function",type:l.CommandType.OPERATION,handler:async(e,t)=>{var I,y;const n=e.get(B.SheetsSelectionsService),r=e.get(te.IEditorService),o=n.getCurrentSelections();if(!o||!o.length)return!1;const s=B.getSheetCommandTarget(e.get(l.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:c,subUnitId:f}=s,m=i.getCellMatrix(),{value:g}=t,S=e.get(l.ICommandService);e.get($.IEditorBridgeService);const h=[],p=[];let u=null,_=0,R=0,E="";if(o.length===1&&(yn(o[0].range)||bn(o[0].range)&&Ot(m,o[0].range))){const{range:b,primary:x}=o[0],D=(I=x==null?void 0:x.actualRow)!=null?I:b.startRow,L=(y=x==null?void 0:x.actualColumn)!=null?y:b.startColumn;u=b,_=D,R=L;const k=xt(m,D,L);k&&(E=N.serializeRange(k))}else o.some(b=>{var L,k;const{range:x,primary:D}=b;if(Ot(m,x)){const P=(L=D==null?void 0:D.actualRow)!=null?L:x.startRow,O=(k=D==null?void 0:D.actualColumn)!=null?k:x.startColumn,F=xt(m,P,O);if(!F)return u=x,_=P,R=O,!0;const w=N.serializeRange(F),M=`=${g}(${w})`;h.push({range:x,primary:{row:P,column:O},formula:M})}else{const{startRow:P,startColumn:O,endRow:F,endColumn:w}=x;if(P===F){const M=Tn(m,P,w,i.getColumnCount()-1),v=M===w?w-1:w,T=N.serializeRange({startRow:P,endRow:F,startColumn:O,endColumn:v}),A=`=${g}(${T})`;p.push({range:x,primary:{row:P,column:M},formula:A})}else{let M=-1;for(let T=O;T<=w;T++){const A=Mn(m,T,F,i.getRowCount()-1);M=Math.max(M,A)}const v=M===F?F-1:F;for(let T=O;T<=w;T++){const A=N.serializeRange({startRow:P,endRow:v,startColumn:T,endColumn:T}),j=`=${g}(${A})`;p.push({range:x,primary:{row:M,column:T},formula:j})}}}return!1});if(u){const b=B.getCellAtRowCol(_,R,i),x={range:l.Rectangle.clone(u),primary:{startRow:b.startRow,startColumn:b.startColumn,endRow:b.endRow,endColumn:b.endColumn,actualRow:_,actualColumn:R,isMerged:b.isMerged,isMergedMainCell:b.startRow===_&&b.startColumn===R}},D={unitId:c,subUnitId:f,selections:[x]};await S.executeCommand(B.SetSelectionsOperation.id,D);const L=r.getEditor(l.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),k=r.getEditor(l.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);S.syncExecuteCommand($.SetCellEditVisibleOperation.id,{visible:!0,unitId:c,eventType:z.DeviceInputEventType.Dblclick});const P=`=${g}(${E}`;L==null||L.replaceText(P),k==null||k.replaceText(P,!1)}return h.length===0&&p.length===0?!1:S.executeCommand(xe.InsertFunctionCommand.id,{list:h,listOfRangeHasNumber:p})}};function xt(e,t,n){const r=En(e,t,n);if(r!==t)return{startRow:r,endRow:t-1,startColumn:n,endColumn:n};const o=_n(e,t,n);return o!==n?{startRow:t,endRow:t,startColumn:o,endColumn:n-1}:null}function En(e,t,n){let r=!1;if(t===0)return t;for(let o=t-1;o>=0;o--){const s=e.getValue(o,n);if(qe(s)&&!r){if(o===0)return 0;r=!0}else{if(r&&!qe(s))return o+1;if(r&&o===0)return 0}}return t}function _n(e,t,n){let r=!1;if(n===0)return n;for(let o=n-1;o>=0;o--){const s=e.getValue(t,o);if(qe(s)&&!r){if(o===0)return 0;r=!0}else{if(r&&!qe(s))return o+1;if(r&&o===0)return 0}}return n}function qe(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return!1;const n=t.dataStream,o=n.substring(n.length-2,n.length)===l.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n;return l.isRealNum(o)}return e&&(e.t===l.CellValueType.NUMBER||l.getCellValueType(e)===l.CellValueType.NUMBER)}function yn(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function bn(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function Ot(e,t){for(let n=t.startRow;n<=t.endRow;n++)for(let r=t.startColumn;r<=t.endColumn;r++)if(qe(e.getValue(n,r)))return!1;return!0}function Tn(e,t,n,r){for(let o=n;o<=r;o++)if(!e.getValue(t,o))return o;return r}function Mn(e,t,n,r){for(let o=n;o<=r;o++)if(!e.getValue(o,t))return o;return r}const Ht="SHEET_FORMULA_UI_PLUGIN",Ut=`${Ht}_MORE_FUNCTIONS_COMPONENT`,ot={id:"formula-ui.operation.more-functions",type:l.CommandType.OPERATION,handler:async e=>(e.get(a.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:Ut}}),!0)},Rt={id:"formula-ui.operation.change-ref-to-absolute",type:l.CommandType.OPERATION,handler:async e=>!0},Wt={id:"formula-ui.operation.search-function",type:l.CommandType.OPERATION,handler:async(e,t)=>(e.get(ze).search(t),!0)};var ve=function(){return ve=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},ve.apply(this,arguments)},Nn=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n},Oe=d.forwardRef(function(e,t){var n=e.icon,r=e.id,o=e.className,s=e.extend,i=Nn(e,["icon","id","className","extend"]),c="univerjs-icon univerjs-icon-".concat(r," ").concat(o||"").trim(),f=d.useRef("_".concat(On()));return Vt(n,"".concat(r),{defIds:n.defIds,idSuffix:f.current},ve({ref:t,className:c},i),s)});function Vt(e,t,n,r,o){return d.createElement(e.tag,ve(ve({key:t},Fn(e,n,o)),r),(xn(e,n).children||[]).map(function(s,i){return Vt(s,"".concat(t,"-").concat(e.tag,"-").concat(i),n,void 0,o)}))}function Fn(e,t,n){var r=ve({},e.attrs);n!=null&&n.colorChannel1&&r.fill==="colorChannel1"&&(r.fill=n.colorChannel1);var o=t.defIds;return!o||o.length===0||(e.tag==="use"&&r["xlink:href"]&&(r["xlink:href"]=r["xlink:href"]+t.idSuffix),Object.entries(r).forEach(function(s){var i=s[0],c=s[1];typeof c=="string"&&(r[i]=c.replace(/url\(#(.*)\)/,"url(#$1".concat(t.idSuffix,")")))})),r}function xn(e,t){var n,r=t.defIds;return!r||r.length===0?e:e.tag==="defs"&&(!((n=e.children)===null||n===void 0)&&n.length)?ve(ve({},e),{children:e.children.map(function(o){return typeof o.attrs.id=="string"&&r&&r.indexOf(o.attrs.id)>-1?ve(ve({},o),{attrs:ve(ve({},o.attrs),{id:o.attrs.id+t.idSuffix})}):o})}):e}function On(){return Math.random().toString(36).substring(2,8)}Oe.displayName="UniverIcon";var Dn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M14.1544 3.75557C14.3887 3.98988 14.3887 4.36978 14.1544 4.6041L6.51409 12.2444C6.40157 12.3569 6.24896 12.4201 6.08983 12.4201C5.9307 12.4201 5.77808 12.3569 5.66556 12.2444L1.84541 8.42425C1.6111 8.18993 1.6111 7.81003 1.84541 7.57572C2.07973 7.34141 2.45963 7.34141 2.69394 7.57572L6.08983 10.9716L13.3059 3.75557C13.5402 3.52126 13.9201 3.52126 14.1544 3.75557Z",fillRule:"evenodd",clipRule:"evenodd"}}]},Bt=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"check-mark-single",ref:t,icon:Dn}))});Bt.displayName="CheckMarkSingle";var An={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M3.71274 2.86421C3.47843 2.6299 3.09853 2.6299 2.86421 2.86421C2.6299 3.09853 2.6299 3.47843 2.86421 3.71274L7.15154 8.00007L2.86421 12.2874C2.6299 12.5217 2.6299 12.9016 2.86421 13.1359C3.09853 13.3702 3.47843 13.3702 3.71274 13.1359L8.00007 8.84859L12.2874 13.1359C12.5217 13.3702 12.9016 13.3702 13.1359 13.1359C13.3702 12.9016 13.3702 12.5217 13.1359 12.2874L8.84859 8.00007L13.1359 3.71274C13.3702 3.47843 13.3702 3.09853 13.1359 2.86421C12.9016 2.6299 12.5217 2.6299 12.2874 2.86421L8.00007 7.15154L3.71274 2.86421Z"}}]},st=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"close-single",ref:t,icon:An}))});st.displayName="CloseSingle";var Pn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M5.3313 1.4667C5.3313 1.13533 5.59993.866699 5.9313.866699H10.069C10.4004.866699 10.669 1.13533 10.669 1.4667 10.669 1.79807 10.4004 2.0667 10.069 2.0667H5.9313C5.59993 2.0667 5.3313 1.79807 5.3313 1.4667zM1.09985 3.64443C1.09985 3.31306 1.36848 3.04443 1.69985 3.04443H14.2999C14.6312 3.04443 14.8999 3.31306 14.8999 3.64443 14.8999 3.9758 14.6312 4.24443 14.2999 4.24443H1.69985C1.36848 4.24443 1.09985 3.9758 1.09985 3.64443zM6.12398 8.30171C6.35829 8.0674 6.73819 8.0674 6.97251 8.30171L8.00007 9.32928 9.02764 8.30171C9.26195 8.0674 9.64185 8.0674 9.87617 8.30171 10.1105 8.53603 10.1105 8.91593 9.87617 9.15024L8.8486 10.1778 9.87617 11.2054C10.1105 11.4397 10.1105 11.8196 9.87617 12.0539 9.64185 12.2882 9.26195 12.2882 9.02764 12.0539L8.00007 11.0263 6.97251 12.0539C6.73819 12.2882 6.35829 12.2882 6.12398 12.0539 5.88966 11.8196 5.88966 11.4397 6.12398 11.2054L7.15154 10.1778 6.12398 9.15024C5.88966 8.91593 5.88966 8.53603 6.12398 8.30171z"}},{tag:"path",attrs:{fill:"currentColor",d:"M4.75332 5.22217C3.86966 5.22217 3.15332 5.93851 3.15332 6.82217V12.5331C3.15332 13.9691 4.31738 15.1332 5.75332 15.1332H10.2465C11.6825 15.1332 12.8465 13.9691 12.8465 12.5331V6.82217C12.8465 5.93851 12.1302 5.22217 11.2465 5.22217H4.75332ZM4.35332 6.82217C4.35332 6.60125 4.53241 6.42217 4.75332 6.42217H11.2465C11.4674 6.42217 11.6465 6.60125 11.6465 6.82217V12.5331C11.6465 13.3063 11.0197 13.9332 10.2465 13.9332H5.75332C4.98012 13.9332 4.35332 13.3063 4.35332 12.5331V6.82217Z",fillRule:"evenodd",clipRule:"evenodd"}}]},Kt=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"delete-single",ref:t,icon:Pn}))});Kt.displayName="DeleteSingle";var Ln={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M8.75 5.32495C8.75 5.73916 8.41421 6.07495 8 6.07495 7.58579 6.07495 7.25 5.73916 7.25 5.32495 7.25 4.91074 7.58579 4.57495 8 4.57495 8.41421 4.57495 8.75 4.91074 8.75 5.32495zM8.5999 7.52505C8.5999 7.19368 8.33127 6.92505 7.9999 6.92505 7.66853 6.92505 7.3999 7.19368 7.3999 7.52505V11.425C7.3999 11.7564 7.66853 12.025 7.9999 12.025 8.33127 12.025 8.5999 11.7564 8.5999 11.425V7.52505z"}},{tag:"path",attrs:{fill:"currentColor",d:"M0.899902 8.00002C0.899902 4.0788 4.07868 0.900024 7.9999 0.900024C11.9211 0.900024 15.0999 4.0788 15.0999 8.00002C15.0999 11.9212 11.9211 15.1 7.9999 15.1C4.07868 15.1 0.899902 11.9212 0.899902 8.00002ZM7.9999 2.10002C4.74142 2.10002 2.0999 4.74154 2.0999 8.00002C2.0999 11.2585 4.74142 13.9 7.9999 13.9C11.2584 13.9 13.8999 11.2585 13.8999 8.00002C13.8999 4.74154 11.2584 2.10002 7.9999 2.10002Z",fillRule:"evenodd",clipRule:"evenodd"}}]},qt=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"details-single",ref:t,icon:Ln}))});qt.displayName="DetailsSingle";var wn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M8.6 1.99991C8.60001 1.66854 8.33138 1.39991 8.00001 1.3999C7.66864 1.3999 7.40001 1.66853 7.4 1.9999L7.39996 7.3999H1.9999C1.66853 7.3999 1.3999 7.66853 1.3999 7.9999C1.3999 8.33127 1.66853 8.5999 1.9999 8.5999H7.39995L7.3999 13.9999C7.3999 14.3313 7.66853 14.5999 7.9999 14.5999C8.33127 14.5999 8.5999 14.3313 8.5999 13.9999L8.59995 8.5999H13.9999C14.3313 8.5999 14.5999 8.33127 14.5999 7.9999C14.5999 7.66853 14.3313 7.3999 13.9999 7.3999H8.59996L8.6 1.99991Z"}}]},Yt=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"increase-single",ref:t,icon:wn}))});Yt.displayName="IncreaseSingle";var kn={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M5.90913 3.57564C6.14345 3.34132 6.52335 3.34132 6.75766 3.57564L10.7577 7.57564C10.992 7.80995 10.992 8.18985 10.7577 8.42417L6.75766 12.4242C6.52335 12.6585 6.14345 12.6585 5.90913 12.4242C5.67482 12.1899 5.67482 11.81 5.90913 11.5756L9.48487 7.9999L5.90913 4.42417C5.67482 4.18985 5.67482 3.80995 5.90913 3.57564Z",fillRule:"evenodd",clipRule:"evenodd"}}]},It=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"more-single",ref:t,icon:kn}))});It.displayName="MoreSingle";var $n={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M12.6185 12.4423C12.5907 12.2749 12.7773 12.15 12.9343 12.2308L15.4242 13.5126C15.6102 13.6084 15.5544 13.8745 15.3439 13.8955L14.2456 14.184L13.4521 15.1286C13.3495 15.2939 13.085 15.2463 13.0534 15.0568L12.6185 12.4423Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M1 3.6C1 2.16406 2.16406 1 3.6 1H12.3C13.7359 1 14.9 2.16406 14.9 3.6V5.81156C14.9003 5.81881 14.9004 5.82609 14.9004 5.8334C14.9004 5.84071 14.9003 5.84799 14.9 5.85524V10.045C14.9003 10.0522 14.9004 10.0595 14.9004 10.0668C14.9004 10.3982 14.6318 10.6668 14.3004 10.6668H11.1668C10.8907 10.6668 10.6668 10.8907 10.6668 11.1668V14.3C10.6668 14.6314 10.3982 14.9 10.0668 14.9L10.05 14.8998L3.6 14.9C2.16406 14.9 1 13.7359 1 12.3V3.6ZM13.2 5.2334C13.4761 5.2334 13.7 5.00954 13.7 4.7334V3.6C13.7 2.8268 13.0732 2.2 12.3 2.2H11.1668C10.8907 2.2 10.6668 2.42386 10.6668 2.7V4.7334C10.6668 5.00954 10.8907 5.2334 11.1668 5.2334H13.2ZM10.6668 6.9334C10.6668 6.65726 10.8907 6.4334 11.1668 6.4334H13.2C13.4761 6.4334 13.7 6.65726 13.7 6.9334V8.9668C13.7 9.24294 13.4761 9.4668 13.2 9.4668H11.1668C10.8907 9.4668 10.6668 9.24294 10.6668 8.9668V6.9334ZM8.9668 5.2334C9.24294 5.2334 9.4668 5.00954 9.4668 4.7334V2.7C9.4668 2.42386 9.24294 2.2 8.9668 2.2H6.9334C6.65726 2.2 6.4334 2.42386 6.4334 2.7V4.7334C6.4334 5.00954 6.65726 5.2334 6.9334 5.2334L8.9668 5.2334ZM6.4334 6.9334C6.4334 6.65726 6.65726 6.4334 6.9334 6.4334L8.9668 6.4334C9.24294 6.4334 9.4668 6.65726 9.4668 6.9334V8.9668C9.4668 9.24294 9.24294 9.4668 8.9668 9.4668L6.9334 9.4668C6.65726 9.4668 6.4334 9.24294 6.4334 8.9668V6.9334ZM4.7334 5.2334C5.00954 5.2334 5.2334 5.00954 5.2334 4.7334V2.7C5.2334 2.42386 5.00954 2.2 4.7334 2.2H3.6C2.8268 2.2 2.2 2.8268 2.2 3.6V4.7334C2.2 5.00954 2.42386 5.2334 2.7 5.2334H4.7334ZM2.2 6.9334C2.2 6.65726 2.42386 6.4334 2.7 6.4334H4.7334C5.00954 6.4334 5.2334 6.65725 5.2334 6.9334V8.9668C5.2334 9.24294 5.00954 9.4668 4.7334 9.4668H2.7C2.42386 9.4668 2.2 9.24294 2.2 8.9668V6.9334ZM5.2334 11.1668C5.2334 10.8907 5.00954 10.6668 4.7334 10.6668H2.7C2.42386 10.6668 2.2 10.8907 2.2 11.1668V12.3C2.2 13.0732 2.8268 13.7 3.6 13.7H4.7334C5.00954 13.7 5.2334 13.4761 5.2334 13.2V11.1668ZM9.4668 11.1668C9.4668 10.8907 9.24294 10.6668 8.9668 10.6668H6.9334C6.65726 10.6668 6.4334 10.8907 6.4334 11.1668V13.2C6.4334 13.4761 6.65726 13.7 6.9334 13.7H8.9668C9.24294 13.7 9.4668 13.4761 9.4668 13.2V11.1668Z",fillRule:"evenodd",clipRule:"evenodd"}}]},zt=d.forwardRef(function(e,t){return d.createElement(Oe,Object.assign({},e,{id:"select-range-single",ref:t,icon:$n}))});zt.displayName="SelectRangeSingle";function Gt(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=Gt(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function pt(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Gt(e))&&(r&&(r+=" "),r+=t);return r}var jn=Object.defineProperty,Hn=Object.getOwnPropertyDescriptor,Un=(e,t,n,r)=>{for(var o=r>1?void 0:r?Hn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&jn(t,n,o),o},$e=(e,t)=>(n,r)=>t(n,r,e);exports.RefSelectionsRenderService=class extends $.BaseSelectionRenderService{constructor(n,r,o,s,i,c,f){super(r,o,s,i,c);ee(this,"_workbookSelections");ee(this,"_eventDisposables");this._context=n,this._contextService=c,this._refSelectionsService=f,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Wn(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(n){this._remainLastEnabled=n}setSkipLastEnabled(n){this._skipLastEnabled=n}clearLastSelection(){const n=this._selectionControls[this._selectionControls.length-1];n&&(n.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),l.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var n;(n=this._eventDisposables)==null||n.dispose(),this._eventDisposables=null}disableSelectionChanging(){this._disableSelectionChanging()}_initCanvasEventListeners(){const n=this._getSheetObject(),{spreadsheetRowHeader:r,spreadsheetColumnHeader:o,spreadsheet:s,spreadsheetLeftTopPlaceholder:i}=n,{scene:c}=this._context,f=new l.DisposableCollection;return f.add(s==null?void 0:s.onPointerDown$.subscribeEvent((m,g)=>{this.inRefSelectionMode()&&(this._onPointerDown(m,s.zIndex+1,l.RANGE_TYPE.NORMAL,this._getActiveViewport(m)),m.button!==2&&g.stopPropagation())})),f.add(r==null?void 0:r.onPointerDown$.subscribeEvent((m,g)=>{if(!this.inRefSelectionMode())return;const S=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:h}=$.getCoordByOffset(m.offsetX,m.offsetY,c,S);$.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,l.RANGE_TYPE.ROW)||(this._onPointerDown(m,(s.zIndex||1)+1,l.RANGE_TYPE.ROW,this._getActiveViewport(m),z.ScrollTimerType.Y),m.button!==2&&g.stopPropagation())})),f.add(o==null?void 0:o.onPointerDown$.subscribeEvent((m,g)=>{if(!this.inRefSelectionMode())return;const S=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:h}=$.getCoordByOffset(m.offsetX,m.offsetY,c,S);$.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,l.RANGE_TYPE.COLUMN)||(this._onPointerDown(m,(s.zIndex||1)+1,l.RANGE_TYPE.COLUMN,this._getActiveViewport(m),z.ScrollTimerType.X),m.button!==2&&g.stopPropagation())})),f.add(i==null?void 0:i.onPointerDown$.subscribeEvent((m,g)=>{if(this._reset(),!this.inRefSelectionMode())return;const S=this._sheetSkeletonManagerService.getCurrent().skeleton,h=$.getAllSelection(S);this._addSelectionControlByModelData(h),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const p=c.onPointerUp$.subscribeEvent(()=>{p.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});m.button!==2&&g.stopPropagation()})),f}_addSelectionControlByModelData(n){var c;const r=this._skeleton,o=(c=n.style)!=null?c:$.genNormalSelectionStyle(this._themeService),s=this._scene;return n.style=o,this.newSelectionControl(s,r,n)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(n=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(n||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(n=>{this._updateSelections(n,B.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(n=>{this._updateSelections(n,B.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(n=>{this._updateSelections(n,B.SelectionMoveType.MOVE_END)}))}_updateSelections(n,r){const s=this._context.unit.getActiveSheet().getSheetId();n.length!==0&&this._workbookSelections.setSelections(s,n.map(i=>B.convertSelectionDataToRange(i)),r)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(n=>{if(!n)return;const{skeleton:r}=n,{scene:o}=this._context,s=o.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&this._skeleton.worksheet.getSheetId()!==r.worksheet.getSheetId()&&this._reset(),this._changeRuntime(r,o,s);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(n){const r=this._getSheetObject();return r==null?void 0:r.scene.getActiveViewportByCoord(z.Vector2.FromArray([n.offsetX,n.offsetY]))}_getSheetObject(){return $.getSheetObject(this._context.unit,this._context)}_onPointerDown(n,r=0,o=l.RANGE_TYPE.NORMAL,s,i=z.ScrollTimerType.ALL){var F;this._rangeType=o;const c=this._skeleton,f=this._scene;if(!f||!c)return;s&&(this._activeViewport=s);const{offsetX:m,offsetY:g}=n,S=f.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!S)return;const h=f.getCoordRelativeToViewport(z.Vector2.FromArray([m,g])),{x:p,y:u}=h;this._startViewportPosX=p,this._startViewportPosY=u;const _=f.getScrollXYInfoByViewport(h),{scaleX:R,scaleY:E}=f.getAncestorScale(),I=this._skeleton.getCellByOffset(p,u,R,E,_);if(!I)return;switch(o){case l.RANGE_TYPE.NORMAL:break;case l.RANGE_TYPE.ROW:I.startColumn=0,I.endColumn=this._skeleton.getColumnCount()-1;break;case l.RANGE_TYPE.COLUMN:I.startRow=0,I.endRow=this._skeleton.getRowCount()-1;break;case l.RANGE_TYPE.ALL:I.startRow=0,I.startColumn=0,I.endRow=this._skeleton.getRowCount()-1,I.endColumn=this._skeleton.getColumnCount()-1}const y={range:I,primary:I,style:null};y.range.rangeType=o;const b=$.attachSelectionWithCoord(y,this._skeleton);this._startRangeWhenPointerDown={...b.rangeWithCoord};const x={...b.rangeWithCoord,rangeType:o};let D=this.getActiveSelectionControl();const L=this.getSelectionControls();for(const w of L){if(n.button===2&&w.model.isInclude(x)){D=w;return}if(w.model.isEqual(x)){D=w;break}}this._checkClearPreviousControls(n);const k=D==null?void 0:D.model.currentCell,P=n.shiftKey&&k,O=this._remainLastEnabled&&!n.ctrlKey&&!n.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;P&&k?this._makeSelectionByTwoCells(k,x,c,o,D):O&&D?D.updateRangeBySelectionWithCoord(b):D=this.newSelectionControl(f,c,y);for(let w=0;w<this.getSelectionControls().length-1;w++)this.getSelectionControls()[w].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),f.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(F=f.getTransformer())==null||F.clearSelectedObjects(),this._setupPointerMoveListener(S,D,o,i,p,u),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=f.onPointerUp$.subscribeEvent(()=>{var w;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(w=this._escapeShortcutDisposable)==null||w.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(n,r,o){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:c}=r,f=new $.SelectionControl(n,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:c}),m=$.attachSelectionWithCoord(o,r);return f.updateRangeBySelectionWithCoord(m),this._selectionControls.push(f),f.setControlExtension({skeleton:r,scene:n,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),f}};exports.RefSelectionsRenderService=Un([$e(1,l.Inject(l.Injector)),$e(2,l.Inject(l.ThemeService)),$e(3,a.IShortcutService),$e(4,l.Inject($.SheetSkeletonManagerService)),$e(5,l.IContextService),$e(6,B.IRefSelectionsService)],exports.RefSelectionsRenderService);function Wn(e){const t=$.genNormalSelectionStyle(e);return t.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},t}const Vn=(e,t,n)=>{const o=a.useDependency(z.IRenderManagerService).getRenderById(e),s=o==null?void 0:o.with(exports.RefSelectionsRenderService);d.useEffect(()=>{if(n&&s){const i=n.input$.subscribe(c=>{c.content===N.matchToken.COMMA?s.setSkipLastEnabled(!0):s.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[n,s]),d.useEffect(()=>{s&&(t.endsWith(N.matchToken.COMMA)||s.setSkipLastEnabled(!1))},[t,s])},it=()=>{const e=a.useDependency(N.LexerTreeBuilder);return d.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])},Bn=(e,t,n,r,o,s)=>{const i=it(),c=d.useRef(!0);d.useEffect(()=>{var f,m;if(s){if(c.current){const g=i(e);if(g.length){const S=r(s,g);n&&o(S)}else{const S=s.getDocumentData(),p={dataStream:(m=(f=S.body)==null?void 0:f.dataStream)!=null?m:`${t}\r
2
+ `,...S.body};s.setDocumentData({...S,body:p})}c.current=!1}else if(n){const g=i(e),S=r(s,g);o(S)}}},[s,n])},Zt=e=>{const t=a.useDependency(te.IEditorService);return a.useEvent(r=>{var o,s;if(e){t.focus(e.getEditorId());const i=[...e.getSelectionRanges()];if(l.Tools.isDefine(r))e.setSelectionRanges([{startOffset:r,endOffset:r}]);else if(!i.length&&!e.docSelectionRenderService.isOnPointerEvent){const c=(s=(o=e.getDocumentData().body)==null?void 0:o.dataStream)!=null?s:`\r
3
+ `,f=Math.max(c.length-2,0);e.setSelectionRanges([{startOffset:f,endOffset:f}])}}})};function Kn(e,t,n){const r=e.getCurrentTheme(),o=new l.ColorKit(t).setAlpha(.05).toRgbString();return{id:n,strokeWidth:1,stroke:t,fill:o,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:r.colorWhite}}function Xt(e){var E,I,y;const{unitId:t,subUnitId:n,refSelections:r,editor:o,refSelectionsService:s,refSelectionsRenderService:i,sheetSkeletonManagerService:c,themeService:f,univerInstanceService:m}=e,g=m.getUnit(t,l.UniverInstanceType.UNIVER_SHEET),S=g==null?void 0:g.getActiveSheet(),h=[];if(!g||!S){s.setSelections(h);return}const p=S.getSheetId(),u=b=>{var x;return(x=g==null?void 0:g.getSheetBySheetName(b))==null?void 0:x.getSheetId()};if(!((E=c==null?void 0:c.getWorksheetSkeleton(p))==null?void 0:E.skeleton))return;const R=[];for(let b=0,x=r.length;b<x;b++){const D=r[b],{themeColor:L,token:k,refIndex:P,endIndex:O}=D,F=N.deserializeRangeWithSheet(k),{unitId:w,sheetName:M,range:v}=F;if(w&&t!==w)continue;const T=u(M);if(T&&T!==p||!T&&p!==n)continue;const A=B.setEndForRange(v,S.getRowCount(),S.getColumnCount());h.push({range:A,primary:null,style:Kn(f,L,P.toString())}),R.push(O)}if(o){const b=(y=(I=o.getSelectionRanges())==null?void 0:I[0])==null?void 0:y.startOffset,x=R.findIndex(D=>D+2===b);x!==-1?i==null||i.setActiveSelectionIndex(x):i==null||i.resetActiveSelectionIndex()}return h}function Et(e,t){const n=a.useDependency(l.IUniverInstanceService),r=a.useDependency(l.ThemeService),o=a.useDependency(B.IRefSelectionsService),i=a.useDependency(z.IRenderManagerService).getRenderById(e),c=i==null?void 0:i.with(exports.RefSelectionsRenderService),f=i==null?void 0:i.with($.SheetSkeletonManagerService),m=d.useCallback((g,S)=>{const h=Xt({unitId:e,subUnitId:t,refSelections:g,editor:S,refSelectionsService:o,refSelectionsRenderService:c,sheetSkeletonManagerService:f,themeService:r,univerInstanceService:n});if(!h)return;((c==null?void 0:c.getSelectionControls())||[]).length===h.length?c==null||c.resetSelectionsByModelData(h):o.setSelections(h)},[c,o,f,r,e,t,n]);return d.useEffect(()=>()=>{c==null||c.resetActiveSelectionIndex()},[c]),m}function Jt(e=""){const t=a.useDependency(xe.IDescriptionService),n=Qt(),r=a.useDependency(l.ICommandService),o=d.useMemo(()=>e.length,[e]);return d.useCallback((i,c,f=!0,m)=>{const g=i.getDocumentData(),S=i.getEditorId();if(!g)return[];const h=g.body;if(!h)return[];const p=h.dataStream.slice(0,h.dataStream.length-2),u={dataStream:"",...g.body};if(!p.startsWith(e))return[];if(c==null||c.length===0)return u.textRuns=[],r.syncExecuteCommand(te.ReplaceTextRunsCommand.id,{unitId:S,body:l.getBodySlice(u,0,u.dataStream.length-2)}),[];{const{textRuns:_,refSelections:R}=en(t,n,c);o&&_.forEach(y=>{y.ed=y.ed+o,y.st=y.st+o}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},..._];const E=c.reduce((y,b)=>typeof b=="string"?`${y}${b}`:`${y}${b.token}`,"");u.dataStream=`${e}${E}\r
4
+ `;let I;if(f){I=i.getSelectionRanges();const y=u.dataStream.length-2+o;I.forEach(b=>{b.startOffset=Math.max(0,Math.min(b.startOffset,y)),b.endOffset=Math.max(0,Math.min(b.endOffset,y))})}return r.syncExecuteCommand(te.ReplaceTextRunsCommand.id,{unitId:S,body:l.getBodySlice(u,0,u.dataStream.length-2),textRanges:m!=null?m:I}),R}},[r,t,n,o,e])}function Qt(){const t=a.useDependency(l.ThemeService).getCurrentTheme();return d.useMemo(()=>{const r=[t.loopColor1,t.loopColor2,t.loopColor3,t.loopColor4,t.loopColor5,t.loopColor6,t.loopColor7,t.loopColor8,t.loopColor9,t.loopColor10,t.loopColor11,t.loopColor12],o=t.hyacinth700,s=t.verdancy800,i=t.colorBlack;return{formulaRefColors:r,numberColor:o,stringColor:s,plainTextColor:i}},[t])}function en(e,t,n){const{formulaRefColors:r,numberColor:o,stringColor:s,plainTextColor:i}=t,c=[],f=[],m=new Map;let g=0;for(let S=0,h=n.length;S<h;S++){const p=n[S];if(typeof p=="string"){const y=c[c.length-1],b=y?y.ed:0,x=b+p.length;c.push({st:b,ed:x,ts:{cl:{rgb:i},fs:11}});continue}if(e.hasDefinedNameDescription(p.token.trim())){c.push({st:p.startIndex,ed:p.endIndex+1,ts:{cl:{rgb:i},fs:11}});continue}const{startIndex:u,endIndex:_,nodeType:R,token:E}=p;let I="";if(R===N.sequenceNodeType.REFERENCE){if(m.has(E))I=m.get(E);else{const y=g%r.length;I=r[y],m.set(E,I),g++}f.push({refIndex:S,themeColor:I,token:E,startIndex:p.startIndex,endIndex:p.endIndex,index:f.length})}else R===N.sequenceNodeType.NUMBER?I=o:(R===N.sequenceNodeType.STRING||R===N.sequenceNodeType.ARRAY)&&(I=s);I&&I.length>0?c.push({st:u,ed:_+1,ts:{cl:{rgb:I},fs:11}}):c.push({st:u,ed:_+1,ts:{cl:{rgb:i},fs:11}})}return{textRuns:c,refSelections:f}}function qn(e){var o,s;const n=e.get(l.IUniverInstanceService).getCurrentUniverDocInstance();return n!=null&&n.getBody()?{dataStream:(s=(o=n.getBody())==null?void 0:o.dataStream)!=null?s:"",offset:0}:void 0}var Ze=(e=>(e[e.NOT_SELECT=0]="NOT_SELECT",e[e.NEED_ADD=1]="NEED_ADD",e[e.CAN_EDIT=2]="CAN_EDIT",e))(Ze||{});function Yn(e){var I;const{editorId:t,isFocus:n,disableOnClick:r,unitId:o}=e,s=a.useDependency(z.IRenderManagerService),i=s.getRenderById(o),c=s.getRenderById(t),f=c==null?void 0:c.with(te.DocSelectionRenderService),m=a.useDependency(Ct.DocSelectionManagerService),g=a.useDependency(l.Injector),[S,h]=d.useState(0),p=a.useDependency(N.LexerTreeBuilder),u=d.useRef(!0),_=d.useRef(S);_.current=S;const R=i==null?void 0:i.with(exports.RefSelectionsRenderService),E=a.useEvent(y=>{R&&R.setSkipLastEnabled(y===1),h(y)});return d.useEffect(()=>{const y=m.textSelection$.pipe(q.filter(b=>b.unitId===t),q.map(()=>{const b=f==null?void 0:f.getActiveTextRange();return b!=null&&b.collapsed?b.startOffset:-1})).subscribe(b=>{var M,v;const x=qn(g);if(!x)return;const D=(M=x==null?void 0:x.dataStream)==null?void 0:M.slice(0,-2),L=(v=p.sequenceNodesBuilder(D))!=null?v:[],k=D[b-1],P=D[b],O=L.findIndex(T=>typeof T=="object"&&T.nodeType===N.sequenceNodeType.REFERENCE&&b===T.endIndex+2),F=k&&N.matchRefDrawToken(k)&&(!P||N.isFormulaLexerToken(P)&&P!==N.matchToken.OPEN_BRACKET),w=O>-1;if((D==null?void 0:D.substring(0,1))==="="&&(F||w))if(w){if(u.current)return;E(2)}else u.current=!1,E(1);else E(0)});return()=>y.unsubscribe()},[m.textSelection$,f,t,g,p]),d.useEffect(()=>{n||(E(0),u.current=!0)},[n]),d.useEffect(()=>{var b;if(!r)return;const y=(b=c==null?void 0:c.mainComponent)==null?void 0:b.onPointerDown$.subscribeEvent(()=>{E(0),u.current=!0});return()=>y==null?void 0:y.unsubscribe()},[r,(I=c==null?void 0:c.mainComponent)==null?void 0:I.onPointerDown$]),{isSelecting:S}}const tn=(e,t,n,r)=>{const o=a.useDependency(l.ICommandService),s=a.useDependency(a.IShortcutService),i=d.useRef(t);i.current=t;const c=d.useRef(r);c.current=r,d.useEffect(()=>{if(!n||!e)return;const m=`sheet.formula-embedding-editor.${n.getEditorId()}`,g=new l.DisposableCollection,S=(u,_)=>{if(c.current){c.current(u,_);return}let R=l.Direction.LEFT;u===a.KeyCode.ARROW_DOWN?R=l.Direction.DOWN:u===a.KeyCode.ARROW_UP?R=l.Direction.UP:u===a.KeyCode.ARROW_RIGHT&&(R=l.Direction.RIGHT),_===a.MetaKeys.SHIFT?o.executeCommand(te.MoveSelectionOperation.id,{direction:R}):o.executeCommand(te.MoveCursorOperation.id,{direction:R})},h=(u,_)=>{let R=l.Direction.DOWN;u===a.KeyCode.ARROW_DOWN?R=l.Direction.DOWN:u===a.KeyCode.ARROW_UP?R=l.Direction.UP:u===a.KeyCode.ARROW_LEFT?R=l.Direction.LEFT:u===a.KeyCode.ARROW_RIGHT&&(R=l.Direction.RIGHT),i.current?_===a.MetaKeys.CTRL_COMMAND?o.executeCommand($.MoveSelectionCommand.id,{direction:R,jumpOver:$.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:i.current===Ze.NEED_ADD}):_===a.MetaKeys.SHIFT?o.executeCommand($.ExpandSelectionCommand.id,{direction:R,extra:"formula-editor"}):_===(a.MetaKeys.CTRL_COMMAND|a.MetaKeys.SHIFT)?o.executeCommand($.ExpandSelectionCommand.id,{direction:R,jumpOver:$.JumpOver.moveGap,extra:"formula-editor"}):o.executeCommand($.MoveSelectionCommand.id,{direction:R,extra:"formula-editor",fromCurrentSelection:i.current===Ze.NEED_ADD}):S(u,_)};return g.add(o.registerCommand({id:m,type:l.CommandType.OPERATION,handler(u,_){const{keyCode:R,metaKey:E}=_;h(R,E)}})),[{keyCode:a.KeyCode.ARROW_DOWN},{keyCode:a.KeyCode.ARROW_LEFT},{keyCode:a.KeyCode.ARROW_RIGHT},{keyCode:a.KeyCode.ARROW_UP},{keyCode:a.KeyCode.ARROW_DOWN,metaKey:a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_LEFT,metaKey:a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_RIGHT,metaKey:a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_UP,metaKey:a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_DOWN,metaKey:a.MetaKeys.CTRL_COMMAND},{keyCode:a.KeyCode.ARROW_LEFT,metaKey:a.MetaKeys.CTRL_COMMAND},{keyCode:a.KeyCode.ARROW_RIGHT,metaKey:a.MetaKeys.CTRL_COMMAND},{keyCode:a.KeyCode.ARROW_UP,metaKey:a.MetaKeys.CTRL_COMMAND},{keyCode:a.KeyCode.ARROW_DOWN,metaKey:a.MetaKeys.CTRL_COMMAND|a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_LEFT,metaKey:a.MetaKeys.CTRL_COMMAND|a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_RIGHT,metaKey:a.MetaKeys.CTRL_COMMAND|a.MetaKeys.SHIFT},{keyCode:a.KeyCode.ARROW_UP,metaKey:a.MetaKeys.CTRL_COMMAND|a.MetaKeys.SHIFT}].map(({keyCode:u,metaKey:_})=>({id:m,binding:_?u|_:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:u,metaKey:_}})).forEach(u=>{g.add(s.registerShortcut(u))}),()=>{g.dispose()}},[o,n,e,s])},nn=(e,t)=>{const r=a.useDependency(z.IRenderManagerService).getRenderById(e),o=r==null?void 0:r.with(exports.RefSelectionsRenderService);d.useEffect(()=>{o&&(t?o==null||o.setRemainLastEnabled(!1):o==null||o.setRemainLastEnabled(!0))},[t,o])},_t=(e,t,n,r=!0)=>{const o=a.useDependency(z.IRenderManagerService),s=a.useDependency(l.IContextService),i=a.useDependency(a.IContextMenuService),c=a.useDependency(B.IRefSelectionsService),f=o.getRenderById(n),m=f==null?void 0:f.with(exports.RefSelectionsRenderService);d.useLayoutEffect(()=>{if(e)return s.setContextValue(l.EDITOR_ACTIVATED,!0),()=>{s.setContextValue(l.EDITOR_ACTIVATED,!1),c.clear()}},[s,e,c]),d.useLayoutEffect(()=>{if(e&&t){const g=m==null?void 0:m.enableSelectionChanging();return s.setContextValue(B.REF_SELECTIONS_ENABLED,!0),()=>{s.setContextValue(B.REF_SELECTIONS_ENABLED,!1),g==null||g.dispose()}}},[s,e,m,t]),d.useEffect(()=>{if(e)return s.setContextValue(l.EDITOR_ACTIVATED,!0),r&&i.disable(),()=>{s.setContextValue(l.EDITOR_ACTIVATED,!1),r&&i.enable()}},[i,s,e,r]),d.useEffect(()=>{e&&(m==null||m.setSkipLastEnabled(!1))},[e,m])},zn=()=>{d.useEffect(()=>()=>{},[])},rn=(e,t,n)=>{const r=a.useDependency(l.IUniverInstanceService),o=a.useDependency(B.SheetsSelectionsService);return d.useCallback(()=>{if(e){const i=[...o.getWorkbookSelections(t).getSelectionsOfWorksheet(n)],c=r.getCurrentUnitForType(l.UniverInstanceType.UNIVER_SHEET),f=c==null?void 0:c.getActiveSheet();f&&f.getSheetId()===n&&o.setSelections(i)}},[e,o,n,t,r])},St=e=>typeof e=="string"?e===N.matchToken.COMMA:!1,Gn=e=>{if(typeof e=="object")return e.nodeType===N.sequenceNodeType.REFERENCE},Zn=e=>e.filter(t=>St(t)||Gn(t)),yt=e=>{if(e.endColumn<e.startColumn){const t=e.endColumn;e.endColumn=e.startColumn,e.startColumn=t}if(e.endRow<e.startRow){const t=e.endRow;e.endRow=e.startRow,e.startRow=t}return e},Ee=e=>e.map(t=>typeof t=="string"?t:t.token).join("");function Dt(e,t,n){var r,o;return((o=(r=e.getUnit(t))==null?void 0:r.getSheetBySheetId(n))==null?void 0:o.getName())||""}const Re=(e,t=!1,n="")=>t?e.map(r=>r.sheetName!==""&&r.sheetName!==n?N.serializeRangeWithSheet(r.sheetName,r.range):N.serializeRange(r.range)):e.map(r=>N.serializeRange(r.range)),on=(e,t,n,r,o,s,i)=>{const c=a.useDependency(z.IRenderManagerService),f=a.useDependency(l.IUniverInstanceService),m=d.useRef(!1),g=c.getRenderById(t),S=g==null?void 0:g.with(exports.RefSelectionsRenderService),h=d.useRef([]),p=d.useMemo(()=>{const _=Zn(r),R=h.current;return _.length===R.length?(R.splice(0),R.push(..._),R):_},[r]);h.current=p;const u=d.useRef(void 0);d.useEffect(()=>{if(e&&S){let _=!0;const R=(y,b)=>{var M;if(_||m.current){_=!1;return}const x=[...y],D=f.getUnit(t),L=((M=D==null?void 0:D.getActiveSheet())==null?void 0:M.getName())||"",k=p.map((v,T)=>{if(typeof v=="string"){if(!p[T-1])return null;const j=p[T+1];return St(v)&&(St(j)||T===p.length-1)?null:v}else if(v.nodeType===N.sequenceNodeType.REFERENCE){const A=N.deserializeRangeWithSheet(v.token);A.unitId=A.unitId===""?t:A.unitId,A.sheetName=A.sheetName===""?L:A.sheetName;const{unitId:j,sheetName:V}=A;if(s&&(j!==t||L!==V))return null;if(j===t&&L===V){const G=x.shift();if(G&&Dt(f,t,G.rangeWithCoord.sheetId||"")===V){const Y={...v};return yt(G.rangeWithCoord),o?Y.token=N.serializeRangeWithSheet(L,G.rangeWithCoord):Y.token=N.serializeRange(G.rangeWithCoord),Y}}return v}return null}).filter(v=>!!v),P=Re(x.map(v=>{var T,A,j;return{range:v.rangeWithCoord,unitId:(T=v.rangeWithCoord.unitId)!=null?T:"",sheetName:Dt(f,(A=v.rangeWithCoord.unitId)!=null?A:"",(j=v.rangeWithCoord.sheetId)!=null?j:"")}}),o).join(N.matchToken.COMMA),O=Ee(k),F=`${O}${O&&P?N.matchToken.COMMA:""}${P}`,w=m.current;i(F,w?-1:F.length,b)},E=S.selectionMoveEnd$.subscribe(y=>{if(R(y,!0),m.current=!1,u.current){const{result:b,offset:x}=u.current;i(b,x,!0),u.current=void 0}}),I=S.selectionMoving$.pipe(Be.throttleTime(50)).subscribe(y=>{R(y,!1)});return()=>{E.unsubscribe(),I.unsubscribe()}}},[e,p,S,o,s,i,f,t]),d.useEffect(()=>{if(e&&S){const _=new l.DisposableCollection,R=(y,b)=>{var w;let x=0,D=0,L=!1;const k=f.getUnit(t),P=((w=k==null?void 0:k.getActiveSheet())==null?void 0:w.getName())||"",O=p.map(M=>{if(typeof M=="string")return L||(D+=M.length),M;if(M.nodeType===N.sequenceNodeType.REFERENCE){const v=N.deserializeRangeWithSheet(y);if(v.unitId=v.unitId===""?t:v.unitId,v.sheetName=v.sheetName===""?P:v.sheetName,x===b){L=!0;const T={...M,token:y};return o?T.token=N.serializeRangeWithSheet(v.sheetName,v.range):T.token=N.serializeRange(v.range),x++,D+=T.token.length,T}return x++,L||(D+=M.token.length),M}return M}),F=Ee(O);u.current={result:F,offset:D},i(F,-1,!1)};let E=0;const I=S.selectionMoveEnd$.subscribe(()=>{E=setTimeout(()=>{_.dispose(),S.getSelectionControls().forEach((b,x)=>{_.add(q.merge(b.selectionMoving$,b.selectionScaling$).pipe(q.map(D=>N.serializeRange(D)),q.distinctUntilChanged()).subscribe(D=>{m.current=!0,R(D,x)}))})},30)});return()=>{I.unsubscribe(),_.dispose(),clearTimeout(E)}}},[e,S,p,i,f,t,o])},bt=(e,t,n,r,o,s)=>{const i=a.useDependency(l.ICommandService),c=a.useDependency(te.IEditorService),m=a.useDependency(z.IRenderManagerService).getRenderById(t),g=m==null?void 0:m.with(exports.RefSelectionsRenderService);d.useEffect(()=>{if(e&&g)if(n){const S=i.onCommandExecuted(h=>{if(h.id===B.SetWorksheetActiveOperation.id){const p=g.getSelectionControls().length;for(let u=1;u<=p;u++)g.clearLastSelection();setTimeout(()=>{s()},30)}});return()=>{S.dispose()}}else{const S=i.beforeCommandExecuted(h=>{if(h.id===B.SetWorksheetActiveOperation.id){r(!1),o(),s();const p=c.getEditor(l.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);p==null||p.focus()}});return()=>{S.dispose()}}},[e,g])},sn=e=>!e.some(n=>{if(typeof n=="string"){if(n!==N.matchToken.COMMA)return!0}else if(n.nodeType!==N.sequenceNodeType.REFERENCE)return!0;return!1}),Xn=(e,t,n)=>{const r=d.useRef(!0);d.useEffect(()=>{if(e){const o=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(o)}}},[e]),d.useEffect(()=>{if(!r.current&&t){const o=sn(n);t(o,Ee(n))}},[n,t])},Jn="univer-sheet-range-selector-text-wrap",Qn="univer-sheet-range-selector-placeholder",er="univer-sheet-range-selector-error",tr="univer-sheet-range-selector-error-wrap",nr="univer-sheet-range-selector-text",rr="univer-sheet-range-selector-active",or="univer-sheet-range-selector-icon",sr="univer-sheet-range-selector-dialog-item",ir="univer-sheet-range-selector-dialog-item-delete",Ce={sheetRangeSelectorTextWrap:Jn,sheetRangeSelectorPlaceholder:Qn,sheetRangeSelectorError:er,sheetRangeSelectorErrorWrap:tr,sheetRangeSelectorText:nr,sheetRangeSelectorActive:rr,sheetRangeSelectorIcon:or,sheetRangeSelectorDialogItem:sr,sheetRangeSelectorDialogItemDelete:ir},He=()=>{};function cn(e){const{initValue:t,unitId:n,subUnitId:r,errorText:o,placeholder:s,actions:i,onChange:c=He,onVerify:f=He,onRangeSelectorDialogVisibleChange:m=He,onBlur:g=He,onFocus:S=He,isFocus:h=!0,isOnlyOneRange:p=!1,isSupportAcrossSheet:u=!1}=e,_=a.useEvent(c),R=a.useDependency(te.IEditorService),E=a.useDependency(l.LocaleService),I=a.useDependency(l.ICommandService),y=a.useDependency(N.LexerTreeBuilder),b=d.useRef(null),[x,D]=d.useState(!1),[L,k]=d.useState(h),P=d.useMemo(()=>l.createInternalEditorID(`${$.RANGE_SELECTOR_SYMBOLS}-${l.generateRandomId(4)}`),[]),O=d.useRef(void 0),F=O.current,w=d.useRef(null),M=a.useDependency(l.IUniverInstanceService),v=d.useMemo(()=>!x&&L,[x,L]),[T,A]=d.useState(()=>typeof t=="string"?t:Re(t,u).join(N.matchToken.COMMA)),j=d.useMemo(()=>M.getCurrentTypeOfUnit$(l.UniverInstanceType.UNIVER_DOC),[M]),V=a.useObservable(j),G=(V==null?void 0:V.getUnitId())===P,Y=d.useRef([]),U=a.useEvent((H,W)=>{b.current&&!x&&!b.current.contains(H.target)&&W()});i&&(i.handleOutClick=U);const he=d.useMemo(()=>T.split(N.matchToken.COMMA).filter(H=>!!H).map(H=>N.deserializeRangeWithSheet(H)),[T]),J=d.useMemo(()=>o!==void 0,[o]),ne=rn(!x&&L,n,r);d.useMemo(()=>H=>{const W=y.sequenceNodesBuilder(H);if(W){if(sn(W)){const Z=W.map(se=>{if(typeof se=="string")return se;if(se.nodeType===N.sequenceNodeType.REFERENCE){const Le={...se},ye=N.deserializeRangeWithSheet(se.token);return ye.range=yt(ye.range),u||(ye.sheetName="",ye.unitId=""),Le.token=Re([ye],u)[0],Le}return se}),Q=Ee(Z);_(Q)}}else A("")},[u]);const K=Zt(F),{checkScrollBar:re}=te.useResize(F,!0,!0),fe=it(),Se=d.useMemo(()=>fe(T),[T]),oe=Jt(),me=Et(n,r),ce=a.useEvent((H,W=!0,X=!0)=>{if(!O.current)return;const Z=fe(H),Q=oe(O.current,Z,W);Y.current=Q,X&&me(Q,O.current)});d.useEffect(()=>{const H=I.onCommandExecuted(W=>{var X,Z;if(W.id===Ct.RichTextEditingMutation.id){const Q=W.params,{unitId:se}=Q;se===P&&_(l.BuildTextUtils.transform.getPlainText((Z=(X=F==null?void 0:F.getDocumentData().body)==null?void 0:X.dataStream)!=null?Z:""))}});return()=>H.dispose()},[I,F,P,_]);const Ie=a.useEvent((H,W,X)=>{ce(H),A(H),X&&(K(),W!==-1&&setTimeout(()=>{const Z={startOffset:W,endOffset:W};F==null||F.setSelectionRanges([Z]);const Q=F==null?void 0:F.render.with(te.DocBackScrollRenderController);Q==null||Q.scrollToRange({...Z,collapsed:!0})},50),re())});on(v,n,r,Se,u,p,Ie),_t(v,v&&G,n),nn(n,p),Vn(n,T,F),Xn(v,f,Se),tn(v,0,F),zn(),bt(v,n,u,k,g,()=>{v&&ce(T)}),d.useEffect(()=>{if(F){const H=F.input$.pipe(q.throttleTime(100)).subscribe(W=>{var Z,Q;const X=((Q=(Z=W.data.body)==null?void 0:Z.dataStream)!=null?Q:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");ce(X,!1),A(X)});return()=>{H.unsubscribe()}}},[F]),d.useEffect(()=>{const H=I.onCommandExecuted(W=>{W.id===$.SetCellEditVisibleOperation.id&&(D(!1),m(!1),k(!1),g())});return()=>{H.dispose()}},[u]),d.useLayoutEffect(()=>{let H;if(w.current){H=R.register({autofocus:!0,editorUnitId:P,initialSnapshot:{id:P,body:{dataStream:`${T}\r
5
+ `,textRuns:[]},documentStyle:{}}},w.current);const W=R.getEditor(P);O.current=W,ce(T,!1,!1)}return()=>{H==null||H.dispose()}},[]),d.useLayoutEffect(()=>{h?(k(h),K()):(F==null||F.blur(),ne(),k(h))},[h,K]),Bn(T,"",L,oe,me,F);const de=()=>{S(),K(),k(!0)},ge=H=>{const W=Re(H,u).join(N.matchToken.COMMA);W||F==null||F.setDocumentData({...F.getDocumentData(),body:{dataStream:`\r
6
+ `,textRuns:[]}}),ce(W),A(W),D(!1),m(!1),setTimeout(()=>{k(!0),F==null||F.setSelectionRanges([{startOffset:W.length,endOffset:W.length}]),K(),re()},30)},Me=()=>{D(!1),m(!1),setTimeout(()=>{k(!0),K()},30)},_e=()=>{J||(K(),setTimeout(()=>{D(!0),m(!0),k(!1)},30))};return C.jsxs("div",{className:Ce.sheetRangeSelector,ref:b,children:[C.jsxs("div",{className:pt(Ce.sheetRangeSelectorTextWrap,{[Ce.sheetRangeSelectorActive]:L&&!J,[Ce.sheetRangeSelectorError]:J}),children:[C.jsx("div",{className:Ce.sheetRangeSelectorText,ref:w,onMouseUp:de}),C.jsx(pe.Tooltip,{title:E.t("rangeSelector.buttonTooltip"),placement:"bottom",children:C.jsx(zt,{className:Ce.sheetRangeSelectorIcon,onClick:_e})}),o!==void 0?C.jsx("div",{className:Ce.sheetRangeSelectorErrorWrap,children:o}):null,s!==void 0&&!T?C.jsx("div",{className:Ce.sheetRangeSelectorPlaceholder,children:s}):null]}),x&&C.jsx(cr,{editorId:P,handleConfirm:ge,handleClose:Me,unitId:n,subUnitId:r,initValue:he,visible:x,isOnlyOneRange:p,isSupportAcrossSheet:u})]})}function cr(e){const{handleConfirm:t,handleClose:n,visible:r,initValue:o,unitId:s,subUnitId:i,isOnlyOneRange:c,isSupportAcrossSheet:f}=e,m=a.useDependency(l.LocaleService),g=a.useDependency(xe.IDescriptionService),S=a.useDependency(N.LexerTreeBuilder),p=a.useDependency(z.IRenderManagerService).getRenderById(s),u=p==null?void 0:p.with(exports.RefSelectionsRenderService),[_,R]=d.useState(()=>{if(c){const v=o[0];return v?Re([v],f):[""]}return Re(o,f)}),[E,I]=d.useState(()=>_.length-1),y=Qt(),b=d.useMemo(()=>_.join(N.matchToken.COMMA),[_]),x=it(),D=d.useMemo(()=>x(b),[b]),L=d.useMemo(()=>en(g,y,D).refSelections,[D]),k=()=>{R([]),setTimeout(()=>{n()},30)},P=(v,T)=>{T?u==null||u.setSkipLastEnabled(!1):u==null||u.setSkipLastEnabled(!0),R(A=>{const j=[...A];return j[v]=T,j})},O=v=>{u==null||u.setSkipLastEnabled(!1),R(T=>{if(T.length===1)return T;const A=[];return T.forEach((j,V)=>{v!==V&&A.push(j)}),A})},F=()=>{u==null||u.setSkipLastEnabled(!0),R(v=>(v.push(""),I(v.length-1),[...v]))},w=a.useEvent(v=>{var A;u==null||u.setSkipLastEnabled(!1);const T=v.split(N.matchToken.COMMA).filter(j=>!!j);R(c?[(A=T[0])!=null?A:""]:T)}),M=Et(s,i);return on(E>=0,s,i,D,f,c,w),_t(E>=0,E>=0,s),nn(s,c),bt(E>=0,s,f,q.noop,q.noop,()=>M(L)),d.useEffect(()=>{M(L)},[L]),d.useEffect(()=>{(_.length===0||_.length===1&&!_[0])&&(u==null||u.setSkipLastEnabled(!0))},[_]),C.jsx(pe.Dialog,{width:"328px",visible:r,title:m.t("rangeSelector.title"),draggable:!0,closeIcon:C.jsx(st,{}),footer:C.jsxs("footer",{children:[C.jsx(pe.Button,{onClick:k,children:m.t("rangeSelector.cancel")}),C.jsx(pe.Button,{style:{marginLeft:10},onClick:()=>t(_.filter(v=>{const T=S.sequenceNodesBuilder(v);return T&&T.length===1&&typeof T[0]!="string"&&T[0].nodeType===N.sequenceNodeType.REFERENCE}).map(v=>N.deserializeRangeWithSheet(v)).map(v=>({...v,range:yt(v.range)}))),type:"primary",children:m.t("rangeSelector.confirm")})]}),onClose:k,children:C.jsxs("div",{className:Ce.sheetRangeSelectorDialog,children:[_.map((v,T)=>C.jsxs("div",{className:Ce.sheetRangeSelectorDialogItem,children:[C.jsx(pe.Input,{affixWrapperStyle:{width:"100%"},placeholder:m.t("rangeSelector.placeHolder"),onFocus:()=>I(T),value:v,onChange:A=>P(T,A)},`input_${T}`),_.length>1&&!c&&C.jsx(Kt,{className:Ce.sheetRangeSelectorDialogItemDelete,onClick:()=>O(T)})]},`${v}_${T}`)),!c&&C.jsx("div",{children:C.jsxs(pe.Button,{type:"link",size:"small",onClick:F,children:[C.jsx(Yt,{}),C.jsx("span",{children:m.t("rangeSelector.addAnotherRange")})]})})]})})}function ar(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function Tt(e){if(!e.require&&!e.repeat)return`[${e.name}]`;if(e.require&&!e.repeat)return e.name;if(!e.require&&e.repeat)return`[${e.name},...]`;if(e.require&&e.repeat)return`${e.name},...`}const lr=(e,t=100)=>{d.useEffect(()=>{let n=null;const r=()=>{n===null&&(n=window.setTimeout(()=>{e(),n=null},t))};return window.addEventListener("scroll",r),window.addEventListener("resize",r),()=>{n!==null&&clearTimeout(n),window.removeEventListener("scroll",r),window.removeEventListener("resize",r)}},[e,t])};function an(e,t,n){const r=a.useDependency(te.IEditorService),o=d.useMemo(()=>new q.BehaviorSubject({left:-999,top:-999,right:-999,bottom:-999}),[]),s=a.useDependency(a.ISidebarService),i=a.useDependency(l.IUniverInstanceService),c=a.useEvent(()=>{const f=r.getEditor(e);if(!f)return;const m=f.getBoundingClientRect(),{left:g,top:S,right:h,bottom:p}=m,u=o.getValue();if(!(u.left===g&&u.top===S&&u.right===h&&u.bottom===p))return o.next({left:g-1,right:h+1,top:S-1,bottom:p+1}),m});return d.useEffect(()=>{t&&c()},[e,r,i.unitAdded$,c,t,...n!=null?n:[]]),lr(c),d.useEffect(()=>{const f=s.scrollEvent$.pipe(q.throttleTime(100)).subscribe(c);return()=>{f.unsubscribe()}},[]),[o,c]}const Ye=e=>{const t=d.useRef(e);return t.current=e,t},ur=(e,t,n)=>{const r=a.useDependency(xe.IDescriptionService),o=a.useDependency(N.LexerTreeBuilder),[s,i]=d.useState(),[c,f]=d.useState(-1),[m,g]=d.useState(!0),S=Ye(m),h=d.useRef(t);h.current=t;const p=()=>{i(void 0),f(-1),g(!1)};return d.useEffect(()=>{if(n&&e){const u=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(R=>{if(R.textRanges.length===1){const[E]=R.textRanges;if(E.collapsed&&S.current){const I=o.getFunctionAndParameter(`${h.current}A`,E.startOffset-1);if(I){const{functionName:y,paramIndex:b}=I,x=r.getFunctionInfo(y);i(x),f(b);return}}}i(void 0),f(-1)}),_=n.selectionChange$.pipe(q.filter(R=>R.isEditing),q.filter(R=>R.textRanges.length===1),q.map(R=>R.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{g(!0)});return()=>{u.unsubscribe(),_.unsubscribe()}}},[n,e]),d.useEffect(()=>{e||p()},[e]),{functionInfo:s,paramIndex:c,reset:p}},fr="univer-formula-help-function",dr="univer-formula-help-function-title",hr="univer-formula-help-function-title-icons",mr="univer-formula-help-function-title-icon",gr="univer-formula-help-function-content",pr="univer-formula-help-function-content-inner",Sr="univer-formula-help-function-content-params",vr="univer-formula-help-function-content-params-title",Cr="univer-formula-help-function-content-params-detail",Rr="univer-formula-help-function-active",Ir="univer-formula-help-decorator",Er="univer-formula-help-param",_r="univer-formula-help-param-prefix",yr="univer-formula-help-param-item",br="univer-formula-help-param-active",ue={formulaHelpFunction:fr,formulaHelpFunctionTitle:dr,formulaHelpFunctionTitleIcons:hr,formulaHelpFunctionTitleIcon:mr,formulaHelpFunctionContent:gr,formulaHelpFunctionContentInner:pr,formulaHelpFunctionContentParams:Sr,formulaHelpFunctionContentParamsTitle:vr,formulaHelpFunctionContentParamsDetail:Cr,formulaHelpFunctionActive:Rr,formulaHelpDecorator:Ir,formulaHelpParam:Er,formulaHelpParamPrefix:_r,formulaHelpParamItem:yr,formulaHelpParamActive:br},lt=({className:e,title:t,value:n})=>C.jsxs("div",{className:ue.formulaHelpFunctionContentParams,children:[C.jsx("div",{className:`
7
7
  ${ue.formulaHelpFunctionContentParamsTitle}
8
8
  ${e}
9
- `,children:t}),C.jsx("div",{className:ue.formulaHelpFunctionContentParamsDetail,children:n})]}),br=e=>{const{prefix:t,value:n,active:o,onClick:r}=e;return C.jsxs("div",{className:ue.formulaHelpParam,children:[C.jsxs("span",{className:ue.formulaHelpParamPrefix,children:[t,"("]}),n&&n.map((i,s)=>C.jsxs("span",{className:ue.formulaHelpParamItem,children:[C.jsx("span",{className:o===s?ue.formulaHelpFunctionActive:ue.formulaHelpParamActive,onClick:()=>r(s),children:bt(i)}),s===n.length-1?"":","]},i.name)),")"]})},At=()=>{};function Mr(e){const{onParamsSwitch:t=At,onClose:n=At,isFocus:o,editor:r,formulaText:i}=e,{functionInfo:s,paramIndex:a,reset:f}=ur(o,i,r),d=u.useMemo(()=>!!s&&a>=0,[s,a]),[h,g]=u.useState(!0),m=c.useDependency(c.LocaleService),v=m.t("formula.prompt.required"),l=m.t("formula.prompt.optional"),S=r.getEditorId(),[I]=an(S,d,[s,a]);function y(_){t&&t(_)}const R=()=>{f(),n()};return d&&s?C.jsx(E.RectPopup,{portal:!0,onClickOutside:()=>f(),anchorRect$:I,direction:"vertical",children:C.jsxs("div",{className:ue.formulaHelpFunction,children:[C.jsxs("div",{className:ue.formulaHelpFunctionTitle,children:[C.jsx(br,{prefix:s.functionName,value:s.functionParameter,active:a,onClick:y}),C.jsxs("div",{className:ue.formulaHelpFunctionTitleIcons,children:[C.jsx("div",{className:ue.formulaHelpFunctionTitleIcon,style:{transform:h?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>g(!h),children:C.jsx(It,{})}),C.jsx("div",{className:ue.formulaHelpFunctionTitleIcon,onClick:R,children:C.jsx(st,{})})]})]}),C.jsx("div",{className:ue.formulaHelpFunctionContent,style:{height:h?"unset":0,padding:h?"revert-layer":0},children:C.jsxs("div",{className:ue.formulaHelpFunctionContentInner,children:[C.jsx(lt,{title:m.t("formula.prompt.helpExample"),value:`${s.functionName}(${s.functionParameter.map(_=>_.example).join(",")})`}),C.jsx(lt,{title:m.t("formula.prompt.helpAbstract"),value:s.description}),s&&s.functionParameter&&s.functionParameter.map((_,x)=>C.jsx(lt,{className:a===x?ue.formulaHelpFunctionActive:"",title:_.name,value:`${_.require?v:l} ${_.detail}`},x))]})})]})}):null}const ln=(e,t,n=!0)=>{let o=-1;return e.reduce((r,i,s)=>{if(r.isFinish)return r;const a=r.currentIndex;if(typeof i!="string")r.currentIndex+=i.token.length;else{const f=i.length;r.currentIndex+=f}return(n?r.currentIndex===t:t>a&&t<=r.currentIndex)&&(o=s,r.isFinish=!0),r},{currentIndex:0,isFinish:!1}),o},Ge=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),Nr=()=>{},Fr=(e,t,n,o,r,i,s,a,f,d,h=Nr)=>{const g=c.useDependency(z.IRenderManagerService),m=c.useDependency(c.IUniverInstanceService),v=c.useDependency(c.ICommandService),l=Ye(i),S=c.useDependency(Ct.DocSelectionManagerService),I=c.useDependency(c.ThemeService),y=m.getUnit(o),R=E.useEvent(M=>{var p,T;return(T=(p=y==null?void 0:y.getSheetBySheetId(M))==null?void 0:p.getName())!=null?T:""}),_=u.useMemo(()=>R(r),[R,r]),x=c.useObservable(y==null?void 0:y.activeSheet$),A=Ye({activeSheet:x,sheetName:_}),O=g.getRenderById(o),P=O==null?void 0:O.with(exports.RefSelectionsRenderService),k=O==null?void 0:O.with($.SheetSkeletonManagerService),L=c.useDependency(V.IRefSelectionsService),N=u.useRef(!1),F=u.useRef(n);F.current=n;const w=u.useRef(void 0);u.useEffect(()=>{if(P&&e){let M=!0;const p=(D,j)=>{var J,ne,K,re,fe,Se;if(M){M=!1;return}const U=d==null?void 0:d.getSelectionRanges();if((U==null?void 0:U.length)!==1)return;const Y=U[0].startOffset-1,W=[...l.current],he=ln(W,Y,!1);if(F.current===Ze.NEED_ADD)if(Y!==0){if(he===-1&&W.length)return;const oe=D[D.length-1],me=W.splice(he+1),ce=(J=oe.rangeWithCoord.sheetId)!=null?J:r,Ie={range:oe.rangeWithCoord,unitId:(ne=oe.rangeWithCoord.unitId)!=null?ne:o,sheetName:R(ce)},ge=Re([Ie],a&&ce!==r,_);W.push({token:ge[0],nodeType:b.sequenceNodeType.REFERENCE});const Me=[...W,...me],_e=Ee(Me);h(_e,Ge(W),j)}else{const oe=D[D.length-1],me=(K=oe.rangeWithCoord.sheetId)!=null?K:r,ce={range:oe.rangeWithCoord,unitId:(re=oe.rangeWithCoord.unitId)!=null?re:o,sheetName:R(me)},de=Re([ce],a&&me!==r);W.unshift({token:de[0],nodeType:b.sequenceNodeType.REFERENCE});const ge=Ee(W);h(ge,de[0].length,j)}else{let oe=0;const me=W.map(H=>{var B,X,Z;if(typeof H=="string")return H;if(H.nodeType===b.sequenceNodeType.REFERENCE){const Q=b.deserializeRangeWithSheet(H.token);if(Q.sheetName||(Q.sheetName=_),a&&((B=A.current.activeSheet)==null?void 0:B.getName())!==Q.sheetName)return H.token;const se=D[oe];if(oe++,!se)return"";const Le=(X=se.rangeWithCoord.sheetId)!=null?X:r,ye={range:se.rangeWithCoord,unitId:(Z=se.rangeWithCoord.unitId)!=null?Z:o,sheetName:R(Le)};return Re([ye],a,_)[0]}return H.token});let ce="",Ie;me.forEach((H,B)=>{ce+=H,B===he&&(Ie=ce.length)});const de=[];for(let H=oe;H<=D.length-1;H++){const B=D[H],X=(fe=B.rangeWithCoord.sheetId)!=null?fe:r,Z={range:B.rangeWithCoord,unitId:(Se=B.rangeWithCoord.unitId)!=null?Se:o,sheetName:R(X)},se=Re([Z],a&&X!==r,_);de.push(se[0])}const ge=W[W.length-1],Me=ge&&(typeof ge=="string"?!1:ge.nodeType===b.sequenceNodeType.REFERENCE),_e=`${ce}${de.length&&Me?",":""}${de.join(",")}`;h(_e,!de.length&&Ie?Ie:_e.length,j)}},T=new c.DisposableCollection;return T.add(P.selectionMoving$.subscribe(D=>{N.current||p(D,!1)})),T.add(P.selectionMoveEnd$.subscribe(D=>{N.current||p(D,!0)})),()=>{T.dispose()}}},[P,d,a,e,l,r,o,R,_,h,A]),u.useEffect(()=>{if(t&&P&&d){const M=new c.DisposableCollection,p=(j,U)=>{let G=0,Y=0,W=!1;const{sheetName:he}=A.current,J=l.current.map(K=>{var re;if(typeof K=="string")return W||(Y+=K.length),K;if(K.nodeType===b.sequenceNodeType.REFERENCE){const fe=b.deserializeRangeWithSheet(K.token);if(fe.unitId||(fe.unitId=o),fe.sheetName||(fe.sheetName=he),a&&((re=A.current.activeSheet)==null?void 0:re.getName())!==fe.sheetName)return W||(Y+=K.token.length),K;if(G===U){W=!0;const Se={...K,token:j};return a&&fe.sheetName!==he?Se.token=b.serializeRangeWithSheet(fe.sheetName,b.deserializeRangeWithSheet(j).range):Se.token=j,Y+=Se.token.length,G++,Se}return W||(Y+=K.token.length),G++,K}return W||(Y+=K.token.length),K}),ne=Ee(J);h(ne,-1,!0),w.current={result:ne,offset:Y}},T=()=>{M.dispose(),P.getSelectionControls().forEach((U,G)=>{M.add(q.merge(U.selectionMoving$,U.selectionScaling$).pipe(Ve.map(Y=>b.serializeRange(Y)),Ve.distinctUntilChanged(),Ve.debounceTime(100)).subscribe(Y=>{N.current=!0,p(Y,G)}))}),M.add(P.selectionMoveEnd$.subscribe(U=>{if(N.current=!1,w.current){const{result:G,offset:Y}=w.current;h(G,Y||-1,!0),w.current=void 0}}))},D=q.merge(d.input$,L.selectionSet$,P.selectionMoveEnd$).pipe(Ve.debounceTime(50)).subscribe(()=>{T()});return()=>{D.unsubscribe(),M.dispose()}}},[t,P,d,L.selectionSet$,A,l,h,a,o]),u.useEffect(()=>{if(f){const M=v.onCommandExecuted(p=>{if(p.id!==V.SetSelectionsOperation.id)return;const T=p.params;if(T.extra!=="formula-editor")return;const{selections:D}=T;if(D.length){const j=D[D.length-1];if(j){const U=j.range,G=r,Y={range:U,unitId:T.unitId===o?"":T.unitId,sheetName:T.subUnitId===G?"":R(G)},W=[...l.current],J=Re([Y],a,_)[0];let ne=W[W.length-1];if(typeof ne=="object"&&ne.nodeType===b.sequenceNodeType.REFERENCE){ne={...ne},ne.token=J,ne.endIndex=ne.startIndex+J.length,W[W.length-1]=ne;const K=Ee(W);h(K,Ge(W),!0)}else{const K=Ge(W);W.push({nodeType:b.sequenceNodeType.REFERENCE,token:J,startIndex:K,endIndex:K+J.length});const re=Ee(W);h(re,Ge(W),!0)}}}});return()=>{M.dispose()}}},[v,R,h,a,f,l,_,r,o]),u.useEffect(()=>{if(!d)return;const M=S.textSelection$.subscribe(p=>{p.unitId===d.getEditorId()&&Xt({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:L,refSelectionsRenderService:P,sheetSkeletonManagerService:k,themeService:I,univerInstanceService:m})});return()=>M.unsubscribe()},[S.textSelection$,d,s,P,L,l,k,r,I,o,m])},xr=(e,t,n)=>{const o=c.useDependency(b.LexerTreeBuilder),r=u.useRef(!0);u.useEffect(()=>{if(e){const i=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(i)}}},[e]),u.useEffect(()=>{if(!r.current&&t){const i=o.checkIfAddBracket(n);t(i===0&&n.startsWith(b.operatorToken.EQUALS),`${n}`)}},[n,t])},Or="univer-sheet-embedding-formula-editor-active",Dr="univer-sheet-embedding-formula-editor-wrap",Ar="univer-sheet-embedding-formula-editor-text",Pr="univer-sheet-embedding-formula-editor-error",Lr="univer-sheet-embedding-formula-editor",wr="univer-sheet-embedding-formula-editor-error-wrap",je={sheetEmbeddingFormulaEditorActive:Or,sheetEmbeddingFormulaEditorWrap:Dr,sheetEmbeddingFormulaEditorText:Ar,sheetEmbeddingFormulaEditorError:Pr,sheetEmbeddingFormulaEditor:Lr,sheetEmbeddingFormulaEditorErrorWrap:wr},kr=(e,t=[],n)=>{const o=c.useDependency(xe.IDescriptionService),[r,i]=u.useState([]),[s,a]=u.useState(""),f=u.useRef(-1),d=Ye({nodes:t}),h=()=>{i([]),a(""),f.current=-1};return u.useEffect(()=>{if(n&&e){const m=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const v=n.getSelectionRanges();if(v.length===1){const l=d.current.nodes,S=v[0];if(S.collapsed){const I=ln(l,S.startOffset-1,!1);f.current=I;const y=l[I];if(y&&typeof y!="string"&&y.nodeType===b.sequenceNodeType.FUNCTION){f.current=I;const R=y.token,_=o.getSearchListByNameFirstLetter(R);i(_),a(R);return}}}f.current=-1,a(""),i(l=>l!=null&&l.length?[]:l)});return()=>{m.unsubscribe()}}},[n,e]),u.useEffect(()=>{e||h()},[e]),{searchList:r,searchText:s,handlerFormulaReplace:m=>{const v=[...d.current.nodes];if(f.current!==-1){const l=v.splice(f.current+1),S=v.pop()||"";let I=(typeof S=="string"?S.length:S.token.length)-m.length;return v.push(m),l[0]!==b.matchToken.OPEN_BRACKET&&(v.push(b.matchToken.OPEN_BRACKET),I--),{text:Ee([...v,...l]),offset:I}}},reset:h}},$r="univer-formula-search-function",jr="univer-formula-search-function-item",Hr="univer-formula-search-function-item-name",Ur="univer-formula-search-function-item-name-light",Wr="univer-formula-search-function-item-desc",Br="univer-formula-search-function-item-active",Ne={formulaSearchFunction:$r,formulaSearchFunctionItem:jr,formulaSearchFunctionItemName:Hr,formulaSearchFunctionItemNameLight:Ur,formulaSearchFunctionItemDesc:Wr,formulaSearchFunctionItemActive:Br},Vr=()=>{},Kr=u.forwardRef(qr);function qr(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:i,onClose:s=Vr}=e,a=i.getEditorId(),f=c.useDependency(E.IShortcutService),d=c.useDependency(c.ICommandService),{searchList:h,searchText:g,handlerFormulaReplace:m,reset:v}=kr(n,o,i),l=u.useMemo(()=>!!h.length,[h]),S=u.useRef(void 0),[I,y]=u.useState(0),R=u.useRef(!1),[_]=an(a,l,[g,h]),x=Ye({searchList:h,active:I}),A=N=>{const F=m(N);F&&(v(),r(F))};function O(N){R.current&&y(N)}function P(){R.current&&y(-1)}u.useEffect(()=>{if(!h.length)return;const N=`sheet.formula-embedding-editor.search_function.${a}`,F=new c.DisposableCollection,w=M=>{const{searchList:p,active:T}=x.current;switch(M){case E.KeyCode.ARROW_UP:{y(D=>{const j=Math.max(0,D-1);return k(j),j});break}case E.KeyCode.ARROW_DOWN:{y(D=>{const j=Math.min(p.length-1,D+1);return k(j),j});break}case E.KeyCode.TAB:case E.KeyCode.ENTER:{const D=p[T];A(D.name);break}case E.KeyCode.ESC:{v(),s();break}}};return F.add(d.registerCommand({id:N,type:c.CommandType.OPERATION,handler(M,p){const{keyCode:T}=p;w(T)}})),[E.KeyCode.ARROW_UP,E.KeyCode.ARROW_DOWN,E.KeyCode.ENTER,E.KeyCode.ESC,E.KeyCode.TAB].map(M=>({id:N,binding:M,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:M}})).forEach(M=>{F.add(f.registerShortcut(M))}),()=>{F.dispose()}},[h]);function k(N){var Y;const F=(Y=S.current)==null?void 0:Y.querySelectorAll(`.${Ne.formulaSearchFunctionItem}`)[N];if(!F)return;const w=F.parentNode;if(!w)return;const p=w.getBoundingClientRect().top,T=w.offsetHeight,D=F.getBoundingClientRect(),j=D.top,U=D.height;if(j>=0&&j>p&&j-p+U<=T)return;const G=F.offsetTop-(T-U)/2;w.scrollTo({top:G,behavior:"smooth"})}const L=u.useMemo(()=>{let N="";return()=>{clearTimeout(N),R.current=!0,N=setTimeout(()=>{R.current=!1},300)}},[]);return h.length>0&&l&&C.jsx(E.RectPopup,{portal:!0,anchorRect$:_,direction:"vertical",children:C.jsx("ul",{className:Ne.formulaSearchFunction,ref:N=>{S.current=N,t&&(t.current=N)},children:h.map((N,F)=>C.jsxs("li",{className:I===F?`
9
+ `,children:t}),C.jsx("div",{className:ue.formulaHelpFunctionContentParamsDetail,children:n})]}),Tr=e=>{const{prefix:t,value:n,active:r,onClick:o}=e;return C.jsxs("div",{className:ue.formulaHelpParam,children:[C.jsxs("span",{className:ue.formulaHelpParamPrefix,children:[t,"("]}),n&&n.map((s,i)=>C.jsxs("span",{className:ue.formulaHelpParamItem,children:[C.jsx("span",{className:r===i?ue.formulaHelpFunctionActive:ue.formulaHelpParamActive,onClick:()=>o(i),children:Tt(s)}),i===n.length-1?"":","]},s.name)),")"]})},At=()=>{};function Mr(e){const{onParamsSwitch:t=At,onClose:n=At,isFocus:r,editor:o,formulaText:s}=e,{functionInfo:i,paramIndex:c,reset:f}=ur(r,s,o),m=d.useMemo(()=>!!i&&c>=0,[i,c]),[g,S]=d.useState(!0),h=a.useDependency(l.LocaleService),p=h.t("formula.prompt.required"),u=h.t("formula.prompt.optional"),_=o.getEditorId(),[R]=an(_,m,[i,c]);function E(y){t&&t(y)}const I=()=>{f(),n()};return m&&i?C.jsx(a.RectPopup,{portal:!0,onClickOutside:()=>f(),anchorRect$:R,direction:"vertical",children:C.jsxs("div",{className:ue.formulaHelpFunction,children:[C.jsxs("div",{className:ue.formulaHelpFunctionTitle,children:[C.jsx(Tr,{prefix:i.functionName,value:i.functionParameter,active:c,onClick:E}),C.jsxs("div",{className:ue.formulaHelpFunctionTitleIcons,children:[C.jsx("div",{className:ue.formulaHelpFunctionTitleIcon,style:{transform:g?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>S(!g),children:C.jsx(It,{})}),C.jsx("div",{className:ue.formulaHelpFunctionTitleIcon,onClick:I,children:C.jsx(st,{})})]})]}),C.jsx("div",{className:ue.formulaHelpFunctionContent,style:{height:g?"unset":0,padding:g?"revert-layer":0},children:C.jsxs("div",{className:ue.formulaHelpFunctionContentInner,children:[C.jsx(lt,{title:h.t("formula.prompt.helpExample"),value:`${i.functionName}(${i.functionParameter.map(y=>y.example).join(",")})`}),C.jsx(lt,{title:h.t("formula.prompt.helpAbstract"),value:i.description}),i&&i.functionParameter&&i.functionParameter.map((y,b)=>C.jsx(lt,{className:c===b?ue.formulaHelpFunctionActive:"",title:y.name,value:`${y.require?p:u} ${y.detail}`},b))]})})]})}):null}const ln=(e,t,n=!0)=>{let r=-1;return e.reduce((o,s,i)=>{if(o.isFinish)return o;const c=o.currentIndex;if(typeof s!="string")o.currentIndex+=s.token.length;else{const f=s.length;o.currentIndex+=f}return(n?o.currentIndex===t:t>c&&t<=o.currentIndex)&&(r=i,o.isFinish=!0),o},{currentIndex:0,isFinish:!1}),r},Ge=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),Nr=()=>{},Fr=(e,t,n,r,o,s,i,c,f,m,g=Nr)=>{const S=a.useDependency(z.IRenderManagerService),h=a.useDependency(l.IUniverInstanceService),p=a.useDependency(l.ICommandService),u=Ye(s),_=a.useDependency(Ct.DocSelectionManagerService),R=a.useDependency(l.ThemeService),E=h.getUnit(r),I=a.useEvent(M=>{var v,T;return(T=(v=E==null?void 0:E.getSheetBySheetId(M))==null?void 0:v.getName())!=null?T:""}),y=d.useMemo(()=>I(o),[I,o]),b=a.useObservable(E==null?void 0:E.activeSheet$),x=Ye({activeSheet:b,sheetName:y}),D=S.getRenderById(r),L=D==null?void 0:D.with(exports.RefSelectionsRenderService),k=D==null?void 0:D.with($.SheetSkeletonManagerService),P=a.useDependency(B.IRefSelectionsService),O=d.useRef(!1),F=d.useRef(n);F.current=n;const w=d.useRef(void 0);d.useEffect(()=>{if(L&&e){let M=!0;const v=(A,j)=>{var J,ne,K,re,fe,Se;if(M){M=!1;return}const V=m==null?void 0:m.getSelectionRanges();if((V==null?void 0:V.length)!==1)return;const Y=V[0].startOffset-1,U=[...u.current],he=ln(U,Y,!1);if(F.current===Ze.NEED_ADD)if(Y!==0){if(he===-1&&U.length)return;const oe=A[A.length-1],me=U.splice(he+1),ce=(J=oe.rangeWithCoord.sheetId)!=null?J:o,Ie={range:oe.rangeWithCoord,unitId:(ne=oe.rangeWithCoord.unitId)!=null?ne:r,sheetName:I(ce)},ge=Re([Ie],c&&ce!==o,y);U.push({token:ge[0],nodeType:N.sequenceNodeType.REFERENCE});const Me=[...U,...me],_e=Ee(Me);g(_e,Ge(U),j)}else{const oe=A[A.length-1],me=(K=oe.rangeWithCoord.sheetId)!=null?K:o,ce={range:oe.rangeWithCoord,unitId:(re=oe.rangeWithCoord.unitId)!=null?re:r,sheetName:I(me)},de=Re([ce],c&&me!==o);U.unshift({token:de[0],nodeType:N.sequenceNodeType.REFERENCE});const ge=Ee(U);g(ge,de[0].length,j)}else{let oe=0;const me=U.map(H=>{var W,X,Z;if(typeof H=="string")return H;if(H.nodeType===N.sequenceNodeType.REFERENCE){const Q=N.deserializeRangeWithSheet(H.token);if(Q.sheetName||(Q.sheetName=y),c&&((W=x.current.activeSheet)==null?void 0:W.getName())!==Q.sheetName)return H.token;const se=A[oe];if(oe++,!se)return"";const Le=(X=se.rangeWithCoord.sheetId)!=null?X:o,ye={range:se.rangeWithCoord,unitId:(Z=se.rangeWithCoord.unitId)!=null?Z:r,sheetName:I(Le)};return Re([ye],c,y)[0]}return H.token});let ce="",Ie;me.forEach((H,W)=>{ce+=H,W===he&&(Ie=ce.length)});const de=[];for(let H=oe;H<=A.length-1;H++){const W=A[H],X=(fe=W.rangeWithCoord.sheetId)!=null?fe:o,Z={range:W.rangeWithCoord,unitId:(Se=W.rangeWithCoord.unitId)!=null?Se:r,sheetName:I(X)},se=Re([Z],c&&X!==o,y);de.push(se[0])}const ge=U[U.length-1],Me=ge&&(typeof ge=="string"?!1:ge.nodeType===N.sequenceNodeType.REFERENCE),_e=`${ce}${de.length&&Me?",":""}${de.join(",")}`;g(_e,!de.length&&Ie?Ie:_e.length,j)}},T=new l.DisposableCollection;return T.add(L.selectionMoving$.subscribe(A=>{O.current||v(A,!1)})),T.add(L.selectionMoveEnd$.subscribe(A=>{O.current||v(A,!0)})),()=>{T.dispose()}}},[L,m,c,e,u,o,r,I,y,g,x]),d.useEffect(()=>{if(t&&L&&m){const M=new l.DisposableCollection,v=(j,V)=>{let G=0,Y=0,U=!1;const{sheetName:he}=x.current,J=u.current.map(K=>{var re;if(typeof K=="string")return U||(Y+=K.length),K;if(K.nodeType===N.sequenceNodeType.REFERENCE){const fe=N.deserializeRangeWithSheet(K.token);if(fe.unitId||(fe.unitId=r),fe.sheetName||(fe.sheetName=he),c&&((re=x.current.activeSheet)==null?void 0:re.getName())!==fe.sheetName)return U||(Y+=K.token.length),K;if(G===V){U=!0;const Se={...K,token:j};return c&&fe.sheetName!==he?Se.token=N.serializeRangeWithSheet(fe.sheetName,N.deserializeRangeWithSheet(j).range):Se.token=j,Y+=Se.token.length,G++,Se}return U||(Y+=K.token.length),G++,K}return U||(Y+=K.token.length),K}),ne=Ee(J);g(ne,-1,!0),w.current={result:ne,offset:Y}},T=()=>{M.dispose(),L.getSelectionControls().forEach((V,G)=>{M.add(q.merge(V.selectionMoving$,V.selectionScaling$).pipe(Be.map(Y=>N.serializeRange(Y)),Be.distinctUntilChanged(),Be.debounceTime(100)).subscribe(Y=>{O.current=!0,v(Y,G)}))}),M.add(L.selectionMoveEnd$.subscribe(V=>{if(O.current=!1,w.current){const{result:G,offset:Y}=w.current;g(G,Y||-1,!0),w.current=void 0}}))},A=q.merge(m.input$,P.selectionSet$,L.selectionMoveEnd$).pipe(Be.debounceTime(50)).subscribe(()=>{T()});return()=>{A.unsubscribe(),M.dispose()}}},[t,L,m,P.selectionSet$,x,u,g,c,r]),d.useEffect(()=>{if(f){const M=p.onCommandExecuted(v=>{if(v.id!==B.SetSelectionsOperation.id)return;const T=v.params;if(T.extra!=="formula-editor")return;const{selections:A}=T;if(A.length){const j=A[A.length-1];if(j){const V=j.range,G=o,Y={range:V,unitId:T.unitId===r?"":T.unitId,sheetName:T.subUnitId===G?"":I(G)},U=[...u.current],J=Re([Y],c,y)[0];let ne=U[U.length-1];if(typeof ne=="object"&&ne.nodeType===N.sequenceNodeType.REFERENCE){ne={...ne},ne.token=J,ne.endIndex=ne.startIndex+J.length,U[U.length-1]=ne;const K=Ee(U);g(K,Ge(U),!0)}else{const K=Ge(U);U.push({nodeType:N.sequenceNodeType.REFERENCE,token:J,startIndex:K,endIndex:K+J.length});const re=Ee(U);g(re,Ge(U),!0)}}}});return()=>{M.dispose()}}},[p,I,g,c,f,u,y,o,r]),d.useEffect(()=>{if(!m)return;const M=_.textSelection$.subscribe(v=>{v.unitId===m.getEditorId()&&Xt({unitId:r,subUnitId:o,refSelections:i.current,editor:m,refSelectionsService:P,refSelectionsRenderService:L,sheetSkeletonManagerService:k,themeService:R,univerInstanceService:h})});return()=>M.unsubscribe()},[_.textSelection$,m,i,L,P,u,k,o,R,r,h])},xr=(e,t,n)=>{const r=a.useDependency(N.LexerTreeBuilder),o=d.useRef(!0);d.useEffect(()=>{if(e){const s=setTimeout(()=>{o.current=!1},500);return()=>{clearTimeout(s)}}},[e]),d.useEffect(()=>{if(!o.current&&t){const s=r.checkIfAddBracket(n);t(s===0&&n.startsWith(N.operatorToken.EQUALS),`${n}`)}},[n,t])},Or="univer-sheet-embedding-formula-editor-active",Dr="univer-sheet-embedding-formula-editor-wrap",Ar="univer-sheet-embedding-formula-editor-text",Pr="univer-sheet-embedding-formula-editor-error",Lr="univer-sheet-embedding-formula-editor",wr="univer-sheet-embedding-formula-editor-error-wrap",je={sheetEmbeddingFormulaEditorActive:Or,sheetEmbeddingFormulaEditorWrap:Dr,sheetEmbeddingFormulaEditorText:Ar,sheetEmbeddingFormulaEditorError:Pr,sheetEmbeddingFormulaEditor:Lr,sheetEmbeddingFormulaEditorErrorWrap:wr},kr=(e,t=[],n)=>{const r=a.useDependency(xe.IDescriptionService),[o,s]=d.useState([]),[i,c]=d.useState(""),f=d.useRef(-1),m=Ye({nodes:t}),g=()=>{s([]),c(""),f.current=-1};return d.useEffect(()=>{if(n&&e){const h=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const p=n.getSelectionRanges();if(p.length===1){const u=m.current.nodes,_=p[0];if(_.collapsed){const R=ln(u,_.startOffset-1,!1);f.current=R;const E=u[R];if(E&&typeof E!="string"&&E.nodeType===N.sequenceNodeType.FUNCTION){f.current=R;const I=E.token,y=r.getSearchListByNameFirstLetter(I);s(y),c(I);return}}}f.current=-1,c(""),s(u=>u!=null&&u.length?[]:u)});return()=>{h.unsubscribe()}}},[n,e]),d.useEffect(()=>{e||g()},[e]),{searchList:o,searchText:i,handlerFormulaReplace:h=>{const p=[...m.current.nodes];if(f.current!==-1){const u=p.splice(f.current+1),_=p.pop()||"";let R=(typeof _=="string"?_.length:_.token.length)-h.length;return p.push(h),u[0]!==N.matchToken.OPEN_BRACKET&&(p.push(N.matchToken.OPEN_BRACKET),R--),{text:Ee([...p,...u]),offset:R}}},reset:g}},$r="univer-formula-search-function",jr="univer-formula-search-function-item",Hr="univer-formula-search-function-item-name",Ur="univer-formula-search-function-item-name-light",Wr="univer-formula-search-function-item-desc",Vr="univer-formula-search-function-item-active",Ne={formulaSearchFunction:$r,formulaSearchFunctionItem:jr,formulaSearchFunctionItemName:Hr,formulaSearchFunctionItemNameLight:Ur,formulaSearchFunctionItemDesc:Wr,formulaSearchFunctionItemActive:Vr},Br=()=>{},Kr=d.forwardRef(qr);function qr(e,t){const{isFocus:n,sequenceNodes:r,onSelect:o,editor:s,onClose:i=Br}=e,c=s.getEditorId(),f=a.useDependency(a.IShortcutService),m=a.useDependency(l.ICommandService),{searchList:g,searchText:S,handlerFormulaReplace:h,reset:p}=kr(n,r,s),u=d.useMemo(()=>!!g.length,[g]),_=d.useRef(void 0),[R,E]=d.useState(0),I=d.useRef(!1),[y]=an(c,u,[S,g]),b=Ye({searchList:g,active:R}),x=O=>{const F=h(O);F&&(p(),o(F))};function D(O){I.current&&E(O)}function L(){I.current&&E(-1)}d.useEffect(()=>{if(!g.length)return;const O=`sheet.formula-embedding-editor.search_function.${c}`,F=new l.DisposableCollection,w=M=>{const{searchList:v,active:T}=b.current;switch(M){case a.KeyCode.ARROW_UP:{E(A=>{const j=Math.max(0,A-1);return k(j),j});break}case a.KeyCode.ARROW_DOWN:{E(A=>{const j=Math.min(v.length-1,A+1);return k(j),j});break}case a.KeyCode.TAB:case a.KeyCode.ENTER:{const A=v[T];x(A.name);break}case a.KeyCode.ESC:{p(),i();break}}};return F.add(m.registerCommand({id:O,type:l.CommandType.OPERATION,handler(M,v){const{keyCode:T}=v;w(T)}})),[a.KeyCode.ARROW_UP,a.KeyCode.ARROW_DOWN,a.KeyCode.ENTER,a.KeyCode.ESC,a.KeyCode.TAB].map(M=>({id:O,binding:M,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:M}})).forEach(M=>{F.add(f.registerShortcut(M))}),()=>{F.dispose()}},[g]);function k(O){var Y;const F=(Y=_.current)==null?void 0:Y.querySelectorAll(`.${Ne.formulaSearchFunctionItem}`)[O];if(!F)return;const w=F.parentNode;if(!w)return;const v=w.getBoundingClientRect().top,T=w.offsetHeight,A=F.getBoundingClientRect(),j=A.top,V=A.height;if(j>=0&&j>v&&j-v+V<=T)return;const G=F.offsetTop-(T-V)/2;w.scrollTo({top:G,behavior:"smooth"})}const P=d.useMemo(()=>{let O="";return()=>{clearTimeout(O),I.current=!0,O=setTimeout(()=>{I.current=!1},300)}},[]);return g.length>0&&u&&C.jsx(a.RectPopup,{portal:!0,anchorRect$:y,direction:"vertical",children:C.jsx("ul",{className:Ne.formulaSearchFunction,ref:O=>{_.current=O,t&&(t.current=O)},children:g.map((O,F)=>C.jsxs("li",{className:R===F?`
10
10
  ${Ne.formulaSearchFunctionItem}
11
11
  ${Ne.formulaSearchFunctionItemActive}
12
- `:Ne.formulaSearchFunctionItem,onMouseEnter:()=>O(F),onMouseLeave:P,onMouseMove:L,onClick:()=>{A(N.name),i&&i.focus()},children:[C.jsxs("span",{className:Ne.formulaSearchFunctionItemName,children:[C.jsx("span",{className:Ne.formulaSearchFunctionItemNameLight,children:N.name.substring(0,g.length)}),C.jsx("span",{children:N.name.slice(g.length)})]}),C.jsx("span",{className:Ne.formulaSearchFunctionItemDesc,children:N.desc})]},N.name))})})}const Yr=e=>e.startsWith(b.operatorToken.EQUALS)?e.slice(1):"",ut=()=>{};function un(e){var Nt,Ft;const{errorText:t,initValue:n,unitId:o,subUnitId:r,isFocus:i=!0,isSupportAcrossSheet:s=!1,onFocus:a=ut,onBlur:f=ut,onChange:d,onVerify:h,actions:g,className:m,editorId:v,moveCursor:l=!0,onFormulaSelectingChange:S,keyboradEventConfig:I,onMoveInEditor:y,resetSelectionOnBlur:R=!0,autoScrollbar:_=!0,isSingle:x=!0,disableSelectionOnClick:A=!1,disableContextMenu:O,style:P}=e,k=c.useDependency(te.IEditorService),L=u.useRef(null),N=E.useEvent(d);g&&(g.handleOutClick=(ae,le)=>{L.current&&!L.current.contains(ae.target)&&le()});const F=E.useEvent(S),w=u.useRef(null),M=u.useRef(void 0),p=M.current,[T,D]=u.useState(i),j=u.useRef(null),U=u.useMemo(()=>v!=null?v:c.createInternalEditorID(`${$.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),G=u.useMemo(()=>t!==void 0,[t]),Y=c.useDependency(c.IUniverInstanceService),W=Y.getUnit(U);c.useObservable(W==null?void 0:W.change$);const he=it(),J=c.BuildTextUtils.transform.getPlainText((Ft=(Nt=W==null?void 0:W.getBody())==null?void 0:Nt.dataStream)!=null?Ft:""),ne=u.useMemo(()=>Yr(J),[J]),K=u.useMemo(()=>he(ne),[ne,he]),{isSelecting:re}=Yn(U,T,A),fe=u.useRef(""),oe=c.useDependency(z.IRenderManagerService).getRenderById(U),me=oe==null?void 0:oe.with(te.DocSelectionRenderService),ce=me==null?void 0:me.isFocusing,Ie=u.useMemo(()=>Y.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC),[Y]),de=c.useObservable(Ie),ge=(de==null?void 0:de.getUnitId())===U,Me=u.useRef([]),_e=re;E.useUpdateEffect(()=>{N(J)},[J,N]);const H=Jt("="),B=Et(o,r),X=E.useEvent((ae,le=!0,Te,we)=>{if(!M.current)return;fe.current=ae;const at=he(ae[0]==="="?ae.slice(1):""),ke=H(M.current,at,le,we);Me.current=ke,Te&&B(T?ke:[],M.current)});u.useEffect(()=>{T&&X(J,!1,!0)},[J,T,X]),xr(T,h,J);const Z=Zt(p),Q=rn(T,o,r);u.useEffect(()=>{F(re)},[F,re]),te.useKeyboardEvent(T,I,p),u.useLayoutEffect(()=>{let ae;if(j.current){ae=k.register({autofocus:!0,editorUnitId:U,initialSnapshot:{id:U,body:{dataStream:`${n}\r
13
- `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},j.current);const le=k.getEditor(U);M.current=le,X(n,!1,!0)}return()=>{ae==null||ae.dispose()}},[]),u.useLayoutEffect(()=>{i?(D(i),Z()):(R&&(p==null||p.blur(),Q()),D(i))},[i,p,Z,Q,R]);const{checkScrollBar:se}=te.useResize(p,x,_);_t(T,!!(re&&ge),o,O),tn(T&&l,_e,p,y);const Le=E.useEvent((ae,le,Te)=>{if(!ce)return;const we=le!==-1?[{startOffset:le+1,endOffset:le+1,collapsed:!0}]:void 0;X(`=${ae}`,!0,Te,we),Te&&(Z(),le!==-1&&setTimeout(()=>{const at={startOffset:le+1,endOffset:le+1},ke=p==null?void 0:p.render.with(te.DocBackScrollRenderController);ke==null||ke.scrollToRange({...at,collapsed:!0})},50),se())});Fr(T&&!!(re&&ge),T,re,o,r,K,Me,s,!!_e,p,Le),Tt(T&&!!(re&&ge),o,s,D,f,ut);const ye=ae=>{if(ae){const le=p==null?void 0:p.getSelectionRanges();if(le&&le.length===1){const Te=le[0];if(Te.collapsed){const we=ae.offset;setTimeout(()=>{p==null||p.setSelectionRanges([{startOffset:Te.startOffset-we,endOffset:Te.endOffset-we}])},30)}}Z(),X(`=${ae.text}`)}},Mt=()=>{D(!0),a(),Z()};return C.jsxs("div",{style:P,className:pt(je.sheetEmbeddingFormulaEditor,m),children:[C.jsx("div",{className:pt(je.sheetEmbeddingFormulaEditorWrap,{[je.sheetEmbeddingFormulaEditorActive]:T,[je.sheetEmbeddingFormulaEditorError]:G}),ref:L,children:C.jsx("div",{className:je.sheetEmbeddingFormulaEditorText,ref:j,onMouseUp:Mt})}),t!==void 0?C.jsx("div",{className:je.sheetEmbeddingFormulaEditorErrorWrap,children:t}):null,p?C.jsx(Mr,{editor:p,isFocus:T,formulaText:J,onClose:()=>Z()}):null,p?C.jsx(Kr,{isFocus:T,sequenceNodes:K,onSelect:ye,ref:w,editor:p}):null]})}const zr="sheets-formula-ui.base.config",Pt={};function Gr(e){return e.getContextValue(c.FOCUSING_DOC)&&e.getContextValue(c.FOCUSING_UNIVER_EDITOR)}function fn(e,t=!1){return!t&&!(c.isFormulaString(e==null?void 0:e.f)||c.isFormulaId(e==null?void 0:e.si))?null:typeof(e==null?void 0:e.v)=="string"&&b.ERROR_TYPE_SET.has(e.v)?e.v:null}var Zr=Object.defineProperty,Xr=Object.getOwnPropertyDescriptor,Jr=(e,t,n,o)=>{for(var r=o>1?void 0:o?Xr(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&Zr(t,n,r),r},Ue=(e,t)=>(n,o)=>t(n,o,e);const ft="SHEET_FORMULA_ALERT",Qr={[b.ErrorType.DIV_BY_ZERO]:"divByZero",[b.ErrorType.NAME]:"name",[b.ErrorType.VALUE]:"value",[b.ErrorType.NUM]:"num",[b.ErrorType.NA]:"na",[b.ErrorType.CYCLE]:"cycle",[b.ErrorType.REF]:"ref",[b.ErrorType.SPILL]:"spill",[b.ErrorType.CALC]:"calc",[b.ErrorType.ERROR]:"error",[b.ErrorType.CONNECT]:"connect",[b.ErrorType.NULL]:"null"};let vt=class extends c.Disposable{constructor(e,t,n,o,r,i){super(),this._context=e,this._hoverManagerService=t,this._cellAlertManagerService=n,this._localeService=o,this._formulaDataModel=r,this._zenZoneService=i,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(q.debounceTime(100)).subscribe(e=>{var t,n,o,r,i;if(e){const a=this._context.unit.getActiveSheet();if(!a)return;const f=a.getCell(e.location.row,e.location.col),d=(r=(o=(n=(t=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:t[e.location.unitId])==null?void 0:n[e.location.subUnitId])==null?void 0:o[e.location.row])==null?void 0:r[e.location.col];if(c.isICellData(f)){const h=fn(f,!!d);if(!h){this._hideAlert();return}const g=this._cellAlertManagerService.currentAlert.get(ft),m=(i=g==null?void 0:g.alert)==null?void 0:i.location;if(m&&m.row===e.location.row&&m.col===e.location.col&&m.subUnitId===e.location.subUnitId&&m.unitId===e.location.unitId)return;this._cellAlertManagerService.showAlert({type:$.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${Qr[h]}`),location:e.location,width:200,height:74,key:ft});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(e=>{e&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(ft)}};vt=Jr([Ue(1,c.Inject($.HoverManagerService)),Ue(2,c.Inject($.CellAlertManagerService)),Ue(3,c.Inject(c.LocaleService)),Ue(4,c.Inject(b.FormulaDataModel)),Ue(5,E.IZenZoneService)],vt);var eo=Object.defineProperty,to=Object.getOwnPropertyDescriptor,no=(e,t,n,o)=>{for(var r=o>1?void 0:o?to(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&eo(t,n,r),r},Lt=(e,t)=>(n,o)=>t(n,o,e);let Xe=class extends c.Disposable{constructor(e,t){super(),this._autoFillService=e,this._lexerTreeBuilder=t,this._registerAutoFill()}_registerAutoFill(){const e={type:$.DATA_TYPE.FORMULA,priority:1001,match:t=>c.isFormulaString(t==null?void 0:t.f)||c.isFormulaId(t==null?void 0:t.si),isContinue:(t,n)=>t.type===$.DATA_TYPE.FORMULA,applyFunctions:{[$.APPLY_TYPE.COPY]:(t,n,o,r)=>{const{data:i,index:s}=t;return this._fillCopyFormula(i,n,o,s,r)}}};this._autoFillService.registerRule(e)}_fillCopyFormula(e,t,n,o,r){var f,d;const i=oo(r),s=[],a=new Map;for(let h=1;h<=t;h++){const g=(h-1)%e.length,m=c.Tools.deepClone(e[g]);if(m){const v=((f=e[g])==null?void 0:f.f)||"",l=((d=e[g])==null?void 0:d.si)||"",S=c.isFormulaString(v);if(c.isFormulaId(l))m.si=l,m.f=null,m.v=null,m.p=null,m.t=null,s.push(m);else if(S){let y=a.get(g);if(y)m.si=y,m.f=null,m.v=null,m.p=null,m.t=null;else{y=c.Tools.generateRandomId(6),a.set(g,y);const{offsetX:R,offsetY:_}=ro(i,t,n),x=this._lexerTreeBuilder.moveFormulaRefOffset(v,R,_);m.si=y,m.f=x,m.v=null,m.p=null,m.t=null}s.push(m)}}}return s}};Xe=no([Lt(0,$.IAutoFillService),Lt(1,c.Inject(b.LexerTreeBuilder))],Xe);function ro(e,t,n){let o=0,r=0;switch(n){case c.Direction.UP:r=-e*t;break;case c.Direction.RIGHT:o=e;break;case c.Direction.DOWN:r=e;break;case c.Direction.LEFT:o=-e*t;break}return{offsetX:o,offsetY:r}}function oo(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}var so=Object.defineProperty,io=Object.getOwnPropertyDescriptor,co=(e,t,n,o)=>{for(var r=o>1?void 0:o?io(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&so(t,n,r),r},We=(e,t)=>(n,o)=>t(n,o,e);const ao="default-paste-formula";let Je=class extends c.Disposable{constructor(e,t,n,o,r){super(),this._currentUniverSheet=e,this._lexerTreeBuilder=t,this._sheetClipboardService=n,this._injector=o,this._formulaDataModel=r,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!0)}}_pasteWithFormulaHook(){return{id:ao,priority:10,onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!1)}}_onPasteCells(e,t,n,o,r){var m;if([$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(o.pasteType))return{undos:[],redos:[]};const s=this._currentUniverSheet.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),a=t.unitId||s.getUnitId(),f=t.subUnitId||((m=s.getActiveSheet())==null?void 0:m.getSheetId());if(!a||!f)return{undos:[],redos:[]};const d=t.range,h=n,g={copyType:o.copyType||$.COPY_TYPE.COPY,copyRange:e==null?void 0:e.range,pasteType:o.pasteType};return this._injector.invoke(v=>lo(a,f,d,h,v,g,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};Je=co([We(0,c.IUniverInstanceService),We(1,c.Inject(b.LexerTreeBuilder)),We(2,$.ISheetClipboardService),We(3,c.Inject(c.Injector)),We(4,c.Inject(b.FormulaDataModel))],Je);function lo(e,t,n,o,r,i,s,a,f=!1,d){const h=[],g=[],m=uo(e,t,n,o,i,s,a,d),v={unitId:e,subUnitId:t,cellValue:m.getData()};h.push({id:V.SetRangeValuesMutation.id,params:v});const l=V.SetRangeValuesUndoMutationFactory(r,v);return g.push({id:V.SetRangeValuesMutation.id,params:l}),{undos:g,redos:h}}function uo(e,t,n,o,r,i,s,a){return a?r.pasteType===$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?ho(e,t,n,o,s,a):r.pasteType===$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?mo(e,t,n,o,i,s,a):go(e,t,n,o,i,s,a):fo(e,t,n,o,s)}function fo(e,t,n,o,r){const i=new c.ObjectMatrix,s=r.getSheetFormulaData(e,t);return o.forValue((a,f,d)=>{var v;const h=n.rows[a],g=n.cols[f],m={};c.isFormulaString(d.v)?(m.v=null,m.f=`${d.v}`,m.si=null,m.p=null,i.setValue(h,g,m)):(v=s==null?void 0:s[h])!=null&&v[g]&&(m.v=d.v,m.f=null,m.si=null,m.p=null,i.setValue(h,g,m))}),i}function ho(e,t,n,o,r,i){var d,h;const s=new c.ObjectMatrix,a=(h=(d=r.getArrayFormulaCellData())==null?void 0:d[i.unitId])==null?void 0:h[i.subUnitId],f=r.getSheetFormulaData(e,t);return o.forValue((g,m,v)=>{var _,x;const l=i.range.rows[g%i.range.rows.length],S=i.range.cols[m%i.range.cols.length],I=n.rows[g],y=n.cols[m],R={};if(c.isFormulaString(v.f)||c.isFormulaId(v.si))R.v=v.v,R.f=null,R.si=null,R.p=null,s.setValue(I,y,R);else if((_=a==null?void 0:a[l])!=null&&_[S]){const A=a[l][S];R.v=A.v,R.f=null,R.si=null,R.p=null,s.setValue(I,y,R)}else if((x=f==null?void 0:f[I])!=null&&x[y]){if(R.v=v.v,R.f=null,R.si=null,R.p=null,v.p){const A=dn(v);A&&(R.v=A)}s.setValue(I,y,R)}}),s}function mo(e,t,n,o,r,i,s){const a=new c.ObjectMatrix,f=new Map;return o.forValue((d,h,g)=>{const m=n.rows[d],v=n.cols[h],l={};if(c.isFormulaId(g.si)){if(s.unitId!==e||s.subUnitId!==t){const S=i.getFormulaStringByCell(s.range.rows[d%s.range.rows.length],s.range.cols[h%s.range.cols.length],s.subUnitId,s.unitId),I=n.cols[h]-s.range.cols[h%s.range.cols.length],y=n.rows[d]-s.range.rows[d%s.range.rows.length],R=r.moveFormulaRefOffset(S||"",I,y);l.si=null,l.f=R}else l.si=g.si,l.f=null;l.v=null,l.p=null,a.setValue(m,v,l)}else if(c.isFormulaString(g.f)){const S=`${d%s.range.rows.length}_${h%s.range.cols.length}`;let I=f.get(S);if(I)l.si=I,l.f=null;else{I=c.Tools.generateRandomId(6),f.set(S,I);const y=n.cols[h]-s.range.cols[h%s.range.cols.length],R=n.rows[d]-s.range.rows[d%s.range.rows.length],_=r.moveFormulaRefOffset(g.f||"",y,R);l.si=I,l.f=_}l.v=null,l.p=null,a.setValue(m,v,l)}else{if(l.v=g.v,l.f=null,l.si=null,l.p=null,g.p){const S=dn(g);S&&(l.v=S)}a.setValue(m,v,l)}}),a}function go(e,t,n,o,r,i,s){const a=new c.ObjectMatrix,f=new Map,d=i.getSheetFormulaData(e,t);return o.forValue((h,g,m)=>{var I;const v=n.rows[h],l=n.cols[g],S={};if(c.isFormulaId(m.si)){if(s.unitId!==e||s.subUnitId!==t){const y=i.getFormulaStringByCell(s.range.rows[h%s.range.rows.length],s.range.cols[g%s.range.cols.length],s.subUnitId,s.unitId),R=n.cols[g]-s.range.cols[g%s.range.cols.length],_=n.rows[h]-s.range.rows[h%s.range.rows.length],x=r.moveFormulaRefOffset(y||"",R,_);S.si=null,S.f=x}else S.si=m.si,S.f=null;S.v=null,S.p=null,a.setValue(v,l,S)}else if(c.isFormulaString(m.f)){const y=`${h%s.range.rows.length}_${g%s.range.cols.length}`;let R=f.get(y);if(R)S.si=R,S.f=null;else{R=c.Tools.generateRandomId(6),f.set(y,R);const _=n.cols[g]-s.range.cols[g%s.range.cols.length],x=n.rows[h]-s.range.rows[h%s.range.rows.length],A=r.moveFormulaRefOffset(m.f||"",_,x);S.si=R,S.f=A}S.v=null,S.p=null,a.setValue(v,l,S)}else(I=d==null?void 0:d[v])!=null&&I[l]&&(S.v=m.v,S.f=null,S.si=null,S.p=m.p,a.setValue(v,l,S))}),a}function dn(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return;const n=t.dataStream;return n.substring(n.length-2,n.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n}}var po=Object.defineProperty,So=Object.getOwnPropertyDescriptor,vo=(e,t,n,o)=>{for(var r=o>1?void 0:o?So(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&po(t,n,r),r},De=(e,t)=>(n,o)=>t(n,o,e);let Qe=class extends c.Disposable{constructor(t,n,o,r,i,s,a,f){super();ee(this,"_previousShape");ee(this,"_skeleton");this._context=t,this._sheetInterceptorService=n,this._formulaDataModel=o,this._themeService=r,this._renderManagerService=i,this._sheetSkeletonManagerService=s,this._commandService=a,this._logService=f,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{var n,o;if(t==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:r}=t,i=(o=(n=this._skeleton)==null?void 0:n.worksheet)==null?void 0:o.getSheetId();if(this._changeRuntime(r),i!==r.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:s,sheetId:a}=t;this._updateArrayFormulaRangeShape(s,a)}}}))}_changeRuntime(t){this._skeleton=t}_initInterceptorEditorStart(){this.disposeWithMe(c.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(V.BEFORE_CELL_EDIT,{handler:(t,n,o)=>{var l,S,I,y;const{row:r,col:i,unitId:s,subUnitId:a,worksheet:f}=n,d=this._formulaDataModel.getArrayFormulaRange(),h=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),t==null)return o(t);let g=null;const m=this._formulaDataModel.getFormulaStringByCell(r,i,a,s);if(m!==null&&(g={f:m}),t.v!=null&&t.v!==""&&((I=(S=(l=h[s])==null?void 0:l[a])==null?void 0:S[r])==null?void 0:I[i])==null)return g?{...t,...g}:o(t);const v=(y=d==null?void 0:d[s])==null?void 0:y[a];return v!=null&&(g=this._displayArrayFormulaRangeShape(v,r,i,s,a,f,g)),g?{...t,...g}:o(t)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{(t.id===b.SetFormulaCalculationResultMutation.id||t.id===b.SetArrayFormulaDataMutation.id&&n&&n.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{V.SetWorksheetRowAutoHeightMutation.id===t.id&&requestIdleCallback(()=>{const n=t.params,{unitId:o,subUnitId:r,rowsAutoHeightInfo:i}=n;this._refreshArrayFormulaRangeShapeByRow(o,r,i)})}))}_displayArrayFormulaRangeShape(t,n,o,r,i,s,a){const f=this._formulaDataModel.getSheetFormulaData(r,i);return new c.ObjectMatrix(t).forValue((d,h,g)=>{var I;if(g==null)return!0;const{startRow:m,startColumn:v,endRow:l,endColumn:S}=g;if(d===n&&h===o)return this._createArrayFormulaRangeShape(g,r),!1;if(n>=m&&n<=l&&o>=v&&o<=S){const y=s.getCell(m,v);if((y==null?void 0:y.v)===b.ErrorType.SPILL)return;const R=(I=f==null?void 0:f[d])==null?void 0:I[h];return R==null||R.f==null?!0:(a==null&&(a={f:R.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(g,r),!1)}}),a}_createArrayFormulaRangeShape(t,n){const o=this._renderManagerService.getRenderById(n),r=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!o||!r)return;const{scene:i}=o;if(!i)return;const s=this._themeService.getCurrentTheme(),a={range:t,primary:null,style:{strokeWidth:1,stroke:s.hyacinth700,fill:new c.ColorKit(s.colorWhite).setAlpha(0).toString(),widgets:{}}},f=$.attachSelectionWithCoord(a,r),{rowHeaderWidth:d,columnHeaderHeight:h}=r,g=new $.SelectionControl(i,$.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:h});g.updateRangeBySelectionWithCoord(f),g.setEvent(!1),this._previousShape=g}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(t,n){if(this._previousShape){const{startRow:o,endRow:r,startColumn:i,endColumn:s}=this._previousShape.getRange(),a={startRow:o,endRow:r,startColumn:i,endColumn:s};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(a,t)}}_checkCurrentSheet(t,n){const o=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!o)return!1;const r=o.worksheet;return r?r.unitId===t&&r.getSheetId()===n:!1}_updateArrayFormulaRangeShape(t,n){this._checkCurrentSheet(t,n)&&this._previousShape&&this._refreshArrayFormulaRangeShape(t)}_refreshArrayFormulaRangeShapeByRow(t,n,o){if(!this._checkCurrentSheet(t,n)||!this._previousShape)return;const{startRow:r,endRow:i,startColumn:s,endColumn:a}=this._previousShape.getRange();for(let f=0;f<o.length;f++){const{row:d}=o[f];if(r>=d){const h={startRow:r,endRow:i,startColumn:s,endColumn:a};this._refreshArrayFormulaRangeShape(t,h);break}}}};Qe=vo([De(1,c.Inject(V.SheetInterceptorService)),De(2,c.Inject(b.FormulaDataModel)),De(3,c.Inject(c.ThemeService)),De(4,z.IRenderManagerService),De(5,c.Inject($.SheetSkeletonManagerService)),De(6,c.ICommandService),De(7,c.ILogService)],Qe);var Co=Object.defineProperty,Ro=Object.getOwnPropertyDescriptor,Io=(e,t,n,o)=>{for(var r=o>1?void 0:o?Ro(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&Co(t,n,r),r},wt=(e,t)=>(n,o)=>t(n,o,e);const Eo={tl:{size:6,color:"#409f11"}};let et=class extends c.RxDisposable{constructor(e,t){super(),this._sheetInterceptorService=e,this._formulaDataModel=t,this.disposeWithMe(this._sheetInterceptorService.intercept(V.INTERCEPTOR_POINT.CELL_CONTENT,{effect:c.InterceptorEffectEnum.Style,handler:(n,o,r)=>{var a,f,d,h;const i=(h=(d=(f=(a=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:a[o.unitId])==null?void 0:f[o.subUnitId])==null?void 0:d[o.row])==null?void 0:h[o.col];return fn(n,!!i)?r({...n,markers:{...n==null?void 0:n.markers,...Eo}}):r(n)},priority:10}))}};et=Io([wt(0,c.Inject(V.SheetInterceptorService)),wt(1,c.Inject(b.FormulaDataModel))],et);function _o(){const e=c.useDependency(xe.TriggerCalculationController),t=c.useDependency(c.ICommandService),n=c.useObservable(e.progress$),o=u.useCallback(()=>{t.executeCommand(b.SetFormulaCalculationStopMutation.id)},[t]),r=u.useCallback(()=>{e.clearProgress()},[e]);return C.jsx(E.ProgressBar,{progress:n,onTerminate:o,onClearProgress:r})}const yo=(e,t=100)=>{u.useEffect(()=>{let n=null;const o=()=>{n===null&&(n=window.setTimeout(()=>{e(),n=null},t))};return window.addEventListener("scroll",o),window.addEventListener("resize",o),()=>{n!==null&&clearTimeout(n),window.removeEventListener("scroll",o),window.removeEventListener("resize",o)}},[e,t])},To="univer-formula-help-function",bo="univer-formula-help-function-title",Mo="univer-formula-help-function-title-icons",No="univer-formula-help-function-title-icon",Fo="univer-formula-help-function-content",xo="univer-formula-help-function-content-inner",Oo="univer-formula-help-function-content-params",Do="univer-formula-help-function-content-params-title",Ao="univer-formula-help-function-content-params-detail",Po="univer-formula-help-function-active",Lo="univer-formula-help-decorator",wo="univer-formula-help-param",ko="univer-formula-help-param-prefix",$o="univer-formula-help-param-item",jo="univer-formula-help-param-active",ie={formulaHelpFunction:To,formulaHelpFunctionTitle:bo,formulaHelpFunctionTitleIcons:Mo,formulaHelpFunctionTitleIcon:No,formulaHelpFunctionContent:Fo,formulaHelpFunctionContentInner:xo,formulaHelpFunctionContentParams:Oo,formulaHelpFunctionContentParamsTitle:Do,formulaHelpFunctionContentParamsDetail:Ao,formulaHelpFunctionActive:Po,formulaHelpDecorator:Lo,formulaHelpParam:wo,formulaHelpParamPrefix:ko,formulaHelpParamItem:$o,formulaHelpParamActive:jo};function Ho(){const[e,t]=u.useState(!1),[n,o]=u.useState(!0),[r,i]=u.useState(!0),[s,a]=u.useState(0),[f,d]=u.useState([0,0]),[h,g]=u.useState({left:0,top:0}),[m,v]=u.useState(null),l=c.useDependency(ze),S=c.useDependency(c.LocaleService),I=S.t("formula.prompt.required"),y=S.t("formula.prompt.optional"),R=c.useDependency(c.IUniverInstanceService),_=c.useDependency(te.IEditorService),x=c.useDependency(E.ISidebarService),A=c.useInjector();yo(O),u.useEffect(()=>{const N=l.help$.subscribe(w=>{const{visible:M,paramIndex:p,functionInfo:T}=w;if(!M){t(M);return}const D=P();if(D==null)return;const{left:j,top:U,height:G}=D;T.description===""&&T.functionParameter.length===0||(d([j,U+G]),a(p),v(T),g({left:j,top:U}),t(M))}),F=x.scrollEvent$.pipe(q.throttleTime(100)).subscribe(O);return()=>{N==null||N.unsubscribe(),F.unsubscribe()}},[]);function O(){if(!r)return;const N=P();if(N==null)return;const{left:F,top:w,height:M}=N;d([F,w+M])}function P(){const N=R.getCurrentUniverDocInstance();if(!N)return;const F=N.getUnitId();if(!_.isEditor(F))return;const w=_.getEditor(F);return w==null?void 0:w.getBoundingClientRect()}function k(N){a(N)}function L(){i(!r),A.get(E.ILayoutService).focus()}return C.jsx(C.Fragment,{children:r?C.jsx(pe.Popup,{visible:e,offset:f,children:m?C.jsxs("div",{className:ie.formulaHelpFunction,children:[C.jsxs("div",{className:ie.formulaHelpFunctionTitle,children:[C.jsx(Uo,{prefix:m.functionName,value:m.functionParameter,active:s,onClick:k}),C.jsxs("div",{className:ie.formulaHelpFunctionTitleIcons,children:[C.jsx("div",{className:ie.formulaHelpFunctionTitleIcon,style:{transform:n?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>o(!n),children:C.jsx(It,{})}),C.jsx("div",{className:ie.formulaHelpFunctionTitleIcon,onClick:L,children:C.jsx(st,{})})]})]}),C.jsx("div",{className:ie.formulaHelpFunctionContent,style:{height:n?"unset":0,padding:n?"revert-layer":0},children:C.jsxs("div",{className:ie.formulaHelpFunctionContentInner,children:[C.jsx(dt,{title:S.t("formula.prompt.helpExample"),value:`${m.functionName}(${m.functionParameter.map(N=>N.example).join(",")})`}),C.jsx(dt,{title:S.t("formula.prompt.helpAbstract"),value:m.description}),m&&m.functionParameter&&m.functionParameter.map((N,F)=>C.jsx(dt,{className:s===F?ie.formulaHelpFunctionActive:"",title:N.name,value:`${N.require?I:y} ${N.detail}`},F))]})})]}):C.jsx(C.Fragment,{})}):e?C.jsx("div",{className:ie.formulaHelpDecorator,onClick:()=>i(!r),style:{left:h.left-24,top:h.top},children:C.jsx(qt,{})}):C.jsx(C.Fragment,{})})}const dt=e=>C.jsxs("div",{className:ie.formulaHelpFunctionContentParams,children:[C.jsx("div",{className:`
12
+ `:Ne.formulaSearchFunctionItem,onMouseEnter:()=>D(F),onMouseLeave:L,onMouseMove:P,onClick:()=>{x(O.name),s&&s.focus()},children:[C.jsxs("span",{className:Ne.formulaSearchFunctionItemName,children:[C.jsx("span",{className:Ne.formulaSearchFunctionItemNameLight,children:O.name.substring(0,S.length)}),C.jsx("span",{children:O.name.slice(S.length)})]}),C.jsx("span",{className:Ne.formulaSearchFunctionItemDesc,children:O.desc})]},O.name))})})}const Yr=e=>e.startsWith(N.operatorToken.EQUALS)?e.slice(1):"",ut=()=>{};function un(e){var Nt,Ft;const{errorText:t,initValue:n,unitId:r,subUnitId:o,isFocus:s=!0,isSupportAcrossSheet:i=!1,onFocus:c=ut,onBlur:f=ut,onChange:m,onVerify:g,actions:S,className:h,editorId:p,moveCursor:u=!0,onFormulaSelectingChange:_,keyboradEventConfig:R,onMoveInEditor:E,resetSelectionOnBlur:I=!0,autoScrollbar:y=!0,isSingle:b=!0,disableSelectionOnClick:x=!1,disableContextMenu:D,style:L}=e,k=a.useDependency(te.IEditorService),P=d.useRef(null),O=a.useEvent(m);S&&(S.handleOutClick=(ae,le)=>{P.current&&!P.current.contains(ae.target)&&le()});const F=a.useEvent(_),w=d.useRef(null),M=d.useRef(void 0),v=M.current,[T,A]=d.useState(s),j=d.useRef(null),V=d.useMemo(()=>p!=null?p:l.createInternalEditorID(`${$.EMBEDDING_FORMULA_EDITOR}-${l.generateRandomId(4)}`),[]),G=d.useMemo(()=>t!==void 0,[t]),Y=a.useDependency(l.IUniverInstanceService),U=Y.getUnit(V);a.useObservable(U==null?void 0:U.change$);const he=it(),J=l.BuildTextUtils.transform.getPlainText((Ft=(Nt=U==null?void 0:U.getBody())==null?void 0:Nt.dataStream)!=null?Ft:""),ne=d.useMemo(()=>Yr(J),[J]),K=d.useMemo(()=>he(ne),[ne,he]),{isSelecting:re}=Yn({unitId:r,subUnitId:o,editorId:V,isFocus:T,disableOnClick:x}),fe=d.useRef(""),oe=a.useDependency(z.IRenderManagerService).getRenderById(V),me=oe==null?void 0:oe.with(te.DocSelectionRenderService),ce=me==null?void 0:me.isFocusing,Ie=d.useMemo(()=>Y.getCurrentTypeOfUnit$(l.UniverInstanceType.UNIVER_DOC),[Y]),de=a.useObservable(Ie),ge=(de==null?void 0:de.getUnitId())===V,Me=d.useRef([]),_e=re;a.useUpdateEffect(()=>{O(J)},[J,O]);const H=Jt("="),W=Et(r,o),X=a.useEvent((ae,le=!0,be,we)=>{if(!M.current)return;fe.current=ae;const at=he(ae[0]==="="?ae.slice(1):""),ke=H(M.current,at,le,we);Me.current=ke,be&&W(T?ke:[],M.current)});d.useEffect(()=>{T&&X(J,!1,!0)},[J,T,X]),xr(T,g,J);const Z=Zt(v),Q=rn(T,r,o);d.useEffect(()=>{F(re)},[F,re]),te.useKeyboardEvent(T,R,v),d.useLayoutEffect(()=>{let ae;if(j.current){ae=k.register({autofocus:!0,editorUnitId:V,initialSnapshot:{id:V,body:{dataStream:`${n}\r
13
+ `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},j.current);const le=k.getEditor(V);M.current=le,X(n,!1,!0)}return()=>{ae==null||ae.dispose()}},[]),d.useLayoutEffect(()=>{s?(A(s),Z()):(I&&(v==null||v.blur(),Q()),A(s))},[s,v,Z,Q,I]);const{checkScrollBar:se}=te.useResize(v,b,y);_t(T,!!(re&&ge),r,D),tn(T&&u,_e,v,E);const Le=a.useEvent((ae,le,be)=>{if(!ce)return;const we=le!==-1?[{startOffset:le+1,endOffset:le+1,collapsed:!0}]:void 0;X(`=${ae}`,!0,be,we),be&&(Z(),le!==-1&&setTimeout(()=>{const at={startOffset:le+1,endOffset:le+1},ke=v==null?void 0:v.render.with(te.DocBackScrollRenderController);ke==null||ke.scrollToRange({...at,collapsed:!0})},50),se())});Fr(T&&!!(re&&ge),T,re,r,o,K,Me,i,!!_e,v,Le),bt(T&&!!(re&&ge),r,i,A,f,ut);const ye=ae=>{if(ae){const le=v==null?void 0:v.getSelectionRanges();if(le&&le.length===1){const be=le[0];if(be.collapsed){const we=ae.offset;setTimeout(()=>{v==null||v.setSelectionRanges([{startOffset:be.startOffset-we,endOffset:be.endOffset-we}])},30)}}Z(),X(`=${ae.text}`)}},Mt=()=>{A(!0),c(),Z()};return C.jsxs("div",{style:L,className:pt(je.sheetEmbeddingFormulaEditor,h),children:[C.jsx("div",{className:pt(je.sheetEmbeddingFormulaEditorWrap,{[je.sheetEmbeddingFormulaEditorActive]:T,[je.sheetEmbeddingFormulaEditorError]:G}),ref:P,children:C.jsx("div",{className:je.sheetEmbeddingFormulaEditorText,ref:j,onMouseUp:Mt})}),t!==void 0?C.jsx("div",{className:je.sheetEmbeddingFormulaEditorErrorWrap,children:t}):null,v?C.jsx(Mr,{editor:v,isFocus:T,formulaText:J,onClose:()=>Z()}):null,v?C.jsx(Kr,{isFocus:T,sequenceNodes:K,onSelect:ye,ref:w,editor:v}):null]})}const zr="sheets-formula-ui.base.config",Pt={};function Gr(e){return e.getContextValue(l.FOCUSING_DOC)&&e.getContextValue(l.FOCUSING_UNIVER_EDITOR)}function fn(e,t=!1){return!t&&!(l.isFormulaString(e==null?void 0:e.f)||l.isFormulaId(e==null?void 0:e.si))?null:typeof(e==null?void 0:e.v)=="string"&&N.ERROR_TYPE_SET.has(e.v)?e.v:null}var Zr=Object.defineProperty,Xr=Object.getOwnPropertyDescriptor,Jr=(e,t,n,r)=>{for(var o=r>1?void 0:r?Xr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&Zr(t,n,o),o},Ue=(e,t)=>(n,r)=>t(n,r,e);const ft="SHEET_FORMULA_ALERT",Qr={[N.ErrorType.DIV_BY_ZERO]:"divByZero",[N.ErrorType.NAME]:"name",[N.ErrorType.VALUE]:"value",[N.ErrorType.NUM]:"num",[N.ErrorType.NA]:"na",[N.ErrorType.CYCLE]:"cycle",[N.ErrorType.REF]:"ref",[N.ErrorType.SPILL]:"spill",[N.ErrorType.CALC]:"calc",[N.ErrorType.ERROR]:"error",[N.ErrorType.CONNECT]:"connect",[N.ErrorType.NULL]:"null"};let vt=class extends l.Disposable{constructor(e,t,n,r,o,s){super(),this._context=e,this._hoverManagerService=t,this._cellAlertManagerService=n,this._localeService=r,this._formulaDataModel=o,this._zenZoneService=s,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(q.debounceTime(100)).subscribe(e=>{var t,n,r,o,s;if(e){const c=this._context.unit.getActiveSheet();if(!c)return;const f=c.getCell(e.location.row,e.location.col),m=(o=(r=(n=(t=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:t[e.location.unitId])==null?void 0:n[e.location.subUnitId])==null?void 0:r[e.location.row])==null?void 0:o[e.location.col];if(l.isICellData(f)){const g=fn(f,!!m);if(!g){this._hideAlert();return}const S=this._cellAlertManagerService.currentAlert.get(ft),h=(s=S==null?void 0:S.alert)==null?void 0:s.location;if(h&&h.row===e.location.row&&h.col===e.location.col&&h.subUnitId===e.location.subUnitId&&h.unitId===e.location.unitId)return;this._cellAlertManagerService.showAlert({type:$.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${Qr[g]}`),location:e.location,width:200,height:74,key:ft});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(e=>{e&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(ft)}};vt=Jr([Ue(1,l.Inject($.HoverManagerService)),Ue(2,l.Inject($.CellAlertManagerService)),Ue(3,l.Inject(l.LocaleService)),Ue(4,l.Inject(N.FormulaDataModel)),Ue(5,a.IZenZoneService)],vt);var eo=Object.defineProperty,to=Object.getOwnPropertyDescriptor,no=(e,t,n,r)=>{for(var o=r>1?void 0:r?to(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&eo(t,n,o),o},Lt=(e,t)=>(n,r)=>t(n,r,e);let Xe=class extends l.Disposable{constructor(e,t){super(),this._autoFillService=e,this._lexerTreeBuilder=t,this._registerAutoFill()}_registerAutoFill(){const e={type:$.DATA_TYPE.FORMULA,priority:1001,match:t=>l.isFormulaString(t==null?void 0:t.f)||l.isFormulaId(t==null?void 0:t.si),isContinue:(t,n)=>t.type===$.DATA_TYPE.FORMULA,applyFunctions:{[$.APPLY_TYPE.COPY]:(t,n,r,o)=>{const{data:s,index:i}=t;return this._fillCopyFormula(s,n,r,i,o)}}};this._autoFillService.registerRule(e)}_fillCopyFormula(e,t,n,r,o){var f,m;const s=oo(o),i=[],c=new Map;for(let g=1;g<=t;g++){const S=(g-1)%e.length,h=l.Tools.deepClone(e[S]);if(h){const p=((f=e[S])==null?void 0:f.f)||"",u=((m=e[S])==null?void 0:m.si)||"",_=l.isFormulaString(p);if(l.isFormulaId(u))h.si=u,h.f=null,h.v=null,h.p=null,h.t=null,i.push(h);else if(_){let E=c.get(S);if(E)h.si=E,h.f=null,h.v=null,h.p=null,h.t=null;else{E=l.Tools.generateRandomId(6),c.set(S,E);const{offsetX:I,offsetY:y}=ro(s,t,n),b=this._lexerTreeBuilder.moveFormulaRefOffset(p,I,y);h.si=E,h.f=b,h.v=null,h.p=null,h.t=null}i.push(h)}}}return i}};Xe=no([Lt(0,$.IAutoFillService),Lt(1,l.Inject(N.LexerTreeBuilder))],Xe);function ro(e,t,n){let r=0,o=0;switch(n){case l.Direction.UP:o=-e*t;break;case l.Direction.RIGHT:r=e;break;case l.Direction.DOWN:o=e;break;case l.Direction.LEFT:r=-e*t;break}return{offsetX:r,offsetY:o}}function oo(e){let t=0;for(const n in e)e[n].forEach(r=>{t+=r.data.length});return t}var so=Object.defineProperty,io=Object.getOwnPropertyDescriptor,co=(e,t,n,r)=>{for(var o=r>1?void 0:r?io(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&so(t,n,o),o},We=(e,t)=>(n,r)=>t(n,r,e);const ao="default-paste-formula";let Je=class extends l.Disposable{constructor(e,t,n,r,o){super(),this._currentUniverSheet=e,this._lexerTreeBuilder=t,this._sheetClipboardService=n,this._injector=r,this._formulaDataModel=o,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(e,t,n,r)=>this._onPasteCells(e,t,n,r,!0)}}_pasteWithFormulaHook(){return{id:ao,priority:10,onPasteCells:(e,t,n,r)=>this._onPasteCells(e,t,n,r,!1)}}_onPasteCells(e,t,n,r,o){var h;if([$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(r.pasteType))return{undos:[],redos:[]};const i=this._currentUniverSheet.getCurrentUnitForType(l.UniverInstanceType.UNIVER_SHEET),c=t.unitId||i.getUnitId(),f=t.subUnitId||((h=i.getActiveSheet())==null?void 0:h.getSheetId());if(!c||!f)return{undos:[],redos:[]};const m=t.range,g=n,S={copyType:r.copyType||$.COPY_TYPE.COPY,copyRange:e==null?void 0:e.range,pasteType:r.pasteType};return this._injector.invoke(p=>lo(c,f,m,g,p,S,this._lexerTreeBuilder,this._formulaDataModel,o,e))}};Je=co([We(0,l.IUniverInstanceService),We(1,l.Inject(N.LexerTreeBuilder)),We(2,$.ISheetClipboardService),We(3,l.Inject(l.Injector)),We(4,l.Inject(N.FormulaDataModel))],Je);function lo(e,t,n,r,o,s,i,c,f=!1,m){const g=[],S=[],h=uo(e,t,n,r,s,i,c,m),p={unitId:e,subUnitId:t,cellValue:h.getData()};g.push({id:B.SetRangeValuesMutation.id,params:p});const u=B.SetRangeValuesUndoMutationFactory(o,p);return S.push({id:B.SetRangeValuesMutation.id,params:u}),{undos:S,redos:g}}function uo(e,t,n,r,o,s,i,c){return c?o.pasteType===$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?ho(e,t,n,r,i,c):o.pasteType===$.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?mo(e,t,n,r,s,i,c):go(e,t,n,r,o.copyType,s,i,c):fo(e,t,n,r,i)}function fo(e,t,n,r,o){const s=new l.ObjectMatrix,i=o.getSheetFormulaData(e,t);return r.forValue((c,f,m)=>{var p;const g=n.rows[c],S=n.cols[f],h={};l.isFormulaString(m.v)?(h.v=null,h.f=`${m.v}`,h.si=null,h.p=null,s.setValue(g,S,h)):(p=i==null?void 0:i[g])!=null&&p[S]&&(h.v=m.v,h.f=null,h.si=null,h.p=null,s.setValue(g,S,h))}),s}function ho(e,t,n,r,o,s){var m,g;const i=new l.ObjectMatrix,c=(g=(m=o.getArrayFormulaCellData())==null?void 0:m[s.unitId])==null?void 0:g[s.subUnitId],f=o.getSheetFormulaData(e,t);return r.forValue((S,h,p)=>{var y,b;const u=s.range.rows[S%s.range.rows.length],_=s.range.cols[h%s.range.cols.length],R=n.rows[S],E=n.cols[h],I={};if(l.isFormulaString(p.f)||l.isFormulaId(p.si))I.v=p.v,I.f=null,I.si=null,I.p=null,i.setValue(R,E,I);else if((y=c==null?void 0:c[u])!=null&&y[_]){const x=c[u][_];I.v=x.v,I.f=null,I.si=null,I.p=null,i.setValue(R,E,I)}else if((b=f==null?void 0:f[R])!=null&&b[E]){if(I.v=p.v,I.f=null,I.si=null,I.p=null,p.p){const x=dn(p);x&&(I.v=x)}i.setValue(R,E,I)}}),i}function mo(e,t,n,r,o,s,i){const c=new l.ObjectMatrix,f=new Map;return r.forValue((m,g,S)=>{const h=n.rows[m],p=n.cols[g],u={};if(l.isFormulaId(S.si)){if(i.unitId!==e||i.subUnitId!==t){const _=s.getFormulaStringByCell(i.range.rows[m%i.range.rows.length],i.range.cols[g%i.range.cols.length],i.subUnitId,i.unitId),R=n.cols[g]-i.range.cols[g%i.range.cols.length],E=n.rows[m]-i.range.rows[m%i.range.rows.length],I=o.moveFormulaRefOffset(_||"",R,E);u.si=null,u.f=I}else u.si=S.si,u.f=null;u.v=null,u.p=null,c.setValue(h,p,u)}else if(l.isFormulaString(S.f)){const _=`${m%i.range.rows.length}_${g%i.range.cols.length}`;let R=f.get(_);if(R)u.si=R,u.f=null;else{R=l.Tools.generateRandomId(6),f.set(_,R);const E=n.cols[g]-i.range.cols[g%i.range.cols.length],I=n.rows[m]-i.range.rows[m%i.range.rows.length],y=o.moveFormulaRefOffset(S.f||"",E,I);u.si=R,u.f=y}u.v=null,u.p=null,c.setValue(h,p,u)}else{if(u.v=S.v,u.f=null,u.si=null,u.p=null,S.p){const _=dn(S);_&&(u.v=_)}c.setValue(h,p,u)}}),c}function go(e,t,n,r,o,s,i,c){const f=new l.ObjectMatrix,m=new Map,g=i.getSheetFormulaData(e,t),S=[];return o===$.COPY_TYPE.CUT?r.forValue((h,p,u)=>{const _=n.rows[h],R=n.cols[p],E={};if(l.isFormulaId(u.si)){if(l.isFormulaString(u.f))S.push(u.si),E.f=u.f,E.si=u.si;else if(S.includes(u.si))E.f=null,E.si=u.si;else{const I=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[p%c.range.cols.length],c.subUnitId,c.unitId);E.f=I,E.si=null}E.v=null,E.p=null,f.setValue(_,R,E)}else l.isFormulaString(u.f)&&(E.f=u.f,E.si=null,E.v=null,E.p=null,f.setValue(_,R,E))}):r.forValue((h,p,u)=>{var I;const _=n.rows[h],R=n.cols[p],E={};if(l.isFormulaId(u.si)){if(c.unitId!==e||c.subUnitId!==t){const y=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[p%c.range.cols.length],c.subUnitId,c.unitId),b=n.cols[p]-c.range.cols[p%c.range.cols.length],x=n.rows[h]-c.range.rows[h%c.range.rows.length],D=s.moveFormulaRefOffset(y||"",b,x);E.si=null,E.f=D}else E.si=u.si,E.f=null;E.v=null,E.p=null,f.setValue(_,R,E)}else if(l.isFormulaString(u.f)){const y=`${h%c.range.rows.length}_${p%c.range.cols.length}`;let b=m.get(y);if(b)E.si=b,E.f=null;else{b=l.Tools.generateRandomId(6),m.set(y,b);const x=n.cols[p]-c.range.cols[p%c.range.cols.length],D=n.rows[h]-c.range.rows[h%c.range.rows.length],L=s.moveFormulaRefOffset(u.f||"",x,D);E.si=b,E.f=L}E.v=null,E.p=null,f.setValue(_,R,E)}else(I=g==null?void 0:g[_])!=null&&I[R]&&(E.v=u.v,E.f=null,E.si=null,E.p=u.p,f.setValue(_,R,E))}),S.length>0&&new l.ObjectMatrix(g).forValue((h,p,u)=>{if(!(c.range.rows.includes(h)&&c.range.cols.includes(p))&&!(n.rows.includes(h)&&n.cols.includes(p))&&S.includes(u==null?void 0:u.si)){const _=i.getFormulaStringByCell(h,p,c.subUnitId,c.unitId);f.setValue(h,p,{f:_,si:null,v:null,p:null})}}),f}function dn(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return;const n=t.dataStream;return n.substring(n.length-2,n.length)===l.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n}}var po=Object.defineProperty,So=Object.getOwnPropertyDescriptor,vo=(e,t,n,r)=>{for(var o=r>1?void 0:r?So(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&po(t,n,o),o},De=(e,t)=>(n,r)=>t(n,r,e);let Qe=class extends l.Disposable{constructor(t,n,r,o,s,i,c,f){super();ee(this,"_previousShape");ee(this,"_skeleton");this._context=t,this._sheetInterceptorService=n,this._formulaDataModel=r,this._themeService=o,this._renderManagerService=s,this._sheetSkeletonManagerService=i,this._commandService=c,this._logService=f,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{var n,r;if(t==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:o}=t,s=(r=(n=this._skeleton)==null?void 0:n.worksheet)==null?void 0:r.getSheetId();if(this._changeRuntime(o),s!==o.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:c}=t;this._updateArrayFormulaRangeShape(i,c)}}}))}_changeRuntime(t){this._skeleton=t}_initInterceptorEditorStart(){this.disposeWithMe(l.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(B.BEFORE_CELL_EDIT,{handler:(t,n,r)=>{var u,_,R,E;const{row:o,col:s,unitId:i,subUnitId:c,worksheet:f}=n,m=this._formulaDataModel.getArrayFormulaRange(),g=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),t==null)return r(t);let S=null;const h=this._formulaDataModel.getFormulaStringByCell(o,s,c,i);if(h!==null&&(S={f:h}),t.v!=null&&t.v!==""&&((R=(_=(u=g[i])==null?void 0:u[c])==null?void 0:_[o])==null?void 0:R[s])==null)return S?{...t,...S}:r(t);const p=(E=m==null?void 0:m[i])==null?void 0:E[c];return p!=null&&(S=this._displayArrayFormulaRangeShape(p,o,s,i,c,f,S)),S?{...t,...S}:r(t)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{(t.id===N.SetFormulaCalculationResultMutation.id||t.id===N.SetArrayFormulaDataMutation.id&&n&&n.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{B.SetWorksheetRowAutoHeightMutation.id===t.id&&requestIdleCallback(()=>{const n=t.params,{unitId:r,subUnitId:o,rowsAutoHeightInfo:s}=n;this._refreshArrayFormulaRangeShapeByRow(r,o,s)})}))}_displayArrayFormulaRangeShape(t,n,r,o,s,i,c){const f=this._formulaDataModel.getSheetFormulaData(o,s);return new l.ObjectMatrix(t).forValue((m,g,S)=>{var R;if(S==null)return!0;const{startRow:h,startColumn:p,endRow:u,endColumn:_}=S;if(m===n&&g===r)return this._createArrayFormulaRangeShape(S,o),!1;if(n>=h&&n<=u&&r>=p&&r<=_){const E=i.getCell(h,p);if((E==null?void 0:E.v)===N.ErrorType.SPILL)return;const I=(R=f==null?void 0:f[m])==null?void 0:R[g];return I==null||I.f==null?!0:(c==null&&(c={f:I.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(S,o),!1)}}),c}_createArrayFormulaRangeShape(t,n){const r=this._renderManagerService.getRenderById(n),o=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!r||!o)return;const{scene:s}=r;if(!s)return;const i=this._themeService.getCurrentTheme(),c={range:t,primary:null,style:{strokeWidth:1,stroke:i.hyacinth700,fill:new l.ColorKit(i.colorWhite).setAlpha(0).toString(),widgets:{}}},f=$.attachSelectionWithCoord(c,o),{rowHeaderWidth:m,columnHeaderHeight:g}=o,S=new $.SelectionControl(s,$.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:m,columnHeaderHeight:g});S.updateRangeBySelectionWithCoord(f),S.setEvent(!1),this._previousShape=S}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(t,n){if(this._previousShape){const{startRow:r,endRow:o,startColumn:s,endColumn:i}=this._previousShape.getRange(),c={startRow:r,endRow:o,startColumn:s,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(c,t)}}_checkCurrentSheet(t,n){const r=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!r)return!1;const o=r.worksheet;return o?o.unitId===t&&o.getSheetId()===n:!1}_updateArrayFormulaRangeShape(t,n){this._checkCurrentSheet(t,n)&&this._previousShape&&this._refreshArrayFormulaRangeShape(t)}_refreshArrayFormulaRangeShapeByRow(t,n,r){if(!this._checkCurrentSheet(t,n)||!this._previousShape)return;const{startRow:o,endRow:s,startColumn:i,endColumn:c}=this._previousShape.getRange();for(let f=0;f<r.length;f++){const{row:m}=r[f];if(o>=m){const g={startRow:o,endRow:s,startColumn:i,endColumn:c};this._refreshArrayFormulaRangeShape(t,g);break}}}};Qe=vo([De(1,l.Inject(B.SheetInterceptorService)),De(2,l.Inject(N.FormulaDataModel)),De(3,l.Inject(l.ThemeService)),De(4,z.IRenderManagerService),De(5,l.Inject($.SheetSkeletonManagerService)),De(6,l.ICommandService),De(7,l.ILogService)],Qe);var Co=Object.defineProperty,Ro=Object.getOwnPropertyDescriptor,Io=(e,t,n,r)=>{for(var o=r>1?void 0:r?Ro(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&Co(t,n,o),o},wt=(e,t)=>(n,r)=>t(n,r,e);const Eo={tl:{size:6,color:"#409f11"}};let et=class extends l.RxDisposable{constructor(e,t){super(),this._sheetInterceptorService=e,this._formulaDataModel=t,this.disposeWithMe(this._sheetInterceptorService.intercept(B.INTERCEPTOR_POINT.CELL_CONTENT,{effect:l.InterceptorEffectEnum.Style,handler:(n,r,o)=>{var c,f,m,g;const s=(g=(m=(f=(c=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:c[r.unitId])==null?void 0:f[r.subUnitId])==null?void 0:m[r.row])==null?void 0:g[r.col];return fn(n,!!s)?o({...n,markers:{...n==null?void 0:n.markers,...Eo}}):o(n)},priority:10}))}};et=Io([wt(0,l.Inject(B.SheetInterceptorService)),wt(1,l.Inject(N.FormulaDataModel))],et);function _o(){const e=a.useDependency(xe.TriggerCalculationController),t=a.useDependency(l.ICommandService),n=a.useObservable(e.progress$),r=d.useCallback(()=>{t.executeCommand(N.SetFormulaCalculationStopMutation.id)},[t]),o=d.useCallback(()=>{e.clearProgress()},[e]);return C.jsx(a.ProgressBar,{progress:n,onTerminate:r,onClearProgress:o})}const yo=(e,t=100)=>{d.useEffect(()=>{let n=null;const r=()=>{n===null&&(n=window.setTimeout(()=>{e(),n=null},t))};return window.addEventListener("scroll",r),window.addEventListener("resize",r),()=>{n!==null&&clearTimeout(n),window.removeEventListener("scroll",r),window.removeEventListener("resize",r)}},[e,t])},bo="univer-formula-help-function",To="univer-formula-help-function-title",Mo="univer-formula-help-function-title-icons",No="univer-formula-help-function-title-icon",Fo="univer-formula-help-function-content",xo="univer-formula-help-function-content-inner",Oo="univer-formula-help-function-content-params",Do="univer-formula-help-function-content-params-title",Ao="univer-formula-help-function-content-params-detail",Po="univer-formula-help-function-active",Lo="univer-formula-help-decorator",wo="univer-formula-help-param",ko="univer-formula-help-param-prefix",$o="univer-formula-help-param-item",jo="univer-formula-help-param-active",ie={formulaHelpFunction:bo,formulaHelpFunctionTitle:To,formulaHelpFunctionTitleIcons:Mo,formulaHelpFunctionTitleIcon:No,formulaHelpFunctionContent:Fo,formulaHelpFunctionContentInner:xo,formulaHelpFunctionContentParams:Oo,formulaHelpFunctionContentParamsTitle:Do,formulaHelpFunctionContentParamsDetail:Ao,formulaHelpFunctionActive:Po,formulaHelpDecorator:Lo,formulaHelpParam:wo,formulaHelpParamPrefix:ko,formulaHelpParamItem:$o,formulaHelpParamActive:jo};function Ho(){const[e,t]=d.useState(!1),[n,r]=d.useState(!0),[o,s]=d.useState(!0),[i,c]=d.useState(0),[f,m]=d.useState([0,0]),[g,S]=d.useState({left:0,top:0}),[h,p]=d.useState(null),u=a.useDependency(ze),_=a.useDependency(l.LocaleService),R=_.t("formula.prompt.required"),E=_.t("formula.prompt.optional"),I=a.useDependency(l.IUniverInstanceService),y=a.useDependency(te.IEditorService),b=a.useDependency(a.ISidebarService),x=a.useInjector();yo(D),d.useEffect(()=>{const O=u.help$.subscribe(w=>{const{visible:M,paramIndex:v,functionInfo:T}=w;if(!M){t(M);return}const A=L();if(A==null)return;const{left:j,top:V,height:G}=A;T.description===""&&T.functionParameter.length===0||(m([j,V+G]),c(v),p(T),S({left:j,top:V}),t(M))}),F=b.scrollEvent$.pipe(q.throttleTime(100)).subscribe(D);return()=>{O==null||O.unsubscribe(),F.unsubscribe()}},[]);function D(){if(!o)return;const O=L();if(O==null)return;const{left:F,top:w,height:M}=O;m([F,w+M])}function L(){const O=I.getCurrentUniverDocInstance();if(!O)return;const F=O.getUnitId();if(!y.isEditor(F))return;const w=y.getEditor(F);return w==null?void 0:w.getBoundingClientRect()}function k(O){c(O)}function P(){s(!o),x.get(a.ILayoutService).focus()}return C.jsx(C.Fragment,{children:o?C.jsx(pe.Popup,{visible:e,offset:f,children:h?C.jsxs("div",{className:ie.formulaHelpFunction,children:[C.jsxs("div",{className:ie.formulaHelpFunctionTitle,children:[C.jsx(Uo,{prefix:h.functionName,value:h.functionParameter,active:i,onClick:k}),C.jsxs("div",{className:ie.formulaHelpFunctionTitleIcons,children:[C.jsx("div",{className:ie.formulaHelpFunctionTitleIcon,style:{transform:n?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>r(!n),children:C.jsx(It,{})}),C.jsx("div",{className:ie.formulaHelpFunctionTitleIcon,onClick:P,children:C.jsx(st,{})})]})]}),C.jsx("div",{className:ie.formulaHelpFunctionContent,style:{height:n?"unset":0,padding:n?"revert-layer":0},children:C.jsxs("div",{className:ie.formulaHelpFunctionContentInner,children:[C.jsx(dt,{title:_.t("formula.prompt.helpExample"),value:`${h.functionName}(${h.functionParameter.map(O=>O.example).join(",")})`}),C.jsx(dt,{title:_.t("formula.prompt.helpAbstract"),value:h.description}),h&&h.functionParameter&&h.functionParameter.map((O,F)=>C.jsx(dt,{className:i===F?ie.formulaHelpFunctionActive:"",title:O.name,value:`${O.require?R:E} ${O.detail}`},F))]})})]}):C.jsx(C.Fragment,{})}):e?C.jsx("div",{className:ie.formulaHelpDecorator,onClick:()=>s(!o),style:{left:g.left-24,top:g.top},children:C.jsx(qt,{})}):C.jsx(C.Fragment,{})})}const dt=e=>C.jsxs("div",{className:ie.formulaHelpFunctionContentParams,children:[C.jsx("div",{className:`
14
14
  ${ie.formulaHelpFunctionContentParamsTitle}
15
15
  ${e.className}
16
- `,children:e.title}),C.jsx("div",{className:ie.formulaHelpFunctionContentParamsDetail,children:e.value})]}),Uo=e=>{const{prefix:t,value:n,active:o,onClick:r}=e;return C.jsxs("div",{className:ie.formulaHelpParam,children:[C.jsxs("span",{className:ie.formulaHelpParamPrefix,children:[t,"("]}),n&&n.map((i,s)=>C.jsxs("span",{className:ie.formulaHelpParamItem,children:[C.jsx("span",{className:o===s?ie.formulaHelpFunctionActive:ie.formulaHelpParamActive,onClick:()=>r(s),children:bt(i)}),s===n.length-1?"":","]},s)),")"]})},Wo="univer-formula-search-function",Bo="univer-formula-search-function-item",Vo="univer-formula-search-function-item-name",Ko="univer-formula-search-function-item-name-light",qo="univer-formula-search-function-item-desc",Yo="univer-formula-search-function-item-active",Fe={formulaSearchFunction:Wo,formulaSearchFunctionItem:Bo,formulaSearchFunctionItemName:Vo,formulaSearchFunctionItemNameLight:Ko,formulaSearchFunctionItemDesc:qo,formulaSearchFunctionItemActive:Yo};function zo(){const[e,t]=u.useState(!1),[n,o]=u.useState(0),[r,i]=u.useState([0,0]),[s,a]=u.useState([]),[f,d]=u.useState(""),h=u.useRef(null),g=c.useDependency(ze),m=c.useDependency(c.IUniverInstanceService),v=c.useDependency(te.IEditorService);u.useEffect(()=>{let R=[],_=0;const x=g.search$.subscribe(P=>{const{visible:k,searchText:L,searchList:N}=P;if(!k){t(k);return}const F=l();if(F==null)return;const{left:w,top:M,height:p}=F;d(L),a(N),R=N,i([w,M+p]),t(k),o(0),_=0}),A=g.navigate$.subscribe(P=>{const{direction:k}=P;if(k===c.Direction.UP){let L=_-1;L=L<0?R.length-1:L,o(L),_=L}else if(k===c.Direction.DOWN){let L=_+1;L=L>=R.length?0:L,o(L),_=L}y(_)}),O=g.accept$.subscribe(P=>{const k=R[_].name;g.acceptFormulaName(k)});return()=>{x==null||x.unsubscribe(),A==null||A.unsubscribe(),O==null||O.unsubscribe()}},[]);function l(){const _=m.getCurrentUniverDocInstance().getUnitId();if(!v.isEditor(_))return;const x=v.getEditor(_);return x==null?void 0:x.getBoundingClientRect()}function S(R){o(R)}function I(){o(-1)}function y(R){var w;const _=(w=h.current)==null?void 0:w.querySelectorAll(`.${Fe.formulaSearchFunctionItem}`)[R];if(!_)return;const x=_.parentNode;if(!x)return;const O=x.getBoundingClientRect().top,P=x.offsetHeight,k=_.getBoundingClientRect(),L=k.top,N=k.height;if(L>=0&&L>O&&L-O+N<=P)return;const F=_.offsetTop-(P-N)/2;x.scrollTo({top:F,behavior:"smooth"})}return s.length>0&&C.jsx(pe.Popup,{visible:e,offset:r,children:C.jsx("ul",{className:Fe.formulaSearchFunction,ref:h,children:s.map((R,_)=>C.jsxs("li",{className:n===_?`
16
+ `,children:e.title}),C.jsx("div",{className:ie.formulaHelpFunctionContentParamsDetail,children:e.value})]}),Uo=e=>{const{prefix:t,value:n,active:r,onClick:o}=e;return C.jsxs("div",{className:ie.formulaHelpParam,children:[C.jsxs("span",{className:ie.formulaHelpParamPrefix,children:[t,"("]}),n&&n.map((s,i)=>C.jsxs("span",{className:ie.formulaHelpParamItem,children:[C.jsx("span",{className:r===i?ie.formulaHelpFunctionActive:ie.formulaHelpParamActive,onClick:()=>o(i),children:Tt(s)}),i===n.length-1?"":","]},i)),")"]})},Wo="univer-formula-search-function",Vo="univer-formula-search-function-item",Bo="univer-formula-search-function-item-name",Ko="univer-formula-search-function-item-name-light",qo="univer-formula-search-function-item-desc",Yo="univer-formula-search-function-item-active",Fe={formulaSearchFunction:Wo,formulaSearchFunctionItem:Vo,formulaSearchFunctionItemName:Bo,formulaSearchFunctionItemNameLight:Ko,formulaSearchFunctionItemDesc:qo,formulaSearchFunctionItemActive:Yo};function zo(){const[e,t]=d.useState(!1),[n,r]=d.useState(0),[o,s]=d.useState([0,0]),[i,c]=d.useState([]),[f,m]=d.useState(""),g=d.useRef(null),S=a.useDependency(ze),h=a.useDependency(l.IUniverInstanceService),p=a.useDependency(te.IEditorService);d.useEffect(()=>{let I=[],y=0;const b=S.search$.subscribe(L=>{const{visible:k,searchText:P,searchList:O}=L;if(!k){t(k);return}const F=u();if(F==null)return;const{left:w,top:M,height:v}=F;m(P),c(O),I=O,s([w,M+v]),t(k),r(0),y=0}),x=S.navigate$.subscribe(L=>{const{direction:k}=L;if(k===l.Direction.UP){let P=y-1;P=P<0?I.length-1:P,r(P),y=P}else if(k===l.Direction.DOWN){let P=y+1;P=P>=I.length?0:P,r(P),y=P}E(y)}),D=S.accept$.subscribe(L=>{const k=I[y].name;S.acceptFormulaName(k)});return()=>{b==null||b.unsubscribe(),x==null||x.unsubscribe(),D==null||D.unsubscribe()}},[]);function u(){const y=h.getCurrentUniverDocInstance().getUnitId();if(!p.isEditor(y))return;const b=p.getEditor(y);return b==null?void 0:b.getBoundingClientRect()}function _(I){r(I)}function R(){r(-1)}function E(I){var w;const y=(w=g.current)==null?void 0:w.querySelectorAll(`.${Fe.formulaSearchFunctionItem}`)[I];if(!y)return;const b=y.parentNode;if(!b)return;const D=b.getBoundingClientRect().top,L=b.offsetHeight,k=y.getBoundingClientRect(),P=k.top,O=k.height;if(P>=0&&P>D&&P-D+O<=L)return;const F=y.offsetTop-(L-O)/2;b.scrollTo({top:F,behavior:"smooth"})}return i.length>0&&C.jsx(pe.Popup,{visible:e,offset:o,children:C.jsx("ul",{className:Fe.formulaSearchFunction,ref:g,children:i.map((I,y)=>C.jsxs("li",{className:n===y?`
17
17
  ${Fe.formulaSearchFunctionItem}
18
18
  ${Fe.formulaSearchFunctionItemActive}
19
- `:Fe.formulaSearchFunctionItem,onMouseEnter:()=>S(_),onMouseLeave:I,onClick:()=>g.acceptFormulaName(R.name),children:[C.jsxs("span",{className:Fe.formulaSearchFunctionItemName,children:[C.jsx("span",{className:Fe.formulaSearchFunctionItemNameLight,children:R.name.substring(0,f.length)}),C.jsx("span",{children:R.name.slice(f.length)})]}),C.jsx("span",{className:Fe.formulaSearchFunctionItemDesc,children:R.desc})]},_))})})}function Go(){return C.jsxs(C.Fragment,{children:[C.jsx(zo,{}),C.jsx(Ho,{})]})}const Zo="univer-formula-more-functions",Xo="univer-formula-more-functions-operation",kt={formulaMoreFunctions:Zo,formulaMoreFunctionsOperation:Xo};function hn(e){const{prefix:t,value:n}=e;return C.jsxs("div",{children:[C.jsxs("span",{children:[t,"("]}),n&&n.map((o,r)=>C.jsxs("span",{children:[C.jsx("span",{children:bt(o)}),r===n.length-1?"":","]},r)),")"]})}const Jo="univer-formula-function-params",Qo="univer-formula-function-params-title",es="univer-formula-function-params-detail",ht={formulaFunctionParams:Jo,formulaFunctionParamsTitle:Qo,formulaFunctionParamsDetail:es};function Ke(e){const{className:t,value:n,title:o}=e;return C.jsxs("div",{className:ht.formulaFunctionParams,children:[C.jsx("div",{className:`
19
+ `:Fe.formulaSearchFunctionItem,onMouseEnter:()=>_(y),onMouseLeave:R,onClick:()=>S.acceptFormulaName(I.name),children:[C.jsxs("span",{className:Fe.formulaSearchFunctionItemName,children:[C.jsx("span",{className:Fe.formulaSearchFunctionItemNameLight,children:I.name.substring(0,f.length)}),C.jsx("span",{children:I.name.slice(f.length)})]}),C.jsx("span",{className:Fe.formulaSearchFunctionItemDesc,children:I.desc})]},y))})})}function Go(){return C.jsxs(C.Fragment,{children:[C.jsx(zo,{}),C.jsx(Ho,{})]})}const Zo="univer-formula-more-functions",Xo="univer-formula-more-functions-operation",kt={formulaMoreFunctions:Zo,formulaMoreFunctionsOperation:Xo};function hn(e){const{prefix:t,value:n}=e;return C.jsxs("div",{children:[C.jsxs("span",{children:[t,"("]}),n&&n.map((r,o)=>C.jsxs("span",{children:[C.jsx("span",{children:Tt(r)}),o===n.length-1?"":","]},o)),")"]})}const Jo="univer-formula-function-params",Qo="univer-formula-function-params-title",es="univer-formula-function-params-detail",ht={formulaFunctionParams:Jo,formulaFunctionParamsTitle:Qo,formulaFunctionParamsDetail:es};function Ke(e){const{className:t,value:n,title:r}=e;return C.jsxs("div",{className:ht.formulaFunctionParams,children:[C.jsx("div",{className:`
20
20
  ${ht.formulaFunctionParamsTitle}
21
21
  ${t}
22
- `,children:o}),C.jsx("div",{className:ht.formulaFunctionParamsDetail,children:n})]})}const ts="univer-formula-input-params-list",ns="univer-formula-input-params-list-item-name",rs="univer-formula-input-params-list-item-selector",Be={formulaInputParamsList:ts,formulaInputParamsListItemName:ns,formulaInputParamsListItemSelector:rs};function os(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;u.useState([]);const[o,r]=u.useState(t.functionParameter),[i,s]=u.useState(-1);return C.jsxs("div",{className:Be.formulaInputParams,children:[C.jsx("div",{className:Be.formulaInputParamsList,children:o.map((a,f)=>C.jsxs("div",{children:[C.jsx("div",{className:Be.formulaInputParamsListItemName,children:a.name}),C.jsx("div",{className:Be.formulaInputParamsListItemSelector})]},f))}),C.jsx("div",{className:Be.formulaInputParamsInfo,children:C.jsx(Ke,{title:i===-1?C.jsx(hn,{prefix:t.functionName,value:o}):o[i].name,value:i===-1?t.description:o[i].detail})})]})}const ss="univer-formula-select-function-select",is="univer-formula-select-function-result",cs="univer-formula-select-function-result-item",as="univer-formula-select-function-result-item-name-light",ls="univer-formula-select-function-result-item-selected",us="univer-formula-select-function-result-item-active",fs="univer-formula-select-function-content",be={formulaSelectFunctionSelect:ss,formulaSelectFunctionResult:is,formulaSelectFunctionResultItem:cs,formulaSelectFunctionResultItemNameLight:as,formulaSelectFunctionResultItemSelected:ls,formulaSelectFunctionResultItemActive:us,formulaSelectFunctionContent:fs};function ds(e){const{onChange:t}=e,n="-1",[o,r]=u.useState(""),[i,s]=u.useState([]),[a,f]=u.useState(0),[d,h]=u.useState(n),[g,m]=u.useState(0),[v,l]=u.useState(null),S=c.useDependency(xe.IDescriptionService),I=c.useDependency(c.LocaleService),y=c.useDependency(E.ISidebarService),R=c.useObservable(y.sidebarOptions$),_=ar(b.FunctionType,I);_.unshift({label:I.t("formula.moreFunctions.allFunctions"),value:n});const x=I.t("formula.prompt.required"),A=I.t("formula.prompt.optional");u.useEffect(()=>{k(n)},[]),u.useEffect(()=>{P(0)},[i]),u.useEffect(()=>{R!=null&&R.visible&&(r(""),s([]),f(0),h(n),m(0),l(null),k(n))},[R]);const O=M=>{if(o.trim()==="")return M;const p=new RegExp(`(${o.toLocaleUpperCase()})`);return M.split(p).filter(Boolean).map((D,j)=>D.match(p)?C.jsx("span",{className:be.formulaSelectFunctionResultItemNameLight,children:D},j):D)},P=M=>{if(i.length===0){l(null);return}m(M);const p=S.getFunctionInfo(i[M].name);if(!p){l(null);return}l(p),t(p)};function k(M){h(M);const p=S.getSearchListByType(+M);s(p)}function L(M){r(M);const p=S.getSearchListByName(M);s(p)}function N(M){if(M.stopPropagation(),M.key==="ArrowDown"){const p=a+1;f(p===i.length?0:p)}else if(M.key==="ArrowUp"){const p=a-1;f(p===-1?i.length-1:p)}else M.key==="Enter"&&P(a)}const F=M=>{f(M)},w=()=>{f(-1)};return C.jsxs("div",{children:[C.jsxs("div",{className:be.formulaSelectFunctionSelect,children:[C.jsx(pe.Select,{value:d,options:_,onChange:k}),C.jsx(pe.Input,{placeholder:I.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:N,value:o,onChange:L,size:"large",allowClear:!0})]}),C.jsx("ul",{className:be.formulaSelectFunctionResult,onKeyDown:N,tabIndex:-1,children:i.map(({name:M},p)=>C.jsxs("li",{className:a===p?`
23
- ${be.formulaSelectFunctionResultItem}
24
- ${be.formulaSelectFunctionResultItemActive}
25
- `:be.formulaSelectFunctionResultItem,onMouseEnter:()=>F(p),onMouseLeave:w,onClick:()=>P(p),children:[g===p&&C.jsx(Vt,{className:be.formulaSelectFunctionResultItemSelected}),C.jsx("span",{className:be.formulaSelectFunctionResultItemName,children:O(M)})]},p))}),v&&C.jsxs("div",{className:be.formulaSelectFunctionContent,children:[C.jsx(Ke,{title:v.functionName,value:v.description}),C.jsx(Ke,{title:I.t("formula.moreFunctions.syntax"),value:C.jsx(hn,{prefix:v.functionName,value:v.functionParameter})}),C.jsx(Ke,{title:I.t("formula.prompt.helpExample"),value:`${v.functionName}(${v.functionParameter.map(M=>M.example).join(",")})`}),v.functionParameter&&v.functionParameter.map((M,p)=>C.jsx(Ke,{title:M.name,value:`${M.require?x:A} ${M.detail}`},p))]})]})}function hs(){const e=$.useActiveWorkbook(),[t,n]=u.useState(!0),[o,r]=u.useState(!1),[i,s]=u.useState(null),a=c.useDependency($.IEditorBridgeService),f=c.useDependency(c.LocaleService),d=c.useDependency(te.IEditorService),h=c.useDependency(c.IUniverInstanceService);function g(){n(!t),r(!o)}function m(){const v=V.getSheetCommandTarget(h);if(!v)return;a.changeVisible({visible:!0,unitId:v.unitId,eventType:z.DeviceInputEventType.Dblclick});const l=d.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),S=d.getEditor(c.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),I=`=${i==null?void 0:i.functionName}(`;l==null||l.replaceText(I),S==null||S.replaceText(I,!1)}return C.jsxs("div",{className:kt.formulaMoreFunctions,children:[t&&C.jsx(ds,{onChange:s}),o&&C.jsx(os,{functionInfo:i,onChange:()=>{}}),C.jsxs("div",{className:kt.formulaMoreFunctionsOperation,children:[o&&C.jsx(pe.Button,{type:"primary",size:"small",onClick:g,children:f.t("formula.moreFunctions.next")}),o&&C.jsx(pe.Button,{size:"small",onClick:g,children:f.t("formula.moreFunctions.prev")}),t&&!!e&&C.jsx(pe.Button,{type:"primary",size:"small",onClick:m,children:f.t("formula.moreFunctions.confirm")})]})]})}function ms(e){return{id:rt.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:E.MenuItemType.SELECTOR,selections:[{label:"SUM",value:"SUM",icon:"SumSingle"},{label:"AVERAGE",value:"AVERAGE",icon:"AvgSingle"},{label:"COUNT",value:"COUNT",icon:"CntSingle"},{label:"MAX",value:"MAX",icon:"MaxSingle"},{label:"MIN",value:"MIN",icon:"MinSingle"}],hidden$:E.getMenuHiddenObservable(e,c.UniverInstanceType.UNIVER_SHEET),disabled$:$.getCurrentRangeDisable$(e,{workbookTypes:[V.WorkbookEditablePermission],worksheetTypes:[V.WorksheetEditPermission,V.WorksheetSetCellValuePermission],rangeTypes:[V.RangeProtectionPermissionEditPoint]})}}function gs(e){return{id:ot.id,title:"formula.insert.more",type:E.MenuItemType.BUTTON}}function ps(e){return e.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(q.switchMap(o=>o&&e.get(E.IClipboardInterfaceService)?new q.Observable(i=>i.next(!e.get(E.IClipboardInterfaceService).supportClipboard)):q.of(!0)))}function Ss(e){return{id:nt.id,type:E.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:ps(e).pipe(q.combineLatestWith($.getCurrentRangeDisable$(e,{workbookTypes:[V.WorkbookEditablePermission],rangeTypes:[V.RangeProtectionPermissionEditPoint],worksheetTypes:[V.WorksheetSetCellValuePermission,V.WorksheetEditPermission]})),q.map(([t,n])=>t||n))}}const vs={[E.RibbonStartGroup.FORMULAS_INSERT]:{[rt.id]:{order:1,menuItemFactory:ms,[ot.id]:{order:1,menuItemFactory:gs}}},[$.PASTE_SPECIAL_MENU_ID]:{[nt.id]:{order:4,menuItemFactory:Ss}}},Cs="meta_key_ctrl_And_Shift",ct=[E.KeyCode.ARROW_DOWN,E.KeyCode.ARROW_UP,E.KeyCode.ARROW_LEFT,E.KeyCode.ARROW_RIGHT],Rs=[...ct,E.KeyCode.ENTER,E.KeyCode.TAB,E.KeyCode.ESC];function Is(){const e=[];for(const t of Rs)e.push({id:Pe.id,binding:t,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t}});return e}function Es(){const e=[];for(const t of ct)e.push({id:Pe.id,binding:t|E.MetaKeys.SHIFT,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,metaKey:E.MetaKeys.SHIFT}});return e}function _s(){const e=[];for(const t of ct)e.push({id:Pe.id,binding:t|E.MetaKeys.CTRL_COMMAND,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,metaKey:E.MetaKeys.CTRL_COMMAND}});return e}function ys(){const e=[];for(const t of ct)e.push({id:Pe.id,binding:t|E.MetaKeys.SHIFT|E.MetaKeys.CTRL_COMMAND,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,metaKey:Cs}});return e}const Ts={id:Rt.id,binding:E.KeyCode.F4,preconditions:e=>$.whenFormulaEditorActivated(e)};function bs(){const e=[];for(const t of[E.KeyCode.ENTER,E.KeyCode.TAB,E.KeyCode.ARROW_DOWN,E.KeyCode.ARROW_UP])e.push({id:Pe.id,binding:t,preconditions:n=>Gr(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}var Ms=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,Fs=(e,t,n,o)=>{for(var r=o>1?void 0:o?Ns(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&Ms(t,n,r),r},Ae=(e,t)=>(n,o)=>t(n,o,e);let tt=class extends c.Disposable{constructor(e,t,n,o,r,i,s){super(),this._injector=e,this._menuManagerService=t,this._commandService=n,this._shortcutService=o,this._uiPartsService=r,this._renderManagerService=i,this._componentManager=s,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(vs)}_registerCommands(){[nt,rt,ot,Wt,jt,Pe,Rt].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_registerShortcuts(){[...Is(),...Es(),..._s(),...ys(),...bs(),Ts].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(E.BuiltInUIPart.CONTENT,()=>c.connectInjector(Go,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent($.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(_o,this._injector))),this._componentManager.register(Ut,hs)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[Qe]))}};tt=Fs([Ae(0,c.Inject(c.Injector)),Ae(1,E.IMenuManagerService),Ae(2,c.ICommandService),Ae(3,E.IShortcutService),Ae(4,E.IUIPartsService),Ae(5,z.IRenderManagerService),Ae(6,c.Inject(E.ComponentManager))],tt);var mn=Object.defineProperty,xs=Object.getOwnPropertyDescriptor,Os=(e,t,n)=>t in e?mn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ds=(e,t,n,o)=>{for(var r=o>1?void 0:o?xs(t,n):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(o?s(t,n,r):s(r))||r);return o&&r&&mn(t,n,r),r},mt=(e,t)=>(n,o)=>t(n,o,e),gn=(e,t,n)=>Os(e,typeof t!="symbol"?t+"":t,n);exports.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(t=Pt,n,o,r){super(),this._config=t,this._injector=n,this._renderManagerService=o,this._configService=r;const{menu:i,...s}=c.merge(Pt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(zr,s)}onStarting(){const t=this._injector;[[ze,{useClass:gt}],[tt],[Xe],[Je],[Qe],[et]].forEach(r=>t.add(r));const o=this._injector.get(E.ComponentManager);o.register($.RANGE_SELECTOR_COMPONENT_KEY,cn),o.register($.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,un)}onRendered(){[[exports.RefSelectionsRenderService],[vt]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[tt],[Je],[et]])}onSteady(){this._injector.get(Xe)}};gn(exports.UniverSheetsFormulaUIPlugin,"pluginName",Ht);gn(exports.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=Ds([c.DependentOn(b.UniverFormulaEnginePlugin,xe.UniverSheetsFormulaPlugin),mt(1,c.Inject(c.Injector)),mt(2,z.IRenderManagerService),mt(3,c.IConfigService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=$t;exports.FormulaEditor=un;exports.HelpFunctionOperation=jt;exports.InsertFunctionOperation=rt;exports.MoreFunctionsOperation=ot;exports.RangeSelector=cn;exports.ReferenceAbsoluteOperation=Rt;exports.SearchFunctionOperation=Wt;exports.SelectEditorFormulaOperation=Pe;exports.SheetOnlyPasteFormulaCommand=nt;
22
+ `,children:r}),C.jsx("div",{className:ht.formulaFunctionParamsDetail,children:n})]})}const ts="univer-formula-input-params-list",ns="univer-formula-input-params-list-item-name",rs="univer-formula-input-params-list-item-selector",Ve={formulaInputParamsList:ts,formulaInputParamsListItemName:ns,formulaInputParamsListItemSelector:rs};function os(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;d.useState([]);const[r,o]=d.useState(t.functionParameter),[s,i]=d.useState(-1);return C.jsxs("div",{className:Ve.formulaInputParams,children:[C.jsx("div",{className:Ve.formulaInputParamsList,children:r.map((c,f)=>C.jsxs("div",{children:[C.jsx("div",{className:Ve.formulaInputParamsListItemName,children:c.name}),C.jsx("div",{className:Ve.formulaInputParamsListItemSelector})]},f))}),C.jsx("div",{className:Ve.formulaInputParamsInfo,children:C.jsx(Ke,{title:s===-1?C.jsx(hn,{prefix:t.functionName,value:r}):r[s].name,value:s===-1?t.description:r[s].detail})})]})}const ss="univer-formula-select-function-select",is="univer-formula-select-function-result",cs="univer-formula-select-function-result-item",as="univer-formula-select-function-result-item-name-light",ls="univer-formula-select-function-result-item-selected",us="univer-formula-select-function-result-item-active",fs="univer-formula-select-function-content",Te={formulaSelectFunctionSelect:ss,formulaSelectFunctionResult:is,formulaSelectFunctionResultItem:cs,formulaSelectFunctionResultItemNameLight:as,formulaSelectFunctionResultItemSelected:ls,formulaSelectFunctionResultItemActive:us,formulaSelectFunctionContent:fs};function ds(e){const{onChange:t}=e,n="-1",[r,o]=d.useState(""),[s,i]=d.useState([]),[c,f]=d.useState(0),[m,g]=d.useState(n),[S,h]=d.useState(0),[p,u]=d.useState(null),_=a.useDependency(xe.IDescriptionService),R=a.useDependency(l.LocaleService),E=a.useDependency(a.ISidebarService),I=a.useObservable(E.sidebarOptions$),y=ar(N.FunctionType,R);y.unshift({label:R.t("formula.moreFunctions.allFunctions"),value:n});const b=R.t("formula.prompt.required"),x=R.t("formula.prompt.optional");d.useEffect(()=>{k(n)},[]),d.useEffect(()=>{L(0)},[s]),d.useEffect(()=>{I!=null&&I.visible&&(o(""),i([]),f(0),g(n),h(0),u(null),k(n))},[I]);const D=M=>{if(r.trim()==="")return M;const v=new RegExp(`(${r.toLocaleUpperCase()})`);return M.split(v).filter(Boolean).map((A,j)=>A.match(v)?C.jsx("span",{className:Te.formulaSelectFunctionResultItemNameLight,children:A},j):A)},L=M=>{if(s.length===0){u(null);return}h(M);const v=_.getFunctionInfo(s[M].name);if(!v){u(null);return}u(v),t(v)};function k(M){g(M);const v=_.getSearchListByType(+M);i(v)}function P(M){o(M);const v=_.getSearchListByName(M);i(v)}function O(M){if(M.stopPropagation(),M.key==="ArrowDown"){const v=c+1;f(v===s.length?0:v)}else if(M.key==="ArrowUp"){const v=c-1;f(v===-1?s.length-1:v)}else M.key==="Enter"&&L(c)}const F=M=>{f(M)},w=()=>{f(-1)};return C.jsxs("div",{children:[C.jsxs("div",{className:Te.formulaSelectFunctionSelect,children:[C.jsx(pe.Select,{value:m,options:y,onChange:k}),C.jsx(pe.Input,{placeholder:R.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:O,value:r,onChange:P,size:"large",allowClear:!0})]}),C.jsx("ul",{className:Te.formulaSelectFunctionResult,onKeyDown:O,tabIndex:-1,children:s.map(({name:M},v)=>C.jsxs("li",{className:c===v?`
23
+ ${Te.formulaSelectFunctionResultItem}
24
+ ${Te.formulaSelectFunctionResultItemActive}
25
+ `:Te.formulaSelectFunctionResultItem,onMouseEnter:()=>F(v),onMouseLeave:w,onClick:()=>L(v),children:[S===v&&C.jsx(Bt,{className:Te.formulaSelectFunctionResultItemSelected}),C.jsx("span",{className:Te.formulaSelectFunctionResultItemName,children:D(M)})]},v))}),p&&C.jsxs("div",{className:Te.formulaSelectFunctionContent,children:[C.jsx(Ke,{title:p.functionName,value:p.description}),C.jsx(Ke,{title:R.t("formula.moreFunctions.syntax"),value:C.jsx(hn,{prefix:p.functionName,value:p.functionParameter})}),C.jsx(Ke,{title:R.t("formula.prompt.helpExample"),value:`${p.functionName}(${p.functionParameter.map(M=>M.example).join(",")})`}),p.functionParameter&&p.functionParameter.map((M,v)=>C.jsx(Ke,{title:M.name,value:`${M.require?b:x} ${M.detail}`},v))]})]})}function hs(){const e=$.useActiveWorkbook(),[t,n]=d.useState(!0),[r,o]=d.useState(!1),[s,i]=d.useState(null);a.useDependency($.IEditorBridgeService);const c=a.useDependency(l.LocaleService),f=a.useDependency(te.IEditorService),m=a.useDependency(l.IUniverInstanceService),g=a.useDependency(l.ICommandService);function S(){n(!t),o(!r)}function h(){const p=B.getSheetCommandTarget(m);if(!p)return;g.executeCommand($.SetCellEditVisibleOperation.id,{visible:!0,unitId:p.unitId,eventType:z.DeviceInputEventType.Dblclick});const u=f.getEditor(l.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),_=f.getEditor(l.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),R=`=${s==null?void 0:s.functionName}(`;u==null||u.replaceText(R),_==null||_.replaceText(R,!1)}return C.jsxs("div",{className:kt.formulaMoreFunctions,children:[t&&C.jsx(ds,{onChange:i}),r&&C.jsx(os,{functionInfo:s,onChange:()=>{}}),C.jsxs("div",{className:kt.formulaMoreFunctionsOperation,children:[r&&C.jsx(pe.Button,{type:"primary",size:"small",onClick:S,children:c.t("formula.moreFunctions.next")}),r&&C.jsx(pe.Button,{size:"small",onClick:S,children:c.t("formula.moreFunctions.prev")}),t&&!!e&&C.jsx(pe.Button,{type:"primary",size:"small",onClick:h,children:c.t("formula.moreFunctions.confirm")})]})]})}function ms(e){return{id:rt.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:a.MenuItemType.SELECTOR,selections:[{label:"SUM",value:"SUM",icon:"SumSingle"},{label:"AVERAGE",value:"AVERAGE",icon:"AvgSingle"},{label:"COUNT",value:"COUNT",icon:"CntSingle"},{label:"MAX",value:"MAX",icon:"MaxSingle"},{label:"MIN",value:"MIN",icon:"MinSingle"}],hidden$:a.getMenuHiddenObservable(e,l.UniverInstanceType.UNIVER_SHEET),disabled$:$.getCurrentRangeDisable$(e,{workbookTypes:[B.WorkbookEditablePermission],worksheetTypes:[B.WorksheetEditPermission,B.WorksheetSetCellValuePermission],rangeTypes:[B.RangeProtectionPermissionEditPoint]})}}function gs(e){return{id:ot.id,title:"formula.insert.more",type:a.MenuItemType.BUTTON}}function ps(e){return e.get(l.IUniverInstanceService).getCurrentTypeOfUnit$(l.UniverInstanceType.UNIVER_SHEET).pipe(q.switchMap(r=>r&&e.get(a.IClipboardInterfaceService)?new q.Observable(s=>s.next(!e.get(a.IClipboardInterfaceService).supportClipboard)):q.of(!0)))}function Ss(e){return{id:nt.id,type:a.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:ps(e).pipe(q.combineLatestWith($.getCurrentRangeDisable$(e,{workbookTypes:[B.WorkbookEditablePermission],rangeTypes:[B.RangeProtectionPermissionEditPoint],worksheetTypes:[B.WorksheetSetCellValuePermission,B.WorksheetEditPermission]})),q.map(([t,n])=>t||n))}}const vs={[a.RibbonStartGroup.FORMULAS_INSERT]:{[rt.id]:{order:1,menuItemFactory:ms,[ot.id]:{order:1,menuItemFactory:gs}}},[$.PASTE_SPECIAL_MENU_ID]:{[nt.id]:{order:4,menuItemFactory:Ss}}},Cs="meta_key_ctrl_And_Shift",ct=[a.KeyCode.ARROW_DOWN,a.KeyCode.ARROW_UP,a.KeyCode.ARROW_LEFT,a.KeyCode.ARROW_RIGHT],Rs=[...ct,a.KeyCode.ENTER,a.KeyCode.TAB,a.KeyCode.ESC];function Is(){const e=[];for(const t of Rs)e.push({id:Pe.id,binding:t,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t}});return e}function Es(){const e=[];for(const t of ct)e.push({id:Pe.id,binding:t|a.MetaKeys.SHIFT,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,metaKey:a.MetaKeys.SHIFT}});return e}function _s(){const e=[];for(const t of ct)e.push({id:Pe.id,binding:t|a.MetaKeys.CTRL_COMMAND,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,metaKey:a.MetaKeys.CTRL_COMMAND}});return e}function ys(){const e=[];for(const t of ct)e.push({id:Pe.id,binding:t|a.MetaKeys.SHIFT|a.MetaKeys.CTRL_COMMAND,preconditions:n=>$.whenFormulaEditorActivated(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,metaKey:Cs}});return e}const bs={id:Rt.id,binding:a.KeyCode.F4,preconditions:e=>$.whenFormulaEditorActivated(e)};function Ts(){const e=[];for(const t of[a.KeyCode.ENTER,a.KeyCode.TAB,a.KeyCode.ARROW_DOWN,a.KeyCode.ARROW_UP])e.push({id:Pe.id,binding:t,preconditions:n=>Gr(n),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}var Ms=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,Fs=(e,t,n,r)=>{for(var o=r>1?void 0:r?Ns(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&Ms(t,n,o),o},Ae=(e,t)=>(n,r)=>t(n,r,e);let tt=class extends l.Disposable{constructor(e,t,n,r,o,s,i){super(),this._injector=e,this._menuManagerService=t,this._commandService=n,this._shortcutService=r,this._uiPartsService=o,this._renderManagerService=s,this._componentManager=i,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(vs)}_registerCommands(){[nt,rt,ot,Wt,jt,Pe,Rt].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_registerShortcuts(){[...Is(),...Es(),..._s(),...ys(),...Ts(),bs].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(a.BuiltInUIPart.CONTENT,()=>a.connectInjector(Go,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent($.SheetsUIPart.FORMULA_AUX,()=>a.connectInjector(_o,this._injector))),this._componentManager.register(Ut,hs)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(l.UniverInstanceType.UNIVER_SHEET,[Qe]))}};tt=Fs([Ae(0,l.Inject(l.Injector)),Ae(1,a.IMenuManagerService),Ae(2,l.ICommandService),Ae(3,a.IShortcutService),Ae(4,a.IUIPartsService),Ae(5,z.IRenderManagerService),Ae(6,l.Inject(a.ComponentManager))],tt);var mn=Object.defineProperty,xs=Object.getOwnPropertyDescriptor,Os=(e,t,n)=>t in e?mn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ds=(e,t,n,r)=>{for(var o=r>1?void 0:r?xs(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(r?i(t,n,o):i(o))||o);return r&&o&&mn(t,n,o),o},mt=(e,t)=>(n,r)=>t(n,r,e),gn=(e,t,n)=>Os(e,typeof t!="symbol"?t+"":t,n);exports.UniverSheetsFormulaUIPlugin=class extends l.Plugin{constructor(t=Pt,n,r,o){super(),this._config=t,this._injector=n,this._renderManagerService=r,this._configService=o;const{menu:s,...i}=l.merge(Pt,this._config);s&&this._configService.setConfig("menu",s,{merge:!0}),this._configService.setConfig(zr,i)}onStarting(){const t=this._injector;[[ze,{useClass:gt}],[tt],[Xe],[Je],[Qe],[et]].forEach(o=>t.add(o));const r=this._injector.get(a.ComponentManager);r.register($.RANGE_SELECTOR_COMPONENT_KEY,cn),r.register($.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,un)}onRendered(){[[exports.RefSelectionsRenderService],[vt]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(l.UniverInstanceType.UNIVER_SHEET,t))}),l.touchDependencies(this._injector,[[tt],[Je],[et]])}onSteady(){this._injector.get(Xe)}};gn(exports.UniverSheetsFormulaUIPlugin,"pluginName",Ht);gn(exports.UniverSheetsFormulaUIPlugin,"type",l.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=Ds([l.DependentOn(N.UniverFormulaEnginePlugin,xe.UniverSheetsFormulaPlugin),mt(1,l.Inject(l.Injector)),mt(2,z.IRenderManagerService),mt(3,l.IConfigService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=$t;exports.FormulaEditor=un;exports.HelpFunctionOperation=jt;exports.InsertFunctionOperation=rt;exports.MoreFunctionsOperation=ot;exports.RangeSelector=cn;exports.ReferenceAbsoluteOperation=Rt;exports.SearchFunctionOperation=Wt;exports.SelectEditorFormulaOperation=Pe;exports.SheetOnlyPasteFormulaCommand=nt;