@univerjs/sheets-formula-ui 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/umd/index.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(j,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@univerjs/core"),require("@univerjs/sheets-ui"),require("@univerjs/engine-formula"),require("rxjs"),require("@univerjs/docs-ui"),require("@univerjs/sheets"),require("@univerjs/sheets-formula"),require("@univerjs/ui"),require("react"),require("@univerjs/design"),require("@univerjs/engine-render"),require("@univerjs/docs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/sheets-ui","@univerjs/engine-formula","rxjs","@univerjs/docs-ui","@univerjs/sheets","@univerjs/sheets-formula","@univerjs/ui","react","@univerjs/design","@univerjs/engine-render","@univerjs/docs","rxjs/operators"],c):(j=typeof globalThis<"u"?globalThis:j||self,c(j.UniverSheetsFormulaUi={},j.UniverCore,j.UniverSheetsUi,j.UniverEngineFormula,j.rxjs,j.UniverDocsUi,j.UniverSheets,j.UniverSheetsFormula,j.UniverUi,j.React,j.UniverDesign,j.UniverEngineRender,j.UniverDocs,j.rxjs.operators))})(this,function(j,c,P,I,K,J,U,me,O,S,ne,G,He,Ue){"use strict";var ds=Object.defineProperty;var hs=(j,c,P)=>c in j?ds(j,c,{enumerable:!0,configurable:!0,writable:!0,value:P}):j[c]=P;var V=(j,c,P)=>hs(j,typeof c!="symbol"?c+"":c,P);const We={id:"sheet.command.paste-formula",type:c.CommandType.COMMAND,handler:async o=>o.get(c.ICommandService).executeCommand(P.SheetPasteCommand.id,{value:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},ve={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(o,e)=>!0};var hn=Object.defineProperty,mn=Object.getOwnPropertyDescriptor,Sn=(o,e,t,n)=>{for(var s=n>1?void 0:n?mn(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&hn(e,t,s),s},pn=(o,e)=>(t,n)=>e(t,n,o);const Et="FORMULA_PROMPT_ACTIVATED",Ne=c.createIdentifier("formula-ui.prompt-service");let rt=class{constructor(o){V(this,"_search$",new K.Subject);V(this,"_help$",new K.Subject);V(this,"_navigate$",new K.Subject);V(this,"_accept$",new K.Subject);V(this,"_acceptFormulaName$",new K.Subject);V(this,"search$",this._search$.asObservable());V(this,"help$",this._help$.asObservable());V(this,"navigate$",this._navigate$.asObservable());V(this,"accept$",this._accept$.asObservable());V(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());V(this,"_searching",!1);V(this,"_helping",!1);V(this,"_sequenceNodes",[]);V(this,"_isLockedOnSelectionChangeRefString",!1);V(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=o}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(o){this._contextService.setContextValue(Et,o.visible),this._searching=o.visible,this._search$.next(o)}isSearching(){return this._searching}help(o){this._helping=o.visible,this._help$.next(o)}isHelping(){return this._helping}navigate(o){this._navigate$.next(o)}accept(o){this._accept$.next(o)}acceptFormulaName(o){this._acceptFormulaName$.next(o)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(o){this._sequenceNodes=o}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(o){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(o)]}getCurrentSequenceNodeByIndex(o){return this._sequenceNodes[o]}getCurrentSequenceNodeIndex(o){let e=0;const t=this._sequenceNodes[0];for(let n=0,s=this._sequenceNodes.length;n<s;n++){const r=this._sequenceNodes[n];if(typeof r=="string")e++;else{const{endIndex:i}=r;e=i}if(o<=e)return typeof t=="string"&&o!==0?n+1:n}return this._sequenceNodes.length}updateSequenceRef(o,e){const t=this._sequenceNodes[o];if(typeof t=="string"||t.nodeType!==I.sequenceNodeType.REFERENCE)return;const n=e.length-t.token.length,s={...t};s.token=e,s.endIndex+=n,this._sequenceNodes[o]=s;for(let r=o+1,i=this._sequenceNodes.length;r<i;r++){const a=this._sequenceNodes[r];if(typeof a=="string")continue;const l={...a};l.startIndex+=n,l.endIndex+=n,this._sequenceNodes[r]=l}}insertSequenceRef(o,e){const t=e.length,n=this.getCurrentSequenceNodeIndex(o);this._sequenceNodes.splice(n,0,{token:e,startIndex:o,endIndex:o+t-1,nodeType:I.sequenceNodeType.REFERENCE});for(let s=n+1,r=this._sequenceNodes.length;s<r;s++){const i=this._sequenceNodes[s];if(typeof i=="string")continue;const a={...i};a.startIndex+=t,a.endIndex+=t,this._sequenceNodes[s]=a}}insertSequenceString(o,e){const t=this.getCurrentSequenceNodeIndex(o),n=e.split("");this._sequenceNodes.splice(t,0,...n);const s=n.length;for(let r=t+s,i=this._sequenceNodes.length;r<i;r++){const a=this._sequenceNodes[r];if(typeof a=="string")continue;const l={...a};l.startIndex+=s,l.endIndex+=s,this._sequenceNodes[r]=l}}enableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!0}disableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!1}isLockedSelectionChange(){return this._isLockedOnSelectionChangeRefString}enableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!0}disableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!1}isLockedSelectionInsert(){return this._isLockedOnSelectionInsertRefString}};rt=Sn([pn(0,c.IContextService)],rt);const Be={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(o,e)=>(o.get(Ne).help(e),!0)},Ve={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(o,e)=>{var E,m;const t=o.get(U.SheetsSelectionsService),n=o.get(J.IEditorService),s=t.getCurrentSelections();if(!s||!s.length)return!1;const r=U.getSheetCommandTarget(o.get(c.IUniverInstanceService));if(!r)return!1;const{worksheet:i,unitId:a,subUnitId:l}=r,f=i.getCellMatrix(),{value:h}=e,d=o.get(c.ICommandService),u=[];let p=null,v=0,C=0,g="";if(s.length===1&&(_n(s[0].range)||Cn(s[0].range))){const{range:R,primary:y}=s[0],M=(E=y==null?void 0:y.actualRow)!=null?E:R.startRow,b=(m=y==null?void 0:y.actualColumn)!=null?m:R.startColumn;p=R,v=M,C=b;const T=yt(f,M,b);T&&(g=I.serializeRange(T))}else s.some(R=>{var F,k;const{range:y,primary:M}=R,b=(F=M==null?void 0:M.actualRow)!=null?F:y.startRow,T=(k=M==null?void 0:M.actualColumn)!=null?k:y.startColumn,A=yt(f,b,T);if(!A)return p=y,v=b,C=T,!0;const N=I.serializeRange(A),L=`=${h}(${N})`;return u.push({range:y,primary:{row:b,column:T},formula:L}),!1});if(p){const R=U.getCellAtRowCol(v,C,i),y={range:c.Rectangle.clone(p),primary:{startRow:R.startRow,startColumn:R.startColumn,endRow:R.endRow,endColumn:R.endColumn,actualRow:v,actualColumn:C,isMerged:R.isMerged,isMergedMainCell:R.startRow===v&&R.startColumn===C}},M={unitId:a,subUnitId:l,selections:[y]};await d.executeCommand(U.SetSelectionsOperation.id,M),setTimeout(()=>{n.setFormula(`=${h}(${g}`)},0)}return u.length===0?!1:d.executeCommand(me.InsertFunctionCommand.id,{list:u})}};function yt(o,e,t){const n=gn(o,e,t);if(n!==e)return{startRow:n,endRow:e-1,startColumn:t,endColumn:t};const s=vn(o,e,t);return s!==t?{startRow:e,endRow:e,startColumn:s,endColumn:t-1}:null}function gn(o,e,t){let n=!1;if(e===0)return e;for(let s=e-1;s>=0;s--){const r=o.getValue(s,t);if(Ke(r)&&!n){if(s===0)return 0;n=!0}else{if(n&&!Ke(r))return s+1;if(n&&s===0)return 0}}return e}function vn(o,e,t){let n=!1;if(t===0)return t;for(let s=t-1;s>=0;s--){const r=o.getValue(e,s);if(Ke(r)&&!n){if(s===0)return 0;n=!0}else{if(n&&!Ke(r))return s+1;if(n&&s===0)return 0}}return t}function Ke(o){if(o!=null&&o.p){const e=o==null?void 0:o.p.body;if(e==null)return!1;const t=e.dataStream,s=t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t;return c.isRealNum(s)}return o&&(o.t===c.CellValueType.NUMBER||c.getCellValueType(o)===c.CellValueType.NUMBER)}function _n(o){return o.startRow===o.endRow&&o.startColumn===o.endColumn}function Cn(o){return o.startRow!==o.endRow&&o.startColumn!==o.endColumn}const Tt="SHEET_FORMULA_UI_PLUGIN",bt=`${Tt}_MORE_FUNCTIONS_COMPONENT`,ze={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async o=>(o.get(O.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:bt}}),!0)},Ye={id:"formula-ui.operation.change-ref-to-absolute",type:c.CommandType.OPERATION,handler:async o=>!0},Ge={id:"formula-ui.operation.search-function",type:c.CommandType.OPERATION,handler:async(o,e)=>(o.get(Ne).search(e),!0)};var it={exports:{}},xe={};/**
1
+ (function(j,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@univerjs/core"),require("@univerjs/sheets-ui"),require("@univerjs/engine-formula"),require("rxjs"),require("@univerjs/docs-ui"),require("@univerjs/sheets"),require("@univerjs/sheets-formula"),require("@univerjs/ui"),require("react"),require("@univerjs/design"),require("@univerjs/engine-render"),require("@univerjs/docs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/sheets-ui","@univerjs/engine-formula","rxjs","@univerjs/docs-ui","@univerjs/sheets","@univerjs/sheets-formula","@univerjs/ui","react","@univerjs/design","@univerjs/engine-render","@univerjs/docs","rxjs/operators"],c):(j=typeof globalThis<"u"?globalThis:j||self,c(j.UniverSheetsFormulaUi={},j.UniverCore,j.UniverSheetsUi,j.UniverEngineFormula,j.rxjs,j.UniverDocsUi,j.UniverSheets,j.UniverSheetsFormula,j.UniverUi,j.React,j.UniverDesign,j.UniverEngineRender,j.UniverDocs,j.rxjs.operators))})(this,function(j,c,P,I,B,J,U,me,O,S,ne,G,He,Ue){"use strict";var dr=Object.defineProperty;var hr=(j,c,P)=>c in j?dr(j,c,{enumerable:!0,configurable:!0,writable:!0,value:P}):j[c]=P;var K=(j,c,P)=>hr(j,typeof c!="symbol"?c+"":c,P);const We={id:"sheet.command.paste-formula",type:c.CommandType.COMMAND,handler:async o=>o.get(c.ICommandService).executeCommand(P.SheetPasteCommand.id,{value:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},ve={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(o,e)=>!0};var mn=Object.defineProperty,Sn=Object.getOwnPropertyDescriptor,pn=(o,e,t,n)=>{for(var r=n>1?void 0:n?Sn(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&mn(e,t,r),r},gn=(o,e)=>(t,n)=>e(t,n,o);const Et="FORMULA_PROMPT_ACTIVATED",Ne=c.createIdentifier("formula-ui.prompt-service");let st=class{constructor(o){K(this,"_search$",new B.Subject);K(this,"_help$",new B.Subject);K(this,"_navigate$",new B.Subject);K(this,"_accept$",new B.Subject);K(this,"_acceptFormulaName$",new B.Subject);K(this,"search$",this._search$.asObservable());K(this,"help$",this._help$.asObservable());K(this,"navigate$",this._navigate$.asObservable());K(this,"accept$",this._accept$.asObservable());K(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());K(this,"_searching",!1);K(this,"_helping",!1);K(this,"_sequenceNodes",[]);K(this,"_isLockedOnSelectionChangeRefString",!1);K(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=o}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(o){this._contextService.setContextValue(Et,o.visible),this._searching=o.visible,this._search$.next(o)}isSearching(){return this._searching}help(o){this._helping=o.visible,this._help$.next(o)}isHelping(){return this._helping}navigate(o){this._navigate$.next(o)}accept(o){this._accept$.next(o)}acceptFormulaName(o){this._acceptFormulaName$.next(o)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(o){this._sequenceNodes=o}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(o){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(o)]}getCurrentSequenceNodeByIndex(o){return this._sequenceNodes[o]}getCurrentSequenceNodeIndex(o){let e=0;const t=this._sequenceNodes[0];for(let n=0,r=this._sequenceNodes.length;n<r;n++){const s=this._sequenceNodes[n];if(typeof s=="string")e++;else{const{endIndex:i}=s;e=i}if(o<=e)return typeof t=="string"&&o!==0?n+1:n}return this._sequenceNodes.length}updateSequenceRef(o,e){const t=this._sequenceNodes[o];if(typeof t=="string"||t.nodeType!==I.sequenceNodeType.REFERENCE)return;const n=e.length-t.token.length,r={...t};r.token=e,r.endIndex+=n,this._sequenceNodes[o]=r;for(let s=o+1,i=this._sequenceNodes.length;s<i;s++){const a=this._sequenceNodes[s];if(typeof a=="string")continue;const l={...a};l.startIndex+=n,l.endIndex+=n,this._sequenceNodes[s]=l}}insertSequenceRef(o,e){const t=e.length,n=this.getCurrentSequenceNodeIndex(o);this._sequenceNodes.splice(n,0,{token:e,startIndex:o,endIndex:o+t-1,nodeType:I.sequenceNodeType.REFERENCE});for(let r=n+1,s=this._sequenceNodes.length;r<s;r++){const i=this._sequenceNodes[r];if(typeof i=="string")continue;const a={...i};a.startIndex+=t,a.endIndex+=t,this._sequenceNodes[r]=a}}insertSequenceString(o,e){const t=this.getCurrentSequenceNodeIndex(o),n=e.split("");this._sequenceNodes.splice(t,0,...n);const r=n.length;for(let s=t+r,i=this._sequenceNodes.length;s<i;s++){const a=this._sequenceNodes[s];if(typeof a=="string")continue;const l={...a};l.startIndex+=r,l.endIndex+=r,this._sequenceNodes[s]=l}}enableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!0}disableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!1}isLockedSelectionChange(){return this._isLockedOnSelectionChangeRefString}enableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!0}disableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!1}isLockedSelectionInsert(){return this._isLockedOnSelectionInsertRefString}};st=pn([gn(0,c.IContextService)],st);const Be={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(o,e)=>(o.get(Ne).help(e),!0)},Ve={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(o,e)=>{var E,m;const t=o.get(U.SheetsSelectionsService),n=o.get(J.IEditorService),r=t.getCurrentSelections();if(!r||!r.length)return!1;const s=U.getSheetCommandTarget(o.get(c.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:a,subUnitId:l}=s,f=i.getCellMatrix(),{value:h}=e,d=o.get(c.ICommandService),u=[];let p=null,v=0,C=0,g="";if(r.length===1&&(Cn(r[0].range)||In(r[0].range))){const{range:R,primary:y}=r[0],M=(E=y==null?void 0:y.actualRow)!=null?E:R.startRow,b=(m=y==null?void 0:y.actualColumn)!=null?m:R.startColumn;p=R,v=M,C=b;const T=yt(f,M,b);T&&(g=I.serializeRange(T))}else r.some(R=>{var F,k;const{range:y,primary:M}=R,b=(F=M==null?void 0:M.actualRow)!=null?F:y.startRow,T=(k=M==null?void 0:M.actualColumn)!=null?k:y.startColumn,A=yt(f,b,T);if(!A)return p=y,v=b,C=T,!0;const N=I.serializeRange(A),L=`=${h}(${N})`;return u.push({range:y,primary:{row:b,column:T},formula:L}),!1});if(p){const R=U.getCellAtRowCol(v,C,i),y={range:c.Rectangle.clone(p),primary:{startRow:R.startRow,startColumn:R.startColumn,endRow:R.endRow,endColumn:R.endColumn,actualRow:v,actualColumn:C,isMerged:R.isMerged,isMergedMainCell:R.startRow===v&&R.startColumn===C}},M={unitId:a,subUnitId:l,selections:[y]};await d.executeCommand(U.SetSelectionsOperation.id,M),setTimeout(()=>{n.setFormula(`=${h}(${g}`)},0)}return u.length===0?!1:d.executeCommand(me.InsertFunctionCommand.id,{list:u})}};function yt(o,e,t){const n=vn(o,e,t);if(n!==e)return{startRow:n,endRow:e-1,startColumn:t,endColumn:t};const r=_n(o,e,t);return r!==t?{startRow:e,endRow:e,startColumn:r,endColumn:t-1}:null}function vn(o,e,t){let n=!1;if(e===0)return e;for(let r=e-1;r>=0;r--){const s=o.getValue(r,t);if(Ke(s)&&!n){if(r===0)return 0;n=!0}else{if(n&&!Ke(s))return r+1;if(n&&r===0)return 0}}return e}function _n(o,e,t){let n=!1;if(t===0)return t;for(let r=t-1;r>=0;r--){const s=o.getValue(e,r);if(Ke(s)&&!n){if(r===0)return 0;n=!0}else{if(n&&!Ke(s))return r+1;if(n&&r===0)return 0}}return t}function Ke(o){if(o!=null&&o.p){const e=o==null?void 0:o.p.body;if(e==null)return!1;const t=e.dataStream,r=t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t;return c.isRealNum(r)}return o&&(o.t===c.CellValueType.NUMBER||c.getCellValueType(o)===c.CellValueType.NUMBER)}function Cn(o){return o.startRow===o.endRow&&o.startColumn===o.endColumn}function In(o){return o.startRow!==o.endRow&&o.startColumn!==o.endColumn}const Tt="SHEET_FORMULA_UI_PLUGIN",bt=`${Tt}_MORE_FUNCTIONS_COMPONENT`,ze={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async o=>(o.get(O.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:bt}}),!0)},Ye={id:"formula-ui.operation.change-ref-to-absolute",type:c.CommandType.OPERATION,handler:async o=>!0},Ge={id:"formula-ui.operation.search-function",type:c.CommandType.OPERATION,handler:async(o,e)=>(o.get(Ne).search(e),!0)};var it={exports:{}},Pe={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,29 +6,29 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var Nt;function In(){if(Nt)return xe;Nt=1;var o=S,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,s=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,r={key:!0,ref:!0,__self:!0,__source:!0};function i(a,l,f){var h,d={},u=null,p=null;f!==void 0&&(u=""+f),l.key!==void 0&&(u=""+l.key),l.ref!==void 0&&(p=l.ref);for(h in l)n.call(l,h)&&!r.hasOwnProperty(h)&&(d[h]=l[h]);if(a&&a.defaultProps)for(h in l=a.defaultProps,l)d[h]===void 0&&(d[h]=l[h]);return{$$typeof:e,type:a,key:u,ref:p,props:d,_owner:s.current}}return xe.Fragment=t,xe.jsx=i,xe.jsxs=i,xe}var Mt;function Rn(){return Mt||(Mt=1,it.exports=In()),it.exports}var _=Rn(),ae=function(){return ae=Object.assign||function(o){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(o[s]=e[s])}return o},ae.apply(this,arguments)},En=function(o,e){var t={};for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&e.indexOf(n)<0&&(t[n]=o[n]);if(o!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(o);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(o,n[s])&&(t[n[s]]=o[n[s]]);return t},_e=S.forwardRef(function(o,e){var t=o.icon,n=o.id,s=o.className,r=o.extend,i=En(o,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(n," ").concat(s||"").trim(),l=S.useRef("_".concat(bn()));return Ot(t,"".concat(n),{defIds:t.defIds,idSuffix:l.current},ae({ref:e,className:a},i),r)});function Ot(o,e,t,n,s){return S.createElement(o.tag,ae(ae({key:e},yn(o,t,s)),n),(Tn(o,t).children||[]).map(function(r,i){return Ot(r,"".concat(e,"-").concat(o.tag,"-").concat(i),t,void 0,s)}))}function yn(o,e,t){var n=ae({},o.attrs);t!=null&&t.colorChannel1&&n.fill==="colorChannel1"&&(n.fill=t.colorChannel1);var s=e.defIds;return!s||s.length===0||(o.tag==="use"&&n["xlink:href"]&&(n["xlink:href"]=n["xlink:href"]+e.idSuffix),Object.entries(n).forEach(function(r){var i=r[0],a=r[1];typeof a=="string"&&(n[i]=a.replace(/url\(#(.*)\)/,"url(#$1".concat(e.idSuffix,")")))})),n}function Tn(o,e){var t,n=e.defIds;return!n||n.length===0?o:o.tag==="defs"&&(!((t=o.children)===null||t===void 0)&&t.length)?ae(ae({},o),{children:o.children.map(function(s){return typeof s.attrs.id=="string"&&n&&n.indexOf(s.attrs.id)>-1?ae(ae({},s),{attrs:ae(ae({},s.attrs),{id:s.attrs.id+e.idSuffix})}):s})}):o}function bn(){return Math.random().toString(36).substring(2,8)}_e.displayName="UniverIcon";var Nn={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"}}]},At=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"check-mark-single",ref:e,icon:Nn}))});At.displayName="CheckMarkSingle";var Mn={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"}}]},Ze=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"close-single",ref:e,icon:Mn}))});Ze.displayName="CloseSingle";var On={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"}}]},xt=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"delete-single",ref:e,icon:On}))});xt.displayName="DeleteSingle";var An={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"}}]},Pt=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"details-single",ref:e,icon:An}))});Pt.displayName="DetailsSingle";var xn={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"}}]},Dt=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"increase-single",ref:e,icon:xn}))});Dt.displayName="IncreaseSingle";var Pn={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"}}]},ct=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"more-single",ref:e,icon:Pn}))});ct.displayName="MoreSingle";var Dn={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"}}]},Ft=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"select-range-single",ref:e,icon:Dn}))});Ft.displayName="SelectRangeSingle";function Lt(o){var e,t,n="";if(typeof o=="string"||typeof o=="number")n+=o;else if(typeof o=="object")if(Array.isArray(o)){var s=o.length;for(e=0;e<s;e++)o[e]&&(t=Lt(o[e]))&&(n&&(n+=" "),n+=t)}else for(t in o)o[t]&&(n&&(n+=" "),n+=t);return n}function wt(){for(var o,e,t=0,n="",s=arguments.length;t<s;t++)(o=arguments[t])&&(e=Lt(o))&&(n&&(n+=" "),n+=e);return n}var Fn=Object.defineProperty,Ln=Object.getOwnPropertyDescriptor,wn=(o,e,t,n)=>{for(var s=n>1?void 0:n?Ln(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&Fn(e,t,s),s},Pe=(o,e)=>(t,n)=>e(t,n,o);j.RefSelectionsRenderService=class extends P.BaseSelectionRenderService{constructor(t,n,s,r,i,a){super(n,s,r,i);V(this,"_workbookSelections");V(this,"_eventDisposables");this._context=t,this._refSelectionsService=a,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(kn(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(t){this._remainLastEnabled=t}setSkipLastEnabled(t){this._skipLastEnabled=t}clearLastSelection(){const t=this._selectionControls[this._selectionControls.length-1];t&&(t.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),c.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var t;(t=this._eventDisposables)==null||t.dispose(),this._eventDisposables=null}_initCanvasEventListeners(){const t=this._getSheetObject(),{spreadsheetRowHeader:n,spreadsheetColumnHeader:s,spreadsheet:r,spreadsheetLeftTopPlaceholder:i}=t,{scene:a}=this._context,l=new c.DisposableCollection;return l.add(r==null?void 0:r.onPointerDown$.subscribeEvent((f,h)=>{this._onPointerDown(f,r.zIndex+1,c.RANGE_TYPE.NORMAL,this._getActiveViewport(f)),f.button!==2&&h.stopPropagation()})),l.add(n==null?void 0:n.onPointerDown$.subscribeEvent((f,h)=>{const d=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:u}=P.getCoordByOffset(f.offsetX,f.offsetY,a,d);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.ROW)||(this._onPointerDown(f,(r.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(f),G.ScrollTimerType.Y),f.button!==2&&h.stopPropagation())})),l.add(s==null?void 0:s.onPointerDown$.subscribeEvent((f,h)=>{const d=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:u}=P.getCoordByOffset(f.offsetX,f.offsetY,a,d);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(f,(r.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(f),G.ScrollTimerType.X),f.button!==2&&h.stopPropagation())})),l.add(i==null?void 0:i.onPointerDown$.subscribeEvent((f,h)=>{this._reset();const d=this._sheetSkeletonManagerService.getCurrent().skeleton,u=P.getAllSelection(d);this._addSelectionControlByModelData(u),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const p=a.onPointerUp$.subscribeEvent(()=>{p.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});f.button!==2&&h.stopPropagation()})),l}_addSelectionControlByModelData(t){var a;const n=this._skeleton,s=(a=t.style)!=null?a:P.genNormalSelectionStyle(this._themeService),r=this._scene;return t.style=s,this.newSelectionControl(r,n,t)}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(t=>{this._updateSelections(t,U.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(t=>{this._updateSelections(t,U.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(t=>{this._updateSelections(t,U.SelectionMoveType.MOVE_END)}))}_updateSelections(t,n){const r=this._context.unit.getActiveSheet().getSheetId();t.length!==0&&this._workbookSelections.setSelections(r,t.map(i=>U.convertSelectionDataToRange(i)),n)}_initSelectionChangeListener(){this.disposeWithMe(this._workbookSelections.selectionSet$.subscribe(t=>{if(this._reset(),!!this._skeleton)for(const s of t)this._addSelectionControlByModelData(s)}))}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{if(!t)return;const{skeleton:n}=t,{scene:s}=this._context,r=s.getViewport(G.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&this._skeleton.worksheet.getSheetId()!==n.worksheet.getSheetId()&&this._reset(),this._changeRuntime(n,s,r);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(t){const n=this._getSheetObject();return n==null?void 0:n.scene.getActiveViewportByCoord(G.Vector2.FromArray([t.offsetX,t.offsetY]))}_getSheetObject(){return P.getSheetObject(this._context.unit,this._context)}_onPointerDown(t,n=0,s=c.RANGE_TYPE.NORMAL,r,i=G.ScrollTimerType.ALL){var F;this._rangeType=s;const a=this._skeleton,l=this._scene;if(!l||!a)return;r&&(this._activeViewport=r);const{offsetX:f,offsetY:h}=t,d=l.getViewport(G.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!d)return;const u=l.getCoordRelativeToViewport(G.Vector2.FromArray([f,h])),{x:p,y:v}=u;this._startViewportPosX=p,this._startViewportPosY=v;const C=l.getScrollXYInfoByViewport(u),{scaleX:g,scaleY:E}=l.getAncestorScale(),m=this._skeleton.getCellByOffset(p,v,g,E,C);if(!m)return;switch(s){case c.RANGE_TYPE.NORMAL:break;case c.RANGE_TYPE.ROW:m.startColumn=0,m.endColumn=this._skeleton.getColumnCount()-1;break;case c.RANGE_TYPE.COLUMN:m.startRow=0,m.endRow=this._skeleton.getRowCount()-1;break;case c.RANGE_TYPE.ALL:m.startRow=0,m.startColumn=0,m.endRow=this._skeleton.getRowCount()-1,m.endColumn=this._skeleton.getColumnCount()-1}const R={range:m,primary:m,style:null};R.range.rangeType=s;const y=P.attachSelectionWithCoord(R,this._skeleton);this._startRangeWhenPointerDown={...y.rangeWithCoord};const M={...y.rangeWithCoord,rangeType:s};let b=this.getActiveSelectionControl();const T=this.getSelectionControls();for(const k of T){if(t.button===2&&k.model.isInclude(M)){b=k;return}if(k.model.isEqual(M)){b=k;break}}this._checkClearPreviousControls(t);const A=b==null?void 0:b.model.currentCell,N=t.shiftKey&&A,L=this._remainLastEnabled&&!t.ctrlKey&&!t.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;N&&A?this._makeSelectionByTwoCells(A,M,a,s,b):L&&b?b.updateRangeBySelectionWithCoord(y):b=this.newSelectionControl(l,a,R);for(let k=0;k<this.getSelectionControls().length-1;k++)this.getSelectionControls()[k].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),l.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(F=l.getTransformer())==null||F.clearSelectedObjects(),this._setupPointerMoveListener(d,b,s,i,p,v),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=l.onPointerUp$.subscribeEvent(()=>{var k;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(k=this._escapeShortcutDisposable)==null||k.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(t,n,s){const r=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:a}=n,l=new P.SelectionControl(t,r,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:a}),f=P.attachSelectionWithCoord(s,n);return l.updateRangeBySelectionWithCoord(f),this._selectionControls.push(l),l.setControlExtension({skeleton:n,scene:t,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),l}},j.RefSelectionsRenderService=wn([Pe(1,c.Inject(c.Injector)),Pe(2,c.Inject(c.ThemeService)),Pe(3,O.IShortcutService),Pe(4,c.Inject(P.SheetSkeletonManagerService)),Pe(5,U.IRefSelectionsService)],j.RefSelectionsRenderService);function kn(o){const e=P.genNormalSelectionStyle(o);return e.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},e}const jn=(o,e,t)=>{const s=c.useDependency(G.IRenderManagerService).getRenderById(o),r=s==null?void 0:s.with(j.RefSelectionsRenderService);S.useEffect(()=>{if(t&&r){const i=t.input$.subscribe(a=>{a.content===I.matchToken.COMMA?r.setSkipLastEnabled(!0):r.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[t,r]),S.useEffect(()=>{r&&(e.endsWith(I.matchToken.COMMA)||r.setSkipLastEnabled(!1))},[e,r])},Se=o=>o.map(e=>typeof e=="string"?e:e.token).join(""),kt=(o,e,t)=>{const n=S.useRef(!1);return S.useEffect(()=>{if(t){const r=t.input$.subscribe(()=>{n.current=!0});return()=>{r.unsubscribe()}}},[t]),S.useEffect(()=>{if(n.current&&o){n.current=!1;const r=Se(o);e(r)}},[o]),()=>n.current=!0},Xe=()=>{const o=c.useDependency(I.LexerTreeBuilder);return t=>o.sequenceNodesBuilder(t)||[]},jt=(o,e,t,n,s,r)=>{const i=Xe(),a=S.useRef(!0);S.useEffect(()=>{var l,f;if(r){if(a.current){const h=i(o);if(h.length){const d=n(r,h);t&&s(d)}else{const d=r.getDocumentData(),p={dataStream:(f=(l=d.body)==null?void 0:l.dataStream)!=null?f:`${e}\r
10
- `,...d.body};r.setDocumentData({...d,body:p})}a.current=!1}else if(t){const h=i(o),d=n(r,h);s(d)}}},[r,t])},Ht=o=>S.useMemo(()=>()=>{var t,n;if(o){o.focus();const s=[...o.getSelectionRanges()];if(s.length&&o.setSelectionRanges(s),!s.length){const r=(n=(t=o.getDocumentData().body)==null?void 0:t.dataStream)!=null?n:`\r
11
- `,i=Math.max(r.length-2,0);o.setSelectionRanges([{startOffset:i,endOffset:i}])}}},[o]);function Qe(o,e,t){const n=o.getCurrentTheme(),s=new c.ColorKit(e).setAlpha(.05).toRgbString();return{id:t,strokeWidth:1,stroke:e,fill:s,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:n.colorWhite}}function at(o){const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(c.ThemeService),n=c.useDependency(U.IRefSelectionsService),r=c.useDependency(G.IRenderManagerService).getRenderById(o),i=r==null?void 0:r.with(j.RefSelectionsRenderService),a=r==null?void 0:r.with(P.SheetSkeletonManagerService);return f=>{var E;const h=e.getUnit(o),d=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!d){n.setSelections(u);return}const p=d.getSheetId(),v=m=>{var R;return(R=h==null?void 0:h.getSheetBySheetName(m))==null?void 0:R.getSheetId()};if(!((E=a==null?void 0:a.getWorksheetSkeleton(p))==null?void 0:E.skeleton))return;for(let m=0,R=f.length;m<R;m++){const y=f[m],{themeColor:M,token:b,refIndex:T}=y,A=I.deserializeRangeWithSheet(b),{unitId:N,sheetName:L,range:F}=A;if(N&&o!==N)continue;const k=v(L);if(k&&k!==p)continue;const D=U.setEndForRange(F,d.getRowCount(),d.getColumnCount());u.push({range:D,primary:null,style:Qe(t,M,T.toString())})}((i==null?void 0:i.getSelectionControls())||[]).length===u.length?i==null||i.resetSelectionsByModelData(u):n.setSelections(u)}}function Ut(o=""){const e=c.useDependency(me.IDescriptionService),t=Wt(),n=S.useMemo(()=>o.length,[o]);return(r,i,a=!0)=>{const l=r.getDocumentData();if(!l)return[];if(!l.body)return[];const h={dataStream:"",...l.body};if(i==null||i.length===0){h.textRuns=[];const d={...l,body:h};return r.setDocumentData(d),[]}else{const{textRuns:d,refSelections:u}=Bt(e,t,i);n&&d.forEach(g=>{g.ed=g.ed+n,g.st=g.st+n}),h.textRuns=d;const p=i.reduce((g,E)=>typeof E=="string"?`${g}${E}`:`${g}${E.token}`,"");h.dataStream=`${o}${p}\r
12
- `;let v;if(a){v=r.getSelectionRanges();const g=h.dataStream.length-2+n;v.forEach(E=>{E.startOffset=Math.max(0,Math.min(E.startOffset,g)),E.endOffset=Math.max(0,Math.min(E.endOffset,g))})}const C={...l,body:h};return r.setDocumentData(C,v),u}}}function Wt(){const e=c.useDependency(c.ThemeService).getCurrentTheme();return S.useMemo(()=>{const n=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],s=e.hyacinth700,r=e.verdancy800;return{formulaRefColors:n,numberColor:s,stringColor:r}},[e])}function Bt(o,e,t){const{formulaRefColors:n,numberColor:s,stringColor:r}=e,i=[],a=[],l=new Map;let f=0;for(let h=0,d=t.length;h<d;h++){const u=t[h];if(typeof u=="string"){const m=i[i.length-1],R=m?m.ed:0,y=R+u.length;i.push({st:R,ed:y});continue}if(o.hasDefinedNameDescription(u.token.trim()))continue;const{startIndex:p,endIndex:v,nodeType:C,token:g}=u;let E="";if(C===I.sequenceNodeType.REFERENCE){if(l.has(g))E=l.get(g);else{const m=f%n.length;E=n[m],l.set(g,E),f++}a.push({refIndex:h,themeColor:E,token:g})}else C===I.sequenceNodeType.NUMBER?E=s:(C===I.sequenceNodeType.STRING||C===I.sequenceNodeType.ARRAY)&&(E=r);E&&E.length>0&&i.push({st:p,ed:v+1,ts:{cl:{rgb:E}}})}return{textRuns:i,refSelections:a}}const Vt=(o,e)=>{const t=c.useDependency(c.ICommandService),n=c.useDependency(O.IShortcutService);S.useEffect(()=>{if(!e||!o)return;const r=`sheet.formula-embedding-editor.${e.getEditorId()}`,i=new c.DisposableCollection,a=l=>{var h;const f=e.getSelectionRanges();if(f.length===1){const d=f[0];switch(l){case O.KeyCode.ARROW_LEFT:{const u=Math.max(d.startOffset-1,0);e.setSelectionRanges([{startOffset:u,endOffset:u}]);break}case O.KeyCode.ARROW_RIGHT:{const u=(((h=e.getDocumentData().body)==null?void 0:h.dataStream)||",,").length-2,p=Math.min(d.endOffset+1,u);e.setSelectionRanges([{startOffset:p,endOffset:p}]);break}}}};return i.add(t.registerCommand({id:r,type:c.CommandType.OPERATION,handler(l,f){const{keyCode:h}=f;a(h)}})),[O.KeyCode.ARROW_LEFT,O.KeyCode.ARROW_RIGHT,O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP].map(l=>({id:r,binding:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keyCode:l}})).forEach(l=>{i.add(n.registerShortcut(l))}),()=>{i.dispose()}},[e,o])},Kt=(o,e)=>{const n=c.useDependency(G.IRenderManagerService).getRenderById(o),s=n==null?void 0:n.with(j.RefSelectionsRenderService);S.useEffect(()=>{s&&(e?s==null||s.setRemainLastEnabled(!1):s==null||s.setRemainLastEnabled(!0))},[e,s])},lt=(o,e)=>{const t=c.useDependency(G.IRenderManagerService),n=c.useDependency(c.IContextService),s=c.useDependency(O.IContextMenuService),r=c.useDependency(U.IRefSelectionsService),i=t.getRenderById(e),a=i==null?void 0:i.with(j.RefSelectionsRenderService);S.useLayoutEffect(()=>{if(o){const l=a==null?void 0:a.enableSelectionChanging();return n.setContextValue(U.DISABLE_NORMAL_SELECTIONS,!0),n.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{n.setContextValue(c.EDITOR_ACTIVATED,!1),n.setContextValue(U.DISABLE_NORMAL_SELECTIONS,!1),l==null||l.dispose()}}},[o]),S.useLayoutEffect(()=>{if(o)return()=>{r.clear()}},[o]),S.useEffect(()=>{if(o)return s.disable(),()=>{s.enable()}},[o]),S.useEffect(()=>{o&&(a==null||a.setSkipLastEnabled(!1))},[o])},zt=()=>{S.useEffect(()=>()=>{},[])},Yt=o=>{const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(U.SheetsSelectionsService);return S.useMemo(()=>{if(o){const s=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),r=s==null?void 0:s.getActiveSheet(),i=[...t.getCurrentSelections()];return()=>{const a=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),l=a==null?void 0:a.getActiveSheet();l&&l===r&&t.setSelections(i)}}return()=>{}},[o])},Gt=o=>{const e=()=>{if(o){const{scene:n,mainComponent:s}=o.render,r=o.render.with(He.DocSkeletonManagerService),{width:i,height:a}=o.getBoundingClientRect();r.getViewModel().getDataModel().updateDocumentDataPageSize(1/0),n.transformByState({width:i,height:a}),s==null||s.resize(i,a)}},t=S.useMemo(()=>c.debounce(()=>{var v;if(!o)return;const s=o.render.with(He.DocSkeletonManagerService).getSkeleton(),{scene:r,mainComponent:i}=o.render,a=r.getViewport(J.VIEWPORT_KEY.VIEW_MAIN),{actualWidth:l}=s.getActualSize(),{width:f,height:h}=o.getBoundingClientRect();let d=a==null?void 0:a.getScrollBar();const u=Math.max(l,f),p=h;r.transformByState({width:u,height:p}),i==null||i.resize(u,p),l>f?d==null?a&&new G.ScrollBar(a,{barSize:8,enableVertical:!1}):a==null||a.resetCanvasSizeAndUpdateScroll():(d=null,a==null||a.scrollToBarPos({x:0,y:0}),(v=a==null?void 0:a.getScrollBar())==null||v.dispose())},30),[o]);return S.useEffect(()=>{if(o){const n=setTimeout(()=>{e(),t()},500);return()=>{clearTimeout(n)}}},[o]),S.useEffect(()=>{if(o){const n=o.input$.subscribe(()=>{t()});return()=>{n.unsubscribe()}}},[o]),{resize:e,checkScrollBar:t}},ut=o=>typeof o=="string"?o===I.matchToken.COMMA:!1,Hn=o=>{if(typeof o=="object")return o.nodeType===I.sequenceNodeType.REFERENCE},Un=o=>o.filter(e=>ut(e)||Hn(e)),ft=o=>{if(o.endColumn<o.startColumn){const e=o.endColumn;o.endColumn=o.startColumn,o.startColumn=e}if(o.endRow<o.startRow){const e=o.endRow;o.endRow=o.startRow,o.startRow=e}return o};function Zt(o,e,t){var n,s;return((s=(n=o.getUnit(e))==null?void 0:n.getSheetBySheetId(t))==null?void 0:s.getName())||""}const de=(o,e=!1)=>e?o.map(t=>t.sheetName!==""?I.serializeRangeWithSheet(t.sheetName,t.range):I.serializeRange(t.range)):o.map(t=>I.serializeRange(t.range)),Xt=(o,e,t,n,s,r,i)=>{const a=c.useDependency(G.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),f=S.useRef(!1),h=a.getRenderById(e),d=h==null?void 0:h.with(j.RefSelectionsRenderService),u=S.useRef([]),p=S.useMemo(()=>{const C=Un(n),g=u.current;return C.length===g.length?(g.splice(0),g.push(...C),g):C},[n]);u.current=p;const v=S.useRef();S.useEffect(()=>{if(o&&d){let C=!0;const g=(R,y)=>{var D;if(C||f.current){C=!1;return}const M=[...R],b=l.getUnit(e),T=((D=b==null?void 0:b.getActiveSheet())==null?void 0:D.getName())||"",A=p.map((x,z)=>{if(typeof x=="string"){if(!p[z-1])return null;const H=p[z+1];return ut(x)&&(ut(H)||z===p.length-1)?null:x}else if(x.nodeType===I.sequenceNodeType.REFERENCE){const w=I.deserializeRangeWithSheet(x.token);w.unitId=w.unitId===""?e:w.unitId,w.sheetName=w.sheetName===""?T:w.sheetName;const{unitId:H,sheetName:B}=w;if(r&&(H!==e||T!==B))return null;if(H===e&&T===B){const W=M.shift();if(W&&Zt(l,e,W.rangeWithCoord.sheetId||"")===B){const $={...x};return ft(W.rangeWithCoord),s?$.token=I.serializeRangeWithSheet(T,W.rangeWithCoord):$.token=I.serializeRange(W.rangeWithCoord),$}}return x}return null}).filter(x=>!!x),N=de(M.map(x=>{var z,w,H;return{range:x.rangeWithCoord,unitId:(z=x.rangeWithCoord.unitId)!=null?z:"",sheetName:Zt(l,(w=x.rangeWithCoord.unitId)!=null?w:"",(H=x.rangeWithCoord.sheetId)!=null?H:"")}}),s).join(I.matchToken.COMMA),L=Se(A),F=`${L}${L&&N?I.matchToken.COMMA:""}${N}`,k=f.current;i(F,k?-1:F.length,y)},E=d.selectionMoveEnd$.subscribe(R=>{if(g(R,!0),f.current=!1,v.current){const{result:y,offset:M}=v.current;i(y,M,!0),v.current=void 0}}),m=d.selectionMoving$.pipe(Ue.throttleTime(50)).subscribe(R=>{g(R,!1)});return()=>{E.unsubscribe(),m.unsubscribe()}}},[o,p,d,s,r,i]),S.useEffect(()=>{if(o&&d){const C=new c.DisposableCollection,g=(R,y)=>{var k;let M=0,b=0,T=!1;const A=l.getUnit(e),N=((k=A==null?void 0:A.getActiveSheet())==null?void 0:k.getName())||"",L=p.map(D=>{if(typeof D=="string")return T||(b+=D.length),D;if(D.nodeType===I.sequenceNodeType.REFERENCE){const x=I.deserializeRangeWithSheet(R);if(x.unitId=x.unitId===""?e:x.unitId,x.sheetName=x.sheetName===""?N:x.sheetName,M===y){T=!0;const z={...D,token:R};return s?z.token=I.serializeRangeWithSheet(x.sheetName,x.range):z.token=I.serializeRange(x.range),M++,b+=z.token.length,z}return M++,T||(b+=D.token.length),D}return D}),F=Se(L);v.current={result:F,offset:b},i(F,-1,!1)};let E=0;const m=d.selectionMoveEnd$.subscribe(()=>{E=setTimeout(()=>{C.dispose(),d.getSelectionControls().forEach((y,M)=>{C.add(K.merge(y.selectionMoving$,y.selectionScaling$).pipe(K.map(b=>I.serializeRange(b)),K.distinctUntilChanged()).subscribe(b=>{f.current=!0,g(b,M)}))})},30)});return()=>{m.unsubscribe(),C.dispose(),clearTimeout(E)}}},[o,d,p,i])},dt=(o,e,t,n,s,r)=>{const i=c.useDependency(c.ICommandService),a=c.useDependency(J.IEditorService),f=c.useDependency(G.IRenderManagerService).getRenderById(e),h=f==null?void 0:f.with(j.RefSelectionsRenderService);S.useEffect(()=>{if(o&&h)if(t){const d=i.onCommandExecuted(u=>{if(u.id===U.SetWorksheetActiveOperation.id){const p=h.getSelectionControls().length;for(let v=1;v<=p;v++)h.clearLastSelection();setTimeout(()=>{r()},30)}});return()=>{d.dispose()}}else{const d=i.beforeCommandExecuted(u=>{if(u.id===U.SetWorksheetActiveOperation.id){n(!1),s(),r();const p=a.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);p==null||p.focus()}});return()=>{d.dispose()}}},[o,h])},Qt=o=>!o.some(t=>{if(typeof t=="string"){if(t!==I.matchToken.COMMA)return!0}else if(t.nodeType!==I.sequenceNodeType.REFERENCE)return!0;return!1}),Wn=(o,e,t)=>{const n=S.useRef(!0);S.useEffect(()=>{if(o){const s=setTimeout(()=>{n.current=!1},500);return()=>{clearTimeout(s)}}},[o]),S.useEffect(()=>{if(!n.current&&e){const s=Qt(t);e(s,Se(t))}},[t,e])},fe={sheetRangeSelectorTextWrap:"univer-sheet-range-selector-text-wrap",sheetRangeSelectorPlaceholder:"univer-sheet-range-selector-placeholder",sheetRangeSelectorError:"univer-sheet-range-selector-error",sheetRangeSelectorErrorWrap:"univer-sheet-range-selector-error-wrap",sheetRangeSelectorText:"univer-sheet-range-selector-text",sheetRangeSelectorActive:"univer-sheet-range-selector-active",sheetRangeSelectorIcon:"univer-sheet-range-selector-icon",sheetRangeSelectorDialogItem:"univer-sheet-range-selector-dialog-item",sheetRangeSelectorDialogItemDelete:"univer-sheet-range-selector-dialog-item-delete"},De=()=>{};function Jt(o){const{initValue:e,unitId:t,subUnitId:n,errorText:s,placeholder:r,actions:i,onChange:a=De,onVerify:l=De,onRangeSelectorDialogVisibleChange:f=De,onBlur:h=De,onFocus:d=De,isFocus:u=!0,isOnlyOneRange:p=!1,isSupportAcrossSheet:v=!1}=o,C=c.useDependency(J.IEditorService),g=c.useDependency(c.LocaleService),E=c.useDependency(c.ICommandService),m=c.useDependency(I.LexerTreeBuilder),R=S.useRef(null),[y,M]=S.useState(!1),[b,T]=S.useState(u),A=S.useMemo(()=>c.createInternalEditorID(`${P.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),[N,L]=S.useState(),F=S.useRef(null),k=S.useMemo(()=>!y&&b,[y,b]),[D,x]=S.useState(()=>typeof e=="string"?e:de(e,v).join(I.matchToken.COMMA));i&&(i.handleOutClick=(Y,X)=>{R.current&&!y&&!R.current.contains(Y.target)&&X()});const z=S.useMemo(()=>D.split(I.matchToken.COMMA).filter(Y=>!!Y).map(Y=>I.deserializeRangeWithSheet(Y)),[D]),w=S.useMemo(()=>s!==void 0,[s]),H=Yt(!y&&b),B=S.useMemo(()=>Y=>{const X=m.sequenceNodesBuilder(Y);if(X){if(Qt(X)){const ge=X.map(Ae=>{if(typeof Ae=="string")return Ae;if(Ae.nodeType===I.sequenceNodeType.REFERENCE){const dn={...Ae},je=I.deserializeRangeWithSheet(Ae.token);return je.range=ft(je.range),v||(je.sheetName="",je.unitId=""),dn.token=de([je],v)[0],dn}return Ae}),ye=Se(ge);a(ye)}}else x("")},[v]),W=Ht(N);S.useLayoutEffect(()=>{if(u){const Y=setTimeout(()=>{T(u),u&&W()},30);return()=>{clearTimeout(Y)}}else H(),T(u),N==null||N.blur()},[u,W]);const{checkScrollBar:$}=Gt(N),le=Xe(),ue=S.useMemo(()=>le(D),[D]),he=Ut(),ee=at(t),se=(Y,X=!0)=>{if(!N)return;const Ee=le(Y),ge=he(N,Ee,X);ee(ge)},ce=kt(ue,B,N),Re=S.useMemo(()=>(Y,X,Ee)=>{se(Y),x(Y),ce(),Ee&&(W(),X!==-1&&setTimeout(()=>{const ge={startOffset:X,endOffset:X};N==null||N.setSelectionRanges([ge]);const ye=N==null?void 0:N.render.with(J.DocBackScrollRenderController);ye==null||ye.scrollToRange({...ge,collapsed:!0})},50),$())},[N]);Xt(k,t,n,ue,v,p,Re),lt(k,t),Kt(t,p),jn(t,D,N),Wn(k,l,ue),Vt(k,N),zt(),dt(k,t,v,T,h,()=>{k&&se(D)}),S.useEffect(()=>{if(N){const Y=N.input$.pipe(K.throttleTime(100)).subscribe(X=>{var ge,ye;const Ee=((ye=(ge=X.data.body)==null?void 0:ge.dataStream)!=null?ye:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");se(Ee,!1),x(Ee),ce()});return()=>{Y.unsubscribe()}}},[N]),S.useEffect(()=>{const Y=E.onCommandExecuted(X=>{X.id===P.SetCellEditVisibleOperation.id&&(M(!1),f(!1),T(!1),h())});return()=>{Y.dispose()}},[v]),S.useLayoutEffect(()=>{let Y;if(F.current){Y=C.register({autofocus:!0,editorUnitId:A,isSingle:!0,initialSnapshot:{id:A,body:{dataStream:`\r
13
- `},documentStyle:{}}},F.current);const X=C.getEditor(A);L(X)}return()=>{Y==null||Y.dispose()}},[]),jt(D,"",b,he,ee,N);const Z=()=>{setTimeout(()=>{d(),W(),T(!0)},30)},Q=Y=>{const X=de(Y,v).join(I.matchToken.COMMA);se(X),ce(),x(X),M(!1),f(!1),setTimeout(()=>{T(!0),N==null||N.setSelectionRanges([{startOffset:X.length,endOffset:X.length}]),W()},30)},re=()=>{M(!1),f(!1),setTimeout(()=>{T(!0),W()},30)},ie=()=>{w||(W(),setTimeout(()=>{M(!0),f(!0),T(!1)},30))};return _.jsxs("div",{className:fe.sheetRangeSelector,ref:R,children:[_.jsxs("div",{className:wt(fe.sheetRangeSelectorTextWrap,{[fe.sheetRangeSelectorActive]:b&&!w,[fe.sheetRangeSelectorError]:w}),children:[_.jsx("div",{className:fe.sheetRangeSelectorText,ref:F,onMouseUp:Z}),_.jsx(ne.Tooltip,{title:g.t("rangeSelector.buttonTooltip"),placement:"bottom",children:_.jsx(Ft,{className:fe.sheetRangeSelectorIcon,onClick:ie})}),s!==void 0?_.jsx("div",{className:fe.sheetRangeSelectorErrorWrap,children:s}):null,r!==void 0&&!D?_.jsx("div",{className:fe.sheetRangeSelectorPlaceholder,children:r}):null]}),y&&_.jsx(Bn,{editorId:A,handleConfirm:Q,handleClose:re,unitId:t,subUnitId:n,initValue:z,visible:y,isOnlyOneRange:p,isSupportAcrossSheet:v})]})}function Bn(o){const{editorId:e,handleConfirm:t,handleClose:n,visible:s,initValue:r,unitId:i,subUnitId:a,isOnlyOneRange:l,isSupportAcrossSheet:f}=o,h=c.useDependency(c.LocaleService),d=c.useDependency(J.IEditorService),u=c.useDependency(me.IDescriptionService),p=c.useDependency(I.LexerTreeBuilder),C=c.useDependency(G.IRenderManagerService).getRenderById(i),g=C==null?void 0:C.with(j.RefSelectionsRenderService),[E,m]=S.useState(()=>{if(l){const w=r[0];return w?de([w],f):[""]}return de(r,f)}),[R,y]=S.useState(()=>E.length-1),M=Wt(),b=S.useMemo(()=>E.join(I.matchToken.COMMA),[E]),T=Xe(),A=S.useMemo(()=>T(b),[b]),N=S.useMemo(()=>Bt(u,M,A).refSelections,[A]),L=()=>{m([]),setTimeout(()=>{n()},30)},F=(w,H)=>{H?g==null||g.setSkipLastEnabled(!1):g==null||g.setSkipLastEnabled(!0),m(B=>{const W=[...B];return W[w]=H,W})},k=w=>{g==null||g.setSkipLastEnabled(!1),m(H=>{if(H.length===1)return H;const B=[];return H.forEach((W,$)=>{w!==$&&B.push(W)}),B})},D=()=>{g==null||g.setSkipLastEnabled(!0),m(w=>(w.push(""),y(w.length-1),[...w]))},x=S.useCallback(w=>{var B;g==null||g.setSkipLastEnabled(!1);const H=w.split(I.matchToken.COMMA).filter(W=>!!W);m(l?[(B=H[0])!=null?B:""]:H)},[R,l]),z=at(i);return Xt(R>=0,i,a,A,f,l,x),lt(R>=0,i),Kt(i,l),dt(R>=0,i,f,K.noop,K.noop,()=>z(N)),S.useEffect(()=>{z(N)},[N]),S.useEffect(()=>{(E.length===0||E.length===1&&!E[0])&&(g==null||g.setSkipLastEnabled(!0))},[E]),S.useEffect(()=>{const w=d.focusStyle$.pipe(K.filter(H=>!!H&&c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY!==H)).subscribe(H=>{H!==e&&L()});return()=>{w.unsubscribe()}},[d,e]),_.jsx(ne.Dialog,{width:"328px",visible:s,title:h.t("rangeSelector.title"),draggable:!0,closeIcon:_.jsx(Ze,{}),footer:_.jsxs("footer",{children:[_.jsx(ne.Button,{onClick:L,children:h.t("rangeSelector.cancel")}),_.jsx(ne.Button,{style:{marginLeft:10},onClick:()=>t(E.filter(w=>{const H=p.sequenceNodesBuilder(w);return H&&H.length===1&&typeof H[0]!="string"&&H[0].nodeType===I.sequenceNodeType.REFERENCE}).map(w=>I.deserializeRangeWithSheet(w)).map(w=>({...w,range:ft(w.range)}))),type:"primary",children:h.t("rangeSelector.confirm")})]}),onClose:L,children:_.jsxs("div",{className:fe.sheetRangeSelectorDialog,children:[E.map((w,H)=>_.jsxs("div",{className:fe.sheetRangeSelectorDialogItem,children:[_.jsx(ne.Input,{affixWrapperStyle:{width:"100%"},placeholder:h.t("rangeSelector.placeHolder"),onFocus:()=>y(H),value:w,onChange:B=>F(H,B)},`input_${H}`),E.length>1&&!l&&_.jsx(xt,{className:fe.sheetRangeSelectorDialogItemDelete,onClick:()=>k(H)})]},H)),!l&&_.jsx("div",{children:_.jsxs(ne.Button,{type:"link",size:"small",onClick:D,children:[_.jsx(Dt,{}),_.jsx("span",{children:h.t("rangeSelector.addAnotherRange")})]})})]})})}function Vn(o,e){return Object.keys(o).filter(t=>isNaN(Number(t))&&t!=="DefinedName").map(t=>({label:e.t(`formula.functionType.${t.toLocaleLowerCase()}`),value:`${o[t]}`}))}function ht(o){if(!o.require&&!o.repeat)return`[${o.name}]`;if(o.require&&!o.repeat)return o.name;if(!o.require&&o.repeat)return`[${o.name},...]`;if(o.require&&o.repeat)return`${o.name},...`}const Kn=(o,e=100)=>{S.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{o(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[o,e])},te={formulaHelpFunction:"univer-formula-help-function",formulaHelpFunctionTitle:"univer-formula-help-function-title",formulaHelpFunctionTitleIcons:"univer-formula-help-function-title-icons",formulaHelpFunctionTitleIcon:"univer-formula-help-function-title-icon",formulaHelpFunctionContent:"univer-formula-help-function-content",formulaHelpFunctionContentInner:"univer-formula-help-function-content-inner",formulaHelpFunctionContentParams:"univer-formula-help-function-content-params",formulaHelpFunctionContentParamsTitle:"univer-formula-help-function-content-params-title",formulaHelpFunctionContentParamsDetail:"univer-formula-help-function-content-params-detail",formulaHelpFunctionActive:"univer-formula-help-function-active",formulaHelpDecorator:"univer-formula-help-decorator",formulaHelpParam:"univer-formula-help-param",formulaHelpParamPrefix:"univer-formula-help-param-prefix",formulaHelpParamItem:"univer-formula-help-param-item",formulaHelpParamActive:"univer-formula-help-param-active"},qt=()=>{};function zn(o){const{functionInfo:e,paramIndex:t,editorId:n,onParamsSwitch:s=qt,onClose:r=qt}=o,i=c.useDependency(J.IEditorService),a=c.useDependency(O.ISidebarService),l=S.useMemo(()=>!!e&&t>=0,[e,t]),[f,h]=S.useState(!0),[d,u]=S.useState([0,0]),p=c.useDependency(c.LocaleService),v=p.t("formula.prompt.required"),C=p.t("formula.prompt.optional");Kn(g),S.useEffect(()=>{const m=a.scrollEvent$.pipe(K.throttleTime(100)).subscribe(g);return()=>{m.unsubscribe()}},[]),S.useEffect(()=>{const m=i.getEditor(n);if(!m)return;const R=m.getBoundingClientRect(),{left:y,top:M,height:b}=R;u([y,M+b])},[e,t,n]);function g(){const m=i.getEditor(n);if(!m)return;const R=m.getBoundingClientRect(),{left:y,top:M,height:b}=R;return u([y,M+b]),R}function E(m){s&&s(m)}return _.jsx(ne.Popup,{visible:l,offset:d,children:e?_.jsxs("div",{className:te.formulaHelpFunction,children:[_.jsxs("div",{className:te.formulaHelpFunctionTitle,children:[_.jsx(Yn,{prefix:e.functionName,value:e.functionParameter,active:t,onClick:E}),_.jsxs("div",{className:te.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:te.formulaHelpFunctionTitleIcon,style:{transform:f?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!f),children:_.jsx(ct,{})}),_.jsx("div",{className:te.formulaHelpFunctionTitleIcon,onClick:r,children:_.jsx(Ze,{})})]})]}),_.jsx("div",{className:te.formulaHelpFunctionContent,style:{height:f?"unset":0,padding:f?"revert-layer":0},children:_.jsxs("div",{className:te.formulaHelpFunctionContentInner,children:[_.jsx(mt,{title:p.t("formula.prompt.helpExample"),value:`${e.functionName}(${e.functionParameter.map(m=>m.example).join(",")})`}),_.jsx(mt,{title:p.t("formula.prompt.helpAbstract"),value:e.description}),e&&e.functionParameter&&e.functionParameter.map((m,R)=>_.jsx(mt,{className:t===R?te.formulaHelpFunctionActive:"",title:m.name,value:`${m.require?v:C} ${m.detail}`},R))]})})]}):_.jsx(_.Fragment,{})})}const mt=o=>_.jsxs("div",{className:te.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`
9
+ */var Nt;function Rn(){if(Nt)return Pe;Nt=1;var o=S,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,r=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,l,f){var h,d={},u=null,p=null;f!==void 0&&(u=""+f),l.key!==void 0&&(u=""+l.key),l.ref!==void 0&&(p=l.ref);for(h in l)n.call(l,h)&&!s.hasOwnProperty(h)&&(d[h]=l[h]);if(a&&a.defaultProps)for(h in l=a.defaultProps,l)d[h]===void 0&&(d[h]=l[h]);return{$$typeof:e,type:a,key:u,ref:p,props:d,_owner:r.current}}return Pe.Fragment=t,Pe.jsx=i,Pe.jsxs=i,Pe}var Mt;function En(){return Mt||(Mt=1,it.exports=Rn()),it.exports}var _=En(),ae=function(){return ae=Object.assign||function(o){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(o[r]=e[r])}return o},ae.apply(this,arguments)},yn=function(o,e){var t={};for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&e.indexOf(n)<0&&(t[n]=o[n]);if(o!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(o);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(o,n[r])&&(t[n[r]]=o[n[r]]);return t},_e=S.forwardRef(function(o,e){var t=o.icon,n=o.id,r=o.className,s=o.extend,i=yn(o,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(n," ").concat(r||"").trim(),l=S.useRef("_".concat(Nn()));return Ot(t,"".concat(n),{defIds:t.defIds,idSuffix:l.current},ae({ref:e,className:a},i),s)});function Ot(o,e,t,n,r){return S.createElement(o.tag,ae(ae({key:e},Tn(o,t,r)),n),(bn(o,t).children||[]).map(function(s,i){return Ot(s,"".concat(e,"-").concat(o.tag,"-").concat(i),t,void 0,r)}))}function Tn(o,e,t){var n=ae({},o.attrs);t!=null&&t.colorChannel1&&n.fill==="colorChannel1"&&(n.fill=t.colorChannel1);var r=e.defIds;return!r||r.length===0||(o.tag==="use"&&n["xlink:href"]&&(n["xlink:href"]=n["xlink:href"]+e.idSuffix),Object.entries(n).forEach(function(s){var i=s[0],a=s[1];typeof a=="string"&&(n[i]=a.replace(/url\(#(.*)\)/,"url(#$1".concat(e.idSuffix,")")))})),n}function bn(o,e){var t,n=e.defIds;return!n||n.length===0?o:o.tag==="defs"&&(!((t=o.children)===null||t===void 0)&&t.length)?ae(ae({},o),{children:o.children.map(function(r){return typeof r.attrs.id=="string"&&n&&n.indexOf(r.attrs.id)>-1?ae(ae({},r),{attrs:ae(ae({},r.attrs),{id:r.attrs.id+e.idSuffix})}):r})}):o}function Nn(){return Math.random().toString(36).substring(2,8)}_e.displayName="UniverIcon";var Mn={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"}}]},At=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"check-mark-single",ref:e,icon:Mn}))});At.displayName="CheckMarkSingle";var On={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"}}]},Ze=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"close-single",ref:e,icon:On}))});Ze.displayName="CloseSingle";var An={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"}}]},xt=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"delete-single",ref:e,icon:An}))});xt.displayName="DeleteSingle";var xn={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"}}]},Pt=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"details-single",ref:e,icon:xn}))});Pt.displayName="DetailsSingle";var Pn={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"}}]},Dt=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"increase-single",ref:e,icon:Pn}))});Dt.displayName="IncreaseSingle";var Dn={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"}}]},ct=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"more-single",ref:e,icon:Dn}))});ct.displayName="MoreSingle";var Fn={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"}}]},Ft=S.forwardRef(function(o,e){return S.createElement(_e,Object.assign({},o,{id:"select-range-single",ref:e,icon:Fn}))});Ft.displayName="SelectRangeSingle";function Lt(o){var e,t,n="";if(typeof o=="string"||typeof o=="number")n+=o;else if(typeof o=="object")if(Array.isArray(o)){var r=o.length;for(e=0;e<r;e++)o[e]&&(t=Lt(o[e]))&&(n&&(n+=" "),n+=t)}else for(t in o)o[t]&&(n&&(n+=" "),n+=t);return n}function wt(){for(var o,e,t=0,n="",r=arguments.length;t<r;t++)(o=arguments[t])&&(e=Lt(o))&&(n&&(n+=" "),n+=e);return n}var Ln=Object.defineProperty,wn=Object.getOwnPropertyDescriptor,kn=(o,e,t,n)=>{for(var r=n>1?void 0:n?wn(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&Ln(e,t,r),r},Me=(o,e)=>(t,n)=>e(t,n,o);j.RefSelectionsRenderService=class extends P.BaseSelectionRenderService{constructor(t,n,r,s,i,a,l){super(n,r,s,i,a);K(this,"_workbookSelections");K(this,"_eventDisposables");this._context=t,this._contextService=a,this._refSelectionsService=l,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(jn(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(t){this._remainLastEnabled=t}setSkipLastEnabled(t){this._skipLastEnabled=t}clearLastSelection(){const t=this._selectionControls[this._selectionControls.length-1];t&&(t.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),c.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var t;(t=this._eventDisposables)==null||t.dispose(),this._eventDisposables=null}_initCanvasEventListeners(){const t=this._getSheetObject(),{spreadsheetRowHeader:n,spreadsheetColumnHeader:r,spreadsheet:s,spreadsheetLeftTopPlaceholder:i}=t,{scene:a}=this._context,l=new c.DisposableCollection;return l.add(s==null?void 0:s.onPointerDown$.subscribeEvent((f,h)=>{this.inRefSelectionMode()&&(this._onPointerDown(f,s.zIndex+1,c.RANGE_TYPE.NORMAL,this._getActiveViewport(f)),f.button!==2&&h.stopPropagation())})),l.add(n==null?void 0:n.onPointerDown$.subscribeEvent((f,h)=>{if(!this.inRefSelectionMode())return;const d=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:u}=P.getCoordByOffset(f.offsetX,f.offsetY,a,d);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.ROW)||(this._onPointerDown(f,(s.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(f),G.ScrollTimerType.Y),f.button!==2&&h.stopPropagation())})),l.add(r==null?void 0:r.onPointerDown$.subscribeEvent((f,h)=>{if(!this.inRefSelectionMode())return;const d=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:u}=P.getCoordByOffset(f.offsetX,f.offsetY,a,d);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(f,(s.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(f),G.ScrollTimerType.X),f.button!==2&&h.stopPropagation())})),l.add(i==null?void 0:i.onPointerDown$.subscribeEvent((f,h)=>{if(this._reset(),!this.inRefSelectionMode())return;const d=this._sheetSkeletonManagerService.getCurrent().skeleton,u=P.getAllSelection(d);this._addSelectionControlByModelData(u),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const p=a.onPointerUp$.subscribeEvent(()=>{p.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});f.button!==2&&h.stopPropagation()})),l}_addSelectionControlByModelData(t){var a;const n=this._skeleton,r=(a=t.style)!=null?a:P.genNormalSelectionStyle(this._themeService),s=this._scene;return t.style=r,this.newSelectionControl(s,n,t)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(t=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(t||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(t=>{this._updateSelections(t,U.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(t=>{this._updateSelections(t,U.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(t=>{this._updateSelections(t,U.SelectionMoveType.MOVE_END)}))}_updateSelections(t,n){const s=this._context.unit.getActiveSheet().getSheetId();t.length!==0&&this._workbookSelections.setSelections(s,t.map(i=>U.convertSelectionDataToRange(i)),n)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{if(!t)return;const{skeleton:n}=t,{scene:r}=this._context,s=r.getViewport(G.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&this._skeleton.worksheet.getSheetId()!==n.worksheet.getSheetId()&&this._reset(),this._changeRuntime(n,r,s);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(t){const n=this._getSheetObject();return n==null?void 0:n.scene.getActiveViewportByCoord(G.Vector2.FromArray([t.offsetX,t.offsetY]))}_getSheetObject(){return P.getSheetObject(this._context.unit,this._context)}_onPointerDown(t,n=0,r=c.RANGE_TYPE.NORMAL,s,i=G.ScrollTimerType.ALL){var F;this._rangeType=r;const a=this._skeleton,l=this._scene;if(!l||!a)return;s&&(this._activeViewport=s);const{offsetX:f,offsetY:h}=t,d=l.getViewport(G.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!d)return;const u=l.getCoordRelativeToViewport(G.Vector2.FromArray([f,h])),{x:p,y:v}=u;this._startViewportPosX=p,this._startViewportPosY=v;const C=l.getScrollXYInfoByViewport(u),{scaleX:g,scaleY:E}=l.getAncestorScale(),m=this._skeleton.getCellByOffset(p,v,g,E,C);if(!m)return;switch(r){case c.RANGE_TYPE.NORMAL:break;case c.RANGE_TYPE.ROW:m.startColumn=0,m.endColumn=this._skeleton.getColumnCount()-1;break;case c.RANGE_TYPE.COLUMN:m.startRow=0,m.endRow=this._skeleton.getRowCount()-1;break;case c.RANGE_TYPE.ALL:m.startRow=0,m.startColumn=0,m.endRow=this._skeleton.getRowCount()-1,m.endColumn=this._skeleton.getColumnCount()-1}const R={range:m,primary:m,style:null};R.range.rangeType=r;const y=P.attachSelectionWithCoord(R,this._skeleton);this._startRangeWhenPointerDown={...y.rangeWithCoord};const M={...y.rangeWithCoord,rangeType:r};let b=this.getActiveSelectionControl();const T=this.getSelectionControls();for(const k of T){if(t.button===2&&k.model.isInclude(M)){b=k;return}if(k.model.isEqual(M)){b=k;break}}this._checkClearPreviousControls(t);const A=b==null?void 0:b.model.currentCell,N=t.shiftKey&&A,L=this._remainLastEnabled&&!t.ctrlKey&&!t.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;N&&A?this._makeSelectionByTwoCells(A,M,a,r,b):L&&b?b.updateRangeBySelectionWithCoord(y):b=this.newSelectionControl(l,a,R);for(let k=0;k<this.getSelectionControls().length-1;k++)this.getSelectionControls()[k].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),l.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(F=l.getTransformer())==null||F.clearSelectedObjects(),this._setupPointerMoveListener(d,b,r,i,p,v),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=l.onPointerUp$.subscribeEvent(()=>{var k;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(k=this._escapeShortcutDisposable)==null||k.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(t,n,r){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:a}=n,l=new P.SelectionControl(t,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:a}),f=P.attachSelectionWithCoord(r,n);return l.updateRangeBySelectionWithCoord(f),this._selectionControls.push(l),l.setControlExtension({skeleton:n,scene:t,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),l}},j.RefSelectionsRenderService=kn([Me(1,c.Inject(c.Injector)),Me(2,c.Inject(c.ThemeService)),Me(3,O.IShortcutService),Me(4,c.Inject(P.SheetSkeletonManagerService)),Me(5,c.IContextService),Me(6,U.IRefSelectionsService)],j.RefSelectionsRenderService);function jn(o){const e=P.genNormalSelectionStyle(o);return e.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},e}const Hn=(o,e,t)=>{const r=c.useDependency(G.IRenderManagerService).getRenderById(o),s=r==null?void 0:r.with(j.RefSelectionsRenderService);S.useEffect(()=>{if(t&&s){const i=t.input$.subscribe(a=>{a.content===I.matchToken.COMMA?s.setSkipLastEnabled(!0):s.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[t,s]),S.useEffect(()=>{s&&(e.endsWith(I.matchToken.COMMA)||s.setSkipLastEnabled(!1))},[e,s])},Se=o=>o.map(e=>typeof e=="string"?e:e.token).join(""),kt=(o,e,t)=>{const n=S.useRef(!1);return S.useEffect(()=>{if(t){const s=t.input$.subscribe(()=>{n.current=!0});return()=>{s.unsubscribe()}}},[t]),S.useEffect(()=>{if(n.current&&o){n.current=!1;const s=Se(o);e(s)}},[o]),()=>n.current=!0},Xe=()=>{const o=c.useDependency(I.LexerTreeBuilder);return t=>o.sequenceNodesBuilder(t)||[]},jt=(o,e,t,n,r,s)=>{const i=Xe(),a=S.useRef(!0);S.useEffect(()=>{var l,f;if(s){if(a.current){const h=i(o);if(h.length){const d=n(s,h);t&&r(d)}else{const d=s.getDocumentData(),p={dataStream:(f=(l=d.body)==null?void 0:l.dataStream)!=null?f:`${e}\r
10
+ `,...d.body};s.setDocumentData({...d,body:p})}a.current=!1}else if(t){const h=i(o),d=n(s,h);r(d)}}},[s,t])},Ht=o=>S.useMemo(()=>()=>{var t,n;if(o){o.focus();const r=[...o.getSelectionRanges()];if(r.length&&o.setSelectionRanges(r),!r.length){const s=(n=(t=o.getDocumentData().body)==null?void 0:t.dataStream)!=null?n:`\r
11
+ `,i=Math.max(s.length-2,0);o.setSelectionRanges([{startOffset:i,endOffset:i}])}}},[o]);function Qe(o,e,t){const n=o.getCurrentTheme(),r=new c.ColorKit(e).setAlpha(.05).toRgbString();return{id:t,strokeWidth:1,stroke:e,fill:r,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:n.colorWhite}}function at(o){const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(c.ThemeService),n=c.useDependency(U.IRefSelectionsService),s=c.useDependency(G.IRenderManagerService).getRenderById(o),i=s==null?void 0:s.with(j.RefSelectionsRenderService),a=s==null?void 0:s.with(P.SheetSkeletonManagerService);return f=>{var E;const h=e.getUnit(o),d=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!d){n.setSelections(u);return}const p=d.getSheetId(),v=m=>{var R;return(R=h==null?void 0:h.getSheetBySheetName(m))==null?void 0:R.getSheetId()};if(!((E=a==null?void 0:a.getWorksheetSkeleton(p))==null?void 0:E.skeleton))return;for(let m=0,R=f.length;m<R;m++){const y=f[m],{themeColor:M,token:b,refIndex:T}=y,A=I.deserializeRangeWithSheet(b),{unitId:N,sheetName:L,range:F}=A;if(N&&o!==N)continue;const k=v(L);if(k&&k!==p)continue;const D=U.setEndForRange(F,d.getRowCount(),d.getColumnCount());u.push({range:D,primary:null,style:Qe(t,M,T.toString())})}((i==null?void 0:i.getSelectionControls())||[]).length===u.length?i==null||i.resetSelectionsByModelData(u):n.setSelections(u)}}function Ut(o=""){const e=c.useDependency(me.IDescriptionService),t=Wt(),n=S.useMemo(()=>o.length,[o]);return(s,i,a=!0)=>{const l=s.getDocumentData();if(!l)return[];if(!l.body)return[];const h={dataStream:"",...l.body};if(i==null||i.length===0){h.textRuns=[];const d={...l,body:h};return s.setDocumentData(d),[]}else{const{textRuns:d,refSelections:u}=Bt(e,t,i);n&&d.forEach(g=>{g.ed=g.ed+n,g.st=g.st+n}),h.textRuns=d;const p=i.reduce((g,E)=>typeof E=="string"?`${g}${E}`:`${g}${E.token}`,"");h.dataStream=`${o}${p}\r
12
+ `;let v;if(a){v=s.getSelectionRanges();const g=h.dataStream.length-2+n;v.forEach(E=>{E.startOffset=Math.max(0,Math.min(E.startOffset,g)),E.endOffset=Math.max(0,Math.min(E.endOffset,g))})}const C={...l,body:h};return s.setDocumentData(C,v),u}}}function Wt(){const e=c.useDependency(c.ThemeService).getCurrentTheme();return S.useMemo(()=>{const n=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],r=e.hyacinth700,s=e.verdancy800;return{formulaRefColors:n,numberColor:r,stringColor:s}},[e])}function Bt(o,e,t){const{formulaRefColors:n,numberColor:r,stringColor:s}=e,i=[],a=[],l=new Map;let f=0;for(let h=0,d=t.length;h<d;h++){const u=t[h];if(typeof u=="string"){const m=i[i.length-1],R=m?m.ed:0,y=R+u.length;i.push({st:R,ed:y});continue}if(o.hasDefinedNameDescription(u.token.trim()))continue;const{startIndex:p,endIndex:v,nodeType:C,token:g}=u;let E="";if(C===I.sequenceNodeType.REFERENCE){if(l.has(g))E=l.get(g);else{const m=f%n.length;E=n[m],l.set(g,E),f++}a.push({refIndex:h,themeColor:E,token:g})}else C===I.sequenceNodeType.NUMBER?E=r:(C===I.sequenceNodeType.STRING||C===I.sequenceNodeType.ARRAY)&&(E=s);E&&E.length>0&&i.push({st:p,ed:v+1,ts:{cl:{rgb:E}}})}return{textRuns:i,refSelections:a}}const Vt=(o,e)=>{const t=c.useDependency(c.ICommandService),n=c.useDependency(O.IShortcutService);S.useEffect(()=>{if(!e||!o)return;const s=`sheet.formula-embedding-editor.${e.getEditorId()}`,i=new c.DisposableCollection,a=l=>{var h;const f=e.getSelectionRanges();if(f.length===1){const d=f[0];switch(l){case O.KeyCode.ARROW_LEFT:{const u=Math.max(d.startOffset-1,0);e.setSelectionRanges([{startOffset:u,endOffset:u}]);break}case O.KeyCode.ARROW_RIGHT:{const u=(((h=e.getDocumentData().body)==null?void 0:h.dataStream)||",,").length-2,p=Math.min(d.endOffset+1,u);e.setSelectionRanges([{startOffset:p,endOffset:p}]);break}}}};return i.add(t.registerCommand({id:s,type:c.CommandType.OPERATION,handler(l,f){const{keyCode:h}=f;a(h)}})),[O.KeyCode.ARROW_LEFT,O.KeyCode.ARROW_RIGHT,O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP].map(l=>({id:s,binding:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keyCode:l}})).forEach(l=>{i.add(n.registerShortcut(l))}),()=>{i.dispose()}},[e,o])},Kt=(o,e)=>{const n=c.useDependency(G.IRenderManagerService).getRenderById(o),r=n==null?void 0:n.with(j.RefSelectionsRenderService);S.useEffect(()=>{r&&(e?r==null||r.setRemainLastEnabled(!1):r==null||r.setRemainLastEnabled(!0))},[e,r])},lt=(o,e)=>{const t=c.useDependency(G.IRenderManagerService),n=c.useDependency(c.IContextService),r=c.useDependency(O.IContextMenuService),s=c.useDependency(U.IRefSelectionsService),i=t.getRenderById(e),a=i==null?void 0:i.with(j.RefSelectionsRenderService);S.useLayoutEffect(()=>{if(o){const l=a==null?void 0:a.enableSelectionChanging();return n.setContextValue(U.REF_SELECTIONS_ENABLED,!0),n.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{n.setContextValue(c.EDITOR_ACTIVATED,!1),n.setContextValue(U.REF_SELECTIONS_ENABLED,!1),l==null||l.dispose()}}},[o]),S.useLayoutEffect(()=>{if(o)return()=>{s.clear()}},[o]),S.useEffect(()=>{if(o)return r.disable(),()=>{r.enable()}},[o]),S.useEffect(()=>{o&&(a==null||a.setSkipLastEnabled(!1))},[o])},zt=()=>{S.useEffect(()=>()=>{},[])},Yt=o=>{const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(U.SheetsSelectionsService);return S.useMemo(()=>{if(o){const r=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),s=r==null?void 0:r.getActiveSheet(),i=[...t.getCurrentSelections()];return()=>{const a=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),l=a==null?void 0:a.getActiveSheet();l&&l===s&&t.setSelections(i)}}return()=>{}},[o])},Gt=o=>{const e=()=>{if(o){const{scene:n,mainComponent:r}=o.render,s=o.render.with(He.DocSkeletonManagerService),{width:i,height:a}=o.getBoundingClientRect();s.getViewModel().getDataModel().updateDocumentDataPageSize(1/0),n.transformByState({width:i,height:a}),r==null||r.resize(i,a)}},t=S.useMemo(()=>c.debounce(()=>{var v;if(!o)return;const r=o.render.with(He.DocSkeletonManagerService).getSkeleton(),{scene:s,mainComponent:i}=o.render,a=s.getViewport(J.VIEWPORT_KEY.VIEW_MAIN),{actualWidth:l}=r.getActualSize(),{width:f,height:h}=o.getBoundingClientRect();let d=a==null?void 0:a.getScrollBar();const u=Math.max(l,f),p=h;s.transformByState({width:u,height:p}),i==null||i.resize(u,p),l>f?d==null?a&&new G.ScrollBar(a,{barSize:8,enableVertical:!1}):a==null||a.resetCanvasSizeAndUpdateScroll():(d=null,a==null||a.scrollToBarPos({x:0,y:0}),(v=a==null?void 0:a.getScrollBar())==null||v.dispose())},30),[o]);return S.useEffect(()=>{if(o){const n=setTimeout(()=>{e(),t()},500);return()=>{clearTimeout(n)}}},[o]),S.useEffect(()=>{if(o){const n=o.input$.subscribe(()=>{t()});return()=>{n.unsubscribe()}}},[o]),{resize:e,checkScrollBar:t}},ut=o=>typeof o=="string"?o===I.matchToken.COMMA:!1,Un=o=>{if(typeof o=="object")return o.nodeType===I.sequenceNodeType.REFERENCE},Wn=o=>o.filter(e=>ut(e)||Un(e)),ft=o=>{if(o.endColumn<o.startColumn){const e=o.endColumn;o.endColumn=o.startColumn,o.startColumn=e}if(o.endRow<o.startRow){const e=o.endRow;o.endRow=o.startRow,o.startRow=e}return o};function Zt(o,e,t){var n,r;return((r=(n=o.getUnit(e))==null?void 0:n.getSheetBySheetId(t))==null?void 0:r.getName())||""}const de=(o,e=!1)=>e?o.map(t=>t.sheetName!==""?I.serializeRangeWithSheet(t.sheetName,t.range):I.serializeRange(t.range)):o.map(t=>I.serializeRange(t.range)),Xt=(o,e,t,n,r,s,i)=>{const a=c.useDependency(G.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),f=S.useRef(!1),h=a.getRenderById(e),d=h==null?void 0:h.with(j.RefSelectionsRenderService),u=S.useRef([]),p=S.useMemo(()=>{const C=Wn(n),g=u.current;return C.length===g.length?(g.splice(0),g.push(...C),g):C},[n]);u.current=p;const v=S.useRef();S.useEffect(()=>{if(o&&d){let C=!0;const g=(R,y)=>{var D;if(C||f.current){C=!1;return}const M=[...R],b=l.getUnit(e),T=((D=b==null?void 0:b.getActiveSheet())==null?void 0:D.getName())||"",A=p.map((x,z)=>{if(typeof x=="string"){if(!p[z-1])return null;const H=p[z+1];return ut(x)&&(ut(H)||z===p.length-1)?null:x}else if(x.nodeType===I.sequenceNodeType.REFERENCE){const w=I.deserializeRangeWithSheet(x.token);w.unitId=w.unitId===""?e:w.unitId,w.sheetName=w.sheetName===""?T:w.sheetName;const{unitId:H,sheetName:V}=w;if(s&&(H!==e||T!==V))return null;if(H===e&&T===V){const W=M.shift();if(W&&Zt(l,e,W.rangeWithCoord.sheetId||"")===V){const $={...x};return ft(W.rangeWithCoord),r?$.token=I.serializeRangeWithSheet(T,W.rangeWithCoord):$.token=I.serializeRange(W.rangeWithCoord),$}}return x}return null}).filter(x=>!!x),N=de(M.map(x=>{var z,w,H;return{range:x.rangeWithCoord,unitId:(z=x.rangeWithCoord.unitId)!=null?z:"",sheetName:Zt(l,(w=x.rangeWithCoord.unitId)!=null?w:"",(H=x.rangeWithCoord.sheetId)!=null?H:"")}}),r).join(I.matchToken.COMMA),L=Se(A),F=`${L}${L&&N?I.matchToken.COMMA:""}${N}`,k=f.current;i(F,k?-1:F.length,y)},E=d.selectionMoveEnd$.subscribe(R=>{if(g(R,!0),f.current=!1,v.current){const{result:y,offset:M}=v.current;i(y,M,!0),v.current=void 0}}),m=d.selectionMoving$.pipe(Ue.throttleTime(50)).subscribe(R=>{g(R,!1)});return()=>{E.unsubscribe(),m.unsubscribe()}}},[o,p,d,r,s,i]),S.useEffect(()=>{if(o&&d){const C=new c.DisposableCollection,g=(R,y)=>{var k;let M=0,b=0,T=!1;const A=l.getUnit(e),N=((k=A==null?void 0:A.getActiveSheet())==null?void 0:k.getName())||"",L=p.map(D=>{if(typeof D=="string")return T||(b+=D.length),D;if(D.nodeType===I.sequenceNodeType.REFERENCE){const x=I.deserializeRangeWithSheet(R);if(x.unitId=x.unitId===""?e:x.unitId,x.sheetName=x.sheetName===""?N:x.sheetName,M===y){T=!0;const z={...D,token:R};return r?z.token=I.serializeRangeWithSheet(x.sheetName,x.range):z.token=I.serializeRange(x.range),M++,b+=z.token.length,z}return M++,T||(b+=D.token.length),D}return D}),F=Se(L);v.current={result:F,offset:b},i(F,-1,!1)};let E=0;const m=d.selectionMoveEnd$.subscribe(()=>{E=setTimeout(()=>{C.dispose(),d.getSelectionControls().forEach((y,M)=>{C.add(B.merge(y.selectionMoving$,y.selectionScaling$).pipe(B.map(b=>I.serializeRange(b)),B.distinctUntilChanged()).subscribe(b=>{f.current=!0,g(b,M)}))})},30)});return()=>{m.unsubscribe(),C.dispose(),clearTimeout(E)}}},[o,d,p,i])},dt=(o,e,t,n,r,s)=>{const i=c.useDependency(c.ICommandService),a=c.useDependency(J.IEditorService),f=c.useDependency(G.IRenderManagerService).getRenderById(e),h=f==null?void 0:f.with(j.RefSelectionsRenderService);S.useEffect(()=>{if(o&&h)if(t){const d=i.onCommandExecuted(u=>{if(u.id===U.SetWorksheetActiveOperation.id){const p=h.getSelectionControls().length;for(let v=1;v<=p;v++)h.clearLastSelection();setTimeout(()=>{s()},30)}});return()=>{d.dispose()}}else{const d=i.beforeCommandExecuted(u=>{if(u.id===U.SetWorksheetActiveOperation.id){n(!1),r(),s();const p=a.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);p==null||p.focus()}});return()=>{d.dispose()}}},[o,h])},Qt=o=>!o.some(t=>{if(typeof t=="string"){if(t!==I.matchToken.COMMA)return!0}else if(t.nodeType!==I.sequenceNodeType.REFERENCE)return!0;return!1}),Bn=(o,e,t)=>{const n=S.useRef(!0);S.useEffect(()=>{if(o){const r=setTimeout(()=>{n.current=!1},500);return()=>{clearTimeout(r)}}},[o]),S.useEffect(()=>{if(!n.current&&e){const r=Qt(t);e(r,Se(t))}},[t,e])},fe={sheetRangeSelectorTextWrap:"univer-sheet-range-selector-text-wrap",sheetRangeSelectorPlaceholder:"univer-sheet-range-selector-placeholder",sheetRangeSelectorError:"univer-sheet-range-selector-error",sheetRangeSelectorErrorWrap:"univer-sheet-range-selector-error-wrap",sheetRangeSelectorText:"univer-sheet-range-selector-text",sheetRangeSelectorActive:"univer-sheet-range-selector-active",sheetRangeSelectorIcon:"univer-sheet-range-selector-icon",sheetRangeSelectorDialogItem:"univer-sheet-range-selector-dialog-item",sheetRangeSelectorDialogItemDelete:"univer-sheet-range-selector-dialog-item-delete"},De=()=>{};function Jt(o){const{initValue:e,unitId:t,subUnitId:n,errorText:r,placeholder:s,actions:i,onChange:a=De,onVerify:l=De,onRangeSelectorDialogVisibleChange:f=De,onBlur:h=De,onFocus:d=De,isFocus:u=!0,isOnlyOneRange:p=!1,isSupportAcrossSheet:v=!1}=o,C=c.useDependency(J.IEditorService),g=c.useDependency(c.LocaleService),E=c.useDependency(c.ICommandService),m=c.useDependency(I.LexerTreeBuilder),R=S.useRef(null),[y,M]=S.useState(!1),[b,T]=S.useState(u),A=S.useMemo(()=>c.createInternalEditorID(`${P.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),[N,L]=S.useState(),F=S.useRef(null),k=S.useMemo(()=>!y&&b,[y,b]),[D,x]=S.useState(()=>typeof e=="string"?e:de(e,v).join(I.matchToken.COMMA));i&&(i.handleOutClick=(Y,X)=>{R.current&&!y&&!R.current.contains(Y.target)&&X()});const z=S.useMemo(()=>D.split(I.matchToken.COMMA).filter(Y=>!!Y).map(Y=>I.deserializeRangeWithSheet(Y)),[D]),w=S.useMemo(()=>r!==void 0,[r]),H=Yt(!y&&b),V=S.useMemo(()=>Y=>{const X=m.sequenceNodesBuilder(Y);if(X){if(Qt(X)){const ge=X.map(xe=>{if(typeof xe=="string")return xe;if(xe.nodeType===I.sequenceNodeType.REFERENCE){const hn={...xe},je=I.deserializeRangeWithSheet(xe.token);return je.range=ft(je.range),v||(je.sheetName="",je.unitId=""),hn.token=de([je],v)[0],hn}return xe}),ye=Se(ge);a(ye)}}else x("")},[v]),W=Ht(N);S.useLayoutEffect(()=>{if(u){const Y=setTimeout(()=>{T(u),u&&W()},30);return()=>{clearTimeout(Y)}}else H(),T(u),N==null||N.blur()},[u,W]);const{checkScrollBar:$}=Gt(N),le=Xe(),ue=S.useMemo(()=>le(D),[D]),he=Ut(),ee=at(t),re=(Y,X=!0)=>{if(!N)return;const Ee=le(Y),ge=he(N,Ee,X);ee(ge)},ce=kt(ue,V,N),Re=S.useMemo(()=>(Y,X,Ee)=>{re(Y),x(Y),ce(),Ee&&(W(),X!==-1&&setTimeout(()=>{const ge={startOffset:X,endOffset:X};N==null||N.setSelectionRanges([ge]);const ye=N==null?void 0:N.render.with(J.DocBackScrollRenderController);ye==null||ye.scrollToRange({...ge,collapsed:!0})},50),$())},[N]);Xt(k,t,n,ue,v,p,Re),lt(k,t),Kt(t,p),Hn(t,D,N),Bn(k,l,ue),Vt(k,N),zt(),dt(k,t,v,T,h,()=>{k&&re(D)}),S.useEffect(()=>{if(N){const Y=N.input$.pipe(B.throttleTime(100)).subscribe(X=>{var ge,ye;const Ee=((ye=(ge=X.data.body)==null?void 0:ge.dataStream)!=null?ye:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");re(Ee,!1),x(Ee),ce()});return()=>{Y.unsubscribe()}}},[N]),S.useEffect(()=>{const Y=E.onCommandExecuted(X=>{X.id===P.SetCellEditVisibleOperation.id&&(M(!1),f(!1),T(!1),h())});return()=>{Y.dispose()}},[v]),S.useLayoutEffect(()=>{let Y;if(F.current){Y=C.register({autofocus:!0,editorUnitId:A,isSingle:!0,initialSnapshot:{id:A,body:{dataStream:`\r
13
+ `},documentStyle:{}}},F.current);const X=C.getEditor(A);L(X)}return()=>{Y==null||Y.dispose()}},[]),jt(D,"",b,he,ee,N);const Z=()=>{setTimeout(()=>{d(),W(),T(!0)},30)},Q=Y=>{const X=de(Y,v).join(I.matchToken.COMMA);re(X),ce(),x(X),M(!1),f(!1),setTimeout(()=>{T(!0),N==null||N.setSelectionRanges([{startOffset:X.length,endOffset:X.length}]),W()},30)},se=()=>{M(!1),f(!1),setTimeout(()=>{T(!0),W()},30)},ie=()=>{w||(W(),setTimeout(()=>{M(!0),f(!0),T(!1)},30))};return _.jsxs("div",{className:fe.sheetRangeSelector,ref:R,children:[_.jsxs("div",{className:wt(fe.sheetRangeSelectorTextWrap,{[fe.sheetRangeSelectorActive]:b&&!w,[fe.sheetRangeSelectorError]:w}),children:[_.jsx("div",{className:fe.sheetRangeSelectorText,ref:F,onMouseUp:Z}),_.jsx(ne.Tooltip,{title:g.t("rangeSelector.buttonTooltip"),placement:"bottom",children:_.jsx(Ft,{className:fe.sheetRangeSelectorIcon,onClick:ie})}),r!==void 0?_.jsx("div",{className:fe.sheetRangeSelectorErrorWrap,children:r}):null,s!==void 0&&!D?_.jsx("div",{className:fe.sheetRangeSelectorPlaceholder,children:s}):null]}),y&&_.jsx(Vn,{editorId:A,handleConfirm:Q,handleClose:se,unitId:t,subUnitId:n,initValue:z,visible:y,isOnlyOneRange:p,isSupportAcrossSheet:v})]})}function Vn(o){const{editorId:e,handleConfirm:t,handleClose:n,visible:r,initValue:s,unitId:i,subUnitId:a,isOnlyOneRange:l,isSupportAcrossSheet:f}=o,h=c.useDependency(c.LocaleService),d=c.useDependency(J.IEditorService),u=c.useDependency(me.IDescriptionService),p=c.useDependency(I.LexerTreeBuilder),C=c.useDependency(G.IRenderManagerService).getRenderById(i),g=C==null?void 0:C.with(j.RefSelectionsRenderService),[E,m]=S.useState(()=>{if(l){const w=s[0];return w?de([w],f):[""]}return de(s,f)}),[R,y]=S.useState(()=>E.length-1),M=Wt(),b=S.useMemo(()=>E.join(I.matchToken.COMMA),[E]),T=Xe(),A=S.useMemo(()=>T(b),[b]),N=S.useMemo(()=>Bt(u,M,A).refSelections,[A]),L=()=>{m([]),setTimeout(()=>{n()},30)},F=(w,H)=>{H?g==null||g.setSkipLastEnabled(!1):g==null||g.setSkipLastEnabled(!0),m(V=>{const W=[...V];return W[w]=H,W})},k=w=>{g==null||g.setSkipLastEnabled(!1),m(H=>{if(H.length===1)return H;const V=[];return H.forEach((W,$)=>{w!==$&&V.push(W)}),V})},D=()=>{g==null||g.setSkipLastEnabled(!0),m(w=>(w.push(""),y(w.length-1),[...w]))},x=S.useCallback(w=>{var V;g==null||g.setSkipLastEnabled(!1);const H=w.split(I.matchToken.COMMA).filter(W=>!!W);m(l?[(V=H[0])!=null?V:""]:H)},[R,l]),z=at(i);return Xt(R>=0,i,a,A,f,l,x),lt(R>=0,i),Kt(i,l),dt(R>=0,i,f,B.noop,B.noop,()=>z(N)),S.useEffect(()=>{z(N)},[N]),S.useEffect(()=>{(E.length===0||E.length===1&&!E[0])&&(g==null||g.setSkipLastEnabled(!0))},[E]),S.useEffect(()=>{const w=d.focusStyle$.pipe(B.filter(H=>!!H&&c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY!==H)).subscribe(H=>{H!==e&&L()});return()=>{w.unsubscribe()}},[d,e]),_.jsx(ne.Dialog,{width:"328px",visible:r,title:h.t("rangeSelector.title"),draggable:!0,closeIcon:_.jsx(Ze,{}),footer:_.jsxs("footer",{children:[_.jsx(ne.Button,{onClick:L,children:h.t("rangeSelector.cancel")}),_.jsx(ne.Button,{style:{marginLeft:10},onClick:()=>t(E.filter(w=>{const H=p.sequenceNodesBuilder(w);return H&&H.length===1&&typeof H[0]!="string"&&H[0].nodeType===I.sequenceNodeType.REFERENCE}).map(w=>I.deserializeRangeWithSheet(w)).map(w=>({...w,range:ft(w.range)}))),type:"primary",children:h.t("rangeSelector.confirm")})]}),onClose:L,children:_.jsxs("div",{className:fe.sheetRangeSelectorDialog,children:[E.map((w,H)=>_.jsxs("div",{className:fe.sheetRangeSelectorDialogItem,children:[_.jsx(ne.Input,{affixWrapperStyle:{width:"100%"},placeholder:h.t("rangeSelector.placeHolder"),onFocus:()=>y(H),value:w,onChange:V=>F(H,V)},`input_${H}`),E.length>1&&!l&&_.jsx(xt,{className:fe.sheetRangeSelectorDialogItemDelete,onClick:()=>k(H)})]},H)),!l&&_.jsx("div",{children:_.jsxs(ne.Button,{type:"link",size:"small",onClick:D,children:[_.jsx(Dt,{}),_.jsx("span",{children:h.t("rangeSelector.addAnotherRange")})]})})]})})}function Kn(o,e){return Object.keys(o).filter(t=>isNaN(Number(t))&&t!=="DefinedName").map(t=>({label:e.t(`formula.functionType.${t.toLocaleLowerCase()}`),value:`${o[t]}`}))}function ht(o){if(!o.require&&!o.repeat)return`[${o.name}]`;if(o.require&&!o.repeat)return o.name;if(!o.require&&o.repeat)return`[${o.name},...]`;if(o.require&&o.repeat)return`${o.name},...`}const zn=(o,e=100)=>{S.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{o(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[o,e])},te={formulaHelpFunction:"univer-formula-help-function",formulaHelpFunctionTitle:"univer-formula-help-function-title",formulaHelpFunctionTitleIcons:"univer-formula-help-function-title-icons",formulaHelpFunctionTitleIcon:"univer-formula-help-function-title-icon",formulaHelpFunctionContent:"univer-formula-help-function-content",formulaHelpFunctionContentInner:"univer-formula-help-function-content-inner",formulaHelpFunctionContentParams:"univer-formula-help-function-content-params",formulaHelpFunctionContentParamsTitle:"univer-formula-help-function-content-params-title",formulaHelpFunctionContentParamsDetail:"univer-formula-help-function-content-params-detail",formulaHelpFunctionActive:"univer-formula-help-function-active",formulaHelpDecorator:"univer-formula-help-decorator",formulaHelpParam:"univer-formula-help-param",formulaHelpParamPrefix:"univer-formula-help-param-prefix",formulaHelpParamItem:"univer-formula-help-param-item",formulaHelpParamActive:"univer-formula-help-param-active"},qt=()=>{};function Yn(o){const{functionInfo:e,paramIndex:t,editorId:n,onParamsSwitch:r=qt,onClose:s=qt}=o,i=c.useDependency(J.IEditorService),a=c.useDependency(O.ISidebarService),l=S.useMemo(()=>!!e&&t>=0,[e,t]),[f,h]=S.useState(!0),[d,u]=S.useState([0,0]),p=c.useDependency(c.LocaleService),v=p.t("formula.prompt.required"),C=p.t("formula.prompt.optional");zn(g),S.useEffect(()=>{const m=a.scrollEvent$.pipe(B.throttleTime(100)).subscribe(g);return()=>{m.unsubscribe()}},[]),S.useEffect(()=>{const m=i.getEditor(n);if(!m)return;const R=m.getBoundingClientRect(),{left:y,top:M,height:b}=R;u([y,M+b])},[e,t,n]);function g(){const m=i.getEditor(n);if(!m)return;const R=m.getBoundingClientRect(),{left:y,top:M,height:b}=R;return u([y,M+b]),R}function E(m){r&&r(m)}return _.jsx(ne.Popup,{visible:l,offset:d,children:e?_.jsxs("div",{className:te.formulaHelpFunction,children:[_.jsxs("div",{className:te.formulaHelpFunctionTitle,children:[_.jsx(Gn,{prefix:e.functionName,value:e.functionParameter,active:t,onClick:E}),_.jsxs("div",{className:te.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:te.formulaHelpFunctionTitleIcon,style:{transform:f?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!f),children:_.jsx(ct,{})}),_.jsx("div",{className:te.formulaHelpFunctionTitleIcon,onClick:s,children:_.jsx(Ze,{})})]})]}),_.jsx("div",{className:te.formulaHelpFunctionContent,style:{height:f?"unset":0,padding:f?"revert-layer":0},children:_.jsxs("div",{className:te.formulaHelpFunctionContentInner,children:[_.jsx(mt,{title:p.t("formula.prompt.helpExample"),value:`${e.functionName}(${e.functionParameter.map(m=>m.example).join(",")})`}),_.jsx(mt,{title:p.t("formula.prompt.helpAbstract"),value:e.description}),e&&e.functionParameter&&e.functionParameter.map((m,R)=>_.jsx(mt,{className:t===R?te.formulaHelpFunctionActive:"",title:m.name,value:`${m.require?v:C} ${m.detail}`},R))]})})]}):_.jsx(_.Fragment,{})})}const mt=o=>_.jsxs("div",{className:te.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`
14
14
  ${te.formulaHelpFunctionContentParamsTitle}
15
15
  ${o.className}
16
- `,children:o.title}),_.jsx("div",{className:te.formulaHelpFunctionContentParamsDetail,children:o.value})]}),Yn=o=>{const{prefix:e,value:t,active:n,onClick:s}=o;return _.jsxs("div",{className:te.formulaHelpParam,children:[_.jsxs("span",{className:te.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((r,i)=>_.jsxs("span",{className:te.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?te.formulaHelpFunctionActive:te.formulaHelpParamActive,onClick:()=>s(i),children:ht(r)}),i===t.length-1?"":","]},i)),")"]})},Me=o=>{const e=S.useRef();return e.current=o,e},Gn=(o,e,t)=>{const n=c.useDependency(me.IDescriptionService),s=c.useDependency(I.LexerTreeBuilder),[r,i]=S.useState(),[a,l]=S.useState(-1),[f,h]=S.useState(!0),d=Me(f),u=S.useRef(e);u.current=e;const p=()=>{i(void 0),l(-1),h(!1)};return S.useEffect(()=>{if(t&&o){const v=t.selectionChange$.pipe(K.debounceTime(50)).subscribe(g=>{if(g.textRanges.length===1){const[E]=g.textRanges;if(E.collapsed&&d.current){const m=s.getFunctionAndParameter(u.current,E.startOffset-1);if(m){const{functionName:R,paramIndex:y}=m,M=n.getFunctionInfo(R);i(M),l(y);return}}}i(void 0),l(-1)}),C=t.selectionChange$.pipe(K.filter(g=>g.isEditing),K.filter(g=>g.textRanges.length===1),K.map(g=>g.textRanges[0].startOffset),K.distinctUntilChanged()).subscribe(()=>{h(!0)});return()=>{v.unsubscribe(),C.unsubscribe()}}},[t,o]),S.useEffect(()=>{o||p()},[o]),{functionInfo:r,paramIndex:a,reset:p}},Je=(o,e,t=!0)=>{let n=-1;return o.reduce((s,r,i)=>{if(s.isFinish)return s;const a=s.currentIndex;if(typeof r!="string")s.currentIndex+=r.token.length;else{const l=r.length;s.currentIndex+=l}return(t?s.currentIndex===e:e>a&&e<=s.currentIndex)&&(n=i,s.isFinish=!0),s},{currentIndex:0,isFinish:!1}),n},Zn=(o,e=[],t)=>{const n=c.useDependency(me.IDescriptionService),[s,r]=S.useState([]),[i,a]=S.useState(""),l=S.useRef(-1),f=Me({nodes:e}),h=()=>{r([]),a(""),l.current=-1};return S.useEffect(()=>{if(t&&o){const u=t.input$.pipe(K.debounceTime(300)).subscribe(()=>{const p=t.getSelectionRanges();if(p.length===1){const v=f.current.nodes,C=p[0];if(C.collapsed){const g=Je(v,C.startOffset-1,!1);l.current=g;const E=v[g];if(E&&typeof E!="string"&&E.nodeType===I.sequenceNodeType.FUNCTION){l.current=g;const m=E.token,R=n.getSearchListByNameFirstLetter(m);r(R),a(m);return}}}l.current=-1,a(""),r(v=>v!=null&&v.length?[]:v)});return()=>{u.unsubscribe()}}},[t,o]),S.useEffect(()=>{o||h()},[o]),{searchList:s,searchText:i,handlerFormulaReplace:u=>{const p=[...f.current.nodes];if(l.current!==-1){const v=p.splice(l.current+1),C=p.pop()||"";let g=(typeof C=="string"?C.length:C.token.length)-u.length;return p.push(u),v[0]!==I.matchToken.OPEN_BRACKET&&(p.push(I.matchToken.OPEN_BRACKET),g--),{text:Se([...p,...v]),offset:g}}},reset:h}},Xn=o=>o.reduce((e,t)=>typeof t=="string"?e+t.length:e+t.token.length,0),Qn=(o,e=300)=>{let t=o,n=0;const s=()=>t,r=a=>{clearTimeout(n),t=a};function i(){clearTimeout(n),n=setTimeout(()=>{t=o},e)}return{getValue:s,setValue:r,reset:i}},St=[I.compareToken.EQUALS,I.compareToken.GREATER_THAN,I.compareToken.GREATER_THAN_OR_EQUAL,I.compareToken.LESS_THAN,I.compareToken.LESS_THAN_OR_EQUAL,I.compareToken.NOT_EQUAL,I.operatorToken.CONCATENATE,I.operatorToken.DIVIDED,I.operatorToken.MINUS,I.operatorToken.MULTIPLY,I.operatorToken.PLUS,I.operatorToken.POWER,I.matchToken.COMMA],$t=[...St,I.matchToken.COLON,I.matchToken.OPEN_BRACKET],Jn=[...St,I.matchToken.CLOSE_BRACKET],pt=o=>typeof o=="string"?o:o.token,qn=(o,e,t)=>{const s=c.useDependency(G.IRenderManagerService).getRenderById(o),r=s==null?void 0:s.with(j.RefSelectionsRenderService),i=S.useRef(!1),a=Me(e),l=S.useMemo(()=>Qn(!1,300),[]),f=d=>{r&&r.setSkipLastEnabled(d),i.current=d},h=()=>i.current;return S.useEffect(()=>{if(t&&r){const d=t.input$.subscribe(p=>{const v=p.content;v.length===1&&$t.includes(v)?(f(!0),l.setValue(!0),l.reset()):(f(!1),l.setValue(!1))}),u=t.selectionChange$.pipe(K.debounceTime(100)).subscribe(p=>{if(l.getValue())return;const v=p.textRanges;if(!v.length)return;if(v.length!==1){f(!1);return}const C=v[0];if(!C.collapsed){f(!1);return}const g=a.current;if(!g.length){f(!0);return}const E=C.startOffset-1;if(E===0){const T=Je(g,1,!1),A=g[T]||"",N=pt(A);if(St.includes(N)){f(!0);return}}const m=Je(g,E,!1),R=g[m];if(!R){f(!1);return}const y=g[m+1]||"",M=pt(y),b=pt(R);$t.includes(b)&&(!y||Jn.includes(M))?f(!0):f(!1)});return r.selectionMoveEnd$.subscribe(()=>{Promise.resolve().then(()=>{f(!1)})}),()=>{d.unsubscribe(),u.unsubscribe()}}},[t,r]),{setIsAddSelection:f,getIsNeedAddSelection:h,isLockSelectionEvent:l}},$n=()=>{},eo=(o,e,t,n,s,r,i=$n)=>{const a=c.useDependency(G.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),f=Me(n),{getIsNeedAddSelection:h}=qn(e,n,r),d=l.getUnit(e),u=y=>{var M,b;return(b=(M=d==null?void 0:d.getSheetBySheetId(y))==null?void 0:M.getName())!=null?b:""},p=S.useMemo(()=>u(t),[t]),v=c.useObservable(d==null?void 0:d.activeSheet$),C=Me({activeSheet:v,sheetName:p}),g=a.getRenderById(e),E=g==null?void 0:g.with(j.RefSelectionsRenderService),m=S.useRef(!1),R=S.useRef();S.useEffect(()=>{if(E&&o){let y=!0;const M=T=>{var k,D,x,z,w,H;if(y||m.current){y=!1;return}const A=r==null?void 0:r.getSelectionRanges();if((A==null?void 0:A.length)!==1)return;const L=A[0].startOffset-1,F=[...f.current];if(h())if(L!==0){const B=Je(F,L,!1);if(B===-1&&F.length)return;const W=T[T.length-1],$=F.splice(B+1),le=(k=W.rangeWithCoord.sheetId)!=null?k:t,ue={range:W.rangeWithCoord,unitId:(D=W.rangeWithCoord.unitId)!=null?D:e,sheetName:u(le)},ee=de([ue],s&&le!==t);F.push({token:ee[0],nodeType:I.sequenceNodeType.REFERENCE});const se=[...F,...$],ce=Se(se);i(ce,Xn(F),!0)}else{const B=T[T.length-1],W=(x=B.rangeWithCoord.sheetId)!=null?x:t,$={range:B.rangeWithCoord,unitId:(z=B.rangeWithCoord.unitId)!=null?z:e,sheetName:u(W)},ue=de([$],s&&W!==t);F.unshift({token:ue[0],nodeType:I.sequenceNodeType.REFERENCE});const he=Se(F);i(he,ue[0].length,!0)}else{let B=0;const W=F.map(ee=>{var se,ce,Re;if(typeof ee=="string")return ee;if(ee.nodeType===I.sequenceNodeType.REFERENCE){const Z=I.deserializeRangeWithSheet(ee.token);if(Z.sheetName||(Z.sheetName=p),s&&((se=C.current.activeSheet)==null?void 0:se.getName())!==Z.sheetName)return ee.token;const Q=T[B];if(B++,!Q)return"";const re=(ce=Q.rangeWithCoord.sheetId)!=null?ce:t,ie={range:Q.rangeWithCoord,unitId:(Re=Q.rangeWithCoord.unitId)!=null?Re:e,sheetName:u(re)};return de([ie],s)[0]}return ee.token}).join(""),$=[];for(let ee=B;ee<=T.length-1;ee++){const se=T[ee],ce=(w=se.rangeWithCoord.sheetId)!=null?w:t,Re={range:se.rangeWithCoord,unitId:(H=se.rangeWithCoord.unitId)!=null?H:e,sheetName:u(ce)},Q=de([Re],s&&ce!==t);$.push(Q[0])}const le=F[F.length-1],ue=le&&(typeof le=="string"?!1:le.nodeType===I.sequenceNodeType.REFERENCE),he=`${W}${$.length&&ue?",":""}${$.join(",")}`;i(he,he.length,!0)}},b=E.selectionMoveEnd$.subscribe(T=>{if(M(T),m.current=!1,R.current){const{result:A,offset:N}=R.current;i(A,N||-1,!0),R.current=void 0}});return()=>{b.unsubscribe()}}},[E,r,s,o]),S.useEffect(()=>{if(o&&E&&r){const y=new c.DisposableCollection,M=(A,N)=>{let L=0,F=0,k=!1;const{sheetName:D}=C.current,x=f.current.map(w=>{var H;if(typeof w=="string")return k||(F+=w.length),w;if(w.nodeType===I.sequenceNodeType.REFERENCE){const B=I.deserializeRangeWithSheet(w.token);if(B.unitId||(B.unitId=e),B.sheetName||(B.sheetName=D),s&&((H=C.current.activeSheet)==null?void 0:H.getName())!==B.sheetName)return k||(F+=w.token.length),w;if(L===N){k=!0;const W={...w,token:A};return s&&B.sheetName!==D?W.token=I.serializeRangeWithSheet(B.sheetName,I.deserializeRangeWithSheet(A).range):W.token=A,F+=W.token.length,L++,W}return k||(F+=w.token.length),L++,w}return k||(F+=w.token.length),w}),z=Se(x);i(z,-1,!1),R.current={result:z,offset:F}},b=()=>{y.dispose(),E.getSelectionControls().forEach((N,L)=>{y.add(K.merge(N.selectionMoving$,N.selectionScaling$).pipe(Ue.map(F=>I.serializeRange(F)),Ue.distinctUntilChanged()).subscribe(F=>{m.current=!0,M(F,L)}))})},T=K.merge(r.input$,E.selectionMoveEnd$).pipe(Ue.debounceTime(50)).subscribe(()=>{b()});return()=>{T.unsubscribe(),y.dispose()}}},[o,E,r])},to=(o,e,t)=>{const n=c.useDependency(I.LexerTreeBuilder),s=S.useRef(!0);S.useEffect(()=>{if(o){const r=setTimeout(()=>{s.current=!1},500);return()=>{clearTimeout(r)}}},[o]),S.useEffect(()=>{if(!s.current&&e){const r=n.checkIfAddBracket(t);e(r===0&&t.startsWith(I.operatorToken.EQUALS),`${t}`)}},[t,e])},Oe={sheetEmbeddingFormulaEditorActive:"univer-sheet-embedding-formula-editor-active",sheetEmbeddingFormulaEditorWrap:"univer-sheet-embedding-formula-editor-wrap",sheetEmbeddingFormulaEditorText:"univer-sheet-embedding-formula-editor-text",sheetEmbeddingFormulaEditorErrorWrap:"univer-sheet-embedding-formula-editor-error-wrap",sheetEmbeddingFormulaEditorError:"univer-sheet-embedding-formula-editor-error"},Ce={formulaSearchFunction:"univer-formula-search-function",formulaSearchFunctionItem:"univer-formula-search-function-item",formulaSearchFunctionItemName:"univer-formula-search-function-item-name",formulaSearchFunctionItemNameLight:"univer-formula-search-function-item-name-light",formulaSearchFunctionItemDesc:"univer-formula-search-function-item-desc",formulaSearchFunctionItemActive:"univer-formula-search-function-item-active"},no=()=>{},oo=S.forwardRef(so);function so(o,e){const{searchText:t,searchList:n,onSelect:s,editorId:r,onClose:i=no}=o,a=c.useDependency(J.IEditorService),l=c.useDependency(O.IShortcutService),f=c.useDependency(c.ICommandService),h=S.useMemo(()=>!!n.length,[n]),d=S.useRef(),[u,p]=S.useState(0),[v,C]=S.useState([0,0]),g=S.useRef(!1),E=Me({searchList:n,active:u}),m=a.getEditor(r);S.useEffect(()=>{const T=a.getEditor(r),A=T==null?void 0:T.getBoundingClientRect();if(A==null)return;const{left:N,top:L,height:F}=A;C([N,L+F]),p(0)},[t,n]);function R(T){g.current&&p(T)}function y(){g.current&&p(-1)}S.useEffect(()=>{if(!n.length)return;const T=`sheet.formula-embedding-editor.search_function.${r}`,A=new c.DisposableCollection,N=L=>{const{searchList:F,active:k}=E.current;switch(L){case O.KeyCode.ARROW_UP:{p(D=>{const x=Math.max(0,D-1);return M(x),x});break}case O.KeyCode.ARROW_DOWN:{p(D=>{const x=Math.min(F.length-1,D+1);return M(x),x});break}case O.KeyCode.TAB:case O.KeyCode.ENTER:{const D=F[k];s(D.name);break}case O.KeyCode.ESC:{s("");break}}};return A.add(f.registerCommand({id:T,type:c.CommandType.OPERATION,handler(L,F){const{keyCode:k}=F;N(k)}})),[O.KeyCode.ARROW_UP,O.KeyCode.ARROW_DOWN,O.KeyCode.ENTER,O.KeyCode.ESC,O.KeyCode.TAB].map(L=>({id:T,binding:L,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keyCode:L}})).forEach(L=>{A.add(l.registerShortcut(L))}),()=>{A.dispose()}},[n]);function M(T){var H;const A=(H=d.current)==null?void 0:H.querySelectorAll(`.${Ce.formulaSearchFunctionItem}`)[T];if(!A)return;const N=A.parentNode;if(!N)return;const F=N.getBoundingClientRect().top,k=N.offsetHeight,D=A.getBoundingClientRect(),x=D.top,z=D.height;if(x>=0&&x>F&&x-F+z<=k)return;const w=A.offsetTop-(k-z)/2;N.scrollTo({top:w,behavior:"smooth"})}const b=S.useMemo(()=>{let T="";return()=>{clearTimeout(T),g.current=!0,T=setTimeout(()=>{g.current=!1},300)}},[]);return n.length>0&&_.jsx(ne.Popup,{visible:h,offset:v,children:_.jsx("ul",{className:Ce.formulaSearchFunction,ref:T=>{d.current=T,e&&(e.current=T)},children:n.map((T,A)=>_.jsxs("li",{className:u===A?`
16
+ `,children:o.title}),_.jsx("div",{className:te.formulaHelpFunctionContentParamsDetail,children:o.value})]}),Gn=o=>{const{prefix:e,value:t,active:n,onClick:r}=o;return _.jsxs("div",{className:te.formulaHelpParam,children:[_.jsxs("span",{className:te.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>_.jsxs("span",{className:te.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?te.formulaHelpFunctionActive:te.formulaHelpParamActive,onClick:()=>r(i),children:ht(s)}),i===t.length-1?"":","]},i)),")"]})},Oe=o=>{const e=S.useRef();return e.current=o,e},Zn=(o,e,t)=>{const n=c.useDependency(me.IDescriptionService),r=c.useDependency(I.LexerTreeBuilder),[s,i]=S.useState(),[a,l]=S.useState(-1),[f,h]=S.useState(!0),d=Oe(f),u=S.useRef(e);u.current=e;const p=()=>{i(void 0),l(-1),h(!1)};return S.useEffect(()=>{if(t&&o){const v=t.selectionChange$.pipe(B.debounceTime(50)).subscribe(g=>{if(g.textRanges.length===1){const[E]=g.textRanges;if(E.collapsed&&d.current){const m=r.getFunctionAndParameter(u.current,E.startOffset-1);if(m){const{functionName:R,paramIndex:y}=m,M=n.getFunctionInfo(R);i(M),l(y);return}}}i(void 0),l(-1)}),C=t.selectionChange$.pipe(B.filter(g=>g.isEditing),B.filter(g=>g.textRanges.length===1),B.map(g=>g.textRanges[0].startOffset),B.distinctUntilChanged()).subscribe(()=>{h(!0)});return()=>{v.unsubscribe(),C.unsubscribe()}}},[t,o]),S.useEffect(()=>{o||p()},[o]),{functionInfo:s,paramIndex:a,reset:p}},Je=(o,e,t=!0)=>{let n=-1;return o.reduce((r,s,i)=>{if(r.isFinish)return r;const a=r.currentIndex;if(typeof s!="string")r.currentIndex+=s.token.length;else{const l=s.length;r.currentIndex+=l}return(t?r.currentIndex===e:e>a&&e<=r.currentIndex)&&(n=i,r.isFinish=!0),r},{currentIndex:0,isFinish:!1}),n},Xn=(o,e=[],t)=>{const n=c.useDependency(me.IDescriptionService),[r,s]=S.useState([]),[i,a]=S.useState(""),l=S.useRef(-1),f=Oe({nodes:e}),h=()=>{s([]),a(""),l.current=-1};return S.useEffect(()=>{if(t&&o){const u=t.input$.pipe(B.debounceTime(300)).subscribe(()=>{const p=t.getSelectionRanges();if(p.length===1){const v=f.current.nodes,C=p[0];if(C.collapsed){const g=Je(v,C.startOffset-1,!1);l.current=g;const E=v[g];if(E&&typeof E!="string"&&E.nodeType===I.sequenceNodeType.FUNCTION){l.current=g;const m=E.token,R=n.getSearchListByNameFirstLetter(m);s(R),a(m);return}}}l.current=-1,a(""),s(v=>v!=null&&v.length?[]:v)});return()=>{u.unsubscribe()}}},[t,o]),S.useEffect(()=>{o||h()},[o]),{searchList:r,searchText:i,handlerFormulaReplace:u=>{const p=[...f.current.nodes];if(l.current!==-1){const v=p.splice(l.current+1),C=p.pop()||"";let g=(typeof C=="string"?C.length:C.token.length)-u.length;return p.push(u),v[0]!==I.matchToken.OPEN_BRACKET&&(p.push(I.matchToken.OPEN_BRACKET),g--),{text:Se([...p,...v]),offset:g}}},reset:h}},Qn=o=>o.reduce((e,t)=>typeof t=="string"?e+t.length:e+t.token.length,0),Jn=(o,e=300)=>{let t=o,n=0;const r=()=>t,s=a=>{clearTimeout(n),t=a};function i(){clearTimeout(n),n=setTimeout(()=>{t=o},e)}return{getValue:r,setValue:s,reset:i}},St=[I.compareToken.EQUALS,I.compareToken.GREATER_THAN,I.compareToken.GREATER_THAN_OR_EQUAL,I.compareToken.LESS_THAN,I.compareToken.LESS_THAN_OR_EQUAL,I.compareToken.NOT_EQUAL,I.operatorToken.CONCATENATE,I.operatorToken.DIVIDED,I.operatorToken.MINUS,I.operatorToken.MULTIPLY,I.operatorToken.PLUS,I.operatorToken.POWER,I.matchToken.COMMA],$t=[...St,I.matchToken.COLON,I.matchToken.OPEN_BRACKET],qn=[...St,I.matchToken.CLOSE_BRACKET],pt=o=>typeof o=="string"?o:o.token,$n=(o,e,t)=>{const r=c.useDependency(G.IRenderManagerService).getRenderById(o),s=r==null?void 0:r.with(j.RefSelectionsRenderService),i=S.useRef(!1),a=Oe(e),l=S.useMemo(()=>Jn(!1,300),[]),f=d=>{s&&s.setSkipLastEnabled(d),i.current=d},h=()=>i.current;return S.useEffect(()=>{if(t&&s){const d=t.input$.subscribe(p=>{const v=p.content;v.length===1&&$t.includes(v)?(f(!0),l.setValue(!0),l.reset()):(f(!1),l.setValue(!1))}),u=t.selectionChange$.pipe(B.debounceTime(100)).subscribe(p=>{if(l.getValue())return;const v=p.textRanges;if(!v.length)return;if(v.length!==1){f(!1);return}const C=v[0];if(!C.collapsed){f(!1);return}const g=a.current;if(!g.length){f(!0);return}const E=C.startOffset-1;if(E===0){const T=Je(g,1,!1),A=g[T]||"",N=pt(A);if(St.includes(N)){f(!0);return}}const m=Je(g,E,!1),R=g[m];if(!R){f(!1);return}const y=g[m+1]||"",M=pt(y),b=pt(R);$t.includes(b)&&(!y||qn.includes(M))?f(!0):f(!1)});return s.selectionMoveEnd$.subscribe(()=>{Promise.resolve().then(()=>{f(!1)})}),()=>{d.unsubscribe(),u.unsubscribe()}}},[t,s]),{setIsAddSelection:f,getIsNeedAddSelection:h,isLockSelectionEvent:l}},eo=()=>{},to=(o,e,t,n,r,s,i=eo)=>{const a=c.useDependency(G.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),f=Oe(n),{getIsNeedAddSelection:h}=$n(e,n,s),d=l.getUnit(e),u=y=>{var M,b;return(b=(M=d==null?void 0:d.getSheetBySheetId(y))==null?void 0:M.getName())!=null?b:""},p=S.useMemo(()=>u(t),[t]),v=c.useObservable(d==null?void 0:d.activeSheet$),C=Oe({activeSheet:v,sheetName:p}),g=a.getRenderById(e),E=g==null?void 0:g.with(j.RefSelectionsRenderService),m=S.useRef(!1),R=S.useRef();S.useEffect(()=>{if(E&&o){let y=!0;const M=T=>{var k,D,x,z,w,H;if(y||m.current){y=!1;return}const A=s==null?void 0:s.getSelectionRanges();if((A==null?void 0:A.length)!==1)return;const L=A[0].startOffset-1,F=[...f.current];if(h())if(L!==0){const V=Je(F,L,!1);if(V===-1&&F.length)return;const W=T[T.length-1],$=F.splice(V+1),le=(k=W.rangeWithCoord.sheetId)!=null?k:t,ue={range:W.rangeWithCoord,unitId:(D=W.rangeWithCoord.unitId)!=null?D:e,sheetName:u(le)},ee=de([ue],r&&le!==t);F.push({token:ee[0],nodeType:I.sequenceNodeType.REFERENCE});const re=[...F,...$],ce=Se(re);i(ce,Qn(F),!0)}else{const V=T[T.length-1],W=(x=V.rangeWithCoord.sheetId)!=null?x:t,$={range:V.rangeWithCoord,unitId:(z=V.rangeWithCoord.unitId)!=null?z:e,sheetName:u(W)},ue=de([$],r&&W!==t);F.unshift({token:ue[0],nodeType:I.sequenceNodeType.REFERENCE});const he=Se(F);i(he,ue[0].length,!0)}else{let V=0;const W=F.map(ee=>{var re,ce,Re;if(typeof ee=="string")return ee;if(ee.nodeType===I.sequenceNodeType.REFERENCE){const Z=I.deserializeRangeWithSheet(ee.token);if(Z.sheetName||(Z.sheetName=p),r&&((re=C.current.activeSheet)==null?void 0:re.getName())!==Z.sheetName)return ee.token;const Q=T[V];if(V++,!Q)return"";const se=(ce=Q.rangeWithCoord.sheetId)!=null?ce:t,ie={range:Q.rangeWithCoord,unitId:(Re=Q.rangeWithCoord.unitId)!=null?Re:e,sheetName:u(se)};return de([ie],r)[0]}return ee.token}).join(""),$=[];for(let ee=V;ee<=T.length-1;ee++){const re=T[ee],ce=(w=re.rangeWithCoord.sheetId)!=null?w:t,Re={range:re.rangeWithCoord,unitId:(H=re.rangeWithCoord.unitId)!=null?H:e,sheetName:u(ce)},Q=de([Re],r&&ce!==t);$.push(Q[0])}const le=F[F.length-1],ue=le&&(typeof le=="string"?!1:le.nodeType===I.sequenceNodeType.REFERENCE),he=`${W}${$.length&&ue?",":""}${$.join(",")}`;i(he,he.length,!0)}},b=E.selectionMoveEnd$.subscribe(T=>{if(M(T),m.current=!1,R.current){const{result:A,offset:N}=R.current;i(A,N||-1,!0),R.current=void 0}});return()=>{b.unsubscribe()}}},[E,s,r,o]),S.useEffect(()=>{if(o&&E&&s){const y=new c.DisposableCollection,M=(A,N)=>{let L=0,F=0,k=!1;const{sheetName:D}=C.current,x=f.current.map(w=>{var H;if(typeof w=="string")return k||(F+=w.length),w;if(w.nodeType===I.sequenceNodeType.REFERENCE){const V=I.deserializeRangeWithSheet(w.token);if(V.unitId||(V.unitId=e),V.sheetName||(V.sheetName=D),r&&((H=C.current.activeSheet)==null?void 0:H.getName())!==V.sheetName)return k||(F+=w.token.length),w;if(L===N){k=!0;const W={...w,token:A};return r&&V.sheetName!==D?W.token=I.serializeRangeWithSheet(V.sheetName,I.deserializeRangeWithSheet(A).range):W.token=A,F+=W.token.length,L++,W}return k||(F+=w.token.length),L++,w}return k||(F+=w.token.length),w}),z=Se(x);i(z,-1,!1),R.current={result:z,offset:F}},b=()=>{y.dispose(),E.getSelectionControls().forEach((N,L)=>{y.add(B.merge(N.selectionMoving$,N.selectionScaling$).pipe(Ue.map(F=>I.serializeRange(F)),Ue.distinctUntilChanged()).subscribe(F=>{m.current=!0,M(F,L)}))})},T=B.merge(s.input$,E.selectionMoveEnd$).pipe(Ue.debounceTime(50)).subscribe(()=>{b()});return()=>{T.unsubscribe(),y.dispose()}}},[o,E,s])},no=(o,e,t)=>{const n=c.useDependency(I.LexerTreeBuilder),r=S.useRef(!0);S.useEffect(()=>{if(o){const s=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(s)}}},[o]),S.useEffect(()=>{if(!r.current&&e){const s=n.checkIfAddBracket(t);e(s===0&&t.startsWith(I.operatorToken.EQUALS),`${t}`)}},[t,e])},Ae={sheetEmbeddingFormulaEditorActive:"univer-sheet-embedding-formula-editor-active",sheetEmbeddingFormulaEditorWrap:"univer-sheet-embedding-formula-editor-wrap",sheetEmbeddingFormulaEditorText:"univer-sheet-embedding-formula-editor-text",sheetEmbeddingFormulaEditorErrorWrap:"univer-sheet-embedding-formula-editor-error-wrap",sheetEmbeddingFormulaEditorError:"univer-sheet-embedding-formula-editor-error"},Ce={formulaSearchFunction:"univer-formula-search-function",formulaSearchFunctionItem:"univer-formula-search-function-item",formulaSearchFunctionItemName:"univer-formula-search-function-item-name",formulaSearchFunctionItemNameLight:"univer-formula-search-function-item-name-light",formulaSearchFunctionItemDesc:"univer-formula-search-function-item-desc",formulaSearchFunctionItemActive:"univer-formula-search-function-item-active"},oo=()=>{},ro=S.forwardRef(so);function so(o,e){const{searchText:t,searchList:n,onSelect:r,editorId:s,onClose:i=oo}=o,a=c.useDependency(J.IEditorService),l=c.useDependency(O.IShortcutService),f=c.useDependency(c.ICommandService),h=S.useMemo(()=>!!n.length,[n]),d=S.useRef(),[u,p]=S.useState(0),[v,C]=S.useState([0,0]),g=S.useRef(!1),E=Oe({searchList:n,active:u}),m=a.getEditor(s);S.useEffect(()=>{const T=a.getEditor(s),A=T==null?void 0:T.getBoundingClientRect();if(A==null)return;const{left:N,top:L,height:F}=A;C([N,L+F]),p(0)},[t,n]);function R(T){g.current&&p(T)}function y(){g.current&&p(-1)}S.useEffect(()=>{if(!n.length)return;const T=`sheet.formula-embedding-editor.search_function.${s}`,A=new c.DisposableCollection,N=L=>{const{searchList:F,active:k}=E.current;switch(L){case O.KeyCode.ARROW_UP:{p(D=>{const x=Math.max(0,D-1);return M(x),x});break}case O.KeyCode.ARROW_DOWN:{p(D=>{const x=Math.min(F.length-1,D+1);return M(x),x});break}case O.KeyCode.TAB:case O.KeyCode.ENTER:{const D=F[k];r(D.name);break}case O.KeyCode.ESC:{r("");break}}};return A.add(f.registerCommand({id:T,type:c.CommandType.OPERATION,handler(L,F){const{keyCode:k}=F;N(k)}})),[O.KeyCode.ARROW_UP,O.KeyCode.ARROW_DOWN,O.KeyCode.ENTER,O.KeyCode.ESC,O.KeyCode.TAB].map(L=>({id:T,binding:L,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keyCode:L}})).forEach(L=>{A.add(l.registerShortcut(L))}),()=>{A.dispose()}},[n]);function M(T){var H;const A=(H=d.current)==null?void 0:H.querySelectorAll(`.${Ce.formulaSearchFunctionItem}`)[T];if(!A)return;const N=A.parentNode;if(!N)return;const F=N.getBoundingClientRect().top,k=N.offsetHeight,D=A.getBoundingClientRect(),x=D.top,z=D.height;if(x>=0&&x>F&&x-F+z<=k)return;const w=A.offsetTop-(k-z)/2;N.scrollTo({top:w,behavior:"smooth"})}const b=S.useMemo(()=>{let T="";return()=>{clearTimeout(T),g.current=!0,T=setTimeout(()=>{g.current=!1},300)}},[]);return n.length>0&&_.jsx(ne.Popup,{visible:h,offset:v,children:_.jsx("ul",{className:Ce.formulaSearchFunction,ref:T=>{d.current=T,e&&(e.current=T)},children:n.map((T,A)=>_.jsxs("li",{className:u===A?`
17
17
  ${Ce.formulaSearchFunctionItem}
18
18
  ${Ce.formulaSearchFunctionItemActive}
19
- `:Ce.formulaSearchFunctionItem,onMouseEnter:()=>R(A),onMouseLeave:y,onMouseMove:b,onClick:()=>{s(T.name),m&&m.focus()},children:[_.jsxs("span",{className:Ce.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Ce.formulaSearchFunctionItemNameLight,children:T.name.substring(0,t.length)}),_.jsx("span",{children:T.name.slice(t.length)})]}),_.jsx("span",{className:Ce.formulaSearchFunctionItemDesc,children:T.desc})]},A))})})}const en=o=>o.startsWith(I.operatorToken.EQUALS)?o.slice(1):"",gt=()=>{};function tn(o){const{errorText:e,initValue:t,unitId:n,subUnitId:s,isFocus:r=!0,isSupportAcrossSheet:i=!1,onFocus:a=gt,onBlur:l=gt,onChange:f,onVerify:h,actions:d}=o,u=c.useDependency(J.IEditorService),p=S.useRef(null),[v,C]=S.useState(()=>t.startsWith(I.operatorToken.EQUALS)?t:"");d&&(d.handleOutClick=(Z,Q)=>{p.current&&!p.current.contains(Z.target)&&Q()});const g=S.useMemo(()=>en(v),[v]),E=S.useRef(null),[m,R]=S.useState(),[y,M]=S.useState(r),b=S.useRef(null),T=S.useMemo(()=>c.createInternalEditorID(`${P.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),A=S.useMemo(()=>e!==void 0,[e]),N=Xe(),L=S.useMemo(()=>N(g),[g]),F=kt(L,Z=>{f(`=${Z}`)},m),k=Ut("="),D=at(n),x=(Z,Q=!0)=>{if(!m)return;const re=N(Z),ie=k(m,re,Q);D(ie)};to(y,h,v);const z=Ht(m),w=Yt(y);S.useLayoutEffect(()=>{if(r){const Z=setTimeout(()=>{M(r),r&&z()},30);return()=>{clearTimeout(Z)}}else w(),M(r)},[r,z]);const{checkScrollBar:H}=Gt(m);lt(y,n),Vt(y,m),eo(y,n,s,L,i,m,(Z,Q,re)=>{const ie=`=${Z}`;F(),C(ie),x(Z),re&&(z(),Q!==-1&&setTimeout(()=>{const Y={startOffset:Q+1,endOffset:Q+1};m==null||m.setSelectionRanges([Y]);const X=m==null?void 0:m.render.with(J.DocBackScrollRenderController);X==null||X.scrollToRange({...Y,collapsed:!0})},50),H())}),zt(),dt(y,n,i,M,l,gt);const{searchList:W,searchText:$,handlerFormulaReplace:le,reset:ue}=Zn(y,L,m),{functionInfo:he,paramIndex:ee,reset:se}=Gn(y,v,m);S.useEffect(()=>{if(m){const Z=m.input$.subscribe(Q=>{var ie,Y;const re=((Y=(ie=Q.data.body)==null?void 0:ie.dataStream)!=null?Y:"").replaceAll(/\n|\r/g,"");F(),C(re),x(en(re),!1)});return()=>{Z.unsubscribe()}}},[m]),jt(g,"=",y,k,D,m),S.useLayoutEffect(()=>{let Z;if(b.current){Z=u.register({autofocus:!0,editorUnitId:T,isSingle:!0,initialSnapshot:{id:T,body:{dataStream:`${t}\r
20
- `},documentStyle:{}}},b.current);const Q=u.getEditor(T);R(Q)}return()=>{Z==null||Z.dispose()}},[]);const ce=Z=>{const Q=le(Z);if(Q){C(`=${Q.text}`);const re=m==null?void 0:m.getSelectionRanges();if(re&&re.length===1){const ie=re[0];if(ie.collapsed){const Y=Q.offset;setTimeout(()=>{m==null||m.setSelectionRanges([{startOffset:ie.startOffset-Y,endOffset:ie.endOffset-Y}])},30)}}ue(),z(),x(Q.text)}},Re=()=>{setTimeout(()=>{M(!0),a(),z()},30)};return _.jsxs("div",{className:Oe.sheetEmbeddingFormulaEditor,children:[_.jsxs("div",{className:wt(Oe.sheetEmbeddingFormulaEditorWrap,{[Oe.sheetEmbeddingFormulaEditorActive]:y,[Oe.sheetEmbeddingFormulaEditorError]:A}),ref:p,children:[_.jsx("div",{className:Oe.sheetEmbeddingFormulaEditorText,ref:b,onMouseUp:Re}),e!==void 0?_.jsx("div",{className:Oe.sheetEmbeddingFormulaEditorErrorWrap,children:e}):null]}),_.jsx(zn,{editorId:T,paramIndex:ee,functionInfo:he,onClose:()=>{se(),z()}}),_.jsx(oo,{searchText:$,editorId:T,searchList:W,onSelect:ce,ref:E})]})}const ro="sheets-formula-ui.base.config",io={};function co(o){return o.getContextValue(c.FOCUSING_DOC)&&o.getContextValue(c.FOCUSING_UNIVER_EDITOR)&&o.getContextValue(c.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)}function nn(o,e=!1){return!e&&!(c.isFormulaString(o==null?void 0:o.f)||c.isFormulaId(o==null?void 0:o.si))?null:typeof(o==null?void 0:o.v)=="string"&&I.ERROR_TYPE_SET.has(o.v)?o.v:null}var ao=Object.defineProperty,lo=Object.getOwnPropertyDescriptor,uo=(o,e,t,n)=>{for(var s=n>1?void 0:n?lo(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&ao(e,t,s),s},Fe=(o,e)=>(t,n)=>e(t,n,o);const vt="SHEET_FORMULA_ALERT",fo={[I.ErrorType.DIV_BY_ZERO]:"divByZero",[I.ErrorType.NAME]:"name",[I.ErrorType.VALUE]:"value",[I.ErrorType.NUM]:"num",[I.ErrorType.NA]:"na",[I.ErrorType.CYCLE]:"cycle",[I.ErrorType.REF]:"ref",[I.ErrorType.SPILL]:"spill",[I.ErrorType.CALC]:"calc",[I.ErrorType.ERROR]:"error",[I.ErrorType.CONNECT]:"connect",[I.ErrorType.NULL]:"null"};let _t=class extends c.Disposable{constructor(o,e,t,n,s,r){super(),this._context=o,this._hoverManagerService=e,this._cellAlertManagerService=t,this._localeService=n,this._formulaDataModel=s,this._zenZoneService=r,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(K.debounceTime(100)).subscribe(o=>{var e,t,n,s,r;if(o){const a=this._context.unit.getActiveSheet();if(!a)return;const l=a.getCell(o.location.row,o.location.col),f=(s=(n=(t=(e=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:e[o.location.unitId])==null?void 0:t[o.location.subUnitId])==null?void 0:n[o.location.row])==null?void 0:s[o.location.col];if(c.isICellData(l)){const h=nn(l,!!f);if(!h){this._hideAlert();return}const d=this._cellAlertManagerService.currentAlert.get(vt),u=(r=d==null?void 0:d.alert)==null?void 0:r.location;if(u&&u.row===o.location.row&&u.col===o.location.col&&u.subUnitId===o.location.subUnitId&&u.unitId===o.location.unitId)return;this._cellAlertManagerService.showAlert({type:P.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${fo[h]}`),location:o.location,width:200,height:74,key:vt});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(o=>{o&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(vt)}};_t=uo([Fe(1,c.Inject(P.HoverManagerService)),Fe(2,c.Inject(P.CellAlertManagerService)),Fe(3,c.Inject(c.LocaleService)),Fe(4,c.Inject(I.FormulaDataModel)),Fe(5,O.IZenZoneService)],_t);var ho=Object.defineProperty,mo=Object.getOwnPropertyDescriptor,So=(o,e,t,n)=>{for(var s=n>1?void 0:n?mo(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&ho(e,t,s),s},on=(o,e)=>(t,n)=>e(t,n,o);let qe=class extends c.Disposable{constructor(o,e){super(),this._autoFillService=o,this._lexerTreeBuilder=e,this._registerAutoFill()}_registerAutoFill(){const o={type:P.DATA_TYPE.FORMULA,priority:1001,match:e=>c.isFormulaString(e==null?void 0:e.f)||c.isFormulaId(e==null?void 0:e.si),isContinue:(e,t)=>e.type===P.DATA_TYPE.FORMULA,applyFunctions:{[P.APPLY_TYPE.COPY]:(e,t,n,s)=>{const{data:r,index:i}=e;return this._fillCopyFormula(r,t,n,i,s)}}};this._autoFillService.registerRule(o)}_fillCopyFormula(o,e,t,n,s){var l,f;const r=go(s),i=[],a=new Map;for(let h=1;h<=e;h++){const d=(h-1)%o.length,u=c.Tools.deepClone(o[d]);if(u){const p=((l=o[d])==null?void 0:l.f)||"",v=((f=o[d])==null?void 0:f.si)||"",C=c.isFormulaString(p);if(c.isFormulaId(v))u.si=v,u.f=null,u.v=null,u.p=null,u.t=null,t===c.Direction.DOWN||t===c.Direction.RIGHT?i.push(u):i.unshift(u);else if(C){let E=a.get(d);if(E)u.si=E,u.f=null,u.v=null,u.p=null,u.t=null;else{E=c.Tools.generateRandomId(6),a.set(d,E);const{offsetX:m,offsetY:R}=po(r,t),y=this._lexerTreeBuilder.moveFormulaRefOffset(p,m,R);u.si=E,u.f=y,u.v=null,u.p=null,u.t=null}t===c.Direction.DOWN||t===c.Direction.RIGHT?i.push(u):i.unshift(u)}}}return i}};qe=So([on(0,P.IAutoFillService),on(1,c.Inject(I.LexerTreeBuilder))],qe);function po(o,e){let t=0,n=0;switch(e){case c.Direction.UP:n=-o;break;case c.Direction.RIGHT:t=o;break;case c.Direction.DOWN:n=o;break;case c.Direction.LEFT:t=-o;break}return{offsetX:t,offsetY:n}}function go(o){let e=0;for(const t in o)o[t].forEach(n=>{e+=n.data.length});return e}var vo=Object.defineProperty,_o=Object.getOwnPropertyDescriptor,Co=(o,e,t,n)=>{for(var s=n>1?void 0:n?_o(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&vo(e,t,s),s},Le=(o,e)=>(t,n)=>e(t,n,o);const Io="default-paste-formula";let $e=class extends c.Disposable{constructor(o,e,t,n,s){super(),this._currentUniverSheet=o,this._lexerTreeBuilder=e,this._sheetClipboardService=t,this._injector=n,this._formulaDataModel=s,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(o,e,t,n)=>this._onPasteCells(o,e,t,n,!0)}}_pasteWithFormulaHook(){return{id:Io,priority:10,onPasteCells:(o,e,t,n)=>this._onPasteCells(o,e,t,n,!1)}}_onPasteCells(o,e,t,n,s){var d;if([P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(n.pasteType))return{undos:[],redos:[]};const r=this._currentUniverSheet.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),i=e.unitId||r.getUnitId(),a=e.subUnitId||((d=r.getActiveSheet())==null?void 0:d.getSheetId());if(!i||!a)return{undos:[],redos:[]};const l=e.range,f=t,h={copyType:n.copyType||P.COPY_TYPE.COPY,copyRange:o==null?void 0:o.range,pasteType:n.pasteType};return this._injector.invoke(u=>Ro(i,a,l,f,u,h,this._lexerTreeBuilder,this._formulaDataModel,s,o))}};$e=Co([Le(0,c.IUniverInstanceService),Le(1,c.Inject(I.LexerTreeBuilder)),Le(2,P.ISheetClipboardService),Le(3,c.Inject(c.Injector)),Le(4,c.Inject(I.FormulaDataModel))],$e);function Ro(o,e,t,n,s,r,i,a,l=!1,f){const h=[],d=[],u=Eo(o,e,t,n,r,i,a,f),p={unitId:o,subUnitId:e,cellValue:u.getData()};h.push({id:U.SetRangeValuesMutation.id,params:p});const v=U.SetRangeValuesUndoMutationFactory(s,p);return d.push({id:U.SetRangeValuesMutation.id,params:v}),{undos:d,redos:h}}function Eo(o,e,t,n,s,r,i,a){return a?s.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?To(o,e,t,n,i,a):s.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?bo(o,e,t,n,r,i,a):No(o,e,t,n,r,i,a):yo(o,e,t,n,i)}function yo(o,e,t,n,s){const r=new c.ObjectMatrix,i=s.getSheetFormulaData(o,e);return n.forValue((a,l,f)=>{var p;const h=t.rows[a],d=t.cols[l],u={};c.isFormulaString(f.v)?(u.v=null,u.f=`${f.v}`,u.si=null,u.p=null,r.setValue(h,d,u)):(p=i==null?void 0:i[h])!=null&&p[d]&&(u.v=f.v,u.f=null,u.si=null,u.p=null,r.setValue(h,d,u))}),r}function To(o,e,t,n,s,r){var f,h;const i=new c.ObjectMatrix,a=(h=(f=s.getArrayFormulaCellData())==null?void 0:f[r.unitId])==null?void 0:h[r.subUnitId],l=s.getSheetFormulaData(o,e);return n.forValue((d,u,p)=>{var R,y;const v=r.range.rows[d%r.range.rows.length],C=r.range.cols[u%r.range.cols.length],g=t.rows[d],E=t.cols[u],m={};if(c.isFormulaString(p.f)||c.isFormulaId(p.si))m.v=p.v,m.f=null,m.si=null,m.p=null,i.setValue(g,E,m);else if((R=a==null?void 0:a[v])!=null&&R[C]){const M=a[v][C];m.v=M.v,m.f=null,m.si=null,m.p=null,i.setValue(g,E,m)}else if((y=l==null?void 0:l[g])!=null&&y[E]){if(m.v=p.v,m.f=null,m.si=null,m.p=null,p.p){const M=sn(p);M&&(m.v=M)}i.setValue(g,E,m)}}),i}function bo(o,e,t,n,s,r,i){const a=new c.ObjectMatrix,l=new Map;return n.forValue((f,h,d)=>{const u=t.rows[f],p=t.cols[h],v={};if(c.isFormulaId(d.si)){if(i.unitId!==o||i.subUnitId!==e){const C=r.getFormulaStringByCell(i.range.rows[f%i.range.rows.length],i.range.cols[h%i.range.cols.length],i.subUnitId,i.unitId),g=t.cols[h]-i.range.cols[h%i.range.cols.length],E=t.rows[f]-i.range.rows[f%i.range.rows.length],m=s.moveFormulaRefOffset(C||"",g,E);v.si=null,v.f=m}else v.si=d.si,v.f=null;v.v=null,v.p=null,a.setValue(u,p,v)}else if(c.isFormulaString(d.f)){const C=`${f%i.range.rows.length}_${h%i.range.cols.length}`;let g=l.get(C);if(g)v.si=g,v.f=null;else{g=c.Tools.generateRandomId(6),l.set(C,g);const E=t.cols[h]-i.range.cols[h%i.range.cols.length],m=t.rows[f]-i.range.rows[f%i.range.rows.length],R=s.moveFormulaRefOffset(d.f||"",E,m);v.si=g,v.f=R}v.v=null,v.p=null,a.setValue(u,p,v)}else{if(v.v=d.v,v.f=null,v.si=null,v.p=null,d.p){const C=sn(d);C&&(v.v=C)}a.setValue(u,p,v)}}),a}function No(o,e,t,n,s,r,i){const a=new c.ObjectMatrix,l=new Map,f=r.getSheetFormulaData(o,e);return n.forValue((h,d,u)=>{var g;const p=t.rows[h],v=t.cols[d],C={};if(c.isFormulaId(u.si)){if(i.unitId!==o||i.subUnitId!==e){const E=r.getFormulaStringByCell(i.range.rows[h%i.range.rows.length],i.range.cols[d%i.range.cols.length],i.subUnitId,i.unitId),m=t.cols[d]-i.range.cols[d%i.range.cols.length],R=t.rows[h]-i.range.rows[h%i.range.rows.length],y=s.moveFormulaRefOffset(E||"",m,R);C.si=null,C.f=y}else C.si=u.si,C.f=null;C.v=null,C.p=null,a.setValue(p,v,C)}else if(c.isFormulaString(u.f)){const E=`${h%i.range.rows.length}_${d%i.range.cols.length}`;let m=l.get(E);if(m)C.si=m,C.f=null;else{m=c.Tools.generateRandomId(6),l.set(E,m);const R=t.cols[d]-i.range.cols[d%i.range.cols.length],y=t.rows[h]-i.range.rows[h%i.range.rows.length],M=s.moveFormulaRefOffset(u.f||"",R,y);C.si=m,C.f=M}C.v=null,C.p=null,a.setValue(p,v,C)}else(g=f==null?void 0:f[p])!=null&&g[v]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,a.setValue(p,v,C))}),a}function sn(o){if(o!=null&&o.p){const e=o==null?void 0:o.p.body;if(e==null)return;const t=e.dataStream;return t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t}}var Mo=Object.defineProperty,Oo=Object.getOwnPropertyDescriptor,Ao=(o,e,t,n)=>{for(var s=n>1?void 0:n?Oo(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&Mo(e,t,s),s},Te=(o,e)=>(t,n)=>e(t,n,o);let et=class extends c.Disposable{constructor(e,t,n,s,r,i,a,l){super();V(this,"_previousShape");V(this,"_skeleton");this._context=e,this._sheetInterceptorService=t,this._formulaDataModel=n,this._themeService=s,this._renderManagerService=r,this._sheetSkeletonManagerService=i,this._commandService=a,this._logService=l,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(e=>{var t,n;if(e==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:s}=e,r=(n=(t=this._skeleton)==null?void 0:t.worksheet)==null?void 0:n.getSheetId();if(this._changeRuntime(s),r!==s.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:a}=e;this._updateArrayFormulaRangeShape(i,a)}}}))}_changeRuntime(e){this._skeleton=e}_initInterceptorEditorStart(){this.disposeWithMe(c.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(U.BEFORE_CELL_EDIT,{handler:(e,t,n)=>{var v,C,g,E;const{row:s,col:r,unitId:i,subUnitId:a,worksheet:l}=t,f=this._formulaDataModel.getArrayFormulaRange(),h=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),e==null)return n(e);let d=null;const u=this._formulaDataModel.getFormulaStringByCell(s,r,a,i);if(u!==null&&(d={f:u}),e.v!=null&&e.v!==""&&((g=(C=(v=h[i])==null?void 0:v[a])==null?void 0:C[s])==null?void 0:g[r])==null)return d?{...e,...d}:n(e);const p=(E=f==null?void 0:f[i])==null?void 0:E[a];return p!=null&&(d=this._displayArrayFormulaRangeShape(p,s,r,i,a,l,d)),d?{...e,...d}:n(e)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{(e.id===I.SetFormulaCalculationResultMutation.id||e.id===I.SetArrayFormulaDataMutation.id&&t&&t.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{U.SetWorksheetRowAutoHeightMutation.id===e.id&&requestIdleCallback(()=>{const t=e.params,{unitId:n,subUnitId:s,rowsAutoHeightInfo:r}=t;this._refreshArrayFormulaRangeShapeByRow(n,s,r)})}))}_displayArrayFormulaRangeShape(e,t,n,s,r,i,a){const l=this._formulaDataModel.getSheetFormulaData(s,r);return new c.ObjectMatrix(e).forValue((f,h,d)=>{var g;if(d==null)return!0;const{startRow:u,startColumn:p,endRow:v,endColumn:C}=d;if(f===t&&h===n)return this._createArrayFormulaRangeShape(d,s),!1;if(t>=u&&t<=v&&n>=p&&n<=C){const E=i.getCell(u,p);if((E==null?void 0:E.v)===I.ErrorType.SPILL)return;const m=(g=l==null?void 0:l[f])==null?void 0:g[h];return m==null||m.f==null?!0:(a==null&&(a={f:m.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(d,s),!1)}}),a}_createArrayFormulaRangeShape(e,t){const n=this._renderManagerService.getRenderById(t),s=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n||!s)return;const{scene:r}=n;if(!r)return;const i=this._themeService.getCurrentTheme(),a={range:e,primary:null,style:{strokeWidth:1,stroke:i.hyacinth700,fill:new c.ColorKit(i.colorWhite).setAlpha(0).toString(),widgets:{}}},l=P.attachSelectionWithCoord(a,s),{rowHeaderWidth:f,columnHeaderHeight:h}=s,d=new P.SelectionControl(r,P.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:f,columnHeaderHeight:h});d.updateRangeBySelectionWithCoord(l),d.setEvent(!1),this._previousShape=d}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(e,t){if(this._previousShape){const{startRow:n,endRow:s,startColumn:r,endColumn:i}=this._previousShape.getRange(),a={startRow:n,endRow:s,startColumn:r,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(a,e)}}_checkCurrentSheet(e,t){const n=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n)return!1;const s=n.worksheet;return s?s.unitId===e&&s.getSheetId()===t:!1}_updateArrayFormulaRangeShape(e,t){this._checkCurrentSheet(e,t)&&this._previousShape&&this._refreshArrayFormulaRangeShape(e)}_refreshArrayFormulaRangeShapeByRow(e,t,n){if(!this._checkCurrentSheet(e,t)||!this._previousShape)return;const{startRow:s,endRow:r,startColumn:i,endColumn:a}=this._previousShape.getRange();for(let l=0;l<n.length;l++){const{row:f}=n[l];if(s>=f){const h={startRow:s,endRow:r,startColumn:i,endColumn:a};this._refreshArrayFormulaRangeShape(e,h);break}}}};et=Ao([Te(1,c.Inject(U.SheetInterceptorService)),Te(2,c.Inject(I.FormulaDataModel)),Te(3,c.Inject(c.ThemeService)),Te(4,G.IRenderManagerService),Te(5,c.Inject(P.SheetSkeletonManagerService)),Te(6,c.ICommandService),Te(7,c.ILogService)],et);var xo=Object.defineProperty,Po=Object.getOwnPropertyDescriptor,Do=(o,e,t,n)=>{for(var s=n>1?void 0:n?Po(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&xo(e,t,s),s},rn=(o,e)=>(t,n)=>e(t,n,o);const Fo={tl:{size:6,color:"#409f11"}};let tt=class extends c.RxDisposable{constructor(o,e){super(),this._sheetInterceptorService=o,this._formulaDataModel=e,this.disposeWithMe(this._sheetInterceptorService.intercept(U.INTERCEPTOR_POINT.CELL_CONTENT,{effect:c.InterceptorEffectEnum.Style,handler:(t,n,s)=>{var a,l,f,h;const r=(h=(f=(l=(a=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:a[n.unitId])==null?void 0:l[n.subUnitId])==null?void 0:f[n.row])==null?void 0:h[n.col];return nn(t,!!r)?s({...t,markers:{...t==null?void 0:t.markers,...Fo}}):s(t)},priority:10}))}};tt=Do([rn(0,c.Inject(U.SheetInterceptorService)),rn(1,c.Inject(I.FormulaDataModel))],tt);function Lo(){const o=c.useDependency(me.TriggerCalculationController),e=c.useDependency(c.ICommandService),t=c.useObservable(o.progress$),n=S.useCallback(()=>{e.executeCommand(I.SetFormulaCalculationStopMutation.id)},[e]),s=S.useCallback(()=>{o.clearProgress()},[o]);return _.jsx(O.ProgressBar,{progress:t,onTerminate:n,onClearProgress:s})}const wo=(o,e=100)=>{S.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{o(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[o,e])},q={formulaHelpFunction:"univer-formula-help-function",formulaHelpFunctionTitle:"univer-formula-help-function-title",formulaHelpFunctionTitleIcons:"univer-formula-help-function-title-icons",formulaHelpFunctionTitleIcon:"univer-formula-help-function-title-icon",formulaHelpFunctionContent:"univer-formula-help-function-content",formulaHelpFunctionContentInner:"univer-formula-help-function-content-inner",formulaHelpFunctionContentParams:"univer-formula-help-function-content-params",formulaHelpFunctionContentParamsTitle:"univer-formula-help-function-content-params-title",formulaHelpFunctionContentParamsDetail:"univer-formula-help-function-content-params-detail",formulaHelpFunctionActive:"univer-formula-help-function-active",formulaHelpDecorator:"univer-formula-help-decorator",formulaHelpParam:"univer-formula-help-param",formulaHelpParamPrefix:"univer-formula-help-param-prefix",formulaHelpParamItem:"univer-formula-help-param-item",formulaHelpParamActive:"univer-formula-help-param-active"};function ko(){const[o,e]=S.useState(!1),[t,n]=S.useState(!0),[s,r]=S.useState(!0),[i,a]=S.useState(0),[l,f]=S.useState([0,0]),[h,d]=S.useState({left:0,top:0}),[u,p]=S.useState(null),v=c.useDependency(Ne),C=c.useDependency(c.LocaleService),g=C.t("formula.prompt.required"),E=C.t("formula.prompt.optional"),m=c.useDependency(c.IUniverInstanceService),R=c.useDependency(J.IEditorService),y=c.useDependency(O.ISidebarService),M=c.useInjector();wo(b),S.useEffect(()=>{const L=v.help$.subscribe(k=>{const{visible:D,paramIndex:x,functionInfo:z}=k;if(!D){e(D);return}const w=T();if(w==null)return;const{left:H,top:B,height:W}=w;z.description===""&&z.functionParameter.length===0||(f([H,B+W]),a(x),p(z),d({left:H,top:B}),e(D))}),F=y.scrollEvent$.pipe(K.throttleTime(100)).subscribe(b);return()=>{L==null||L.unsubscribe(),F.unsubscribe()}},[]);function b(){if(!s)return;const L=T();if(L==null)return;const{left:F,top:k,height:D}=L;f([F,k+D])}function T(){const L=m.getCurrentUniverDocInstance();if(!L)return;const F=L.getUnitId();if(!R.isEditor(F))return;const k=R.getEditor(F);return k==null?void 0:k.getBoundingClientRect()}function A(L){a(L)}function N(){r(!s),M.get(O.ILayoutService).focus()}return _.jsx(_.Fragment,{children:s?_.jsx(ne.Popup,{visible:o,offset:l,children:u?_.jsxs("div",{className:q.formulaHelpFunction,children:[_.jsxs("div",{className:q.formulaHelpFunctionTitle,children:[_.jsx(jo,{prefix:u.functionName,value:u.functionParameter,active:i,onClick:A}),_.jsxs("div",{className:q.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:q.formulaHelpFunctionTitleIcon,style:{transform:t?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>n(!t),children:_.jsx(ct,{})}),_.jsx("div",{className:q.formulaHelpFunctionTitleIcon,onClick:N,children:_.jsx(Ze,{})})]})]}),_.jsx("div",{className:q.formulaHelpFunctionContent,style:{height:t?"unset":0,padding:t?"revert-layer":0},children:_.jsxs("div",{className:q.formulaHelpFunctionContentInner,children:[_.jsx(Ct,{title:C.t("formula.prompt.helpExample"),value:`${u.functionName}(${u.functionParameter.map(L=>L.example).join(",")})`}),_.jsx(Ct,{title:C.t("formula.prompt.helpAbstract"),value:u.description}),u&&u.functionParameter&&u.functionParameter.map((L,F)=>_.jsx(Ct,{className:i===F?q.formulaHelpFunctionActive:"",title:L.name,value:`${L.require?g:E} ${L.detail}`},F))]})})]}):_.jsx(_.Fragment,{})}):o?_.jsx("div",{className:q.formulaHelpDecorator,onClick:()=>r(!s),style:{left:h.left-24,top:h.top},children:_.jsx(Pt,{})}):_.jsx(_.Fragment,{})})}const Ct=o=>_.jsxs("div",{className:q.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`
19
+ `:Ce.formulaSearchFunctionItem,onMouseEnter:()=>R(A),onMouseLeave:y,onMouseMove:b,onClick:()=>{r(T.name),m&&m.focus()},children:[_.jsxs("span",{className:Ce.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Ce.formulaSearchFunctionItemNameLight,children:T.name.substring(0,t.length)}),_.jsx("span",{children:T.name.slice(t.length)})]}),_.jsx("span",{className:Ce.formulaSearchFunctionItemDesc,children:T.desc})]},A))})})}const en=o=>o.startsWith(I.operatorToken.EQUALS)?o.slice(1):"",gt=()=>{};function tn(o){const{errorText:e,initValue:t,unitId:n,subUnitId:r,isFocus:s=!0,isSupportAcrossSheet:i=!1,onFocus:a=gt,onBlur:l=gt,onChange:f,onVerify:h,actions:d}=o,u=c.useDependency(J.IEditorService),p=S.useRef(null),[v,C]=S.useState(()=>t.startsWith(I.operatorToken.EQUALS)?t:"");d&&(d.handleOutClick=(Z,Q)=>{p.current&&!p.current.contains(Z.target)&&Q()});const g=S.useMemo(()=>en(v),[v]),E=S.useRef(null),[m,R]=S.useState(),[y,M]=S.useState(s),b=S.useRef(null),T=S.useMemo(()=>c.createInternalEditorID(`${P.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),A=S.useMemo(()=>e!==void 0,[e]),N=Xe(),L=S.useMemo(()=>N(g),[g]),F=kt(L,Z=>{f(`=${Z}`)},m),k=Ut("="),D=at(n),x=(Z,Q=!0)=>{if(!m)return;const se=N(Z),ie=k(m,se,Q);D(ie)};no(y,h,v);const z=Ht(m),w=Yt(y);S.useLayoutEffect(()=>{if(s){const Z=setTimeout(()=>{M(s),s&&z()},30);return()=>{clearTimeout(Z)}}else w(),M(s)},[s,z]);const{checkScrollBar:H}=Gt(m);lt(y,n),Vt(y,m),to(y,n,r,L,i,m,(Z,Q,se)=>{const ie=`=${Z}`;F(),C(ie),x(Z),se&&(z(),Q!==-1&&setTimeout(()=>{const Y={startOffset:Q+1,endOffset:Q+1};m==null||m.setSelectionRanges([Y]);const X=m==null?void 0:m.render.with(J.DocBackScrollRenderController);X==null||X.scrollToRange({...Y,collapsed:!0})},50),H())}),zt(),dt(y,n,i,M,l,gt);const{searchList:W,searchText:$,handlerFormulaReplace:le,reset:ue}=Xn(y,L,m),{functionInfo:he,paramIndex:ee,reset:re}=Zn(y,v,m);S.useEffect(()=>{if(m){const Z=m.input$.subscribe(Q=>{var ie,Y;const se=((Y=(ie=Q.data.body)==null?void 0:ie.dataStream)!=null?Y:"").replaceAll(/\n|\r/g,"");F(),C(se),x(en(se),!1)});return()=>{Z.unsubscribe()}}},[m]),jt(g,"=",y,k,D,m),S.useLayoutEffect(()=>{let Z;if(b.current){Z=u.register({autofocus:!0,editorUnitId:T,isSingle:!0,initialSnapshot:{id:T,body:{dataStream:`${t}\r
20
+ `},documentStyle:{}}},b.current);const Q=u.getEditor(T);R(Q)}return()=>{Z==null||Z.dispose()}},[]);const ce=Z=>{const Q=le(Z);if(Q){C(`=${Q.text}`);const se=m==null?void 0:m.getSelectionRanges();if(se&&se.length===1){const ie=se[0];if(ie.collapsed){const Y=Q.offset;setTimeout(()=>{m==null||m.setSelectionRanges([{startOffset:ie.startOffset-Y,endOffset:ie.endOffset-Y}])},30)}}ue(),z(),x(Q.text)}},Re=()=>{setTimeout(()=>{M(!0),a(),z()},30)};return _.jsxs("div",{className:Ae.sheetEmbeddingFormulaEditor,children:[_.jsxs("div",{className:wt(Ae.sheetEmbeddingFormulaEditorWrap,{[Ae.sheetEmbeddingFormulaEditorActive]:y,[Ae.sheetEmbeddingFormulaEditorError]:A}),ref:p,children:[_.jsx("div",{className:Ae.sheetEmbeddingFormulaEditorText,ref:b,onMouseUp:Re}),e!==void 0?_.jsx("div",{className:Ae.sheetEmbeddingFormulaEditorErrorWrap,children:e}):null]}),_.jsx(Yn,{editorId:T,paramIndex:ee,functionInfo:he,onClose:()=>{re(),z()}}),_.jsx(ro,{searchText:$,editorId:T,searchList:W,onSelect:ce,ref:E})]})}const io="sheets-formula-ui.base.config",nn={};function co(o){return o.getContextValue(c.FOCUSING_DOC)&&o.getContextValue(c.FOCUSING_UNIVER_EDITOR)&&o.getContextValue(c.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)}function on(o,e=!1){return!e&&!(c.isFormulaString(o==null?void 0:o.f)||c.isFormulaId(o==null?void 0:o.si))?null:typeof(o==null?void 0:o.v)=="string"&&I.ERROR_TYPE_SET.has(o.v)?o.v:null}var ao=Object.defineProperty,lo=Object.getOwnPropertyDescriptor,uo=(o,e,t,n)=>{for(var r=n>1?void 0:n?lo(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&ao(e,t,r),r},Fe=(o,e)=>(t,n)=>e(t,n,o);const vt="SHEET_FORMULA_ALERT",fo={[I.ErrorType.DIV_BY_ZERO]:"divByZero",[I.ErrorType.NAME]:"name",[I.ErrorType.VALUE]:"value",[I.ErrorType.NUM]:"num",[I.ErrorType.NA]:"na",[I.ErrorType.CYCLE]:"cycle",[I.ErrorType.REF]:"ref",[I.ErrorType.SPILL]:"spill",[I.ErrorType.CALC]:"calc",[I.ErrorType.ERROR]:"error",[I.ErrorType.CONNECT]:"connect",[I.ErrorType.NULL]:"null"};let _t=class extends c.Disposable{constructor(o,e,t,n,r,s){super(),this._context=o,this._hoverManagerService=e,this._cellAlertManagerService=t,this._localeService=n,this._formulaDataModel=r,this._zenZoneService=s,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(B.debounceTime(100)).subscribe(o=>{var e,t,n,r,s;if(o){const a=this._context.unit.getActiveSheet();if(!a)return;const l=a.getCell(o.location.row,o.location.col),f=(r=(n=(t=(e=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:e[o.location.unitId])==null?void 0:t[o.location.subUnitId])==null?void 0:n[o.location.row])==null?void 0:r[o.location.col];if(c.isICellData(l)){const h=on(l,!!f);if(!h){this._hideAlert();return}const d=this._cellAlertManagerService.currentAlert.get(vt),u=(s=d==null?void 0:d.alert)==null?void 0:s.location;if(u&&u.row===o.location.row&&u.col===o.location.col&&u.subUnitId===o.location.subUnitId&&u.unitId===o.location.unitId)return;this._cellAlertManagerService.showAlert({type:P.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${fo[h]}`),location:o.location,width:200,height:74,key:vt});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(o=>{o&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(vt)}};_t=uo([Fe(1,c.Inject(P.HoverManagerService)),Fe(2,c.Inject(P.CellAlertManagerService)),Fe(3,c.Inject(c.LocaleService)),Fe(4,c.Inject(I.FormulaDataModel)),Fe(5,O.IZenZoneService)],_t);var ho=Object.defineProperty,mo=Object.getOwnPropertyDescriptor,So=(o,e,t,n)=>{for(var r=n>1?void 0:n?mo(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&ho(e,t,r),r},rn=(o,e)=>(t,n)=>e(t,n,o);let qe=class extends c.Disposable{constructor(o,e){super(),this._autoFillService=o,this._lexerTreeBuilder=e,this._registerAutoFill()}_registerAutoFill(){const o={type:P.DATA_TYPE.FORMULA,priority:1001,match:e=>c.isFormulaString(e==null?void 0:e.f)||c.isFormulaId(e==null?void 0:e.si),isContinue:(e,t)=>e.type===P.DATA_TYPE.FORMULA,applyFunctions:{[P.APPLY_TYPE.COPY]:(e,t,n,r)=>{const{data:s,index:i}=e;return this._fillCopyFormula(s,t,n,i,r)}}};this._autoFillService.registerRule(o)}_fillCopyFormula(o,e,t,n,r){var l,f;const s=go(r),i=[],a=new Map;for(let h=1;h<=e;h++){const d=(h-1)%o.length,u=c.Tools.deepClone(o[d]);if(u){const p=((l=o[d])==null?void 0:l.f)||"",v=((f=o[d])==null?void 0:f.si)||"",C=c.isFormulaString(p);if(c.isFormulaId(v))u.si=v,u.f=null,u.v=null,u.p=null,u.t=null,i.push(u);else if(C){let E=a.get(d);if(E)u.si=E,u.f=null,u.v=null,u.p=null,u.t=null;else{E=c.Tools.generateRandomId(6),a.set(d,E);const{offsetX:m,offsetY:R}=po(s,e,t),y=this._lexerTreeBuilder.moveFormulaRefOffset(p,m,R);u.si=E,u.f=y,u.v=null,u.p=null,u.t=null}i.push(u)}}}return i}};qe=So([rn(0,P.IAutoFillService),rn(1,c.Inject(I.LexerTreeBuilder))],qe);function po(o,e,t){let n=0,r=0;switch(t){case c.Direction.UP:r=-o*e;break;case c.Direction.RIGHT:n=o;break;case c.Direction.DOWN:r=o;break;case c.Direction.LEFT:n=-o*e;break}return{offsetX:n,offsetY:r}}function go(o){let e=0;for(const t in o)o[t].forEach(n=>{e+=n.data.length});return e}var vo=Object.defineProperty,_o=Object.getOwnPropertyDescriptor,Co=(o,e,t,n)=>{for(var r=n>1?void 0:n?_o(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&vo(e,t,r),r},Le=(o,e)=>(t,n)=>e(t,n,o);const Io="default-paste-formula";let $e=class extends c.Disposable{constructor(o,e,t,n,r){super(),this._currentUniverSheet=o,this._lexerTreeBuilder=e,this._sheetClipboardService=t,this._injector=n,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:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(o,e,t,n)=>this._onPasteCells(o,e,t,n,!0)}}_pasteWithFormulaHook(){return{id:Io,priority:10,onPasteCells:(o,e,t,n)=>this._onPasteCells(o,e,t,n,!1)}}_onPasteCells(o,e,t,n,r){var d;if([P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(n.pasteType))return{undos:[],redos:[]};const s=this._currentUniverSheet.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),i=e.unitId||s.getUnitId(),a=e.subUnitId||((d=s.getActiveSheet())==null?void 0:d.getSheetId());if(!i||!a)return{undos:[],redos:[]};const l=e.range,f=t,h={copyType:n.copyType||P.COPY_TYPE.COPY,copyRange:o==null?void 0:o.range,pasteType:n.pasteType};return this._injector.invoke(u=>Ro(i,a,l,f,u,h,this._lexerTreeBuilder,this._formulaDataModel,r,o))}};$e=Co([Le(0,c.IUniverInstanceService),Le(1,c.Inject(I.LexerTreeBuilder)),Le(2,P.ISheetClipboardService),Le(3,c.Inject(c.Injector)),Le(4,c.Inject(I.FormulaDataModel))],$e);function Ro(o,e,t,n,r,s,i,a,l=!1,f){const h=[],d=[],u=Eo(o,e,t,n,s,i,a,f),p={unitId:o,subUnitId:e,cellValue:u.getData()};h.push({id:U.SetRangeValuesMutation.id,params:p});const v=U.SetRangeValuesUndoMutationFactory(r,p);return d.push({id:U.SetRangeValuesMutation.id,params:v}),{undos:d,redos:h}}function Eo(o,e,t,n,r,s,i,a){return a?r.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?To(o,e,t,n,i,a):r.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?bo(o,e,t,n,s,i,a):No(o,e,t,n,s,i,a):yo(o,e,t,n,i)}function yo(o,e,t,n,r){const s=new c.ObjectMatrix,i=r.getSheetFormulaData(o,e);return n.forValue((a,l,f)=>{var p;const h=t.rows[a],d=t.cols[l],u={};c.isFormulaString(f.v)?(u.v=null,u.f=`${f.v}`,u.si=null,u.p=null,s.setValue(h,d,u)):(p=i==null?void 0:i[h])!=null&&p[d]&&(u.v=f.v,u.f=null,u.si=null,u.p=null,s.setValue(h,d,u))}),s}function To(o,e,t,n,r,s){var f,h;const i=new c.ObjectMatrix,a=(h=(f=r.getArrayFormulaCellData())==null?void 0:f[s.unitId])==null?void 0:h[s.subUnitId],l=r.getSheetFormulaData(o,e);return n.forValue((d,u,p)=>{var R,y;const v=s.range.rows[d%s.range.rows.length],C=s.range.cols[u%s.range.cols.length],g=t.rows[d],E=t.cols[u],m={};if(c.isFormulaString(p.f)||c.isFormulaId(p.si))m.v=p.v,m.f=null,m.si=null,m.p=null,i.setValue(g,E,m);else if((R=a==null?void 0:a[v])!=null&&R[C]){const M=a[v][C];m.v=M.v,m.f=null,m.si=null,m.p=null,i.setValue(g,E,m)}else if((y=l==null?void 0:l[g])!=null&&y[E]){if(m.v=p.v,m.f=null,m.si=null,m.p=null,p.p){const M=sn(p);M&&(m.v=M)}i.setValue(g,E,m)}}),i}function bo(o,e,t,n,r,s,i){const a=new c.ObjectMatrix,l=new Map;return n.forValue((f,h,d)=>{const u=t.rows[f],p=t.cols[h],v={};if(c.isFormulaId(d.si)){if(i.unitId!==o||i.subUnitId!==e){const C=s.getFormulaStringByCell(i.range.rows[f%i.range.rows.length],i.range.cols[h%i.range.cols.length],i.subUnitId,i.unitId),g=t.cols[h]-i.range.cols[h%i.range.cols.length],E=t.rows[f]-i.range.rows[f%i.range.rows.length],m=r.moveFormulaRefOffset(C||"",g,E);v.si=null,v.f=m}else v.si=d.si,v.f=null;v.v=null,v.p=null,a.setValue(u,p,v)}else if(c.isFormulaString(d.f)){const C=`${f%i.range.rows.length}_${h%i.range.cols.length}`;let g=l.get(C);if(g)v.si=g,v.f=null;else{g=c.Tools.generateRandomId(6),l.set(C,g);const E=t.cols[h]-i.range.cols[h%i.range.cols.length],m=t.rows[f]-i.range.rows[f%i.range.rows.length],R=r.moveFormulaRefOffset(d.f||"",E,m);v.si=g,v.f=R}v.v=null,v.p=null,a.setValue(u,p,v)}else{if(v.v=d.v,v.f=null,v.si=null,v.p=null,d.p){const C=sn(d);C&&(v.v=C)}a.setValue(u,p,v)}}),a}function No(o,e,t,n,r,s,i){const a=new c.ObjectMatrix,l=new Map,f=s.getSheetFormulaData(o,e);return n.forValue((h,d,u)=>{var g;const p=t.rows[h],v=t.cols[d],C={};if(c.isFormulaId(u.si)){if(i.unitId!==o||i.subUnitId!==e){const E=s.getFormulaStringByCell(i.range.rows[h%i.range.rows.length],i.range.cols[d%i.range.cols.length],i.subUnitId,i.unitId),m=t.cols[d]-i.range.cols[d%i.range.cols.length],R=t.rows[h]-i.range.rows[h%i.range.rows.length],y=r.moveFormulaRefOffset(E||"",m,R);C.si=null,C.f=y}else C.si=u.si,C.f=null;C.v=null,C.p=null,a.setValue(p,v,C)}else if(c.isFormulaString(u.f)){const E=`${h%i.range.rows.length}_${d%i.range.cols.length}`;let m=l.get(E);if(m)C.si=m,C.f=null;else{m=c.Tools.generateRandomId(6),l.set(E,m);const R=t.cols[d]-i.range.cols[d%i.range.cols.length],y=t.rows[h]-i.range.rows[h%i.range.rows.length],M=r.moveFormulaRefOffset(u.f||"",R,y);C.si=m,C.f=M}C.v=null,C.p=null,a.setValue(p,v,C)}else(g=f==null?void 0:f[p])!=null&&g[v]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,a.setValue(p,v,C))}),a}function sn(o){if(o!=null&&o.p){const e=o==null?void 0:o.p.body;if(e==null)return;const t=e.dataStream;return t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t}}var Mo=Object.defineProperty,Oo=Object.getOwnPropertyDescriptor,Ao=(o,e,t,n)=>{for(var r=n>1?void 0:n?Oo(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&Mo(e,t,r),r},Te=(o,e)=>(t,n)=>e(t,n,o);let et=class extends c.Disposable{constructor(e,t,n,r,s,i,a,l){super();K(this,"_previousShape");K(this,"_skeleton");this._context=e,this._sheetInterceptorService=t,this._formulaDataModel=n,this._themeService=r,this._renderManagerService=s,this._sheetSkeletonManagerService=i,this._commandService=a,this._logService=l,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(e=>{var t,n;if(e==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:r}=e,s=(n=(t=this._skeleton)==null?void 0:t.worksheet)==null?void 0:n.getSheetId();if(this._changeRuntime(r),s!==r.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:a}=e;this._updateArrayFormulaRangeShape(i,a)}}}))}_changeRuntime(e){this._skeleton=e}_initInterceptorEditorStart(){this.disposeWithMe(c.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(U.BEFORE_CELL_EDIT,{handler:(e,t,n)=>{var v,C,g,E;const{row:r,col:s,unitId:i,subUnitId:a,worksheet:l}=t,f=this._formulaDataModel.getArrayFormulaRange(),h=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),e==null)return n(e);let d=null;const u=this._formulaDataModel.getFormulaStringByCell(r,s,a,i);if(u!==null&&(d={f:u}),e.v!=null&&e.v!==""&&((g=(C=(v=h[i])==null?void 0:v[a])==null?void 0:C[r])==null?void 0:g[s])==null)return d?{...e,...d}:n(e);const p=(E=f==null?void 0:f[i])==null?void 0:E[a];return p!=null&&(d=this._displayArrayFormulaRangeShape(p,r,s,i,a,l,d)),d?{...e,...d}:n(e)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{(e.id===I.SetFormulaCalculationResultMutation.id||e.id===I.SetArrayFormulaDataMutation.id&&t&&t.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{U.SetWorksheetRowAutoHeightMutation.id===e.id&&requestIdleCallback(()=>{const t=e.params,{unitId:n,subUnitId:r,rowsAutoHeightInfo:s}=t;this._refreshArrayFormulaRangeShapeByRow(n,r,s)})}))}_displayArrayFormulaRangeShape(e,t,n,r,s,i,a){const l=this._formulaDataModel.getSheetFormulaData(r,s);return new c.ObjectMatrix(e).forValue((f,h,d)=>{var g;if(d==null)return!0;const{startRow:u,startColumn:p,endRow:v,endColumn:C}=d;if(f===t&&h===n)return this._createArrayFormulaRangeShape(d,r),!1;if(t>=u&&t<=v&&n>=p&&n<=C){const E=i.getCell(u,p);if((E==null?void 0:E.v)===I.ErrorType.SPILL)return;const m=(g=l==null?void 0:l[f])==null?void 0:g[h];return m==null||m.f==null?!0:(a==null&&(a={f:m.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(d,r),!1)}}),a}_createArrayFormulaRangeShape(e,t){const n=this._renderManagerService.getRenderById(t),r=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n||!r)return;const{scene:s}=n;if(!s)return;const i=this._themeService.getCurrentTheme(),a={range:e,primary:null,style:{strokeWidth:1,stroke:i.hyacinth700,fill:new c.ColorKit(i.colorWhite).setAlpha(0).toString(),widgets:{}}},l=P.attachSelectionWithCoord(a,r),{rowHeaderWidth:f,columnHeaderHeight:h}=r,d=new P.SelectionControl(s,P.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:f,columnHeaderHeight:h});d.updateRangeBySelectionWithCoord(l),d.setEvent(!1),this._previousShape=d}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(e,t){if(this._previousShape){const{startRow:n,endRow:r,startColumn:s,endColumn:i}=this._previousShape.getRange(),a={startRow:n,endRow:r,startColumn:s,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(a,e)}}_checkCurrentSheet(e,t){const n=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n)return!1;const r=n.worksheet;return r?r.unitId===e&&r.getSheetId()===t:!1}_updateArrayFormulaRangeShape(e,t){this._checkCurrentSheet(e,t)&&this._previousShape&&this._refreshArrayFormulaRangeShape(e)}_refreshArrayFormulaRangeShapeByRow(e,t,n){if(!this._checkCurrentSheet(e,t)||!this._previousShape)return;const{startRow:r,endRow:s,startColumn:i,endColumn:a}=this._previousShape.getRange();for(let l=0;l<n.length;l++){const{row:f}=n[l];if(r>=f){const h={startRow:r,endRow:s,startColumn:i,endColumn:a};this._refreshArrayFormulaRangeShape(e,h);break}}}};et=Ao([Te(1,c.Inject(U.SheetInterceptorService)),Te(2,c.Inject(I.FormulaDataModel)),Te(3,c.Inject(c.ThemeService)),Te(4,G.IRenderManagerService),Te(5,c.Inject(P.SheetSkeletonManagerService)),Te(6,c.ICommandService),Te(7,c.ILogService)],et);var xo=Object.defineProperty,Po=Object.getOwnPropertyDescriptor,Do=(o,e,t,n)=>{for(var r=n>1?void 0:n?Po(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&xo(e,t,r),r},cn=(o,e)=>(t,n)=>e(t,n,o);const Fo={tl:{size:6,color:"#409f11"}};let tt=class extends c.RxDisposable{constructor(o,e){super(),this._sheetInterceptorService=o,this._formulaDataModel=e,this.disposeWithMe(this._sheetInterceptorService.intercept(U.INTERCEPTOR_POINT.CELL_CONTENT,{effect:c.InterceptorEffectEnum.Style,handler:(t,n,r)=>{var a,l,f,h;const s=(h=(f=(l=(a=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:a[n.unitId])==null?void 0:l[n.subUnitId])==null?void 0:f[n.row])==null?void 0:h[n.col];return on(t,!!s)?r({...t,markers:{...t==null?void 0:t.markers,...Fo}}):r(t)},priority:10}))}};tt=Do([cn(0,c.Inject(U.SheetInterceptorService)),cn(1,c.Inject(I.FormulaDataModel))],tt);function Lo(){const o=c.useDependency(me.TriggerCalculationController),e=c.useDependency(c.ICommandService),t=c.useObservable(o.progress$),n=S.useCallback(()=>{e.executeCommand(I.SetFormulaCalculationStopMutation.id)},[e]),r=S.useCallback(()=>{o.clearProgress()},[o]);return _.jsx(O.ProgressBar,{progress:t,onTerminate:n,onClearProgress:r})}const wo=(o,e=100)=>{S.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{o(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[o,e])},q={formulaHelpFunction:"univer-formula-help-function",formulaHelpFunctionTitle:"univer-formula-help-function-title",formulaHelpFunctionTitleIcons:"univer-formula-help-function-title-icons",formulaHelpFunctionTitleIcon:"univer-formula-help-function-title-icon",formulaHelpFunctionContent:"univer-formula-help-function-content",formulaHelpFunctionContentInner:"univer-formula-help-function-content-inner",formulaHelpFunctionContentParams:"univer-formula-help-function-content-params",formulaHelpFunctionContentParamsTitle:"univer-formula-help-function-content-params-title",formulaHelpFunctionContentParamsDetail:"univer-formula-help-function-content-params-detail",formulaHelpFunctionActive:"univer-formula-help-function-active",formulaHelpDecorator:"univer-formula-help-decorator",formulaHelpParam:"univer-formula-help-param",formulaHelpParamPrefix:"univer-formula-help-param-prefix",formulaHelpParamItem:"univer-formula-help-param-item",formulaHelpParamActive:"univer-formula-help-param-active"};function ko(){const[o,e]=S.useState(!1),[t,n]=S.useState(!0),[r,s]=S.useState(!0),[i,a]=S.useState(0),[l,f]=S.useState([0,0]),[h,d]=S.useState({left:0,top:0}),[u,p]=S.useState(null),v=c.useDependency(Ne),C=c.useDependency(c.LocaleService),g=C.t("formula.prompt.required"),E=C.t("formula.prompt.optional"),m=c.useDependency(c.IUniverInstanceService),R=c.useDependency(J.IEditorService),y=c.useDependency(O.ISidebarService),M=c.useInjector();wo(b),S.useEffect(()=>{const L=v.help$.subscribe(k=>{const{visible:D,paramIndex:x,functionInfo:z}=k;if(!D){e(D);return}const w=T();if(w==null)return;const{left:H,top:V,height:W}=w;z.description===""&&z.functionParameter.length===0||(f([H,V+W]),a(x),p(z),d({left:H,top:V}),e(D))}),F=y.scrollEvent$.pipe(B.throttleTime(100)).subscribe(b);return()=>{L==null||L.unsubscribe(),F.unsubscribe()}},[]);function b(){if(!r)return;const L=T();if(L==null)return;const{left:F,top:k,height:D}=L;f([F,k+D])}function T(){const L=m.getCurrentUniverDocInstance();if(!L)return;const F=L.getUnitId();if(!R.isEditor(F))return;const k=R.getEditor(F);return k==null?void 0:k.getBoundingClientRect()}function A(L){a(L)}function N(){s(!r),M.get(O.ILayoutService).focus()}return _.jsx(_.Fragment,{children:r?_.jsx(ne.Popup,{visible:o,offset:l,children:u?_.jsxs("div",{className:q.formulaHelpFunction,children:[_.jsxs("div",{className:q.formulaHelpFunctionTitle,children:[_.jsx(jo,{prefix:u.functionName,value:u.functionParameter,active:i,onClick:A}),_.jsxs("div",{className:q.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:q.formulaHelpFunctionTitleIcon,style:{transform:t?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>n(!t),children:_.jsx(ct,{})}),_.jsx("div",{className:q.formulaHelpFunctionTitleIcon,onClick:N,children:_.jsx(Ze,{})})]})]}),_.jsx("div",{className:q.formulaHelpFunctionContent,style:{height:t?"unset":0,padding:t?"revert-layer":0},children:_.jsxs("div",{className:q.formulaHelpFunctionContentInner,children:[_.jsx(Ct,{title:C.t("formula.prompt.helpExample"),value:`${u.functionName}(${u.functionParameter.map(L=>L.example).join(",")})`}),_.jsx(Ct,{title:C.t("formula.prompt.helpAbstract"),value:u.description}),u&&u.functionParameter&&u.functionParameter.map((L,F)=>_.jsx(Ct,{className:i===F?q.formulaHelpFunctionActive:"",title:L.name,value:`${L.require?g:E} ${L.detail}`},F))]})})]}):_.jsx(_.Fragment,{})}):o?_.jsx("div",{className:q.formulaHelpDecorator,onClick:()=>s(!r),style:{left:h.left-24,top:h.top},children:_.jsx(Pt,{})}):_.jsx(_.Fragment,{})})}const Ct=o=>_.jsxs("div",{className:q.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`
21
21
  ${q.formulaHelpFunctionContentParamsTitle}
22
22
  ${o.className}
23
- `,children:o.title}),_.jsx("div",{className:q.formulaHelpFunctionContentParamsDetail,children:o.value})]}),jo=o=>{const{prefix:e,value:t,active:n,onClick:s}=o;return _.jsxs("div",{className:q.formulaHelpParam,children:[_.jsxs("span",{className:q.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((r,i)=>_.jsxs("span",{className:q.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?q.formulaHelpFunctionActive:q.formulaHelpParamActive,onClick:()=>s(i),children:ht(r)}),i===t.length-1?"":","]},i)),")"]})},Ie={formulaSearchFunction:"univer-formula-search-function",formulaSearchFunctionItem:"univer-formula-search-function-item",formulaSearchFunctionItemName:"univer-formula-search-function-item-name",formulaSearchFunctionItemNameLight:"univer-formula-search-function-item-name-light",formulaSearchFunctionItemDesc:"univer-formula-search-function-item-desc",formulaSearchFunctionItemActive:"univer-formula-search-function-item-active"};function Ho(){const[o,e]=S.useState(!1),[t,n]=S.useState(0),[s,r]=S.useState([0,0]),[i,a]=S.useState([]),[l,f]=S.useState(""),h=S.useRef(null),d=c.useDependency(Ne),u=c.useDependency(c.IUniverInstanceService),p=c.useDependency(J.IEditorService);S.useEffect(()=>{let m=[],R=0;const y=d.search$.subscribe(T=>{const{visible:A,searchText:N,searchList:L}=T;if(!A){e(A);return}const F=v();if(F==null)return;const{left:k,top:D,height:x}=F;f(N),a(L),m=L,r([k,D+x]),e(A),n(0),R=0}),M=d.navigate$.subscribe(T=>{const{direction:A}=T;if(A===c.Direction.UP){let N=R-1;N=N<0?m.length-1:N,n(N),R=N}else if(A===c.Direction.DOWN){let N=R+1;N=N>=m.length?0:N,n(N),R=N}E(R)}),b=d.accept$.subscribe(T=>{const A=m[R].name;d.acceptFormulaName(A)});return()=>{y==null||y.unsubscribe(),M==null||M.unsubscribe(),b==null||b.unsubscribe()}},[]);function v(){const R=u.getCurrentUniverDocInstance().getUnitId();if(!p.isEditor(R))return;const y=p.getEditor(R);return y==null?void 0:y.getBoundingClientRect()}function C(m){n(m)}function g(){n(-1)}function E(m){var k;const R=(k=h.current)==null?void 0:k.querySelectorAll(`.${Ie.formulaSearchFunctionItem}`)[m];if(!R)return;const y=R.parentNode;if(!y)return;const b=y.getBoundingClientRect().top,T=y.offsetHeight,A=R.getBoundingClientRect(),N=A.top,L=A.height;if(N>=0&&N>b&&N-b+L<=T)return;const F=R.offsetTop-(T-L)/2;y.scrollTo({top:F,behavior:"smooth"})}return i.length>0&&_.jsx(ne.Popup,{visible:o,offset:s,children:_.jsx("ul",{className:Ie.formulaSearchFunction,ref:h,children:i.map((m,R)=>_.jsxs("li",{className:t===R?`
23
+ `,children:o.title}),_.jsx("div",{className:q.formulaHelpFunctionContentParamsDetail,children:o.value})]}),jo=o=>{const{prefix:e,value:t,active:n,onClick:r}=o;return _.jsxs("div",{className:q.formulaHelpParam,children:[_.jsxs("span",{className:q.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>_.jsxs("span",{className:q.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?q.formulaHelpFunctionActive:q.formulaHelpParamActive,onClick:()=>r(i),children:ht(s)}),i===t.length-1?"":","]},i)),")"]})},Ie={formulaSearchFunction:"univer-formula-search-function",formulaSearchFunctionItem:"univer-formula-search-function-item",formulaSearchFunctionItemName:"univer-formula-search-function-item-name",formulaSearchFunctionItemNameLight:"univer-formula-search-function-item-name-light",formulaSearchFunctionItemDesc:"univer-formula-search-function-item-desc",formulaSearchFunctionItemActive:"univer-formula-search-function-item-active"};function Ho(){const[o,e]=S.useState(!1),[t,n]=S.useState(0),[r,s]=S.useState([0,0]),[i,a]=S.useState([]),[l,f]=S.useState(""),h=S.useRef(null),d=c.useDependency(Ne),u=c.useDependency(c.IUniverInstanceService),p=c.useDependency(J.IEditorService);S.useEffect(()=>{let m=[],R=0;const y=d.search$.subscribe(T=>{const{visible:A,searchText:N,searchList:L}=T;if(!A){e(A);return}const F=v();if(F==null)return;const{left:k,top:D,height:x}=F;f(N),a(L),m=L,s([k,D+x]),e(A),n(0),R=0}),M=d.navigate$.subscribe(T=>{const{direction:A}=T;if(A===c.Direction.UP){let N=R-1;N=N<0?m.length-1:N,n(N),R=N}else if(A===c.Direction.DOWN){let N=R+1;N=N>=m.length?0:N,n(N),R=N}E(R)}),b=d.accept$.subscribe(T=>{const A=m[R].name;d.acceptFormulaName(A)});return()=>{y==null||y.unsubscribe(),M==null||M.unsubscribe(),b==null||b.unsubscribe()}},[]);function v(){const R=u.getCurrentUniverDocInstance().getUnitId();if(!p.isEditor(R))return;const y=p.getEditor(R);return y==null?void 0:y.getBoundingClientRect()}function C(m){n(m)}function g(){n(-1)}function E(m){var k;const R=(k=h.current)==null?void 0:k.querySelectorAll(`.${Ie.formulaSearchFunctionItem}`)[m];if(!R)return;const y=R.parentNode;if(!y)return;const b=y.getBoundingClientRect().top,T=y.offsetHeight,A=R.getBoundingClientRect(),N=A.top,L=A.height;if(N>=0&&N>b&&N-b+L<=T)return;const F=R.offsetTop-(T-L)/2;y.scrollTo({top:F,behavior:"smooth"})}return i.length>0&&_.jsx(ne.Popup,{visible:o,offset:r,children:_.jsx("ul",{className:Ie.formulaSearchFunction,ref:h,children:i.map((m,R)=>_.jsxs("li",{className:t===R?`
24
24
  ${Ie.formulaSearchFunctionItem}
25
25
  ${Ie.formulaSearchFunctionItemActive}
26
- `:Ie.formulaSearchFunctionItem,onMouseEnter:()=>C(R),onMouseLeave:g,onClick:()=>d.acceptFormulaName(m.name),children:[_.jsxs("span",{className:Ie.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Ie.formulaSearchFunctionItemNameLight,children:m.name.substring(0,l.length)}),_.jsx("span",{children:m.name.slice(l.length)})]}),_.jsx("span",{className:Ie.formulaSearchFunctionItemDesc,children:m.desc})]},R))})})}function Uo(){return _.jsxs(_.Fragment,{children:[_.jsx(Ho,{}),_.jsx(ko,{})]})}const cn={formulaMoreFunctions:"univer-formula-more-functions",formulaMoreFunctionsOperation:"univer-formula-more-functions-operation"};function an(o){const{prefix:e,value:t}=o;return _.jsxs("div",{children:[_.jsxs("span",{children:[e,"("]}),t&&t.map((n,s)=>_.jsxs("span",{children:[_.jsx("span",{children:ht(n)}),s===t.length-1?"":","]},s)),")"]})}const It={formulaFunctionParams:"univer-formula-function-params",formulaFunctionParamsTitle:"univer-formula-function-params-title",formulaFunctionParamsDetail:"univer-formula-function-params-detail"};function we(o){const{className:e,value:t,title:n}=o;return _.jsxs("div",{className:It.formulaFunctionParams,children:[_.jsx("div",{className:`
26
+ `:Ie.formulaSearchFunctionItem,onMouseEnter:()=>C(R),onMouseLeave:g,onClick:()=>d.acceptFormulaName(m.name),children:[_.jsxs("span",{className:Ie.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Ie.formulaSearchFunctionItemNameLight,children:m.name.substring(0,l.length)}),_.jsx("span",{children:m.name.slice(l.length)})]}),_.jsx("span",{className:Ie.formulaSearchFunctionItemDesc,children:m.desc})]},R))})})}function Uo(){return _.jsxs(_.Fragment,{children:[_.jsx(Ho,{}),_.jsx(ko,{})]})}const an={formulaMoreFunctions:"univer-formula-more-functions",formulaMoreFunctionsOperation:"univer-formula-more-functions-operation"};function ln(o){const{prefix:e,value:t}=o;return _.jsxs("div",{children:[_.jsxs("span",{children:[e,"("]}),t&&t.map((n,r)=>_.jsxs("span",{children:[_.jsx("span",{children:ht(n)}),r===t.length-1?"":","]},r)),")"]})}const It={formulaFunctionParams:"univer-formula-function-params",formulaFunctionParamsTitle:"univer-formula-function-params-title",formulaFunctionParamsDetail:"univer-formula-function-params-detail"};function we(o){const{className:e,value:t,title:n}=o;return _.jsxs("div",{className:It.formulaFunctionParams,children:[_.jsx("div",{className:`
27
27
  ${It.formulaFunctionParamsTitle}
28
28
  ${e}
29
- `,children:n}),_.jsx("div",{className:It.formulaFunctionParamsDetail,children:t})]})}const ke={formulaInputParamsList:"univer-formula-input-params-list",formulaInputParamsListItemName:"univer-formula-input-params-list-item-name",formulaInputParamsListItemSelector:"univer-formula-input-params-list-item-selector"};function Wo(o){const{functionInfo:e,onChange:t}=o;if(!e)return null;S.useState([]);const[n,s]=S.useState(e.functionParameter),[r,i]=S.useState(-1);return _.jsxs("div",{className:ke.formulaInputParams,children:[_.jsx("div",{className:ke.formulaInputParamsList,children:n.map((a,l)=>_.jsxs("div",{children:[_.jsx("div",{className:ke.formulaInputParamsListItemName,children:a.name}),_.jsx("div",{className:ke.formulaInputParamsListItemSelector})]},l))}),_.jsx("div",{className:ke.formulaInputParamsInfo,children:_.jsx(we,{title:r===-1?_.jsx(an,{prefix:e.functionName,value:n}):n[r].name,value:r===-1?e.description:n[r].detail})})]})}const pe={formulaSelectFunctionSelect:"univer-formula-select-function-select",formulaSelectFunctionResult:"univer-formula-select-function-result",formulaSelectFunctionResultItem:"univer-formula-select-function-result-item",formulaSelectFunctionResultItemNameLight:"univer-formula-select-function-result-item-name-light",formulaSelectFunctionResultItemSelected:"univer-formula-select-function-result-item-selected",formulaSelectFunctionResultItemActive:"univer-formula-select-function-result-item-active",formulaSelectFunctionContent:"univer-formula-select-function-content"};function Bo(o){const{onChange:e}=o,t="-1",[n,s]=S.useState(""),[r,i]=S.useState([]),[a,l]=S.useState(0),[f,h]=S.useState(t),[d,u]=S.useState(0),[p,v]=S.useState(null),C=c.useDependency(me.IDescriptionService),g=c.useDependency(c.LocaleService),E=c.useDependency(O.ISidebarService),m=c.useObservable(E.sidebarOptions$),R=Vn(I.FunctionType,g);R.unshift({label:g.t("formula.moreFunctions.allFunctions"),value:t});const y=g.t("formula.prompt.required"),M=g.t("formula.prompt.optional");S.useEffect(()=>{A(t)},[]),S.useEffect(()=>{T(0)},[r]),S.useEffect(()=>{m!=null&&m.visible&&(s(""),i([]),l(0),h(t),u(0),v(null),A(t))},[m]);const b=D=>{if(n.trim()==="")return D;const x=new RegExp(`(${n.toLocaleUpperCase()})`);return D.split(x).filter(Boolean).map((w,H)=>w.match(x)?_.jsx("span",{className:pe.formulaSelectFunctionResultItemNameLight,children:w},H):w)},T=D=>{if(r.length===0){v(null);return}u(D);const x=C.getFunctionInfo(r[D].name);if(!x){v(null);return}v(x),e(x)};function A(D){h(D);const x=C.getSearchListByType(+D);i(x)}function N(D){s(D);const x=C.getSearchListByName(D);i(x)}function L(D){if(D.stopPropagation(),D.key==="ArrowDown"){const x=a+1;l(x===r.length?0:x)}else if(D.key==="ArrowUp"){const x=a-1;l(x===-1?r.length-1:x)}else D.key==="Enter"&&T(a)}const F=D=>{l(D)},k=()=>{l(-1)};return _.jsxs("div",{children:[_.jsxs("div",{className:pe.formulaSelectFunctionSelect,children:[_.jsx(ne.Select,{value:f,options:R,onChange:A}),_.jsx(ne.Input,{placeholder:g.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:L,value:n,onChange:N,size:"large",allowClear:!0})]}),_.jsx("ul",{className:pe.formulaSelectFunctionResult,onKeyDown:L,tabIndex:-1,children:r.map(({name:D},x)=>_.jsxs("li",{className:a===x?`
29
+ `,children:n}),_.jsx("div",{className:It.formulaFunctionParamsDetail,children:t})]})}const ke={formulaInputParamsList:"univer-formula-input-params-list",formulaInputParamsListItemName:"univer-formula-input-params-list-item-name",formulaInputParamsListItemSelector:"univer-formula-input-params-list-item-selector"};function Wo(o){const{functionInfo:e,onChange:t}=o;if(!e)return null;S.useState([]);const[n,r]=S.useState(e.functionParameter),[s,i]=S.useState(-1);return _.jsxs("div",{className:ke.formulaInputParams,children:[_.jsx("div",{className:ke.formulaInputParamsList,children:n.map((a,l)=>_.jsxs("div",{children:[_.jsx("div",{className:ke.formulaInputParamsListItemName,children:a.name}),_.jsx("div",{className:ke.formulaInputParamsListItemSelector})]},l))}),_.jsx("div",{className:ke.formulaInputParamsInfo,children:_.jsx(we,{title:s===-1?_.jsx(ln,{prefix:e.functionName,value:n}):n[s].name,value:s===-1?e.description:n[s].detail})})]})}const pe={formulaSelectFunctionSelect:"univer-formula-select-function-select",formulaSelectFunctionResult:"univer-formula-select-function-result",formulaSelectFunctionResultItem:"univer-formula-select-function-result-item",formulaSelectFunctionResultItemNameLight:"univer-formula-select-function-result-item-name-light",formulaSelectFunctionResultItemSelected:"univer-formula-select-function-result-item-selected",formulaSelectFunctionResultItemActive:"univer-formula-select-function-result-item-active",formulaSelectFunctionContent:"univer-formula-select-function-content"};function Bo(o){const{onChange:e}=o,t="-1",[n,r]=S.useState(""),[s,i]=S.useState([]),[a,l]=S.useState(0),[f,h]=S.useState(t),[d,u]=S.useState(0),[p,v]=S.useState(null),C=c.useDependency(me.IDescriptionService),g=c.useDependency(c.LocaleService),E=c.useDependency(O.ISidebarService),m=c.useObservable(E.sidebarOptions$),R=Kn(I.FunctionType,g);R.unshift({label:g.t("formula.moreFunctions.allFunctions"),value:t});const y=g.t("formula.prompt.required"),M=g.t("formula.prompt.optional");S.useEffect(()=>{A(t)},[]),S.useEffect(()=>{T(0)},[s]),S.useEffect(()=>{m!=null&&m.visible&&(r(""),i([]),l(0),h(t),u(0),v(null),A(t))},[m]);const b=D=>{if(n.trim()==="")return D;const x=new RegExp(`(${n.toLocaleUpperCase()})`);return D.split(x).filter(Boolean).map((w,H)=>w.match(x)?_.jsx("span",{className:pe.formulaSelectFunctionResultItemNameLight,children:w},H):w)},T=D=>{if(s.length===0){v(null);return}u(D);const x=C.getFunctionInfo(s[D].name);if(!x){v(null);return}v(x),e(x)};function A(D){h(D);const x=C.getSearchListByType(+D);i(x)}function N(D){r(D);const x=C.getSearchListByName(D);i(x)}function L(D){if(D.stopPropagation(),D.key==="ArrowDown"){const x=a+1;l(x===s.length?0:x)}else if(D.key==="ArrowUp"){const x=a-1;l(x===-1?s.length-1:x)}else D.key==="Enter"&&T(a)}const F=D=>{l(D)},k=()=>{l(-1)};return _.jsxs("div",{children:[_.jsxs("div",{className:pe.formulaSelectFunctionSelect,children:[_.jsx(ne.Select,{value:f,options:R,onChange:A}),_.jsx(ne.Input,{placeholder:g.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:L,value:n,onChange:N,size:"large",allowClear:!0})]}),_.jsx("ul",{className:pe.formulaSelectFunctionResult,onKeyDown:L,tabIndex:-1,children:s.map(({name:D},x)=>_.jsxs("li",{className:a===x?`
30
30
  ${pe.formulaSelectFunctionResultItem}
31
31
  ${pe.formulaSelectFunctionResultItemActive}
32
- `:pe.formulaSelectFunctionResultItem,onMouseEnter:()=>F(x),onMouseLeave:k,onClick:()=>T(x),children:[d===x&&_.jsx(At,{className:pe.formulaSelectFunctionResultItemSelected}),_.jsx("span",{className:pe.formulaSelectFunctionResultItemName,children:b(D)})]},x))}),p&&_.jsxs("div",{className:pe.formulaSelectFunctionContent,children:[_.jsx(we,{title:p.functionName,value:p.description}),_.jsx(we,{title:g.t("formula.moreFunctions.syntax"),value:_.jsx(an,{prefix:p.functionName,value:p.functionParameter})}),_.jsx(we,{title:g.t("formula.prompt.helpExample"),value:`${p.functionName}(${p.functionParameter.map(D=>D.example).join(",")})`}),p.functionParameter&&p.functionParameter.map((D,x)=>_.jsx(we,{title:D.name,value:`${D.require?y:M} ${D.detail}`},x))]})]})}function Vo(){const o=P.useActiveWorkbook(),[e,t]=S.useState(!0),[n,s]=S.useState(!1),[r,i]=S.useState(null),a=c.useDependency(c.LocaleService),l=c.useDependency(J.IEditorService);function f(){t(!e),s(!n)}function h(){l.setFormula(`=${r==null?void 0:r.functionName}(`)}return _.jsxs("div",{className:cn.formulaMoreFunctions,children:[e&&_.jsx(Bo,{onChange:i}),n&&_.jsx(Wo,{functionInfo:r,onChange:()=>{}}),_.jsxs("div",{className:cn.formulaMoreFunctionsOperation,children:[n&&_.jsx(ne.Button,{type:"primary",size:"small",onClick:f,children:a.t("formula.moreFunctions.next")}),n&&_.jsx(ne.Button,{size:"small",onClick:f,children:a.t("formula.moreFunctions.prev")}),e&&!!o&&_.jsx(ne.Button,{type:"primary",size:"small",onClick:h,children:a.t("formula.moreFunctions.confirm")})]})]})}function Ko(o){return{id:Ve.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:O.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$:O.getMenuHiddenObservable(o,c.UniverInstanceType.UNIVER_SHEET),disabled$:P.getCurrentRangeDisable$(o,{workbookTypes:[U.WorkbookEditablePermission],worksheetTypes:[U.WorksheetEditPermission,U.WorksheetSetCellValuePermission],rangeTypes:[U.RangeProtectionPermissionEditPoint]})}}function zo(o){return{id:ze.id,title:"formula.insert.more",type:O.MenuItemType.BUTTON}}function Yo(o){return o.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(K.switchMap(n=>n&&o.get(O.IClipboardInterfaceService)?new K.Observable(r=>r.next(!o.get(O.IClipboardInterfaceService).supportClipboard)):K.of(!0)))}function Go(o){return{id:We.id,type:O.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:Yo(o).pipe(K.combineLatestWith(P.getCurrentRangeDisable$(o,{workbookTypes:[U.WorkbookEditablePermission],rangeTypes:[U.RangeProtectionPermissionEditPoint],worksheetTypes:[U.WorksheetSetCellValuePermission,U.WorksheetEditPermission]})),K.map(([e,t])=>e||t))}}const Zo={[O.RibbonStartGroup.FORMULAS_INSERT]:{[Ve.id]:{order:1,menuItemFactory:Ko,[ze.id]:{order:1,menuItemFactory:zo}}},[P.PASTE_SPECIAL_MENU_ID]:{[We.id]:{order:4,menuItemFactory:Go}}},ln="meta_key_ctrl_And_Shift",nt=[O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP,O.KeyCode.ARROW_LEFT,O.KeyCode.ARROW_RIGHT],Xo=[...nt,O.KeyCode.ENTER,O.KeyCode.TAB,O.KeyCode.ESC];function Qo(){const o=[];for(const e of Xo)o.push({id:ve.id,binding:e,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e}});return o}function Jo(){const o=[];for(const e of nt)o.push({id:ve.id,binding:e|O.MetaKeys.SHIFT,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,metaKey:O.MetaKeys.SHIFT}});return o}function qo(){const o=[];for(const e of nt)o.push({id:ve.id,binding:e|O.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,metaKey:O.MetaKeys.CTRL_COMMAND}});return o}function $o(){const o=[];for(const e of nt)o.push({id:ve.id,binding:e|O.MetaKeys.SHIFT|O.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,metaKey:ln}});return o}const es={id:Ye.id,binding:O.KeyCode.F4,preconditions:o=>P.whenFormulaEditorActivated(o)};function ts(){const o=[];for(const e of[O.KeyCode.ENTER,O.KeyCode.TAB,O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP])o.push({id:ve.id,binding:e,preconditions:t=>co(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,isSingleEditor:!0}});return o}var ns=Object.defineProperty,os=Object.getOwnPropertyDescriptor,ss=(o,e,t,n)=>{for(var s=n>1?void 0:n?os(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&ns(e,t,s),s},be=(o,e)=>(t,n)=>e(t,n,o);let ot=class extends c.Disposable{constructor(o,e,t,n,s,r,i){super(),this._injector=o,this._menuManagerService=e,this._commandService=t,this._shortcutService=n,this._uiPartsService=s,this._renderManagerService=r,this._componentManager=i,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(Zo)}_registerCommands(){[We,Ve,ze,Ge,Be,ve,Ye].forEach(o=>this.disposeWithMe(this._commandService.registerCommand(o)))}_registerShortcuts(){[...Qo(),...Jo(),...qo(),...$o(),...ts(),es].forEach(o=>{this.disposeWithMe(this._shortcutService.registerShortcut(o))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(O.BuiltInUIPart.CONTENT,()=>c.connectInjector(Uo,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent(P.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(Lo,this._injector))),this._componentManager.register(bt,Vo)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[et]))}};ot=ss([be(0,c.Inject(c.Injector)),be(1,O.IMenuManagerService),be(2,c.ICommandService),be(3,O.IShortcutService),be(4,O.IUIPartsService),be(5,G.IRenderManagerService),be(6,c.Inject(O.ComponentManager))],ot);var rs=Object.defineProperty,is=Object.getOwnPropertyDescriptor,cs=(o,e,t,n)=>{for(var s=n>1?void 0:n?is(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&rs(e,t,s),s},oe=(o,e)=>(t,n)=>e(t,n,o);const as=[c.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let st=class extends c.Disposable{constructor(e,t,n,s,r,i,a,l,f,h,d,u,p,v,C){super();V(this,"_listenInputCache",new Set);V(this,"_formulaRefColors",[]);V(this,"_previousSequenceNodes");V(this,"_previousRangesCount",0);V(this,"_previousInsertRefStringIndex");V(this,"_currentInsertRefStringIndex",-1);V(this,"_arrowMoveActionState",0);V(this,"_isSelectionMovingRefSelections",[]);V(this,"_stringColor","");V(this,"_numberColor","");V(this,"_insertSelections",[]);V(this,"_inputPanelState",0);V(this,"_userCursorMove",!1);V(this,"_previousEditorUnitId");V(this,"_existsSequenceNode",!1);V(this,"_currentlyWorkingRefRenderer",null);V(this,"_selectionsChangeDisposables");V(this,"_isSelectingMode",!1);this._commandService=e,this._contextService=t,this._editorBridgeService=n,this._formulaPromptService=s,this._lexerTreeBuilder=r,this._renderManagerService=i,this._themeService=a,this._sheetsSelectionsService=l,this._refSelectionsService=f,this._univerInstanceService=h,this._descriptionService=d,this._docSelectionManagerService=u,this._contextMenuService=p,this._editorService=v,this._layoutService=C,this._initialize()}get _selectionRenderService(){return this._renderManagerService.getRenderById(this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(j.RefSelectionsRenderService)}get _allSelectionRenderServices(){return this._renderManagerService.getAllRenderersOfType(c.UniverInstanceType.UNIVER_SHEET).map(e=>e.with(j.RefSelectionsRenderService))}dispose(){this._formulaRefColors=[],this._resetTemp()}_resetTemp(){this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._isSelectionMovingRefSelections=[],this._previousRangesCount=0,this._currentInsertRefStringIndex=-1}_initialize(){this._initialCursorSync(),this._initAcceptFormula(),this._initialFormulaTheme(),this._initSelectionsEndListener(),this._closeRangePromptWhenEditorInvisible(),this._initialEditorInputChange(),this._commandExecutedListener(),this._cursorStateListener(),this._inputFormulaListener(),this._userMouseListener(),this._initialChangeEditor()}_initialFormulaTheme(){const e=this._themeService.getCurrentTheme();this._formulaRefColors=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],this._numberColor=e.hyacinth700,this._stringColor=e.verdancy800}_initialCursorSync(){this.disposeWithMe(this._docSelectionManagerService.textSelection$.pipe(K.filter(e=>!P.isRangeSelector(e.unitId)&&!P.isEmbeddingFormulaEditor(e.unitId))).subscribe(e=>{var s;if((e==null?void 0:e.unitId)==null)return;const t=this._editorService.getEditor(e.unitId);if(!t||t.onlyInputContent()||t.isSheetEditor()&&!this._isFormulaEditorActivated()||t.params.scrollBar)return;const n=t.onlyInputRange();(s=e==null?void 0:e.options)!=null&&s.fromSelection||(this._quitSelectingMode(),this._contextSwitch(),this._checkShouldEnterSelectingMode(n),!this._formulaPromptService.isLockedSelectionChange()&&(this._highlightFormula(),!n&&this._changeFunctionPanelState()))}))}_initialEditorInputChange(){const e=[O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP,O.KeyCode.ARROW_LEFT,O.KeyCode.ARROW_RIGHT,O.KeyCode.CTRL,O.KeyCode.SHIFT];this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(K.filter(t=>{const n=(t==null?void 0:t.getUnitId())||"";return!P.isRangeSelector(n)&&!P.isEmbeddingFormulaEditor(n)})).subscribe(t=>{var i;const n=t==null?void 0:t.getUnitId();if(n==null||this._listenInputCache.has(n)||this._editorService.getEditor(n)==null)return;const r=(i=this._renderManagerService.getRenderById(n))==null?void 0:i.with(J.DocSelectionRenderService);r&&this.disposeWithMe(r.onInputBefore$.subscribe(a=>{this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._selectionRenderService.setSkipLastEnabled(!0);const l=a==null?void 0:a.event;l&&(e.includes(l.which)?this._inputPanelState=2:(this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._inputPanelState=1),l.which!==O.KeyCode.F4&&(this._userCursorMove=!1))})),this._listenInputCache.add(n)})}_closeRangePromptWhenEditorInvisible(){this.disposeWithMe(this._editorBridgeService.afterVisible$.pipe(K.distinctUntilKeyChanged("visible")).subscribe(e=>{e.visible||this._closeRangePrompt()})),this.disposeWithMe(this._contextService.subscribeContextValue$(c.FORMULA_EDITOR_ACTIVATED).pipe(K.distinctUntilChanged()).subscribe(e=>{e||this._closeRangePrompt()}))}_initialChangeEditor(){this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(K.filter(e=>{const t=(e==null?void 0:e.getUnitId())||"";return!P.isRangeSelector(t)&&!P.isEmbeddingFormulaEditor(t)})).subscribe(e=>{if(e==null)return;const t=e.getUnitId();!this._editorService.isEditor(t)||this._previousEditorUnitId===t||this._editorService.isSheetEditor(t)||(this._closeRangePrompt(t),this._previousEditorUnitId=t)})),this.disposeWithMe(this._editorService.closeRangePrompt$.subscribe(()=>{(!this._editorService.getSpreadsheetFocusState()||!this._formulaPromptService.isLockedSelectionInsert())&&this._closeRangePrompt()}))}_closeRangePrompt(e){var n;const t=e||((n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:n.getUnitId())||"";P.isRangeSelector(t)||P.isEmbeddingFormulaEditor(t)||t===c.DOCS_ZEN_EDITOR_UNIT_ID_KEY||(this._insertSelections=[],this._refSelectionsService.clear(),e&&this._editorService.isSheetEditor(e)&&this._updateEditorModel(`\r
33
- `,[]),this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue(U.DISABLE_NORMAL_SELECTIONS,!1),this._contextService.setContextValue(O.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._quitSelectingMode(),this._resetTemp(),this._hideFunctionPanel())}_initSelectionsEndListener(){const e=new c.DisposableCollection;this.disposeWithMe(this._refSelectionsService.selectionMoveEnd$.subscribe(t=>{var r;if(e.dispose(),t.length===0)return;const n=((r=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:r.getUnitId())||"";if(P.isRangeSelector(n)||P.isEmbeddingFormulaEditor(n))return;this._allSelectionRenderServices.map(i=>i.getSelectionControls()).flat().forEach(i=>{i.disableHelperSelection(),e.add(K.merge(i.selectionMoving$,i.selectionScaling$).subscribe(a=>{var f;const l=((f=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:f.getUnitId())||"";if(P.isRangeSelector(l)||P.isEmbeddingFormulaEditor(l)){e.dispose(),this._formulaPromptService.disableLockedSelectionChange();return}this._onSelectionControlChange(a,i)})),e.add(K.merge(i.selectionMoved$,i.selectionScaled$).subscribe(()=>{this._formulaPromptService.disableLockedSelectionChange()}))})}))}_updateSelecting(e,t=!1){if(e.length!==0&&!(this._editorService.selectionChangingState()&&!this._formulaPromptService.isLockedSelectionInsert())&&(this._insertControlSelections(e),t)){const n=e[e.length-1];this._insertControlSelectionReplace(n)}}_enableRefSelectionsRenderService(){const e=this._selectionsChangeDisposables=new c.DisposableCollection;this._allSelectionRenderServices.forEach(t=>{e.add(t.enableSelectionChanging()),e.add(t.selectionMoving$.subscribe(n=>{this._updateSelecting(n.map(s=>U.convertSelectionDataToRange(s)))})),e.add(t.selectionMoveStart$.subscribe(n=>{const s=this._checkClearingLastSelection(t);this._currentlyWorkingRefRenderer=t,this._updateSelecting(n.map(r=>U.convertSelectionDataToRange(r)),s)}))})}_checkClearingLastSelection(e){return this._currentlyWorkingRefRenderer&&this._currentlyWorkingRefRenderer!==e?(this._currentlyWorkingRefRenderer.clearLastSelection(),!1):!0}_disposeSelectionsChangeListeners(){var e;(e=this._selectionsChangeDisposables)==null||e.dispose(),this._selectionsChangeDisposables=null}_insertControlSelections(e){const t=e[e.length-1];if(this._resetSequenceNodes(e.length),(e.length===this._previousRangesCount||this._previousRangesCount===0)&&this._previousSequenceNodes!=null)this._insertControlSelectionReplace(t);else{let n=this._formulaPromptService.getSequenceNodes();const s=this._getCurrentChar();n.length===0&&this._currentInsertRefStringIndex>0&&(this._currentInsertRefStringIndex=-1),this._previousInsertRefStringIndex=this._currentInsertRefStringIndex,!I.matchRefDrawToken(s)&&this._focusIsOnlyRange(e.length)&&(this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex,I.matchToken.COMMA),n=this._formulaPromptService.getSequenceNodes(),this._previousInsertRefStringIndex+=1),this._previousSequenceNodes=c.Tools.deepClone(n),this._formulaPromptService.setSequenceNodes(n);const r=this._generateRefString(t);this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,r),this._selectionRenderService.setSkipLastEnabled(!1)}this._arrowMoveActionState=2,this._previousRangesCount=e.length}_initAcceptFormula(){this.disposeWithMe(this._formulaPromptService.acceptFormulaName$.subscribe(e=>{const t=this._docSelectionManagerService.getActiveTextRange();if(t==null){this._hideFunctionPanel();return}const{startOffset:n}=t,s=this._formulaPromptService.getSequenceNodes(),r=this._formulaPromptService.getCurrentSequenceNodeIndex(n-2),i=s[r];if(i==null||typeof i=="string"){this._hideFunctionPanel();return}const a=e.length-i.token.length,l={...i};l.token=e,l.endIndex+=a,s[r]=l;const f=this._descriptionService.hasDefinedNameDescription(e),h=this._descriptionService.isFormulaDefinedName(e),d=e.length+1,u=!f||h;u&&s.splice(r+1,0,I.matchToken.OPEN_BRACKET);for(let v=r+2,C=s.length;v<C;v++){const g=s[v];if(typeof g=="string")continue;const E={...g};E.startIndex+=d,E.endIndex+=d,s[v]=E}let p=l.endIndex+1;u&&(p+=1),this._syncToEditor(s,p,void 0,!0,!1)}))}_changeFunctionPanelState(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null){this._hideFunctionPanel();return}const{startOffset:t}=e,n=this._formulaPromptService.getCurrentSequenceNode(t-2);if(n==null){this._hideFunctionPanel();return}if(typeof n!="string"&&n.nodeType===I.sequenceNodeType.FUNCTION&&!this._descriptionService.hasDefinedNameDescription(n.token.trim())){const l=n.token.toUpperCase();if(this._inputPanelState===1){const f=this._descriptionService.getSearchListByNameFirstLetter(l);if(this._hideFunctionPanel(),f==null||f.length===0)return;this._commandService.executeCommand(Ge.id,{visible:!0,searchText:l,searchList:f})}else this._changeHelpFunctionPanelState(l,-1);return}const s=this._getCurrentBodyDataStreamAndOffset(),r=this._lexerTreeBuilder.getFunctionAndParameter((s==null?void 0:s.dataStream)||"",t-1+((s==null?void 0:s.offset)||0));if(!r){this._hideFunctionPanel();return}const{functionName:i,paramIndex:a}=r;this._changeHelpFunctionPanelState(i.toUpperCase(),a)}_changeHelpFunctionPanelState(e,t){const n=this._descriptionService.getFunctionInfo(e);this._hideFunctionPanel(),n!=null&&this._commandService.executeCommand(Be.id,{visible:!0,paramIndex:t,functionInfo:n})}_hideFunctionPanel(){this._commandService.executeCommand(Ge.id,{visible:!1,searchText:""}),this._commandService.executeCommand(Be.id,{visible:!1,paramIndex:-1})}_checkShouldEnterSelectingMode(e=!1){if(e){this._enterSelectingMode();return}const t=this._getCurrentChar(),n=this._getCurrentDataStream();(n==null?void 0:n.substring(0,1))==="="&&t&&I.matchRefDrawToken(t)?this._enterSelectingMode():this._quitSelectingMode()}_getCurrentChar(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=this._getCurrentBodyDataStreamAndOffset();return n==null||t==null?void 0:n.dataStream[t-1+n.offset]}_getCurrentDataStream(){const e=this._getCurrentBodyDataStreamAndOffset();return e==null?void 0:e.dataStream}_enterSelectingMode(){this._isSelectingMode||(this._editorBridgeService.enableForceKeepVisible(),this._contextMenuService.disable(),this._formulaPromptService.enableLockedSelectionInsert(),this._selectionRenderService.setRemainLastEnabled(!0),this._enableRefSelectionsRenderService(),this._currentlyWorkingRefRenderer=null,this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._isSelectingMode=!0)}_quitSelectingMode(){this._isSelectingMode&&(this._editorBridgeService.disableForceKeepVisible(),this._contextMenuService.enable(),this._formulaPromptService.disableLockedSelectionInsert(),this._currentInsertRefStringIndex=-1,this._disposeSelectionsChangeListeners(),this._arrowMoveActionState===2&&(this._arrowMoveActionState=4),this._isSelectingMode=!1)}_getCurrentBodyDataStreamAndOffset(){var r,i;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!(e!=null&&e.getBody()))return;const t=e.getUnitId(),n=this._editorService.getEditor(t),s=(i=(r=e.getBody())==null?void 0:r.dataStream)!=null?i:"";return!n||!n.onlyInputRange()?{dataStream:s,offset:0}:{dataStream:I.compareToken.EQUALS+s,offset:1}}_getFormulaAndCellEditorBody(e){return e.map(t=>{const n=this._univerInstanceService.getUniverDocInstance(t);return n==null?void 0:n.getBody()})}_editorModelUnitIds(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();return this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t)?[t]:as}_contextSwitch(){const e=this._getCurrentBodyDataStreamAndOffset();if(e&&c.isFormulaString(e.dataStream)){this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!0),this._contextService.setContextValue(U.DISABLE_NORMAL_SELECTIONS,!0),this._contextService.setContextValue(O.UNI_DISABLE_CHANGING_FOCUS_KEY,!0);const t=this._lexerTreeBuilder.sequenceNodesBuilder(e.dataStream)||[];this._formulaPromptService.setSequenceNodes(t);const n=this._docSelectionManagerService.getActiveTextRange();if(n==null)return;const{startOffset:s}=n;this._currentInsertRefStringIndex=s-1+e.offset;return}this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue(U.DISABLE_NORMAL_SELECTIONS,!1),this._contextService.setContextValue(O.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._formulaPromptService.disableLockedSelectionChange(),this._formulaPromptService.disableLockedSelectionInsert(),this._formulaPromptService.clearSequenceNodes(),this._hideFunctionPanel()}_getContextState(){return this._contextService.getContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA)}_highlightFormula(){if(this._getContextState()===!1)return;const e=this._formulaPromptService.getSequenceNodes(),t=this._editorModelUnitIds(),n=this._getFormulaAndCellEditorBody(t).filter(s=>!!s);if(this._refSelectionsService.clear(),e==null||e.length===0)this._existsSequenceNode=!1,n.forEach(s=>s.textRuns=[]);else{this._existsSequenceNode=!0;const{textRuns:s,refSelections:r}=this._buildTextRuns(e);n.forEach(i=>i.textRuns=s),this._allSelectionRenderServices.forEach(i=>this._refreshSelectionForReference(i,r))}this._refreshFormulaAndCellEditor(t)}_buildTextRuns(e){var a;const t=[],n=[],s=new Map;let r=0;const i=((a=this._getCurrentBodyDataStreamAndOffset())==null?void 0:a.offset)||0;for(let l=0,f=e.length;l<f;l++){const h=e[l];if(typeof h=="string"||this._descriptionService.hasDefinedNameDescription(h.token.trim()))continue;const{startIndex:d,endIndex:u,nodeType:p,token:v}=h;let C="";if(p===I.sequenceNodeType.REFERENCE){if(s.has(v))C=s.get(v);else{const g=r%this._formulaRefColors.length;C=this._formulaRefColors[g],s.set(v,C),r++}n.push({refIndex:l,themeColor:C,token:v})}else p===I.sequenceNodeType.NUMBER?C=this._numberColor:p===I.sequenceNodeType.STRING?C=this._stringColor:p===I.sequenceNodeType.ARRAY&&(C=this._stringColor);C&&C.length>0&&t.push({st:d+1-i,ed:u+2-i,ts:{cl:{rgb:C}}})}return{textRuns:t,refSelections:n}}_exceedCurrentRange(e,t,n){const{startRow:s,startColumn:r}=e;return s>t-1||r>n-1}_refreshSelectionForReference(e,t){const{unitId:n,sheetId:s}=this._editorBridgeService.getEditCellState(),{unitId:r,sheetId:i}=this._getCurrentUnitIdAndSheetId(),a=s===i,f=this._univerInstanceService.getUniverSheetInstance(n).getSheetBySheetId(s);let h=null;const d=[];for(let u=0,p=t.length;u<p;u++){const v=t[u],{themeColor:C,token:g,refIndex:E}=v,m=I.deserializeRangeWithSheet(g),{unitId:R,sheetName:y,range:M}=m,b=U.setEndForRange(M,f.getRowCount(),f.getColumnCount());if(R!=null&&R.length>0&&n!==R)continue;const T=this._getSheetIdByName(n,y.trim());if(!a&&T!==i||a&&y.length!==0&&T!==s||this._exceedCurrentRange(b,f.getRowCount(),f.getColumnCount()))continue;const A=this._getPrimary(b,C,E);if(A){h=A,d.push(h);continue}const N=U.getPrimaryForRange(b,f);!c.Rectangle.equals(N,b)&&b.startRow===b.endRow&&b.startColumn===b.endColumn&&(b.startRow=N.startRow,b.endRow=N.endRow,b.startColumn=N.startColumn,b.endColumn=N.endColumn),d.push({range:b,primary:N,style:Qe(this._themeService,C,E.toString())})}d.length&&this._refSelectionsService.addSelections(n,s,d)}_getPrimary(e,t,n){const s=this._insertSelections.find(d=>{const{startRow:u,startColumn:p,endRow:v,endColumn:C}=d.range;return u===e.startRow&&p===e.startColumn&&v===e.endRow&&C===e.endColumn||u===e.startRow&&p===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn});if((s==null?void 0:s.primary)==null)return;const{isMerged:r,isMergedMainCell:i,startRow:a,endRow:l,startColumn:f,endColumn:h}=s.primary;return(r||i)&&a===e.startRow&&f===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn&&(e.endRow=l,e.endColumn=h),{range:e,primary:s.primary,style:Qe(this._themeService,t,n.toString())}}_getSheetIdByName(e,t){var s;const n=this._univerInstanceService.getUniverSheetInstance(e);return(s=n==null?void 0:n.getSheetBySheetName(I.normalizeSheetName(t)))==null?void 0:s.getSheetId()}_getSheetNameById(e,t){var r;const n=this._univerInstanceService.getUniverSheetInstance(e);return((r=n==null?void 0:n.getSheetBySheetId(t))==null?void 0:r.getName())||""}_getCurrentUnitIdAndSheetId(){var s,r;const e=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),t=e.getActiveSheet(),n=(r=(s=this._renderManagerService.getRenderById(e.getUnitId()))==null?void 0:s.with(P.SheetSkeletonManagerService))==null?void 0:r.getCurrentSkeleton();return{unitId:e.getUnitId(),sheetId:(t==null?void 0:t.getSheetId())||"",skeleton:n}}_getEditorOpenedForSheet(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),n=this._editorService.getEditor(t);return n?{openUnitId:n.getOpenForSheetUnitId(),openSheetId:n.getOpenForSheetSubUnitId()}:{openUnitId:null,openSheetId:null}}_generateRefString(e){let t="",n="";const{unitId:s,sheetId:r}=e.range,{openUnitId:i,openSheetId:a}=this._getEditorOpenedForSheet();s!==i&&s&&(t=s),r!==a&&s&&r&&(n=this._getSheetNameById(s,r));const{range:l,primary:f}=e;let{startRow:h,endRow:d,startColumn:u,endColumn:p}=l;const{startAbsoluteRefType:v,endAbsoluteRefType:C,rangeType:g}=l;if(f){const{isMerged:E,isMergedMainCell:m,startRow:R,endRow:y,startColumn:M,endColumn:b}=f;(E||m)&&R===h&&M===u&&y===d&&b===p&&(h=R,u=M,d=R,p=M)}return I.serializeRangeToRefString({sheetName:n,unitId:t,range:{startRow:h,endRow:d,startColumn:u,endColumn:p,rangeType:g,startAbsoluteRefType:v,endAbsoluteRefType:C}})}_syncToEditor(e,t,n,s=!0,r=!0){let i=I.generateStringWithSequence(e);const{textRuns:a,refSelections:l}=this._buildTextRuns(e);this._isSelectionMovingRefSelections=l,this._allSelectionRenderServices.forEach(C=>this._updateRefSelectionStyle(C,this._isSelectionMovingRefSelections));const f=this._docSelectionManagerService.getActiveTextRange();if(f==null)return;this._currentInsertRefStringIndex=t,n==null&&(n=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId()),this._fitEditorSize();const h=this._editorService.getEditor(n);h!=null&&h.isSingleChoice()?(i=i.split(",")[0],this._selectionRenderService.setSingleSelectionEnabled(!0)):this._selectionRenderService.setSingleSelectionEnabled(!1);let d=i,u=1;(!h||!h.onlyInputRange())&&(d=`${I.compareToken.EQUALS}${i}`,u=0);const{collapsed:p,style:v}=f;s?(this._commandService.executeCommand(J.ReplaceContentCommand.id,{unitId:n,body:{dataStream:d,textRuns:a},textRanges:[{startOffset:t+1-u,endOffset:t+1-u,collapsed:p,style:v}],segmentId:null,options:{fromSelection:r}}),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:v}],!0,{fromSelection:r})):(this._updateEditorModel(`${d}\r
34
- `,a),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:v}],!0,{fromSelection:r})),this._layoutService.focus()}_fitEditorSize(){var n;const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();if(!(this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t))&&(this._editorBridgeService.changeEditorDirty(!0),!!this._editorBridgeService.isVisible().visible&&t===c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY)){const s=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),r=(n=s==null?void 0:s.getUnitId())!=null?n:"",i=this._renderManagerService.getRenderById(r);if(!i)return;i.with(P.SheetCellEditorResizeService).fitTextSize()}}_updateEditorModel(e,t){var l;const n=this._univerInstanceService.getCurrentUniverDocInstance(),s=n.getUnitId();if(!this._editorService.isEditor(s))return;const r=(l=this._renderManagerService.getRenderById(s))==null?void 0:l.with(He.DocSkeletonManagerService).getViewModel();if(r==null||n==null)return;const i=n==null?void 0:n.getSnapshot();if(i==null)return;const a={dataStream:e,textRuns:t};i.body=a,r.reset(n)}_insertControlSelectionReplace(e){this._previousSequenceNodes==null&&(this._previousSequenceNodes=this._formulaPromptService.getSequenceNodes()),this._previousInsertRefStringIndex==null&&(this._previousInsertRefStringIndex=this._currentInsertRefStringIndex);const t=c.Tools.deepClone(this._previousSequenceNodes);if(t==null)return;const n=this._generateRefString(e);this._formulaPromptService.setSequenceNodes(t),this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,n),this._syncToEditor(t,this._previousInsertRefStringIndex+n.length);const s=this._selectionRenderService.getSelectionDataWithStyle()||[];this._insertSelections=[];const r=s[s.length-1];if(r){const i=U.convertSelectionDataToRange(r);this._insertSelections.push(i)}}_focusIsOnlyRange(e){const t=this._editorService.getFocusEditor();return!t||!t.onlyInputRange()||this._existsSequenceNode||e>1||this._previousSequenceNodes!=null&&this._previousSequenceNodes.length>0?!0:(this._previousInsertRefStringIndex!=null&&(this._previousInsertRefStringIndex+=1),!1)}_resetSequenceNodes(e){const t=this._editorService.getFocusEditor();t&&t.onlyInputRange()&&(e>1||this._existsSequenceNode&&(this._formulaPromptService.clearSequenceNodes(),this._previousRangesCount=0,this._existsSequenceNode=!1))}_updateRefSelectionStyle(e,t){const n=e.getSelectionControls(),[s,r]=e.getLocation(),i=new Set;for(let a=0,l=t.length;a<l;a++){const f=t[a],{refIndex:h,themeColor:d,token:u}=f,p=I.deserializeRangeWithSheet(u),{unitId:v,sheetName:C,range:g}=p;if(!v&&v.length>0&&s!==v)continue;const E=this._getSheetIdByName(s,C.trim());if(E&&E!==r)continue;const m=n.find(R=>{const{startRow:y,startColumn:M,endRow:b,endColumn:T,rangeType:A}=R.getRange();return A===c.RANGE_TYPE.COLUMN&&M===g.startColumn&&T===g.endColumn||A===c.RANGE_TYPE.ROW&&y===g.startRow&&b===g.endRow||y===g.startRow&&M===g.startColumn&&b===g.endRow&&T===g.endColumn||y===g.startRow&&M===g.startColumn&&g.startRow===g.endRow&&g.startColumn===g.endColumn});if(m){const R=Qe(this._themeService,d,h.toString());m.updateStyle(R),i.add(m)}}}_onSelectionControlChange(e,t){var m;const{skeleton:n}=this._getCurrentUnitIdAndSheetId();if(!n)return;this._formulaPromptService.enableLockedSelectionChange();const s=(m=t.currentStyle)==null?void 0:m.id;if(!s||!c.Tools.isStringNumber(s))return;let{startRow:r,endRow:i,startColumn:a,endColumn:l}=e;const f=n?n.worksheet.getCellInfoInMergeData(r,a):{actualRow:r,actualColumn:a,isMergedMainCell:!1,isMerged:!1,endRow:r,endColumn:a,startRow:r,startColumn:a};if(f){const{isMerged:R,isMergedMainCell:y,startRow:M,endRow:b,startColumn:T,endColumn:A}=f;(R||y)&&M===r&&T===a&&b===i&&A===l&&(r=M,a=T,i=M,l=T)}const h=Number(s),d=this._formulaPromptService.getCurrentSequenceNodeByIndex(h);if(!d)return;let u={startAbsoluteRefType:c.AbsoluteRefType.NONE};if(typeof d!="string"){const R=d.token;u=I.getAbsoluteRefTypeWitString(R),u.endAbsoluteRefType==null&&(u.endAbsoluteRefType=u.startAbsoluteRefType)}const p=n==null?void 0:n.worksheet.getUnitId(),v=n==null?void 0:n.worksheet.getSheetId(),C=this._generateRefString({range:{startRow:Math.min(r,i),endRow:Math.max(r,i),startColumn:Math.min(a,l),endColumn:Math.max(a,l),...u,sheetId:v,unitId:p},primary:f,style:null});this._formulaPromptService.updateSequenceRef(h,C);const g=this._formulaPromptService.getSequenceNodes(),E=g[h];typeof E!="string"&&(this._syncToEditor(g,E.endIndex+1),t.updateRange(e,this._selectionRenderService.attachPrimaryWithCoord(f)))}_refreshFormulaAndCellEditor(e){var t;for(const n of e){const s=P.getEditorObject(n,this._renderManagerService),r=s==null?void 0:s.document;r!=null&&((t=r.getSkeleton())==null||t.calculate(),r.makeDirty())}}_cursorStateListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t.onPointerDown$.subscribeEvent(()=>{this._arrowMoveActionState=1,this._inputPanelState=3}))}_pressEnter(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressTab(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressEsc(e){const{keycode:t}=e,n=this._editorService.getFocusEditor();(!n||(n==null?void 0:n.isSheetEditor())===!0)&&this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressArrowKey(e){const{keycode:t,metaKey:n}=e;let s=c.Direction.DOWN;t===O.KeyCode.ARROW_DOWN?s=c.Direction.DOWN:t===O.KeyCode.ARROW_UP?s=c.Direction.UP:t===O.KeyCode.ARROW_LEFT?s=c.Direction.LEFT:t===O.KeyCode.ARROW_RIGHT&&(s=c.Direction.RIGHT),n===O.MetaKeys.CTRL_COMMAND?this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:s,jumpOver:P.JumpOver.moveGap}):n===O.MetaKeys.SHIFT?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:s}):n===ln?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:s,jumpOver:P.JumpOver.moveGap}):this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:s})}_commandExecutedListener(){const e=[ve.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC),s=(n==null?void 0:n.getUnitId())||"";if(!(P.isRangeSelector(s)||P.isEmbeddingFormulaEditor(s))){if(t.id===Ye.id)this._changeRefString();else if(e.includes(t.id)){const r=t.params,{keycode:i,isSingleEditor:a=!1}=r;if(i===O.KeyCode.ENTER){this._pressEnter(r);return}if(i===O.KeyCode.TAB){this._pressTab(r);return}if(i===O.KeyCode.ESC){this._pressEsc(r);return}if(this._formulaPromptService.isSearching()){if(i===O.KeyCode.ARROW_DOWN){this._formulaPromptService.navigate({direction:c.Direction.DOWN});return}if(i===O.KeyCode.ARROW_UP){this._formulaPromptService.navigate({direction:c.Direction.UP});return}}if(a===!0)return;if(this._arrowMoveActionState===1){this._moveInEditor(i);return}if(this._arrowMoveActionState===4){this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:i,unitId:""});return}if(this._arrowMoveActionState===2&&(this._arrowMoveActionState=3),this._refSelectionsService.getCurrentSelections().length===0){const d=this._sheetsSelectionsService.getCurrentLastSelection();if(d!=null){const u=c.Tools.deepClone(d);this._refSelectionsService.addSelections([u])}}this._pressArrowKey(r);const f=this._refSelectionsService.getCurrentSelections(),h=f[f.length-1];this._insertControlSelectionReplace(h),this._highlightFormula()}}}))}_moveInEditor(e){if(e==null)return;let t=c.Direction.LEFT;e===O.KeyCode.ARROW_DOWN?t=c.Direction.DOWN:e===O.KeyCode.ARROW_UP?t=c.Direction.UP:e===O.KeyCode.ARROW_RIGHT&&(t=c.Direction.RIGHT),this._commandService.executeCommand(J.MoveCursorOperation.id,{direction:t})}_userMouseListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t==null?void 0:t.onPointerDown$.subscribeEvent(()=>{this._userCursorMove=!0}))}_inputFormulaListener(){this.disposeWithMe(this._editorService.inputFormula$.subscribe(e=>{const{formulaString:t,editorUnitId:n}=e;if(t.substring(0,1)!==I.compareToken.EQUALS)return;const{unitId:s}=this._getCurrentUnitIdAndSheetId();this._editorBridgeService.isVisible().visible===!1&&this._editorBridgeService.changeVisible({visible:!0,eventType:G.DeviceInputEventType.Dblclick,unitId:s});const i=this._lexerTreeBuilder.sequenceNodesBuilder(t)||[];this._formulaPromptService.setSequenceNodes(i),this._syncToEditor(i,t.length-1,n,!0,!1)}))}_changeRefString(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=t-2,s=this._formulaPromptService.getCurrentSequenceNodeIndex(n),r=this._formulaPromptService.getCurrentSequenceNodeByIndex(s);if(r==null||typeof r=="string"||r.nodeType!==I.sequenceNodeType.REFERENCE)return;const i=r.token.split("!");let a=r.token;i.length>1&&(a=i[i.length-1]);let l="";for(let d=0,u=i.length;d<u-1;d++)l+=i[d];let f=a;if(a.indexOf(I.matchToken.COLON)>-1)if(!this._userCursorMove)f=this._changeRangeRef(a);else{const d=a.split(I.matchToken.COLON),u=d[0],p=d[1];n-r.startIndex<=u.length?f=this._changeSingleRef(u)+I.matchToken.COLON+p:f=u+I.matchToken.COLON+this._changeSingleRef(p)}else f=this._changeSingleRef(a);f=l+f;const h=f.length-r.token.length;this._formulaPromptService.updateSequenceRef(s,f),this._syncToEditor(this._formulaPromptService.getSequenceNodes(),n+h+1)}_changeRangeRef(e){const t=I.deserializeRangeWithSheet(e).range;let n="";return t.startAbsoluteRefType===c.AbsoluteRefType.NONE||t.startAbsoluteRefType==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),n=I.serializeRange(t),n}_changeSingleRef(e){const t=I.deserializeRangeWithSheet(e).range,n=t.startAbsoluteRefType;let s="";return n===c.AbsoluteRefType.NONE||n==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):n===c.AbsoluteRefType.ALL?(t.startAbsoluteRefType=c.AbsoluteRefType.ROW,t.endAbsoluteRefType=c.AbsoluteRefType.ROW):n===c.AbsoluteRefType.ROW?(t.startAbsoluteRefType=c.AbsoluteRefType.COLUMN,t.endAbsoluteRefType=c.AbsoluteRefType.COLUMN):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),s=I.serializeRange(t),s}_getEditorObject(){const e=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),t=this._editorService.getEditor(e);return t==null?void 0:t.render}_isFormulaEditorActivated(){return this._editorBridgeService.isVisible().visible===!0||this._contextService.getContextValue(c.FORMULA_EDITOR_ACTIVATED)}_isSheetOrFormulaEditor(e){return e.isSheetEditor()||e.isFormulaEditor()}};st=cs([oe(0,c.ICommandService),oe(1,c.IContextService),oe(2,c.Inject(P.IEditorBridgeService)),oe(3,c.Inject(Ne)),oe(4,c.Inject(I.LexerTreeBuilder)),oe(5,G.IRenderManagerService),oe(6,c.Inject(c.ThemeService)),oe(7,c.Inject(U.SheetsSelectionsService)),oe(8,U.IRefSelectionsService),oe(9,c.IUniverInstanceService),oe(10,c.Inject(me.IDescriptionService)),oe(11,c.Inject(He.DocSelectionManagerService)),oe(12,O.IContextMenuService),oe(13,J.IEditorService),oe(14,O.ILayoutService)],st);var un=Object.defineProperty,ls=Object.getOwnPropertyDescriptor,us=(o,e,t)=>e in o?un(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,fs=(o,e,t,n)=>{for(var s=n>1?void 0:n?ls(e,t):e,r=o.length-1,i;r>=0;r--)(i=o[r])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&un(e,t,s),s},Rt=(o,e)=>(t,n)=>e(t,n,o),fn=(o,e,t)=>us(o,typeof e!="symbol"?e+"":e,t);j.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(e=io,t,n,s){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=s;const{menu:r,...i}=this._config;r&&this._configService.setConfig("menu",r,{merge:!0}),this._configService.setConfig(ro,i)}onStarting(){const e=this._injector;[[Ne,{useClass:rt}],[ot],[qe],[$e],[et],[tt],[st]].forEach(n=>e.add(n))}onRendered(){[[j.RefSelectionsRenderService],[_t]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[ot],[$e],[tt]]);const e=this._injector.get(O.ComponentManager);e.register(P.RANGE_SELECTOR_COMPONENT_KEY,Jt),e.register(P.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,tn)}onSteady(){this._injector.get(qe),this._injector.get(st)}},fn(j.UniverSheetsFormulaUIPlugin,"pluginName",Tt),fn(j.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET),j.UniverSheetsFormulaUIPlugin=fs([c.DependentOn(I.UniverFormulaEnginePlugin,me.UniverSheetsFormulaPlugin),Rt(1,c.Inject(c.Injector)),Rt(2,G.IRenderManagerService),Rt(3,c.IConfigService)],j.UniverSheetsFormulaUIPlugin),j.FORMULA_PROMPT_ACTIVATED=Et,j.FormulaEditor=tn,j.HelpFunctionOperation=Be,j.InsertFunctionOperation=Ve,j.MoreFunctionsOperation=ze,j.RangeSelector=Jt,j.ReferenceAbsoluteOperation=Ye,j.SearchFunctionOperation=Ge,j.SelectEditorFormulaOperation=ve,j.SheetOnlyPasteFormulaCommand=We,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})});
32
+ `:pe.formulaSelectFunctionResultItem,onMouseEnter:()=>F(x),onMouseLeave:k,onClick:()=>T(x),children:[d===x&&_.jsx(At,{className:pe.formulaSelectFunctionResultItemSelected}),_.jsx("span",{className:pe.formulaSelectFunctionResultItemName,children:b(D)})]},x))}),p&&_.jsxs("div",{className:pe.formulaSelectFunctionContent,children:[_.jsx(we,{title:p.functionName,value:p.description}),_.jsx(we,{title:g.t("formula.moreFunctions.syntax"),value:_.jsx(ln,{prefix:p.functionName,value:p.functionParameter})}),_.jsx(we,{title:g.t("formula.prompt.helpExample"),value:`${p.functionName}(${p.functionParameter.map(D=>D.example).join(",")})`}),p.functionParameter&&p.functionParameter.map((D,x)=>_.jsx(we,{title:D.name,value:`${D.require?y:M} ${D.detail}`},x))]})]})}function Vo(){const o=P.useActiveWorkbook(),[e,t]=S.useState(!0),[n,r]=S.useState(!1),[s,i]=S.useState(null),a=c.useDependency(c.LocaleService),l=c.useDependency(J.IEditorService);function f(){t(!e),r(!n)}function h(){l.setFormula(`=${s==null?void 0:s.functionName}(`)}return _.jsxs("div",{className:an.formulaMoreFunctions,children:[e&&_.jsx(Bo,{onChange:i}),n&&_.jsx(Wo,{functionInfo:s,onChange:()=>{}}),_.jsxs("div",{className:an.formulaMoreFunctionsOperation,children:[n&&_.jsx(ne.Button,{type:"primary",size:"small",onClick:f,children:a.t("formula.moreFunctions.next")}),n&&_.jsx(ne.Button,{size:"small",onClick:f,children:a.t("formula.moreFunctions.prev")}),e&&!!o&&_.jsx(ne.Button,{type:"primary",size:"small",onClick:h,children:a.t("formula.moreFunctions.confirm")})]})]})}function Ko(o){return{id:Ve.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:O.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$:O.getMenuHiddenObservable(o,c.UniverInstanceType.UNIVER_SHEET),disabled$:P.getCurrentRangeDisable$(o,{workbookTypes:[U.WorkbookEditablePermission],worksheetTypes:[U.WorksheetEditPermission,U.WorksheetSetCellValuePermission],rangeTypes:[U.RangeProtectionPermissionEditPoint]})}}function zo(o){return{id:ze.id,title:"formula.insert.more",type:O.MenuItemType.BUTTON}}function Yo(o){return o.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(B.switchMap(n=>n&&o.get(O.IClipboardInterfaceService)?new B.Observable(s=>s.next(!o.get(O.IClipboardInterfaceService).supportClipboard)):B.of(!0)))}function Go(o){return{id:We.id,type:O.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:Yo(o).pipe(B.combineLatestWith(P.getCurrentRangeDisable$(o,{workbookTypes:[U.WorkbookEditablePermission],rangeTypes:[U.RangeProtectionPermissionEditPoint],worksheetTypes:[U.WorksheetSetCellValuePermission,U.WorksheetEditPermission]})),B.map(([e,t])=>e||t))}}const Zo={[O.RibbonStartGroup.FORMULAS_INSERT]:{[Ve.id]:{order:1,menuItemFactory:Ko,[ze.id]:{order:1,menuItemFactory:zo}}},[P.PASTE_SPECIAL_MENU_ID]:{[We.id]:{order:4,menuItemFactory:Go}}},un="meta_key_ctrl_And_Shift",nt=[O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP,O.KeyCode.ARROW_LEFT,O.KeyCode.ARROW_RIGHT],Xo=[...nt,O.KeyCode.ENTER,O.KeyCode.TAB,O.KeyCode.ESC];function Qo(){const o=[];for(const e of Xo)o.push({id:ve.id,binding:e,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e}});return o}function Jo(){const o=[];for(const e of nt)o.push({id:ve.id,binding:e|O.MetaKeys.SHIFT,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,metaKey:O.MetaKeys.SHIFT}});return o}function qo(){const o=[];for(const e of nt)o.push({id:ve.id,binding:e|O.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,metaKey:O.MetaKeys.CTRL_COMMAND}});return o}function $o(){const o=[];for(const e of nt)o.push({id:ve.id,binding:e|O.MetaKeys.SHIFT|O.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,metaKey:un}});return o}const er={id:Ye.id,binding:O.KeyCode.F4,preconditions:o=>P.whenFormulaEditorActivated(o)};function tr(){const o=[];for(const e of[O.KeyCode.ENTER,O.KeyCode.TAB,O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP])o.push({id:ve.id,binding:e,preconditions:t=>co(t),staticParameters:{eventType:G.DeviceInputEventType.Keyboard,keycode:e,isSingleEditor:!0}});return o}var nr=Object.defineProperty,or=Object.getOwnPropertyDescriptor,rr=(o,e,t,n)=>{for(var r=n>1?void 0:n?or(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&nr(e,t,r),r},be=(o,e)=>(t,n)=>e(t,n,o);let ot=class extends c.Disposable{constructor(o,e,t,n,r,s,i){super(),this._injector=o,this._menuManagerService=e,this._commandService=t,this._shortcutService=n,this._uiPartsService=r,this._renderManagerService=s,this._componentManager=i,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(Zo)}_registerCommands(){[We,Ve,ze,Ge,Be,ve,Ye].forEach(o=>this.disposeWithMe(this._commandService.registerCommand(o)))}_registerShortcuts(){[...Qo(),...Jo(),...qo(),...$o(),...tr(),er].forEach(o=>{this.disposeWithMe(this._shortcutService.registerShortcut(o))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(O.BuiltInUIPart.CONTENT,()=>c.connectInjector(Uo,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent(P.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(Lo,this._injector))),this._componentManager.register(bt,Vo)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[et]))}};ot=rr([be(0,c.Inject(c.Injector)),be(1,O.IMenuManagerService),be(2,c.ICommandService),be(3,O.IShortcutService),be(4,O.IUIPartsService),be(5,G.IRenderManagerService),be(6,c.Inject(O.ComponentManager))],ot);var sr=Object.defineProperty,ir=Object.getOwnPropertyDescriptor,cr=(o,e,t,n)=>{for(var r=n>1?void 0:n?ir(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&sr(e,t,r),r},oe=(o,e)=>(t,n)=>e(t,n,o);const ar=[c.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let rt=class extends c.Disposable{constructor(e,t,n,r,s,i,a,l,f,h,d,u,p,v,C){super();K(this,"_listenInputCache",new Set);K(this,"_formulaRefColors",[]);K(this,"_previousSequenceNodes");K(this,"_previousRangesCount",0);K(this,"_previousInsertRefStringIndex");K(this,"_currentInsertRefStringIndex",-1);K(this,"_arrowMoveActionState",0);K(this,"_isSelectionMovingRefSelections",[]);K(this,"_stringColor","");K(this,"_numberColor","");K(this,"_insertSelections",[]);K(this,"_inputPanelState",0);K(this,"_userCursorMove",!1);K(this,"_previousEditorUnitId");K(this,"_existsSequenceNode",!1);K(this,"_currentlyWorkingRefRenderer",null);K(this,"_selectionsChangeDisposables");K(this,"_isSelectingMode",!1);this._commandService=e,this._contextService=t,this._editorBridgeService=n,this._formulaPromptService=r,this._lexerTreeBuilder=s,this._renderManagerService=i,this._themeService=a,this._sheetsSelectionsService=l,this._refSelectionsService=f,this._univerInstanceService=h,this._descriptionService=d,this._docSelectionManagerService=u,this._contextMenuService=p,this._editorService=v,this._layoutService=C,this._initialize()}get _selectionRenderService(){return this._renderManagerService.getRenderById(this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(j.RefSelectionsRenderService)}get _allSelectionRenderServices(){return this._renderManagerService.getAllRenderersOfType(c.UniverInstanceType.UNIVER_SHEET).map(e=>e.with(j.RefSelectionsRenderService))}dispose(){this._formulaRefColors=[],this._resetTemp()}_resetTemp(){this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._isSelectionMovingRefSelections=[],this._previousRangesCount=0,this._currentInsertRefStringIndex=-1}_initialize(){this._initialCursorSync(),this._initAcceptFormula(),this._initialFormulaTheme(),this._initSelectionsEndListener(),this._closeRangePromptWhenEditorInvisible(),this._initialEditorInputChange(),this._commandExecutedListener(),this._cursorStateListener(),this._inputFormulaListener(),this._userMouseListener(),this._initialChangeEditor()}_initialFormulaTheme(){const e=this._themeService.getCurrentTheme();this._formulaRefColors=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],this._numberColor=e.hyacinth700,this._stringColor=e.verdancy800}_initialCursorSync(){this.disposeWithMe(this._docSelectionManagerService.textSelection$.pipe(B.filter(e=>!P.isRangeSelector(e.unitId)&&!P.isEmbeddingFormulaEditor(e.unitId))).subscribe(e=>{var r;if((e==null?void 0:e.unitId)==null)return;const t=this._editorService.getEditor(e.unitId);if(!t||t.onlyInputContent()||t.isSheetEditor()&&!this._isFormulaEditorActivated()||t.params.scrollBar)return;const n=t.onlyInputRange();(r=e==null?void 0:e.options)!=null&&r.fromSelection||(this._quitSelectingMode(),this._contextSwitch(),this._checkShouldEnterSelectingMode(n),!this._formulaPromptService.isLockedSelectionChange()&&(this._highlightFormula(),!n&&this._changeFunctionPanelState()))}))}_initialEditorInputChange(){const e=[O.KeyCode.ARROW_DOWN,O.KeyCode.ARROW_UP,O.KeyCode.ARROW_LEFT,O.KeyCode.ARROW_RIGHT,O.KeyCode.CTRL,O.KeyCode.SHIFT];this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(B.filter(t=>{const n=(t==null?void 0:t.getUnitId())||"";return!P.isRangeSelector(n)&&!P.isEmbeddingFormulaEditor(n)})).subscribe(t=>{var i;const n=t==null?void 0:t.getUnitId();if(n==null||this._listenInputCache.has(n)||this._editorService.getEditor(n)==null)return;const s=(i=this._renderManagerService.getRenderById(n))==null?void 0:i.with(J.DocSelectionRenderService);s&&this.disposeWithMe(s.onInputBefore$.subscribe(a=>{this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._selectionRenderService.setSkipLastEnabled(!0);const l=a==null?void 0:a.event;l&&(e.includes(l.which)?this._inputPanelState=2:(this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._inputPanelState=1),l.which!==O.KeyCode.F4&&(this._userCursorMove=!1))})),this._listenInputCache.add(n)})}_closeRangePromptWhenEditorInvisible(){this.disposeWithMe(this._editorBridgeService.afterVisible$.pipe(B.distinctUntilKeyChanged("visible")).subscribe(e=>{e.visible||this._closeRangePrompt()})),this.disposeWithMe(this._contextService.subscribeContextValue$(c.FORMULA_EDITOR_ACTIVATED).pipe(B.distinctUntilChanged()).subscribe(e=>{e||this._closeRangePrompt()}))}_initialChangeEditor(){this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(B.filter(e=>{const t=(e==null?void 0:e.getUnitId())||"";return!P.isRangeSelector(t)&&!P.isEmbeddingFormulaEditor(t)})).subscribe(e=>{if(e==null)return;const t=e.getUnitId();!this._editorService.isEditor(t)||this._previousEditorUnitId===t||this._editorService.isSheetEditor(t)||(this._closeRangePrompt(t),this._previousEditorUnitId=t)})),this.disposeWithMe(this._editorService.closeRangePrompt$.subscribe(()=>{(!this._editorService.getSpreadsheetFocusState()||!this._formulaPromptService.isLockedSelectionInsert())&&this._closeRangePrompt()}))}_closeRangePrompt(e){var n;const t=e||((n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:n.getUnitId())||"";P.isRangeSelector(t)||P.isEmbeddingFormulaEditor(t)||t===c.DOCS_ZEN_EDITOR_UNIT_ID_KEY||(this._insertSelections=[],this._refSelectionsService.clear(),e&&this._editorService.isSheetEditor(e)&&this._updateEditorModel(`\r
33
+ `,[]),this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue(U.REF_SELECTIONS_ENABLED,!1),this._contextService.setContextValue(O.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._quitSelectingMode(),this._resetTemp(),this._hideFunctionPanel())}_initSelectionsEndListener(){const e=new c.DisposableCollection;this.disposeWithMe(B.merge(this._refSelectionsService.selectionSet$,this._refSelectionsService.selectionMoveEnd$).subscribe(t=>{var s;if(e.dispose(),!t||t.length===0)return;const n=((s=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:s.getUnitId())||"";if(P.isRangeSelector(n)||P.isEmbeddingFormulaEditor(n))return;this._allSelectionRenderServices.map(i=>i.getSelectionControls()).flat().forEach(i=>{i.disableHelperSelection(),e.add(B.merge(i.selectionMoving$,i.selectionScaling$).subscribe(a=>{var f;const l=((f=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:f.getUnitId())||"";if(P.isRangeSelector(l)||P.isEmbeddingFormulaEditor(l)){e.dispose(),this._formulaPromptService.disableLockedSelectionChange();return}this._onSelectionControlChange(a,i)})),e.add(B.merge(i.selectionMoveEnd$,i.selectionScaled$).subscribe(()=>{this._formulaPromptService.disableLockedSelectionChange()}))})}))}_updateSelecting(e,t=!1){if(e.length!==0&&!(this._editorService.selectionChangingState()&&!this._formulaPromptService.isLockedSelectionInsert())&&(this._insertControlSelections(e),t)){const n=e[e.length-1];this._insertControlSelectionReplace(n)}}_enableRefSelectionsRenderService(){const e=this._selectionsChangeDisposables=new c.DisposableCollection;this._allSelectionRenderServices.forEach(t=>{e.add(t.enableSelectionChanging()),e.add(t.selectionMoving$.subscribe(n=>{this._updateSelecting(n.map(r=>U.convertSelectionDataToRange(r)))})),e.add(t.selectionMoveStart$.subscribe(n=>{const r=this._checkClearingLastSelection(t);this._currentlyWorkingRefRenderer=t,this._updateSelecting(n.map(s=>U.convertSelectionDataToRange(s)),r)}))})}_checkClearingLastSelection(e){return this._currentlyWorkingRefRenderer&&this._currentlyWorkingRefRenderer!==e?(this._currentlyWorkingRefRenderer.clearLastSelection(),!1):!0}_disposeSelectionsChangeListeners(){var e;(e=this._selectionsChangeDisposables)==null||e.dispose(),this._selectionsChangeDisposables=null}_insertControlSelections(e){const t=e[e.length-1];if(this._resetSequenceNodes(e.length),(e.length===this._previousRangesCount||this._previousRangesCount===0)&&this._previousSequenceNodes!=null)this._insertControlSelectionReplace(t);else{let n=this._formulaPromptService.getSequenceNodes();const r=this._getCurrentChar();n.length===0&&this._currentInsertRefStringIndex>0&&(this._currentInsertRefStringIndex=-1),this._previousInsertRefStringIndex=this._currentInsertRefStringIndex,!I.matchRefDrawToken(r)&&this._focusIsOnlyRange(e.length)&&(this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex,I.matchToken.COMMA),n=this._formulaPromptService.getSequenceNodes(),this._previousInsertRefStringIndex+=1),this._previousSequenceNodes=c.Tools.deepClone(n),this._formulaPromptService.setSequenceNodes(n);const s=this._generateRefString(t);this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,s),this._selectionRenderService.setSkipLastEnabled(!1)}this._arrowMoveActionState=2,this._previousRangesCount=e.length}_initAcceptFormula(){this.disposeWithMe(this._formulaPromptService.acceptFormulaName$.subscribe(e=>{const t=this._docSelectionManagerService.getActiveTextRange();if(t==null){this._hideFunctionPanel();return}const{startOffset:n}=t,r=this._formulaPromptService.getSequenceNodes(),s=this._formulaPromptService.getCurrentSequenceNodeIndex(n-2),i=r[s];if(i==null||typeof i=="string"){this._hideFunctionPanel();return}const a=e.length-i.token.length,l={...i};l.token=e,l.endIndex+=a,r[s]=l;const f=this._descriptionService.hasDefinedNameDescription(e),h=this._descriptionService.isFormulaDefinedName(e),d=e.length+1,u=!f||h;u&&r.splice(s+1,0,I.matchToken.OPEN_BRACKET);for(let v=s+2,C=r.length;v<C;v++){const g=r[v];if(typeof g=="string")continue;const E={...g};E.startIndex+=d,E.endIndex+=d,r[v]=E}let p=l.endIndex+1;u&&(p+=1),this._syncToEditor(r,p,void 0,!0,!1)}))}_changeFunctionPanelState(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null){this._hideFunctionPanel();return}const{startOffset:t}=e,n=this._formulaPromptService.getCurrentSequenceNode(t-2);if(n==null){this._hideFunctionPanel();return}if(typeof n!="string"&&n.nodeType===I.sequenceNodeType.FUNCTION&&!this._descriptionService.hasDefinedNameDescription(n.token.trim())){const l=n.token.toUpperCase();if(this._inputPanelState===1){const f=this._descriptionService.getSearchListByNameFirstLetter(l);if(this._hideFunctionPanel(),f==null||f.length===0)return;this._commandService.executeCommand(Ge.id,{visible:!0,searchText:l,searchList:f})}else this._changeHelpFunctionPanelState(l,-1);return}const r=this._getCurrentBodyDataStreamAndOffset(),s=this._lexerTreeBuilder.getFunctionAndParameter((r==null?void 0:r.dataStream)||"",t-1+((r==null?void 0:r.offset)||0));if(!s){this._hideFunctionPanel();return}const{functionName:i,paramIndex:a}=s;this._changeHelpFunctionPanelState(i.toUpperCase(),a)}_changeHelpFunctionPanelState(e,t){const n=this._descriptionService.getFunctionInfo(e);this._hideFunctionPanel(),n!=null&&this._commandService.executeCommand(Be.id,{visible:!0,paramIndex:t,functionInfo:n})}_hideFunctionPanel(){this._commandService.executeCommand(Ge.id,{visible:!1,searchText:""}),this._commandService.executeCommand(Be.id,{visible:!1,paramIndex:-1})}_checkShouldEnterSelectingMode(e=!1){if(e){this._enterSelectingMode();return}const t=this._getCurrentChar(),n=this._getCurrentDataStream();(n==null?void 0:n.substring(0,1))==="="&&t&&I.matchRefDrawToken(t)?this._enterSelectingMode():this._quitSelectingMode()}_getCurrentChar(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=this._getCurrentBodyDataStreamAndOffset();return n==null||t==null?void 0:n.dataStream[t-1+n.offset]}_getCurrentDataStream(){const e=this._getCurrentBodyDataStreamAndOffset();return e==null?void 0:e.dataStream}_enterSelectingMode(){this._isSelectingMode||(this._editorBridgeService.enableForceKeepVisible(),this._contextMenuService.disable(),this._formulaPromptService.enableLockedSelectionInsert(),this._selectionRenderService.setRemainLastEnabled(!0),this._enableRefSelectionsRenderService(),this._currentlyWorkingRefRenderer=null,this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._isSelectingMode=!0)}_quitSelectingMode(){this._isSelectingMode&&(this._editorBridgeService.disableForceKeepVisible(),this._contextMenuService.enable(),this._formulaPromptService.disableLockedSelectionInsert(),this._currentInsertRefStringIndex=-1,this._disposeSelectionsChangeListeners(),this._arrowMoveActionState===2&&(this._arrowMoveActionState=4),this._isSelectingMode=!1)}_getCurrentBodyDataStreamAndOffset(){var s,i;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!(e!=null&&e.getBody()))return;const t=e.getUnitId(),n=this._editorService.getEditor(t),r=(i=(s=e.getBody())==null?void 0:s.dataStream)!=null?i:"";return!n||!n.onlyInputRange()?{dataStream:r,offset:0}:{dataStream:I.compareToken.EQUALS+r,offset:1}}_getFormulaAndCellEditorBody(e){return e.map(t=>{const n=this._univerInstanceService.getUniverDocInstance(t);return n==null?void 0:n.getBody()})}_editorModelUnitIds(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();return this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t)?[t]:ar}_contextSwitch(){const e=this._getCurrentBodyDataStreamAndOffset();if(e&&c.isFormulaString(e.dataStream)){this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!0),this._contextService.setContextValue(U.REF_SELECTIONS_ENABLED,!0),this._contextService.setContextValue(O.UNI_DISABLE_CHANGING_FOCUS_KEY,!0);const t=this._lexerTreeBuilder.sequenceNodesBuilder(e.dataStream)||[];this._formulaPromptService.setSequenceNodes(t);const n=this._docSelectionManagerService.getActiveTextRange();if(n==null)return;const{startOffset:r}=n;this._currentInsertRefStringIndex=r-1+e.offset;return}this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue(U.REF_SELECTIONS_ENABLED,!1),this._contextService.setContextValue(O.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._formulaPromptService.disableLockedSelectionChange(),this._formulaPromptService.disableLockedSelectionInsert(),this._formulaPromptService.clearSequenceNodes(),this._hideFunctionPanel()}_getContextState(){return this._contextService.getContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA)}_highlightFormula(){if(this._getContextState()===!1)return;const e=this._formulaPromptService.getSequenceNodes(),t=this._editorModelUnitIds(),n=this._getFormulaAndCellEditorBody(t).filter(r=>!!r);if(e==null||e.length===0)this._existsSequenceNode=!1,n.forEach(r=>r.textRuns=[]);else{this._existsSequenceNode=!0;const{textRuns:r,refSelections:s}=this._buildTextRuns(e);n.forEach(i=>i.textRuns=r),this._allSelectionRenderServices.forEach(i=>this._refreshSelectionForReference(i,s))}this._refreshFormulaAndCellEditor(t)}_buildTextRuns(e){var a;const t=[],n=[],r=new Map;let s=0;const i=((a=this._getCurrentBodyDataStreamAndOffset())==null?void 0:a.offset)||0;for(let l=0,f=e.length;l<f;l++){const h=e[l];if(typeof h=="string"||this._descriptionService.hasDefinedNameDescription(h.token.trim()))continue;const{startIndex:d,endIndex:u,nodeType:p,token:v}=h;let C="";if(p===I.sequenceNodeType.REFERENCE){if(r.has(v))C=r.get(v);else{const g=s%this._formulaRefColors.length;C=this._formulaRefColors[g],r.set(v,C),s++}n.push({refIndex:l,themeColor:C,token:v})}else p===I.sequenceNodeType.NUMBER?C=this._numberColor:p===I.sequenceNodeType.STRING?C=this._stringColor:p===I.sequenceNodeType.ARRAY&&(C=this._stringColor);C&&C.length>0&&t.push({st:d+1-i,ed:u+2-i,ts:{cl:{rgb:C}}})}return{textRuns:t,refSelections:n}}_exceedCurrentRange(e,t,n){const{startRow:r,startColumn:s}=e;return r>t-1||s>n-1}_refreshSelectionForReference(e,t){const{unitId:n,sheetId:r}=this._editorBridgeService.getEditCellState(),{unitId:s,sheetId:i}=this._getCurrentUnitIdAndSheetId(),a=r===i,f=this._univerInstanceService.getUniverSheetInstance(n).getSheetBySheetId(r);let h=null;const d=[];for(let u=0,p=t.length;u<p;u++){const v=t[u],{themeColor:C,token:g,refIndex:E}=v,m=I.deserializeRangeWithSheet(g),{unitId:R,sheetName:y,range:M}=m,b=U.setEndForRange(M,f.getRowCount(),f.getColumnCount());if(R!=null&&R.length>0&&n!==R)continue;const T=this._getSheetIdByName(n,y.trim());if(!a&&T!==i||a&&y.length!==0&&T!==r||this._exceedCurrentRange(b,f.getRowCount(),f.getColumnCount()))continue;const A=this._getPrimary(b,C,E);if(A){h=A,d.push(h);continue}const N=U.getPrimaryForRange(b,f);!c.Rectangle.equals(N,b)&&b.startRow===b.endRow&&b.startColumn===b.endColumn&&(b.startRow=N.startRow,b.endRow=N.endRow,b.startColumn=N.startColumn,b.endColumn=N.endColumn),d.push({range:b,primary:N,style:Qe(this._themeService,C,E.toString())})}d.length&&this._refSelectionsService.setSelections(n,r,d,U.SelectionMoveType.ONLY_SET)}_getPrimary(e,t,n){const r=this._insertSelections.find(d=>{const{startRow:u,startColumn:p,endRow:v,endColumn:C}=d.range;return u===e.startRow&&p===e.startColumn&&v===e.endRow&&C===e.endColumn||u===e.startRow&&p===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn});if((r==null?void 0:r.primary)==null)return;const{isMerged:s,isMergedMainCell:i,startRow:a,endRow:l,startColumn:f,endColumn:h}=r.primary;return(s||i)&&a===e.startRow&&f===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn&&(e.endRow=l,e.endColumn=h),{range:e,primary:r.primary,style:Qe(this._themeService,t,n.toString())}}_getSheetIdByName(e,t){var r;const n=this._univerInstanceService.getUniverSheetInstance(e);return(r=n==null?void 0:n.getSheetBySheetName(I.normalizeSheetName(t)))==null?void 0:r.getSheetId()}_getSheetNameById(e,t){var s;const n=this._univerInstanceService.getUniverSheetInstance(e);return((s=n==null?void 0:n.getSheetBySheetId(t))==null?void 0:s.getName())||""}_getCurrentUnitIdAndSheetId(){var r,s;const e=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),t=e.getActiveSheet(),n=(s=(r=this._renderManagerService.getRenderById(e.getUnitId()))==null?void 0:r.with(P.SheetSkeletonManagerService))==null?void 0:s.getCurrentSkeleton();return{unitId:e.getUnitId(),sheetId:(t==null?void 0:t.getSheetId())||"",skeleton:n}}_getEditorOpenedForSheet(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),n=this._editorService.getEditor(t);return n?{openUnitId:n.getOpenForSheetUnitId(),openSheetId:n.getOpenForSheetSubUnitId()}:{openUnitId:null,openSheetId:null}}_generateRefString(e){let t="",n="";const{unitId:r,sheetId:s}=e.range,{openUnitId:i,openSheetId:a}=this._getEditorOpenedForSheet();r!==i&&r&&(t=r),s!==a&&r&&s&&(n=this._getSheetNameById(r,s));const{range:l,primary:f}=e;let{startRow:h,endRow:d,startColumn:u,endColumn:p}=l;const{startAbsoluteRefType:v,endAbsoluteRefType:C,rangeType:g}=l;if(f){const{isMerged:E,isMergedMainCell:m,startRow:R,endRow:y,startColumn:M,endColumn:b}=f;(E||m)&&R===h&&M===u&&y===d&&b===p&&(h=R,u=M,d=R,p=M)}return I.serializeRangeToRefString({sheetName:n,unitId:t,range:{startRow:h,endRow:d,startColumn:u,endColumn:p,rangeType:g,startAbsoluteRefType:v,endAbsoluteRefType:C}})}_syncToEditor(e,t,n,r=!0,s=!0){let i=I.generateStringWithSequence(e);const{textRuns:a,refSelections:l}=this._buildTextRuns(e);this._isSelectionMovingRefSelections=l,this._allSelectionRenderServices.forEach(C=>this._updateRefSelectionStyle(C,this._isSelectionMovingRefSelections));const f=this._docSelectionManagerService.getActiveTextRange();if(f==null)return;this._currentInsertRefStringIndex=t,n==null&&(n=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId()),this._fitEditorSize();const h=this._editorService.getEditor(n);h!=null&&h.isSingleChoice()?(i=i.split(",")[0],this._selectionRenderService.setSingleSelectionEnabled(!0)):this._selectionRenderService.setSingleSelectionEnabled(!1);let d=i,u=1;(!h||!h.onlyInputRange())&&(d=`${I.compareToken.EQUALS}${i}`,u=0);const{collapsed:p,style:v}=f;r?(this._commandService.executeCommand(J.ReplaceContentCommand.id,{unitId:n,body:{dataStream:d,textRuns:a},textRanges:[{startOffset:t+1-u,endOffset:t+1-u,collapsed:p,style:v}],segmentId:null,options:{fromSelection:s}}),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:v}],!0,{fromSelection:s})):(this._updateEditorModel(`${d}\r
34
+ `,a),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:v}],!0,{fromSelection:s})),this._layoutService.focus()}_fitEditorSize(){var n;const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();if(!(this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t))&&(this._editorBridgeService.changeEditorDirty(!0),!!this._editorBridgeService.isVisible().visible&&t===c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY)){const r=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),s=(n=r==null?void 0:r.getUnitId())!=null?n:"",i=this._renderManagerService.getRenderById(s);if(!i)return;i.with(P.SheetCellEditorResizeService).fitTextSize()}}_updateEditorModel(e,t){var l;const n=this._univerInstanceService.getCurrentUniverDocInstance(),r=n.getUnitId();if(!this._editorService.isEditor(r))return;const s=(l=this._renderManagerService.getRenderById(r))==null?void 0:l.with(He.DocSkeletonManagerService).getViewModel();if(s==null||n==null)return;const i=n==null?void 0:n.getSnapshot();if(i==null)return;const a={dataStream:e,textRuns:t};i.body=a,s.reset(n)}_insertControlSelectionReplace(e){this._previousSequenceNodes==null&&(this._previousSequenceNodes=this._formulaPromptService.getSequenceNodes()),this._previousInsertRefStringIndex==null&&(this._previousInsertRefStringIndex=this._currentInsertRefStringIndex);const t=c.Tools.deepClone(this._previousSequenceNodes);if(t==null)return;const{skeleton:n}=this._getCurrentUnitIdAndSheetId(),r=n==null?void 0:n.worksheet.getUnitId(),s=n==null?void 0:n.worksheet.getSheetId();e.range.sheetId=s,e.range.unitId=r;const i=this._generateRefString(e);this._formulaPromptService.setSequenceNodes(t),this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,i),this._syncToEditor(t,this._previousInsertRefStringIndex+i.length);const a=this._selectionRenderService.getSelectionDataWithStyle()||[];this._insertSelections=[];const l=a[a.length-1];if(l){const f=U.convertSelectionDataToRange(l);this._insertSelections.push(f)}}_focusIsOnlyRange(e){const t=this._editorService.getFocusEditor();return!t||!t.onlyInputRange()||this._existsSequenceNode||e>1||this._previousSequenceNodes!=null&&this._previousSequenceNodes.length>0?!0:(this._previousInsertRefStringIndex!=null&&(this._previousInsertRefStringIndex+=1),!1)}_resetSequenceNodes(e){const t=this._editorService.getFocusEditor();t&&t.onlyInputRange()&&(e>1||this._existsSequenceNode&&(this._formulaPromptService.clearSequenceNodes(),this._previousRangesCount=0,this._existsSequenceNode=!1))}_updateRefSelectionStyle(e,t){const n=e.getSelectionControls(),[r,s]=e.getLocation(),i=new Set;for(let a=0,l=t.length;a<l;a++){const f=t[a],{refIndex:h,themeColor:d,token:u}=f,p=I.deserializeRangeWithSheet(u),{unitId:v,sheetName:C,range:g}=p;if(!v&&v.length>0&&r!==v)continue;const E=this._getSheetIdByName(r,C.trim());if(E&&E!==s)continue;const m=n.find(R=>{const{startRow:y,startColumn:M,endRow:b,endColumn:T,rangeType:A}=R.getRange();return A===c.RANGE_TYPE.COLUMN&&M===g.startColumn&&T===g.endColumn||A===c.RANGE_TYPE.ROW&&y===g.startRow&&b===g.endRow||y===g.startRow&&M===g.startColumn&&b===g.endRow&&T===g.endColumn||y===g.startRow&&M===g.startColumn&&g.startRow===g.endRow&&g.startColumn===g.endColumn});if(m){const R=Qe(this._themeService,d,h.toString());m.updateStyle(R),i.add(m)}}}_onSelectionControlChange(e,t){var m;const{skeleton:n}=this._getCurrentUnitIdAndSheetId();if(!n)return;this._formulaPromptService.enableLockedSelectionChange();const r=(m=t.currentStyle)==null?void 0:m.id;if(!r||!c.Tools.isStringNumber(r))return;let{startRow:s,endRow:i,startColumn:a,endColumn:l}=e;const f=n?n.worksheet.getCellInfoInMergeData(s,a):{actualRow:s,actualColumn:a,isMergedMainCell:!1,isMerged:!1,endRow:s,endColumn:a,startRow:s,startColumn:a};if(f){const{isMerged:R,isMergedMainCell:y,startRow:M,endRow:b,startColumn:T,endColumn:A}=f;(R||y)&&M===s&&T===a&&b===i&&A===l&&(s=M,a=T,i=M,l=T)}const h=Number(r),d=this._formulaPromptService.getCurrentSequenceNodeByIndex(h);if(!d)return;let u={startAbsoluteRefType:c.AbsoluteRefType.NONE};if(typeof d!="string"){const R=d.token;u=I.getAbsoluteRefTypeWitString(R),u.endAbsoluteRefType==null&&(u.endAbsoluteRefType=u.startAbsoluteRefType)}const p=n==null?void 0:n.worksheet.getUnitId(),v=n==null?void 0:n.worksheet.getSheetId(),C=this._generateRefString({range:{startRow:Math.min(s,i),endRow:Math.max(s,i),startColumn:Math.min(a,l),endColumn:Math.max(a,l),...u,sheetId:v,unitId:p},primary:f,style:null});this._formulaPromptService.updateSequenceRef(h,C);const g=this._formulaPromptService.getSequenceNodes(),E=g[h];typeof E!="string"&&(this._syncToEditor(g,E.endIndex+1),t.updateRange(e,this._selectionRenderService.attachPrimaryWithCoord(f)))}_refreshFormulaAndCellEditor(e){var t;for(const n of e){const r=P.getEditorObject(n,this._renderManagerService),s=r==null?void 0:r.document;s!=null&&((t=s.getSkeleton())==null||t.calculate(),s.makeDirty())}}_cursorStateListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t.onPointerDown$.subscribeEvent(()=>{this._arrowMoveActionState=1,this._inputPanelState=3}))}_pressEnter(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressTab(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressEsc(e){const{keycode:t}=e,n=this._editorService.getFocusEditor();(!n||(n==null?void 0:n.isSheetEditor())===!0)&&this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressArrowKey(e){const{keycode:t,metaKey:n}=e;let r=c.Direction.DOWN;t===O.KeyCode.ARROW_DOWN?r=c.Direction.DOWN:t===O.KeyCode.ARROW_UP?r=c.Direction.UP:t===O.KeyCode.ARROW_LEFT?r=c.Direction.LEFT:t===O.KeyCode.ARROW_RIGHT&&(r=c.Direction.RIGHT),n===O.MetaKeys.CTRL_COMMAND?this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:r,jumpOver:P.JumpOver.moveGap}):n===O.MetaKeys.SHIFT?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:r}):n===un?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:r,jumpOver:P.JumpOver.moveGap}):this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:r})}_commandExecutedListener(){const e=[ve.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC),r=(n==null?void 0:n.getUnitId())||"";if(!(P.isRangeSelector(r)||P.isEmbeddingFormulaEditor(r))){if(t.id===Ye.id)this._changeRefString();else if(e.includes(t.id)){const s=t.params,{keycode:i,isSingleEditor:a=!1}=s;if(i===O.KeyCode.ENTER){this._pressEnter(s);return}if(i===O.KeyCode.TAB){this._pressTab(s);return}if(i===O.KeyCode.ESC){this._pressEsc(s);return}if(this._formulaPromptService.isSearching()){if(i===O.KeyCode.ARROW_DOWN){this._formulaPromptService.navigate({direction:c.Direction.DOWN});return}if(i===O.KeyCode.ARROW_UP){this._formulaPromptService.navigate({direction:c.Direction.UP});return}}if(a===!0)return;if(this._arrowMoveActionState===1){this._moveInEditor(i);return}if(this._arrowMoveActionState===4){this._editorBridgeService.changeVisible({visible:!1,eventType:G.DeviceInputEventType.Keyboard,keycode:i,unitId:""});return}if(this._arrowMoveActionState===2&&(this._arrowMoveActionState=3),this._refSelectionsService.getCurrentSelections().length===0){const d=this._sheetsSelectionsService.getCurrentLastSelection();if(d!=null){const u=c.Tools.deepClone(d);this._refSelectionsService.setSelections([u])}}this._pressArrowKey(s);const f=this._refSelectionsService.getCurrentSelections(),h=f[f.length-1];this._insertControlSelectionReplace(h),this._highlightFormula()}}}))}_moveInEditor(e){if(e==null)return;let t=c.Direction.LEFT;e===O.KeyCode.ARROW_DOWN?t=c.Direction.DOWN:e===O.KeyCode.ARROW_UP?t=c.Direction.UP:e===O.KeyCode.ARROW_RIGHT&&(t=c.Direction.RIGHT),this._commandService.executeCommand(J.MoveCursorOperation.id,{direction:t})}_userMouseListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t==null?void 0:t.onPointerDown$.subscribeEvent(()=>{this._userCursorMove=!0}))}_inputFormulaListener(){this.disposeWithMe(this._editorService.inputFormula$.subscribe(e=>{const{formulaString:t,editorUnitId:n}=e;if(t.substring(0,1)!==I.compareToken.EQUALS)return;const{unitId:r}=this._getCurrentUnitIdAndSheetId();this._editorBridgeService.isVisible().visible===!1&&this._editorBridgeService.changeVisible({visible:!0,eventType:G.DeviceInputEventType.Dblclick,unitId:r});const i=this._lexerTreeBuilder.sequenceNodesBuilder(t)||[];this._formulaPromptService.setSequenceNodes(i),this._syncToEditor(i,t.length-1,n,!0,!1)}))}_changeRefString(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=t-2,r=this._formulaPromptService.getCurrentSequenceNodeIndex(n),s=this._formulaPromptService.getCurrentSequenceNodeByIndex(r);if(s==null||typeof s=="string"||s.nodeType!==I.sequenceNodeType.REFERENCE)return;const i=s.token.split("!");let a=s.token;i.length>1&&(a=i[i.length-1]);let l="";for(let d=0,u=i.length;d<u-1;d++)l+=i[d];let f=a;if(a.indexOf(I.matchToken.COLON)>-1)if(!this._userCursorMove)f=this._changeRangeRef(a);else{const d=a.split(I.matchToken.COLON),u=d[0],p=d[1];n-s.startIndex<=u.length?f=this._changeSingleRef(u)+I.matchToken.COLON+p:f=u+I.matchToken.COLON+this._changeSingleRef(p)}else f=this._changeSingleRef(a);f=l+f;const h=f.length-s.token.length;this._formulaPromptService.updateSequenceRef(r,f),this._syncToEditor(this._formulaPromptService.getSequenceNodes(),n+h+1)}_changeRangeRef(e){const t=I.deserializeRangeWithSheet(e).range;let n="";return t.startAbsoluteRefType===c.AbsoluteRefType.NONE||t.startAbsoluteRefType==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),n=I.serializeRange(t),n}_changeSingleRef(e){const t=I.deserializeRangeWithSheet(e).range,n=t.startAbsoluteRefType;let r="";return n===c.AbsoluteRefType.NONE||n==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):n===c.AbsoluteRefType.ALL?(t.startAbsoluteRefType=c.AbsoluteRefType.ROW,t.endAbsoluteRefType=c.AbsoluteRefType.ROW):n===c.AbsoluteRefType.ROW?(t.startAbsoluteRefType=c.AbsoluteRefType.COLUMN,t.endAbsoluteRefType=c.AbsoluteRefType.COLUMN):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),r=I.serializeRange(t),r}_getEditorObject(){const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const t=e.getUnitId(),n=this._editorService.getEditor(t);return n==null?void 0:n.render}_isFormulaEditorActivated(){return this._editorBridgeService.isVisible().visible===!0||this._contextService.getContextValue(c.FORMULA_EDITOR_ACTIVATED)}_isSheetOrFormulaEditor(e){return e.isSheetEditor()||e.isFormulaEditor()}};rt=cr([oe(0,c.ICommandService),oe(1,c.IContextService),oe(2,c.Inject(P.IEditorBridgeService)),oe(3,c.Inject(Ne)),oe(4,c.Inject(I.LexerTreeBuilder)),oe(5,G.IRenderManagerService),oe(6,c.Inject(c.ThemeService)),oe(7,c.Inject(U.SheetsSelectionsService)),oe(8,U.IRefSelectionsService),oe(9,c.IUniverInstanceService),oe(10,c.Inject(me.IDescriptionService)),oe(11,c.Inject(He.DocSelectionManagerService)),oe(12,O.IContextMenuService),oe(13,J.IEditorService),oe(14,O.ILayoutService)],rt);var fn=Object.defineProperty,lr=Object.getOwnPropertyDescriptor,ur=(o,e,t)=>e in o?fn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,fr=(o,e,t,n)=>{for(var r=n>1?void 0:n?lr(e,t):e,s=o.length-1,i;s>=0;s--)(i=o[s])&&(r=(n?i(e,t,r):i(r))||r);return n&&r&&fn(e,t,r),r},Rt=(o,e)=>(t,n)=>e(t,n,o),dn=(o,e,t)=>ur(o,typeof e!="symbol"?e+"":e,t);j.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(e=nn,t,n,r){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=r;const{menu:s,...i}=c.merge(nn,this._config);s&&this._configService.setConfig("menu",s,{merge:!0}),this._configService.setConfig(io,i)}onStarting(){const e=this._injector;[[Ne,{useClass:st}],[ot],[qe],[$e],[et],[tt],[rt]].forEach(n=>e.add(n))}onRendered(){[[j.RefSelectionsRenderService],[_t]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[ot],[$e],[tt]]);const e=this._injector.get(O.ComponentManager);e.register(P.RANGE_SELECTOR_COMPONENT_KEY,Jt),e.register(P.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,tn)}onSteady(){this._injector.get(qe),this._injector.get(rt)}},dn(j.UniverSheetsFormulaUIPlugin,"pluginName",Tt),dn(j.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET),j.UniverSheetsFormulaUIPlugin=fr([c.DependentOn(I.UniverFormulaEnginePlugin,me.UniverSheetsFormulaPlugin),Rt(1,c.Inject(c.Injector)),Rt(2,G.IRenderManagerService),Rt(3,c.IConfigService)],j.UniverSheetsFormulaUIPlugin),j.FORMULA_PROMPT_ACTIVATED=Et,j.FormulaEditor=tn,j.HelpFunctionOperation=Be,j.InsertFunctionOperation=Ve,j.MoreFunctionsOperation=ze,j.RangeSelector=Jt,j.ReferenceAbsoluteOperation=Ye,j.SearchFunctionOperation=Ge,j.SelectEditorFormulaOperation=ve,j.SheetOnlyPasteFormulaCommand=We,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})});