@univerjs/sheets-formula-ui 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/umd/index.js CHANGED
@@ -1,5 +1,5 @@
1
- (function($,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("@univerjs/sheets-ui"),require("@univerjs/engine-formula"),require("rxjs"),require("@univerjs/docs-ui"),require("@univerjs/engine-render"),require("@univerjs/sheets"),require("@univerjs/sheets-formula"),require("@univerjs/ui"),require("react/jsx-runtime"),require("react"),require("@univerjs/design"),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/engine-render","@univerjs/sheets","@univerjs/sheets-formula","@univerjs/ui","react/jsx-runtime","react","@univerjs/design","@univerjs/docs","rxjs/operators"],a):($=typeof globalThis<"u"?globalThis:$||self,a($.UniverSheetsFormulaUi={},$.UniverCore,$.UniverSheetsUi,$.UniverEngineFormula,$.rxjs,$.UniverDocsUi,$.UniverEngineRender,$.UniverSheets,$.UniverSheetsFormula,$.UniverUi,$.React,$.React,$.UniverDesign,$.UniverDocs,$.rxjs.operators))})(this,(function($,a,N,T,q,Q,j,x,ge,l,y,E,B,pt,tn){"use strict";var lo=Object.defineProperty;var uo=($,a,N)=>a in $?lo($,a,{enumerable:!0,configurable:!0,writable:!0,value:N}):$[a]=N;var Y=($,a,N)=>uo($,typeof a!="symbol"?a+"":a,N);const We={id:"sheet.command.copy-formula-only",type:a.CommandType.COMMAND,handler:async e=>e.get(N.ISheetClipboardService).copy({copyHookType:N.PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY})},Ue={id:"sheet.command.paste-formula",type:a.CommandType.COMMAND,handler:async e=>e.get(a.ICommandService).executeCommand(N.SheetPasteCommand.id,{value:N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA})},Ee={id:"formula-ui.operation.select-editor-formula",type:a.CommandType.OPERATION,handler:(e,t)=>!0};var nn=Object.getOwnPropertyDescriptor,rn=(e,t,n,o)=>{for(var r=o>1?void 0:o?nn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},on=(e,t)=>(n,o)=>t(n,o,e);const vt="FORMULA_PROMPT_ACTIVATED",Ve=a.createIdentifier("formula-ui.prompt-service");let st=class{constructor(e){Y(this,"_search$",new q.Subject);Y(this,"_help$",new q.Subject);Y(this,"_navigate$",new q.Subject);Y(this,"_accept$",new q.Subject);Y(this,"_acceptFormulaName$",new q.Subject);Y(this,"search$",this._search$.asObservable());Y(this,"help$",this._help$.asObservable());Y(this,"navigate$",this._navigate$.asObservable());Y(this,"accept$",this._accept$.asObservable());Y(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());Y(this,"_searching",!1);Y(this,"_helping",!1);Y(this,"_sequenceNodes",[]);Y(this,"_isLockedOnSelectionChangeRefString",!1);Y(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=e}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(e){this._contextService.setContextValue(vt,e.visible),this._searching=e.visible,this._search$.next(e)}isSearching(){return this._searching}help(e){this._helping=e.visible,this._help$.next(e)}isHelping(){return this._helping}navigate(e){this._navigate$.next(e)}accept(e){this._accept$.next(e)}acceptFormulaName(e){this._acceptFormulaName$.next(e)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(e){this._sequenceNodes=e}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(e){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(e)]}getCurrentSequenceNodeByIndex(e){return this._sequenceNodes[e]}getCurrentSequenceNodeIndex(e){let t=0;const n=this._sequenceNodes[0];for(let o=0,r=this._sequenceNodes.length;o<r;o++){const s=this._sequenceNodes[o];if(typeof s=="string")t++;else{const{endIndex:i}=s;t=i}if(e<=t)return typeof n=="string"&&e!==0?o+1:o}return this._sequenceNodes.length}updateSequenceRef(e,t){const n=this._sequenceNodes[e];if(typeof n=="string"||n.nodeType!==T.sequenceNodeType.REFERENCE)return;const o=t.length-n.token.length,r={...n};r.token=t,r.endIndex+=o,this._sequenceNodes[e]=r;for(let s=e+1,i=this._sequenceNodes.length;s<i;s++){const c=this._sequenceNodes[s];if(typeof c=="string")continue;const d={...c};d.startIndex+=o,d.endIndex+=o,this._sequenceNodes[s]=d}}insertSequenceRef(e,t){const n=t.length,o=this.getCurrentSequenceNodeIndex(e);this._sequenceNodes.splice(o,0,{token:t,startIndex:e,endIndex:e+n-1,nodeType:T.sequenceNodeType.REFERENCE});for(let r=o+1,s=this._sequenceNodes.length;r<s;r++){const i=this._sequenceNodes[r];if(typeof i=="string")continue;const c={...i};c.startIndex+=n,c.endIndex+=n,this._sequenceNodes[r]=c}}insertSequenceString(e,t){const n=this.getCurrentSequenceNodeIndex(e),o=t.split("");this._sequenceNodes.splice(n,0,...o);const r=o.length;for(let s=n+r,i=this._sequenceNodes.length;s<i;s++){const c=this._sequenceNodes[s];if(typeof c=="string")continue;const d={...c};d.startIndex+=r,d.endIndex+=r,this._sequenceNodes[s]=d}}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=rn([on(0,a.IContextService)],st);const mt={id:"formula-ui.operation.help-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ve).help(t),!0)},ce={id:"formula-ui.operation.insert-function",type:a.CommandType.OPERATION,handler:async(e,t)=>{var I,R;const n=e.get(x.SheetsSelectionsService),o=e.get(Q.IEditorService),r=n.getCurrentSelections();if(!r||!r.length)return!1;const s=x.getSheetCommandTarget(e.get(a.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:c,subUnitId:d}=s,f=i.getCellMatrix(),{value:S}=t,p=e.get(a.ICommandService);e.get(N.IEditorBridgeService);const h=[],g=[];let u=null,m=0,C=0,_="";if(r.length===1&&(an(r[0].range)||ln(r[0].range)&&_t(f,r[0].range))){const{range:D,primary:v}=r[0],M=(I=v==null?void 0:v.actualRow)!=null?I:D.startRow,w=(R=v==null?void 0:v.actualColumn)!=null?R:D.startColumn;u=D,m=M,C=w;const W=Ct(f,M,w);W&&(_=T.serializeRange(W))}else r.some(D=>{var w,W;const{range:v,primary:M}=D;if(_t(f,v)){const U=(w=M==null?void 0:M.actualRow)!=null?w:v.startRow,P=(W=M==null?void 0:M.actualColumn)!=null?W:v.startColumn,F=Ct(f,U,P);if(!F)return u=v,m=U,C=P,!0;const A=T.serializeRange(F),O=`=${S}(${A})`;h.push({range:v,primary:{row:U,column:P},formula:O})}else{const{startRow:U,startColumn:P,endRow:F,endColumn:A}=v;if(U===F){const O=un(f,U,A,i.getColumnCount()-1),L=O===A?A-1:A,b=T.serializeRange({startRow:U,endRow:F,startColumn:P,endColumn:L}),k=`=${S}(${b})`;g.push({range:v,primary:{row:U,column:O},formula:k})}else{let O=-1;for(let b=P;b<=A;b++){const k=dn(f,b,F,i.getRowCount()-1);O=Math.max(O,k)}const L=O===F?F-1:F;for(let b=P;b<=A;b++){const k=T.serializeRange({startRow:U,endRow:L,startColumn:b,endColumn:b}),V=`=${S}(${k})`;g.push({range:v,primary:{row:O,column:b},formula:V})}}}return!1});if(u){const D=x.getCellAtRowCol(m,C,i),v={range:a.Rectangle.clone(u),primary:{startRow:D.startRow,startColumn:D.startColumn,endRow:D.endRow,endColumn:D.endColumn,actualRow:m,actualColumn:C,isMerged:D.isMerged,isMergedMainCell:D.startRow===m&&D.startColumn===C}},M={unitId:c,subUnitId:d,selections:[v]};await p.executeCommand(x.SetSelectionsOperation.id,M);const w=o.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),W=o.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);p.syncExecuteCommand(N.SetCellEditVisibleOperation.id,{visible:!0,unitId:c,eventType:j.DeviceInputEventType.Dblclick});const U=`=${S}(${_}`;w==null||w.replaceText(U),W==null||W.replaceText(U,!1)}return h.length===0&&g.length===0?!1:p.executeCommand(ge.InsertFunctionCommand.id,{list:h,listOfRangeHasNumber:g})}};function Ct(e,t,n){const o=sn(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=cn(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function sn(e,t,n){let o=!1;if(t===0)return t;for(let r=t-1;r>=0;r--){const s=e.getValue(r,n);if(xe(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!xe(s))return r+1;if(o&&r===0)return 0}}return t}function cn(e,t,n){let o=!1;if(n===0)return n;for(let r=n-1;r>=0;r--){const s=e.getValue(t,r);if(xe(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!xe(s))return r+1;if(o&&r===0)return 0}}return n}function xe(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return!1;const n=t.dataStream,r=n.substring(n.length-2,n.length)===a.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n;return a.isRealNum(r)}return e&&(e.t===a.CellValueType.NUMBER||a.getCellValueType(e)===a.CellValueType.NUMBER)}function an(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function ln(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function _t(e,t){for(let n=t.startRow;n<=t.endRow;n++)for(let o=t.startColumn;o<=t.endColumn;o++)if(xe(e.getValue(n,o)))return!1;return!0}function un(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function dn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const Et="SHEET_FORMULA_UI_PLUGIN",It=`${Et}_MORE_FUNCTIONS_COMPONENT`,He={id:"formula-ui.operation.more-functions",type:a.CommandType.OPERATION,handler:async e=>(e.get(l.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:It}}),!0)},it={id:"formula-ui.operation.change-ref-to-absolute",type:a.CommandType.OPERATION,handler:async e=>!0},yt={id:"formula-ui.operation.search-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ve).search(t),!0)};var fn=Object.getOwnPropertyDescriptor,hn=(e,t,n,o)=>{for(var r=o>1?void 0:o?fn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Be=(e,t)=>(n,o)=>t(n,o,e);$.FormulaReorderController=class extends a.Disposable{constructor(t,n,o,r){super(),this._sheetInterceptorService=t,this._univerInstanceService=n,this._formulaDataModel=o,this._lexerTreeBuilder=r,this._initialize()}_initialize(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:t=>t.id===x.ReorderRangeCommand.id?this._reorderFormula(t.params):{redos:[],undos:[]}}))}_reorderFormula(t){const n=[],o=[],{unitId:r,subUnitId:s,range:i,order:c}=t,d=this._univerInstanceService.getUniverSheetInstance(r),f=d==null?void 0:d.getSheetBySheetId(s);if(!f)return{redos:n,undos:o};const S=f.getCellMatrix(),p=new a.ObjectMatrix,h=new a.ObjectMatrix;let g=!1;return a.Range.foreach(i,(u,m)=>{let C=u;c.hasOwnProperty(u)&&(C=c[u]);const _=S.getValue(C,m);if(_!=null&&_.f||_!=null&&_.si){g=!0;const I=this._formulaDataModel.getFormulaStringByCell(C,m,s,r),R=this._lexerTreeBuilder.moveFormulaRefOffset(I,0,u-C),D=a.Tools.deepClone(_);D.f=R,D.si=null,p.setValue(u,m,D)}else p.setValue(u,m,_);h.setValue(u,m,S.getValue(u,m))}),g?(n.push({id:x.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:p.getMatrix()}}),o.push({id:x.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:h.getMatrix()}}),{redos:n,undos:o}):{redos:n,undos:o}}},$.FormulaReorderController=hn([Be(0,a.Inject(x.SheetInterceptorService)),Be(1,a.Inject(a.IUniverInstanceService)),Be(2,a.Inject(T.FormulaDataModel)),Be(3,a.Inject(T.LexerTreeBuilder))],$.FormulaReorderController);const Rt="sheets-formula-ui.base.config",Tt={};var gn=Object.getOwnPropertyDescriptor,Sn=(e,t,n,o)=>{for(var r=o>1?void 0:o?gn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Pe=(e,t)=>(n,o)=>t(n,o,e);const ct="SHEET_FORMULA_ALERT",pn={[T.ErrorType.DIV_BY_ZERO]:"divByZero",[T.ErrorType.NAME]:"name",[T.ErrorType.VALUE]:"value",[T.ErrorType.NUM]:"num",[T.ErrorType.NA]:"na",[T.ErrorType.CYCLE]:"cycle",[T.ErrorType.REF]:"ref",[T.ErrorType.SPILL]:"spill",[T.ErrorType.CALC]:"calc",[T.ErrorType.ERROR]:"error",[T.ErrorType.CONNECT]:"connect",[T.ErrorType.NULL]:"null"};let at=class extends a.Disposable{constructor(e,t,n,o,r,s){super(),this._context=e,this._hoverManagerService=t,this._cellAlertManagerService=n,this._localeService=o,this._formulaDataModel=r,this._zenZoneService=s,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(q.debounceTime(100)).subscribe(e=>{var t,n,o,r,s;if(e){const c=this._context.unit.getActiveSheet();if(!c)return this._hideAlert();const d=c.getCell(e.location.row,e.location.col),f=(r=(o=(n=(t=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:t[e.location.unitId])==null?void 0:n[e.location.subUnitId])==null?void 0:o[e.location.row])==null?void 0:r[e.location.col];if(a.isICellData(d)){const S=T.extractFormulaError(d,!!f);if(!S){this._hideAlert();return}const p=this._cellAlertManagerService.currentAlert.get(ct),h=(s=p==null?void 0:p.alert)==null?void 0:s.location;if(h&&h.row===e.location.row&&h.col===e.location.col&&h.subUnitId===e.location.subUnitId&&h.unitId===e.location.unitId){this._hideAlert();return}this._cellAlertManagerService.showAlert({type:N.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${pn[S]}`),location:e.location,width:200,height:74,key:ct});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(e=>{e&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(ct)}};at=Sn([Pe(1,a.Inject(N.HoverManagerService)),Pe(2,a.Inject(N.CellAlertManagerService)),Pe(3,a.Inject(a.LocaleService)),Pe(4,a.Inject(T.FormulaDataModel)),Pe(5,l.IZenZoneService)],at);var vn=Object.getOwnPropertyDescriptor,mn=(e,t,n,o)=>{for(var r=o>1?void 0:o?vn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},bt=(e,t)=>(n,o)=>t(n,o,e);let Ke=class extends a.Disposable{constructor(e,t){super(),this._autoFillService=e,this._lexerTreeBuilder=t,this._registerAutoFill()}_registerAutoFill(){const e={type:N.DATA_TYPE.FORMULA,priority:1001,match:t=>a.isFormulaString(t==null?void 0:t.f)||a.isFormulaId(t==null?void 0:t.si),isContinue:(t,n)=>t.type===N.DATA_TYPE.FORMULA,applyFunctions:{[N.APPLY_TYPE.COPY]:(t,n,o,r,s)=>{const{data:i,index:c}=t;return this._fillCopyFormula(i,n,o,c,r,s)}}};this._autoFillService.registerRule(e)}_fillCopyFormula(e,t,n,o,r,s){var f,S;const i=_n(r),c=[],d=new Map;for(let p=1;p<=t;p++){const h=(p-1)%e.length,g=o[h],u=a.Tools.deepClone(e[h]);if(u){const m=((f=e[h])==null?void 0:f.f)||"",C=((S=e[h])==null?void 0:S.si)||"",_=a.isFormulaString(m);if(a.isFormulaId(C))u.si=C,u.f=null,u.v=null,u.p=null,u.t=null,c.push(u);else if(_){let R=d.get(h);if(R)u.si=R,u.f=null,u.v=null,u.p=null,u.t=null;else{R=a.generateRandomId(6),d.set(h,R);const{offsetX:D,offsetY:v}=Cn(i,t,n,s,g),M=this._lexerTreeBuilder.moveFormulaRefOffset(m,D,v);u.si=R,u.f=M,u.v=null,u.p=null,u.t=null}c.push(u)}}}return c}};Ke=mn([bt(0,N.IAutoFillService),bt(1,a.Inject(T.LexerTreeBuilder))],Ke);function Cn(e,t,n,o,r){const{source:s,target:i}=o,{rows:c}=i,{rows:d}=s;let f=0,S=0;switch(n){case a.Direction.UP:S=c[r]-d[r];break;case a.Direction.RIGHT:f=e;break;case a.Direction.DOWN:S=c[r]-d[r];break;case a.Direction.LEFT:f=-e*t;break}return{offsetX:f,offsetY:S}}function _n(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}var En=Object.getOwnPropertyDescriptor,In=(e,t,n,o)=>{for(var r=o>1?void 0:o?En(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Le=(e,t)=>(n,o)=>t(n,o,e);const yn="default-paste-formula";let je=class extends a.Disposable{constructor(e,t,n,o,r){super(),this._univerInstanceService=e,this._lexerTreeBuilder=t,this._sheetClipboardService=n,this._injector=o,this._formulaDataModel=r,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._copyFormulaOnlyHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_copyFormulaOnlyHook(){const e=this;let t=null;return{id:N.PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY,priority:10,onBeforeCopy(n,o){t=e._getWorksheet(n,o)},onCopyCellContent(n,o){if(!t)return"";const r=t.getCellRaw(n,o);return r?a.isFormulaString(r.f)?r.f:a.isFormulaId(r.si)&&e._formulaDataModel.getFormulaStringByCell(n,o,t.getSheetId(),t.getUnitId())||"":""},onAfterCopy(){t=null},getFilteredOutRows(n,o,r){const s=e._getWorksheet(n,o);if(!s)return[];const{startRow:i,endRow:c}=r,d=[];for(let f=i;f<=c;f++)s.getRowFiltered(f)&&d.push(f);return d},handleMatrixOnCell(n,o,r,s,i,c,d){const f=i.getValue(n,o);if(t&&f&&(a.isFormulaString(f.f)||a.isFormulaId(f.si))){const S=a.isFormulaString(f.f)?f.f:e._formulaDataModel.getFormulaStringByCell(n,o,t.getSheetId(),t.getUnitId());c.setValue(r,s,{...a.getEmptyCell(),f:S}),d.setValue(r,s,{...a.getEmptyCell(),f:S,displayV:S})}else i.setValue(n,o,a.getEmptyCell()),c.setValue(r,s,a.getEmptyCell()),d.setValue(r,s,a.getEmptyCell())}}}_pasteFormulaHook(){return{id:N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!0)}}_pasteWithFormulaHook(){return{id:yn,priority:10,onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!1)}}_getWorkbook(e){return e?this._univerInstanceService.getUnit(e,a.UniverInstanceType.UNIVER_SHEET):this._univerInstanceService.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET)}_getWorksheet(e,t){const n=this._getWorkbook(e);return t?n==null?void 0:n.getSheetBySheetId(t):n==null?void 0:n.getActiveSheet()}_onPasteCells(e,t,n,o,r){var h;if([N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT,N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH].includes(o.pasteType))return{undos:[],redos:[]};const i=this._getWorkbook(),c=t.unitId||(i==null?void 0:i.getUnitId()),d=t.subUnitId||((h=i==null?void 0:i.getActiveSheet())==null?void 0:h.getSheetId());if(!c||!d)return{undos:[],redos:[]};const f=t.range,S=n,p={copyType:o.copyType||N.COPY_TYPE.COPY,copyRange:e==null?void 0:e.range,pasteType:o.pasteType};return this._injector.invoke(g=>Rn(c,d,f,S,g,p,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};je=In([Le(0,a.IUniverInstanceService),Le(1,a.Inject(T.LexerTreeBuilder)),Le(2,N.ISheetClipboardService),Le(3,a.Inject(a.Injector)),Le(4,a.Inject(T.FormulaDataModel))],je);function Rn(e,t,n,o,r,s,i,c,d=!1,f){const S=[],p=[],h=Tn(e,t,n,o,s,i,c,f);if(!h.hasValue())return{undos:[],redos:[]};const g={unitId:e,subUnitId:t,cellValue:h.getData()};S.push({id:x.SetRangeValuesMutation.id,params:g});const u=x.SetRangeValuesUndoMutationFactory(r,g);return p.push({id:x.SetRangeValuesMutation.id,params:u}),{undos:p,redos:S}}function Tn(e,t,n,o,r,s,i,c){return c?r.pasteType===N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE?Mn(e,t,n,o,i,c):r.pasteType===N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA?On(e,t,n,o,s,i,c):Nn(e,t,n,o,r.copyType,s,i,c):bn(e,t,n,o,i)}function bn(e,t,n,o,r){const s=new a.ObjectMatrix,i=r.getSheetFormulaData(e,t);return o.forValue((c,d,f)=>{var g;const S=n.rows[c],p=n.cols[d],h={};a.isFormulaString(f.v)?(h.v=null,h.f=`${f.v}`,h.si=null,h.p=null,s.setValue(S,p,h)):(g=i==null?void 0:i[S])!=null&&g[p]&&(h.v=f.v,h.f=null,h.si=null,h.p=null,s.setValue(S,p,h))}),s}function Mn(e,t,n,o,r,s){var f,S;const i=new a.ObjectMatrix,c=(S=(f=r.getArrayFormulaCellData())==null?void 0:f[s.unitId])==null?void 0:S[s.subUnitId],d=r.getSheetFormulaData(e,t);return o.forValue((p,h,g)=>{var R,D;const u=s.range.rows[p%s.range.rows.length],m=s.range.cols[h%s.range.cols.length],C=n.rows[p],_=n.cols[h],I={};if(a.isFormulaString(g.f)||a.isFormulaId(g.si))I.v=g.v,I.f=null,I.si=null,I.p=null,i.setValue(C,_,I);else if((R=c==null?void 0:c[u])!=null&&R[m]){const v=c[u][m];I.v=v.v,I.f=null,I.si=null,I.p=null,i.setValue(C,_,I)}else if((D=d==null?void 0:d[C])!=null&&D[_]){if(I.v=g.v,I.f=null,I.si=null,I.p=null,g.p){const v=Mt(g);v&&(I.v=v)}i.setValue(C,_,I)}}),i}function On(e,t,n,o,r,s,i){const c=new a.ObjectMatrix,d=new Map;return o.forValue((f,S,p)=>{const h=n.rows[f],g=n.cols[S],u={};if(a.isFormulaId(p.si)){if(i.unitId!==e||i.subUnitId!==t){const m=s.getFormulaStringByCell(i.range.rows[f%i.range.rows.length],i.range.cols[S%i.range.cols.length],i.subUnitId,i.unitId),C=n.cols[S]-i.range.cols[S%i.range.cols.length],_=n.rows[f]-i.range.rows[f%i.range.rows.length],I=r.moveFormulaRefOffset(m||"",C,_);u.si=null,u.f=I}else u.si=p.si,u.f=null;u.v=null,u.p=null,c.setValue(h,g,u)}else if(a.isFormulaString(p.f)){const m=`${f%i.range.rows.length}_${S%i.range.cols.length}`;let C=d.get(m);if(C)u.si=C,u.f=null;else{C=a.generateRandomId(6),d.set(m,C);const _=n.cols[S]-i.range.cols[S%i.range.cols.length],I=n.rows[f]-i.range.rows[f%i.range.rows.length],R=r.moveFormulaRefOffset(p.f||"",_,I);u.si=C,u.f=R}u.v=null,u.p=null,c.setValue(h,g,u)}else{if(u.v=p.v,u.f=null,u.si=null,u.p=null,p.p){const m=Mt(p);m&&(u.v=m)}c.setValue(h,g,u)}}),c}function Nn(e,t,n,o,r,s,i,c){const d=new a.ObjectMatrix,f=new Map,S=i.getSheetFormulaData(e,t),p=[];return r===N.COPY_TYPE.CUT?o.forValue((h,g,u)=>{const m=n.rows[h],C=n.cols[g],_={};if(a.isFormulaId(u.si)){if(a.isFormulaString(u.f))p.push(u.si),_.f=u.f,_.si=u.si;else if(p.includes(u.si))_.f=null,_.si=u.si;else{const I=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[g%c.range.cols.length],c.subUnitId,c.unitId);_.f=I,_.si=null}_.v=null,_.p=null,d.setValue(m,C,_)}else a.isFormulaString(u.f)&&(_.f=u.f,_.si=null,_.v=null,_.p=null,d.setValue(m,C,_))}):o.forValue((h,g,u)=>{var I;const m=n.rows[h],C=n.cols[g],_={};if(a.isFormulaId(u.si)){if(c.unitId!==e||c.subUnitId!==t){const R=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[g%c.range.cols.length],c.subUnitId,c.unitId),D=n.cols[g]-c.range.cols[g%c.range.cols.length],v=n.rows[h]-c.range.rows[h%c.range.rows.length],M=s.moveFormulaRefOffset(R||"",D,v);_.si=null,_.f=M}else _.si=u.si,_.f=null;_.v=null,_.p=null,d.setValue(m,C,_)}else if(a.isFormulaString(u.f)){const R=`${h%c.range.rows.length}_${g%c.range.cols.length}`;let D=f.get(R);if(D)_.si=D,_.f=null;else{D=a.generateRandomId(6),f.set(R,D);const v=n.cols[g]-c.range.cols[g%c.range.cols.length],M=n.rows[h]-c.range.rows[h%c.range.rows.length],w=s.moveFormulaRefOffset(u.f||"",v,M);_.si=D,_.f=w}_.v=null,_.p=null,d.setValue(m,C,_)}else(I=S==null?void 0:S[m])!=null&&I[C]&&(_.v=u.v,_.f=null,_.si=null,_.p=u.p,d.setValue(m,C,_))}),p.length>0&&new a.ObjectMatrix(S).forValue((h,g,u)=>{if(!(c.range.rows.includes(h)&&c.range.cols.includes(g))&&!(n.rows.includes(h)&&n.cols.includes(g))&&p.includes(u==null?void 0:u.si)){const m=i.getFormulaStringByCell(h,g,c.subUnitId,c.unitId);d.setValue(h,g,{f:m,si:null,v:null,p:null})}}),d}function Mt(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return;const n=t.dataStream;return n.substring(n.length-2,n.length)===a.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n}}var Dn=Object.getOwnPropertyDescriptor,kn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Dn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Ie=(e,t)=>(n,o)=>t(n,o,e);let qe=class extends a.Disposable{constructor(t,n,o,r,s,i,c,d){super();Y(this,"_previousShape");Y(this,"_skeleton");this._context=t,this._sheetInterceptorService=n,this._formulaDataModel=o,this._themeService=r,this._renderManagerService=s,this._sheetSkeletonManagerService=i,this._commandService=c,this._logService=d,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{var n,o;if(t==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:r}=t,s=(o=(n=this._skeleton)==null?void 0:n.worksheet)==null?void 0:o.getSheetId();if(this._changeRuntime(r),s!==r.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:c}=t;this._updateArrayFormulaRangeShape(i,c)}}}))}_changeRuntime(t){this._skeleton=t}_initInterceptorEditorStart(){this.disposeWithMe(a.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(x.BEFORE_CELL_EDIT,{handler:(t,n,o)=>{var u,m,C,_;const{row:r,col:s,unitId:i,subUnitId:c,worksheet:d}=n,f=this._formulaDataModel.getArrayFormulaRange(),S=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),t==null)return o(t);let p=null;const h=this._formulaDataModel.getFormulaStringByCell(r,s,c,i);if(h!==null&&(p={f:h}),t.v!=null&&t.v!==""&&((C=(m=(u=S[i])==null?void 0:u[c])==null?void 0:m[r])==null?void 0:C[s])==null)return p?{...t,...p}:o(t);const g=(_=f==null?void 0:f[i])==null?void 0:_[c];return g!=null&&(p=this._displayArrayFormulaRangeShape(g,r,s,i,c,d,p)),p?{...t,...p}:o(t)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{(t.id===T.SetFormulaCalculationResultMutation.id||t.id===T.SetArrayFormulaDataMutation.id&&n&&n.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{x.SetWorksheetRowAutoHeightMutation.id===t.id&&requestIdleCallback(()=>{const n=t.params,{unitId:o,subUnitId:r,rowsAutoHeightInfo:s}=n;this._refreshArrayFormulaRangeShapeByRow(o,r,s)})}))}_displayArrayFormulaRangeShape(t,n,o,r,s,i,c){return new a.ObjectMatrix(t).forValue((d,f,S)=>{if(S==null)return!0;const{startRow:p,startColumn:h,endRow:g,endColumn:u}=S;if(d===n&&f===o)return this._createArrayFormulaRangeShape(S,r),!1;if(n>=p&&n<=g&&o>=h&&o<=u){const m=i.getCell(p,h);return(m==null?void 0:m.v)===T.ErrorType.SPILL||(m==null?void 0:m.f)==null?void 0:(c==null&&(c={f:m.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(S,r),!1)}}),c}_createArrayFormulaRangeShape(t,n){const o=this._renderManagerService.getRenderById(n),r=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!o||!r)return;const{scene:s}=o;if(!s)return;const i={range:t,primary:null,style:{strokeWidth:1,stroke:this._themeService.getColorFromTheme("primary.600"),fill:new a.ColorKit(this._themeService.getColorFromTheme("white")).setAlpha(0).toString(),widgets:{}}},c=N.attachSelectionWithCoord(i,r),{rowHeaderWidth:d,columnHeaderHeight:f}=r,S=new N.SelectionControl(s,N.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:f});S.updateRangeBySelectionWithCoord(c),S.setEvent(!1),this._previousShape=S}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(t,n){if(this._previousShape){const{startRow:o,endRow:r,startColumn:s,endColumn:i}=this._previousShape.getRange(),c={startRow:o,endRow:r,startColumn:s,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(c,t)}}_checkCurrentSheet(t,n){const o=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!o)return!1;const r=o.worksheet;return r?r.unitId===t&&r.getSheetId()===n:!1}_updateArrayFormulaRangeShape(t,n){this._checkCurrentSheet(t,n)&&this._previousShape&&this._refreshArrayFormulaRangeShape(t)}_refreshArrayFormulaRangeShapeByRow(t,n,o){if(!this._checkCurrentSheet(t,n)||!this._previousShape)return;const{startRow:r,endRow:s,startColumn:i,endColumn:c}=this._previousShape.getRange();for(let d=0;d<o.length;d++){const{row:f}=o[d];if(r>=f){const S={startRow:r,endRow:s,startColumn:i,endColumn:c};this._refreshArrayFormulaRangeShape(t,S);break}}}};qe=kn([Ie(1,a.Inject(x.SheetInterceptorService)),Ie(2,a.Inject(T.FormulaDataModel)),Ie(3,a.Inject(a.ThemeService)),Ie(4,j.IRenderManagerService),Ie(5,a.Inject(N.SheetSkeletonManagerService)),Ie(6,a.ICommandService),Ie(7,a.ILogService)],qe);var wn=Object.getOwnPropertyDescriptor,An=(e,t,n,o)=>{for(var r=o>1?void 0:o?wn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Ot=(e,t)=>(n,o)=>t(n,o,e);const xn={tl:{size:6,color:"#409f11"}};let Ye=class extends a.RxDisposable{constructor(e,t){super(),this._sheetInterceptorService=e,this._formulaDataModel=t,this.disposeWithMe(this._sheetInterceptorService.intercept(x.INTERCEPTOR_POINT.CELL_CONTENT,{effect:a.InterceptorEffectEnum.Style,handler:(n,o,r)=>{var c,d,f,S;const s=(S=(f=(d=(c=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:c[o.unitId])==null?void 0:d[o.subUnitId])==null?void 0:f[o.row])==null?void 0:S[o.col];return!T.extractFormulaError(n,!!s)||!n||(n===o.rawData&&(n={...o.rawData}),n.markers={...n==null?void 0:n.markers,...xn}),r(n)},priority:10}))}};Ye=An([Ot(0,a.Inject(x.SheetInterceptorService)),Ot(1,a.Inject(T.FormulaDataModel))],Ye);function Pn(){const e=l.useDependency(ge.TriggerCalculationController),t=l.useDependency(a.ICommandService),n=l.useObservable(e.progress$),o=E.useCallback(()=>{t.executeCommand(T.SetFormulaCalculationStopMutation.id)},[t]),r=E.useCallback(()=>{e.clearProgress()},[e]);return y.jsx(l.ProgressBar,{progress:n,onTerminate:o,onClearProgress:r})}function Ln(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName"&&n!=="Table").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function Nt(e){if(!e.require&&!e.repeat)return`[${e.name}]`;if(e.require&&!e.repeat)return e.name;if(!e.require&&e.repeat)return`[${e.name},...]`;if(e.require&&e.repeat)return`${e.name},...`}function Dt(e){const{prefix:t,value:n}=e;return y.jsxs("div",{children:[y.jsxs("span",{children:[t,"("]}),n&&n.map((o,r)=>y.jsxs("span",{children:[y.jsx("span",{children:Nt(o)}),r===n.length-1?"":","]},r)),")"]})}function $e(e){const{className:t,value:n,title:o}=e;return y.jsxs("div",{className:"univer-mb-2 univer-text-xs",children:[y.jsx("div",{className:B.clsx("univer-mb-2 univer-font-medium univer-text-gray-500 dark:!univer-text-gray-300",t),children:o}),y.jsx("div",{className:"univer-break-all univer-text-gray-900 dark:!univer-text-white",children:n})]})}function $n(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;const[o,r]=E.useState([]),[s,i]=E.useState(t.functionParameter),[c,d]=E.useState(-1);return y.jsxs("div",{children:[y.jsx("div",{className:B.clsx("univer-h-[364px] univer-overflow-y-auto",B.scrollbarClassName),children:s.map((f,S)=>y.jsxs("div",{children:[y.jsx("div",{className:"univer-text-sm",children:f.name}),y.jsx("div",{className:"univer-mb-2 univer-mt-1"})]},S))}),y.jsx("div",{className:B.clsx("univer-flex-1 univer-p-3",B.borderLeftClassName),children:y.jsx($e,{title:c===-1?y.jsx(Dt,{prefix:t.functionName,value:s}):s[c].name,value:c===-1?t.description:s[c].detail})})]})}function ye({ref:e,...t}){const{icon:n,id:o,className:r,extend:s,...i}=t,c=`univerjs-icon univerjs-icon-${o} ${r||""}`.trim(),d=E.useRef(`_${Un()}`);return kt(n,`${o}`,{defIds:n.defIds,idSuffix:d.current},{ref:e,className:c,...i},s)}function kt(e,t,n,o,r){return E.createElement(e.tag,{key:t,...Fn(e,n,r),...o},(Wn(e,n).children||[]).map((s,i)=>kt(s,`${t}-${e.tag}-${i}`,n,void 0,r)))}function Fn(e,t,n){const o={...e.attrs};n!=null&&n.colorChannel1&&o.fill==="colorChannel1"&&(o.fill=n.colorChannel1),e.tag==="mask"&&o.id&&(o.id=o.id+t.idSuffix),Object.entries(o).forEach(([s,i])=>{s==="mask"&&typeof i=="string"&&(o[s]=i.replace(/url\(#(.*)\)/,`url(#$1${t.idSuffix})`))});const{defIds:r}=t;return!r||r.length===0||(e.tag==="use"&&o["xlink:href"]&&(o["xlink:href"]=o["xlink:href"]+t.idSuffix),Object.entries(o).forEach(([s,i])=>{typeof i=="string"&&(o[s]=i.replace(/url\(#(.*)\)/,`url(#$1${t.idSuffix})`))})),o}function Wn(e,t){var o;const{defIds:n}=t;return!n||n.length===0?e:e.tag==="defs"&&((o=e.children)!=null&&o.length)?{...e,children:e.children.map(r=>typeof r.attrs.id=="string"&&n&&n.includes(r.attrs.id)?{...r,attrs:{...r.attrs,id:r.attrs.id+t.idSuffix}}:r)}:e}function Un(){return Math.random().toString(36).substring(2,8)}ye.displayName="UniverIcon";const Vn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},wt=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"check-mark-icon",ref:n,icon:Vn}))});wt.displayName="CheckMarkIcon";const Hn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},At=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"close-icon",ref:n,icon:Hn}))});At.displayName="CloseIcon";const Bn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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 0.866699 5.9313 0.866699H10.069C10.4004 0.866699 10.669 1.13533 10.669 1.4667C10.669 1.79807 10.4004 2.0667 10.069 2.0667H5.9313C5.59993 2.0667 5.3313 1.79807 5.3313 1.4667Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M1.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.64443C14.8999 3.9758 14.6312 4.24443 14.2999 4.24443H1.69985C1.36848 4.24443 1.09985 3.9758 1.09985 3.64443Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M6.12398 8.30171C6.35829 8.0674 6.73819 8.0674 6.97251 8.30171L8.00007 9.32928L9.02764 8.30171C9.26195 8.0674 9.64185 8.0674 9.87617 8.30171C10.1105 8.53603 10.1105 8.91593 9.87617 9.15024L8.8486 10.1778L9.87617 11.2054C10.1105 11.4397 10.1105 11.8196 9.87617 12.0539C9.64185 12.2882 9.26195 12.2882 9.02764 12.0539L8.00007 11.0263L6.97251 12.0539C6.73819 12.2882 6.35829 12.2882 6.12398 12.0539C5.88966 11.8196 5.88966 11.4397 6.12398 11.2054L7.15154 10.1778L6.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=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"delete-icon",ref:n,icon:Bn}))});xt.displayName="DeleteIcon";const Kn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},Pt=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"increase-icon",ref:n,icon:Kn}))});Pt.displayName="IncreaseIcon";const jn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},Lt=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"more-icon",ref:n,icon:jn}))});Lt.displayName="MoreIcon";const qn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},$t=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"select-range-icon",ref:n,icon:qn}))});$t.displayName="SelectRangeIcon";function Yn(e){const{onChange:t}=e,n="-1",[o,r]=E.useState(""),[s,i]=E.useState([]),[c,d]=E.useState(0),[f,S]=E.useState(n),[p,h]=E.useState(0),[g,u]=E.useState(null),m=l.useDependency(ge.IDescriptionService),C=l.useDependency(a.LocaleService),_=l.useDependency(l.ISidebarService),I=l.useObservable(_.sidebarOptions$),R=Ln(T.FunctionType,C);R.unshift({label:C.t("formula.moreFunctions.allFunctions"),value:n});const D=C.t("formula.prompt.required"),v=C.t("formula.prompt.optional");E.useEffect(()=>{W(n)},[]),E.useEffect(()=>{w(0)},[s]),E.useEffect(()=>{I!=null&&I.visible&&(r(""),i([]),d(0),S(n),h(0),u(null),W(n))},[I]);const M=O=>{if(o.trim()==="")return O;const L=new RegExp(`(${o.toLocaleUpperCase()})`);return O.split(L).filter(Boolean).map((k,V)=>k.match(L)?y.jsx("span",{className:"univer-text-red-500",children:k},V):k)},w=O=>{if(s.length===0){u(null);return}h(O);const L=m.getFunctionInfo(s[O].name);if(!L){u(null);return}u(L),t(L)};function W(O){S(O);const L=m.getSearchListByType(+O);i(L)}function U(O){r(O);const L=m.getSearchListByName(O);i(L)}function P(O){if(O.stopPropagation(),O.key==="ArrowDown"){const L=c+1;d(L===s.length?0:L)}else if(O.key==="ArrowUp"){const L=c-1;d(L===-1?s.length-1:L)}else O.key==="Enter"&&w(c)}const F=O=>{d(O)},A=()=>{d(-1)};return y.jsxs("div",{children:[y.jsxs("div",{className:"univer-flex univer-items-center univer-justify-between univer-gap-2",children:[y.jsx(B.Select,{value:f,options:R,onChange:W}),y.jsx(B.Input,{placeholder:C.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:P,value:o,onChange:U,size:"small",allowClear:!0})]}),s.length>0&&y.jsx("ul",{className:B.clsx("univer-mb-0 univer-mt-2 univer-box-border univer-max-h-72 univer-w-full univer-select-none univer-list-none univer-overflow-y-auto univer-rounded univer-p-3 univer-outline-none",B.borderClassName,B.scrollbarClassName),onKeyDown:P,tabIndex:-1,children:s.map(({name:O},L)=>y.jsxs("li",{className:B.clsx("univer-relative univer-box-border univer-cursor-pointer univer-rounded univer-px-7 univer-py-1 univer-text-sm univer-text-gray-900 univer-transition-colors dark:!univer-text-white",{"univer-bg-gray-200 dark:!univer-bg-gray-600":c===L}),onMouseEnter:()=>F(L),onMouseLeave:A,onClick:()=>w(L),children:[p===L&&y.jsx(wt,{className:"univer-absolute univer-left-1.5 univer-top-1/2 univer-inline-flex -univer-translate-y-1/2 univer-text-base univer-text-primary-600"}),y.jsx("span",{className:"univer-block",children:M(O)})]},L))}),g&&y.jsxs("div",{className:B.clsx("univer-mx-0 univer-my-2 univer-overflow-y-auto",B.scrollbarClassName),children:[y.jsx($e,{title:g.functionName,value:g.description}),y.jsx($e,{title:C.t("formula.moreFunctions.syntax"),value:y.jsx(Dt,{prefix:g.functionName,value:g.functionParameter})}),y.jsx($e,{title:C.t("formula.prompt.helpExample"),value:`${g.functionName}(${g.functionParameter.map(O=>O.example).join(",")})`}),g.functionParameter&&g.functionParameter.map(O=>y.jsx($e,{title:O.name,value:`${O.require?D:v} ${O.detail}`},O.name))]})]})}function zn(){const e=N.useActiveWorkbook(),[t,n]=E.useState(!0),[o,r]=E.useState(!1),[s,i]=E.useState(null);l.useDependency(N.IEditorBridgeService);const c=l.useDependency(a.LocaleService),d=l.useDependency(Q.IEditorService),f=l.useDependency(a.IUniverInstanceService),S=l.useDependency(a.ICommandService);function p(){n(!t),r(!o)}function h(){const g=x.getSheetCommandTarget(f);if(!g)return;S.executeCommand(N.SetCellEditVisibleOperation.id,{visible:!0,unitId:g.unitId,eventType:j.DeviceInputEventType.Dblclick});const u=d.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),m=d.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),C=`=${s==null?void 0:s.functionName}(`;u==null||u.replaceText(C),m==null||m.replaceText(C,!1)}return y.jsxs("div",{"data-u-comp":"sheets-formula-functions-panel",className:"univer-box-border univer-flex univer-h-full univer-flex-col univer-justify-between univer-py-2",children:[t&&y.jsx(Yn,{onChange:i}),o&&y.jsx($n,{functionInfo:s,onChange:()=>{}}),y.jsxs("div",{className:"univer-flex univer-justify-end",children:[o&&y.jsx(B.Button,{variant:"primary",onClick:p,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.t("formula.moreFunctions.next")}),o&&y.jsx(B.Button,{onClick:p,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.t("formula.moreFunctions.prev")}),t&&!!e&&y.jsx(B.Button,{variant:"primary",onClick:h,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.t("formula.moreFunctions.confirm")})]})]})}function Gn(e){return{id:ce.id,title:"SUM",icon:"SumIcon",type:l.MenuItemType.BUTTON,params:{value:"SUM"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Zn(e){return{id:ce.id,title:"COUNT",icon:"CntIcon",type:l.MenuItemType.BUTTON,params:{value:"COUNT"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Xn(e){return{id:ce.id,title:"AVERAGE",icon:"AvgIcon",type:l.MenuItemType.BUTTON,params:{value:"AVERAGE"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Qn(e){return{id:ce.id,title:"MAX",icon:"MaxIcon",type:l.MenuItemType.BUTTON,params:{value:"MAX"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Jn(e){return{id:ce.id,title:"MIN",icon:"MinIcon",type:l.MenuItemType.BUTTON,params:{value:"MIN"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function er(e){return{id:He.id,title:"formula.insert.more",tooltip:"formula.insert.tooltip",type:l.MenuItemType.BUTTON,hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function tr(e){return e.get(a.IUniverInstanceService).getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).pipe(q.switchMap(o=>o&&e.get(l.IClipboardInterfaceService)?new q.Observable(s=>s.next(!e.get(l.IClipboardInterfaceService).supportClipboard)):q.of(!0)))}function nr(e){return{id:We.id,type:l.MenuItemType.BUTTON,title:"formula.operation.copyFormulaOnly",disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookCopyPermission],worksheetTypes:[x.WorksheetCopyPermission],rangeTypes:[x.RangeProtectionPermissionViewPoint]}),hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET)}}function rr(e){return{id:Ue.id,type:l.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:tr(e).pipe(q.combineLatestWith(N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint],worksheetTypes:[x.WorksheetSetCellValuePermission,x.WorksheetEditPermission]})),q.map(([t,n])=>t||n)),hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET)}}const or={[l.RibbonFormulasGroup.BASIC]:{[`${ce.id}.sum`]:{order:0,menuItemFactory:Gn},[`${ce.id}.count`]:{order:1,menuItemFactory:Zn},[`${ce.id}.average`]:{order:2,menuItemFactory:Xn},[`${ce.id}.max`]:{order:3,menuItemFactory:Qn},[`${ce.id}.min`]:{order:4,menuItemFactory:Jn}},[l.RibbonFormulasGroup.OTHERS]:{[He.id]:{order:0,menuItemFactory:er}},[N.COPY_SPECIAL_MENU_ID]:{[We.id]:{order:0,menuItemFactory:nr}},[N.PASTE_SPECIAL_MENU_ID]:{[Ue.id]:{order:4,menuItemFactory:rr}}},sr="meta_key_ctrl_And_Shift";function ir(e){return e.getContextValue(a.FOCUSING_DOC)&&e.getContextValue(a.FOCUSING_UNIVER_EDITOR)}const ze=[l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP,l.KeyCode.ARROW_LEFT,l.KeyCode.ARROW_RIGHT],cr=[...ze,l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ESC];function ar(){const e=[];for(const t of cr)e.push({id:Ee.id,binding:t,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t}});return e}function lr(){const e=[];for(const t of ze)e.push({id:Ee.id,binding:t|l.MetaKeys.SHIFT,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.SHIFT}});return e}function ur(){const e=[];for(const t of ze)e.push({id:Ee.id,binding:t|l.MetaKeys.CTRL_COMMAND,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.CTRL_COMMAND}});return e}function dr(){const e=[];for(const t of ze)e.push({id:Ee.id,binding:t|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:sr}});return e}const fr={id:it.id,binding:l.KeyCode.F4,preconditions:e=>N.whenFormulaEditorActivated(e)};function hr(){const e=[];for(const t of[l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP])e.push({id:Ee.id,binding:t,preconditions:n=>ir(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}const gr={id:ge.QuickSumCommand.id,binding:l.MetaKeys.ALT|l.KeyCode.EQUAL,preconditions:N.whenSheetEditorFocused,mac:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.ALT|l.KeyCode.EQUAL,description:"shortcut.sheets-formula-ui.quick-sum",group:"4_sheet-edit"};var Sr=Object.getOwnPropertyDescriptor,pr=(e,t,n,o)=>{for(var r=o>1?void 0:o?Sr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Re=(e,t)=>(n,o)=>t(n,o,e);let Ge=class extends a.Disposable{constructor(e,t,n,o,r,s,i){super(),this._injector=e,this._menuManagerService=t,this._commandService=n,this._shortcutService=o,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(or)}_registerCommands(){[We,Ue,ce,He,yt,mt,Ee,it].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_registerShortcuts(){[...ar(),...lr(),...ur(),...dr(),...hr(),gr,fr].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(N.SheetsUIPart.FORMULA_AUX,()=>l.connectInjector(Pn,this._injector))),this._componentManager.register(It,zn)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,[qe]))}};Ge=pr([Re(0,a.Inject(a.Injector)),Re(1,l.IMenuManagerService),Re(2,a.ICommandService),Re(3,l.IShortcutService),Re(4,l.IUIPartsService),Re(5,j.IRenderManagerService),Re(6,a.Inject(l.ComponentManager))],Ge);var vr=Object.getOwnPropertyDescriptor,mr=(e,t,n,o)=>{for(var r=o>1?void 0:o?vr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},lt=(e,t)=>(n,o)=>t(n,o,e);let Ze=class extends a.Disposable{constructor(e,t,n){super(),this._imageFormulaCellInterceptorController=e,this._renderManagerService=t,this._univerInstanceService=n,this._imageFormulaCellInterceptorController.registerRefreshRenderFunction(()=>{const o=this._univerInstanceService.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;const r=this._renderManagerService.getRenderById(o.getUnitId());if(!r)return;r.with(N.SheetSkeletonManagerService).reCalculate();const s=r.mainComponent;s&&s.makeDirty()})}};Ze=mr([lt(0,a.Inject(ge.ImageFormulaCellInterceptorController)),lt(1,j.IRenderManagerService),lt(2,a.IUniverInstanceService)],Ze);class ut{constructor(){Y(this,"_currentSelector$",new q.BehaviorSubject(null));Y(this,"currentSelector$",this._currentSelector$.asObservable())}showRangeSelectorDialog(t){const n=t.callback,o=new Promise(r=>{t.callback=s=>{r(s),n(s)}});return this._currentSelector$.next(t),o}}var Cr=Object.getOwnPropertyDescriptor,_r=(e,t,n,o)=>{for(var r=o>1?void 0:o?Cr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},De=(e,t)=>(n,o)=>t(n,o,e);$.RefSelectionsRenderService=class extends N.BaseSelectionRenderService{constructor(n,o,r,s,i,c,d){super(o,r,s,i,c);Y(this,"_workbookSelections");Y(this,"_eventDisposables");this._context=n,this._contextService=c,this._refSelectionsService=d,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Er(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(n){this._remainLastEnabled=n}setSkipLastEnabled(n){this._skipLastEnabled=n}clearLastSelection(){const n=this._selectionControls[this._selectionControls.length-1];n&&(n.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),a.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var n;(n=this._eventDisposables)==null||n.dispose(),this._eventDisposables=null}disableSelectionChanging(){this._disableSelectionChanging()}_initCanvasEventListeners(){const n=this._getSheetObject(),{spreadsheetRowHeader:o,spreadsheetColumnHeader:r,spreadsheet:s,spreadsheetLeftTopPlaceholder:i}=n,{scene:c}=this._context,d=new a.DisposableCollection;return d.add(s==null?void 0:s.onPointerDown$.subscribeEvent((f,S)=>{this.inRefSelectionMode()&&(this._onPointerDown(f,s.zIndex+1,a.RANGE_TYPE.NORMAL,this._getActiveViewport(f)),f.button!==2&&S.stopPropagation())})),d.add(o==null?void 0:o.onPointerDown$.subscribeEvent((f,S)=>{if(!this.inRefSelectionMode())return;const p=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:h}=N.getCoordByOffset(f.offsetX,f.offsetY,c,p);N.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.ROW)||(this._onPointerDown(f,(s.zIndex||1)+1,a.RANGE_TYPE.ROW,this._getActiveViewport(f),j.ScrollTimerType.Y),f.button!==2&&S.stopPropagation())})),d.add(r==null?void 0:r.onPointerDown$.subscribeEvent((f,S)=>{if(!this.inRefSelectionMode())return;const p=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:h}=N.getCoordByOffset(f.offsetX,f.offsetY,c,p);N.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.COLUMN)||(this._onPointerDown(f,(s.zIndex||1)+1,a.RANGE_TYPE.COLUMN,this._getActiveViewport(f),j.ScrollTimerType.X),f.button!==2&&S.stopPropagation())})),d.add(i==null?void 0:i.onPointerDown$.subscribeEvent((f,S)=>{if(this._reset(),!this.inRefSelectionMode())return;const p=this._sheetSkeletonManagerService.getCurrent().skeleton,h=N.getAllSelection(p);this._addSelectionControlByModelData(h),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const g=c.onPointerUp$.subscribeEvent(()=>{g.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});f.button!==2&&S.stopPropagation()})),d}_addSelectionControlByModelData(n){var c;const o=this._skeleton,r=(c=n.style)!=null?c:N.genNormalSelectionStyle(this._themeService),s=this._scene;return n.style=r,this.newSelectionControl(s,o,n)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(n=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(n||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(n=>{this._updateSelections(n,x.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(n=>{this._updateSelections(n,x.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(n=>{this._updateSelections(n,x.SelectionMoveType.MOVE_END)}))}_updateSelections(n,o){const s=this._context.unit.getActiveSheet().getSheetId();n.length!==0&&this._workbookSelections.setSelections(s,n.map(i=>x.convertSelectionDataToRange(i)),o)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(n=>{var c;if(!n)return;const{skeleton:o}=n,{scene:r}=this._context,s=r.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&((c=this._skeleton.worksheet)==null?void 0:c.getSheetId())!==o.worksheet.getSheetId()&&this._reset(),this._changeRuntime(o,r,s);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(n){const o=this._getSheetObject();return o==null?void 0:o.scene.getActiveViewportByCoord(j.Vector2.FromArray([n.offsetX,n.offsetY]))}_getSheetObject(){return N.getSheetObject(this._context.unit,this._context)}_onPointerDown(n,o=0,r=a.RANGE_TYPE.NORMAL,s,i=j.ScrollTimerType.ALL){var F;this._rangeType=r;const c=this._skeleton,d=this._scene;if(!d||!c)return;s&&(this._activeViewport=s);const{offsetX:f,offsetY:S}=n,p=d.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!p)return;const h=d.getCoordRelativeToViewport(j.Vector2.FromArray([f,S])),{x:g,y:u}=h;this._startViewportPosX=g,this._startViewportPosY=u;const m=d.getScrollXYInfoByViewport(h),{scaleX:C,scaleY:_}=d.getAncestorScale(),I=this._skeleton.getCellByOffset(g,u,C,_,m);if(!I)return;switch(r){case a.RANGE_TYPE.NORMAL:break;case a.RANGE_TYPE.ROW:I.startColumn=0,I.endColumn=this._skeleton.getColumnCount()-1;break;case a.RANGE_TYPE.COLUMN:I.startRow=0,I.endRow=this._skeleton.getRowCount()-1;break;case a.RANGE_TYPE.ALL:I.startRow=0,I.startColumn=0,I.endRow=this._skeleton.getRowCount()-1,I.endColumn=this._skeleton.getColumnCount()-1}let R={range:I,primary:I,style:null};(I.isMerged||I.isMergedMainCell)&&(R={range:{...I,startRow:I.startRow,endRow:I.startRow,startColumn:I.startColumn,endColumn:I.startColumn},primary:{...I,actualRow:I.startRow,actualColumn:I.startColumn,startRow:I.startRow,endRow:I.startRow,startColumn:I.startColumn,endColumn:I.startColumn},style:null}),R.range.rangeType=r;const D=N.attachSelectionWithCoord(R,this._skeleton);this._startRangeWhenPointerDown={...D.rangeWithCoord};const v={...D.rangeWithCoord,rangeType:r};let M=this.getActiveSelectionControl();const w=this.getSelectionControls();for(const A of w){if(n.button===2&&a.Rectangle.contains(A.model,v)){M=A;return}if(A.model.isEqual(v)){M=A;break}}this._checkClearPreviousControls(n);const W=M==null?void 0:M.model.currentCell,U=n.shiftKey&&W,P=this._remainLastEnabled&&!n.ctrlKey&&!n.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;U&&W?this._makeSelectionByTwoCells(W,v,c,r,M):P&&M?M.updateRangeBySelectionWithCoord(D):M=this.newSelectionControl(d,c,R);for(let A=0;A<this.getSelectionControls().length-1;A++)this.getSelectionControls()[A].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),d.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(F=d.getTransformer())==null||F.clearSelectedObjects(),this._setupPointerMoveListener(p,M,r,i,g,u),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=d.onPointerUp$.subscribeEvent(()=>{var A;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(A=this._escapeShortcutDisposable)==null||A.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(n,o,r){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:c}=o,d=new N.SelectionControl(n,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:c}),f=N.attachSelectionWithCoord(r,o);return d.updateRangeBySelectionWithCoord(f),this._selectionControls.push(d),d.setControlExtension({skeleton:o,scene:n,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),d}},$.RefSelectionsRenderService=_r([De(1,a.Inject(a.Injector)),De(2,a.Inject(a.ThemeService)),De(3,l.IShortcutService),De(4,a.Inject(N.SheetSkeletonManagerService)),De(5,a.IContextService),De(6,x.IRefSelectionsService)],$.RefSelectionsRenderService);function Er(e){const t=N.genNormalSelectionStyle(e);return t.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},t}const dt=(e,t,n=!0)=>{let o=-1;return e.reduce((r,s,i)=>{if(r.isFinish)return r;const c=r.currentIndex;if(typeof s!="string")r.currentIndex+=s.token.length;else{const d=s.length;r.currentIndex+=d}return(n?r.currentIndex===t:t>c&&t<=r.currentIndex)&&(o=i,r.isFinish=!0),r},{currentIndex:0,isFinish:!1}),o},Ft=(e,t)=>{const n=e[t];let o=-1;if(!n||typeof n=="string"||n.nodeType!==T.sequenceNodeType.REFERENCE)return-1;for(let r=0;r<=t;r++){const s=e[r];typeof s!="string"&&s.nodeType===T.sequenceNodeType.REFERENCE&&o++}return o},Ir=(e,t=100)=>{E.useEffect(()=>{let n=null;const o=()=>{n===null&&(n=window.setTimeout(()=>{e(),n=null},t))};return window.addEventListener("scroll",o),window.addEventListener("resize",o),()=>{n!==null&&clearTimeout(n),window.removeEventListener("scroll",o),window.removeEventListener("resize",o)}},[e,t])};function Wt(e,t,n){const o=l.useDependency(Q.IEditorService),r=E.useMemo(()=>new q.BehaviorSubject({left:-999,top:-999,right:-999,bottom:-999}),[]),s=l.useDependency(l.ISidebarService),i=l.useDependency(a.IUniverInstanceService),c=l.useEvent(()=>{var R;const d=o.getEditor(e);if(!d)return;const f=d.getBoundingClientRect(),{marginTop:S=0,marginBottom:p=0}=d.getDocumentData().documentStyle,h=d.getSkeleton();if(!h)return;const g=(R=h.getSkeletonData())==null?void 0:R.pages[0].height;let{left:u,top:m,right:C,bottom:_}=f;m=m+S,_=g?m+g:_-p;const I=r.getValue();if(!(I.left===u&&I.top===m&&I.right===C&&I.bottom===_))return r.next({left:u-1,right:C+1,top:m-1,bottom:_+1}),f});return E.useEffect(()=>{t&&c()},[e,o,i.unitAdded$,c,t,...n!=null?n:[]]),Ir(c),E.useEffect(()=>{const d=s.scrollEvent$.pipe(q.throttleTime(100)).subscribe(c);return()=>{d.unsubscribe()}},[]),[r,c]}const Te=e=>{const t=E.useRef(e);return t.current=e,t},yr=(e,t,n)=>{const o=l.useDependency(Ve),r=l.useDependency(ge.IDescriptionService),s=l.useDependency(T.LexerTreeBuilder),[i,c]=E.useState(),[d,f]=E.useState(-1),[S,p]=E.useState(!0),h=Te(S),g=E.useRef(t);g.current=t;const u=()=>{c(void 0),f(-1),p(!1)};return E.useEffect(()=>{const m=s.sequenceNodesBuilder(t.slice(1));o.setSequenceNodes(m!=null?m:[])},[t]),E.useEffect(()=>{if(n&&e){const m=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(_=>{if(_.textRanges.length===1){const[I]=_.textRanges;if(I.collapsed&&h.current){const{startOffset:R}=I,D=o.getCurrentSequenceNodeIndex(R-2),v=o.getCurrentSequenceNodeByIndex(D),M=o.getCurrentSequenceNodeByIndex(D+1);if(v)if(typeof v!="string"&&v.nodeType===3&&!r.hasDefinedNameDescription(v.token.trim())&&M===T.matchToken.OPEN_BRACKET){const w=r.getFunctionInfo(v.token);c(w),f(-1);return}else{const w=s.getFunctionAndParameter(`${g.current}A`,R-1);if(w){const{functionName:W,paramIndex:U}=w,P=r.getFunctionInfo(W);c(P),f(U);return}}}}c(void 0),f(-1)}),C=n.selectionChange$.pipe(q.filter(_=>_.textRanges.length===1),q.map(_=>_.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{p(!0)});return()=>{m.unsubscribe(),C.unsubscribe()}}},[n,e]),E.useEffect(()=>{e||u()},[e]),{functionInfo:i,paramIndex:d,reset:u}},Rr=({onClick:e})=>y.jsx("div",{className:"univer-z-[15] univer-box-border univer-h-[18px] univer-cursor-pointer univer-overflow-visible univer-whitespace-nowrap univer-rounded-l univer-border univer-border-r-0 univer-border-gray-600 univer-bg-primary-600 univer-p-0.5 univer-text-xs univer-font-bold univer-leading-[13px] univer-text-white",onClick:e,children:"?"}),ft=({className:e,title:t,value:n})=>y.jsxs("div",{className:"univer-my-2",children:[y.jsx("div",{className:B.clsx("univer-mb-2 univer-text-sm univer-font-medium univer-text-gray-900 dark:!univer-text-white",e),children:t}),y.jsx("div",{className:"univer-whitespace-pre-wrap univer-break-words univer-text-xs univer-text-gray-500",children:n})]}),Tr=e=>{const{prefix:t,value:n,active:o,onClick:r}=e;return y.jsxs("div",{children:[y.jsxs("span",{children:[t,"("]}),n&&n.map((s,i)=>y.jsxs("span",{children:[y.jsx("span",{className:o===i?"univer-text-primary-500":"",onClick:()=>r(i),children:Nt(s)}),i===n.length-1?"":","]},s.name)),")"]})},Ut=()=>{};function br(e){const{onParamsSwitch:t=Ut,onClose:n=Ut,isFocus:o,editor:r,formulaText:s}=e,{functionInfo:i,paramIndex:c,reset:d}=yr(o,s,r),f=l.useDependency(N.IEditorBridgeService),S=!l.useObservable(f.helpFunctionVisible$),[p,h]=E.useState(!0),g=l.useDependency(a.LocaleService),u=g.t("formula.prompt.required"),m=g.t("formula.prompt.optional"),C=r.getEditorId(),[_]=Wt(C,!!i,[i,c]);function I(v){t&&t(v)}const R=l.useEvent(v=>{f.helpFunctionVisible$.next(!v)}),D=()=>{R(!0),n()};return i?S?y.jsx(l.RectPopup,{portal:!0,anchorRect$:_,direction:"left-center",children:y.jsx(Rr,{onClick:()=>R(!1)})},"hidden"):y.jsx(l.RectPopup,{portal:!0,onClickOutside:()=>d(),anchorRect$:_,direction:"vertical",children:y.jsxs("div",{className:B.clsx("univer-m-0 univer-box-border univer-w-[250px] univer-select-none univer-list-none univer-rounded-lg univer-bg-white univer-leading-5 univer-shadow-md univer-outline-none dark:!univer-bg-gray-900",B.borderClassName),children:[y.jsxs("div",{className:B.clsx("univer-wrap-anywhere univer-box-border univer-flex univer-items-center univer-justify-between univer-px-4 univer-py-3 univer-text-xs univer-font-medium univer-text-gray-900 dark:!univer-text-white",B.borderTopClassName),children:[y.jsx(Tr,{prefix:i.functionName,value:i.functionParameter,active:c,onClick:I}),y.jsxs("div",{className:"univer-flex",children:[y.jsx("div",{className:"univer-ml-2 univer-flex univer-h-6 univer-w-6 univer-cursor-pointer univer-items-center univer-justify-center univer-rounded univer-bg-transparent univer-p-0 univer-text-xs univer-text-gray-500 univer-outline-none univer-transition-colors hover:univer-bg-gray-200 dark:hover:!univer-bg-gray-600",style:{transform:p?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!p),children:y.jsx(Lt,{})}),y.jsx("div",{className:"univer-ml-2 univer-flex univer-h-6 univer-w-6 univer-cursor-pointer univer-items-center univer-justify-center univer-rounded univer-bg-transparent univer-p-0 univer-text-xs univer-text-gray-600 univer-outline-none univer-transition-colors hover:univer-bg-gray-300 dark:!univer-text-gray-200 dark:hover:!univer-bg-gray-600",onClick:D,children:y.jsx(At,{})})]})]}),y.jsx("div",{className:B.clsx("univer-box-border univer-max-h-[350px] univer-overflow-y-auto univer-px-4 univer-pb-3 univer-pt-0",B.scrollbarClassName),style:{height:p?"unset":0,padding:p?"revert-layer":0},children:y.jsxs("div",{className:"univer-mt-3",children:[y.jsx(ft,{title:g.t("formula.prompt.helpExample"),value:`${i.functionName}(${i.functionParameter.map(v=>v.example).join(",")})`}),y.jsx(ft,{title:g.t("formula.prompt.helpAbstract"),value:i.description}),i&&i.functionParameter&&i.functionParameter.map((v,M)=>y.jsx(ft,{className:c===M?"univer-text-primary-500":"",title:v.name,value:`${v.require?u:m} ${v.detail}`},M))]})})]})},"show"):null}const Mr=e=>{const t=l.useDependency(Q.IEditorService);return l.useEvent(o=>{var r,s;if(e){t.focus(e.getEditorId());const i=[...e.getSelectionRanges()];if(a.Tools.isDefine(o))e.setSelectionRanges([{startOffset:o,endOffset:o}]);else if(!i.length&&!e.docSelectionRenderService.isOnPointerEvent){const c=(s=(r=e.getDocumentData().body)==null?void 0:r.dataStream)!=null?s:`\r
2
- `,d=Math.max(c.length-2,0);e.setSelectionRanges([{startOffset:d,endOffset:d}])}else e.setSelectionRanges(i)}})};function Or(e){var r,s;const n=e.get(a.IUniverInstanceService).getCurrentUniverDocInstance();return n!=null&&n.getBody()?{dataStream:(s=(r=n.getBody())==null?void 0:r.dataStream)!=null?s:"",offset:0}:void 0}var Se=(e=>(e[e.NOT_SELECT=0]="NOT_SELECT",e[e.NEED_ADD=1]="NEED_ADD",e[e.CAN_EDIT=2]="CAN_EDIT",e[e.EDIT_OTHER_SHEET_REFERENCE=3]="EDIT_OTHER_SHEET_REFERENCE",e[e.EDIT_OTHER_WORKBOOK_REFERENCE=4]="EDIT_OTHER_WORKBOOK_REFERENCE",e))(Se||{});function Nr(e){var w;const{editorId:t,isFocus:n,disableOnClick:o,unitId:r,subUnitId:s}=e,i=l.useDependency(j.IRenderManagerService),c=l.useDependency(a.IUniverInstanceService),d=i.getRenderById(r),f=i.getRenderById(t),S=f==null?void 0:f.with(Q.DocSelectionRenderService),p=l.useDependency(pt.DocSelectionManagerService),h=l.useDependency(a.Injector),[g,u]=E.useState(0),m=l.useDependency(T.LexerTreeBuilder),C=E.useRef(!0),_=d==null?void 0:d.with($.RefSelectionsRenderService),I=Te(g),R=c.getUnit(r,a.UniverInstanceType.UNIVER_SHEET),D=R==null?void 0:R.getSheetBySheetId(s),v=l.useEvent(W=>{_&&_.setSkipLastEnabled(W===1||W===3||W===4),I.current=W,u(W)}),M=l.useEvent(()=>{var oe,se,ae;const W=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!W)return;const U=W.getActiveSheet(),P=S==null?void 0:S.getActiveTextRange(),F=P!=null&&P.collapsed?P.startOffset:-1,A=Or(h);if(!A)return;const O=(oe=A==null?void 0:A.dataStream)==null?void 0:oe.slice(0,-2),L=((se=m.sequenceNodesBuilder(O))!=null?se:[]).map(G=>typeof G=="object"?G.nodeType===T.sequenceNodeType.REFERENCE?{...G,range:T.deserializeRangeWithSheetWithCache(G.token)}:{...G,range:void 0}:G),b=O[F-1],k=O[F],V=L.find(G=>typeof G=="object"&&G.nodeType===T.sequenceNodeType.REFERENCE&&F===G.endIndex+2),H=b&&T.matchRefDrawToken(b)&&(!k||T.isFormulaLexerToken(k)&&k!==T.matchToken.OPEN_BRACKET),K=!!V;if((O==null?void 0:O.substring(0,1))==="="&&(H||K))if(K){if(C.current)return;const{sheetName:G,unitId:J}=V.range,ke=(ae=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:ae.getUnitId();J&&J!==ke?v(4):!G&&U.getSheetId()===(D==null?void 0:D.getSheetId())||G===U.getName()?v(2):v(3)}else C.current=!1,v(1);else v(0)});return E.useEffect(()=>{const W=p.textSelection$.pipe(q.filter(U=>U.unitId===t)).subscribe(()=>{M()});return()=>W.unsubscribe()},[M,p.textSelection$,t]),E.useEffect(()=>{n||(v(0),C.current=!0)},[n,v]),E.useEffect(()=>{var U;if(!o)return;const W=(U=f==null?void 0:f.mainComponent)==null?void 0:U.onPointerDown$.subscribeEvent(()=>{v(0),C.current=!0});return()=>W==null?void 0:W.unsubscribe()},[o,(w=f==null?void 0:f.mainComponent)==null?void 0:w.onPointerDown$,v]),E.useEffect(()=>{if(!n)return;const W=R==null?void 0:R.activeSheet$.subscribe(()=>{M()}),U=c.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>{M()});return()=>{W==null||W.unsubscribe(),U==null||U.unsubscribe()}},[M,n,R==null?void 0:R.activeSheet$,c.getCurrentTypeOfUnit$]),{isSelecting:g,isSelectingRef:I}}const Dr=()=>{const e=l.useDependency(T.LexerTreeBuilder);return E.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function kr(e,t,n){const o=new a.ColorKit(t).setAlpha(.05).toRgbString();return{id:n,strokeWidth:1,stroke:t,fill:o,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:e.getColorFromTheme("white")}}function Vt(e){var R,D,v;const{unitId:t,subUnitId:n,currentWorkbook:o,refSelections:r,editor:s,refSelectionsService:i,refSelectionsRenderService:c,sheetSkeletonManagerService:d,themeService:f,univerInstanceService:S}=e,p=o.getUnitId(),h=S.getUnit(t,a.UniverInstanceType.UNIVER_SHEET),g=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!g){i.setSelections(u);return}const m=g.getSheetId(),C=M=>{var w;return(w=h==null?void 0:h.getSheetBySheetName(M))==null?void 0:w.getSheetId()};if(!((R=d==null?void 0:d.getWorksheetSkeleton(m))==null?void 0:R.skeleton))return;const I=[];for(let M=0,w=r.length;M<w;M++){const W=r[M],{themeColor:U,token:P,refIndex:F,endIndex:A}=W,O=T.deserializeRangeWithSheet(P),{unitId:L,sheetName:b,range:k}=O,V=C(b);if(!V&&b||p!==t&&L!==p||L&&L!==p||V&&V!==m||!V&&m!==n)continue;const H=x.setEndForRange(k,g.getRowCount(),g.getColumnCount());H.unitId=t,H.sheetId=m,u.push({range:H,primary:null,style:kr(f,U,F.toString())}),I.push(A)}if(s){const M=(v=(D=s.getSelectionRanges())==null?void 0:D[0])==null?void 0:v.startOffset,w=I.findIndex(W=>W+2===M);w!==-1?c==null||c.setActiveSelectionIndex(w):c==null||c.resetActiveSelectionIndex()}return u}function wr(e,t){const n=l.useDependency(a.IUniverInstanceService),o=l.useDependency(a.ThemeService),r=l.useDependency(x.IRefSelectionsService),s=l.useDependency(j.IRenderManagerService),i=l.useObservable(E.useMemo(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[n])),c=i?s.getRenderById(i.getUnitId()):null,d=c==null?void 0:c.with($.RefSelectionsRenderService),f=c==null?void 0:c.with(N.SheetSkeletonManagerService),S=l.useEvent((p,h)=>{const g=n.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!g||d!=null&&d.selectionMoving)return;const u=Vt({unitId:e,subUnitId:t,currentWorkbook:g,refSelections:p,editor:h,refSelectionsService:r,refSelectionsRenderService:d,sheetSkeletonManagerService:f,themeService:o,univerInstanceService:n});if(!u)return;((d==null?void 0:d.getSelectionControls())||[]).length===u.length?d==null||d.resetSelectionsByModelData(u):r.setSelections(u)});return E.useEffect(()=>()=>{d==null||d.resetActiveSelectionIndex()},[d]),S}function Ht(e=""){const t=l.useDependency(ge.IDescriptionService),n=Ar(),o=l.useDependency(a.ICommandService),r=E.useMemo(()=>e.length,[e]);return l.useEvent((i,c,d=!0,f)=>{const S=i.getDocumentData(),p=i.getEditorId();if(!S)return[];const h=S.body;if(!h)return[];const g=h.dataStream.slice(0,h.dataStream.length-2),u={dataStream:"",...S.body};if(!g.startsWith(e))return[];if(c==null||c.length===0)return u.textRuns=[],o.syncExecuteCommand(Q.ReplaceTextRunsCommand.id,{unitId:p,body:a.getBodySlice(u,0,u.dataStream.length-2)}),[];{const{textRuns:m,refSelections:C}=xr(t,n,c);r&&m.forEach(R=>{R.ed=R.ed+r,R.st=R.st+r}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},...m];const _=c.reduce((R,D)=>typeof D=="string"?`${R}${D}`:`${R}${D.token}`,"");u.dataStream=`${e}${_}\r
3
- `;let I;if(d){I=i.getSelectionRanges();const R=u.dataStream.length-2+r;I.forEach(D=>{D.startOffset=Math.max(0,Math.min(D.startOffset,R)),D.endOffset=Math.max(0,Math.min(D.endOffset,R))})}return o.syncExecuteCommand(Q.ReplaceTextRunsCommand.id,{unitId:p,body:a.getBodySlice(u,0,u.dataStream.length-2),textRanges:f!=null?f:I}),C}})}function Ar(){const e=l.useDependency(a.ThemeService),t=e.getCurrentTheme();return E.useMemo(()=>{const o=[e.getColorFromTheme("loop-color.1"),e.getColorFromTheme("loop-color.2"),e.getColorFromTheme("loop-color.3"),e.getColorFromTheme("loop-color.4"),e.getColorFromTheme("loop-color.5"),e.getColorFromTheme("loop-color.6"),e.getColorFromTheme("loop-color.7"),e.getColorFromTheme("loop-color.8"),e.getColorFromTheme("loop-color.9"),e.getColorFromTheme("loop-color.10"),e.getColorFromTheme("loop-color.11"),e.getColorFromTheme("loop-color.12")].map(c=>e.isValidThemeColor(c)?e.getColorFromTheme(c):c),r=e.getColorFromTheme("blue.700"),s=e.getColorFromTheme("jiqing.800"),i=e.getColorFromTheme("black");return{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}},[t])}function xr(e,t,n){const{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}=t,c=[],d=[],f=new Map;let S=0;for(let p=0,h=n.length;p<h;p++){const g=n[p];if(typeof g=="string"){const R=c[c.length-1],D=R?R.ed:0,v=D+g.length;c.push({st:D,ed:v,ts:{cl:{rgb:i},fs:11}});continue}if(e.hasDefinedNameDescription(g.token.trim())){c.push({st:g.startIndex,ed:g.endIndex+1,ts:{cl:{rgb:i},fs:11}});continue}const{startIndex:u,endIndex:m,nodeType:C,token:_}=g;let I="";if(C===T.sequenceNodeType.REFERENCE){if(f.has(_))I=f.get(_);else{const R=S%o.length;I=o[R],f.set(_,I),S++}d.push({refIndex:p,themeColor:I,token:_,startIndex:g.startIndex,endIndex:g.endIndex,index:d.length})}else C===T.sequenceNodeType.NUMBER?I=r:(C===T.sequenceNodeType.STRING||C===T.sequenceNodeType.ARRAY)&&(I=s);I&&I.length>0?c.push({st:u,ed:m+1,ts:{cl:{rgb:I},fs:11}}):c.push({st:u,ed:m+1,ts:{cl:{rgb:i},fs:11}})}return{textRuns:c,refSelections:d}}const Pr=(e,t,n,o)=>{const r=l.useDependency(a.ICommandService),s=l.useDependency(l.IShortcutService),i=E.useRef(t);i.current=t;const c=E.useRef(o);c.current=o,E.useEffect(()=>{if(!n||!e)return;const f=`sheet.formula-embedding-editor.${n.getEditorId()}`,S=new a.DisposableCollection,p=(u,m)=>{if(c.current){c.current(u,m);return}let C=a.Direction.LEFT;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),m===l.MetaKeys.SHIFT?r.executeCommand(Q.MoveSelectionOperation.id,{direction:C}):r.executeCommand(Q.MoveCursorOperation.id,{direction:C})},h=(u,m)=>{let C=a.Direction.DOWN;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_LEFT?C=a.Direction.LEFT:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),i.current?m===l.MetaKeys.CTRL_COMMAND?r.executeCommand(N.MoveSelectionCommand.id,{direction:C,jumpOver:N.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:i.current===Se.NEED_ADD||i.current===Se.EDIT_OTHER_SHEET_REFERENCE}):m===l.MetaKeys.SHIFT?r.executeCommand(N.ExpandSelectionCommand.id,{direction:C,extra:"formula-editor"}):m===(l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT)?r.executeCommand(N.ExpandSelectionCommand.id,{direction:C,jumpOver:N.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand(N.MoveSelectionCommand.id,{direction:C,extra:"formula-editor",fromCurrentSelection:i.current===Se.NEED_ADD||i.current===Se.EDIT_OTHER_SHEET_REFERENCE}):p(u,m)};return S.add(r.registerCommand({id:f,type:a.CommandType.OPERATION,handler(u,m){const{keyCode:C,metaKey:_}=m;h(C,_)}})),[{keyCode:l.KeyCode.ARROW_DOWN},{keyCode:l.KeyCode.ARROW_LEFT},{keyCode:l.KeyCode.ARROW_RIGHT},{keyCode:l.KeyCode.ARROW_UP},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT}].map(({keyCode:u,metaKey:m})=>({id:f,binding:m?u|m:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:u,metaKey:m}})).forEach(u=>{S.add(s.registerShortcut(u))}),()=>{S.dispose()}},[r,n,e,s])},Lr=(e,t,n,o,r=!0)=>{var g;const s=l.useDependency(j.IRenderManagerService),i=l.useDependency(a.IContextService),c=l.useDependency(l.IContextMenuService),d=l.useDependency(x.IRefSelectionsService),f=l.useDependency(a.IUniverInstanceService),S=l.useObservable(E.useMemo(()=>f.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[f])),p=s.getRenderById((g=S==null?void 0:S.getUnitId())!=null?g:""),h=p==null?void 0:p.with($.RefSelectionsRenderService);E.useLayoutEffect(()=>{if(e)return i.setContextValue(a.EDITOR_ACTIVATED,!0),r&&c.disable(),()=>{const u=f.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_DOC);(u==null?void 0:u.getUnitId())===o&&i.setContextValue(a.EDITOR_ACTIVATED,!1),r&&c.enable(),d.clear()}},[i,e,d,r,o]),E.useLayoutEffect(()=>{if(e&&t){const u=h==null?void 0:h.enableSelectionChanging();return i.setContextValue(x.REF_SELECTIONS_ENABLED,!0),()=>{i.setContextValue(x.REF_SELECTIONS_ENABLED,!1),u==null||u.dispose()}}},[i,e,h,t]),E.useEffect(()=>{e&&(h==null||h.setSkipLastEnabled(!1))},[e,h])},$r=(e,t,n)=>{const o=l.useDependency(a.IUniverInstanceService),r=l.useDependency(x.SheetsSelectionsService);return E.useCallback(()=>{if(e){const i=[...r.getWorkbookSelections(t).getSelectionsOfWorksheet(n)],c=o.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),d=c==null?void 0:c.getActiveSheet();(c==null?void 0:c.getUnitId())!==t&&o.setCurrentUnitForType(t),d&&d.getSheetId()===n&&r.setSelections(i)}},[e,r,n,t,o])},Fr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),ht=e=>e.map(t=>typeof t=="string"?t:t.token).join(""),Xe=(e,t=!1,n="",o=!1)=>!t&&!o?e.map(r=>T.serializeRange(r.range)):e.map(r=>o?T.serializeRangeToRefString(r):r.sheetName!==""&&r.sheetName!==n?T.serializeRangeWithSheet(r.sheetName,r.range):T.serializeRange(r.range)),Wr=e=>{var S,p,h;const{editor:t,lexerTreeBuilder:n}=e,o=t==null?void 0:t.getSelectionRanges();if((o==null?void 0:o.length)!==1)return;const s=o[0].startOffset-1,i=((p=(S=t==null?void 0:t.getDocumentData().body)==null?void 0:S.dataStream)!=null?p:`\r
4
- `).slice(0,-2),c=(h=n.sequenceNodesBuilder(i.slice(1)))!=null?h:[],d=dt(c,s,!1),f=Ft(c,d);return{nodeIndex:d,updatingRefIndex:f,sequenceNodes:c,offset:s}},Ur=(()=>{}),Vr=(e,t,n,o,r,s,i,c,d,f=Ur)=>{var F;const S=l.useDependency(j.IRenderManagerService),p=l.useDependency(a.IUniverInstanceService),h=l.useDependency(a.ICommandService),g=l.useDependency(pt.DocSelectionManagerService),u=l.useDependency(a.ThemeService),m=l.useDependency(T.LexerTreeBuilder),C=p.getUnit(o),_=l.useEvent((A,O)=>{var L,b,k;return(k=(b=(L=p.getUnit(A))==null?void 0:L.getSheetBySheetId(O))==null?void 0:b.getName())!=null?k:""}),I=E.useMemo(()=>_(o,r),[_,r,o]),R=l.useObservable(C==null?void 0:C.activeSheet$),D=Te({activeSheet:R,sheetName:I}),v=l.useObservable(E.useMemo(()=>p.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[p])),M=S.getRenderById((F=v==null?void 0:v.getUnitId())!=null?F:""),w=M==null?void 0:M.with($.RefSelectionsRenderService),W=M==null?void 0:M.with(N.SheetSkeletonManagerService),U=l.useDependency(x.IRefSelectionsService),P=l.useEvent((A,O,L)=>{var oe,se,ae,G,J,ke,we,Je,pe,et;const b=Wr({editor:d,lexerTreeBuilder:m});if(!b)return;const{nodeIndex:k,updatingRefIndex:V,sequenceNodes:H,offset:K}=b;if(n.current===Se.NEED_ADD)if(K!==0){if(k===-1&&H.length)return;const z=A[A.length-1],ee=H.splice(k+1),le=(oe=z.sheetId)!=null?oe:r,te={range:z,unitId:(se=z.unitId)!=null?se:v.getUnitId(),sheetName:_((ae=z.unitId)!=null?ae:v.getUnitId(),le)},ie=le!==r,ue=(v==null?void 0:v.getUnitId())!==o,fe=Xe([te],i&&(ie||ue),I,ue);H.push({token:fe[0],nodeType:T.sequenceNodeType.REFERENCE});const be=[...H,...ee],Me=ht(be);f(Me,Fr(H),O)}else{const z=A[A.length-1],ee=(G=z.sheetId)!=null?G:r,le={range:z,unitId:(J=z.unitId)!=null?J:v.getUnitId(),sheetName:_((ke=z.unitId)!=null?ke:v.getUnitId(),ee)},te=ee!==r,ie=(v==null?void 0:v.getUnitId())!==o,ue=Xe([le],i&&(te||ie),I,ie);H.unshift({token:ue[0],nodeType:T.sequenceNodeType.REFERENCE});const fe=ht(H);f(fe,ue[0].length,O)}else if(n.current===Se.EDIT_OTHER_SHEET_REFERENCE||n.current===Se.EDIT_OTHER_WORKBOOK_REFERENCE){const z=A.pop();if(!z)return;const ee=H[k];if(typeof ee=="object"&&ee.nodeType===T.sequenceNodeType.REFERENCE){const le=ee.token;(v==null?void 0:v.getUnitId())!==o?ee.token=T.serializeRangeWithSpreadsheet((we=v==null?void 0:v.getUnitId())!=null?we:"",I,z):ee.token=I===(R==null?void 0:R.getName())?T.serializeRange(z):T.serializeRangeWithSheet(R.getName(),z);const ie=K+(ee.token.length-le.length);f(T.generateStringWithSequence(H),ie,O)}}else{const z=[...A];if(!L&&V!==-1){const Z=z.pop();Z&&z.splice(V,0,Z)}let ee=0;const le=H.map(Z=>{var he,me,Ae,Oe;if(typeof Z=="string")return Z;if(Z.nodeType===T.sequenceNodeType.REFERENCE){const de=T.deserializeRangeWithSheet(Z.token);if(de.sheetName||(de.sheetName=I),(de.unitId||o)!==(v==null?void 0:v.getUnitId())||i&&((he=D.current.activeSheet)==null?void 0:he.getName())!==de.sheetName)return Z.token;const ne=z[ee];if(ee++,!ne)return"";const Fe=(me=ne.sheetId)!=null?me:r,St={range:ne,unitId:(Ae=ne.unitId)!=null?Ae:v.getUnitId(),sheetName:_((Oe=ne.unitId)!=null?Oe:v.getUnitId(),Fe)},tt=(v==null?void 0:v.getUnitId())!==o;return Xe([St],i&&(Fe!==r||tt),I,tt)[0]}return Z.token});let te="",ie;le.forEach((Z,he)=>{te+=Z,he===k&&(ie=te.length)});const ue=[];for(let Z=ee;Z<=A.length-1;Z++){const he=A[Z],me=(Je=he.sheetId)!=null?Je:r,Ae={range:he,unitId:(pe=he.unitId)!=null?pe:v.getUnitId(),sheetName:_((et=he.unitId)!=null?et:v.getUnitId(),me)},Oe=(v==null?void 0:v.getUnitId())!==o,ne=Xe([Ae],i&&(me!==r||Oe),I,Oe);ue.push(ne[0])}const fe=H[H.length-1],be=fe&&(typeof fe=="string"?!1:fe.nodeType===T.sequenceNodeType.REFERENCE),Me=`${te}${ue.length&&be?",":""}${ue.join(",")}`;f(Me,!ue.length&&ie?ie:Me.length,O)}});E.useEffect(()=>{if(w&&e){let A=!0,O=0;const L=(k,V)=>{if(A){A=!1,O=k.length;return}const H=k.length>O;V&&(O=k.length),P(k.map(K=>K.rangeWithCoord),V,H)},b=new a.DisposableCollection;return b.add(w.selectionMoving$.subscribe(k=>{L(k,!1)})),b.add(w.selectionMoveEnd$.subscribe(k=>{L(k,!0)})),()=>{b.dispose()}}},[e,P,w]),E.useEffect(()=>{if(t&&w&&d){const A=new a.DisposableCollection,O=()=>{A.dispose(),w.getSelectionControls().forEach((k,V)=>{A.add(k.selectionScaling$.subscribe(H=>{const K=w.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=K[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,K[V]=H,P(K,!1)})),A.add(k.selectionMoving$.subscribe(H=>{const K=w.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=K[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,K[V]=H,P(K,!0)}))})},L=q.merge(d.input$,U.selectionSet$,w.selectionMoveEnd$).pipe(tn.debounceTime(50)).subscribe(()=>{O()});return()=>{L.unsubscribe(),A.dispose()}}},[d,t,P,w,U.selectionSet$]),w==null||w.getSelectionDataWithStyle(),E.useEffect(()=>{if(c){const A=h.onCommandExecuted(O=>{var b;if(O.id!==x.SetSelectionsOperation.id)return;const L=O.params;if(L.extra==="formula-editor"&&L.selections.length){const k=L.selections[L.selections.length-1];if(k){const V=n.current===Se.NEED_ADD,H=((b=w==null?void 0:w.getSelectionDataWithStyle())!=null?b:[]).map(K=>K.rangeWithCoord);V?H.push(k.range):H[H.length-1]=k.range,P(H,!0)}}});return()=>{A.dispose()}}},[h,d,n,m,c,P,w]),E.useEffect(()=>{if(!d)return;const A=g.textSelection$.subscribe(O=>{O.unitId===d.getEditorId()&&Vt({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:U,refSelectionsRenderService:w,sheetSkeletonManagerService:W,themeService:u,univerInstanceService:p,currentWorkbook:v})});return()=>A.unsubscribe()},[g.textSelection$,d,s,w,U,W,r,u,o,p])},Hr=(e,t,n,o,r,s)=>{const i=l.useDependency(a.ICommandService),c=l.useDependency(Q.IEditorService),f=l.useDependency(j.IRenderManagerService).getRenderById(t),S=l.useDependency(a.IUniverInstanceService),p=f==null?void 0:f.with($.RefSelectionsRenderService);E.useEffect(()=>{if(e&&p)if(n){const h=()=>{const m=p.getSelectionControls().length;for(let C=1;C<=m;C++)p.clearLastSelection();return setTimeout(()=>{s()},30)},g=i.onCommandExecuted(m=>{m.id===x.SetWorksheetActiveOperation.id&&h()}),u=S.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(m=>{h()});return()=>{g.dispose(),u.unsubscribe()}}else{const h=i.beforeCommandExecuted(g=>{if(g.id===x.SetWorksheetActiveOperation.id){o(!1),r(),s();const u=c.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);u==null||u.focus()}});return()=>{h.dispose()}}},[e,p])},Br=(e,t,n)=>{const o=l.useDependency(T.LexerTreeBuilder),r=E.useRef(!0);E.useEffect(()=>{if(e){const s=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(s)}}},[e]),E.useEffect(()=>{if(!r.current&&t){const s=o.checkIfAddBracket(n);t(s===0&&n.startsWith(T.operatorToken.EQUALS),`${n}`)}},[n,t])},Kr=(e,t=[],n)=>{const o=l.useDependency(ge.IDescriptionService),[r,s]=E.useState([]),[i,c]=E.useState(""),d=E.useRef(-1),f=Te({nodes:t}),S=()=>{s([]),c(""),d.current=-1};return E.useEffect(()=>{if(n&&e){const h=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const g=n.getSelectionRanges();if(g.length===1){const u=f.current.nodes,m=g[0];if(m.collapsed){const C=dt(u,m.startOffset-1,!1);d.current=C;const _=u[C];if(_&&typeof _!="string"&&_.nodeType===T.sequenceNodeType.FUNCTION){d.current=C;const I=_.token,R=o.getSearchListByNameFirstLetter(I);s(R),c(I);return}}}d.current=-1,c(""),s(u=>u!=null&&u.length?[]:u)});return()=>{h.unsubscribe()}}},[n,e]),E.useEffect(()=>{e||S()},[e]),{searchList:r,searchText:i,handlerFormulaReplace:(h,g)=>{const u=[...f.current.nodes];if(d.current!==-1){const m=u.splice(d.current+1),C=u.pop()||"";let _=(typeof C=="string"?C.length:C.token.length)-h.length;return u.push(h),m[0]!==T.matchToken.OPEN_BRACKET&&g!==T.FunctionType.DefinedName&&(u.push(T.matchToken.OPEN_BRACKET),_--),{text:ht([...u,...m]),offset:_}}},reset:S}},jr=()=>{},qr=E.forwardRef(Yr);function Yr(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:s,onClose:i=jr}=e,c=s.getEditorId(),d=l.useDependency(l.IShortcutService),f=l.useDependency(a.ICommandService),{searchList:S,searchText:p,handlerFormulaReplace:h,reset:g}=Kr(n,o,s),u=E.useMemo(()=>!!S.length,[S]),m=E.useRef(void 0),[C,_]=E.useState(0),I=E.useRef(!1),[R]=Wt(c,u,[p,S]),D=Te({searchList:S,active:C}),v=(P,F)=>{const A=h(P,F);A&&(g(),r(A))};function M(P){I.current&&_(P)}function w(){I.current&&_(-1)}E.useEffect(()=>{if(!S.length)return;const P=`sheet.formula-embedding-editor.search_function.${c}`,F=new a.DisposableCollection,A=O=>{const{searchList:L,active:b}=D.current;switch(O){case l.KeyCode.ARROW_UP:{_(k=>{const V=Math.max(0,k-1);return W(V),V});break}case l.KeyCode.ARROW_DOWN:{_(k=>{const V=Math.min(L.length-1,k+1);return W(V),V});break}case l.KeyCode.TAB:case l.KeyCode.ENTER:{const k=L[b];v(k.name,k.functionType);break}case l.KeyCode.ESC:{g(),i();break}}};return F.add(f.registerCommand({id:P,type:a.CommandType.OPERATION,handler(O,L){const{keyCode:b}=L;A(b)}})),[l.KeyCode.ARROW_UP,l.KeyCode.ARROW_DOWN,l.KeyCode.ENTER,l.KeyCode.ESC,l.KeyCode.TAB].map(O=>({id:P,binding:O,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:O}})).forEach(O=>{F.add(d.registerShortcut(O))}),()=>{F.dispose()}},[S]);function W(P){const F=m.current;if(!F)return;const A=F.children[P];if(!A)return;const L=F.getBoundingClientRect().top,b=F.offsetHeight,k=A.getBoundingClientRect(),V=k.top,H=k.height;if(V>=0&&V>L&&V-L+H<=b)return;const K=A.offsetTop-(b-H)/2;F.scrollTo({top:K,behavior:"smooth"})}const U=E.useMemo(()=>{let P="";return()=>{clearTimeout(P),I.current=!0,P=setTimeout(()=>{I.current=!1},300)}},[]);return S.length>0&&u&&y.jsx(l.RectPopup,{portal:!0,anchorRect$:R,direction:"vertical",children:y.jsx("ul",{ref:P=>{m.current=P,t&&(t.current=P)},"data-u-comp":"sheets-formula-editor",className:B.clsx("univer-m-0 univer-box-border univer-max-h-[400px] univer-w-[250px] univer-list-none univer-overflow-y-auto univer-rounded-lg univer-bg-white univer-p-2 univer-leading-5 univer-shadow-md univer-outline-none dark:!univer-bg-gray-900",B.borderClassName,B.scrollbarClassName),children:S.map((P,F)=>y.jsxs("li",{className:B.clsx("univer-box-border univer-cursor-pointer univer-rounded univer-px-2 univer-py-1 univer-text-gray-900 univer-transition-colors dark:!univer-text-white",{"univer-bg-gray-200 dark:!univer-bg-gray-600":C===F}),onMouseEnter:()=>M(F),onMouseLeave:w,onMouseMove:U,onClick:()=>{v(P.name,P.functionType),s&&s.focus()},children:[y.jsxs("span",{className:"univer-block univer-truncate univer-text-xs",children:[y.jsx("span",{className:"univer-text-red-500",children:P.name.substring(0,p.length)}),y.jsx("span",{children:P.name.slice(p.length)})]}),y.jsx("span",{className:"univer-block univer-text-xs univer-text-gray-400",children:P.desc})]},P.name))})})}const zr=e=>e.startsWith(T.operatorToken.EQUALS)?e.slice(1):"",Bt=()=>{},Kt=E.forwardRef((e,t)=>{var Gt,Zt,Xt,Qt;const{errorText:n,initValue:o,unitId:r,subUnitId:s,isFocus:i=!0,isSupportAcrossSheet:c=!1,onFocus:d=Bt,onBlur:f=Bt,onChange:S,onVerify:p,className:h,editorId:g,moveCursor:u=!0,onFormulaSelectingChange:m,keyboardEventConfig:C,onMoveInEditor:_,resetSelectionOnBlur:I=!0,autoScrollbar:R=!0,isSingle:D=!0,disableSelectionOnClick:v=!1,autofocus:M=!0,disableContextMenu:w,style:W}=e,U=l.useDependency(Q.IEditorService),P=E.useRef(null),F=l.useEvent(S);E.useImperativeHandle(t,()=>({isClickOutSide:X=>P.current?!P.current.contains(X.target):!1}));const A=l.useEvent(m),O=E.useRef(null),L=E.useRef(void 0),b=L.current,[k,V]=E.useState(i),H=E.useRef(null),K=E.useMemo(()=>g!=null?g:a.createInternalEditorID(`${N.EMBEDDING_FORMULA_EDITOR}-${a.generateRandomId(4)}`),[]),oe=E.useMemo(()=>n!==void 0,[n]),se=l.useDependency(a.IUniverInstanceService),ae=se.getUnit(K);l.useObservable(ae==null?void 0:ae.change$);const G=Dr(),J=a.BuildTextUtils.transform.getPlainText((Zt=(Gt=ae==null?void 0:ae.getBody())==null?void 0:Gt.dataStream)!=null?Zt:""),ke=Te(J),we=E.useMemo(()=>zr(J),[J]),Je=E.useMemo(()=>G(we),[we,G]),{isSelecting:pe,isSelectingRef:et}=Nr({unitId:r,subUnitId:s,editorId:K,isFocus:k,disableOnClick:v}),z=E.useRef(""),le=l.useDependency(j.IRenderManagerService).getRenderById(K),te=le==null?void 0:le.with(Q.DocSelectionRenderService),ie=te==null?void 0:te.isFocusing,ue=E.useMemo(()=>se.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[se]),fe=l.useObservable(ue),be=(fe==null?void 0:fe.getUnitId())===K,Me=E.useRef([]),Z=pe,me=(Qt=(Xt=l.useDependency(a.IConfigService).getConfig(Rt))==null?void 0:Xt.functionScreenTips)!=null?Qt:!0;l.useUpdateEffect(()=>{F(J)},[J,F]);const Ae=Ht("="),Oe=wr(r,s),de=l.useEvent((X,re=!0,Ce,ve)=>{if(!L.current)return;z.current=X;const nt=X[0]==="="?X.slice(1):"",_e=G(nt),io=_e.reduce((Ne,ot)=>typeof ot=="object"?`${Ne}${ot.token}`:`${Ne}${ot}`,""),rt=Ae(L.current,io===nt?_e:[],re,ve);if(Me.current=rt,Ce){const Ne=ve!=null?ve:b==null?void 0:b.getSelectionRanges();if((Ne==null?void 0:Ne.length)!==1)return;const co=Ne[0].startOffset-1,ao=dt(_e,co,!1),Jt=Ft(_e,ao);if(Jt>=0){const en=rt.splice(Jt,1)[0];en&&rt.push(en)}Oe(k?rt:[],L.current)}});E.useEffect(()=>{k&&de(J,!1,!0)},[k]),E.useEffect(()=>{if(k){if(z.current===J)return;de(J,!1,!0)}},[J]),Br(k,p,J);const ne=Mr(b),Fe=$r(k,r,s);E.useEffect(()=>{var X;A(pe,(X=te==null?void 0:te.isFocusing)!=null?X:!0)},[A,pe]),Q.useKeyboardEvent(k,C,b),E.useLayoutEffect(()=>{let X;if(H.current){X=U.register({autofocus:M,editorUnitId:K,initialSnapshot:{id:K,body:{dataStream:`${o}\r
5
- `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},H.current);const re=U.getEditor(K);L.current=re,de(o,!1,!0)}return()=>{X==null||X.dispose()}},[]),E.useLayoutEffect(()=>{i?(V(i),ne()):(I&&(b==null||b.blur(),Fe()),V(i))},[i,b,ne,Fe,I]);const{checkScrollBar:St}=Q.useResize(b,D,R);Lr(k,!!(pe&&be),r,K,w),Pr(!!(k&&ie&&u),Z,b,_);const tt=l.useEvent((X,re,Ce)=>{if(!ie)return;const ve=re!==-1?[{startOffset:re+1,endOffset:re+1,collapsed:!0}]:void 0;de(`=${X}`,!0,Ce,ve),Ce&&(ne(),re!==-1&&setTimeout(()=>{const nt={startOffset:re+1,endOffset:re+1},_e=b==null?void 0:b.render.with(Q.DocBackScrollRenderController);_e==null||_e.scrollToRange({...nt,collapsed:!0})},50),St())});Vr(k&&!!(pe&&be),k,et,r,s,Me,c,!!Z,b,tt),Hr(k&&!!(pe&&be),r,c,V,f,()=>{de(ke.current,!1,!0)});const Yt=X=>{if(X){const re=b==null?void 0:b.getSelectionRanges();if(re&&re.length===1){const Ce=re[0];if(Ce.collapsed){const ve=X.offset;setTimeout(()=>{b==null||b.setSelectionRanges([{startOffset:Ce.startOffset-ve,endOffset:Ce.endOffset-ve}])},30)}}ne(),de(`=${X.text}`)}},zt=()=>{V(!0),d(),ne()};return y.jsxs("div",{className:h,children:[y.jsx("div",{ref:P,className:B.clsx("univer-relative univer-box-border univer-flex univer-h-full univer-w-full univer-items-center univer-justify-around univer-gap-2 univer-rounded-none univer-p-0 univer-ring-1",{"univer-ring-primary-500":k,"univer-ring-red-500":oe}),children:y.jsx("div",{ref:H,className:"univer-relative univer-h-full univer-w-full",onMouseUp:zt})}),n!==void 0&&y.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),me&&b&&we!==""&&y.jsx(br,{editor:b,isFocus:k,formulaText:J,onClose:()=>ne()}),me&&!!b&&y.jsx(qr,{isFocus:k,sequenceNodes:Je,onSelect:Yt,ref:O,editor:b})]})});function Gr(e,t,n,o){const r=l.useDependency(T.LexerTreeBuilder),s=Ht(""),i=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[c,d]=E.useState([]),f=l.useDependency(N.IMarkSelectionService),S=E.useRef(""),p=l.useDependency(a.IUniverInstanceService);return E.useEffect(()=>{if(!e)return;const h=e.getDocumentDataModel().getPlainText();if(S.current===h)return;S.current=h;const g=r.sequenceNodesBuilder(h);d(g!=null?g:[])},[i,e,r]),E.useEffect(()=>{var u,m;if(!e)return;if(!t){const C=e.getDocumentData();e.setDocumentData({...C,body:{...C.body,dataStream:(m=(u=C.body)==null?void 0:u.dataStream)!=null?m:"",textRuns:[]}});return}const h=s(e,c,!1),g=new a.DisposableCollection;return h.forEach(C=>{const _=T.deserializeRangeWithSheet(C.token),I=p.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),R=I==null?void 0:I.getActiveSheet();if(!_.sheetName&&o!==(R==null?void 0:R.getSheetId())||_.sheetName&&(R==null?void 0:R.getName())!==_.sheetName)return;const D=new a.ColorKit(C.themeColor).toRgb(),v=f.addShape({range:_.range,style:{stroke:C.themeColor,fill:`rgba(${D.r}, ${D.g}, ${D.b}, 0.1)`,strokeDash:12},primary:null});v&&g.add(()=>f.removeShape(v))}),()=>{g.dispose()}},[e,t,s,f,c]),{sequenceNodes:c}}function Zr(e){const t=l.useDependency(x.SheetsSelectionsService),{supportAcrossSheet:n=!1,keepSheetReference:o=!1,unitId:r,subUnitId:s,onChange:i}=e,d=l.useDependency(a.IUniverInstanceService).getUnit(r,a.UniverInstanceType.UNIVER_SHEET),f=l.useEvent(i),S=l.useEvent((p,h)=>{const g=d==null?void 0:d.getActiveSheet();if(!g||!n&&g.getSheetId()!==s||!(p!=null&&p.length))return;const u=o?g.getName():g.getSheetId()===s?"":g.getName(),m=p.map(C=>({range:C.range,unitId:r,sheetName:u}));f(m,h)});E.useEffect(()=>{const p=new a.DisposableCollection;return p.add(t.selectionMoveStart$.subscribe(h=>{S(h,!0)})),p.add(t.selectionMoving$.subscribe(h=>{S(h,!1)})),p.add(t.selectionMoveEnd$.subscribe(h=>{S(h,!1)})),()=>{p.dispose()}},[S,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const jt=e=>!e.some(n=>{if(typeof n=="string"){if(n!==T.matchToken.COMMA)return!0}else if(n.nodeType!==T.sequenceNodeType.REFERENCE)return!0;return!1}),Xr=e=>{if(e.endColumn<e.startColumn){const t=e.endColumn;e.endColumn=e.startColumn,e.startColumn=t}if(e.endRow<e.startRow){const t=e.endRow;e.endRow=e.startRow,e.startRow=t}return e};function Qr(e){const{visible:t,initialValue:n,unitId:o,subUnitId:r,maxRangeCount:s=1/0,supportAcrossSheet:i,keepSheetReference:c,onConfirm:d,onClose:f,onShowBySelection:S}=e,p=l.useDependency(a.LocaleService),h=l.useDependency(T.LexerTreeBuilder),[g,u]=E.useState([]),[m,C]=E.useState(0),_=E.useRef(null);E.useEffect(()=>{if(t&&n.length){const v=n.map(M=>M.sheetName?T.serializeRangeWithSheet(M.sheetName,M.range):T.serializeRange(M.range));u(v),C(v.length-1)}else u([""]),C(0)},[t]);const I=(v,M)=>{const w=[...g];w[v]=M,u(w)},R=()=>{u([...g,""]),C(g.length)},D=v=>{g.splice(v,1),u([...g])};return Zr({unitId:o,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(v,M)=>{if(!t&&S!=null&&S(v))return;const w=new Set(g),W=v.map(F=>F.sheetName?T.serializeRangeWithSheet(F.sheetName,F.range):T.serializeRange(F.range)),U=W.filter(F=>!w.has(F));if(!U.length)return;const P=[...g];if(W.length>1){M||P.splice(m,1),P.push(...U);const F=P.slice(0,s);u(F),C(F.length-1),requestAnimationFrame(()=>{var A;(A=_.current)==null||A.scrollTo({top:_.current.scrollHeight})})}else{P.splice(m,1,...U);const F=P.slice(0,s);u(F),C(m+U.length-1)}}}),y.jsx(B.Dialog,{width:"328px",open:t,title:p.t("rangeSelector.title"),draggable:!0,mask:!1,maskClosable:!1,footer:y.jsxs("footer",{className:"univer-flex univer-gap-2",children:[y.jsx(B.Button,{onClick:f,children:p.t("rangeSelector.cancel")}),y.jsx(B.Button,{variant:"primary",onClick:()=>{d(g.filter(v=>{const M=h.sequenceNodesBuilder(v);return M&&M.length===1&&typeof M[0]!="string"&&M[0].nodeType===T.sequenceNodeType.REFERENCE}).map(v=>T.deserializeRangeWithSheet(v)).map(v=>({...v,range:Xr(v.range)})))},children:p.t("rangeSelector.confirm")})]}),onClose:f,children:y.jsxs("div",{ref:_,className:B.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",B.scrollbarClassName),children:[g.map((v,M)=>y.jsxs("div",{className:"univer-mb-2 univer-flex univer-items-center univer-gap-4",children:[y.jsx(B.Input,{className:B.clsx("univer-w-full",{"univer-border-primary-600":m===M}),placeholder:p.t("rangeSelector.placeHolder"),onFocus:()=>C(M),value:v,onChange:w=>I(M,w)}),g.length>1&&y.jsx(xt,{className:"univer-cursor-pointer",onClick:()=>D(M)})]},M)),g.length<s&&y.jsx("div",{children:y.jsxs(B.Button,{variant:"link",onClick:R,children:[y.jsx(Pt,{}),y.jsx("span",{children:p.t("rangeSelector.addAnotherRange")})]})})]})})}function Jr(e){return e.split(T.matchToken.COMMA).filter(t=>!!t).map(t=>T.deserializeRangeWithSheet(t))}function eo(e){return e.map(t=>t.sheetName?T.serializeRangeWithSheet(t.sheetName,t.range):T.serializeRange(t.range)).join(T.matchToken.COMMA)}function gt(e){const[t,n]=E.useState(null),{onVerify:o,selectorRef:r,unitId:s,subUnitId:i,maxRangeCount:c,supportAcrossSheet:d,keepSheetReference:f,autoFocus:S,onChange:p,onRangeSelectorDialogVisibleChange:h,onClickOutside:g,onFocusChange:u,forceShowDialogWhenSelectionChanged:m,hideEditor:C,resetRange:_}=e,[I,R]=E.useState(S!=null?S:!1),[D,v]=E.useState(!1),[M,w]=E.useState([]),W=l.useDependency(a.LocaleService),U=l.useDependency(Q.IEditorService),{sequenceNodes:P}=Gr(t,I,s,i),F=Te(P),A=l.useDependency(a.ICommandService),O=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),U.blur()}),L=l.useEvent(()=>{var b;O(),w(Jr((b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")),v(!0)});return E.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){U.focus(t.getEditorId())},blur:O,verify:()=>jt(F.current),showDialog:b=>{O(),w(b),v(!0)},hideDialog:()=>{w([]),v(!1)},getValue:()=>{var b;return(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:""}})},[O,t,U,r,F]),E.useEffect(()=>{var b;o==null||o(jt(P),(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")},[P]),E.useEffect(()=>{h==null||h(D)},[D]),E.useEffect(()=>{if(D&&_)return()=>{const b={unitId:s,subUnitId:i,selections:_};A.executeCommand(x.SetSelectionsOperation.id,b)}},[D]),y.jsxs(y.Fragment,{children:[C?null:y.jsx(Q.RichTextEditor,{isSingle:!0,...e,onFocusChange:(b,k)=>{R(b),u==null||u(b,k)},editorRef:n,onClickOutside:()=>{R(!1),O(),g==null||g()},icon:y.jsx(B.Tooltip,{title:W.t("rangeSelector.buttonTooltip"),placement:"bottom",children:y.jsx($t,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:L})})}),y.jsx(Qr,{initialValue:M,unitId:s,subUnitId:i,visible:D,maxRangeCount:c,onConfirm:b=>{const k=eo(b),V=a.RichTextBuilder.newEmptyData();V.body.dataStream=k,t==null||t.replaceText(k,!1),p==null||p(V,k),v(!1),w([]),requestAnimationFrame(()=>{O()})},onClose:()=>{v(!1),w([])},supportAcrossSheet:d,keepSheetReference:f,onShowBySelection:b=>I||m?(w(b),v(!0),!1):!0})]})}const to=()=>{var o,r;const e=l.useDependency(ut),t=l.useObservable(e.currentSelector$),n=E.useRef(null);return E.useEffect(()=>{var s,i;if(t)return(i=n.current)==null||i.showDialog((s=t.initialValue)!=null?s:[]),()=>{var c;(c=n.current)==null||c.hideDialog()}},[t]),y.jsx(gt,{unitId:(o=t==null?void 0:t.unitId)!=null?o:"",subUnitId:(r=t==null?void 0:t.subUnitId)!=null?r:"",hideEditor:!0,selectorRef:n,onChange:(s,i)=>{var c;t==null||t.callback((c=i==null?void 0:i.split(",").map(d=>T.deserializeRangeWithSheet(d)))!=null?c:[])}})};var no=Object.defineProperty,ro=Object.getOwnPropertyDescriptor,oo=(e,t,n)=>t in e?no(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,so=(e,t,n,o)=>{for(var r=o>1?void 0:o?ro(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Qe=(e,t)=>(n,o)=>t(n,o,e),qt=(e,t,n)=>oo(e,typeof t!="symbol"?t+"":t,n);$.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=Tt,n,o,r,s){super(),this._config=t,this._injector=n,this._renderManagerService=o,this._configService=r,this._uiPartsService=s;const{menu:i,...c}=a.merge(Tt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(Rt,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[Ve,{useClass:st}],[ut],[Ge],[Ke],[je],[qe],[Ye],[$.FormulaReorderController],[Ze]]),this._initUIPart()}onReady(){[[$.RefSelectionsRenderService]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))})}onRendered(){[[at]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))}),a.touchDependencies(this._injector,[[Ge],[je],[Ye],[Ze]])}onSteady(){this._injector.get(Ke),this._injector.get($.FormulaReorderController)}_initUIPart(){const t=this._injector.get(l.ComponentManager);this.disposeWithMe(t.register(N.RANGE_SELECTOR_COMPONENT_KEY,gt)),this.disposeWithMe(t.register(N.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Kt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(to,this._injector)))}},qt($.UniverSheetsFormulaUIPlugin,"pluginName",Et),qt($.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET),$.UniverSheetsFormulaUIPlugin=so([a.DependentOn(ge.UniverSheetsFormulaPlugin),Qe(1,a.Inject(a.Injector)),Qe(2,j.IRenderManagerService),Qe(3,a.IConfigService),Qe(4,l.IUIPartsService)],$.UniverSheetsFormulaUIPlugin),$.FORMULA_PROMPT_ACTIVATED=vt,$.FormulaEditor=Kt,$.GlobalRangeSelectorService=ut,$.HelpFunctionOperation=mt,$.InsertFunctionOperation=ce,$.MoreFunctionsOperation=He,$.RangeSelector=gt,$.ReferenceAbsoluteOperation=it,$.SearchFunctionOperation=yt,$.SelectEditorFormulaOperation=Ee,$.SheetCopyFormulaOnlyCommand=We,$.SheetOnlyPasteFormulaCommand=Ue,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
1
+ (function($,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("@univerjs/sheets-ui"),require("@univerjs/engine-formula"),require("rxjs"),require("@univerjs/docs-ui"),require("@univerjs/engine-render"),require("@univerjs/sheets"),require("@univerjs/sheets-formula"),require("@univerjs/ui"),require("react/jsx-runtime"),require("react"),require("@univerjs/design"),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/engine-render","@univerjs/sheets","@univerjs/sheets-formula","@univerjs/ui","react/jsx-runtime","react","@univerjs/design","@univerjs/docs","rxjs/operators"],a):($=typeof globalThis<"u"?globalThis:$||self,a($.UniverSheetsFormulaUi={},$.UniverCore,$.UniverSheetsUi,$.UniverEngineFormula,$.rxjs,$.UniverDocsUi,$.UniverEngineRender,$.UniverSheets,$.UniverSheetsFormula,$.UniverUi,$.React,$.React,$.UniverDesign,$.UniverDocs,$.rxjs.operators))})(this,(function($,a,N,T,q,J,j,x,ge,l,y,E,B,pt,tn){"use strict";var lo=Object.defineProperty;var uo=($,a,N)=>a in $?lo($,a,{enumerable:!0,configurable:!0,writable:!0,value:N}):$[a]=N;var Y=($,a,N)=>uo($,typeof a!="symbol"?a+"":a,N);const We={id:"sheet.command.copy-formula-only",type:a.CommandType.COMMAND,handler:async e=>e.get(N.ISheetClipboardService).copy({copyHookType:N.PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY})},Ue={id:"sheet.command.paste-formula",type:a.CommandType.COMMAND,handler:async e=>e.get(a.ICommandService).executeCommand(N.SheetPasteCommand.id,{value:N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA})},Ee={id:"formula-ui.operation.select-editor-formula",type:a.CommandType.OPERATION,handler:(e,t)=>!0};var nn=Object.getOwnPropertyDescriptor,rn=(e,t,n,o)=>{for(var r=o>1?void 0:o?nn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},on=(e,t)=>(n,o)=>t(n,o,e);const vt="FORMULA_PROMPT_ACTIVATED",Ve=a.createIdentifier("formula-ui.prompt-service");let st=class{constructor(e){Y(this,"_search$",new q.Subject);Y(this,"_help$",new q.Subject);Y(this,"_navigate$",new q.Subject);Y(this,"_accept$",new q.Subject);Y(this,"_acceptFormulaName$",new q.Subject);Y(this,"search$",this._search$.asObservable());Y(this,"help$",this._help$.asObservable());Y(this,"navigate$",this._navigate$.asObservable());Y(this,"accept$",this._accept$.asObservable());Y(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());Y(this,"_searching",!1);Y(this,"_helping",!1);Y(this,"_sequenceNodes",[]);Y(this,"_isLockedOnSelectionChangeRefString",!1);Y(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=e}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(e){this._contextService.setContextValue(vt,e.visible),this._searching=e.visible,this._search$.next(e)}isSearching(){return this._searching}help(e){this._helping=e.visible,this._help$.next(e)}isHelping(){return this._helping}navigate(e){this._navigate$.next(e)}accept(e){this._accept$.next(e)}acceptFormulaName(e){this._acceptFormulaName$.next(e)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(e){this._sequenceNodes=e}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(e){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(e)]}getCurrentSequenceNodeByIndex(e){return this._sequenceNodes[e]}getCurrentSequenceNodeIndex(e){let t=0;const n=this._sequenceNodes[0];for(let o=0,r=this._sequenceNodes.length;o<r;o++){const s=this._sequenceNodes[o];if(typeof s=="string")t++;else{const{endIndex:i}=s;t=i}if(e<=t)return typeof n=="string"&&e!==0?o+1:o}return this._sequenceNodes.length}updateSequenceRef(e,t){const n=this._sequenceNodes[e];if(typeof n=="string"||n.nodeType!==T.sequenceNodeType.REFERENCE)return;const o=t.length-n.token.length,r={...n};r.token=t,r.endIndex+=o,this._sequenceNodes[e]=r;for(let s=e+1,i=this._sequenceNodes.length;s<i;s++){const c=this._sequenceNodes[s];if(typeof c=="string")continue;const d={...c};d.startIndex+=o,d.endIndex+=o,this._sequenceNodes[s]=d}}insertSequenceRef(e,t){const n=t.length,o=this.getCurrentSequenceNodeIndex(e);this._sequenceNodes.splice(o,0,{token:t,startIndex:e,endIndex:e+n-1,nodeType:T.sequenceNodeType.REFERENCE});for(let r=o+1,s=this._sequenceNodes.length;r<s;r++){const i=this._sequenceNodes[r];if(typeof i=="string")continue;const c={...i};c.startIndex+=n,c.endIndex+=n,this._sequenceNodes[r]=c}}insertSequenceString(e,t){const n=this.getCurrentSequenceNodeIndex(e),o=t.split("");this._sequenceNodes.splice(n,0,...o);const r=o.length;for(let s=n+r,i=this._sequenceNodes.length;s<i;s++){const c=this._sequenceNodes[s];if(typeof c=="string")continue;const d={...c};d.startIndex+=r,d.endIndex+=r,this._sequenceNodes[s]=d}}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=rn([on(0,a.IContextService)],st);const mt={id:"formula-ui.operation.help-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ve).help(t),!0)},ce={id:"formula-ui.operation.insert-function",type:a.CommandType.OPERATION,handler:async(e,t)=>{var I,R;const n=e.get(x.SheetsSelectionsService),o=e.get(J.IEditorService),r=n.getCurrentSelections();if(!r||!r.length)return!1;const s=x.getSheetCommandTarget(e.get(a.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:c,subUnitId:d}=s,f=i.getCellMatrix(),{value:S}=t,p=e.get(a.ICommandService);e.get(N.IEditorBridgeService);const h=[],g=[];let u=null,m=0,C=0,_="";if(r.length===1&&(an(r[0].range)||ln(r[0].range)&&_t(f,r[0].range))){const{range:D,primary:v}=r[0],M=(I=v==null?void 0:v.actualRow)!=null?I:D.startRow,k=(R=v==null?void 0:v.actualColumn)!=null?R:D.startColumn;u=D,m=M,C=k;const W=Ct(f,M,k);W&&(_=T.serializeRange(W))}else r.some(D=>{var k,W;const{range:v,primary:M}=D;if(_t(f,v)){const U=(k=M==null?void 0:M.actualRow)!=null?k:v.startRow,P=(W=M==null?void 0:M.actualColumn)!=null?W:v.startColumn,F=Ct(f,U,P);if(!F)return u=v,m=U,C=P,!0;const A=T.serializeRange(F),O=`=${S}(${A})`;h.push({range:v,primary:{row:U,column:P},formula:O})}else{const{startRow:U,startColumn:P,endRow:F,endColumn:A}=v;if(U===F){const O=un(f,U,A,i.getColumnCount()-1),L=O===A?A-1:A,b=T.serializeRange({startRow:U,endRow:F,startColumn:P,endColumn:L}),w=`=${S}(${b})`;g.push({range:v,primary:{row:U,column:O},formula:w})}else{let O=-1;for(let b=P;b<=A;b++){const w=dn(f,b,F,i.getRowCount()-1);O=Math.max(O,w)}const L=O===F?F-1:F;for(let b=P;b<=A;b++){const w=T.serializeRange({startRow:U,endRow:L,startColumn:b,endColumn:b}),V=`=${S}(${w})`;g.push({range:v,primary:{row:O,column:b},formula:V})}}}return!1});if(u){const D=x.getCellAtRowCol(m,C,i),v={range:a.Rectangle.clone(u),primary:{startRow:D.startRow,startColumn:D.startColumn,endRow:D.endRow,endColumn:D.endColumn,actualRow:m,actualColumn:C,isMerged:D.isMerged,isMergedMainCell:D.startRow===m&&D.startColumn===C}},M={unitId:c,subUnitId:d,selections:[v]};await p.executeCommand(x.SetSelectionsOperation.id,M);const k=o.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),W=o.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);p.syncExecuteCommand(N.SetCellEditVisibleOperation.id,{visible:!0,unitId:c,eventType:j.DeviceInputEventType.Dblclick});const U=`=${S}(${_}`;k==null||k.replaceText(U),W==null||W.replaceText(U,!1)}return h.length===0&&g.length===0?!1:p.executeCommand(ge.InsertFunctionCommand.id,{list:h,listOfRangeHasNumber:g})}};function Ct(e,t,n){const o=sn(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=cn(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function sn(e,t,n){let o=!1;if(t===0)return t;for(let r=t-1;r>=0;r--){const s=e.getValue(r,n);if(xe(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!xe(s))return r+1;if(o&&r===0)return 0}}return t}function cn(e,t,n){let o=!1;if(n===0)return n;for(let r=n-1;r>=0;r--){const s=e.getValue(t,r);if(xe(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!xe(s))return r+1;if(o&&r===0)return 0}}return n}function xe(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return!1;const n=t.dataStream,r=n.substring(n.length-2,n.length)===a.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n;return a.isRealNum(r)}return e&&(e.t===a.CellValueType.NUMBER||a.getCellValueType(e)===a.CellValueType.NUMBER)}function an(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function ln(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function _t(e,t){for(let n=t.startRow;n<=t.endRow;n++)for(let o=t.startColumn;o<=t.endColumn;o++)if(xe(e.getValue(n,o)))return!1;return!0}function un(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function dn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const Et="SHEET_FORMULA_UI_PLUGIN",It=`${Et}_MORE_FUNCTIONS_COMPONENT`,He={id:"formula-ui.operation.more-functions",type:a.CommandType.OPERATION,handler:async e=>(e.get(l.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:It}}),!0)},it={id:"formula-ui.operation.change-ref-to-absolute",type:a.CommandType.OPERATION,handler:async e=>!0},yt={id:"formula-ui.operation.search-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ve).search(t),!0)};var fn=Object.getOwnPropertyDescriptor,hn=(e,t,n,o)=>{for(var r=o>1?void 0:o?fn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Be=(e,t)=>(n,o)=>t(n,o,e);$.FormulaReorderController=class extends a.Disposable{constructor(t,n,o,r){super(),this._sheetInterceptorService=t,this._univerInstanceService=n,this._formulaDataModel=o,this._lexerTreeBuilder=r,this._initialize()}_initialize(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:t=>t.id===x.ReorderRangeCommand.id?this._reorderFormula(t.params):{redos:[],undos:[]}}))}_reorderFormula(t){const n=[],o=[],{unitId:r,subUnitId:s,range:i,order:c}=t,d=this._univerInstanceService.getUniverSheetInstance(r),f=d==null?void 0:d.getSheetBySheetId(s);if(!f)return{redos:n,undos:o};const S=f.getCellMatrix(),p=new a.ObjectMatrix,h=new a.ObjectMatrix;let g=!1;return a.Range.foreach(i,(u,m)=>{let C=u;c.hasOwnProperty(u)&&(C=c[u]);const _=S.getValue(C,m);if(_!=null&&_.f||_!=null&&_.si){g=!0;const I=this._formulaDataModel.getFormulaStringByCell(C,m,s,r),R=this._lexerTreeBuilder.moveFormulaRefOffset(I,0,u-C),D=a.Tools.deepClone(_);D.f=R,D.si=null,p.setValue(u,m,D)}else p.setValue(u,m,_);h.setValue(u,m,S.getValue(u,m))}),g?(n.push({id:x.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:p.getMatrix()}}),o.push({id:x.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:h.getMatrix()}}),{redos:n,undos:o}):{redos:n,undos:o}}},$.FormulaReorderController=hn([Be(0,a.Inject(x.SheetInterceptorService)),Be(1,a.Inject(a.IUniverInstanceService)),Be(2,a.Inject(T.FormulaDataModel)),Be(3,a.Inject(T.LexerTreeBuilder))],$.FormulaReorderController);const Rt="sheets-formula-ui.base.config",Tt={};var gn=Object.getOwnPropertyDescriptor,Sn=(e,t,n,o)=>{for(var r=o>1?void 0:o?gn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Pe=(e,t)=>(n,o)=>t(n,o,e);const ct="SHEET_FORMULA_ALERT",pn={[T.ErrorType.DIV_BY_ZERO]:"divByZero",[T.ErrorType.NAME]:"name",[T.ErrorType.VALUE]:"value",[T.ErrorType.NUM]:"num",[T.ErrorType.NA]:"na",[T.ErrorType.CYCLE]:"cycle",[T.ErrorType.REF]:"ref",[T.ErrorType.SPILL]:"spill",[T.ErrorType.CALC]:"calc",[T.ErrorType.ERROR]:"error",[T.ErrorType.CONNECT]:"connect",[T.ErrorType.NULL]:"null"};let at=class extends a.Disposable{constructor(e,t,n,o,r,s){super(),this._context=e,this._hoverManagerService=t,this._cellAlertManagerService=n,this._localeService=o,this._formulaDataModel=r,this._zenZoneService=s,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(q.debounceTime(100)).subscribe(e=>{var t,n,o,r,s;if(e){const c=this._context.unit.getActiveSheet();if(!c)return this._hideAlert();const d=c.getCell(e.location.row,e.location.col),f=(r=(o=(n=(t=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:t[e.location.unitId])==null?void 0:n[e.location.subUnitId])==null?void 0:o[e.location.row])==null?void 0:r[e.location.col];if(a.isICellData(d)){const S=T.extractFormulaError(d,!!f);if(!S){this._hideAlert();return}const p=this._cellAlertManagerService.currentAlert.get(ct),h=(s=p==null?void 0:p.alert)==null?void 0:s.location;if(h&&h.row===e.location.row&&h.col===e.location.col&&h.subUnitId===e.location.subUnitId&&h.unitId===e.location.unitId){this._hideAlert();return}this._cellAlertManagerService.showAlert({type:N.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${pn[S]}`),location:e.location,width:200,height:74,key:ct});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(e=>{e&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(ct)}};at=Sn([Pe(1,a.Inject(N.HoverManagerService)),Pe(2,a.Inject(N.CellAlertManagerService)),Pe(3,a.Inject(a.LocaleService)),Pe(4,a.Inject(T.FormulaDataModel)),Pe(5,l.IZenZoneService)],at);var vn=Object.getOwnPropertyDescriptor,mn=(e,t,n,o)=>{for(var r=o>1?void 0:o?vn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},bt=(e,t)=>(n,o)=>t(n,o,e);let Ke=class extends a.Disposable{constructor(e,t){super(),this._autoFillService=e,this._lexerTreeBuilder=t,this._registerAutoFill()}_registerAutoFill(){const e={type:N.DATA_TYPE.FORMULA,priority:1001,match:t=>a.isFormulaString(t==null?void 0:t.f)||a.isFormulaId(t==null?void 0:t.si),isContinue:(t,n)=>t.type===N.DATA_TYPE.FORMULA,applyFunctions:{[N.APPLY_TYPE.COPY]:(t,n,o,r,s)=>{const{data:i,index:c}=t;return this._fillCopyFormula(i,n,o,c,r,s)}}};this._autoFillService.registerRule(e)}_fillCopyFormula(e,t,n,o,r,s){var f,S;const i=_n(r),c=[],d=new Map;for(let p=1;p<=t;p++){const h=(p-1)%e.length,g=o[h],u=a.Tools.deepClone(e[h]);if(u){const m=((f=e[h])==null?void 0:f.f)||"",C=((S=e[h])==null?void 0:S.si)||"",_=a.isFormulaString(m);if(a.isFormulaId(C))u.si=C,u.f=null,u.v=null,u.p=null,u.t=null,c.push(u);else if(_){let R=d.get(h);if(R)u.si=R,u.f=null,u.v=null,u.p=null,u.t=null;else{R=a.generateRandomId(6),d.set(h,R);const{offsetX:D,offsetY:v}=Cn(i,t,n,s,g),M=this._lexerTreeBuilder.moveFormulaRefOffset(m,D,v);u.si=R,u.f=M,u.v=null,u.p=null,u.t=null}c.push(u)}}}return c}};Ke=mn([bt(0,N.IAutoFillService),bt(1,a.Inject(T.LexerTreeBuilder))],Ke);function Cn(e,t,n,o,r){const{source:s,target:i}=o,{rows:c}=i,{rows:d}=s;let f=0,S=0;switch(n){case a.Direction.UP:S=c[r]-d[r];break;case a.Direction.RIGHT:f=e;break;case a.Direction.DOWN:S=c[r]-d[r];break;case a.Direction.LEFT:f=-e*t;break}return{offsetX:f,offsetY:S}}function _n(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}var En=Object.getOwnPropertyDescriptor,In=(e,t,n,o)=>{for(var r=o>1?void 0:o?En(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Le=(e,t)=>(n,o)=>t(n,o,e);const yn="default-paste-formula";let je=class extends a.Disposable{constructor(e,t,n,o,r){super(),this._univerInstanceService=e,this._lexerTreeBuilder=t,this._sheetClipboardService=n,this._injector=o,this._formulaDataModel=r,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._copyFormulaOnlyHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_copyFormulaOnlyHook(){const e=this;let t=null;return{id:N.PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY,priority:10,onBeforeCopy(n,o){t=e._getWorksheet(n,o)},onCopyCellContent(n,o){if(!t)return"";const r=t.getCellRaw(n,o);return r?a.isFormulaString(r.f)?r.f:a.isFormulaId(r.si)&&e._formulaDataModel.getFormulaStringByCell(n,o,t.getSheetId(),t.getUnitId())||"":""},onAfterCopy(){t=null},getFilteredOutRows(n,o,r){const s=e._getWorksheet(n,o);if(!s)return[];const{startRow:i,endRow:c}=r,d=[];for(let f=i;f<=c;f++)s.getRowFiltered(f)&&d.push(f);return d},handleMatrixOnCell(n,o,r,s,i,c,d){const f=i.getValue(n,o);if(t&&f&&(a.isFormulaString(f.f)||a.isFormulaId(f.si))){const S=a.isFormulaString(f.f)?f.f:e._formulaDataModel.getFormulaStringByCell(n,o,t.getSheetId(),t.getUnitId());c.setValue(r,s,{...a.getEmptyCell(),f:S}),d.setValue(r,s,{...a.getEmptyCell(),f:S,displayV:S})}else i.setValue(n,o,a.getEmptyCell()),c.setValue(r,s,a.getEmptyCell()),d.setValue(r,s,a.getEmptyCell())}}}_pasteFormulaHook(){return{id:N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!0)}}_pasteWithFormulaHook(){return{id:yn,priority:10,onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!1)}}_getWorkbook(e){return e?this._univerInstanceService.getUnit(e,a.UniverInstanceType.UNIVER_SHEET):this._univerInstanceService.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET)}_getWorksheet(e,t){const n=this._getWorkbook(e);return t?n==null?void 0:n.getSheetBySheetId(t):n==null?void 0:n.getActiveSheet()}_onPasteCells(e,t,n,o,r){var h;if([N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT,N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH].includes(o.pasteType))return{undos:[],redos:[]};const i=this._getWorkbook(),c=t.unitId||(i==null?void 0:i.getUnitId()),d=t.subUnitId||((h=i==null?void 0:i.getActiveSheet())==null?void 0:h.getSheetId());if(!c||!d)return{undos:[],redos:[]};const f=t.range,S=n,p={copyType:o.copyType||N.COPY_TYPE.COPY,copyRange:e==null?void 0:e.range,pasteType:o.pasteType};return this._injector.invoke(g=>Rn(c,d,f,S,g,p,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};je=In([Le(0,a.IUniverInstanceService),Le(1,a.Inject(T.LexerTreeBuilder)),Le(2,N.ISheetClipboardService),Le(3,a.Inject(a.Injector)),Le(4,a.Inject(T.FormulaDataModel))],je);function Rn(e,t,n,o,r,s,i,c,d=!1,f){const S=[],p=[],h=Tn(e,t,n,o,s,i,c,f);if(!h.hasValue())return{undos:[],redos:[]};const g={unitId:e,subUnitId:t,cellValue:h.getData()};S.push({id:x.SetRangeValuesMutation.id,params:g});const u=x.SetRangeValuesUndoMutationFactory(r,g);return p.push({id:x.SetRangeValuesMutation.id,params:u}),{undos:p,redos:S}}function Tn(e,t,n,o,r,s,i,c){return c?r.pasteType===N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE?Mn(e,t,n,o,i,c):r.pasteType===N.PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA?On(e,t,n,o,s,i,c):Nn(e,t,n,o,r.copyType,s,i,c):bn(e,t,n,o,i)}function bn(e,t,n,o,r){const s=new a.ObjectMatrix,i=r.getSheetFormulaData(e,t);return o.forValue((c,d,f)=>{var g;const S=n.rows[c],p=n.cols[d],h={};a.isFormulaString(f.v)?(h.v=null,h.f=`${f.v}`,h.si=null,h.p=null,s.setValue(S,p,h)):(g=i==null?void 0:i[S])!=null&&g[p]&&(h.v=f.v,h.f=null,h.si=null,h.p=null,s.setValue(S,p,h))}),s}function Mn(e,t,n,o,r,s){var f,S;const i=new a.ObjectMatrix,c=(S=(f=r.getArrayFormulaCellData())==null?void 0:f[s.unitId])==null?void 0:S[s.subUnitId],d=r.getSheetFormulaData(e,t);return o.forValue((p,h,g)=>{var R,D;const u=s.range.rows[p%s.range.rows.length],m=s.range.cols[h%s.range.cols.length],C=n.rows[p],_=n.cols[h],I={};if(a.isFormulaString(g.f)||a.isFormulaId(g.si))I.v=g.v,I.f=null,I.si=null,I.p=null,i.setValue(C,_,I);else if((R=c==null?void 0:c[u])!=null&&R[m]){const v=c[u][m];I.v=v.v,I.f=null,I.si=null,I.p=null,i.setValue(C,_,I)}else if((D=d==null?void 0:d[C])!=null&&D[_]){if(I.v=g.v,I.f=null,I.si=null,I.p=null,g.p){const v=Mt(g);v&&(I.v=v)}i.setValue(C,_,I)}}),i}function On(e,t,n,o,r,s,i){const c=new a.ObjectMatrix,d=new Map;return o.forValue((f,S,p)=>{const h=n.rows[f],g=n.cols[S],u={};if(a.isFormulaId(p.si)){if(i.unitId!==e||i.subUnitId!==t){const m=s.getFormulaStringByCell(i.range.rows[f%i.range.rows.length],i.range.cols[S%i.range.cols.length],i.subUnitId,i.unitId),C=n.cols[S]-i.range.cols[S%i.range.cols.length],_=n.rows[f]-i.range.rows[f%i.range.rows.length],I=r.moveFormulaRefOffset(m||"",C,_);u.si=null,u.f=I}else u.si=p.si,u.f=null;u.v=null,u.p=null,c.setValue(h,g,u)}else if(a.isFormulaString(p.f)){const m=`${f%i.range.rows.length}_${S%i.range.cols.length}`;let C=d.get(m);if(C)u.si=C,u.f=null;else{C=a.generateRandomId(6),d.set(m,C);const _=n.cols[S]-i.range.cols[S%i.range.cols.length],I=n.rows[f]-i.range.rows[f%i.range.rows.length],R=r.moveFormulaRefOffset(p.f||"",_,I);u.si=C,u.f=R}u.v=null,u.p=null,c.setValue(h,g,u)}else{if(u.v=p.v,u.f=null,u.si=null,u.p=null,p.p){const m=Mt(p);m&&(u.v=m)}c.setValue(h,g,u)}}),c}function Nn(e,t,n,o,r,s,i,c){const d=new a.ObjectMatrix,f=new Map,S=i.getSheetFormulaData(e,t),p=[];return r===N.COPY_TYPE.CUT?o.forValue((h,g,u)=>{const m=n.rows[h],C=n.cols[g],_={};if(a.isFormulaId(u.si)){if(a.isFormulaString(u.f))p.push(u.si),_.f=u.f,_.si=u.si;else if(p.includes(u.si))_.f=null,_.si=u.si;else{const I=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[g%c.range.cols.length],c.subUnitId,c.unitId);_.f=I,_.si=null}_.v=null,_.p=null,d.setValue(m,C,_)}else a.isFormulaString(u.f)&&(_.f=u.f,_.si=null,_.v=null,_.p=null,d.setValue(m,C,_))}):o.forValue((h,g,u)=>{var I;const m=n.rows[h],C=n.cols[g],_={};if(a.isFormulaId(u.si)){if(c.unitId!==e||c.subUnitId!==t){const R=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[g%c.range.cols.length],c.subUnitId,c.unitId),D=n.cols[g]-c.range.cols[g%c.range.cols.length],v=n.rows[h]-c.range.rows[h%c.range.rows.length],M=s.moveFormulaRefOffset(R||"",D,v);_.si=null,_.f=M}else _.si=u.si,_.f=null;_.v=null,_.p=null,d.setValue(m,C,_)}else if(a.isFormulaString(u.f)){const R=`${h%c.range.rows.length}_${g%c.range.cols.length}`;let D=f.get(R);if(D)_.si=D,_.f=null;else{D=a.generateRandomId(6),f.set(R,D);const v=n.cols[g]-c.range.cols[g%c.range.cols.length],M=n.rows[h]-c.range.rows[h%c.range.rows.length],k=s.moveFormulaRefOffset(u.f||"",v,M);_.si=D,_.f=k}_.v=null,_.p=null,d.setValue(m,C,_)}else(I=S==null?void 0:S[m])!=null&&I[C]&&(_.v=u.v,_.f=null,_.si=null,_.p=u.p,d.setValue(m,C,_))}),p.length>0&&new a.ObjectMatrix(S).forValue((h,g,u)=>{if(!(c.range.rows.includes(h)&&c.range.cols.includes(g))&&!(n.rows.includes(h)&&n.cols.includes(g))&&p.includes(u==null?void 0:u.si)){const m=i.getFormulaStringByCell(h,g,c.subUnitId,c.unitId);d.setValue(h,g,{f:m,si:null,v:null,p:null})}}),d}function Mt(e){if(e!=null&&e.p){const t=e==null?void 0:e.p.body;if(t==null)return;const n=t.dataStream;return n.substring(n.length-2,n.length)===a.DEFAULT_EMPTY_DOCUMENT_VALUE?n.substring(0,n.length-2):n}}var Dn=Object.getOwnPropertyDescriptor,kn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Dn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Ie=(e,t)=>(n,o)=>t(n,o,e);let qe=class extends a.Disposable{constructor(t,n,o,r,s,i,c,d){super();Y(this,"_previousShape");Y(this,"_skeleton");this._context=t,this._sheetInterceptorService=n,this._formulaDataModel=o,this._themeService=r,this._renderManagerService=s,this._sheetSkeletonManagerService=i,this._commandService=c,this._logService=d,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{var n,o;if(t==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:r}=t,s=(o=(n=this._skeleton)==null?void 0:n.worksheet)==null?void 0:o.getSheetId();if(this._changeRuntime(r),s!==r.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:c}=t;this._updateArrayFormulaRangeShape(i,c)}}}))}_changeRuntime(t){this._skeleton=t}_initInterceptorEditorStart(){this.disposeWithMe(a.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(x.BEFORE_CELL_EDIT,{handler:(t,n,o)=>{var u,m,C,_;const{row:r,col:s,unitId:i,subUnitId:c,worksheet:d}=n,f=this._formulaDataModel.getArrayFormulaRange(),S=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),t==null)return o(t);let p=null;const h=this._formulaDataModel.getFormulaStringByCell(r,s,c,i);if(h!==null&&(p={f:h}),t.v!=null&&t.v!==""&&((C=(m=(u=S[i])==null?void 0:u[c])==null?void 0:m[r])==null?void 0:C[s])==null)return p?{...t,...p}:o(t);const g=(_=f==null?void 0:f[i])==null?void 0:_[c];return g!=null&&(p=this._displayArrayFormulaRangeShape(g,r,s,i,c,d,p)),p?{...t,...p}:o(t)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{(t.id===T.SetFormulaCalculationResultMutation.id||t.id===T.SetArrayFormulaDataMutation.id&&n&&n.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{x.SetWorksheetRowAutoHeightMutation.id===t.id&&requestIdleCallback(()=>{const n=t.params,{unitId:o,subUnitId:r,rowsAutoHeightInfo:s}=n;this._refreshArrayFormulaRangeShapeByRow(o,r,s)})}))}_displayArrayFormulaRangeShape(t,n,o,r,s,i,c){return new a.ObjectMatrix(t).forValue((d,f,S)=>{if(S==null)return!0;const{startRow:p,startColumn:h,endRow:g,endColumn:u}=S;if(d===n&&f===o)return this._createArrayFormulaRangeShape(S,r),!1;if(n>=p&&n<=g&&o>=h&&o<=u){const m=i.getCell(p,h);return(m==null?void 0:m.v)===T.ErrorType.SPILL||(m==null?void 0:m.f)==null?void 0:(c==null&&(c={f:m.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(S,r),!1)}}),c}_createArrayFormulaRangeShape(t,n){const o=this._renderManagerService.getRenderById(n),r=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!o||!r)return;const{scene:s}=o;if(!s)return;const i={range:t,primary:null,style:{strokeWidth:1,stroke:this._themeService.getColorFromTheme("primary.600"),fill:new a.ColorKit(this._themeService.getColorFromTheme("white")).setAlpha(0).toString(),widgets:{}}},c=N.attachSelectionWithCoord(i,r),{rowHeaderWidth:d,columnHeaderHeight:f}=r,S=new N.SelectionControl(s,N.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:f});S.updateRangeBySelectionWithCoord(c),S.setEvent(!1),this._previousShape=S}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(t,n){if(this._previousShape){const{startRow:o,endRow:r,startColumn:s,endColumn:i}=this._previousShape.getRange(),c={startRow:o,endRow:r,startColumn:s,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(c,t)}}_checkCurrentSheet(t,n){const o=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!o)return!1;const r=o.worksheet;return r?r.unitId===t&&r.getSheetId()===n:!1}_updateArrayFormulaRangeShape(t,n){this._checkCurrentSheet(t,n)&&this._previousShape&&this._refreshArrayFormulaRangeShape(t)}_refreshArrayFormulaRangeShapeByRow(t,n,o){if(!this._checkCurrentSheet(t,n)||!this._previousShape)return;const{startRow:r,endRow:s,startColumn:i,endColumn:c}=this._previousShape.getRange();for(let d=0;d<o.length;d++){const{row:f}=o[d];if(r>=f){const S={startRow:r,endRow:s,startColumn:i,endColumn:c};this._refreshArrayFormulaRangeShape(t,S);break}}}};qe=kn([Ie(1,a.Inject(x.SheetInterceptorService)),Ie(2,a.Inject(T.FormulaDataModel)),Ie(3,a.Inject(a.ThemeService)),Ie(4,j.IRenderManagerService),Ie(5,a.Inject(N.SheetSkeletonManagerService)),Ie(6,a.ICommandService),Ie(7,a.ILogService)],qe);var wn=Object.getOwnPropertyDescriptor,An=(e,t,n,o)=>{for(var r=o>1?void 0:o?wn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Ot=(e,t)=>(n,o)=>t(n,o,e);const xn={tl:{size:6,color:"#409f11"}};let Ye=class extends a.RxDisposable{constructor(e,t){super(),this._sheetInterceptorService=e,this._formulaDataModel=t,this.disposeWithMe(this._sheetInterceptorService.intercept(x.INTERCEPTOR_POINT.CELL_CONTENT,{effect:a.InterceptorEffectEnum.Style,handler:(n,o,r)=>{var c,d,f,S;const s=(S=(f=(d=(c=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:c[o.unitId])==null?void 0:d[o.subUnitId])==null?void 0:f[o.row])==null?void 0:S[o.col];return!T.extractFormulaError(n,!!s)||!n||(n===o.rawData&&(n={...o.rawData}),n.markers={...n==null?void 0:n.markers,...xn}),r(n)},priority:10}))}};Ye=An([Ot(0,a.Inject(x.SheetInterceptorService)),Ot(1,a.Inject(T.FormulaDataModel))],Ye);function Pn(){const e=l.useDependency(ge.TriggerCalculationController),t=l.useDependency(a.ICommandService),n=l.useObservable(e.progress$),o=E.useCallback(()=>{t.executeCommand(T.SetFormulaCalculationStopMutation.id)},[t]),r=E.useCallback(()=>{e.clearProgress()},[e]);return y.jsx(l.ProgressBar,{progress:n,onTerminate:o,onClearProgress:r})}function Ln(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName"&&n!=="Table").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function Nt(e){if(!e.require&&!e.repeat)return`[${e.name}]`;if(e.require&&!e.repeat)return e.name;if(!e.require&&e.repeat)return`[${e.name},...]`;if(e.require&&e.repeat)return`${e.name},...`}function Dt(e){const{prefix:t,value:n}=e;return y.jsxs("div",{children:[y.jsxs("span",{children:[t,"("]}),n&&n.map((o,r)=>y.jsxs("span",{children:[y.jsx("span",{children:Nt(o)}),r===n.length-1?"":","]},r)),")"]})}function $e(e){const{className:t,value:n,title:o}=e;return y.jsxs("div",{className:"univer-mb-2 univer-text-xs",children:[y.jsx("div",{className:B.clsx("univer-mb-2 univer-font-medium univer-text-gray-500 dark:!univer-text-gray-300",t),children:o}),y.jsx("div",{className:"univer-break-all univer-text-gray-900 dark:!univer-text-white",children:n})]})}function $n(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;const[o,r]=E.useState([]),[s,i]=E.useState(t.functionParameter),[c,d]=E.useState(-1);return y.jsxs("div",{children:[y.jsx("div",{className:B.clsx("univer-h-[364px] univer-overflow-y-auto",B.scrollbarClassName),children:s.map((f,S)=>y.jsxs("div",{children:[y.jsx("div",{className:"univer-text-sm",children:f.name}),y.jsx("div",{className:"univer-mb-2 univer-mt-1"})]},S))}),y.jsx("div",{className:B.clsx("univer-flex-1 univer-p-3",B.borderLeftClassName),children:y.jsx($e,{title:c===-1?y.jsx(Dt,{prefix:t.functionName,value:s}):s[c].name,value:c===-1?t.description:s[c].detail})})]})}function ye({ref:e,...t}){const{icon:n,id:o,className:r,extend:s,...i}=t,c=`univerjs-icon univerjs-icon-${o} ${r||""}`.trim(),d=E.useRef(`_${Un()}`);return kt(n,`${o}`,{defIds:n.defIds,idSuffix:d.current},{ref:e,className:c,...i},s)}function kt(e,t,n,o,r){return E.createElement(e.tag,{key:t,...Fn(e,n,r),...o},(Wn(e,n).children||[]).map((s,i)=>kt(s,`${t}-${e.tag}-${i}`,n,void 0,r)))}function Fn(e,t,n){const o={...e.attrs};n!=null&&n.colorChannel1&&o.fill==="colorChannel1"&&(o.fill=n.colorChannel1),e.tag==="mask"&&o.id&&(o.id=o.id+t.idSuffix),Object.entries(o).forEach(([s,i])=>{s==="mask"&&typeof i=="string"&&(o[s]=i.replace(/url\(#(.*)\)/,`url(#$1${t.idSuffix})`))});const{defIds:r}=t;return!r||r.length===0||(e.tag==="use"&&o["xlink:href"]&&(o["xlink:href"]=o["xlink:href"]+t.idSuffix),Object.entries(o).forEach(([s,i])=>{typeof i=="string"&&(o[s]=i.replace(/url\(#(.*)\)/,`url(#$1${t.idSuffix})`))})),o}function Wn(e,t){var o;const{defIds:n}=t;return!n||n.length===0?e:e.tag==="defs"&&((o=e.children)!=null&&o.length)?{...e,children:e.children.map(r=>typeof r.attrs.id=="string"&&n&&n.includes(r.attrs.id)?{...r,attrs:{...r.attrs,id:r.attrs.id+t.idSuffix}}:r)}:e}function Un(){return Math.random().toString(36).substring(2,8)}ye.displayName="UniverIcon";const Vn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},wt=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"check-mark-icon",ref:n,icon:Vn}))});wt.displayName="CheckMarkIcon";const Hn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},At=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"close-icon",ref:n,icon:Hn}))});At.displayName="CloseIcon";const Bn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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 0.866699 5.9313 0.866699H10.069C10.4004 0.866699 10.669 1.13533 10.669 1.4667C10.669 1.79807 10.4004 2.0667 10.069 2.0667H5.9313C5.59993 2.0667 5.3313 1.79807 5.3313 1.4667Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M1.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.64443C14.8999 3.9758 14.6312 4.24443 14.2999 4.24443H1.69985C1.36848 4.24443 1.09985 3.9758 1.09985 3.64443Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M6.12398 8.30171C6.35829 8.0674 6.73819 8.0674 6.97251 8.30171L8.00007 9.32928L9.02764 8.30171C9.26195 8.0674 9.64185 8.0674 9.87617 8.30171C10.1105 8.53603 10.1105 8.91593 9.87617 9.15024L8.8486 10.1778L9.87617 11.2054C10.1105 11.4397 10.1105 11.8196 9.87617 12.0539C9.64185 12.2882 9.26195 12.2882 9.02764 12.0539L8.00007 11.0263L6.97251 12.0539C6.73819 12.2882 6.35829 12.2882 6.12398 12.0539C5.88966 11.8196 5.88966 11.4397 6.12398 11.2054L7.15154 10.1778L6.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=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"delete-icon",ref:n,icon:Bn}))});xt.displayName="DeleteIcon";const Kn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},Pt=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"increase-icon",ref:n,icon:Kn}))});Pt.displayName="IncreaseIcon";const jn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},Lt=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"more-icon",ref:n,icon:jn}))});Lt.displayName="MoreIcon";const qn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",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"}}]},$t=E.forwardRef(function(t,n){return E.createElement(ye,Object.assign({},t,{id:"select-range-icon",ref:n,icon:qn}))});$t.displayName="SelectRangeIcon";function Yn(e){const{onChange:t}=e,n="-1",[o,r]=E.useState(""),[s,i]=E.useState([]),[c,d]=E.useState(0),[f,S]=E.useState(n),[p,h]=E.useState(0),[g,u]=E.useState(null),m=l.useDependency(ge.IDescriptionService),C=l.useDependency(a.LocaleService),_=l.useDependency(l.ISidebarService),I=l.useObservable(_.sidebarOptions$),R=Ln(T.FunctionType,C);R.unshift({label:C.t("formula.moreFunctions.allFunctions"),value:n});const D=C.t("formula.prompt.required"),v=C.t("formula.prompt.optional");E.useEffect(()=>{W(n)},[]),E.useEffect(()=>{k(0)},[s]),E.useEffect(()=>{I!=null&&I.visible&&(r(""),i([]),d(0),S(n),h(0),u(null),W(n))},[I]);const M=O=>{if(o.trim()==="")return O;const L=new RegExp(`(${o.toLocaleUpperCase()})`);return O.split(L).filter(Boolean).map((w,V)=>w.match(L)?y.jsx("span",{className:"univer-text-red-500",children:w},V):w)},k=O=>{if(s.length===0){u(null);return}h(O);const L=m.getFunctionInfo(s[O].name);if(!L){u(null);return}u(L),t(L)};function W(O){S(O);const L=m.getSearchListByType(+O);i(L)}function U(O){r(O);const L=m.getSearchListByName(O);i(L)}function P(O){if(O.stopPropagation(),O.key==="ArrowDown"){const L=c+1;d(L===s.length?0:L)}else if(O.key==="ArrowUp"){const L=c-1;d(L===-1?s.length-1:L)}else O.key==="Enter"&&k(c)}const F=O=>{d(O)},A=()=>{d(-1)};return y.jsxs("div",{children:[y.jsxs("div",{className:"univer-flex univer-items-center univer-justify-between univer-gap-2",children:[y.jsx(B.Select,{value:f,options:R,onChange:W}),y.jsx(B.Input,{placeholder:C.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:P,value:o,onChange:U,size:"small",allowClear:!0})]}),s.length>0&&y.jsx("ul",{className:B.clsx("univer-mb-0 univer-mt-2 univer-box-border univer-max-h-72 univer-w-full univer-select-none univer-list-none univer-overflow-y-auto univer-rounded univer-p-3 univer-outline-none",B.borderClassName,B.scrollbarClassName),onKeyDown:P,tabIndex:-1,children:s.map(({name:O},L)=>y.jsxs("li",{className:B.clsx("univer-relative univer-box-border univer-cursor-pointer univer-rounded univer-px-7 univer-py-1 univer-text-sm univer-text-gray-900 univer-transition-colors dark:!univer-text-white",{"univer-bg-gray-200 dark:!univer-bg-gray-600":c===L}),onMouseEnter:()=>F(L),onMouseLeave:A,onClick:()=>k(L),children:[p===L&&y.jsx(wt,{className:"univer-absolute univer-left-1.5 univer-top-1/2 univer-inline-flex -univer-translate-y-1/2 univer-text-base univer-text-primary-600"}),y.jsx("span",{className:"univer-block",children:M(O)})]},L))}),g&&y.jsxs("div",{className:B.clsx("univer-mx-0 univer-my-2 univer-overflow-y-auto",B.scrollbarClassName),children:[y.jsx($e,{title:g.functionName,value:g.description}),y.jsx($e,{title:C.t("formula.moreFunctions.syntax"),value:y.jsx(Dt,{prefix:g.functionName,value:g.functionParameter})}),y.jsx($e,{title:C.t("formula.prompt.helpExample"),value:`${g.functionName}(${g.functionParameter.map(O=>O.example).join(",")})`}),g.functionParameter&&g.functionParameter.map(O=>y.jsx($e,{title:O.name,value:`${O.require?D:v} ${O.detail}`},O.name))]})]})}function zn(){const e=N.useActiveWorkbook(),[t,n]=E.useState(!0),[o,r]=E.useState(!1),[s,i]=E.useState(null);l.useDependency(N.IEditorBridgeService);const c=l.useDependency(a.LocaleService),d=l.useDependency(J.IEditorService),f=l.useDependency(a.IUniverInstanceService),S=l.useDependency(a.ICommandService);function p(){n(!t),r(!o)}function h(){const g=x.getSheetCommandTarget(f);if(!g)return;S.executeCommand(N.SetCellEditVisibleOperation.id,{visible:!0,unitId:g.unitId,eventType:j.DeviceInputEventType.Dblclick});const u=d.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),m=d.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),C=`=${s==null?void 0:s.functionName}(`;u==null||u.replaceText(C),m==null||m.replaceText(C,!1)}return y.jsxs("div",{"data-u-comp":"sheets-formula-functions-panel",className:"univer-box-border univer-flex univer-h-full univer-flex-col univer-justify-between univer-py-2",children:[t&&y.jsx(Yn,{onChange:i}),o&&y.jsx($n,{functionInfo:s,onChange:()=>{}}),y.jsxs("div",{className:"univer-flex univer-justify-end",children:[o&&y.jsx(B.Button,{variant:"primary",onClick:p,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.t("formula.moreFunctions.next")}),o&&y.jsx(B.Button,{onClick:p,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.t("formula.moreFunctions.prev")}),t&&!!e&&y.jsx(B.Button,{variant:"primary",onClick:h,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.t("formula.moreFunctions.confirm")})]})]})}function Gn(e){return{id:ce.id,title:"SUM",icon:"SumIcon",type:l.MenuItemType.BUTTON,params:{value:"SUM"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Zn(e){return{id:ce.id,title:"COUNT",icon:"CntIcon",type:l.MenuItemType.BUTTON,params:{value:"COUNT"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Xn(e){return{id:ce.id,title:"AVERAGE",icon:"AvgIcon",type:l.MenuItemType.BUTTON,params:{value:"AVERAGE"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Qn(e){return{id:ce.id,title:"MAX",icon:"MaxIcon",type:l.MenuItemType.BUTTON,params:{value:"MAX"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function Jn(e){return{id:ce.id,title:"MIN",icon:"MinIcon",type:l.MenuItemType.BUTTON,params:{value:"MIN"},hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function er(e){return{id:He.id,title:"formula.insert.more",tooltip:"formula.insert.tooltip",type:l.MenuItemType.BUTTON,hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],worksheetTypes:[x.WorksheetEditPermission,x.WorksheetSetCellValuePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint]})}}function tr(e){return e.get(a.IUniverInstanceService).getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).pipe(q.switchMap(o=>o&&e.get(l.IClipboardInterfaceService)?new q.Observable(s=>s.next(!e.get(l.IClipboardInterfaceService).supportClipboard)):q.of(!0)))}function nr(e){return{id:We.id,type:l.MenuItemType.BUTTON,title:"formula.operation.copyFormulaOnly",disabled$:N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookCopyPermission],worksheetTypes:[x.WorksheetCopyPermission],rangeTypes:[x.RangeProtectionPermissionViewPoint]}),hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET)}}function rr(e){return{id:Ue.id,type:l.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:tr(e).pipe(q.combineLatestWith(N.getCurrentRangeDisable$(e,{workbookTypes:[x.WorkbookEditablePermission],rangeTypes:[x.RangeProtectionPermissionEditPoint],worksheetTypes:[x.WorksheetSetCellValuePermission,x.WorksheetEditPermission]})),q.map(([t,n])=>t||n)),hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET)}}const or={[l.RibbonFormulasGroup.BASIC]:{[`${ce.id}.sum`]:{order:0,menuItemFactory:Gn},[`${ce.id}.count`]:{order:1,menuItemFactory:Zn},[`${ce.id}.average`]:{order:2,menuItemFactory:Xn},[`${ce.id}.max`]:{order:3,menuItemFactory:Qn},[`${ce.id}.min`]:{order:4,menuItemFactory:Jn}},[l.RibbonFormulasGroup.OTHERS]:{[He.id]:{order:0,menuItemFactory:er}},[N.COPY_SPECIAL_MENU_ID]:{[We.id]:{order:0,menuItemFactory:nr}},[N.PASTE_SPECIAL_MENU_ID]:{[Ue.id]:{order:4,menuItemFactory:rr}}},sr="meta_key_ctrl_And_Shift";function ir(e){return e.getContextValue(a.FOCUSING_DOC)&&e.getContextValue(a.FOCUSING_UNIVER_EDITOR)}const ze=[l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP,l.KeyCode.ARROW_LEFT,l.KeyCode.ARROW_RIGHT],cr=[...ze,l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ESC];function ar(){const e=[];for(const t of cr)e.push({id:Ee.id,binding:t,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t}});return e}function lr(){const e=[];for(const t of ze)e.push({id:Ee.id,binding:t|l.MetaKeys.SHIFT,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.SHIFT}});return e}function ur(){const e=[];for(const t of ze)e.push({id:Ee.id,binding:t|l.MetaKeys.CTRL_COMMAND,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.CTRL_COMMAND}});return e}function dr(){const e=[];for(const t of ze)e.push({id:Ee.id,binding:t|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:n=>N.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:sr}});return e}const fr={id:it.id,binding:l.KeyCode.F4,preconditions:e=>N.whenFormulaEditorActivated(e)};function hr(){const e=[];for(const t of[l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP])e.push({id:Ee.id,binding:t,preconditions:n=>ir(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}const gr={id:ge.QuickSumCommand.id,binding:l.MetaKeys.ALT|l.KeyCode.EQUAL,preconditions:N.whenSheetEditorFocused,mac:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.ALT|l.KeyCode.EQUAL,description:"shortcut.sheets-formula-ui.quick-sum",group:"4_sheet-edit"};var Sr=Object.getOwnPropertyDescriptor,pr=(e,t,n,o)=>{for(var r=o>1?void 0:o?Sr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Re=(e,t)=>(n,o)=>t(n,o,e);let Ge=class extends a.Disposable{constructor(e,t,n,o,r,s,i){super(),this._injector=e,this._menuManagerService=t,this._commandService=n,this._shortcutService=o,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(or)}_registerCommands(){[We,Ue,ce,He,yt,mt,Ee,it].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_registerShortcuts(){[...ar(),...lr(),...ur(),...dr(),...hr(),gr,fr].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(N.SheetsUIPart.FORMULA_AUX,()=>l.connectInjector(Pn,this._injector))),this._componentManager.register(It,zn)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,[qe]))}};Ge=pr([Re(0,a.Inject(a.Injector)),Re(1,l.IMenuManagerService),Re(2,a.ICommandService),Re(3,l.IShortcutService),Re(4,l.IUIPartsService),Re(5,j.IRenderManagerService),Re(6,a.Inject(l.ComponentManager))],Ge);var vr=Object.getOwnPropertyDescriptor,mr=(e,t,n,o)=>{for(var r=o>1?void 0:o?vr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},lt=(e,t)=>(n,o)=>t(n,o,e);let Ze=class extends a.Disposable{constructor(e,t,n){super(),this._imageFormulaCellInterceptorController=e,this._renderManagerService=t,this._univerInstanceService=n,this._imageFormulaCellInterceptorController.registerRefreshRenderFunction(()=>{const o=this._univerInstanceService.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;const r=this._renderManagerService.getRenderById(o.getUnitId());if(!r)return;r.with(N.SheetSkeletonManagerService).reCalculate();const s=r.mainComponent;s&&s.makeDirty()})}};Ze=mr([lt(0,a.Inject(ge.ImageFormulaCellInterceptorController)),lt(1,j.IRenderManagerService),lt(2,a.IUniverInstanceService)],Ze);class ut{constructor(){Y(this,"_currentSelector$",new q.BehaviorSubject(null));Y(this,"currentSelector$",this._currentSelector$.asObservable())}showRangeSelectorDialog(t){const n=t.callback,o=new Promise(r=>{t.callback=s=>{r(s),n(s)}});return this._currentSelector$.next(t),o}}var Cr=Object.getOwnPropertyDescriptor,_r=(e,t,n,o)=>{for(var r=o>1?void 0:o?Cr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},De=(e,t)=>(n,o)=>t(n,o,e);$.RefSelectionsRenderService=class extends N.BaseSelectionRenderService{constructor(n,o,r,s,i,c,d){super(o,r,s,i,c);Y(this,"_workbookSelections");Y(this,"_eventDisposables");this._context=n,this._contextService=c,this._refSelectionsService=d,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Er(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(n){this._remainLastEnabled=n}setSkipLastEnabled(n){this._skipLastEnabled=n}clearLastSelection(){const n=this._selectionControls[this._selectionControls.length-1];n&&(n.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),a.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var n;(n=this._eventDisposables)==null||n.dispose(),this._eventDisposables=null}disableSelectionChanging(){this._disableSelectionChanging()}_initCanvasEventListeners(){const n=this._getSheetObject(),{spreadsheetRowHeader:o,spreadsheetColumnHeader:r,spreadsheet:s,spreadsheetLeftTopPlaceholder:i}=n,{scene:c}=this._context,d=new a.DisposableCollection;return d.add(s==null?void 0:s.onPointerDown$.subscribeEvent((f,S)=>{this.inRefSelectionMode()&&(this._onPointerDown(f,s.zIndex+1,a.RANGE_TYPE.NORMAL,this._getActiveViewport(f)),f.button!==2&&S.stopPropagation())})),d.add(o==null?void 0:o.onPointerDown$.subscribeEvent((f,S)=>{if(!this.inRefSelectionMode())return;const p=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:h}=N.getCoordByOffset(f.offsetX,f.offsetY,c,p);N.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.ROW)||(this._onPointerDown(f,(s.zIndex||1)+1,a.RANGE_TYPE.ROW,this._getActiveViewport(f),j.ScrollTimerType.Y),f.button!==2&&S.stopPropagation())})),d.add(r==null?void 0:r.onPointerDown$.subscribeEvent((f,S)=>{if(!this.inRefSelectionMode())return;const p=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:h}=N.getCoordByOffset(f.offsetX,f.offsetY,c,p);N.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.COLUMN)||(this._onPointerDown(f,(s.zIndex||1)+1,a.RANGE_TYPE.COLUMN,this._getActiveViewport(f),j.ScrollTimerType.X),f.button!==2&&S.stopPropagation())})),d.add(i==null?void 0:i.onPointerDown$.subscribeEvent((f,S)=>{if(this._reset(),!this.inRefSelectionMode())return;const p=this._sheetSkeletonManagerService.getCurrent().skeleton,h=N.getAllSelection(p);this._addSelectionControlByModelData(h),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const g=c.onPointerUp$.subscribeEvent(()=>{g.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});f.button!==2&&S.stopPropagation()})),d}_addSelectionControlByModelData(n){var c;const o=this._skeleton,r=(c=n.style)!=null?c:N.genNormalSelectionStyle(this._themeService),s=this._scene;return n.style=r,this.newSelectionControl(s,o,n)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(n=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(n||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(n=>{this._updateSelections(n,x.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(n=>{this._updateSelections(n,x.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(n=>{this._updateSelections(n,x.SelectionMoveType.MOVE_END)}))}_updateSelections(n,o){const s=this._context.unit.getActiveSheet().getSheetId();n.length!==0&&this._workbookSelections.setSelections(s,n.map(i=>x.convertSelectionDataToRange(i)),o)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(n=>{var c;if(!n)return;const{skeleton:o}=n,{scene:r}=this._context,s=r.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&((c=this._skeleton.worksheet)==null?void 0:c.getSheetId())!==o.worksheet.getSheetId()&&this._reset(),this._changeRuntime(o,r,s);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(n){const o=this._getSheetObject();return o==null?void 0:o.scene.getActiveViewportByCoord(j.Vector2.FromArray([n.offsetX,n.offsetY]))}_getSheetObject(){return N.getSheetObject(this._context.unit,this._context)}_onPointerDown(n,o=0,r=a.RANGE_TYPE.NORMAL,s,i=j.ScrollTimerType.ALL){var F;this._rangeType=r;const c=this._skeleton,d=this._scene;if(!d||!c)return;s&&(this._activeViewport=s);const{offsetX:f,offsetY:S}=n,p=d.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!p)return;const h=d.getCoordRelativeToViewport(j.Vector2.FromArray([f,S])),{x:g,y:u}=h;this._startViewportPosX=g,this._startViewportPosY=u;const m=d.getScrollXYInfoByViewport(h),{scaleX:C,scaleY:_}=d.getAncestorScale(),I=this._skeleton.getCellByOffset(g,u,C,_,m);if(!I)return;switch(r){case a.RANGE_TYPE.NORMAL:break;case a.RANGE_TYPE.ROW:I.startColumn=0,I.endColumn=this._skeleton.getColumnCount()-1;break;case a.RANGE_TYPE.COLUMN:I.startRow=0,I.endRow=this._skeleton.getRowCount()-1;break;case a.RANGE_TYPE.ALL:I.startRow=0,I.startColumn=0,I.endRow=this._skeleton.getRowCount()-1,I.endColumn=this._skeleton.getColumnCount()-1}let R={range:I,primary:I,style:null};(I.isMerged||I.isMergedMainCell)&&(R={range:{...I,startRow:I.startRow,endRow:I.startRow,startColumn:I.startColumn,endColumn:I.startColumn},primary:{...I,actualRow:I.startRow,actualColumn:I.startColumn,startRow:I.startRow,endRow:I.startRow,startColumn:I.startColumn,endColumn:I.startColumn},style:null}),R.range.rangeType=r;const D=N.attachSelectionWithCoord(R,this._skeleton);this._startRangeWhenPointerDown={...D.rangeWithCoord};const v={...D.rangeWithCoord,rangeType:r};let M=this.getActiveSelectionControl();const k=this.getSelectionControls();for(const A of k){if(n.button===2&&a.Rectangle.contains(A.model,v)){M=A;return}if(A.model.isEqual(v)){M=A;break}}this._checkClearPreviousControls(n);const W=M==null?void 0:M.model.currentCell,U=n.shiftKey&&W,P=this._remainLastEnabled&&!n.ctrlKey&&!n.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;U&&W?this._makeSelectionByTwoCells(W,v,c,r,M):P&&M?M.updateRangeBySelectionWithCoord(D):M=this.newSelectionControl(d,c,R);for(let A=0;A<this.getSelectionControls().length-1;A++)this.getSelectionControls()[A].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),d.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(F=d.getTransformer())==null||F.clearSelectedObjects(),this._setupPointerMoveListener(p,M,r,i,g,u),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=d.onPointerUp$.subscribeEvent(()=>{var A;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(A=this._escapeShortcutDisposable)==null||A.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(n,o,r){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:c}=o,d=new N.SelectionControl(n,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:c}),f=N.attachSelectionWithCoord(r,o);return d.updateRangeBySelectionWithCoord(f),this._selectionControls.push(d),d.setControlExtension({skeleton:o,scene:n,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),d}},$.RefSelectionsRenderService=_r([De(1,a.Inject(a.Injector)),De(2,a.Inject(a.ThemeService)),De(3,l.IShortcutService),De(4,a.Inject(N.SheetSkeletonManagerService)),De(5,a.IContextService),De(6,x.IRefSelectionsService)],$.RefSelectionsRenderService);function Er(e){const t=N.genNormalSelectionStyle(e);return t.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},t}const dt=(e,t,n=!0)=>{let o=-1;return e.reduce((r,s,i)=>{if(r.isFinish)return r;const c=r.currentIndex;if(typeof s!="string")r.currentIndex+=s.token.length;else{const d=s.length;r.currentIndex+=d}return(n?r.currentIndex===t:t>c&&t<=r.currentIndex)&&(o=i,r.isFinish=!0),r},{currentIndex:0,isFinish:!1}),o},Ft=(e,t)=>{const n=e[t];let o=-1;if(!n||typeof n=="string"||n.nodeType!==T.sequenceNodeType.REFERENCE)return-1;for(let r=0;r<=t;r++){const s=e[r];typeof s!="string"&&s.nodeType===T.sequenceNodeType.REFERENCE&&o++}return o},Ir=(e,t=100)=>{E.useEffect(()=>{let n=null;const o=()=>{n===null&&(n=window.setTimeout(()=>{e(),n=null},t))};return window.addEventListener("scroll",o),window.addEventListener("resize",o),()=>{n!==null&&clearTimeout(n),window.removeEventListener("scroll",o),window.removeEventListener("resize",o)}},[e,t])};function Wt(e,t,n){const o=l.useDependency(J.IEditorService),r=E.useMemo(()=>new q.BehaviorSubject({left:-999,top:-999,right:-999,bottom:-999}),[]),s=l.useDependency(l.ISidebarService),i=l.useDependency(a.IUniverInstanceService),c=l.useEvent(()=>{var R;const d=o.getEditor(e);if(!d)return;const f=d.getBoundingClientRect(),{marginTop:S=0,marginBottom:p=0}=d.getDocumentData().documentStyle,h=d.getSkeleton();if(!h)return;const g=(R=h.getSkeletonData())==null?void 0:R.pages[0].height;let{left:u,top:m,right:C,bottom:_}=f;m=m+S,_=g?m+g:_-p;const I=r.getValue();if(!(I.left===u&&I.top===m&&I.right===C&&I.bottom===_))return r.next({left:u-1,right:C+1,top:m-1,bottom:_+1}),f});return E.useEffect(()=>{t&&c()},[e,o,i.unitAdded$,c,t,...n!=null?n:[]]),Ir(c),E.useEffect(()=>{const d=s.scrollEvent$.pipe(q.throttleTime(100)).subscribe(c);return()=>{d.unsubscribe()}},[]),[r,c]}const Te=e=>{const t=E.useRef(e);return t.current=e,t},yr=(e,t,n)=>{const o=l.useDependency(Ve),r=l.useDependency(ge.IDescriptionService),s=l.useDependency(T.LexerTreeBuilder),[i,c]=E.useState(),[d,f]=E.useState(-1),[S,p]=E.useState(!0),h=Te(S),g=E.useRef(t);g.current=t;const u=()=>{c(void 0),f(-1),p(!1)};return E.useEffect(()=>{const m=s.sequenceNodesBuilder(t.slice(1));o.setSequenceNodes(m!=null?m:[])},[t]),E.useEffect(()=>{if(n&&e){const m=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(_=>{if(_.textRanges.length===1){const[I]=_.textRanges;if(I.collapsed&&h.current){const{startOffset:R}=I,D=o.getCurrentSequenceNodeIndex(R-2),v=o.getCurrentSequenceNodeByIndex(D),M=o.getCurrentSequenceNodeByIndex(D+1);if(v)if(typeof v!="string"&&v.nodeType===3&&!r.hasDefinedNameDescription(v.token.trim())&&M===T.matchToken.OPEN_BRACKET){const k=r.getFunctionInfo(v.token);c(k),f(-1);return}else{const k=s.getFunctionAndParameter(`${g.current}A`,R-1);if(k){const{functionName:W,paramIndex:U}=k,P=r.getFunctionInfo(W);c(P),f(U);return}}}}c(void 0),f(-1)}),C=n.selectionChange$.pipe(q.filter(_=>_.textRanges.length===1),q.map(_=>_.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{p(!0)});return()=>{m.unsubscribe(),C.unsubscribe()}}},[n,e]),E.useEffect(()=>{e||u()},[e]),{functionInfo:i,paramIndex:d,reset:u}},Rr=({onClick:e})=>y.jsx("div",{className:"univer-z-[15] univer-box-border univer-h-[18px] univer-cursor-pointer univer-overflow-visible univer-whitespace-nowrap univer-rounded-l univer-border univer-border-r-0 univer-border-gray-600 univer-bg-primary-600 univer-p-0.5 univer-text-xs univer-font-bold univer-leading-[13px] univer-text-white",onClick:e,children:"?"}),ft=({className:e,title:t,value:n})=>y.jsxs("div",{className:"univer-my-2",children:[y.jsx("div",{className:B.clsx("univer-mb-2 univer-text-sm univer-font-medium univer-text-gray-900 dark:!univer-text-white",e),children:t}),y.jsx("div",{className:"univer-whitespace-pre-wrap univer-break-words univer-text-xs univer-text-gray-500",children:n})]}),Tr=e=>{const{prefix:t,value:n,active:o,onClick:r}=e;return y.jsxs("div",{children:[y.jsxs("span",{children:[t,"("]}),n&&n.map((s,i)=>y.jsxs("span",{children:[y.jsx("span",{className:o===i?"univer-text-primary-500":"",onClick:()=>r(i),children:Nt(s)}),i===n.length-1?"":","]},s.name)),")"]})},Ut=()=>{};function br(e){const{onParamsSwitch:t=Ut,onClose:n=Ut,isFocus:o,editor:r,formulaText:s}=e,{functionInfo:i,paramIndex:c,reset:d}=yr(o,s,r),f=l.useDependency(N.IEditorBridgeService),S=!l.useObservable(f.helpFunctionVisible$),[p,h]=E.useState(!0),g=l.useDependency(a.LocaleService),u=g.t("formula.prompt.required"),m=g.t("formula.prompt.optional"),C=r.getEditorId(),[_]=Wt(C,!!i,[i,c]);function I(v){t&&t(v)}const R=l.useEvent(v=>{f.helpFunctionVisible$.next(!v)}),D=()=>{R(!0),n()};return i?S?y.jsx(l.RectPopup,{portal:!0,anchorRect$:_,direction:"left-center",children:y.jsx(Rr,{onClick:()=>R(!1)})},"hidden"):y.jsx(l.RectPopup,{portal:!0,onClickOutside:()=>d(),anchorRect$:_,direction:"vertical",children:y.jsxs("div",{className:B.clsx("univer-m-0 univer-box-border univer-w-[250px] univer-select-none univer-list-none univer-rounded-lg univer-bg-white univer-leading-5 univer-shadow-md univer-outline-none dark:!univer-bg-gray-900",B.borderClassName),children:[y.jsxs("div",{className:B.clsx("univer-wrap-anywhere univer-box-border univer-flex univer-items-center univer-justify-between univer-px-4 univer-py-3 univer-text-xs univer-font-medium univer-text-gray-900 dark:!univer-text-white",B.borderTopClassName),children:[y.jsx(Tr,{prefix:i.functionName,value:i.functionParameter,active:c,onClick:I}),y.jsxs("div",{className:"univer-flex",children:[y.jsx("div",{className:"univer-ml-2 univer-flex univer-h-6 univer-w-6 univer-cursor-pointer univer-items-center univer-justify-center univer-rounded univer-bg-transparent univer-p-0 univer-text-xs univer-text-gray-500 univer-outline-none univer-transition-colors hover:univer-bg-gray-200 dark:hover:!univer-bg-gray-600",style:{transform:p?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!p),children:y.jsx(Lt,{})}),y.jsx("div",{className:"univer-ml-2 univer-flex univer-h-6 univer-w-6 univer-cursor-pointer univer-items-center univer-justify-center univer-rounded univer-bg-transparent univer-p-0 univer-text-xs univer-text-gray-600 univer-outline-none univer-transition-colors hover:univer-bg-gray-300 dark:!univer-text-gray-200 dark:hover:!univer-bg-gray-600",onClick:D,children:y.jsx(At,{})})]})]}),y.jsx("div",{className:B.clsx("univer-box-border univer-max-h-[350px] univer-overflow-y-auto univer-px-4 univer-pb-3 univer-pt-0",B.scrollbarClassName),style:{height:p?"unset":0,padding:p?"revert-layer":0},children:y.jsxs("div",{className:"univer-mt-3",children:[y.jsx(ft,{title:g.t("formula.prompt.helpExample"),value:`${i.functionName}(${i.functionParameter.map(v=>v.example).join(",")})`}),y.jsx(ft,{title:g.t("formula.prompt.helpAbstract"),value:i.description}),i&&i.functionParameter&&i.functionParameter.map((v,M)=>y.jsx(ft,{className:c===M?"univer-text-primary-500":"",title:v.name,value:`${v.require?u:m} ${v.detail}`},M))]})})]})},"show"):null}const Mr=e=>{const t=l.useDependency(J.IEditorService);return l.useEvent(o=>{var r,s;if(e){t.focus(e.getEditorId());const i=[...e.getSelectionRanges()];if(a.Tools.isDefine(o))e.setSelectionRanges([{startOffset:o,endOffset:o}]);else if(!i.length&&!e.docSelectionRenderService.isOnPointerEvent){const c=(s=(r=e.getDocumentData().body)==null?void 0:r.dataStream)!=null?s:`\r
2
+ `,d=Math.max(c.length-2,0);e.setSelectionRanges([{startOffset:d,endOffset:d}])}else e.setSelectionRanges(i)}})};function Or(e){var r,s;const n=e.get(a.IUniverInstanceService).getCurrentUniverDocInstance();return n!=null&&n.getBody()?{dataStream:(s=(r=n.getBody())==null?void 0:r.dataStream)!=null?s:"",offset:0}:void 0}var Se=(e=>(e[e.NOT_SELECT=0]="NOT_SELECT",e[e.NEED_ADD=1]="NEED_ADD",e[e.CAN_EDIT=2]="CAN_EDIT",e[e.EDIT_OTHER_SHEET_REFERENCE=3]="EDIT_OTHER_SHEET_REFERENCE",e[e.EDIT_OTHER_WORKBOOK_REFERENCE=4]="EDIT_OTHER_WORKBOOK_REFERENCE",e))(Se||{});function Nr(e){var k;const{editorId:t,isFocus:n,disableOnClick:o,unitId:r,subUnitId:s}=e,i=l.useDependency(j.IRenderManagerService),c=l.useDependency(a.IUniverInstanceService),d=i.getRenderById(r),f=i.getRenderById(t),S=f==null?void 0:f.with(J.DocSelectionRenderService),p=l.useDependency(pt.DocSelectionManagerService),h=l.useDependency(a.Injector),[g,u]=E.useState(0),m=l.useDependency(T.LexerTreeBuilder),C=E.useRef(!0),_=d==null?void 0:d.with($.RefSelectionsRenderService),I=Te(g),R=c.getUnit(r,a.UniverInstanceType.UNIVER_SHEET),D=R==null?void 0:R.getSheetBySheetId(s),v=l.useEvent(W=>{_&&_.setSkipLastEnabled(W===1||W===3||W===4),I.current=W,u(W)}),M=l.useEvent(()=>{var Q,ne,ae;const W=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!W)return;const U=W.getActiveSheet(),P=S==null?void 0:S.getActiveTextRange(),F=P!=null&&P.collapsed?P.startOffset:-1,A=Or(h);if(!A)return;const O=(Q=A==null?void 0:A.dataStream)==null?void 0:Q.slice(0,-2),L=((ne=m.sequenceNodesBuilder(O))!=null?ne:[]).map(G=>typeof G=="object"?G.nodeType===T.sequenceNodeType.REFERENCE?{...G,range:T.deserializeRangeWithSheetWithCache(G.token)}:{...G,range:void 0}:G),b=O[F-1],w=O[F],V=L.find(G=>typeof G=="object"&&G.nodeType===T.sequenceNodeType.REFERENCE&&F===G.endIndex+2),H=b&&T.matchRefDrawToken(b)&&(!w||T.isFormulaLexerToken(w)&&w!==T.matchToken.OPEN_BRACKET),K=!!V;if((O==null?void 0:O.substring(0,1))==="="&&(H||K))if(K){if(C.current)return;const{sheetName:G,unitId:ee}=V.range,ke=(ae=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:ae.getUnitId();ee&&ee!==ke?v(4):!G&&U.getSheetId()===(D==null?void 0:D.getSheetId())||G===U.getName()?v(2):v(3)}else C.current=!1,v(1);else v(0)});return E.useEffect(()=>{const W=p.textSelection$.pipe(q.filter(U=>U.unitId===t)).subscribe(()=>{M()});return()=>W.unsubscribe()},[M,p.textSelection$,t]),E.useEffect(()=>{n||(v(0),C.current=!0)},[n,v]),E.useEffect(()=>{var U;if(!o)return;const W=(U=f==null?void 0:f.mainComponent)==null?void 0:U.onPointerDown$.subscribeEvent(()=>{v(0),C.current=!0});return()=>W==null?void 0:W.unsubscribe()},[o,(k=f==null?void 0:f.mainComponent)==null?void 0:k.onPointerDown$,v]),E.useEffect(()=>{if(!n)return;const W=R==null?void 0:R.activeSheet$.subscribe(()=>{M()}),U=c.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>{M()});return()=>{W==null||W.unsubscribe(),U==null||U.unsubscribe()}},[M,n,R==null?void 0:R.activeSheet$,c.getCurrentTypeOfUnit$]),{isSelecting:g,isSelectingRef:I}}const Dr=()=>{const e=l.useDependency(T.LexerTreeBuilder);return E.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function kr(e,t,n){const o=new a.ColorKit(t).setAlpha(.05).toRgbString();return{id:n,strokeWidth:1,stroke:t,fill:o,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:e.getColorFromTheme("white")}}function Vt(e){var R,D,v;const{unitId:t,subUnitId:n,currentWorkbook:o,refSelections:r,editor:s,refSelectionsService:i,refSelectionsRenderService:c,sheetSkeletonManagerService:d,themeService:f,univerInstanceService:S}=e,p=o.getUnitId(),h=S.getUnit(t,a.UniverInstanceType.UNIVER_SHEET),g=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!g){i.setSelections(u);return}const m=g.getSheetId(),C=M=>{var k;return(k=h==null?void 0:h.getSheetBySheetName(M))==null?void 0:k.getSheetId()};if(!((R=d==null?void 0:d.getWorksheetSkeleton(m))==null?void 0:R.skeleton))return;const I=[];for(let M=0,k=r.length;M<k;M++){const W=r[M],{themeColor:U,token:P,refIndex:F,endIndex:A}=W,O=T.deserializeRangeWithSheet(P),{unitId:L,sheetName:b,range:w}=O,V=C(b);if(!V&&b||p!==t&&L!==p||L&&L!==p||V&&V!==m||!V&&m!==n)continue;const H=x.setEndForRange(w,g.getRowCount(),g.getColumnCount());H.unitId=t,H.sheetId=m,u.push({range:H,primary:null,style:kr(f,U,F.toString())}),I.push(A)}if(s){const M=(v=(D=s.getSelectionRanges())==null?void 0:D[0])==null?void 0:v.startOffset,k=I.findIndex(W=>W+2===M);k!==-1?c==null||c.setActiveSelectionIndex(k):c==null||c.resetActiveSelectionIndex()}return u}function wr(e,t){const n=l.useDependency(a.IUniverInstanceService),o=l.useDependency(a.ThemeService),r=l.useDependency(x.IRefSelectionsService),s=l.useDependency(j.IRenderManagerService),i=l.useObservable(E.useMemo(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[n])),c=i?s.getRenderById(i.getUnitId()):null,d=c==null?void 0:c.with($.RefSelectionsRenderService),f=c==null?void 0:c.with(N.SheetSkeletonManagerService),S=l.useEvent((p,h)=>{const g=n.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!g||d!=null&&d.selectionMoving)return;const u=Vt({unitId:e,subUnitId:t,currentWorkbook:g,refSelections:p,editor:h,refSelectionsService:r,refSelectionsRenderService:d,sheetSkeletonManagerService:f,themeService:o,univerInstanceService:n});if(!u)return;((d==null?void 0:d.getSelectionControls())||[]).length===u.length?d==null||d.resetSelectionsByModelData(u):r.setSelections(u)});return E.useEffect(()=>()=>{d==null||d.resetActiveSelectionIndex()},[d]),S}function Ht(e=""){const t=l.useDependency(ge.IDescriptionService),n=Ar(),o=l.useDependency(a.ICommandService),r=E.useMemo(()=>e.length,[e]);return l.useEvent((i,c,d=!0,f)=>{const S=i.getDocumentData(),p=i.getEditorId();if(!S)return[];const h=S.body;if(!h)return[];const g=h.dataStream.slice(0,h.dataStream.length-2),u={dataStream:"",...S.body};if(!g.startsWith(e))return[];if(c==null||c.length===0)return u.textRuns=[],o.syncExecuteCommand(J.ReplaceTextRunsCommand.id,{unitId:p,body:a.getBodySlice(u,0,u.dataStream.length-2)}),[];{const{textRuns:m,refSelections:C}=xr(t,n,c);r&&m.forEach(R=>{R.ed=R.ed+r,R.st=R.st+r}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},...m];const _=c.reduce((R,D)=>typeof D=="string"?`${R}${D}`:`${R}${D.token}`,"");u.dataStream=`${e}${_}\r
3
+ `;let I;if(d){I=i.getSelectionRanges();const R=u.dataStream.length-2+r;I.forEach(D=>{D.startOffset=Math.max(0,Math.min(D.startOffset,R)),D.endOffset=Math.max(0,Math.min(D.endOffset,R))})}return o.syncExecuteCommand(J.ReplaceTextRunsCommand.id,{unitId:p,body:a.getBodySlice(u,0,u.dataStream.length-2),textRanges:f!=null?f:I}),C}})}function Ar(){const e=l.useDependency(a.ThemeService),t=e.getCurrentTheme();return E.useMemo(()=>{const o=[e.getColorFromTheme("loop-color.1"),e.getColorFromTheme("loop-color.2"),e.getColorFromTheme("loop-color.3"),e.getColorFromTheme("loop-color.4"),e.getColorFromTheme("loop-color.5"),e.getColorFromTheme("loop-color.6"),e.getColorFromTheme("loop-color.7"),e.getColorFromTheme("loop-color.8"),e.getColorFromTheme("loop-color.9"),e.getColorFromTheme("loop-color.10"),e.getColorFromTheme("loop-color.11"),e.getColorFromTheme("loop-color.12")].map(c=>e.isValidThemeColor(c)?e.getColorFromTheme(c):c),r=e.getColorFromTheme("blue.700"),s=e.getColorFromTheme("jiqing.800"),i=e.getColorFromTheme("black");return{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}},[t])}function xr(e,t,n){const{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}=t,c=[],d=[],f=new Map;let S=0;for(let p=0,h=n.length;p<h;p++){const g=n[p];if(typeof g=="string"){const R=c[c.length-1],D=R?R.ed:0,v=D+g.length;c.push({st:D,ed:v,ts:{cl:{rgb:i},fs:11}});continue}if(e.hasDefinedNameDescription(g.token.trim())){c.push({st:g.startIndex,ed:g.endIndex+1,ts:{cl:{rgb:i},fs:11}});continue}const{startIndex:u,endIndex:m,nodeType:C,token:_}=g;let I="";if(C===T.sequenceNodeType.REFERENCE){if(f.has(_))I=f.get(_);else{const R=S%o.length;I=o[R],f.set(_,I),S++}d.push({refIndex:p,themeColor:I,token:_,startIndex:g.startIndex,endIndex:g.endIndex,index:d.length})}else C===T.sequenceNodeType.NUMBER?I=r:(C===T.sequenceNodeType.STRING||C===T.sequenceNodeType.ARRAY)&&(I=s);I&&I.length>0?c.push({st:u,ed:m+1,ts:{cl:{rgb:I},fs:11}}):c.push({st:u,ed:m+1,ts:{cl:{rgb:i},fs:11}})}return{textRuns:c,refSelections:d}}const Pr=(e,t,n,o)=>{const r=l.useDependency(a.ICommandService),s=l.useDependency(l.IShortcutService),i=E.useRef(t);i.current=t;const c=E.useRef(o);c.current=o,E.useEffect(()=>{if(!n||!e)return;const f=`sheet.formula-embedding-editor.${n.getEditorId()}`,S=new a.DisposableCollection,p=(u,m)=>{if(c.current){c.current(u,m);return}let C=a.Direction.LEFT;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),m===l.MetaKeys.SHIFT?r.executeCommand(J.MoveSelectionOperation.id,{direction:C}):r.executeCommand(J.MoveCursorOperation.id,{direction:C})},h=(u,m)=>{let C=a.Direction.DOWN;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_LEFT?C=a.Direction.LEFT:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),i.current?m===l.MetaKeys.CTRL_COMMAND?r.executeCommand(N.MoveSelectionCommand.id,{direction:C,jumpOver:N.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:i.current===Se.NEED_ADD||i.current===Se.EDIT_OTHER_SHEET_REFERENCE}):m===l.MetaKeys.SHIFT?r.executeCommand(N.ExpandSelectionCommand.id,{direction:C,extra:"formula-editor"}):m===(l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT)?r.executeCommand(N.ExpandSelectionCommand.id,{direction:C,jumpOver:N.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand(N.MoveSelectionCommand.id,{direction:C,extra:"formula-editor",fromCurrentSelection:i.current===Se.NEED_ADD||i.current===Se.EDIT_OTHER_SHEET_REFERENCE}):p(u,m)};return S.add(r.registerCommand({id:f,type:a.CommandType.OPERATION,handler(u,m){const{keyCode:C,metaKey:_}=m;h(C,_)}})),[{keyCode:l.KeyCode.ARROW_DOWN},{keyCode:l.KeyCode.ARROW_LEFT},{keyCode:l.KeyCode.ARROW_RIGHT},{keyCode:l.KeyCode.ARROW_UP},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT}].map(({keyCode:u,metaKey:m})=>({id:f,binding:m?u|m:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:u,metaKey:m}})).forEach(u=>{S.add(s.registerShortcut(u))}),()=>{S.dispose()}},[r,n,e,s])},Lr=(e,t,n,o,r=!0)=>{var g;const s=l.useDependency(j.IRenderManagerService),i=l.useDependency(a.IContextService),c=l.useDependency(l.IContextMenuService),d=l.useDependency(x.IRefSelectionsService),f=l.useDependency(a.IUniverInstanceService),S=l.useObservable(E.useMemo(()=>f.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[f])),p=s.getRenderById((g=S==null?void 0:S.getUnitId())!=null?g:""),h=p==null?void 0:p.with($.RefSelectionsRenderService);E.useLayoutEffect(()=>{if(e)return i.setContextValue(a.EDITOR_ACTIVATED,!0),r&&c.disable(),()=>{const u=f.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_DOC);(u==null?void 0:u.getUnitId())===o&&i.setContextValue(a.EDITOR_ACTIVATED,!1),r&&c.enable(),d.clear()}},[i,e,d,r,o]),E.useLayoutEffect(()=>{if(e&&t){const u=h==null?void 0:h.enableSelectionChanging();return i.setContextValue(x.REF_SELECTIONS_ENABLED,!0),()=>{i.setContextValue(x.REF_SELECTIONS_ENABLED,!1),u==null||u.dispose()}}},[i,e,h,t]),E.useEffect(()=>{e&&(h==null||h.setSkipLastEnabled(!1))},[e,h])},$r=(e,t,n)=>{const o=l.useDependency(a.IUniverInstanceService),r=l.useDependency(x.SheetsSelectionsService);return E.useCallback(()=>{if(e){const i=[...r.getWorkbookSelections(t).getSelectionsOfWorksheet(n)],c=o.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),d=c==null?void 0:c.getActiveSheet();(c==null?void 0:c.getUnitId())!==t&&o.setCurrentUnitForType(t),d&&d.getSheetId()===n&&r.setSelections(i)}},[e,r,n,t,o])},Fr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),ht=e=>e.map(t=>typeof t=="string"?t:t.token).join(""),Xe=(e,t=!1,n="",o=!1)=>!t&&!o?e.map(r=>T.serializeRange(r.range)):e.map(r=>o?T.serializeRangeToRefString(r):r.sheetName!==""&&r.sheetName!==n?T.serializeRangeWithSheet(r.sheetName,r.range):T.serializeRange(r.range)),Wr=e=>{var S,p,h;const{editor:t,lexerTreeBuilder:n}=e,o=t==null?void 0:t.getSelectionRanges();if((o==null?void 0:o.length)!==1)return;const s=o[0].startOffset-1,i=((p=(S=t==null?void 0:t.getDocumentData().body)==null?void 0:S.dataStream)!=null?p:`\r
4
+ `).slice(0,-2),c=(h=n.sequenceNodesBuilder(i.slice(1)))!=null?h:[],d=dt(c,s,!1),f=Ft(c,d);return{nodeIndex:d,updatingRefIndex:f,sequenceNodes:c,offset:s}},Ur=(()=>{}),Vr=(e,t,n,o,r,s,i,c,d,f=Ur)=>{var F;const S=l.useDependency(j.IRenderManagerService),p=l.useDependency(a.IUniverInstanceService),h=l.useDependency(a.ICommandService),g=l.useDependency(pt.DocSelectionManagerService),u=l.useDependency(a.ThemeService),m=l.useDependency(T.LexerTreeBuilder),C=p.getUnit(o),_=l.useEvent((A,O)=>{var L,b,w;return(w=(b=(L=p.getUnit(A))==null?void 0:L.getSheetBySheetId(O))==null?void 0:b.getName())!=null?w:""}),I=E.useMemo(()=>_(o,r),[_,r,o]),R=l.useObservable(C==null?void 0:C.activeSheet$),D=Te({activeSheet:R,sheetName:I}),v=l.useObservable(E.useMemo(()=>p.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[p])),M=S.getRenderById((F=v==null?void 0:v.getUnitId())!=null?F:""),k=M==null?void 0:M.with($.RefSelectionsRenderService),W=M==null?void 0:M.with(N.SheetSkeletonManagerService),U=l.useDependency(x.IRefSelectionsService),P=l.useEvent((A,O,L)=>{var Q,ne,ae,G,ee,ke,we,Je,pe,et;const b=Wr({editor:d,lexerTreeBuilder:m});if(!b)return;const{nodeIndex:w,updatingRefIndex:V,sequenceNodes:H,offset:K}=b;if(n.current===Se.NEED_ADD)if(K!==0){if(w===-1&&H.length)return;const z=A[A.length-1],te=H.splice(w+1),le=(Q=z.sheetId)!=null?Q:r,re={range:z,unitId:(ne=z.unitId)!=null?ne:v.getUnitId(),sheetName:_((ae=z.unitId)!=null?ae:v.getUnitId(),le)},ie=le!==r,ue=(v==null?void 0:v.getUnitId())!==o,fe=Xe([re],i&&(ie||ue),I,ue);H.push({token:fe[0],nodeType:T.sequenceNodeType.REFERENCE});const be=[...H,...te],Me=ht(be);f(Me,Fr(H),O)}else{const z=A[A.length-1],te=(G=z.sheetId)!=null?G:r,le={range:z,unitId:(ee=z.unitId)!=null?ee:v.getUnitId(),sheetName:_((ke=z.unitId)!=null?ke:v.getUnitId(),te)},re=te!==r,ie=(v==null?void 0:v.getUnitId())!==o,ue=Xe([le],i&&(re||ie),I,ie);H.unshift({token:ue[0],nodeType:T.sequenceNodeType.REFERENCE});const fe=ht(H);f(fe,ue[0].length,O)}else if(n.current===Se.EDIT_OTHER_SHEET_REFERENCE||n.current===Se.EDIT_OTHER_WORKBOOK_REFERENCE){const z=A.pop();if(!z)return;const te=H[w];if(typeof te=="object"&&te.nodeType===T.sequenceNodeType.REFERENCE){const le=te.token;(v==null?void 0:v.getUnitId())!==o?te.token=T.serializeRangeWithSpreadsheet((we=v==null?void 0:v.getUnitId())!=null?we:"",I,z):te.token=I===(R==null?void 0:R.getName())?T.serializeRange(z):T.serializeRangeWithSheet(R.getName(),z);const ie=K+(te.token.length-le.length);f(T.generateStringWithSequence(H),ie,O)}}else{const z=[...A];if(!L&&V!==-1){const Z=z.pop();Z&&z.splice(V,0,Z)}let te=0;const le=H.map(Z=>{var he,me,Ae,Oe;if(typeof Z=="string")return Z;if(Z.nodeType===T.sequenceNodeType.REFERENCE){const de=T.deserializeRangeWithSheet(Z.token);if(de.sheetName||(de.sheetName=I),(de.unitId||o)!==(v==null?void 0:v.getUnitId())||i&&((he=D.current.activeSheet)==null?void 0:he.getName())!==de.sheetName)return Z.token;const oe=z[te];if(te++,!oe)return"";const Fe=(me=oe.sheetId)!=null?me:r,St={range:oe,unitId:(Ae=oe.unitId)!=null?Ae:v.getUnitId(),sheetName:_((Oe=oe.unitId)!=null?Oe:v.getUnitId(),Fe)},tt=(v==null?void 0:v.getUnitId())!==o;return Xe([St],i&&(Fe!==r||tt),I,tt)[0]}return Z.token});let re="",ie;le.forEach((Z,he)=>{re+=Z,he===w&&(ie=re.length)});const ue=[];for(let Z=te;Z<=A.length-1;Z++){const he=A[Z],me=(Je=he.sheetId)!=null?Je:r,Ae={range:he,unitId:(pe=he.unitId)!=null?pe:v.getUnitId(),sheetName:_((et=he.unitId)!=null?et:v.getUnitId(),me)},Oe=(v==null?void 0:v.getUnitId())!==o,oe=Xe([Ae],i&&(me!==r||Oe),I,Oe);ue.push(oe[0])}const fe=H[H.length-1],be=fe&&(typeof fe=="string"?!1:fe.nodeType===T.sequenceNodeType.REFERENCE),Me=`${re}${ue.length&&be?",":""}${ue.join(",")}`;f(Me,!ue.length&&ie?ie:Me.length,O)}});E.useEffect(()=>{if(k&&e){let A=!0,O=0;const L=(w,V)=>{if(A){A=!1,O=w.length;return}const H=w.length>O;V&&(O=w.length),P(w.map(K=>K.rangeWithCoord),V,H)},b=new a.DisposableCollection;return b.add(k.selectionMoving$.subscribe(w=>{L(w,!1)})),b.add(k.selectionMoveEnd$.subscribe(w=>{L(w,!0)})),()=>{b.dispose()}}},[e,P,k]),E.useEffect(()=>{if(t&&k&&d){const A=new a.DisposableCollection,O=()=>{A.dispose(),k.getSelectionControls().forEach((w,V)=>{A.add(w.selectionScaling$.subscribe(H=>{const K=k.getSelectionDataWithStyle().map(ne=>ne.rangeWithCoord),Q=K[V];H.sheetId=Q.sheetId,H.unitId=Q.unitId,K[V]=H,P(K,!1)})),A.add(w.selectionMoving$.subscribe(H=>{const K=k.getSelectionDataWithStyle().map(ne=>ne.rangeWithCoord),Q=K[V];H.sheetId=Q.sheetId,H.unitId=Q.unitId,K[V]=H,P(K,!0)}))})},L=q.merge(d.input$,U.selectionSet$,k.selectionMoveEnd$).pipe(tn.debounceTime(50)).subscribe(()=>{O()});return()=>{L.unsubscribe(),A.dispose()}}},[d,t,P,k,U.selectionSet$]),k==null||k.getSelectionDataWithStyle(),E.useEffect(()=>{if(c){const A=h.onCommandExecuted(O=>{var b;if(O.id!==x.SetSelectionsOperation.id)return;const L=O.params;if(L.extra==="formula-editor"&&L.selections.length){const w=L.selections[L.selections.length-1];if(w){const{range:V,primary:H}=w;(H!=null&&H.isMergedMainCell||H!=null&&H.isMerged)&&a.Rectangle.contains(H,V)&&(V.startRow=H.startRow,V.endRow=H.startRow,V.startColumn=H.startColumn,V.endColumn=H.startColumn);const K=n.current===Se.NEED_ADD,Q=((b=k==null?void 0:k.getSelectionDataWithStyle())!=null?b:[]).map(ne=>ne.rangeWithCoord);K?Q.push(V):Q[Q.length-1]=V,P(Q,!0)}}});return()=>{A.dispose()}}},[h,d,n,m,c,P,k]),E.useEffect(()=>{if(!d)return;const A=g.textSelection$.subscribe(O=>{O.unitId===d.getEditorId()&&Vt({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:U,refSelectionsRenderService:k,sheetSkeletonManagerService:W,themeService:u,univerInstanceService:p,currentWorkbook:v})});return()=>A.unsubscribe()},[g.textSelection$,d,s,k,U,W,r,u,o,p])},Hr=(e,t,n,o,r,s)=>{const i=l.useDependency(a.ICommandService),c=l.useDependency(J.IEditorService),f=l.useDependency(j.IRenderManagerService).getRenderById(t),S=l.useDependency(a.IUniverInstanceService),p=f==null?void 0:f.with($.RefSelectionsRenderService);E.useEffect(()=>{if(e&&p)if(n){const h=()=>{const m=p.getSelectionControls().length;for(let C=1;C<=m;C++)p.clearLastSelection();return setTimeout(()=>{s()},30)},g=i.onCommandExecuted(m=>{m.id===x.SetWorksheetActiveOperation.id&&h()}),u=S.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(m=>{h()});return()=>{g.dispose(),u.unsubscribe()}}else{const h=i.beforeCommandExecuted(g=>{if(g.id===x.SetWorksheetActiveOperation.id){o(!1),r(),s();const u=c.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);u==null||u.focus()}});return()=>{h.dispose()}}},[e,p])},Br=(e,t,n)=>{const o=l.useDependency(T.LexerTreeBuilder),r=E.useRef(!0);E.useEffect(()=>{if(e){const s=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(s)}}},[e]),E.useEffect(()=>{if(!r.current&&t){const s=o.checkIfAddBracket(n);t(s===0&&n.startsWith(T.operatorToken.EQUALS),`${n}`)}},[n,t])},Kr=(e,t=[],n)=>{const o=l.useDependency(ge.IDescriptionService),[r,s]=E.useState([]),[i,c]=E.useState(""),d=E.useRef(-1),f=Te({nodes:t}),S=()=>{s([]),c(""),d.current=-1};return E.useEffect(()=>{if(n&&e){const h=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const g=n.getSelectionRanges();if(g.length===1){const u=f.current.nodes,m=g[0];if(m.collapsed){const C=dt(u,m.startOffset-1,!1);d.current=C;const _=u[C];if(_&&typeof _!="string"&&_.nodeType===T.sequenceNodeType.FUNCTION){d.current=C;const I=_.token,R=o.getSearchListByNameFirstLetter(I);s(R),c(I);return}}}d.current=-1,c(""),s(u=>u!=null&&u.length?[]:u)});return()=>{h.unsubscribe()}}},[n,e]),E.useEffect(()=>{e||S()},[e]),{searchList:r,searchText:i,handlerFormulaReplace:(h,g)=>{const u=[...f.current.nodes];if(d.current!==-1){const m=u.splice(d.current+1),C=u.pop()||"";let _=(typeof C=="string"?C.length:C.token.length)-h.length;return u.push(h),m[0]!==T.matchToken.OPEN_BRACKET&&g!==T.FunctionType.DefinedName&&(u.push(T.matchToken.OPEN_BRACKET),_--),{text:ht([...u,...m]),offset:_}}},reset:S}},jr=()=>{},qr=E.forwardRef(Yr);function Yr(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:s,onClose:i=jr}=e,c=s.getEditorId(),d=l.useDependency(l.IShortcutService),f=l.useDependency(a.ICommandService),{searchList:S,searchText:p,handlerFormulaReplace:h,reset:g}=Kr(n,o,s),u=E.useMemo(()=>!!S.length,[S]),m=E.useRef(void 0),[C,_]=E.useState(0),I=E.useRef(!1),[R]=Wt(c,u,[p,S]),D=Te({searchList:S,active:C}),v=(P,F)=>{const A=h(P,F);A&&(g(),r(A))};function M(P){I.current&&_(P)}function k(){I.current&&_(-1)}E.useEffect(()=>{if(!S.length)return;const P=`sheet.formula-embedding-editor.search_function.${c}`,F=new a.DisposableCollection,A=O=>{const{searchList:L,active:b}=D.current;switch(O){case l.KeyCode.ARROW_UP:{_(w=>{const V=Math.max(0,w-1);return W(V),V});break}case l.KeyCode.ARROW_DOWN:{_(w=>{const V=Math.min(L.length-1,w+1);return W(V),V});break}case l.KeyCode.TAB:case l.KeyCode.ENTER:{const w=L[b];v(w.name,w.functionType);break}case l.KeyCode.ESC:{g(),i();break}}};return F.add(f.registerCommand({id:P,type:a.CommandType.OPERATION,handler(O,L){const{keyCode:b}=L;A(b)}})),[l.KeyCode.ARROW_UP,l.KeyCode.ARROW_DOWN,l.KeyCode.ENTER,l.KeyCode.ESC,l.KeyCode.TAB].map(O=>({id:P,binding:O,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:O}})).forEach(O=>{F.add(d.registerShortcut(O))}),()=>{F.dispose()}},[S]);function W(P){const F=m.current;if(!F)return;const A=F.children[P];if(!A)return;const L=F.getBoundingClientRect().top,b=F.offsetHeight,w=A.getBoundingClientRect(),V=w.top,H=w.height;if(V>=0&&V>L&&V-L+H<=b)return;const K=A.offsetTop-(b-H)/2;F.scrollTo({top:K,behavior:"smooth"})}const U=E.useMemo(()=>{let P="";return()=>{clearTimeout(P),I.current=!0,P=setTimeout(()=>{I.current=!1},300)}},[]);return S.length>0&&u&&y.jsx(l.RectPopup,{portal:!0,anchorRect$:R,direction:"vertical",children:y.jsx("ul",{ref:P=>{m.current=P,t&&(t.current=P)},"data-u-comp":"sheets-formula-editor",className:B.clsx("univer-m-0 univer-box-border univer-max-h-[400px] univer-w-[250px] univer-list-none univer-overflow-y-auto univer-rounded-lg univer-bg-white univer-p-2 univer-leading-5 univer-shadow-md univer-outline-none dark:!univer-bg-gray-900",B.borderClassName,B.scrollbarClassName),children:S.map((P,F)=>y.jsxs("li",{className:B.clsx("univer-box-border univer-cursor-pointer univer-rounded univer-px-2 univer-py-1 univer-text-gray-900 univer-transition-colors dark:!univer-text-white",{"univer-bg-gray-200 dark:!univer-bg-gray-600":C===F}),onMouseEnter:()=>M(F),onMouseLeave:k,onMouseMove:U,onClick:()=>{v(P.name,P.functionType),s&&s.focus()},children:[y.jsxs("span",{className:"univer-block univer-truncate univer-text-xs",children:[y.jsx("span",{className:"univer-text-red-500",children:P.name.substring(0,p.length)}),y.jsx("span",{children:P.name.slice(p.length)})]}),y.jsx("span",{className:"univer-block univer-text-xs univer-text-gray-400",children:P.desc})]},P.name))})})}const zr=e=>e.startsWith(T.operatorToken.EQUALS)?e.slice(1):"",Bt=()=>{},Kt=E.forwardRef((e,t)=>{var Gt,Zt,Xt,Qt;const{errorText:n,initValue:o,unitId:r,subUnitId:s,isFocus:i=!0,isSupportAcrossSheet:c=!1,onFocus:d=Bt,onBlur:f=Bt,onChange:S,onVerify:p,className:h,editorId:g,moveCursor:u=!0,onFormulaSelectingChange:m,keyboardEventConfig:C,onMoveInEditor:_,resetSelectionOnBlur:I=!0,autoScrollbar:R=!0,isSingle:D=!0,disableSelectionOnClick:v=!1,autofocus:M=!0,disableContextMenu:k,style:W}=e,U=l.useDependency(J.IEditorService),P=E.useRef(null),F=l.useEvent(S);E.useImperativeHandle(t,()=>({isClickOutSide:X=>P.current?!P.current.contains(X.target):!1}));const A=l.useEvent(m),O=E.useRef(null),L=E.useRef(void 0),b=L.current,[w,V]=E.useState(i),H=E.useRef(null),K=E.useMemo(()=>g!=null?g:a.createInternalEditorID(`${N.EMBEDDING_FORMULA_EDITOR}-${a.generateRandomId(4)}`),[]),Q=E.useMemo(()=>n!==void 0,[n]),ne=l.useDependency(a.IUniverInstanceService),ae=ne.getUnit(K);l.useObservable(ae==null?void 0:ae.change$);const G=Dr(),ee=a.BuildTextUtils.transform.getPlainText((Zt=(Gt=ae==null?void 0:ae.getBody())==null?void 0:Gt.dataStream)!=null?Zt:""),ke=Te(ee),we=E.useMemo(()=>zr(ee),[ee]),Je=E.useMemo(()=>G(we),[we,G]),{isSelecting:pe,isSelectingRef:et}=Nr({unitId:r,subUnitId:s,editorId:K,isFocus:w,disableOnClick:v}),z=E.useRef(""),le=l.useDependency(j.IRenderManagerService).getRenderById(K),re=le==null?void 0:le.with(J.DocSelectionRenderService),ie=re==null?void 0:re.isFocusing,ue=E.useMemo(()=>ne.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[ne]),fe=l.useObservable(ue),be=(fe==null?void 0:fe.getUnitId())===K,Me=E.useRef([]),Z=pe,me=(Qt=(Xt=l.useDependency(a.IConfigService).getConfig(Rt))==null?void 0:Xt.functionScreenTips)!=null?Qt:!0;l.useUpdateEffect(()=>{F(ee)},[ee,F]);const Ae=Ht("="),Oe=wr(r,s),de=l.useEvent((X,se=!0,Ce,ve)=>{if(!L.current)return;z.current=X;const nt=X[0]==="="?X.slice(1):"",_e=G(nt),io=_e.reduce((Ne,ot)=>typeof ot=="object"?`${Ne}${ot.token}`:`${Ne}${ot}`,""),rt=Ae(L.current,io===nt?_e:[],se,ve);if(Me.current=rt,Ce){const Ne=ve!=null?ve:b==null?void 0:b.getSelectionRanges();if((Ne==null?void 0:Ne.length)!==1)return;const co=Ne[0].startOffset-1,ao=dt(_e,co,!1),Jt=Ft(_e,ao);if(Jt>=0){const en=rt.splice(Jt,1)[0];en&&rt.push(en)}Oe(w?rt:[],L.current)}});E.useEffect(()=>{w&&de(ee,!1,!0)},[w]),E.useEffect(()=>{if(w){if(z.current===ee)return;de(ee,!1,!0)}},[ee]),Br(w,p,ee);const oe=Mr(b),Fe=$r(w,r,s);E.useEffect(()=>{var X;A(pe,(X=re==null?void 0:re.isFocusing)!=null?X:!0)},[A,pe]),J.useKeyboardEvent(w,C,b),E.useLayoutEffect(()=>{let X;if(H.current){X=U.register({autofocus:M,editorUnitId:K,initialSnapshot:{id:K,body:{dataStream:`${o}\r
5
+ `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},H.current);const se=U.getEditor(K);L.current=se,de(o,!1,!0)}return()=>{X==null||X.dispose()}},[]),E.useLayoutEffect(()=>{i?(V(i),oe()):(I&&(b==null||b.blur(),Fe()),V(i))},[i,b,oe,Fe,I]);const{checkScrollBar:St}=J.useResize(b,D,R);Lr(w,!!(pe&&be),r,K,k),Pr(!!(w&&ie&&u),Z,b,_);const tt=l.useEvent((X,se,Ce)=>{if(!ie)return;const ve=se!==-1?[{startOffset:se+1,endOffset:se+1,collapsed:!0}]:void 0;de(`=${X}`,!0,Ce,ve),Ce&&(oe(),se!==-1&&setTimeout(()=>{const nt={startOffset:se+1,endOffset:se+1},_e=b==null?void 0:b.render.with(J.DocBackScrollRenderController);_e==null||_e.scrollToRange({...nt,collapsed:!0})},50),St())});Vr(w&&!!(pe&&be),w,et,r,s,Me,c,!!Z,b,tt),Hr(w&&!!(pe&&be),r,c,V,f,()=>{de(ke.current,!1,!0)});const Yt=X=>{if(X){const se=b==null?void 0:b.getSelectionRanges();if(se&&se.length===1){const Ce=se[0];if(Ce.collapsed){const ve=X.offset;setTimeout(()=>{b==null||b.setSelectionRanges([{startOffset:Ce.startOffset-ve,endOffset:Ce.endOffset-ve}])},30)}}oe(),de(`=${X.text}`)}},zt=()=>{V(!0),d(),oe()};return y.jsxs("div",{className:h,children:[y.jsx("div",{ref:P,className:B.clsx("univer-relative univer-box-border univer-flex univer-h-full univer-w-full univer-items-center univer-justify-around univer-gap-2 univer-rounded-none univer-p-0 univer-ring-1",{"univer-ring-primary-500":w,"univer-ring-red-500":Q}),children:y.jsx("div",{ref:H,className:"univer-relative univer-h-full univer-w-full",onMouseUp:zt})}),n!==void 0&&y.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),me&&b&&we!==""&&y.jsx(br,{editor:b,isFocus:w,formulaText:ee,onClose:()=>oe()}),me&&!!b&&y.jsx(qr,{isFocus:w,sequenceNodes:Je,onSelect:Yt,ref:O,editor:b})]})});function Gr(e,t,n,o){const r=l.useDependency(T.LexerTreeBuilder),s=Ht(""),i=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[c,d]=E.useState([]),f=l.useDependency(N.IMarkSelectionService),S=E.useRef(""),p=l.useDependency(a.IUniverInstanceService);return E.useEffect(()=>{if(!e)return;const h=e.getDocumentDataModel().getPlainText();if(S.current===h)return;S.current=h;const g=r.sequenceNodesBuilder(h);d(g!=null?g:[])},[i,e,r]),E.useEffect(()=>{var u,m;if(!e)return;if(!t){const C=e.getDocumentData();e.setDocumentData({...C,body:{...C.body,dataStream:(m=(u=C.body)==null?void 0:u.dataStream)!=null?m:"",textRuns:[]}});return}const h=s(e,c,!1),g=new a.DisposableCollection;return h.forEach(C=>{const _=T.deserializeRangeWithSheet(C.token),I=p.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),R=I==null?void 0:I.getActiveSheet();if(!_.sheetName&&o!==(R==null?void 0:R.getSheetId())||_.sheetName&&(R==null?void 0:R.getName())!==_.sheetName)return;const D=new a.ColorKit(C.themeColor).toRgb(),v=f.addShape({range:_.range,style:{stroke:C.themeColor,fill:`rgba(${D.r}, ${D.g}, ${D.b}, 0.1)`,strokeDash:12},primary:null});v&&g.add(()=>f.removeShape(v))}),()=>{g.dispose()}},[e,t,s,f,c]),{sequenceNodes:c}}function Zr(e){const t=l.useDependency(x.SheetsSelectionsService),{supportAcrossSheet:n=!1,keepSheetReference:o=!1,unitId:r,subUnitId:s,onChange:i}=e,d=l.useDependency(a.IUniverInstanceService).getUnit(r,a.UniverInstanceType.UNIVER_SHEET),f=l.useEvent(i),S=l.useEvent((p,h)=>{const g=d==null?void 0:d.getActiveSheet();if(!g||!n&&g.getSheetId()!==s||!(p!=null&&p.length))return;const u=o?g.getName():g.getSheetId()===s?"":g.getName(),m=p.map(C=>({range:C.range,unitId:r,sheetName:u}));f(m,h)});E.useEffect(()=>{const p=new a.DisposableCollection;return p.add(t.selectionMoveStart$.subscribe(h=>{S(h,!0)})),p.add(t.selectionMoving$.subscribe(h=>{S(h,!1)})),p.add(t.selectionMoveEnd$.subscribe(h=>{S(h,!1)})),()=>{p.dispose()}},[S,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const jt=e=>!e.some(n=>{if(typeof n=="string"){if(n!==T.matchToken.COMMA)return!0}else if(n.nodeType!==T.sequenceNodeType.REFERENCE)return!0;return!1}),Xr=e=>{if(e.endColumn<e.startColumn){const t=e.endColumn;e.endColumn=e.startColumn,e.startColumn=t}if(e.endRow<e.startRow){const t=e.endRow;e.endRow=e.startRow,e.startRow=t}return e};function Qr(e){const{visible:t,initialValue:n,unitId:o,subUnitId:r,maxRangeCount:s=1/0,supportAcrossSheet:i,keepSheetReference:c,onConfirm:d,onClose:f,onShowBySelection:S}=e,p=l.useDependency(a.LocaleService),h=l.useDependency(T.LexerTreeBuilder),[g,u]=E.useState([]),[m,C]=E.useState(0),_=E.useRef(null);E.useEffect(()=>{if(t&&n.length){const v=n.map(M=>M.sheetName?T.serializeRangeWithSheet(M.sheetName,M.range):T.serializeRange(M.range));u(v),C(v.length-1)}else u([""]),C(0)},[t]);const I=(v,M)=>{const k=[...g];k[v]=M,u(k)},R=()=>{u([...g,""]),C(g.length)},D=v=>{g.splice(v,1),u([...g])};return Zr({unitId:o,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(v,M)=>{if(!t&&S!=null&&S(v))return;const k=new Set(g),W=v.map(F=>F.sheetName?T.serializeRangeWithSheet(F.sheetName,F.range):T.serializeRange(F.range)),U=W.filter(F=>!k.has(F));if(!U.length)return;const P=[...g];if(W.length>1){M||P.splice(m,1),P.push(...U);const F=P.slice(0,s);u(F),C(F.length-1),requestAnimationFrame(()=>{var A;(A=_.current)==null||A.scrollTo({top:_.current.scrollHeight})})}else{P.splice(m,1,...U);const F=P.slice(0,s);u(F),C(m+U.length-1)}}}),y.jsx(B.Dialog,{width:"328px",open:t,title:p.t("rangeSelector.title"),draggable:!0,mask:!1,maskClosable:!1,footer:y.jsxs("footer",{className:"univer-flex univer-gap-2",children:[y.jsx(B.Button,{onClick:f,children:p.t("rangeSelector.cancel")}),y.jsx(B.Button,{variant:"primary",onClick:()=>{d(g.filter(v=>{const M=h.sequenceNodesBuilder(v);return M&&M.length===1&&typeof M[0]!="string"&&M[0].nodeType===T.sequenceNodeType.REFERENCE}).map(v=>T.deserializeRangeWithSheet(v)).map(v=>({...v,range:Xr(v.range)})))},children:p.t("rangeSelector.confirm")})]}),onClose:f,children:y.jsxs("div",{ref:_,className:B.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",B.scrollbarClassName),children:[g.map((v,M)=>y.jsxs("div",{className:"univer-mb-2 univer-flex univer-items-center univer-gap-4",children:[y.jsx(B.Input,{className:B.clsx("univer-w-full",{"univer-border-primary-600":m===M}),placeholder:p.t("rangeSelector.placeHolder"),onFocus:()=>C(M),value:v,onChange:k=>I(M,k)}),g.length>1&&y.jsx(xt,{className:"univer-cursor-pointer",onClick:()=>D(M)})]},M)),g.length<s&&y.jsx("div",{children:y.jsxs(B.Button,{variant:"link",onClick:R,children:[y.jsx(Pt,{}),y.jsx("span",{children:p.t("rangeSelector.addAnotherRange")})]})})]})})}function Jr(e){return e.split(T.matchToken.COMMA).filter(t=>!!t).map(t=>T.deserializeRangeWithSheet(t))}function eo(e){return e.map(t=>t.sheetName?T.serializeRangeWithSheet(t.sheetName,t.range):T.serializeRange(t.range)).join(T.matchToken.COMMA)}function gt(e){const[t,n]=E.useState(null),{onVerify:o,selectorRef:r,unitId:s,subUnitId:i,maxRangeCount:c,supportAcrossSheet:d,keepSheetReference:f,autoFocus:S,onChange:p,onRangeSelectorDialogVisibleChange:h,onClickOutside:g,onFocusChange:u,forceShowDialogWhenSelectionChanged:m,hideEditor:C,resetRange:_}=e,[I,R]=E.useState(S!=null?S:!1),[D,v]=E.useState(!1),[M,k]=E.useState([]),W=l.useDependency(a.LocaleService),U=l.useDependency(J.IEditorService),{sequenceNodes:P}=Gr(t,I,s,i),F=Te(P),A=l.useDependency(a.ICommandService),O=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),U.blur()}),L=l.useEvent(()=>{var b;O(),k(Jr((b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")),v(!0)});return E.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){U.focus(t.getEditorId())},blur:O,verify:()=>jt(F.current),showDialog:b=>{O(),k(b),v(!0)},hideDialog:()=>{k([]),v(!1)},getValue:()=>{var b;return(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:""}})},[O,t,U,r,F]),E.useEffect(()=>{var b;o==null||o(jt(P),(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")},[P]),E.useEffect(()=>{h==null||h(D)},[D]),E.useEffect(()=>{if(D&&_)return()=>{const b={unitId:s,subUnitId:i,selections:_};A.executeCommand(x.SetSelectionsOperation.id,b)}},[D]),y.jsxs(y.Fragment,{children:[C?null:y.jsx(J.RichTextEditor,{isSingle:!0,...e,onFocusChange:(b,w)=>{R(b),u==null||u(b,w)},editorRef:n,onClickOutside:()=>{R(!1),O(),g==null||g()},icon:y.jsx(B.Tooltip,{title:W.t("rangeSelector.buttonTooltip"),placement:"bottom",children:y.jsx($t,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:L})})}),y.jsx(Qr,{initialValue:M,unitId:s,subUnitId:i,visible:D,maxRangeCount:c,onConfirm:b=>{const w=eo(b),V=a.RichTextBuilder.newEmptyData();V.body.dataStream=w,t==null||t.replaceText(w,!1),p==null||p(V,w),v(!1),k([]),requestAnimationFrame(()=>{O()})},onClose:()=>{v(!1),k([])},supportAcrossSheet:d,keepSheetReference:f,onShowBySelection:b=>I||m?(k(b),v(!0),!1):!0})]})}const to=()=>{var o,r;const e=l.useDependency(ut),t=l.useObservable(e.currentSelector$),n=E.useRef(null);return E.useEffect(()=>{var s,i;if(t)return(i=n.current)==null||i.showDialog((s=t.initialValue)!=null?s:[]),()=>{var c;(c=n.current)==null||c.hideDialog()}},[t]),y.jsx(gt,{unitId:(o=t==null?void 0:t.unitId)!=null?o:"",subUnitId:(r=t==null?void 0:t.subUnitId)!=null?r:"",hideEditor:!0,selectorRef:n,onChange:(s,i)=>{var c;t==null||t.callback((c=i==null?void 0:i.split(",").map(d=>T.deserializeRangeWithSheet(d)))!=null?c:[])}})};var no=Object.defineProperty,ro=Object.getOwnPropertyDescriptor,oo=(e,t,n)=>t in e?no(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,so=(e,t,n,o)=>{for(var r=o>1?void 0:o?ro(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Qe=(e,t)=>(n,o)=>t(n,o,e),qt=(e,t,n)=>oo(e,typeof t!="symbol"?t+"":t,n);$.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=Tt,n,o,r,s){super(),this._config=t,this._injector=n,this._renderManagerService=o,this._configService=r,this._uiPartsService=s;const{menu:i,...c}=a.merge(Tt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(Rt,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[Ve,{useClass:st}],[ut],[Ge],[Ke],[je],[qe],[Ye],[$.FormulaReorderController],[Ze]]),this._initUIPart()}onReady(){[[$.RefSelectionsRenderService]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))})}onRendered(){[[at]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))}),a.touchDependencies(this._injector,[[Ge],[je],[Ye],[Ze]])}onSteady(){this._injector.get(Ke),this._injector.get($.FormulaReorderController)}_initUIPart(){const t=this._injector.get(l.ComponentManager);this.disposeWithMe(t.register(N.RANGE_SELECTOR_COMPONENT_KEY,gt)),this.disposeWithMe(t.register(N.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Kt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(to,this._injector)))}},qt($.UniverSheetsFormulaUIPlugin,"pluginName",Et),qt($.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET),$.UniverSheetsFormulaUIPlugin=so([a.DependentOn(ge.UniverSheetsFormulaPlugin),Qe(1,a.Inject(a.Injector)),Qe(2,j.IRenderManagerService),Qe(3,a.IConfigService),Qe(4,l.IUIPartsService)],$.UniverSheetsFormulaUIPlugin),$.FORMULA_PROMPT_ACTIVATED=vt,$.FormulaEditor=Kt,$.GlobalRangeSelectorService=ut,$.HelpFunctionOperation=mt,$.InsertFunctionOperation=ce,$.MoreFunctionsOperation=He,$.RangeSelector=gt,$.ReferenceAbsoluteOperation=it,$.SearchFunctionOperation=yt,$.SelectEditorFormulaOperation=Ee,$.SheetCopyFormulaOnlyCommand=We,$.SheetOnlyPasteFormulaCommand=Ue,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/sheets-formula-ui",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -63,17 +63,17 @@
63
63
  "rxjs": ">=7.0.0"
64
64
  },
65
65
  "dependencies": {
66
- "@univerjs/icons": "^1.0.2",
67
- "@univerjs/core": "0.14.0",
68
- "@univerjs/design": "0.14.0",
69
- "@univerjs/docs": "0.14.0",
70
- "@univerjs/docs-ui": "0.14.0",
71
- "@univerjs/engine-render": "0.14.0",
72
- "@univerjs/engine-formula": "0.14.0",
73
- "@univerjs/sheets": "0.14.0",
74
- "@univerjs/sheets-ui": "0.14.0",
75
- "@univerjs/sheets-formula": "0.14.0",
76
- "@univerjs/ui": "0.14.0"
66
+ "@univerjs/icons": "^1.1.0",
67
+ "@univerjs/core": "0.15.0",
68
+ "@univerjs/design": "0.15.0",
69
+ "@univerjs/docs": "0.15.0",
70
+ "@univerjs/docs-ui": "0.15.0",
71
+ "@univerjs/sheets": "0.15.0",
72
+ "@univerjs/engine-formula": "0.15.0",
73
+ "@univerjs/sheets-formula": "0.15.0",
74
+ "@univerjs/sheets-ui": "0.15.0",
75
+ "@univerjs/ui": "0.15.0",
76
+ "@univerjs/engine-render": "0.15.0"
77
77
  },
78
78
  "devDependencies": {
79
79
  "postcss": "^8.5.6",
@@ -81,9 +81,9 @@
81
81
  "rxjs": "^7.8.2",
82
82
  "tailwindcss": "3.4.18",
83
83
  "typescript": "^5.9.3",
84
- "vite": "^7.2.7",
85
- "vitest": "^4.0.15",
86
- "@univerjs-infra/shared": "0.14.0"
84
+ "vite": "^7.3.0",
85
+ "vitest": "^4.0.16",
86
+ "@univerjs-infra/shared": "0.15.0"
87
87
  },
88
88
  "scripts": {
89
89
  "test": "vitest run",