@univerjs/sheets-formula-ui 0.10.12 → 0.10.13

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(F,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):(F=typeof globalThis<"u"?globalThis:F||self,a(F.UniverSheetsFormulaUi={},F.UniverCore,F.UniverSheetsUi,F.UniverEngineFormula,F.rxjs,F.UniverDocsUi,F.UniverEngineRender,F.UniverSheets,F.UniverSheetsFormula,F.UniverUi,F.React,F.React,F.UniverDesign,F.UniverDocs,F.rxjs.operators))})(this,(function(F,a,D,R,q,J,j,L,me,l,y,_,B,ht,Qt){"use strict";var so=Object.defineProperty;var io=(F,a,D)=>a in F?so(F,a,{enumerable:!0,configurable:!0,writable:!0,value:D}):F[a]=D;var Y=(F,a,D)=>io(F,typeof a!="symbol"?a+"":a,D);const Ue={id:"sheet.command.paste-formula",type:a.CommandType.COMMAND,handler:async e=>e.get(a.ICommandService).executeCommand(D.SheetPasteCommand.id,{value:D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Ie={id:"formula-ui.operation.select-editor-formula",type:a.CommandType.OPERATION,handler:(e,t)=>!0};var Jt=Object.getOwnPropertyDescriptor,en=(e,t,n,o)=>{for(var r=o>1?void 0:o?Jt(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},tn=(e,t)=>(n,o)=>t(n,o,e);const gt="FORMULA_PROMPT_ACTIVATED",Ve=a.createIdentifier("formula-ui.prompt-service");let ot=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(gt,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:c}=s;t=c}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!==R.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,c=this._sequenceNodes.length;s<c;s++){const i=this._sequenceNodes[s];if(typeof i=="string")continue;const d={...i};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:R.sequenceNodeType.REFERENCE});for(let r=o+1,s=this._sequenceNodes.length;r<s;r++){const c=this._sequenceNodes[r];if(typeof c=="string")continue;const i={...c};i.startIndex+=n,i.endIndex+=n,this._sequenceNodes[r]=i}}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,c=this._sequenceNodes.length;s<c;s++){const i=this._sequenceNodes[s];if(typeof i=="string")continue;const d={...i};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}};ot=en([tn(0,a.IContextService)],ot);const vt={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,b;const n=e.get(L.SheetsSelectionsService),o=e.get(J.IEditorService),r=n.getCurrentSelections();if(!r||!r.length)return!1;const s=L.getSheetCommandTarget(e.get(a.IUniverInstanceService));if(!s)return!1;const{worksheet:c,unitId:i,subUnitId:d}=s,g=c.getCellMatrix(),{value:S}=t,v=e.get(a.ICommandService);e.get(D.IEditorBridgeService);const h=[],f=[];let u=null,E=0,m=0,C="";if(r.length===1&&(on(r[0].range)||sn(r[0].range)&&pt(g,r[0].range))){const{range:N,primary:p}=r[0],M=(I=p==null?void 0:p.actualRow)!=null?I:N.startRow,x=(b=p==null?void 0:p.actualColumn)!=null?b:N.startColumn;u=N,E=M,m=x;const W=St(g,M,x);W&&(C=R.serializeRange(W))}else r.some(N=>{var x,W;const{range:p,primary:M}=N;if(pt(g,p)){const U=(x=M==null?void 0:M.actualRow)!=null?x:p.startRow,w=(W=M==null?void 0:M.actualColumn)!=null?W:p.startColumn,$=St(g,U,w);if(!$)return u=p,E=U,m=w,!0;const k=R.serializeRange($),O=`=${S}(${k})`;h.push({range:p,primary:{row:U,column:w},formula:O})}else{const{startRow:U,startColumn:w,endRow:$,endColumn:k}=p;if(U===$){const O=cn(g,U,k,c.getColumnCount()-1),A=O===k?k-1:k,T=R.serializeRange({startRow:U,endRow:$,startColumn:w,endColumn:A}),P=`=${S}(${T})`;f.push({range:p,primary:{row:U,column:O},formula:P})}else{let O=-1;for(let T=w;T<=k;T++){const P=an(g,T,$,c.getRowCount()-1);O=Math.max(O,P)}const A=O===$?$-1:$;for(let T=w;T<=k;T++){const P=R.serializeRange({startRow:U,endRow:A,startColumn:T,endColumn:T}),V=`=${S}(${P})`;f.push({range:p,primary:{row:O,column:T},formula:V})}}}return!1});if(u){const N=L.getCellAtRowCol(E,m,c),p={range:a.Rectangle.clone(u),primary:{startRow:N.startRow,startColumn:N.startColumn,endRow:N.endRow,endColumn:N.endColumn,actualRow:E,actualColumn:m,isMerged:N.isMerged,isMergedMainCell:N.startRow===E&&N.startColumn===m}},M={unitId:i,subUnitId:d,selections:[p]};await v.executeCommand(L.SetSelectionsOperation.id,M);const x=o.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),W=o.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);v.syncExecuteCommand(D.SetCellEditVisibleOperation.id,{visible:!0,unitId:i,eventType:j.DeviceInputEventType.Dblclick});const U=`=${S}(${C}`;x==null||x.replaceText(U),W==null||W.replaceText(U,!1)}return h.length===0&&f.length===0?!1:v.executeCommand(me.InsertFunctionCommand.id,{list:h,listOfRangeHasNumber:f})}};function St(e,t,n){const o=nn(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=rn(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function nn(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(Le(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!Le(s))return r+1;if(o&&r===0)return 0}}return t}function rn(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(Le(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!Le(s))return r+1;if(o&&r===0)return 0}}return n}function Le(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 on(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function sn(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function pt(e,t){for(let n=t.startRow;n<=t.endRow;n++)for(let o=t.startColumn;o<=t.endColumn;o++)if(Le(e.getValue(n,o)))return!1;return!0}function cn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function an(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const mt="SHEET_FORMULA_UI_PLUGIN",Ct=`${mt}_MORE_FUNCTIONS_COMPONENT`,Be={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:Ct}}),!0)},st={id:"formula-ui.operation.change-ref-to-absolute",type:a.CommandType.OPERATION,handler:async e=>!0},_t={id:"formula-ui.operation.search-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ve).search(t),!0)};var ln=Object.getOwnPropertyDescriptor,un=(e,t,n,o)=>{for(var r=o>1?void 0:o?ln(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},He=(e,t)=>(n,o)=>t(n,o,e);F.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===L.ReorderRangeCommand.id?this._reorderFormula(t.params):{redos:[],undos:[]}}))}_reorderFormula(t){const n=[],o=[],{unitId:r,subUnitId:s,range:c,order:i}=t,d=this._univerInstanceService.getUniverSheetInstance(r),g=d==null?void 0:d.getSheetBySheetId(s);if(!g)return{redos:n,undos:o};const S=g.getCellMatrix(),v=new a.ObjectMatrix,h=new a.ObjectMatrix;let f=!1;return a.Range.foreach(c,(u,E)=>{let m=u;i.hasOwnProperty(u)&&(m=i[u]);const C=S.getValue(m,E);if(C!=null&&C.f||C!=null&&C.si){f=!0;const I=this._formulaDataModel.getFormulaStringByCell(m,E,s,r),b=this._lexerTreeBuilder.moveFormulaRefOffset(I,0,u-m),N=a.Tools.deepClone(C);N.f=b,N.si=null,v.setValue(u,E,N)}else v.setValue(u,E,C);h.setValue(u,E,S.getValue(u,E))}),f?(n.push({id:L.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:v.getMatrix()}}),o.push({id:L.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:h.getMatrix()}}),{redos:n,undos:o}):{redos:n,undos:o}}},F.FormulaReorderController=un([He(0,a.Inject(L.SheetInterceptorService)),He(1,a.Inject(a.IUniverInstanceService)),He(2,a.Inject(R.FormulaDataModel)),He(3,a.Inject(R.LexerTreeBuilder))],F.FormulaReorderController);const Et="sheets-formula-ui.base.config",It={};var dn=Object.getOwnPropertyDescriptor,fn=(e,t,n,o)=>{for(var r=o>1?void 0:o?dn(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},$e=(e,t)=>(n,o)=>t(n,o,e);const it="SHEET_FORMULA_ALERT",hn={[R.ErrorType.DIV_BY_ZERO]:"divByZero",[R.ErrorType.NAME]:"name",[R.ErrorType.VALUE]:"value",[R.ErrorType.NUM]:"num",[R.ErrorType.NA]:"na",[R.ErrorType.CYCLE]:"cycle",[R.ErrorType.REF]:"ref",[R.ErrorType.SPILL]:"spill",[R.ErrorType.CALC]:"calc",[R.ErrorType.ERROR]:"error",[R.ErrorType.CONNECT]:"connect",[R.ErrorType.NULL]:"null"};let ct=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 i=this._context.unit.getActiveSheet();if(!i)return;const d=i.getCell(e.location.row,e.location.col),g=(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=R.extractFormulaError(d,!!g);if(!S){this._hideAlert();return}const v=this._cellAlertManagerService.currentAlert.get(it),h=(s=v==null?void 0:v.alert)==null?void 0:s.location;if(h&&h.row===e.location.row&&h.col===e.location.col&&h.subUnitId===e.location.subUnitId&&h.unitId===e.location.unitId)return;this._cellAlertManagerService.showAlert({type:D.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${hn[S]}`),location:e.location,width:200,height:74,key:it});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(e=>{e&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(it)}};ct=fn([$e(1,a.Inject(D.HoverManagerService)),$e(2,a.Inject(D.CellAlertManagerService)),$e(3,a.Inject(a.LocaleService)),$e(4,a.Inject(R.FormulaDataModel)),$e(5,l.IZenZoneService)],ct);var gn=Object.getOwnPropertyDescriptor,vn=(e,t,n,o)=>{for(var r=o>1?void 0:o?gn(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},yt=(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:D.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===D.DATA_TYPE.FORMULA,applyFunctions:{[D.APPLY_TYPE.COPY]:(t,n,o,r,s)=>{const{data:c,index:i}=t;return this._fillCopyFormula(c,n,o,i,r,s)}}};this._autoFillService.registerRule(e)}_fillCopyFormula(e,t,n,o,r,s){var g,S;const c=pn(r),i=[],d=new Map;for(let v=1;v<=t;v++){const h=(v-1)%e.length,f=o[h],u=a.Tools.deepClone(e[h]);if(u){const E=((g=e[h])==null?void 0:g.f)||"",m=((S=e[h])==null?void 0:S.si)||"",C=a.isFormulaString(E);if(a.isFormulaId(m))u.si=m,u.f=null,u.v=null,u.p=null,u.t=null,i.push(u);else if(C){let b=d.get(h);if(b)u.si=b,u.f=null,u.v=null,u.p=null,u.t=null;else{b=a.generateRandomId(6),d.set(h,b);const{offsetX:N,offsetY:p}=Sn(c,t,n,s,f),M=this._lexerTreeBuilder.moveFormulaRefOffset(E,N,p);u.si=b,u.f=M,u.v=null,u.p=null,u.t=null}i.push(u)}}}return i}};Ke=vn([yt(0,D.IAutoFillService),yt(1,a.Inject(R.LexerTreeBuilder))],Ke);function Sn(e,t,n,o,r){const{source:s,target:c}=o,{rows:i}=c,{rows:d}=s;let g=0,S=0;switch(n){case a.Direction.UP:S=i[r]-d[r];break;case a.Direction.RIGHT:g=e;break;case a.Direction.DOWN:S=i[r]-d[r];break;case a.Direction.LEFT:g=-e*t;break}return{offsetX:g,offsetY:S}}function pn(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}var mn=Object.getOwnPropertyDescriptor,Cn=(e,t,n,o)=>{for(var r=o>1?void 0:o?mn(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},Fe=(e,t)=>(n,o)=>t(n,o,e);const _n="default-paste-formula";let je=class extends a.Disposable{constructor(e,t,n,o,r){super(),this._currentUniverSheet=e,this._lexerTreeBuilder=t,this._sheetClipboardService=n,this._injector=o,this._formulaDataModel=r,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!0)}}_pasteWithFormulaHook(){return{id:_n,priority:10,onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!1)}}_onPasteCells(e,t,n,o,r){var h;if([D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(o.pasteType))return{undos:[],redos:[]};const c=this._currentUniverSheet.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),i=t.unitId||c.getUnitId(),d=t.subUnitId||((h=c.getActiveSheet())==null?void 0:h.getSheetId());if(!i||!d)return{undos:[],redos:[]};const g=t.range,S=n,v={copyType:o.copyType||D.COPY_TYPE.COPY,copyRange:e==null?void 0:e.range,pasteType:o.pasteType};return this._injector.invoke(f=>En(i,d,g,S,f,v,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};je=Cn([Fe(0,a.IUniverInstanceService),Fe(1,a.Inject(R.LexerTreeBuilder)),Fe(2,D.ISheetClipboardService),Fe(3,a.Inject(a.Injector)),Fe(4,a.Inject(R.FormulaDataModel))],je);function En(e,t,n,o,r,s,c,i,d=!1,g){const S=[],v=[],h=In(e,t,n,o,s,c,i,g);if(!h.hasValue())return{undos:[],redos:[]};const f={unitId:e,subUnitId:t,cellValue:h.getData()};S.push({id:L.SetRangeValuesMutation.id,params:f});const u=L.SetRangeValuesUndoMutationFactory(r,f);return v.push({id:L.SetRangeValuesMutation.id,params:u}),{undos:v,redos:S}}function In(e,t,n,o,r,s,c,i){return i?r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?Rn(e,t,n,o,c,i):r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?bn(e,t,n,o,s,c,i):Tn(e,t,n,o,r.copyType,s,c,i):yn(e,t,n,o,c)}function yn(e,t,n,o,r){const s=new a.ObjectMatrix,c=r.getSheetFormulaData(e,t);return o.forValue((i,d,g)=>{var f;const S=n.rows[i],v=n.cols[d],h={};a.isFormulaString(g.v)?(h.v=null,h.f=`${g.v}`,h.si=null,h.p=null,s.setValue(S,v,h)):(f=c==null?void 0:c[S])!=null&&f[v]&&(h.v=g.v,h.f=null,h.si=null,h.p=null,s.setValue(S,v,h))}),s}function Rn(e,t,n,o,r,s){var g,S;const c=new a.ObjectMatrix,i=(S=(g=r.getArrayFormulaCellData())==null?void 0:g[s.unitId])==null?void 0:S[s.subUnitId],d=r.getSheetFormulaData(e,t);return o.forValue((v,h,f)=>{var b,N;const u=s.range.rows[v%s.range.rows.length],E=s.range.cols[h%s.range.cols.length],m=n.rows[v],C=n.cols[h],I={};if(a.isFormulaString(f.f)||a.isFormulaId(f.si))I.v=f.v,I.f=null,I.si=null,I.p=null,c.setValue(m,C,I);else if((b=i==null?void 0:i[u])!=null&&b[E]){const p=i[u][E];I.v=p.v,I.f=null,I.si=null,I.p=null,c.setValue(m,C,I)}else if((N=d==null?void 0:d[m])!=null&&N[C]){if(I.v=f.v,I.f=null,I.si=null,I.p=null,f.p){const p=Rt(f);p&&(I.v=p)}c.setValue(m,C,I)}}),c}function bn(e,t,n,o,r,s,c){const i=new a.ObjectMatrix,d=new Map;return o.forValue((g,S,v)=>{const h=n.rows[g],f=n.cols[S],u={};if(a.isFormulaId(v.si)){if(c.unitId!==e||c.subUnitId!==t){const E=s.getFormulaStringByCell(c.range.rows[g%c.range.rows.length],c.range.cols[S%c.range.cols.length],c.subUnitId,c.unitId),m=n.cols[S]-c.range.cols[S%c.range.cols.length],C=n.rows[g]-c.range.rows[g%c.range.rows.length],I=r.moveFormulaRefOffset(E||"",m,C);u.si=null,u.f=I}else u.si=v.si,u.f=null;u.v=null,u.p=null,i.setValue(h,f,u)}else if(a.isFormulaString(v.f)){const E=`${g%c.range.rows.length}_${S%c.range.cols.length}`;let m=d.get(E);if(m)u.si=m,u.f=null;else{m=a.generateRandomId(6),d.set(E,m);const C=n.cols[S]-c.range.cols[S%c.range.cols.length],I=n.rows[g]-c.range.rows[g%c.range.rows.length],b=r.moveFormulaRefOffset(v.f||"",C,I);u.si=m,u.f=b}u.v=null,u.p=null,i.setValue(h,f,u)}else{if(u.v=v.v,u.f=null,u.si=null,u.p=null,v.p){const E=Rt(v);E&&(u.v=E)}i.setValue(h,f,u)}}),i}function Tn(e,t,n,o,r,s,c,i){const d=new a.ObjectMatrix,g=new Map,S=c.getSheetFormulaData(e,t),v=[];return r===D.COPY_TYPE.CUT?o.forValue((h,f,u)=>{const E=n.rows[h],m=n.cols[f],C={};if(a.isFormulaId(u.si)){if(a.isFormulaString(u.f))v.push(u.si),C.f=u.f,C.si=u.si;else if(v.includes(u.si))C.f=null,C.si=u.si;else{const I=c.getFormulaStringByCell(i.range.rows[h%i.range.rows.length],i.range.cols[f%i.range.cols.length],i.subUnitId,i.unitId);C.f=I,C.si=null}C.v=null,C.p=null,d.setValue(E,m,C)}else a.isFormulaString(u.f)&&(C.f=u.f,C.si=null,C.v=null,C.p=null,d.setValue(E,m,C))}):o.forValue((h,f,u)=>{var I;const E=n.rows[h],m=n.cols[f],C={};if(a.isFormulaId(u.si)){if(i.unitId!==e||i.subUnitId!==t){const b=c.getFormulaStringByCell(i.range.rows[h%i.range.rows.length],i.range.cols[f%i.range.cols.length],i.subUnitId,i.unitId),N=n.cols[f]-i.range.cols[f%i.range.cols.length],p=n.rows[h]-i.range.rows[h%i.range.rows.length],M=s.moveFormulaRefOffset(b||"",N,p);C.si=null,C.f=M}else C.si=u.si,C.f=null;C.v=null,C.p=null,d.setValue(E,m,C)}else if(a.isFormulaString(u.f)){const b=`${h%i.range.rows.length}_${f%i.range.cols.length}`;let N=g.get(b);if(N)C.si=N,C.f=null;else{N=a.generateRandomId(6),g.set(b,N);const p=n.cols[f]-i.range.cols[f%i.range.cols.length],M=n.rows[h]-i.range.rows[h%i.range.rows.length],x=s.moveFormulaRefOffset(u.f||"",p,M);C.si=N,C.f=x}C.v=null,C.p=null,d.setValue(E,m,C)}else(I=S==null?void 0:S[E])!=null&&I[m]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,d.setValue(E,m,C))}),v.length>0&&new a.ObjectMatrix(S).forValue((h,f,u)=>{if(!(i.range.rows.includes(h)&&i.range.cols.includes(f))&&!(n.rows.includes(h)&&n.cols.includes(f))&&v.includes(u==null?void 0:u.si)){const E=c.getFormulaStringByCell(h,f,i.subUnitId,i.unitId);d.setValue(h,f,{f:E,si:null,v:null,p:null})}}),d}function Rt(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 Mn=Object.getOwnPropertyDescriptor,On=(e,t,n,o)=>{for(var r=o>1?void 0:o?Mn(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},ye=(e,t)=>(n,o)=>t(n,o,e);let qe=class extends a.Disposable{constructor(t,n,o,r,s,c,i,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=c,this._commandService=i,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:c,sheetId:i}=t;this._updateArrayFormulaRangeShape(c,i)}}}))}_changeRuntime(t){this._skeleton=t}_initInterceptorEditorStart(){this.disposeWithMe(a.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept(L.BEFORE_CELL_EDIT,{handler:(t,n,o)=>{var u,E,m,C;const{row:r,col:s,unitId:c,subUnitId:i,worksheet:d}=n,g=this._formulaDataModel.getArrayFormulaRange(),S=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),t==null)return o(t);let v=null;const h=this._formulaDataModel.getFormulaStringByCell(r,s,i,c);if(h!==null&&(v={f:h}),t.v!=null&&t.v!==""&&((m=(E=(u=S[c])==null?void 0:u[i])==null?void 0:E[r])==null?void 0:m[s])==null)return v?{...t,...v}:o(t);const f=(C=g==null?void 0:g[c])==null?void 0:C[i];return f!=null&&(v=this._displayArrayFormulaRangeShape(f,r,s,c,i,d,v)),v?{...t,...v}:o(t)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{(t.id===R.SetFormulaCalculationResultMutation.id||t.id===R.SetArrayFormulaDataMutation.id&&n&&n.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{L.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,c,i){const d=this._formulaDataModel.getSheetFormulaData(r,s);return new a.ObjectMatrix(t).forValue((g,S,v)=>{var m;if(v==null)return!0;const{startRow:h,startColumn:f,endRow:u,endColumn:E}=v;if(g===n&&S===o)return this._createArrayFormulaRangeShape(v,r),!1;if(n>=h&&n<=u&&o>=f&&o<=E){const C=c.getCell(h,f);if((C==null?void 0:C.v)===R.ErrorType.SPILL)return;const I=(m=d==null?void 0:d[g])==null?void 0:m[S];return I==null||I.f==null?!0:(i==null&&(i={f:I.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(v,r),!1)}}),i}_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 c={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:{}}},i=D.attachSelectionWithCoord(c,r),{rowHeaderWidth:d,columnHeaderHeight:g}=r,S=new D.SelectionControl(s,D.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:g});S.updateRangeBySelectionWithCoord(i),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:c}=this._previousShape.getRange(),i={startRow:o,endRow:r,startColumn:s,endColumn:c};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(i,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:c,endColumn:i}=this._previousShape.getRange();for(let d=0;d<o.length;d++){const{row:g}=o[d];if(r>=g){const S={startRow:r,endRow:s,startColumn:c,endColumn:i};this._refreshArrayFormulaRangeShape(t,S);break}}}};qe=On([ye(1,a.Inject(L.SheetInterceptorService)),ye(2,a.Inject(R.FormulaDataModel)),ye(3,a.Inject(a.ThemeService)),ye(4,j.IRenderManagerService),ye(5,a.Inject(D.SheetSkeletonManagerService)),ye(6,a.ICommandService),ye(7,a.ILogService)],qe);var Nn=Object.getOwnPropertyDescriptor,Dn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Nn(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},bt=(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(L.INTERCEPTOR_POINT.CELL_CONTENT,{effect:a.InterceptorEffectEnum.Style,handler:(n,o,r)=>{var i,d,g,S;const s=(S=(g=(d=(i=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:i[o.unitId])==null?void 0:d[o.subUnitId])==null?void 0:g[o.row])==null?void 0:S[o.col];return!R.extractFormulaError(n,!!s)||!n||(n===o.rawData&&(n={...o.rawData}),n.markers={...n==null?void 0:n.markers,...xn}),r(n)},priority:10}))}};Ye=Dn([bt(0,a.Inject(L.SheetInterceptorService)),bt(1,a.Inject(R.FormulaDataModel))],Ye);function kn(){const e=l.useDependency(me.TriggerCalculationController),t=l.useDependency(a.ICommandService),n=l.useObservable(e.progress$),o=_.useCallback(()=>{t.executeCommand(R.SetFormulaCalculationStopMutation.id)},[t]),r=_.useCallback(()=>{e.clearProgress()},[e]);return y.jsx(l.ProgressBar,{progress:n,onTerminate:o,onClearProgress:r})}function wn(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function Tt(e){if(!e.require&&!e.repeat)return`[${e.name}]`;if(e.require&&!e.repeat)return e.name;if(!e.require&&e.repeat)return`[${e.name},...]`;if(e.require&&e.repeat)return`${e.name},...`}function Mt(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:Tt(o)}),r===n.length-1?"":","]},r)),")"]})}function We(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 An(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;const[o,r]=_.useState([]),[s,c]=_.useState(t.functionParameter),[i,d]=_.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((g,S)=>y.jsxs("div",{children:[y.jsx("div",{className:"univer-text-sm",children:g.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(We,{title:i===-1?y.jsx(Mt,{prefix:t.functionName,value:s}):s[i].name,value:i===-1?t.description:s[i].detail})})]})}var ae=function(){return ae=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},ae.apply(this,arguments)},Pn=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);return n},Re=_.forwardRef(function(e,t){var n=e.icon,o=e.id,r=e.className,s=e.extend,c=Pn(e,["icon","id","className","extend"]),i="univerjs-icon univerjs-icon-".concat(o," ").concat(r||"").trim(),d=_.useRef("_".concat(Fn()));return Ot(n,"".concat(o),{defIds:n.defIds,idSuffix:d.current},ae({ref:t,className:i},c),s)});function Ot(e,t,n,o,r){return _.createElement(e.tag,ae(ae({key:t},Ln(e,n,r)),o),($n(e,n).children||[]).map(function(s,c){return Ot(s,"".concat(t,"-").concat(e.tag,"-").concat(c),n,void 0,r)}))}function Ln(e,t,n){var o=ae({},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(function(s){var c=s[0],i=s[1];c==="mask"&&typeof i=="string"&&(o[c]=i.replace(/url\(#(.*)\)/,"url(#$1".concat(t.idSuffix,")")))});var r=t.defIds;return!r||r.length===0||(e.tag==="use"&&o["xlink:href"]&&(o["xlink:href"]=o["xlink:href"]+t.idSuffix),Object.entries(o).forEach(function(s){var c=s[0],i=s[1];typeof i=="string"&&(o[c]=i.replace(/url\(#(.*)\)/,"url(#$1".concat(t.idSuffix,")")))})),o}function $n(e,t){var n,o=t.defIds;return!o||o.length===0?e:e.tag==="defs"&&(!((n=e.children)===null||n===void 0)&&n.length)?ae(ae({},e),{children:e.children.map(function(r){return typeof r.attrs.id=="string"&&o&&o.includes(r.attrs.id)?ae(ae({},r),{attrs:ae(ae({},r.attrs),{id:r.attrs.id+t.idSuffix})}):r})}):e}function Fn(){return Math.random().toString(36).substring(2,8)}Re.displayName="UniverIcon";var Wn={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"}}]},Nt=_.forwardRef(function(e,t){return _.createElement(Re,Object.assign({},e,{id:"check-mark-icon",ref:t,icon:Wn}))});Nt.displayName="CheckMarkIcon";var Un={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"}}]},Dt=_.forwardRef(function(e,t){return _.createElement(Re,Object.assign({},e,{id:"close-icon",ref:t,icon:Un}))});Dt.displayName="CloseIcon";var 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:"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=_.forwardRef(function(e,t){return _.createElement(Re,Object.assign({},e,{id:"delete-icon",ref:t,icon:Vn}))});xt.displayName="DeleteIcon";var 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:"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"}}]},kt=_.forwardRef(function(e,t){return _.createElement(Re,Object.assign({},e,{id:"increase-icon",ref:t,icon:Bn}))});kt.displayName="IncreaseIcon";var 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:"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"}}]},wt=_.forwardRef(function(e,t){return _.createElement(Re,Object.assign({},e,{id:"more-icon",ref:t,icon:Hn}))});wt.displayName="MoreIcon";var 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:"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"}}]},At=_.forwardRef(function(e,t){return _.createElement(Re,Object.assign({},e,{id:"select-range-icon",ref:t,icon:Kn}))});At.displayName="SelectRangeIcon";function jn(e){const{onChange:t}=e,n="-1",[o,r]=_.useState(""),[s,c]=_.useState([]),[i,d]=_.useState(0),[g,S]=_.useState(n),[v,h]=_.useState(0),[f,u]=_.useState(null),E=l.useDependency(me.IDescriptionService),m=l.useDependency(a.LocaleService),C=l.useDependency(l.ISidebarService),I=l.useObservable(C.sidebarOptions$),b=wn(R.FunctionType,m);b.unshift({label:m.t("formula.moreFunctions.allFunctions"),value:n});const N=m.t("formula.prompt.required"),p=m.t("formula.prompt.optional");_.useEffect(()=>{W(n)},[]),_.useEffect(()=>{x(0)},[s]),_.useEffect(()=>{I!=null&&I.visible&&(r(""),c([]),d(0),S(n),h(0),u(null),W(n))},[I]);const M=O=>{if(o.trim()==="")return O;const A=new RegExp(`(${o.toLocaleUpperCase()})`);return O.split(A).filter(Boolean).map((P,V)=>P.match(A)?y.jsx("span",{className:"univer-text-red-500",children:P},V):P)},x=O=>{if(s.length===0){u(null);return}h(O);const A=E.getFunctionInfo(s[O].name);if(!A){u(null);return}u(A),t(A)};function W(O){S(O);const A=E.getSearchListByType(+O);c(A)}function U(O){r(O);const A=E.getSearchListByName(O);c(A)}function w(O){if(O.stopPropagation(),O.key==="ArrowDown"){const A=i+1;d(A===s.length?0:A)}else if(O.key==="ArrowUp"){const A=i-1;d(A===-1?s.length-1:A)}else O.key==="Enter"&&x(i)}const $=O=>{d(O)},k=()=>{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:g,options:b,onChange:W}),y.jsx(B.Input,{placeholder:m.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:w,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:w,tabIndex:-1,children:s.map(({name:O},A)=>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":i===A}),onMouseEnter:()=>$(A),onMouseLeave:k,onClick:()=>x(A),children:[v===A&&y.jsx(Nt,{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)})]},A))}),f&&y.jsxs("div",{className:B.clsx("univer-mx-0 univer-my-2 univer-overflow-y-auto",B.scrollbarClassName),children:[y.jsx(We,{title:f.functionName,value:f.description}),y.jsx(We,{title:m.t("formula.moreFunctions.syntax"),value:y.jsx(Mt,{prefix:f.functionName,value:f.functionParameter})}),y.jsx(We,{title:m.t("formula.prompt.helpExample"),value:`${f.functionName}(${f.functionParameter.map(O=>O.example).join(",")})`}),f.functionParameter&&f.functionParameter.map(O=>y.jsx(We,{title:O.name,value:`${O.require?N:p} ${O.detail}`},O.name))]})]})}function qn(){const e=D.useActiveWorkbook(),[t,n]=_.useState(!0),[o,r]=_.useState(!1),[s,c]=_.useState(null);l.useDependency(D.IEditorBridgeService);const i=l.useDependency(a.LocaleService),d=l.useDependency(J.IEditorService),g=l.useDependency(a.IUniverInstanceService),S=l.useDependency(a.ICommandService);function v(){n(!t),r(!o)}function h(){const f=L.getSheetCommandTarget(g);if(!f)return;S.executeCommand(D.SetCellEditVisibleOperation.id,{visible:!0,unitId:f.unitId,eventType:j.DeviceInputEventType.Dblclick});const u=d.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),E=d.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),m=`=${s==null?void 0:s.functionName}(`;u==null||u.replaceText(m),E==null||E.replaceText(m,!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(jn,{onChange:c}),o&&y.jsx(An,{functionInfo:s,onChange:()=>{}}),y.jsxs("div",{className:"univer-flex univer-justify-end",children:[o&&y.jsx(B.Button,{variant:"primary",onClick:v,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:i.t("formula.moreFunctions.next")}),o&&y.jsx(B.Button,{onClick:v,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:i.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:i.t("formula.moreFunctions.confirm")})]})]})}function Yn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Gn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Zn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Xn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Qn(e){return{id:Be.id,title:"formula.insert.more",tooltip:"formula.insert.tooltip",type:l.MenuItemType.BUTTON,hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Jn(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 er(e){return{id:Ue.id,type:l.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:Jn(e).pipe(q.combineLatestWith(D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint],worksheetTypes:[L.WorksheetSetCellValuePermission,L.WorksheetEditPermission]})),q.map(([t,n])=>t||n))}}const tr={[l.RibbonFormulasGroup.BASIC]:{[`${ce.id}.sum`]:{order:0,menuItemFactory:Yn},[`${ce.id}.count`]:{order:1,menuItemFactory:zn},[`${ce.id}.average`]:{order:2,menuItemFactory:Gn},[`${ce.id}.max`]:{order:3,menuItemFactory:Zn},[`${ce.id}.min`]:{order:4,menuItemFactory:Xn}},[l.RibbonFormulasGroup.OTHERS]:{[Be.id]:{order:0,menuItemFactory:Qn}},[D.PASTE_SPECIAL_MENU_ID]:{[Ue.id]:{order:4,menuItemFactory:er}}},nr="meta_key_ctrl_And_Shift";function rr(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],or=[...ze,l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ESC];function sr(){const e=[];for(const t of or)e.push({id:Ie.id,binding:t,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t}});return e}function ir(){const e=[];for(const t of ze)e.push({id:Ie.id,binding:t|l.MetaKeys.SHIFT,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.SHIFT}});return e}function cr(){const e=[];for(const t of ze)e.push({id:Ie.id,binding:t|l.MetaKeys.CTRL_COMMAND,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.CTRL_COMMAND}});return e}function ar(){const e=[];for(const t of ze)e.push({id:Ie.id,binding:t|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:nr}});return e}const lr={id:st.id,binding:l.KeyCode.F4,preconditions:e=>D.whenFormulaEditorActivated(e)};function ur(){const e=[];for(const t of[l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP])e.push({id:Ie.id,binding:t,preconditions:n=>rr(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}const dr={id:me.QuickSumCommand.id,binding:l.MetaKeys.ALT|l.KeyCode.EQUAL,preconditions:D.whenSheetEditorFocused,mac:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.ALT|l.KeyCode.EQUAL,description:"shortcut.sheets-formula-ui.quick-sum",group:"4_sheet-edit"};var fr=Object.getOwnPropertyDescriptor,hr=(e,t,n,o)=>{for(var r=o>1?void 0:o?fr(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},be=(e,t)=>(n,o)=>t(n,o,e);let Ge=class extends a.Disposable{constructor(e,t,n,o,r,s,c){super(),this._injector=e,this._menuManagerService=t,this._commandService=n,this._shortcutService=o,this._uiPartsService=r,this._renderManagerService=s,this._componentManager=c,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(tr)}_registerCommands(){[Ue,ce,Be,_t,vt,Ie,st].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_registerShortcuts(){[...sr(),...ir(),...cr(),...ar(),...ur(),dr,lr].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(D.SheetsUIPart.FORMULA_AUX,()=>l.connectInjector(kn,this._injector))),this._componentManager.register(Ct,qn)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,[qe]))}};Ge=hr([be(0,a.Inject(a.Injector)),be(1,l.IMenuManagerService),be(2,a.ICommandService),be(3,l.IShortcutService),be(4,l.IUIPartsService),be(5,j.IRenderManagerService),be(6,a.Inject(l.ComponentManager))],Ge);class at{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 gr=Object.getOwnPropertyDescriptor,vr=(e,t,n,o)=>{for(var r=o>1?void 0:o?gr(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},ke=(e,t)=>(n,o)=>t(n,o,e);F.RefSelectionsRenderService=class extends D.BaseSelectionRenderService{constructor(n,o,r,s,c,i,d){super(o,r,s,c,i);Y(this,"_workbookSelections");Y(this,"_eventDisposables");this._context=n,this._contextService=i,this._refSelectionsService=d,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Sr(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:c}=n,{scene:i}=this._context,d=new a.DisposableCollection;return d.add(s==null?void 0:s.onPointerDown$.subscribeEvent((g,S)=>{this.inRefSelectionMode()&&(this._onPointerDown(g,s.zIndex+1,a.RANGE_TYPE.NORMAL,this._getActiveViewport(g)),g.button!==2&&S.stopPropagation())})),d.add(o==null?void 0:o.onPointerDown$.subscribeEvent((g,S)=>{if(!this.inRefSelectionMode())return;const v=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:h}=D.getCoordByOffset(g.offsetX,g.offsetY,i,v);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.ROW)||(this._onPointerDown(g,(s.zIndex||1)+1,a.RANGE_TYPE.ROW,this._getActiveViewport(g),j.ScrollTimerType.Y),g.button!==2&&S.stopPropagation())})),d.add(r==null?void 0:r.onPointerDown$.subscribeEvent((g,S)=>{if(!this.inRefSelectionMode())return;const v=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:h}=D.getCoordByOffset(g.offsetX,g.offsetY,i,v);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.COLUMN)||(this._onPointerDown(g,(s.zIndex||1)+1,a.RANGE_TYPE.COLUMN,this._getActiveViewport(g),j.ScrollTimerType.X),g.button!==2&&S.stopPropagation())})),d.add(c==null?void 0:c.onPointerDown$.subscribeEvent((g,S)=>{if(this._reset(),!this.inRefSelectionMode())return;const v=this._sheetSkeletonManagerService.getCurrent().skeleton,h=D.getAllSelection(v);this._addSelectionControlByModelData(h),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const f=i.onPointerUp$.subscribeEvent(()=>{f.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});g.button!==2&&S.stopPropagation()})),d}_addSelectionControlByModelData(n){var i;const o=this._skeleton,r=(i=n.style)!=null?i:D.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,L.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(n=>{this._updateSelections(n,L.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(n=>{this._updateSelections(n,L.SelectionMoveType.MOVE_END)}))}_updateSelections(n,o){const s=this._context.unit.getActiveSheet().getSheetId();n.length!==0&&this._workbookSelections.setSelections(s,n.map(c=>L.convertSelectionDataToRange(c)),o)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(n=>{var i;if(!n)return;const{skeleton:o}=n,{scene:r}=this._context,s=r.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&((i=this._skeleton.worksheet)==null?void 0:i.getSheetId())!==o.worksheet.getSheetId()&&this._reset(),this._changeRuntime(o,r,s);const c=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(c)}))}_getActiveViewport(n){const o=this._getSheetObject();return o==null?void 0:o.scene.getActiveViewportByCoord(j.Vector2.FromArray([n.offsetX,n.offsetY]))}_getSheetObject(){return D.getSheetObject(this._context.unit,this._context)}_onPointerDown(n,o=0,r=a.RANGE_TYPE.NORMAL,s,c=j.ScrollTimerType.ALL){var $;this._rangeType=r;const i=this._skeleton,d=this._scene;if(!d||!i)return;s&&(this._activeViewport=s);const{offsetX:g,offsetY:S}=n,v=d.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!v)return;const h=d.getCoordRelativeToViewport(j.Vector2.FromArray([g,S])),{x:f,y:u}=h;this._startViewportPosX=f,this._startViewportPosY=u;const E=d.getScrollXYInfoByViewport(h),{scaleX:m,scaleY:C}=d.getAncestorScale(),I=this._skeleton.getCellByOffset(f,u,m,C,E);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}const b={range:I,primary:I,style:null};b.range.rangeType=r;const N=D.attachSelectionWithCoord(b,this._skeleton);this._startRangeWhenPointerDown={...N.rangeWithCoord};const p={...N.rangeWithCoord,rangeType:r};let M=this.getActiveSelectionControl();const x=this.getSelectionControls();for(const k of x){if(n.button===2&&a.Rectangle.contains(k.model,p)){M=k;return}if(k.model.isEqual(p)){M=k;break}}this._checkClearPreviousControls(n);const W=M==null?void 0:M.model.currentCell,U=n.shiftKey&&W,w=this._remainLastEnabled&&!n.ctrlKey&&!n.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;U&&W?this._makeSelectionByTwoCells(W,p,i,r,M):w&&M?M.updateRangeBySelectionWithCoord(N):M=this.newSelectionControl(d,i,b);for(let k=0;k<this.getSelectionControls().length-1;k++)this.getSelectionControls()[k].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),d.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),($=d.getTransformer())==null||$.clearSelectedObjects(),this._setupPointerMoveListener(v,M,r,c,f,u),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=d.onPointerUp$.subscribeEvent(()=>{var k;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(k=this._escapeShortcutDisposable)==null||k.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(n,o,r){const s=this.getSelectionControls().length,{rowHeaderWidth:c,columnHeaderHeight:i}=o,d=new D.SelectionControl(n,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:c,columnHeaderHeight:i}),g=D.attachSelectionWithCoord(r,o);return d.updateRangeBySelectionWithCoord(g),this._selectionControls.push(d),d.setControlExtension({skeleton:o,scene:n,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),d}},F.RefSelectionsRenderService=vr([ke(1,a.Inject(a.Injector)),ke(2,a.Inject(a.ThemeService)),ke(3,l.IShortcutService),ke(4,a.Inject(D.SheetSkeletonManagerService)),ke(5,a.IContextService),ke(6,L.IRefSelectionsService)],F.RefSelectionsRenderService);function Sr(e){const t=D.genNormalSelectionStyle(e);return t.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},t}const lt=(e,t,n=!0)=>{let o=-1;return e.reduce((r,s,c)=>{if(r.isFinish)return r;const i=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>i&&t<=r.currentIndex)&&(o=c,r.isFinish=!0),r},{currentIndex:0,isFinish:!1}),o},Pt=(e,t)=>{const n=e[t];let o=-1;if(!n||typeof n=="string"||n.nodeType!==R.sequenceNodeType.REFERENCE)return-1;for(let r=0;r<=t;r++){const s=e[r];typeof s!="string"&&s.nodeType===R.sequenceNodeType.REFERENCE&&o++}return o},pr=(e,t=100)=>{_.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 Lt(e,t,n){const o=l.useDependency(J.IEditorService),r=_.useMemo(()=>new q.BehaviorSubject({left:-999,top:-999,right:-999,bottom:-999}),[]),s=l.useDependency(l.ISidebarService),c=l.useDependency(a.IUniverInstanceService),i=l.useEvent(()=>{var b;const d=o.getEditor(e);if(!d)return;const g=d.getBoundingClientRect(),{marginTop:S=0,marginBottom:v=0}=d.getDocumentData().documentStyle,h=d.getSkeleton();if(!h)return;const f=(b=h.getSkeletonData())==null?void 0:b.pages[0].height;let{left:u,top:E,right:m,bottom:C}=g;E=E+S,C=f?E+f:C-v;const I=r.getValue();if(!(I.left===u&&I.top===E&&I.right===m&&I.bottom===C))return r.next({left:u-1,right:m+1,top:E-1,bottom:C+1}),g});return _.useEffect(()=>{t&&i()},[e,o,c.unitAdded$,i,t,...n!=null?n:[]]),pr(i),_.useEffect(()=>{const d=s.scrollEvent$.pipe(q.throttleTime(100)).subscribe(i);return()=>{d.unsubscribe()}},[]),[r,i]}const Te=e=>{const t=_.useRef(e);return t.current=e,t},mr=(e,t,n)=>{const o=l.useDependency(Ve),r=l.useDependency(me.IDescriptionService),s=l.useDependency(R.LexerTreeBuilder),[c,i]=_.useState(),[d,g]=_.useState(-1),[S,v]=_.useState(!0),h=Te(S),f=_.useRef(t);f.current=t;const u=()=>{i(void 0),g(-1),v(!1)};return _.useEffect(()=>{const E=s.sequenceNodesBuilder(t.slice(1));o.setSequenceNodes(E!=null?E:[])},[t]),_.useEffect(()=>{if(n&&e){const E=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(C=>{if(C.textRanges.length===1){const[I]=C.textRanges;if(I.collapsed&&h.current){const{startOffset:b}=I,N=o.getCurrentSequenceNodeIndex(b-2),p=o.getCurrentSequenceNodeByIndex(N),M=o.getCurrentSequenceNodeByIndex(N+1);if(p)if(typeof p!="string"&&p.nodeType===3&&!r.hasDefinedNameDescription(p.token.trim())&&M===R.matchToken.OPEN_BRACKET){const x=r.getFunctionInfo(p.token);i(x),g(-1);return}else{const x=s.getFunctionAndParameter(`${f.current}A`,b-1);if(x){const{functionName:W,paramIndex:U}=x,w=r.getFunctionInfo(W);i(w),g(U);return}}}}i(void 0),g(-1)}),m=n.selectionChange$.pipe(q.filter(C=>C.textRanges.length===1),q.map(C=>C.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{v(!0)});return()=>{E.unsubscribe(),m.unsubscribe()}}},[n,e]),_.useEffect(()=>{e||u()},[e]),{functionInfo:c,paramIndex:d,reset:u}},Cr=({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:"?"}),ut=({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})]}),_r=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,c)=>y.jsxs("span",{children:[y.jsx("span",{className:o===c?"univer-text-primary-500":"",onClick:()=>r(c),children:Tt(s)}),c===n.length-1?"":","]},s.name)),")"]})},$t=()=>{};function Er(e){const{onParamsSwitch:t=$t,onClose:n=$t,isFocus:o,editor:r,formulaText:s}=e,{functionInfo:c,paramIndex:i,reset:d}=mr(o,s,r),g=l.useDependency(D.IEditorBridgeService),S=!l.useObservable(g.helpFunctionVisible$),[v,h]=_.useState(!0),f=l.useDependency(a.LocaleService),u=f.t("formula.prompt.required"),E=f.t("formula.prompt.optional"),m=r.getEditorId(),[C]=Lt(m,!!c,[c,i]);function I(p){t&&t(p)}const b=l.useEvent(p=>{g.helpFunctionVisible$.next(!p)}),N=()=>{b(!0),n()};return c?S?y.jsx(l.RectPopup,{portal:!0,anchorRect$:C,direction:"left-center",children:y.jsx(Cr,{onClick:()=>b(!1)})},"hidden"):y.jsx(l.RectPopup,{portal:!0,onClickOutside:()=>d(),anchorRect$:C,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(_r,{prefix:c.functionName,value:c.functionParameter,active:i,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:v?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!v),children:y.jsx(wt,{})}),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:N,children:y.jsx(Dt,{})})]})]}),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:v?"unset":0,padding:v?"revert-layer":0},children:y.jsxs("div",{className:"univer-mt-3",children:[y.jsx(ut,{title:f.t("formula.prompt.helpExample"),value:`${c.functionName}(${c.functionParameter.map(p=>p.example).join(",")})`}),y.jsx(ut,{title:f.t("formula.prompt.helpAbstract"),value:c.description}),c&&c.functionParameter&&c.functionParameter.map((p,M)=>y.jsx(ut,{className:i===M?"univer-text-primary-500":"",title:p.name,value:`${p.require?u:E} ${p.detail}`},M))]})})]})},"show"):null}const Ir=e=>{const t=l.useDependency(J.IEditorService);return l.useEvent(o=>{var r,s;if(e){t.focus(e.getEditorId());const c=[...e.getSelectionRanges()];if(a.Tools.isDefine(o))e.setSelectionRanges([{startOffset:o,endOffset:o}]);else if(!c.length&&!e.docSelectionRenderService.isOnPointerEvent){const i=(s=(r=e.getDocumentData().body)==null?void 0:r.dataStream)!=null?s:`\r
2
- `,d=Math.max(i.length-2,0);e.setSelectionRanges([{startOffset:d,endOffset:d}])}else e.setSelectionRanges(c)}})};function yr(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 fe=(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))(fe||{});function Rr(e){var x;const{editorId:t,isFocus:n,disableOnClick:o,unitId:r,subUnitId:s}=e,c=l.useDependency(j.IRenderManagerService),i=l.useDependency(a.IUniverInstanceService),d=c.getRenderById(r),g=c.getRenderById(t),S=g==null?void 0:g.with(J.DocSelectionRenderService),v=l.useDependency(ht.DocSelectionManagerService),h=l.useDependency(a.Injector),[f,u]=_.useState(0),E=l.useDependency(R.LexerTreeBuilder),m=_.useRef(!0),C=d==null?void 0:d.with(F.RefSelectionsRenderService),I=Te(f),b=i.getUnit(r,a.UniverInstanceType.UNIVER_SHEET),N=b==null?void 0:b.getSheetBySheetId(s),p=l.useEvent(W=>{C&&C.setSkipLastEnabled(W===1||W===3||W===4),I.current=W,u(W)}),M=l.useEvent(()=>{var oe,se,le;const W=i.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!W)return;const U=W.getActiveSheet(),w=S==null?void 0:S.getActiveTextRange(),$=w!=null&&w.collapsed?w.startOffset:-1,k=yr(h);if(!k)return;const O=(oe=k==null?void 0:k.dataStream)==null?void 0:oe.slice(0,-2),A=((se=E.sequenceNodesBuilder(O))!=null?se:[]).map(z=>typeof z=="object"?z.nodeType===R.sequenceNodeType.REFERENCE?{...z,range:R.deserializeRangeWithSheetWithCache(z.token)}:{...z,range:void 0}:z),T=O[$-1],P=O[$],V=A.find(z=>typeof z=="object"&&z.nodeType===R.sequenceNodeType.REFERENCE&&$===z.endIndex+2),H=T&&R.matchRefDrawToken(T)&&(!P||R.isFormulaLexerToken(P)&&P!==R.matchToken.OPEN_BRACKET),K=!!V;if((O==null?void 0:O.substring(0,1))==="="&&(H||K))if(K){if(m.current)return;const{sheetName:z,unitId:ee}=V.range,we=(le=i.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:le.getUnitId();ee&&ee!==we?p(4):!z&&U.getSheetId()===(N==null?void 0:N.getSheetId())||z===U.getName()?p(2):p(3)}else m.current=!1,p(1);else p(0)});return _.useEffect(()=>{const W=v.textSelection$.pipe(q.filter(U=>U.unitId===t)).subscribe(()=>{M()});return()=>W.unsubscribe()},[M,v.textSelection$,t]),_.useEffect(()=>{n||(p(0),m.current=!0)},[n,p]),_.useEffect(()=>{var U;if(!o)return;const W=(U=g==null?void 0:g.mainComponent)==null?void 0:U.onPointerDown$.subscribeEvent(()=>{p(0),m.current=!0});return()=>W==null?void 0:W.unsubscribe()},[o,(x=g==null?void 0:g.mainComponent)==null?void 0:x.onPointerDown$,p]),_.useEffect(()=>{if(!n)return;const W=b==null?void 0:b.activeSheet$.subscribe(()=>{M()}),U=i.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>{M()});return()=>{W==null||W.unsubscribe(),U==null||U.unsubscribe()}},[M,n,b==null?void 0:b.activeSheet$,i.getCurrentTypeOfUnit$]),{isSelecting:f,isSelectingRef:I}}const br=()=>{const e=l.useDependency(R.LexerTreeBuilder);return _.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function Tr(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 Ft(e){var b,N,p;const{unitId:t,subUnitId:n,currentWorkbook:o,refSelections:r,editor:s,refSelectionsService:c,refSelectionsRenderService:i,sheetSkeletonManagerService:d,themeService:g,univerInstanceService:S}=e,v=o.getUnitId(),h=S.getUnit(t,a.UniverInstanceType.UNIVER_SHEET),f=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!f){c.setSelections(u);return}const E=f.getSheetId(),m=M=>{var x;return(x=h==null?void 0:h.getSheetBySheetName(M))==null?void 0:x.getSheetId()};if(!((b=d==null?void 0:d.getWorksheetSkeleton(E))==null?void 0:b.skeleton))return;const I=[];for(let M=0,x=r.length;M<x;M++){const W=r[M],{themeColor:U,token:w,refIndex:$,endIndex:k}=W,O=R.deserializeRangeWithSheet(w),{unitId:A,sheetName:T,range:P}=O,V=m(T);if(!V&&T||v!==t&&A!==v||A&&A!==v||V&&V!==E||!V&&E!==n)continue;const H=L.setEndForRange(P,f.getRowCount(),f.getColumnCount());H.unitId=t,H.sheetId=E,u.push({range:H,primary:null,style:Tr(g,U,$.toString())}),I.push(k)}if(s){const M=(p=(N=s.getSelectionRanges())==null?void 0:N[0])==null?void 0:p.startOffset,x=I.findIndex(W=>W+2===M);x!==-1?i==null||i.setActiveSelectionIndex(x):i==null||i.resetActiveSelectionIndex()}return u}function Mr(e,t){const n=l.useDependency(a.IUniverInstanceService),o=l.useDependency(a.ThemeService),r=l.useDependency(L.IRefSelectionsService),s=l.useDependency(j.IRenderManagerService),c=l.useObservable(_.useMemo(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[n])),i=c?s.getRenderById(c.getUnitId()):null,d=i==null?void 0:i.with(F.RefSelectionsRenderService),g=i==null?void 0:i.with(D.SheetSkeletonManagerService),S=l.useEvent((v,h)=>{const f=n.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!f||d!=null&&d.selectionMoving)return;const u=Ft({unitId:e,subUnitId:t,currentWorkbook:f,refSelections:v,editor:h,refSelectionsService:r,refSelectionsRenderService:d,sheetSkeletonManagerService:g,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 _.useEffect(()=>()=>{d==null||d.resetActiveSelectionIndex()},[d]),S}function Wt(e=""){const t=l.useDependency(me.IDescriptionService),n=Or(),o=l.useDependency(a.ICommandService),r=_.useMemo(()=>e.length,[e]);return l.useEvent((c,i,d=!0,g)=>{const S=c.getDocumentData(),v=c.getEditorId();if(!S)return[];const h=S.body;if(!h)return[];const f=h.dataStream.slice(0,h.dataStream.length-2),u={dataStream:"",...S.body};if(!f.startsWith(e))return[];if(i==null||i.length===0)return u.textRuns=[],o.syncExecuteCommand(J.ReplaceTextRunsCommand.id,{unitId:v,body:a.getBodySlice(u,0,u.dataStream.length-2)}),[];{const{textRuns:E,refSelections:m}=Nr(t,n,i);r&&E.forEach(b=>{b.ed=b.ed+r,b.st=b.st+r}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},...E];const C=i.reduce((b,N)=>typeof N=="string"?`${b}${N}`:`${b}${N.token}`,"");u.dataStream=`${e}${C}\r
3
- `;let I;if(d){I=c.getSelectionRanges();const b=u.dataStream.length-2+r;I.forEach(N=>{N.startOffset=Math.max(0,Math.min(N.startOffset,b)),N.endOffset=Math.max(0,Math.min(N.endOffset,b))})}return o.syncExecuteCommand(J.ReplaceTextRunsCommand.id,{unitId:v,body:a.getBodySlice(u,0,u.dataStream.length-2),textRanges:g!=null?g:I}),m}})}function Or(){const e=l.useDependency(a.ThemeService),t=e.getCurrentTheme();return _.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(i=>e.isValidThemeColor(i)?e.getColorFromTheme(i):i),r=e.getColorFromTheme("blue.700"),s=e.getColorFromTheme("jiqing.800"),c=e.getColorFromTheme("black");return{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:c}},[t])}function Nr(e,t,n){const{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:c}=t,i=[],d=[],g=new Map;let S=0;for(let v=0,h=n.length;v<h;v++){const f=n[v];if(typeof f=="string"){const b=i[i.length-1],N=b?b.ed:0,p=N+f.length;i.push({st:N,ed:p,ts:{cl:{rgb:c},fs:11}});continue}if(e.hasDefinedNameDescription(f.token.trim())){i.push({st:f.startIndex,ed:f.endIndex+1,ts:{cl:{rgb:c},fs:11}});continue}const{startIndex:u,endIndex:E,nodeType:m,token:C}=f;let I="";if(m===R.sequenceNodeType.REFERENCE){if(g.has(C))I=g.get(C);else{const b=S%o.length;I=o[b],g.set(C,I),S++}d.push({refIndex:v,themeColor:I,token:C,startIndex:f.startIndex,endIndex:f.endIndex,index:d.length})}else m===R.sequenceNodeType.NUMBER?I=r:(m===R.sequenceNodeType.STRING||m===R.sequenceNodeType.ARRAY)&&(I=s);I&&I.length>0?i.push({st:u,ed:E+1,ts:{cl:{rgb:I},fs:11}}):i.push({st:u,ed:E+1,ts:{cl:{rgb:c},fs:11}})}return{textRuns:i,refSelections:d}}const Dr=(e,t,n,o)=>{const r=l.useDependency(a.ICommandService),s=l.useDependency(l.IShortcutService),c=_.useRef(t);c.current=t;const i=_.useRef(o);i.current=o,_.useEffect(()=>{if(!n||!e)return;const g=`sheet.formula-embedding-editor.${n.getEditorId()}`,S=new a.DisposableCollection,v=(u,E)=>{if(i.current){i.current(u,E);return}let m=a.Direction.LEFT;u===l.KeyCode.ARROW_DOWN?m=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?m=a.Direction.UP:u===l.KeyCode.ARROW_RIGHT&&(m=a.Direction.RIGHT),E===l.MetaKeys.SHIFT?r.executeCommand(J.MoveSelectionOperation.id,{direction:m}):r.executeCommand(J.MoveCursorOperation.id,{direction:m})},h=(u,E)=>{let m=a.Direction.DOWN;u===l.KeyCode.ARROW_DOWN?m=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?m=a.Direction.UP:u===l.KeyCode.ARROW_LEFT?m=a.Direction.LEFT:u===l.KeyCode.ARROW_RIGHT&&(m=a.Direction.RIGHT),c.current?E===l.MetaKeys.CTRL_COMMAND?r.executeCommand(D.MoveSelectionCommand.id,{direction:m,jumpOver:D.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:c.current===fe.NEED_ADD||c.current===fe.EDIT_OTHER_SHEET_REFERENCE}):E===l.MetaKeys.SHIFT?r.executeCommand(D.ExpandSelectionCommand.id,{direction:m,extra:"formula-editor"}):E===(l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT)?r.executeCommand(D.ExpandSelectionCommand.id,{direction:m,jumpOver:D.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand(D.MoveSelectionCommand.id,{direction:m,extra:"formula-editor",fromCurrentSelection:c.current===fe.NEED_ADD||c.current===fe.EDIT_OTHER_SHEET_REFERENCE}):v(u,E)};return S.add(r.registerCommand({id:g,type:a.CommandType.OPERATION,handler(u,E){const{keyCode:m,metaKey:C}=E;h(m,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:E})=>({id:g,binding:E?u|E:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:u,metaKey:E}})).forEach(u=>{S.add(s.registerShortcut(u))}),()=>{S.dispose()}},[r,n,e,s])},xr=(e,t,n,o,r=!0)=>{var f;const s=l.useDependency(j.IRenderManagerService),c=l.useDependency(a.IContextService),i=l.useDependency(l.IContextMenuService),d=l.useDependency(L.IRefSelectionsService),g=l.useDependency(a.IUniverInstanceService),S=l.useObservable(_.useMemo(()=>g.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[g])),v=s.getRenderById((f=S==null?void 0:S.getUnitId())!=null?f:""),h=v==null?void 0:v.with(F.RefSelectionsRenderService);_.useLayoutEffect(()=>{if(e)return c.setContextValue(a.EDITOR_ACTIVATED,!0),r&&i.disable(),()=>{const u=g.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_DOC);(u==null?void 0:u.getUnitId())===o&&c.setContextValue(a.EDITOR_ACTIVATED,!1),r&&i.enable(),d.clear()}},[c,e,d,r,o]),_.useLayoutEffect(()=>{if(e&&t){const u=h==null?void 0:h.enableSelectionChanging();return c.setContextValue(L.REF_SELECTIONS_ENABLED,!0),()=>{c.setContextValue(L.REF_SELECTIONS_ENABLED,!1),u==null||u.dispose()}}},[c,e,h,t]),_.useEffect(()=>{e&&(h==null||h.setSkipLastEnabled(!1))},[e,h])},kr=(e,t,n)=>{const o=l.useDependency(a.IUniverInstanceService),r=l.useDependency(L.SheetsSelectionsService);return _.useCallback(()=>{if(e){const c=[...r.getWorkbookSelections(t).getSelectionsOfWorksheet(n)],i=o.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),d=i==null?void 0:i.getActiveSheet();(i==null?void 0:i.getUnitId())!==t&&o.setCurrentUnitForType(t),d&&d.getSheetId()===n&&r.setSelections(c)}},[e,r,n,t,o])},wr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),dt=e=>e.map(t=>typeof t=="string"?t:t.token).join(""),Ze=(e,t=!1,n="",o=!1)=>!t&&!o?e.map(r=>R.serializeRange(r.range)):e.map(r=>o?R.serializeRangeToRefString(r):r.sheetName!==""&&r.sheetName!==n?R.serializeRangeWithSheet(r.sheetName,r.range):R.serializeRange(r.range)),Ar=e=>{var S,v,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,c=((v=(S=t==null?void 0:t.getDocumentData().body)==null?void 0:S.dataStream)!=null?v:`\r
4
- `).slice(0,-2),i=(h=n.sequenceNodesBuilder(c.slice(1)))!=null?h:[],d=lt(i,s,!1),g=Pt(i,d);return{nodeIndex:d,updatingRefIndex:g,sequenceNodes:i,offset:s}},Pr=(()=>{}),Lr=(e,t,n,o,r,s,c,i,d,g=Pr)=>{var $;const S=l.useDependency(j.IRenderManagerService),v=l.useDependency(a.IUniverInstanceService),h=l.useDependency(a.ICommandService),f=l.useDependency(ht.DocSelectionManagerService),u=l.useDependency(a.ThemeService),E=l.useDependency(R.LexerTreeBuilder),m=v.getUnit(o),C=l.useEvent((k,O)=>{var A,T,P;return(P=(T=(A=v.getUnit(k))==null?void 0:A.getSheetBySheetId(O))==null?void 0:T.getName())!=null?P:""}),I=_.useMemo(()=>C(o,r),[C,r,o]),b=l.useObservable(m==null?void 0:m.activeSheet$),N=Te({activeSheet:b,sheetName:I}),p=l.useObservable(_.useMemo(()=>v.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[v])),M=S.getRenderById(($=p==null?void 0:p.getUnitId())!=null?$:""),x=M==null?void 0:M.with(F.RefSelectionsRenderService),W=M==null?void 0:M.with(D.SheetSkeletonManagerService),U=l.useDependency(L.IRefSelectionsService),w=l.useEvent((k,O)=>{var K,oe,se,le,z,ee,we,Ae,Qe,he;const A=Ar({editor:d,lexerTreeBuilder:E});if(!A)return;const{nodeIndex:T,updatingRefIndex:P,sequenceNodes:V,offset:H}=A;if(n.current===fe.NEED_ADD)if(H!==0){if(T===-1&&V.length)return;const G=k[k.length-1],Q=V.splice(T+1),ge=(K=G.sheetId)!=null?K:r,ue={range:G,unitId:(oe=G.unitId)!=null?oe:p.getUnitId(),sheetName:C((se=G.unitId)!=null?se:p.getUnitId(),ge)},te=ge!==r,ie=(p==null?void 0:p.getUnitId())!==o,ve=Ze([ue],c&&(te||ie),I,ie);V.push({token:ve[0],nodeType:R.sequenceNodeType.REFERENCE});const Me=[...V,...Q],Ce=dt(Me);g(Ce,wr(V),O)}else{const G=k[k.length-1],Q=(le=G.sheetId)!=null?le:r,ge={range:G,unitId:(z=G.unitId)!=null?z:p.getUnitId(),sheetName:C((ee=G.unitId)!=null?ee:p.getUnitId(),Q)},ue=Q!==r,te=(p==null?void 0:p.getUnitId())!==o,ie=Ze([ge],c&&(ue||te),I,te);V.unshift({token:ie[0],nodeType:R.sequenceNodeType.REFERENCE});const ve=dt(V);g(ve,ie[0].length,O)}else if(n.current===fe.EDIT_OTHER_SHEET_REFERENCE||n.current===fe.EDIT_OTHER_WORKBOOK_REFERENCE){const G=k.pop();if(!G)return;const Q=V[T];if(typeof Q=="object"&&Q.nodeType===R.sequenceNodeType.REFERENCE){const ge=Q.token;(p==null?void 0:p.getUnitId())!==o?Q.token=R.serializeRangeWithSpreadsheet((we=p==null?void 0:p.getUnitId())!=null?we:"",I,G):Q.token=I===(b==null?void 0:b.getName())?R.serializeRange(G):R.serializeRangeWithSheet(b.getName(),G);const te=H+(Q.token.length-ge.length);g(R.generateStringWithSequence(V),te,O)}}else{const G=[...k];if(P!==-1){const Z=G.pop();Z&&G.splice(P,0,Z)}let Q=0;const ge=V.map(Z=>{var de,Pe,Oe,Ne;if(typeof Z=="string")return Z;if(Z.nodeType===R.sequenceNodeType.REFERENCE){const De=R.deserializeRangeWithSheet(Z.token);if(De.sheetName||(De.sheetName=I),(De.unitId||o)!==(p==null?void 0:p.getUnitId())||c&&((de=N.current.activeSheet)==null?void 0:de.getName())!==De.sheetName)return Z.token;const ne=G[Q];if(Q++,!ne)return"";const Se=(Pe=ne.sheetId)!=null?Pe:r,Je={range:ne,unitId:(Oe=ne.unitId)!=null?Oe:p.getUnitId(),sheetName:C((Ne=ne.unitId)!=null?Ne:p.getUnitId(),Se)},et=(p==null?void 0:p.getUnitId())!==o;return Ze([Je],c&&(Se!==r||et),I,et)[0]}return Z.token});let ue="",te;ge.forEach((Z,de)=>{ue+=Z,de===T&&(te=ue.length)});const ie=[];for(let Z=Q;Z<=k.length-1;Z++){const de=k[Z],Pe=(Ae=de.sheetId)!=null?Ae:r,Oe={range:de,unitId:(Qe=de.unitId)!=null?Qe:p.getUnitId(),sheetName:C((he=de.unitId)!=null?he:p.getUnitId(),Pe)},Ne=(p==null?void 0:p.getUnitId())!==o,ne=Ze([Oe],c&&(Pe!==r||Ne),I,Ne);ie.push(ne[0])}const ve=V[V.length-1],Me=ve&&(typeof ve=="string"?!1:ve.nodeType===R.sequenceNodeType.REFERENCE),Ce=`${ue}${ie.length&&Me?",":""}${ie.join(",")}`;g(Ce,!ie.length&&te?te:Ce.length,O)}});_.useEffect(()=>{if(x&&e){let k=!0;const O=(T,P)=>{if(k){k=!1;return}w(T.map(V=>V.rangeWithCoord),P)},A=new a.DisposableCollection;return A.add(x.selectionMoving$.subscribe(T=>{O(T,!1)})),A.add(x.selectionMoveEnd$.subscribe(T=>{O(T,!0)})),()=>{A.dispose()}}},[e,w,x]),_.useEffect(()=>{if(t&&x&&d){const k=new a.DisposableCollection,O=()=>{k.dispose(),x.getSelectionControls().forEach((P,V)=>{k.add(P.selectionScaling$.subscribe(H=>{const K=x.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=K[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,K[V]=H,w(K,!1)})),k.add(P.selectionMoving$.subscribe(H=>{const K=x.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=K[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,K[V]=H,w(K,!0)}))})},A=q.merge(d.input$,U.selectionSet$,x.selectionMoveEnd$).pipe(Qt.debounceTime(50)).subscribe(()=>{O()});return()=>{A.unsubscribe(),k.dispose()}}},[d,t,w,x,U.selectionSet$]),x==null||x.getSelectionDataWithStyle(),_.useEffect(()=>{if(i){const k=h.onCommandExecuted(O=>{var T;if(O.id!==L.SetSelectionsOperation.id)return;const A=O.params;if(A.extra==="formula-editor"&&A.selections.length){const P=A.selections[A.selections.length-1];if(P){const V=n.current===fe.NEED_ADD,H=((T=x==null?void 0:x.getSelectionDataWithStyle())!=null?T:[]).map(K=>K.rangeWithCoord);V?H.push(P.range):H[H.length-1]=P.range,w(H,!0)}}});return()=>{k.dispose()}}},[h,d,n,E,i,w,x]),_.useEffect(()=>{if(!d)return;const k=f.textSelection$.subscribe(O=>{O.unitId===d.getEditorId()&&Ft({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:U,refSelectionsRenderService:x,sheetSkeletonManagerService:W,themeService:u,univerInstanceService:v,currentWorkbook:p})});return()=>k.unsubscribe()},[f.textSelection$,d,s,x,U,W,r,u,o,v])},$r=(e,t,n,o,r,s)=>{const c=l.useDependency(a.ICommandService),i=l.useDependency(J.IEditorService),g=l.useDependency(j.IRenderManagerService).getRenderById(t),S=l.useDependency(a.IUniverInstanceService),v=g==null?void 0:g.with(F.RefSelectionsRenderService);_.useEffect(()=>{if(e&&v)if(n){const h=()=>{const E=v.getSelectionControls().length;for(let m=1;m<=E;m++)v.clearLastSelection();return setTimeout(()=>{s()},30)},f=c.onCommandExecuted(E=>{E.id===L.SetWorksheetActiveOperation.id&&h()}),u=S.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(E=>{h()});return()=>{f.dispose(),u.unsubscribe()}}else{const h=c.beforeCommandExecuted(f=>{if(f.id===L.SetWorksheetActiveOperation.id){o(!1),r(),s();const u=i.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);u==null||u.focus()}});return()=>{h.dispose()}}},[e,v])},Fr=(e,t,n)=>{const o=l.useDependency(R.LexerTreeBuilder),r=_.useRef(!0);_.useEffect(()=>{if(e){const s=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(s)}}},[e]),_.useEffect(()=>{if(!r.current&&t){const s=o.checkIfAddBracket(n);t(s===0&&n.startsWith(R.operatorToken.EQUALS),`${n}`)}},[n,t])},Wr=(e,t=[],n)=>{const o=l.useDependency(me.IDescriptionService),[r,s]=_.useState([]),[c,i]=_.useState(""),d=_.useRef(-1),g=Te({nodes:t}),S=()=>{s([]),i(""),d.current=-1};return _.useEffect(()=>{if(n&&e){const h=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const f=n.getSelectionRanges();if(f.length===1){const u=g.current.nodes,E=f[0];if(E.collapsed){const m=lt(u,E.startOffset-1,!1);d.current=m;const C=u[m];if(C&&typeof C!="string"&&C.nodeType===R.sequenceNodeType.FUNCTION){d.current=m;const I=C.token,b=o.getSearchListByNameFirstLetter(I);s(b),i(I);return}}}d.current=-1,i(""),s(u=>u!=null&&u.length?[]:u)});return()=>{h.unsubscribe()}}},[n,e]),_.useEffect(()=>{e||S()},[e]),{searchList:r,searchText:c,handlerFormulaReplace:(h,f)=>{const u=[...g.current.nodes];if(d.current!==-1){const E=u.splice(d.current+1),m=u.pop()||"";let C=(typeof m=="string"?m.length:m.token.length)-h.length;return u.push(h),E[0]!==R.matchToken.OPEN_BRACKET&&f!==R.FunctionType.DefinedName&&(u.push(R.matchToken.OPEN_BRACKET),C--),{text:dt([...u,...E]),offset:C}}},reset:S}},Ur=()=>{},Vr=_.forwardRef(Br);function Br(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:s,onClose:c=Ur}=e,i=s.getEditorId(),d=l.useDependency(l.IShortcutService),g=l.useDependency(a.ICommandService),{searchList:S,searchText:v,handlerFormulaReplace:h,reset:f}=Wr(n,o,s),u=_.useMemo(()=>!!S.length,[S]),E=_.useRef(void 0),[m,C]=_.useState(0),I=_.useRef(!1),[b]=Lt(i,u,[v,S]),N=Te({searchList:S,active:m}),p=(w,$)=>{const k=h(w,$);k&&(f(),r(k))};function M(w){I.current&&C(w)}function x(){I.current&&C(-1)}_.useEffect(()=>{if(!S.length)return;const w=`sheet.formula-embedding-editor.search_function.${i}`,$=new a.DisposableCollection,k=O=>{const{searchList:A,active:T}=N.current;switch(O){case l.KeyCode.ARROW_UP:{C(P=>{const V=Math.max(0,P-1);return W(V),V});break}case l.KeyCode.ARROW_DOWN:{C(P=>{const V=Math.min(A.length-1,P+1);return W(V),V});break}case l.KeyCode.TAB:case l.KeyCode.ENTER:{const P=A[T];p(P.name,P.functionType);break}case l.KeyCode.ESC:{f(),c();break}}};return $.add(g.registerCommand({id:w,type:a.CommandType.OPERATION,handler(O,A){const{keyCode:T}=A;k(T)}})),[l.KeyCode.ARROW_UP,l.KeyCode.ARROW_DOWN,l.KeyCode.ENTER,l.KeyCode.ESC,l.KeyCode.TAB].map(O=>({id:w,binding:O,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:O}})).forEach(O=>{$.add(d.registerShortcut(O))}),()=>{$.dispose()}},[S]);function W(w){const $=E.current;if(!$)return;const k=$.children[w];if(!k)return;const A=$.getBoundingClientRect().top,T=$.offsetHeight,P=k.getBoundingClientRect(),V=P.top,H=P.height;if(V>=0&&V>A&&V-A+H<=T)return;const K=k.offsetTop-(T-H)/2;$.scrollTo({top:K,behavior:"smooth"})}const U=_.useMemo(()=>{let w="";return()=>{clearTimeout(w),I.current=!0,w=setTimeout(()=>{I.current=!1},300)}},[]);return S.length>0&&u&&y.jsx(l.RectPopup,{portal:!0,anchorRect$:b,direction:"vertical",children:y.jsx("ul",{ref:w=>{E.current=w,t&&(t.current=w)},"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((w,$)=>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":m===$}),onMouseEnter:()=>M($),onMouseLeave:x,onMouseMove:U,onClick:()=>{p(w.name,w.functionType),s&&s.focus()},children:[y.jsxs("span",{className:"univer-text-xs",children:[y.jsx("span",{className:"univer-text-red-500",children:w.name.substring(0,v.length)}),y.jsx("span",{children:w.name.slice(v.length)})]}),y.jsx("span",{className:"univer-block univer-text-xs univer-text-gray-400",children:w.desc})]},w.name))})})}const Hr=e=>e.startsWith(R.operatorToken.EQUALS)?e.slice(1):"",Ut=()=>{},Vt=_.forwardRef((e,t)=>{var qt,Yt,zt,Gt;const{errorText:n,initValue:o,unitId:r,subUnitId:s,isFocus:c=!0,isSupportAcrossSheet:i=!1,onFocus:d=Ut,onBlur:g=Ut,onChange:S,onVerify:v,className:h,editorId:f,moveCursor:u=!0,onFormulaSelectingChange:E,keyboardEventConfig:m,onMoveInEditor:C,resetSelectionOnBlur:I=!0,autoScrollbar:b=!0,isSingle:N=!0,disableSelectionOnClick:p=!1,autofocus:M=!0,disableContextMenu:x,style:W}=e,U=l.useDependency(J.IEditorService),w=_.useRef(null),$=l.useEvent(S);_.useImperativeHandle(t,()=>({isClickOutSide:X=>w.current?!w.current.contains(X.target):!1}));const k=l.useEvent(E),O=_.useRef(null),A=_.useRef(void 0),T=A.current,[P,V]=_.useState(c),H=_.useRef(null),K=_.useMemo(()=>f!=null?f:a.createInternalEditorID(`${D.EMBEDDING_FORMULA_EDITOR}-${a.generateRandomId(4)}`),[]),oe=_.useMemo(()=>n!==void 0,[n]),se=l.useDependency(a.IUniverInstanceService),le=se.getUnit(K);l.useObservable(le==null?void 0:le.change$);const z=br(),ee=a.BuildTextUtils.transform.getPlainText((Yt=(qt=le==null?void 0:le.getBody())==null?void 0:qt.dataStream)!=null?Yt:""),we=Te(ee),Ae=_.useMemo(()=>Hr(ee),[ee]),Qe=_.useMemo(()=>z(Ae),[Ae,z]),{isSelecting:he,isSelectingRef:G}=Rr({unitId:r,subUnitId:s,editorId:K,isFocus:P,disableOnClick:p}),Q=_.useRef(""),ue=l.useDependency(j.IRenderManagerService).getRenderById(K),te=ue==null?void 0:ue.with(J.DocSelectionRenderService),ie=te==null?void 0:te.isFocusing,ve=_.useMemo(()=>se.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[se]),Me=l.useObservable(ve),Ce=(Me==null?void 0:Me.getUnitId())===K,Z=_.useRef([]),de=he,Oe=(Gt=(zt=l.useDependency(a.IConfigService).getConfig(Et))==null?void 0:zt.functionScreenTips)!=null?Gt:!0;l.useUpdateEffect(()=>{$(ee)},[ee,$]);const Ne=Wt("="),De=Mr(r,s),ne=l.useEvent((X,re=!0,_e,pe)=>{if(!A.current)return;Q.current=X;const tt=X[0]==="="?X.slice(1):"",Ee=z(tt),no=Ee.reduce((xe,rt)=>typeof rt=="object"?`${xe}${rt.token}`:`${xe}${rt}`,""),nt=Ne(A.current,no===tt?Ee:[],re,pe);if(Z.current=nt,_e){const xe=pe!=null?pe:T==null?void 0:T.getSelectionRanges();if((xe==null?void 0:xe.length)!==1)return;const ro=xe[0].startOffset-1,oo=lt(Ee,ro,!1),Zt=Pt(Ee,oo);if(Zt>=0){const Xt=nt.splice(Zt,1)[0];Xt&&nt.push(Xt)}De(P?nt:[],A.current)}});_.useEffect(()=>{P&&ne(ee,!1,!0)},[P]),_.useEffect(()=>{if(P){if(Q.current===ee)return;ne(ee,!1,!0)}},[ee]),Fr(P,v,ee);const Se=Ir(T),Je=kr(P,r,s);_.useEffect(()=>{var X;k(he,(X=te==null?void 0:te.isFocusing)!=null?X:!0)},[k,he]),J.useKeyboardEvent(P,m,T),_.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);A.current=re,ne(o,!1,!0)}return()=>{X==null||X.dispose()}},[]),_.useLayoutEffect(()=>{c?(V(c),Se()):(I&&(T==null||T.blur(),Je()),V(c))},[c,T,Se,Je,I]);const{checkScrollBar:et}=J.useResize(T,N,b);xr(P,!!(he&&Ce),r,K,x),Dr(!!(P&&ie&&u),de,T,C);const Kt=l.useEvent((X,re,_e)=>{if(!ie)return;const pe=re!==-1?[{startOffset:re+1,endOffset:re+1,collapsed:!0}]:void 0;ne(`=${X}`,!0,_e,pe),_e&&(Se(),re!==-1&&setTimeout(()=>{const tt={startOffset:re+1,endOffset:re+1},Ee=T==null?void 0:T.render.with(J.DocBackScrollRenderController);Ee==null||Ee.scrollToRange({...tt,collapsed:!0})},50),et())});Lr(P&&!!(he&&Ce),P,G,r,s,Z,i,!!de,T,Kt),$r(P&&!!(he&&Ce),r,i,V,g,()=>{ne(we.current,!1,!0)});const jt=X=>{if(X){const re=T==null?void 0:T.getSelectionRanges();if(re&&re.length===1){const _e=re[0];if(_e.collapsed){const pe=X.offset;setTimeout(()=>{T==null||T.setSelectionRanges([{startOffset:_e.startOffset-pe,endOffset:_e.endOffset-pe}])},30)}}Se(),ne(`=${X.text}`)}},to=()=>{V(!0),d(),Se()};return y.jsxs("div",{className:h,children:[y.jsx("div",{ref:w,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":P,"univer-ring-red-500":oe}),children:y.jsx("div",{ref:H,className:"univer-relative univer-h-full univer-w-full",onMouseUp:to})}),n!==void 0&&y.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),Oe&&T&&Ae!==""&&y.jsx(Er,{editor:T,isFocus:P,formulaText:ee,onClose:()=>Se()}),Oe&&!!T&&y.jsx(Vr,{isFocus:P,sequenceNodes:Qe,onSelect:jt,ref:O,editor:T})]})});function Kr(e,t,n,o){const r=l.useDependency(R.LexerTreeBuilder),s=Wt(""),c=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[i,d]=_.useState([]),g=l.useDependency(D.IMarkSelectionService),S=_.useRef(""),v=l.useDependency(a.IUniverInstanceService);return _.useEffect(()=>{if(!e)return;const h=e.getDocumentDataModel().getPlainText();if(S.current===h)return;S.current=h;const f=r.sequenceNodesBuilder(h);d(f!=null?f:[])},[c,e,r]),_.useEffect(()=>{var u,E;if(!e)return;if(!t){const m=e.getDocumentData();e.setDocumentData({...m,body:{...m.body,dataStream:(E=(u=m.body)==null?void 0:u.dataStream)!=null?E:"",textRuns:[]}});return}const h=s(e,i,!1),f=new a.DisposableCollection;return h.forEach(m=>{const C=R.deserializeRangeWithSheet(m.token),I=v.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),b=I==null?void 0:I.getActiveSheet();if(!C.sheetName&&o!==(b==null?void 0:b.getSheetId())||C.sheetName&&(b==null?void 0:b.getName())!==C.sheetName)return;const N=new a.ColorKit(m.themeColor).toRgb(),p=g.addShape({range:C.range,style:{stroke:m.themeColor,fill:`rgba(${N.r}, ${N.g}, ${N.b}, 0.1)`,strokeDash:12},primary:null});p&&f.add(()=>g.removeShape(p))}),()=>{f.dispose()}},[e,t,s,g,i]),{sequenceNodes:i}}function jr(e){const t=l.useDependency(L.SheetsSelectionsService),{supportAcrossSheet:n=!1,keepSheetReference:o=!1,unitId:r,subUnitId:s,onChange:c}=e,d=l.useDependency(a.IUniverInstanceService).getUnit(r,a.UniverInstanceType.UNIVER_SHEET),g=l.useEvent(c),S=l.useEvent((v,h)=>{const f=d==null?void 0:d.getActiveSheet();if(!f||!n&&f.getSheetId()!==s||!(v!=null&&v.length))return;const u=o?f.getName():f.getSheetId()===s?"":f.getName(),E=v.map(m=>({range:m.range,unitId:r,sheetName:u}));g(E,h)});_.useEffect(()=>{const v=new a.DisposableCollection;return v.add(t.selectionMoveStart$.subscribe(h=>{S(h,!0)})),v.add(t.selectionMoving$.subscribe(h=>{S(h,!1)})),v.add(t.selectionMoveEnd$.subscribe(h=>{S(h,!1)})),()=>{v.dispose()}},[S,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const Bt=e=>!e.some(n=>{if(typeof n=="string"){if(n!==R.matchToken.COMMA)return!0}else if(n.nodeType!==R.sequenceNodeType.REFERENCE)return!0;return!1}),qr=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 Yr(e){const{visible:t,initialValue:n,unitId:o,subUnitId:r,maxRangeCount:s=1/0,supportAcrossSheet:c,keepSheetReference:i,onConfirm:d,onClose:g,onShowBySelection:S}=e,v=l.useDependency(a.LocaleService),h=l.useDependency(R.LexerTreeBuilder),[f,u]=_.useState([]),[E,m]=_.useState(0),C=_.useRef(null);_.useEffect(()=>{if(t&&n.length){const p=n.map(M=>M.sheetName?R.serializeRangeWithSheet(M.sheetName,M.range):R.serializeRange(M.range));u(p),m(p.length-1)}else u([""]),m(0)},[t]);const I=(p,M)=>{const x=[...f];x[p]=M,u(x)},b=()=>{u([...f,""]),m(f.length)},N=p=>{f.splice(p,1),u([...f])};return jr({unitId:o,subUnitId:r,supportAcrossSheet:c,keepSheetReference:i,onChange:(p,M)=>{if(!t&&S!=null&&S(p))return;const x=new Set(f),W=p.map($=>$.sheetName?R.serializeRangeWithSheet($.sheetName,$.range):R.serializeRange($.range)),U=W.filter($=>!x.has($));if(!U.length)return;const w=[...f];if(W.length>1){M||w.splice(E,1),w.push(...U);const $=w.slice(0,s);u($),m($.length-1),requestAnimationFrame(()=>{var k;(k=C.current)==null||k.scrollTo({top:C.current.scrollHeight})})}else{w.splice(E,1,...U);const $=w.slice(0,s);u($),m(E+U.length-1)}}}),y.jsx(B.Dialog,{width:"328px",open:t,title:v.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:g,children:v.t("rangeSelector.cancel")}),y.jsx(B.Button,{variant:"primary",onClick:()=>{d(f.filter(p=>{const M=h.sequenceNodesBuilder(p);return M&&M.length===1&&typeof M[0]!="string"&&M[0].nodeType===R.sequenceNodeType.REFERENCE}).map(p=>R.deserializeRangeWithSheet(p)).map(p=>({...p,range:qr(p.range)})))},children:v.t("rangeSelector.confirm")})]}),onClose:g,children:y.jsxs("div",{ref:C,className:B.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",B.scrollbarClassName),children:[f.map((p,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":E===M}),placeholder:v.t("rangeSelector.placeHolder"),onFocus:()=>m(M),value:p,onChange:x=>I(M,x)}),f.length>1&&y.jsx(xt,{className:"univer-cursor-pointer",onClick:()=>N(M)})]},M)),f.length<s&&y.jsx("div",{children:y.jsxs(B.Button,{variant:"link",onClick:b,children:[y.jsx(kt,{}),y.jsx("span",{children:v.t("rangeSelector.addAnotherRange")})]})})]})})}function zr(e){return e.split(R.matchToken.COMMA).filter(t=>!!t).map(t=>R.deserializeRangeWithSheet(t))}function Gr(e){return e.map(t=>t.sheetName?R.serializeRangeWithSheet(t.sheetName,t.range):R.serializeRange(t.range)).join(R.matchToken.COMMA)}function ft(e){const[t,n]=_.useState(null),{onVerify:o,selectorRef:r,unitId:s,subUnitId:c,maxRangeCount:i,supportAcrossSheet:d,keepSheetReference:g,autoFocus:S,onChange:v,onRangeSelectorDialogVisibleChange:h,onClickOutside:f,onFocusChange:u,forceShowDialogWhenSelectionChanged:E,hideEditor:m,resetRange:C}=e,[I,b]=_.useState(S!=null?S:!1),[N,p]=_.useState(!1),[M,x]=_.useState([]),W=l.useDependency(a.LocaleService),U=l.useDependency(J.IEditorService),{sequenceNodes:w}=Kr(t,I,s,c),$=Te(w),k=l.useDependency(a.ICommandService),O=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),U.blur()}),A=l.useEvent(()=>{var T;O(),x(zr((T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:"")),p(!0)});return _.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){U.focus(t.getEditorId())},blur:O,verify:()=>Bt($.current),showDialog:T=>{O(),x(T),p(!0)},hideDialog:()=>{x([]),p(!1)},getValue:()=>{var T;return(T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:""}})},[O,t,U,r,$]),_.useEffect(()=>{var T;o==null||o(Bt(w),(T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:"")},[w]),_.useEffect(()=>{h==null||h(N)},[N]),_.useEffect(()=>{if(N&&C)return()=>{const T={unitId:s,subUnitId:c,selections:C};k.executeCommand(L.SetSelectionsOperation.id,T)}},[N]),y.jsxs(y.Fragment,{children:[m?null:y.jsx(J.RichTextEditor,{isSingle:!0,...e,onFocusChange:(T,P)=>{b(T),u==null||u(T,P)},editorRef:n,onClickOutside:()=>{b(!1),O(),f==null||f()},icon:y.jsx(B.Tooltip,{title:W.t("rangeSelector.buttonTooltip"),placement:"bottom",children:y.jsx(At,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:A})})}),y.jsx(Yr,{initialValue:M,unitId:s,subUnitId:c,visible:N,maxRangeCount:i,onConfirm:T=>{const P=Gr(T),V=a.RichTextBuilder.newEmptyData();V.body.dataStream=P,t==null||t.replaceText(P,!1),v==null||v(V,P),p(!1),x([]),requestAnimationFrame(()=>{O()})},onClose:()=>{p(!1),x([])},supportAcrossSheet:d,keepSheetReference:g,onShowBySelection:T=>I||E?(x(T),p(!0),!1):!0})]})}const Zr=()=>{var o,r;const e=l.useDependency(at),t=l.useObservable(e.currentSelector$),n=_.useRef(null);return _.useEffect(()=>{var s,c;if(t)return(c=n.current)==null||c.showDialog((s=t.initialValue)!=null?s:[]),()=>{var i;(i=n.current)==null||i.hideDialog()}},[t]),y.jsx(ft,{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,c)=>{var i;t==null||t.callback((i=c==null?void 0:c.split(",").map(d=>R.deserializeRangeWithSheet(d)))!=null?i:[])}})};var Xr=Object.defineProperty,Qr=Object.getOwnPropertyDescriptor,Jr=(e,t,n)=>t in e?Xr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,eo=(e,t,n,o)=>{for(var r=o>1?void 0:o?Qr(t,n):t,s=e.length-1,c;s>=0;s--)(c=e[s])&&(r=c(r)||r);return r},Xe=(e,t)=>(n,o)=>t(n,o,e),Ht=(e,t,n)=>Jr(e,typeof t!="symbol"?t+"":t,n);F.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=It,n,o,r,s){super(),this._config=t,this._injector=n,this._renderManagerService=o,this._configService=r,this._uiPartsService=s;const{menu:c,...i}=a.merge(It,this._config);c&&this._configService.setConfig("menu",c,{merge:!0}),this._configService.setConfig(Et,i,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[Ve,{useClass:ot}],[at],[Ge],[Ke],[je],[qe],[Ye],[F.FormulaReorderController]]),this._initUIPart()}onReady(){[[F.RefSelectionsRenderService]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))})}onRendered(){[[ct]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))}),a.touchDependencies(this._injector,[[Ge],[je],[Ye]])}onSteady(){this._injector.get(Ke),this._injector.get(F.FormulaReorderController)}_initUIPart(){const t=this._injector.get(l.ComponentManager);this.disposeWithMe(t.register(D.RANGE_SELECTOR_COMPONENT_KEY,ft)),this.disposeWithMe(t.register(D.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Vt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(Zr,this._injector)))}},Ht(F.UniverSheetsFormulaUIPlugin,"pluginName",mt),Ht(F.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET),F.UniverSheetsFormulaUIPlugin=eo([a.DependentOn(R.UniverFormulaEnginePlugin,me.UniverSheetsFormulaPlugin),Xe(1,a.Inject(a.Injector)),Xe(2,j.IRenderManagerService),Xe(3,a.IConfigService),Xe(4,l.IUIPartsService)],F.UniverSheetsFormulaUIPlugin),F.FORMULA_PROMPT_ACTIVATED=gt,F.FormulaEditor=Vt,F.GlobalRangeSelectorService=at,F.HelpFunctionOperation=vt,F.InsertFunctionOperation=ce,F.MoreFunctionsOperation=Be,F.RangeSelector=ft,F.ReferenceAbsoluteOperation=st,F.SearchFunctionOperation=_t,F.SelectEditorFormulaOperation=Ie,F.SheetOnlyPasteFormulaCommand=Ue,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(F,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):(F=typeof globalThis<"u"?globalThis:F||self,a(F.UniverSheetsFormulaUi={},F.UniverCore,F.UniverSheetsUi,F.UniverEngineFormula,F.rxjs,F.UniverDocsUi,F.UniverEngineRender,F.UniverSheets,F.UniverSheetsFormula,F.UniverUi,F.React,F.React,F.UniverDesign,F.UniverDocs,F.rxjs.operators))})(this,(function(F,a,D,R,q,J,j,L,ve,l,y,I,B,ft,Xt){"use strict";var ro=Object.defineProperty;var oo=(F,a,D)=>a in F?ro(F,a,{enumerable:!0,configurable:!0,writable:!0,value:D}):F[a]=D;var Y=(F,a,D)=>oo(F,typeof a!="symbol"?a+"":a,D);const We={id:"sheet.command.paste-formula",type:a.CommandType.COMMAND,handler:async e=>e.get(a.ICommandService).executeCommand(D.SheetPasteCommand.id,{value:D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Ie={id:"formula-ui.operation.select-editor-formula",type:a.CommandType.OPERATION,handler:(e,t)=>!0};var Qt=Object.getOwnPropertyDescriptor,Jt=(e,t,n,o)=>{for(var r=o>1?void 0:o?Qt(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},en=(e,t)=>(n,o)=>t(n,o,e);const ht="FORMULA_PROMPT_ACTIVATED",Ue=a.createIdentifier("formula-ui.prompt-service");let rt=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(ht,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!==R.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:R.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}};rt=Jt([en(0,a.IContextService)],rt);const gt={id:"formula-ui.operation.help-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ue).help(t),!0)},ce={id:"formula-ui.operation.insert-function",type:a.CommandType.OPERATION,handler:async(e,t)=>{var E,T;const n=e.get(L.SheetsSelectionsService),o=e.get(J.IEditorService),r=n.getCurrentSelections();if(!r||!r.length)return!1;const s=L.getSheetCommandTarget(e.get(a.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:c,subUnitId:d}=s,g=i.getCellMatrix(),{value:p}=t,S=e.get(a.ICommandService);e.get(D.IEditorBridgeService);const h=[],f=[];let u=null,_=0,m=0,C="";if(r.length===1&&(rn(r[0].range)||on(r[0].range)&&pt(g,r[0].range))){const{range:N,primary:v}=r[0],M=(E=v==null?void 0:v.actualRow)!=null?E:N.startRow,x=(T=v==null?void 0:v.actualColumn)!=null?T:N.startColumn;u=N,_=M,m=x;const W=St(g,M,x);W&&(C=R.serializeRange(W))}else r.some(N=>{var x,W;const{range:v,primary:M}=N;if(pt(g,v)){const U=(x=M==null?void 0:M.actualRow)!=null?x:v.startRow,w=(W=M==null?void 0:M.actualColumn)!=null?W:v.startColumn,$=St(g,U,w);if(!$)return u=v,_=U,m=w,!0;const k=R.serializeRange($),O=`=${p}(${k})`;h.push({range:v,primary:{row:U,column:w},formula:O})}else{const{startRow:U,startColumn:w,endRow:$,endColumn:k}=v;if(U===$){const O=sn(g,U,k,i.getColumnCount()-1),A=O===k?k-1:k,b=R.serializeRange({startRow:U,endRow:$,startColumn:w,endColumn:A}),P=`=${p}(${b})`;f.push({range:v,primary:{row:U,column:O},formula:P})}else{let O=-1;for(let b=w;b<=k;b++){const P=cn(g,b,$,i.getRowCount()-1);O=Math.max(O,P)}const A=O===$?$-1:$;for(let b=w;b<=k;b++){const P=R.serializeRange({startRow:U,endRow:A,startColumn:b,endColumn:b}),V=`=${p}(${P})`;f.push({range:v,primary:{row:O,column:b},formula:V})}}}return!1});if(u){const N=L.getCellAtRowCol(_,m,i),v={range:a.Rectangle.clone(u),primary:{startRow:N.startRow,startColumn:N.startColumn,endRow:N.endRow,endColumn:N.endColumn,actualRow:_,actualColumn:m,isMerged:N.isMerged,isMergedMainCell:N.startRow===_&&N.startColumn===m}},M={unitId:c,subUnitId:d,selections:[v]};await S.executeCommand(L.SetSelectionsOperation.id,M);const x=o.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),W=o.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);S.syncExecuteCommand(D.SetCellEditVisibleOperation.id,{visible:!0,unitId:c,eventType:j.DeviceInputEventType.Dblclick});const U=`=${p}(${C}`;x==null||x.replaceText(U),W==null||W.replaceText(U,!1)}return h.length===0&&f.length===0?!1:S.executeCommand(ve.InsertFunctionCommand.id,{list:h,listOfRangeHasNumber:f})}};function St(e,t,n){const o=tn(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=nn(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function tn(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(Pe(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!Pe(s))return r+1;if(o&&r===0)return 0}}return t}function nn(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(Pe(s)&&!o){if(r===0)return 0;o=!0}else{if(o&&!Pe(s))return r+1;if(o&&r===0)return 0}}return n}function Pe(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 rn(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function on(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function pt(e,t){for(let n=t.startRow;n<=t.endRow;n++)for(let o=t.startColumn;o<=t.endColumn;o++)if(Pe(e.getValue(n,o)))return!1;return!0}function sn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function cn(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const vt="SHEET_FORMULA_UI_PLUGIN",mt=`${vt}_MORE_FUNCTIONS_COMPONENT`,Ve={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:mt}}),!0)},ot={id:"formula-ui.operation.change-ref-to-absolute",type:a.CommandType.OPERATION,handler:async e=>!0},Ct={id:"formula-ui.operation.search-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ue).search(t),!0)};var an=Object.getOwnPropertyDescriptor,ln=(e,t,n,o)=>{for(var r=o>1?void 0:o?an(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);F.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===L.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),g=d==null?void 0:d.getSheetBySheetId(s);if(!g)return{redos:n,undos:o};const p=g.getCellMatrix(),S=new a.ObjectMatrix,h=new a.ObjectMatrix;let f=!1;return a.Range.foreach(i,(u,_)=>{let m=u;c.hasOwnProperty(u)&&(m=c[u]);const C=p.getValue(m,_);if(C!=null&&C.f||C!=null&&C.si){f=!0;const E=this._formulaDataModel.getFormulaStringByCell(m,_,s,r),T=this._lexerTreeBuilder.moveFormulaRefOffset(E,0,u-m),N=a.Tools.deepClone(C);N.f=T,N.si=null,S.setValue(u,_,N)}else S.setValue(u,_,C);h.setValue(u,_,p.getValue(u,_))}),f?(n.push({id:L.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:S.getMatrix()}}),o.push({id:L.SetRangeValuesMutation.id,params:{unitId:r,subUnitId:s,cellValue:h.getMatrix()}}),{redos:n,undos:o}):{redos:n,undos:o}}},F.FormulaReorderController=ln([Be(0,a.Inject(L.SheetInterceptorService)),Be(1,a.Inject(a.IUniverInstanceService)),Be(2,a.Inject(R.FormulaDataModel)),Be(3,a.Inject(R.LexerTreeBuilder))],F.FormulaReorderController);const _t="sheets-formula-ui.base.config",It={};var un=Object.getOwnPropertyDescriptor,dn=(e,t,n,o)=>{for(var r=o>1?void 0:o?un(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 st="SHEET_FORMULA_ALERT",fn={[R.ErrorType.DIV_BY_ZERO]:"divByZero",[R.ErrorType.NAME]:"name",[R.ErrorType.VALUE]:"value",[R.ErrorType.NUM]:"num",[R.ErrorType.NA]:"na",[R.ErrorType.CYCLE]:"cycle",[R.ErrorType.REF]:"ref",[R.ErrorType.SPILL]:"spill",[R.ErrorType.CALC]:"calc",[R.ErrorType.ERROR]:"error",[R.ErrorType.CONNECT]:"connect",[R.ErrorType.NULL]:"null"};let it=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;const d=c.getCell(e.location.row,e.location.col),g=(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 p=R.extractFormulaError(d,!!g);if(!p){this._hideAlert();return}const S=this._cellAlertManagerService.currentAlert.get(st),h=(s=S==null?void 0:S.alert)==null?void 0:s.location;if(h&&h.row===e.location.row&&h.col===e.location.col&&h.subUnitId===e.location.subUnitId&&h.unitId===e.location.unitId)return;this._cellAlertManagerService.showAlert({type:D.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${fn[p]}`),location:e.location,width:200,height:74,key:st});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(e=>{e&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(st)}};it=dn([Le(1,a.Inject(D.HoverManagerService)),Le(2,a.Inject(D.CellAlertManagerService)),Le(3,a.Inject(a.LocaleService)),Le(4,a.Inject(R.FormulaDataModel)),Le(5,l.IZenZoneService)],it);var hn=Object.getOwnPropertyDescriptor,gn=(e,t,n,o)=>{for(var r=o>1?void 0:o?hn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Et=(e,t)=>(n,o)=>t(n,o,e);let He=class extends a.Disposable{constructor(e,t){super(),this._autoFillService=e,this._lexerTreeBuilder=t,this._registerAutoFill()}_registerAutoFill(){const e={type:D.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===D.DATA_TYPE.FORMULA,applyFunctions:{[D.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 g,p;const i=pn(r),c=[],d=new Map;for(let S=1;S<=t;S++){const h=(S-1)%e.length,f=o[h],u=a.Tools.deepClone(e[h]);if(u){const _=((g=e[h])==null?void 0:g.f)||"",m=((p=e[h])==null?void 0:p.si)||"",C=a.isFormulaString(_);if(a.isFormulaId(m))u.si=m,u.f=null,u.v=null,u.p=null,u.t=null,c.push(u);else if(C){let T=d.get(h);if(T)u.si=T,u.f=null,u.v=null,u.p=null,u.t=null;else{T=a.generateRandomId(6),d.set(h,T);const{offsetX:N,offsetY:v}=Sn(i,t,n,s,f),M=this._lexerTreeBuilder.moveFormulaRefOffset(_,N,v);u.si=T,u.f=M,u.v=null,u.p=null,u.t=null}c.push(u)}}}return c}};He=gn([Et(0,D.IAutoFillService),Et(1,a.Inject(R.LexerTreeBuilder))],He);function Sn(e,t,n,o,r){const{source:s,target:i}=o,{rows:c}=i,{rows:d}=s;let g=0,p=0;switch(n){case a.Direction.UP:p=c[r]-d[r];break;case a.Direction.RIGHT:g=e;break;case a.Direction.DOWN:p=c[r]-d[r];break;case a.Direction.LEFT:g=-e*t;break}return{offsetX:g,offsetY:p}}function pn(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}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},$e=(e,t)=>(n,o)=>t(n,o,e);const Cn="default-paste-formula";let Ke=class extends a.Disposable{constructor(e,t,n,o,r){super(),this._currentUniverSheet=e,this._lexerTreeBuilder=t,this._sheetClipboardService=n,this._injector=o,this._formulaDataModel=r,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!0)}}_pasteWithFormulaHook(){return{id:Cn,priority:10,onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!1)}}_onPasteCells(e,t,n,o,r){var h;if([D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(o.pasteType))return{undos:[],redos:[]};const i=this._currentUniverSheet.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),c=t.unitId||i.getUnitId(),d=t.subUnitId||((h=i.getActiveSheet())==null?void 0:h.getSheetId());if(!c||!d)return{undos:[],redos:[]};const g=t.range,p=n,S={copyType:o.copyType||D.COPY_TYPE.COPY,copyRange:e==null?void 0:e.range,pasteType:o.pasteType};return this._injector.invoke(f=>_n(c,d,g,p,f,S,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};Ke=mn([$e(0,a.IUniverInstanceService),$e(1,a.Inject(R.LexerTreeBuilder)),$e(2,D.ISheetClipboardService),$e(3,a.Inject(a.Injector)),$e(4,a.Inject(R.FormulaDataModel))],Ke);function _n(e,t,n,o,r,s,i,c,d=!1,g){const p=[],S=[],h=In(e,t,n,o,s,i,c,g);if(!h.hasValue())return{undos:[],redos:[]};const f={unitId:e,subUnitId:t,cellValue:h.getData()};p.push({id:L.SetRangeValuesMutation.id,params:f});const u=L.SetRangeValuesUndoMutationFactory(r,f);return S.push({id:L.SetRangeValuesMutation.id,params:u}),{undos:S,redos:p}}function In(e,t,n,o,r,s,i,c){return c?r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?yn(e,t,n,o,i,c):r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?Rn(e,t,n,o,s,i,c):Tn(e,t,n,o,r.copyType,s,i,c):En(e,t,n,o,i)}function En(e,t,n,o,r){const s=new a.ObjectMatrix,i=r.getSheetFormulaData(e,t);return o.forValue((c,d,g)=>{var f;const p=n.rows[c],S=n.cols[d],h={};a.isFormulaString(g.v)?(h.v=null,h.f=`${g.v}`,h.si=null,h.p=null,s.setValue(p,S,h)):(f=i==null?void 0:i[p])!=null&&f[S]&&(h.v=g.v,h.f=null,h.si=null,h.p=null,s.setValue(p,S,h))}),s}function yn(e,t,n,o,r,s){var g,p;const i=new a.ObjectMatrix,c=(p=(g=r.getArrayFormulaCellData())==null?void 0:g[s.unitId])==null?void 0:p[s.subUnitId],d=r.getSheetFormulaData(e,t);return o.forValue((S,h,f)=>{var T,N;const u=s.range.rows[S%s.range.rows.length],_=s.range.cols[h%s.range.cols.length],m=n.rows[S],C=n.cols[h],E={};if(a.isFormulaString(f.f)||a.isFormulaId(f.si))E.v=f.v,E.f=null,E.si=null,E.p=null,i.setValue(m,C,E);else if((T=c==null?void 0:c[u])!=null&&T[_]){const v=c[u][_];E.v=v.v,E.f=null,E.si=null,E.p=null,i.setValue(m,C,E)}else if((N=d==null?void 0:d[m])!=null&&N[C]){if(E.v=f.v,E.f=null,E.si=null,E.p=null,f.p){const v=yt(f);v&&(E.v=v)}i.setValue(m,C,E)}}),i}function Rn(e,t,n,o,r,s,i){const c=new a.ObjectMatrix,d=new Map;return o.forValue((g,p,S)=>{const h=n.rows[g],f=n.cols[p],u={};if(a.isFormulaId(S.si)){if(i.unitId!==e||i.subUnitId!==t){const _=s.getFormulaStringByCell(i.range.rows[g%i.range.rows.length],i.range.cols[p%i.range.cols.length],i.subUnitId,i.unitId),m=n.cols[p]-i.range.cols[p%i.range.cols.length],C=n.rows[g]-i.range.rows[g%i.range.rows.length],E=r.moveFormulaRefOffset(_||"",m,C);u.si=null,u.f=E}else u.si=S.si,u.f=null;u.v=null,u.p=null,c.setValue(h,f,u)}else if(a.isFormulaString(S.f)){const _=`${g%i.range.rows.length}_${p%i.range.cols.length}`;let m=d.get(_);if(m)u.si=m,u.f=null;else{m=a.generateRandomId(6),d.set(_,m);const C=n.cols[p]-i.range.cols[p%i.range.cols.length],E=n.rows[g]-i.range.rows[g%i.range.rows.length],T=r.moveFormulaRefOffset(S.f||"",C,E);u.si=m,u.f=T}u.v=null,u.p=null,c.setValue(h,f,u)}else{if(u.v=S.v,u.f=null,u.si=null,u.p=null,S.p){const _=yt(S);_&&(u.v=_)}c.setValue(h,f,u)}}),c}function Tn(e,t,n,o,r,s,i,c){const d=new a.ObjectMatrix,g=new Map,p=i.getSheetFormulaData(e,t),S=[];return r===D.COPY_TYPE.CUT?o.forValue((h,f,u)=>{const _=n.rows[h],m=n.cols[f],C={};if(a.isFormulaId(u.si)){if(a.isFormulaString(u.f))S.push(u.si),C.f=u.f,C.si=u.si;else if(S.includes(u.si))C.f=null,C.si=u.si;else{const E=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[f%c.range.cols.length],c.subUnitId,c.unitId);C.f=E,C.si=null}C.v=null,C.p=null,d.setValue(_,m,C)}else a.isFormulaString(u.f)&&(C.f=u.f,C.si=null,C.v=null,C.p=null,d.setValue(_,m,C))}):o.forValue((h,f,u)=>{var E;const _=n.rows[h],m=n.cols[f],C={};if(a.isFormulaId(u.si)){if(c.unitId!==e||c.subUnitId!==t){const T=i.getFormulaStringByCell(c.range.rows[h%c.range.rows.length],c.range.cols[f%c.range.cols.length],c.subUnitId,c.unitId),N=n.cols[f]-c.range.cols[f%c.range.cols.length],v=n.rows[h]-c.range.rows[h%c.range.rows.length],M=s.moveFormulaRefOffset(T||"",N,v);C.si=null,C.f=M}else C.si=u.si,C.f=null;C.v=null,C.p=null,d.setValue(_,m,C)}else if(a.isFormulaString(u.f)){const T=`${h%c.range.rows.length}_${f%c.range.cols.length}`;let N=g.get(T);if(N)C.si=N,C.f=null;else{N=a.generateRandomId(6),g.set(T,N);const v=n.cols[f]-c.range.cols[f%c.range.cols.length],M=n.rows[h]-c.range.rows[h%c.range.rows.length],x=s.moveFormulaRefOffset(u.f||"",v,M);C.si=N,C.f=x}C.v=null,C.p=null,d.setValue(_,m,C)}else(E=p==null?void 0:p[_])!=null&&E[m]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,d.setValue(_,m,C))}),S.length>0&&new a.ObjectMatrix(p).forValue((h,f,u)=>{if(!(c.range.rows.includes(h)&&c.range.cols.includes(f))&&!(n.rows.includes(h)&&n.cols.includes(f))&&S.includes(u==null?void 0:u.si)){const _=i.getFormulaStringByCell(h,f,c.subUnitId,c.unitId);d.setValue(h,f,{f:_,si:null,v:null,p:null})}}),d}function yt(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 bn=Object.getOwnPropertyDescriptor,Mn=(e,t,n,o)=>{for(var r=o>1?void 0:o?bn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Ee=(e,t)=>(n,o)=>t(n,o,e);let je=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(L.BEFORE_CELL_EDIT,{handler:(t,n,o)=>{var u,_,m,C;const{row:r,col:s,unitId:i,subUnitId:c,worksheet:d}=n,g=this._formulaDataModel.getArrayFormulaRange(),p=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),t==null)return o(t);let S=null;const h=this._formulaDataModel.getFormulaStringByCell(r,s,c,i);if(h!==null&&(S={f:h}),t.v!=null&&t.v!==""&&((m=(_=(u=p[i])==null?void 0:u[c])==null?void 0:_[r])==null?void 0:m[s])==null)return S?{...t,...S}:o(t);const f=(C=g==null?void 0:g[i])==null?void 0:C[c];return f!=null&&(S=this._displayArrayFormulaRangeShape(f,r,s,i,c,d,S)),S?{...t,...S}:o(t)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{(t.id===R.SetFormulaCalculationResultMutation.id||t.id===R.SetArrayFormulaDataMutation.id&&n&&n.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{L.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){const d=this._formulaDataModel.getSheetFormulaData(r,s);return new a.ObjectMatrix(t).forValue((g,p,S)=>{var m;if(S==null)return!0;const{startRow:h,startColumn:f,endRow:u,endColumn:_}=S;if(g===n&&p===o)return this._createArrayFormulaRangeShape(S,r),!1;if(n>=h&&n<=u&&o>=f&&o<=_){const C=i.getCell(h,f);if((C==null?void 0:C.v)===R.ErrorType.SPILL)return;const E=(m=d==null?void 0:d[g])==null?void 0:m[p];return E==null||E.f==null?!0:(c==null&&(c={f:E.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=D.attachSelectionWithCoord(i,r),{rowHeaderWidth:d,columnHeaderHeight:g}=r,p=new D.SelectionControl(s,D.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:g});p.updateRangeBySelectionWithCoord(c),p.setEvent(!1),this._previousShape=p}_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:g}=o[d];if(r>=g){const p={startRow:r,endRow:s,startColumn:i,endColumn:c};this._refreshArrayFormulaRangeShape(t,p);break}}}};je=Mn([Ee(1,a.Inject(L.SheetInterceptorService)),Ee(2,a.Inject(R.FormulaDataModel)),Ee(3,a.Inject(a.ThemeService)),Ee(4,j.IRenderManagerService),Ee(5,a.Inject(D.SheetSkeletonManagerService)),Ee(6,a.ICommandService),Ee(7,a.ILogService)],je);var On=Object.getOwnPropertyDescriptor,Nn=(e,t,n,o)=>{for(var r=o>1?void 0:o?On(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Rt=(e,t)=>(n,o)=>t(n,o,e);const Dn={tl:{size:6,color:"#409f11"}};let qe=class extends a.RxDisposable{constructor(e,t){super(),this._sheetInterceptorService=e,this._formulaDataModel=t,this.disposeWithMe(this._sheetInterceptorService.intercept(L.INTERCEPTOR_POINT.CELL_CONTENT,{effect:a.InterceptorEffectEnum.Style,handler:(n,o,r)=>{var c,d,g,p;const s=(p=(g=(d=(c=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:c[o.unitId])==null?void 0:d[o.subUnitId])==null?void 0:g[o.row])==null?void 0:p[o.col];return!R.extractFormulaError(n,!!s)||!n||(n===o.rawData&&(n={...o.rawData}),n.markers={...n==null?void 0:n.markers,...Dn}),r(n)},priority:10}))}};qe=Nn([Rt(0,a.Inject(L.SheetInterceptorService)),Rt(1,a.Inject(R.FormulaDataModel))],qe);function xn(){const e=l.useDependency(ve.TriggerCalculationController),t=l.useDependency(a.ICommandService),n=l.useObservable(e.progress$),o=I.useCallback(()=>{t.executeCommand(R.SetFormulaCalculationStopMutation.id)},[t]),r=I.useCallback(()=>{e.clearProgress()},[e]);return y.jsx(l.ProgressBar,{progress:n,onTerminate:o,onClearProgress:r})}function kn(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function Tt(e){if(!e.require&&!e.repeat)return`[${e.name}]`;if(e.require&&!e.repeat)return e.name;if(!e.require&&e.repeat)return`[${e.name},...]`;if(e.require&&e.repeat)return`${e.name},...`}function bt(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:Tt(o)}),r===n.length-1?"":","]},r)),")"]})}function Fe(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 wn(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;const[o,r]=I.useState([]),[s,i]=I.useState(t.functionParameter),[c,d]=I.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((g,p)=>y.jsxs("div",{children:[y.jsx("div",{className:"univer-text-sm",children:g.name}),y.jsx("div",{className:"univer-mb-2 univer-mt-1"})]},p))}),y.jsx("div",{className:B.clsx("univer-flex-1 univer-p-3",B.borderLeftClassName),children:y.jsx(Fe,{title:c===-1?y.jsx(bt,{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=I.useRef(`_${Ln()}`);return Mt(n,`${o}`,{defIds:n.defIds,idSuffix:d.current},{ref:e,className:c,...i},s)}function Mt(e,t,n,o,r){return I.createElement(e.tag,{key:t,...An(e,n,r),...o},(Pn(e,n).children||[]).map((s,i)=>Mt(s,`${t}-${e.tag}-${i}`,n,void 0,r)))}function An(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 Pn(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 Ln(){return Math.random().toString(36).substring(2,8)}ye.displayName="UniverIcon";const $n={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"}}]},Ot=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"check-mark-icon",ref:n,icon:$n}))});Ot.displayName="CheckMarkIcon";const Fn={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"}}]},Nt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"close-icon",ref:n,icon:Fn}))});Nt.displayName="CloseIcon";const Wn={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"}}]},Dt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"delete-icon",ref:n,icon:Wn}))});Dt.displayName="DeleteIcon";const Un={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"}}]},xt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"increase-icon",ref:n,icon:Un}))});xt.displayName="IncreaseIcon";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:"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"}}]},kt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"more-icon",ref:n,icon:Vn}))});kt.displayName="MoreIcon";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:"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"}}]},wt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"select-range-icon",ref:n,icon:Bn}))});wt.displayName="SelectRangeIcon";function Hn(e){const{onChange:t}=e,n="-1",[o,r]=I.useState(""),[s,i]=I.useState([]),[c,d]=I.useState(0),[g,p]=I.useState(n),[S,h]=I.useState(0),[f,u]=I.useState(null),_=l.useDependency(ve.IDescriptionService),m=l.useDependency(a.LocaleService),C=l.useDependency(l.ISidebarService),E=l.useObservable(C.sidebarOptions$),T=kn(R.FunctionType,m);T.unshift({label:m.t("formula.moreFunctions.allFunctions"),value:n});const N=m.t("formula.prompt.required"),v=m.t("formula.prompt.optional");I.useEffect(()=>{W(n)},[]),I.useEffect(()=>{x(0)},[s]),I.useEffect(()=>{E!=null&&E.visible&&(r(""),i([]),d(0),p(n),h(0),u(null),W(n))},[E]);const M=O=>{if(o.trim()==="")return O;const A=new RegExp(`(${o.toLocaleUpperCase()})`);return O.split(A).filter(Boolean).map((P,V)=>P.match(A)?y.jsx("span",{className:"univer-text-red-500",children:P},V):P)},x=O=>{if(s.length===0){u(null);return}h(O);const A=_.getFunctionInfo(s[O].name);if(!A){u(null);return}u(A),t(A)};function W(O){p(O);const A=_.getSearchListByType(+O);i(A)}function U(O){r(O);const A=_.getSearchListByName(O);i(A)}function w(O){if(O.stopPropagation(),O.key==="ArrowDown"){const A=c+1;d(A===s.length?0:A)}else if(O.key==="ArrowUp"){const A=c-1;d(A===-1?s.length-1:A)}else O.key==="Enter"&&x(c)}const $=O=>{d(O)},k=()=>{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:g,options:T,onChange:W}),y.jsx(B.Input,{placeholder:m.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:w,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:w,tabIndex:-1,children:s.map(({name:O},A)=>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===A}),onMouseEnter:()=>$(A),onMouseLeave:k,onClick:()=>x(A),children:[S===A&&y.jsx(Ot,{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)})]},A))}),f&&y.jsxs("div",{className:B.clsx("univer-mx-0 univer-my-2 univer-overflow-y-auto",B.scrollbarClassName),children:[y.jsx(Fe,{title:f.functionName,value:f.description}),y.jsx(Fe,{title:m.t("formula.moreFunctions.syntax"),value:y.jsx(bt,{prefix:f.functionName,value:f.functionParameter})}),y.jsx(Fe,{title:m.t("formula.prompt.helpExample"),value:`${f.functionName}(${f.functionParameter.map(O=>O.example).join(",")})`}),f.functionParameter&&f.functionParameter.map(O=>y.jsx(Fe,{title:O.name,value:`${O.require?N:v} ${O.detail}`},O.name))]})]})}function Kn(){const e=D.useActiveWorkbook(),[t,n]=I.useState(!0),[o,r]=I.useState(!1),[s,i]=I.useState(null);l.useDependency(D.IEditorBridgeService);const c=l.useDependency(a.LocaleService),d=l.useDependency(J.IEditorService),g=l.useDependency(a.IUniverInstanceService),p=l.useDependency(a.ICommandService);function S(){n(!t),r(!o)}function h(){const f=L.getSheetCommandTarget(g);if(!f)return;p.executeCommand(D.SetCellEditVisibleOperation.id,{visible:!0,unitId:f.unitId,eventType:j.DeviceInputEventType.Dblclick});const u=d.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),_=d.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),m=`=${s==null?void 0:s.functionName}(`;u==null||u.replaceText(m),_==null||_.replaceText(m,!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(Hn,{onChange:i}),o&&y.jsx(wn,{functionInfo:s,onChange:()=>{}}),y.jsxs("div",{className:"univer-flex univer-justify-end",children:[o&&y.jsx(B.Button,{variant:"primary",onClick:S,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:S,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 jn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function qn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Yn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function zn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Gn(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$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Zn(e){return{id:Ve.id,title:"formula.insert.more",tooltip:"formula.insert.tooltip",type:l.MenuItemType.BUTTON,hidden$:l.getMenuHiddenObservable(e,a.UniverInstanceType.UNIVER_SHEET),disabled$:D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],worksheetTypes:[L.WorksheetEditPermission,L.WorksheetSetCellValuePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint]})}}function Xn(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 Qn(e){return{id:We.id,type:l.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:Xn(e).pipe(q.combineLatestWith(D.getCurrentRangeDisable$(e,{workbookTypes:[L.WorkbookEditablePermission],rangeTypes:[L.RangeProtectionPermissionEditPoint],worksheetTypes:[L.WorksheetSetCellValuePermission,L.WorksheetEditPermission]})),q.map(([t,n])=>t||n))}}const Jn={[l.RibbonFormulasGroup.BASIC]:{[`${ce.id}.sum`]:{order:0,menuItemFactory:jn},[`${ce.id}.count`]:{order:1,menuItemFactory:qn},[`${ce.id}.average`]:{order:2,menuItemFactory:Yn},[`${ce.id}.max`]:{order:3,menuItemFactory:zn},[`${ce.id}.min`]:{order:4,menuItemFactory:Gn}},[l.RibbonFormulasGroup.OTHERS]:{[Ve.id]:{order:0,menuItemFactory:Zn}},[D.PASTE_SPECIAL_MENU_ID]:{[We.id]:{order:4,menuItemFactory:Qn}}},er="meta_key_ctrl_And_Shift";function tr(e){return e.getContextValue(a.FOCUSING_DOC)&&e.getContextValue(a.FOCUSING_UNIVER_EDITOR)}const Ye=[l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP,l.KeyCode.ARROW_LEFT,l.KeyCode.ARROW_RIGHT],nr=[...Ye,l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ESC];function rr(){const e=[];for(const t of nr)e.push({id:Ie.id,binding:t,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t}});return e}function or(){const e=[];for(const t of Ye)e.push({id:Ie.id,binding:t|l.MetaKeys.SHIFT,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.SHIFT}});return e}function sr(){const e=[];for(const t of Ye)e.push({id:Ie.id,binding:t|l.MetaKeys.CTRL_COMMAND,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.CTRL_COMMAND}});return e}function ir(){const e=[];for(const t of Ye)e.push({id:Ie.id,binding:t|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,metaKey:er}});return e}const cr={id:ot.id,binding:l.KeyCode.F4,preconditions:e=>D.whenFormulaEditorActivated(e)};function ar(){const e=[];for(const t of[l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP])e.push({id:Ie.id,binding:t,preconditions:n=>tr(n),staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}const lr={id:ve.QuickSumCommand.id,binding:l.MetaKeys.ALT|l.KeyCode.EQUAL,preconditions:D.whenSheetEditorFocused,mac:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.ALT|l.KeyCode.EQUAL,description:"shortcut.sheets-formula-ui.quick-sum",group:"4_sheet-edit"};var ur=Object.getOwnPropertyDescriptor,dr=(e,t,n,o)=>{for(var r=o>1?void 0:o?ur(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 ze=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(Jn)}_registerCommands(){[We,ce,Ve,Ct,gt,Ie,ot].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_registerShortcuts(){[...rr(),...or(),...sr(),...ir(),...ar(),lr,cr].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(D.SheetsUIPart.FORMULA_AUX,()=>l.connectInjector(xn,this._injector))),this._componentManager.register(mt,Kn)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,[je]))}};ze=dr([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))],ze);class ct{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 fr=Object.getOwnPropertyDescriptor,hr=(e,t,n,o)=>{for(var r=o>1?void 0:o?fr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},xe=(e,t)=>(n,o)=>t(n,o,e);F.RefSelectionsRenderService=class extends D.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(gr(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((g,p)=>{this.inRefSelectionMode()&&(this._onPointerDown(g,s.zIndex+1,a.RANGE_TYPE.NORMAL,this._getActiveViewport(g)),g.button!==2&&p.stopPropagation())})),d.add(o==null?void 0:o.onPointerDown$.subscribeEvent((g,p)=>{if(!this.inRefSelectionMode())return;const S=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:h}=D.getCoordByOffset(g.offsetX,g.offsetY,c,S);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.ROW)||(this._onPointerDown(g,(s.zIndex||1)+1,a.RANGE_TYPE.ROW,this._getActiveViewport(g),j.ScrollTimerType.Y),g.button!==2&&p.stopPropagation())})),d.add(r==null?void 0:r.onPointerDown$.subscribeEvent((g,p)=>{if(!this.inRefSelectionMode())return;const S=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:h}=D.getCoordByOffset(g.offsetX,g.offsetY,c,S);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),h,a.RANGE_TYPE.COLUMN)||(this._onPointerDown(g,(s.zIndex||1)+1,a.RANGE_TYPE.COLUMN,this._getActiveViewport(g),j.ScrollTimerType.X),g.button!==2&&p.stopPropagation())})),d.add(i==null?void 0:i.onPointerDown$.subscribeEvent((g,p)=>{if(this._reset(),!this.inRefSelectionMode())return;const S=this._sheetSkeletonManagerService.getCurrent().skeleton,h=D.getAllSelection(S);this._addSelectionControlByModelData(h),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const f=c.onPointerUp$.subscribeEvent(()=>{f.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});g.button!==2&&p.stopPropagation()})),d}_addSelectionControlByModelData(n){var c;const o=this._skeleton,r=(c=n.style)!=null?c:D.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,L.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(n=>{this._updateSelections(n,L.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(n=>{this._updateSelections(n,L.SelectionMoveType.MOVE_END)}))}_updateSelections(n,o){const s=this._context.unit.getActiveSheet().getSheetId();n.length!==0&&this._workbookSelections.setSelections(s,n.map(i=>L.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 D.getSheetObject(this._context.unit,this._context)}_onPointerDown(n,o=0,r=a.RANGE_TYPE.NORMAL,s,i=j.ScrollTimerType.ALL){var $;this._rangeType=r;const c=this._skeleton,d=this._scene;if(!d||!c)return;s&&(this._activeViewport=s);const{offsetX:g,offsetY:p}=n,S=d.getViewport(j.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!S)return;const h=d.getCoordRelativeToViewport(j.Vector2.FromArray([g,p])),{x:f,y:u}=h;this._startViewportPosX=f,this._startViewportPosY=u;const _=d.getScrollXYInfoByViewport(h),{scaleX:m,scaleY:C}=d.getAncestorScale(),E=this._skeleton.getCellByOffset(f,u,m,C,_);if(!E)return;switch(r){case a.RANGE_TYPE.NORMAL:break;case a.RANGE_TYPE.ROW:E.startColumn=0,E.endColumn=this._skeleton.getColumnCount()-1;break;case a.RANGE_TYPE.COLUMN:E.startRow=0,E.endRow=this._skeleton.getRowCount()-1;break;case a.RANGE_TYPE.ALL:E.startRow=0,E.startColumn=0,E.endRow=this._skeleton.getRowCount()-1,E.endColumn=this._skeleton.getColumnCount()-1}const T={range:E,primary:E,style:null};T.range.rangeType=r;const N=D.attachSelectionWithCoord(T,this._skeleton);this._startRangeWhenPointerDown={...N.rangeWithCoord};const v={...N.rangeWithCoord,rangeType:r};let M=this.getActiveSelectionControl();const x=this.getSelectionControls();for(const k of x){if(n.button===2&&a.Rectangle.contains(k.model,v)){M=k;return}if(k.model.isEqual(v)){M=k;break}}this._checkClearPreviousControls(n);const W=M==null?void 0:M.model.currentCell,U=n.shiftKey&&W,w=this._remainLastEnabled&&!n.ctrlKey&&!n.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;U&&W?this._makeSelectionByTwoCells(W,v,c,r,M):w&&M?M.updateRangeBySelectionWithCoord(N):M=this.newSelectionControl(d,c,T);for(let k=0;k<this.getSelectionControls().length-1;k++)this.getSelectionControls()[k].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),d.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),($=d.getTransformer())==null||$.clearSelectedObjects(),this._setupPointerMoveListener(S,M,r,i,f,u),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=d.onPointerUp$.subscribeEvent(()=>{var k;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(k=this._escapeShortcutDisposable)==null||k.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(n,o,r){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:c}=o,d=new D.SelectionControl(n,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:c}),g=D.attachSelectionWithCoord(r,o);return d.updateRangeBySelectionWithCoord(g),this._selectionControls.push(d),d.setControlExtension({skeleton:o,scene:n,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),d}},F.RefSelectionsRenderService=hr([xe(1,a.Inject(a.Injector)),xe(2,a.Inject(a.ThemeService)),xe(3,l.IShortcutService),xe(4,a.Inject(D.SheetSkeletonManagerService)),xe(5,a.IContextService),xe(6,L.IRefSelectionsService)],F.RefSelectionsRenderService);function gr(e){const t=D.genNormalSelectionStyle(e);return t.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},t}const at=(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},At=(e,t)=>{const n=e[t];let o=-1;if(!n||typeof n=="string"||n.nodeType!==R.sequenceNodeType.REFERENCE)return-1;for(let r=0;r<=t;r++){const s=e[r];typeof s!="string"&&s.nodeType===R.sequenceNodeType.REFERENCE&&o++}return o},Sr=(e,t=100)=>{I.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 Pt(e,t,n){const o=l.useDependency(J.IEditorService),r=I.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 T;const d=o.getEditor(e);if(!d)return;const g=d.getBoundingClientRect(),{marginTop:p=0,marginBottom:S=0}=d.getDocumentData().documentStyle,h=d.getSkeleton();if(!h)return;const f=(T=h.getSkeletonData())==null?void 0:T.pages[0].height;let{left:u,top:_,right:m,bottom:C}=g;_=_+p,C=f?_+f:C-S;const E=r.getValue();if(!(E.left===u&&E.top===_&&E.right===m&&E.bottom===C))return r.next({left:u-1,right:m+1,top:_-1,bottom:C+1}),g});return I.useEffect(()=>{t&&c()},[e,o,i.unitAdded$,c,t,...n!=null?n:[]]),Sr(c),I.useEffect(()=>{const d=s.scrollEvent$.pipe(q.throttleTime(100)).subscribe(c);return()=>{d.unsubscribe()}},[]),[r,c]}const Te=e=>{const t=I.useRef(e);return t.current=e,t},pr=(e,t,n)=>{const o=l.useDependency(Ue),r=l.useDependency(ve.IDescriptionService),s=l.useDependency(R.LexerTreeBuilder),[i,c]=I.useState(),[d,g]=I.useState(-1),[p,S]=I.useState(!0),h=Te(p),f=I.useRef(t);f.current=t;const u=()=>{c(void 0),g(-1),S(!1)};return I.useEffect(()=>{const _=s.sequenceNodesBuilder(t.slice(1));o.setSequenceNodes(_!=null?_:[])},[t]),I.useEffect(()=>{if(n&&e){const _=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(C=>{if(C.textRanges.length===1){const[E]=C.textRanges;if(E.collapsed&&h.current){const{startOffset:T}=E,N=o.getCurrentSequenceNodeIndex(T-2),v=o.getCurrentSequenceNodeByIndex(N),M=o.getCurrentSequenceNodeByIndex(N+1);if(v)if(typeof v!="string"&&v.nodeType===3&&!r.hasDefinedNameDescription(v.token.trim())&&M===R.matchToken.OPEN_BRACKET){const x=r.getFunctionInfo(v.token);c(x),g(-1);return}else{const x=s.getFunctionAndParameter(`${f.current}A`,T-1);if(x){const{functionName:W,paramIndex:U}=x,w=r.getFunctionInfo(W);c(w),g(U);return}}}}c(void 0),g(-1)}),m=n.selectionChange$.pipe(q.filter(C=>C.textRanges.length===1),q.map(C=>C.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{S(!0)});return()=>{_.unsubscribe(),m.unsubscribe()}}},[n,e]),I.useEffect(()=>{e||u()},[e]),{functionInfo:i,paramIndex:d,reset:u}},vr=({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:"?"}),lt=({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})]}),mr=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:Tt(s)}),i===n.length-1?"":","]},s.name)),")"]})},Lt=()=>{};function Cr(e){const{onParamsSwitch:t=Lt,onClose:n=Lt,isFocus:o,editor:r,formulaText:s}=e,{functionInfo:i,paramIndex:c,reset:d}=pr(o,s,r),g=l.useDependency(D.IEditorBridgeService),p=!l.useObservable(g.helpFunctionVisible$),[S,h]=I.useState(!0),f=l.useDependency(a.LocaleService),u=f.t("formula.prompt.required"),_=f.t("formula.prompt.optional"),m=r.getEditorId(),[C]=Pt(m,!!i,[i,c]);function E(v){t&&t(v)}const T=l.useEvent(v=>{g.helpFunctionVisible$.next(!v)}),N=()=>{T(!0),n()};return i?p?y.jsx(l.RectPopup,{portal:!0,anchorRect$:C,direction:"left-center",children:y.jsx(vr,{onClick:()=>T(!1)})},"hidden"):y.jsx(l.RectPopup,{portal:!0,onClickOutside:()=>d(),anchorRect$:C,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(mr,{prefix:i.functionName,value:i.functionParameter,active:c,onClick:E}),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:S?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!S),children:y.jsx(kt,{})}),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:N,children:y.jsx(Nt,{})})]})]}),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:S?"unset":0,padding:S?"revert-layer":0},children:y.jsxs("div",{className:"univer-mt-3",children:[y.jsx(lt,{title:f.t("formula.prompt.helpExample"),value:`${i.functionName}(${i.functionParameter.map(v=>v.example).join(",")})`}),y.jsx(lt,{title:f.t("formula.prompt.helpAbstract"),value:i.description}),i&&i.functionParameter&&i.functionParameter.map((v,M)=>y.jsx(lt,{className:c===M?"univer-text-primary-500":"",title:v.name,value:`${v.require?u:_} ${v.detail}`},M))]})})]})},"show"):null}const _r=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 Ir(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 de=(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))(de||{});function Er(e){var x;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),g=i.getRenderById(t),p=g==null?void 0:g.with(J.DocSelectionRenderService),S=l.useDependency(ft.DocSelectionManagerService),h=l.useDependency(a.Injector),[f,u]=I.useState(0),_=l.useDependency(R.LexerTreeBuilder),m=I.useRef(!0),C=d==null?void 0:d.with(F.RefSelectionsRenderService),E=Te(f),T=c.getUnit(r,a.UniverInstanceType.UNIVER_SHEET),N=T==null?void 0:T.getSheetBySheetId(s),v=l.useEvent(W=>{C&&C.setSkipLastEnabled(W===1||W===3||W===4),E.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(),w=p==null?void 0:p.getActiveTextRange(),$=w!=null&&w.collapsed?w.startOffset:-1,k=Ir(h);if(!k)return;const O=(oe=k==null?void 0:k.dataStream)==null?void 0:oe.slice(0,-2),A=((se=_.sequenceNodesBuilder(O))!=null?se:[]).map(z=>typeof z=="object"?z.nodeType===R.sequenceNodeType.REFERENCE?{...z,range:R.deserializeRangeWithSheetWithCache(z.token)}:{...z,range:void 0}:z),b=O[$-1],P=O[$],V=A.find(z=>typeof z=="object"&&z.nodeType===R.sequenceNodeType.REFERENCE&&$===z.endIndex+2),H=b&&R.matchRefDrawToken(b)&&(!P||R.isFormulaLexerToken(P)&&P!==R.matchToken.OPEN_BRACKET),K=!!V;if((O==null?void 0:O.substring(0,1))==="="&&(H||K))if(K){if(m.current)return;const{sheetName:z,unitId:ee}=V.range,ke=(ae=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:ae.getUnitId();ee&&ee!==ke?v(4):!z&&U.getSheetId()===(N==null?void 0:N.getSheetId())||z===U.getName()?v(2):v(3)}else m.current=!1,v(1);else v(0)});return I.useEffect(()=>{const W=S.textSelection$.pipe(q.filter(U=>U.unitId===t)).subscribe(()=>{M()});return()=>W.unsubscribe()},[M,S.textSelection$,t]),I.useEffect(()=>{n||(v(0),m.current=!0)},[n,v]),I.useEffect(()=>{var U;if(!o)return;const W=(U=g==null?void 0:g.mainComponent)==null?void 0:U.onPointerDown$.subscribeEvent(()=>{v(0),m.current=!0});return()=>W==null?void 0:W.unsubscribe()},[o,(x=g==null?void 0:g.mainComponent)==null?void 0:x.onPointerDown$,v]),I.useEffect(()=>{if(!n)return;const W=T==null?void 0:T.activeSheet$.subscribe(()=>{M()}),U=c.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>{M()});return()=>{W==null||W.unsubscribe(),U==null||U.unsubscribe()}},[M,n,T==null?void 0:T.activeSheet$,c.getCurrentTypeOfUnit$]),{isSelecting:f,isSelectingRef:E}}const yr=()=>{const e=l.useDependency(R.LexerTreeBuilder);return I.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function Rr(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 $t(e){var T,N,v;const{unitId:t,subUnitId:n,currentWorkbook:o,refSelections:r,editor:s,refSelectionsService:i,refSelectionsRenderService:c,sheetSkeletonManagerService:d,themeService:g,univerInstanceService:p}=e,S=o.getUnitId(),h=p.getUnit(t,a.UniverInstanceType.UNIVER_SHEET),f=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!f){i.setSelections(u);return}const _=f.getSheetId(),m=M=>{var x;return(x=h==null?void 0:h.getSheetBySheetName(M))==null?void 0:x.getSheetId()};if(!((T=d==null?void 0:d.getWorksheetSkeleton(_))==null?void 0:T.skeleton))return;const E=[];for(let M=0,x=r.length;M<x;M++){const W=r[M],{themeColor:U,token:w,refIndex:$,endIndex:k}=W,O=R.deserializeRangeWithSheet(w),{unitId:A,sheetName:b,range:P}=O,V=m(b);if(!V&&b||S!==t&&A!==S||A&&A!==S||V&&V!==_||!V&&_!==n)continue;const H=L.setEndForRange(P,f.getRowCount(),f.getColumnCount());H.unitId=t,H.sheetId=_,u.push({range:H,primary:null,style:Rr(g,U,$.toString())}),E.push(k)}if(s){const M=(v=(N=s.getSelectionRanges())==null?void 0:N[0])==null?void 0:v.startOffset,x=E.findIndex(W=>W+2===M);x!==-1?c==null||c.setActiveSelectionIndex(x):c==null||c.resetActiveSelectionIndex()}return u}function Tr(e,t){const n=l.useDependency(a.IUniverInstanceService),o=l.useDependency(a.ThemeService),r=l.useDependency(L.IRefSelectionsService),s=l.useDependency(j.IRenderManagerService),i=l.useObservable(I.useMemo(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[n])),c=i?s.getRenderById(i.getUnitId()):null,d=c==null?void 0:c.with(F.RefSelectionsRenderService),g=c==null?void 0:c.with(D.SheetSkeletonManagerService),p=l.useEvent((S,h)=>{const f=n.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!f||d!=null&&d.selectionMoving)return;const u=$t({unitId:e,subUnitId:t,currentWorkbook:f,refSelections:S,editor:h,refSelectionsService:r,refSelectionsRenderService:d,sheetSkeletonManagerService:g,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 I.useEffect(()=>()=>{d==null||d.resetActiveSelectionIndex()},[d]),p}function Ft(e=""){const t=l.useDependency(ve.IDescriptionService),n=br(),o=l.useDependency(a.ICommandService),r=I.useMemo(()=>e.length,[e]);return l.useEvent((i,c,d=!0,g)=>{const p=i.getDocumentData(),S=i.getEditorId();if(!p)return[];const h=p.body;if(!h)return[];const f=h.dataStream.slice(0,h.dataStream.length-2),u={dataStream:"",...p.body};if(!f.startsWith(e))return[];if(c==null||c.length===0)return u.textRuns=[],o.syncExecuteCommand(J.ReplaceTextRunsCommand.id,{unitId:S,body:a.getBodySlice(u,0,u.dataStream.length-2)}),[];{const{textRuns:_,refSelections:m}=Mr(t,n,c);r&&_.forEach(T=>{T.ed=T.ed+r,T.st=T.st+r}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},..._];const C=c.reduce((T,N)=>typeof N=="string"?`${T}${N}`:`${T}${N.token}`,"");u.dataStream=`${e}${C}\r
3
+ `;let E;if(d){E=i.getSelectionRanges();const T=u.dataStream.length-2+r;E.forEach(N=>{N.startOffset=Math.max(0,Math.min(N.startOffset,T)),N.endOffset=Math.max(0,Math.min(N.endOffset,T))})}return o.syncExecuteCommand(J.ReplaceTextRunsCommand.id,{unitId:S,body:a.getBodySlice(u,0,u.dataStream.length-2),textRanges:g!=null?g:E}),m}})}function br(){const e=l.useDependency(a.ThemeService),t=e.getCurrentTheme();return I.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 Mr(e,t,n){const{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}=t,c=[],d=[],g=new Map;let p=0;for(let S=0,h=n.length;S<h;S++){const f=n[S];if(typeof f=="string"){const T=c[c.length-1],N=T?T.ed:0,v=N+f.length;c.push({st:N,ed:v,ts:{cl:{rgb:i},fs:11}});continue}if(e.hasDefinedNameDescription(f.token.trim())){c.push({st:f.startIndex,ed:f.endIndex+1,ts:{cl:{rgb:i},fs:11}});continue}const{startIndex:u,endIndex:_,nodeType:m,token:C}=f;let E="";if(m===R.sequenceNodeType.REFERENCE){if(g.has(C))E=g.get(C);else{const T=p%o.length;E=o[T],g.set(C,E),p++}d.push({refIndex:S,themeColor:E,token:C,startIndex:f.startIndex,endIndex:f.endIndex,index:d.length})}else m===R.sequenceNodeType.NUMBER?E=r:(m===R.sequenceNodeType.STRING||m===R.sequenceNodeType.ARRAY)&&(E=s);E&&E.length>0?c.push({st:u,ed:_+1,ts:{cl:{rgb:E},fs:11}}):c.push({st:u,ed:_+1,ts:{cl:{rgb:i},fs:11}})}return{textRuns:c,refSelections:d}}const Or=(e,t,n,o)=>{const r=l.useDependency(a.ICommandService),s=l.useDependency(l.IShortcutService),i=I.useRef(t);i.current=t;const c=I.useRef(o);c.current=o,I.useEffect(()=>{if(!n||!e)return;const g=`sheet.formula-embedding-editor.${n.getEditorId()}`,p=new a.DisposableCollection,S=(u,_)=>{if(c.current){c.current(u,_);return}let m=a.Direction.LEFT;u===l.KeyCode.ARROW_DOWN?m=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?m=a.Direction.UP:u===l.KeyCode.ARROW_RIGHT&&(m=a.Direction.RIGHT),_===l.MetaKeys.SHIFT?r.executeCommand(J.MoveSelectionOperation.id,{direction:m}):r.executeCommand(J.MoveCursorOperation.id,{direction:m})},h=(u,_)=>{let m=a.Direction.DOWN;u===l.KeyCode.ARROW_DOWN?m=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?m=a.Direction.UP:u===l.KeyCode.ARROW_LEFT?m=a.Direction.LEFT:u===l.KeyCode.ARROW_RIGHT&&(m=a.Direction.RIGHT),i.current?_===l.MetaKeys.CTRL_COMMAND?r.executeCommand(D.MoveSelectionCommand.id,{direction:m,jumpOver:D.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:i.current===de.NEED_ADD||i.current===de.EDIT_OTHER_SHEET_REFERENCE}):_===l.MetaKeys.SHIFT?r.executeCommand(D.ExpandSelectionCommand.id,{direction:m,extra:"formula-editor"}):_===(l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT)?r.executeCommand(D.ExpandSelectionCommand.id,{direction:m,jumpOver:D.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand(D.MoveSelectionCommand.id,{direction:m,extra:"formula-editor",fromCurrentSelection:i.current===de.NEED_ADD||i.current===de.EDIT_OTHER_SHEET_REFERENCE}):S(u,_)};return p.add(r.registerCommand({id:g,type:a.CommandType.OPERATION,handler(u,_){const{keyCode:m,metaKey:C}=_;h(m,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:_})=>({id:g,binding:_?u|_:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:u,metaKey:_}})).forEach(u=>{p.add(s.registerShortcut(u))}),()=>{p.dispose()}},[r,n,e,s])},Nr=(e,t,n,o,r=!0)=>{var f;const s=l.useDependency(j.IRenderManagerService),i=l.useDependency(a.IContextService),c=l.useDependency(l.IContextMenuService),d=l.useDependency(L.IRefSelectionsService),g=l.useDependency(a.IUniverInstanceService),p=l.useObservable(I.useMemo(()=>g.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[g])),S=s.getRenderById((f=p==null?void 0:p.getUnitId())!=null?f:""),h=S==null?void 0:S.with(F.RefSelectionsRenderService);I.useLayoutEffect(()=>{if(e)return i.setContextValue(a.EDITOR_ACTIVATED,!0),r&&c.disable(),()=>{const u=g.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]),I.useLayoutEffect(()=>{if(e&&t){const u=h==null?void 0:h.enableSelectionChanging();return i.setContextValue(L.REF_SELECTIONS_ENABLED,!0),()=>{i.setContextValue(L.REF_SELECTIONS_ENABLED,!1),u==null||u.dispose()}}},[i,e,h,t]),I.useEffect(()=>{e&&(h==null||h.setSkipLastEnabled(!1))},[e,h])},Dr=(e,t,n)=>{const o=l.useDependency(a.IUniverInstanceService),r=l.useDependency(L.SheetsSelectionsService);return I.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])},xr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),ut=e=>e.map(t=>typeof t=="string"?t:t.token).join(""),Ge=(e,t=!1,n="",o=!1)=>!t&&!o?e.map(r=>R.serializeRange(r.range)):e.map(r=>o?R.serializeRangeToRefString(r):r.sheetName!==""&&r.sheetName!==n?R.serializeRangeWithSheet(r.sheetName,r.range):R.serializeRange(r.range)),kr=e=>{var p,S,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=((S=(p=t==null?void 0:t.getDocumentData().body)==null?void 0:p.dataStream)!=null?S:`\r
4
+ `).slice(0,-2),c=(h=n.sequenceNodesBuilder(i.slice(1)))!=null?h:[],d=at(c,s,!1),g=At(c,d);return{nodeIndex:d,updatingRefIndex:g,sequenceNodes:c,offset:s}},wr=(()=>{}),Ar=(e,t,n,o,r,s,i,c,d,g=wr)=>{var $;const p=l.useDependency(j.IRenderManagerService),S=l.useDependency(a.IUniverInstanceService),h=l.useDependency(a.ICommandService),f=l.useDependency(ft.DocSelectionManagerService),u=l.useDependency(a.ThemeService),_=l.useDependency(R.LexerTreeBuilder),m=S.getUnit(o),C=l.useEvent((k,O)=>{var A,b,P;return(P=(b=(A=S.getUnit(k))==null?void 0:A.getSheetBySheetId(O))==null?void 0:b.getName())!=null?P:""}),E=I.useMemo(()=>C(o,r),[C,r,o]),T=l.useObservable(m==null?void 0:m.activeSheet$),N=Te({activeSheet:T,sheetName:E}),v=l.useObservable(I.useMemo(()=>S.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[S])),M=p.getRenderById(($=v==null?void 0:v.getUnitId())!=null?$:""),x=M==null?void 0:M.with(F.RefSelectionsRenderService),W=M==null?void 0:M.with(D.SheetSkeletonManagerService),U=l.useDependency(L.IRefSelectionsService),w=l.useEvent((k,O)=>{var K,oe,se,ae,z,ee,ke,we,Xe,fe;const A=kr({editor:d,lexerTreeBuilder:_});if(!A)return;const{nodeIndex:b,updatingRefIndex:P,sequenceNodes:V,offset:H}=A;if(n.current===de.NEED_ADD)if(H!==0){if(b===-1&&V.length)return;const G=k[k.length-1],Q=V.splice(b+1),he=(K=G.sheetId)!=null?K:r,le={range:G,unitId:(oe=G.unitId)!=null?oe:v.getUnitId(),sheetName:C((se=G.unitId)!=null?se:v.getUnitId(),he)},te=he!==r,ie=(v==null?void 0:v.getUnitId())!==o,ge=Ge([le],i&&(te||ie),E,ie);V.push({token:ge[0],nodeType:R.sequenceNodeType.REFERENCE});const be=[...V,...Q],me=ut(be);g(me,xr(V),O)}else{const G=k[k.length-1],Q=(ae=G.sheetId)!=null?ae:r,he={range:G,unitId:(z=G.unitId)!=null?z:v.getUnitId(),sheetName:C((ee=G.unitId)!=null?ee:v.getUnitId(),Q)},le=Q!==r,te=(v==null?void 0:v.getUnitId())!==o,ie=Ge([he],i&&(le||te),E,te);V.unshift({token:ie[0],nodeType:R.sequenceNodeType.REFERENCE});const ge=ut(V);g(ge,ie[0].length,O)}else if(n.current===de.EDIT_OTHER_SHEET_REFERENCE||n.current===de.EDIT_OTHER_WORKBOOK_REFERENCE){const G=k.pop();if(!G)return;const Q=V[b];if(typeof Q=="object"&&Q.nodeType===R.sequenceNodeType.REFERENCE){const he=Q.token;(v==null?void 0:v.getUnitId())!==o?Q.token=R.serializeRangeWithSpreadsheet((ke=v==null?void 0:v.getUnitId())!=null?ke:"",E,G):Q.token=E===(T==null?void 0:T.getName())?R.serializeRange(G):R.serializeRangeWithSheet(T.getName(),G);const te=H+(Q.token.length-he.length);g(R.generateStringWithSequence(V),te,O)}}else{const G=[...k];if(P!==-1){const Z=G.pop();Z&&G.splice(P,0,Z)}let Q=0;const he=V.map(Z=>{var ue,Ae,Me,Oe;if(typeof Z=="string")return Z;if(Z.nodeType===R.sequenceNodeType.REFERENCE){const Ne=R.deserializeRangeWithSheet(Z.token);if(Ne.sheetName||(Ne.sheetName=E),(Ne.unitId||o)!==(v==null?void 0:v.getUnitId())||i&&((ue=N.current.activeSheet)==null?void 0:ue.getName())!==Ne.sheetName)return Z.token;const ne=G[Q];if(Q++,!ne)return"";const Se=(Ae=ne.sheetId)!=null?Ae:r,Qe={range:ne,unitId:(Me=ne.unitId)!=null?Me:v.getUnitId(),sheetName:C((Oe=ne.unitId)!=null?Oe:v.getUnitId(),Se)},Je=(v==null?void 0:v.getUnitId())!==o;return Ge([Qe],i&&(Se!==r||Je),E,Je)[0]}return Z.token});let le="",te;he.forEach((Z,ue)=>{le+=Z,ue===b&&(te=le.length)});const ie=[];for(let Z=Q;Z<=k.length-1;Z++){const ue=k[Z],Ae=(we=ue.sheetId)!=null?we:r,Me={range:ue,unitId:(Xe=ue.unitId)!=null?Xe:v.getUnitId(),sheetName:C((fe=ue.unitId)!=null?fe:v.getUnitId(),Ae)},Oe=(v==null?void 0:v.getUnitId())!==o,ne=Ge([Me],i&&(Ae!==r||Oe),E,Oe);ie.push(ne[0])}const ge=V[V.length-1],be=ge&&(typeof ge=="string"?!1:ge.nodeType===R.sequenceNodeType.REFERENCE),me=`${le}${ie.length&&be?",":""}${ie.join(",")}`;g(me,!ie.length&&te?te:me.length,O)}});I.useEffect(()=>{if(x&&e){let k=!0;const O=(b,P)=>{if(k){k=!1;return}w(b.map(V=>V.rangeWithCoord),P)},A=new a.DisposableCollection;return A.add(x.selectionMoving$.subscribe(b=>{O(b,!1)})),A.add(x.selectionMoveEnd$.subscribe(b=>{O(b,!0)})),()=>{A.dispose()}}},[e,w,x]),I.useEffect(()=>{if(t&&x&&d){const k=new a.DisposableCollection,O=()=>{k.dispose(),x.getSelectionControls().forEach((P,V)=>{k.add(P.selectionScaling$.subscribe(H=>{const K=x.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=K[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,K[V]=H,w(K,!1)})),k.add(P.selectionMoving$.subscribe(H=>{const K=x.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=K[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,K[V]=H,w(K,!0)}))})},A=q.merge(d.input$,U.selectionSet$,x.selectionMoveEnd$).pipe(Xt.debounceTime(50)).subscribe(()=>{O()});return()=>{A.unsubscribe(),k.dispose()}}},[d,t,w,x,U.selectionSet$]),x==null||x.getSelectionDataWithStyle(),I.useEffect(()=>{if(c){const k=h.onCommandExecuted(O=>{var b;if(O.id!==L.SetSelectionsOperation.id)return;const A=O.params;if(A.extra==="formula-editor"&&A.selections.length){const P=A.selections[A.selections.length-1];if(P){const V=n.current===de.NEED_ADD,H=((b=x==null?void 0:x.getSelectionDataWithStyle())!=null?b:[]).map(K=>K.rangeWithCoord);V?H.push(P.range):H[H.length-1]=P.range,w(H,!0)}}});return()=>{k.dispose()}}},[h,d,n,_,c,w,x]),I.useEffect(()=>{if(!d)return;const k=f.textSelection$.subscribe(O=>{O.unitId===d.getEditorId()&&$t({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:U,refSelectionsRenderService:x,sheetSkeletonManagerService:W,themeService:u,univerInstanceService:S,currentWorkbook:v})});return()=>k.unsubscribe()},[f.textSelection$,d,s,x,U,W,r,u,o,S])},Pr=(e,t,n,o,r,s)=>{const i=l.useDependency(a.ICommandService),c=l.useDependency(J.IEditorService),g=l.useDependency(j.IRenderManagerService).getRenderById(t),p=l.useDependency(a.IUniverInstanceService),S=g==null?void 0:g.with(F.RefSelectionsRenderService);I.useEffect(()=>{if(e&&S)if(n){const h=()=>{const _=S.getSelectionControls().length;for(let m=1;m<=_;m++)S.clearLastSelection();return setTimeout(()=>{s()},30)},f=i.onCommandExecuted(_=>{_.id===L.SetWorksheetActiveOperation.id&&h()}),u=p.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(_=>{h()});return()=>{f.dispose(),u.unsubscribe()}}else{const h=i.beforeCommandExecuted(f=>{if(f.id===L.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,S])},Lr=(e,t,n)=>{const o=l.useDependency(R.LexerTreeBuilder),r=I.useRef(!0);I.useEffect(()=>{if(e){const s=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(s)}}},[e]),I.useEffect(()=>{if(!r.current&&t){const s=o.checkIfAddBracket(n);t(s===0&&n.startsWith(R.operatorToken.EQUALS),`${n}`)}},[n,t])},$r=(e,t=[],n)=>{const o=l.useDependency(ve.IDescriptionService),[r,s]=I.useState([]),[i,c]=I.useState(""),d=I.useRef(-1),g=Te({nodes:t}),p=()=>{s([]),c(""),d.current=-1};return I.useEffect(()=>{if(n&&e){const h=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const f=n.getSelectionRanges();if(f.length===1){const u=g.current.nodes,_=f[0];if(_.collapsed){const m=at(u,_.startOffset-1,!1);d.current=m;const C=u[m];if(C&&typeof C!="string"&&C.nodeType===R.sequenceNodeType.FUNCTION){d.current=m;const E=C.token,T=o.getSearchListByNameFirstLetter(E);s(T),c(E);return}}}d.current=-1,c(""),s(u=>u!=null&&u.length?[]:u)});return()=>{h.unsubscribe()}}},[n,e]),I.useEffect(()=>{e||p()},[e]),{searchList:r,searchText:i,handlerFormulaReplace:(h,f)=>{const u=[...g.current.nodes];if(d.current!==-1){const _=u.splice(d.current+1),m=u.pop()||"";let C=(typeof m=="string"?m.length:m.token.length)-h.length;return u.push(h),_[0]!==R.matchToken.OPEN_BRACKET&&f!==R.FunctionType.DefinedName&&(u.push(R.matchToken.OPEN_BRACKET),C--),{text:ut([...u,..._]),offset:C}}},reset:p}},Fr=()=>{},Wr=I.forwardRef(Ur);function Ur(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:s,onClose:i=Fr}=e,c=s.getEditorId(),d=l.useDependency(l.IShortcutService),g=l.useDependency(a.ICommandService),{searchList:p,searchText:S,handlerFormulaReplace:h,reset:f}=$r(n,o,s),u=I.useMemo(()=>!!p.length,[p]),_=I.useRef(void 0),[m,C]=I.useState(0),E=I.useRef(!1),[T]=Pt(c,u,[S,p]),N=Te({searchList:p,active:m}),v=(w,$)=>{const k=h(w,$);k&&(f(),r(k))};function M(w){E.current&&C(w)}function x(){E.current&&C(-1)}I.useEffect(()=>{if(!p.length)return;const w=`sheet.formula-embedding-editor.search_function.${c}`,$=new a.DisposableCollection,k=O=>{const{searchList:A,active:b}=N.current;switch(O){case l.KeyCode.ARROW_UP:{C(P=>{const V=Math.max(0,P-1);return W(V),V});break}case l.KeyCode.ARROW_DOWN:{C(P=>{const V=Math.min(A.length-1,P+1);return W(V),V});break}case l.KeyCode.TAB:case l.KeyCode.ENTER:{const P=A[b];v(P.name,P.functionType);break}case l.KeyCode.ESC:{f(),i();break}}};return $.add(g.registerCommand({id:w,type:a.CommandType.OPERATION,handler(O,A){const{keyCode:b}=A;k(b)}})),[l.KeyCode.ARROW_UP,l.KeyCode.ARROW_DOWN,l.KeyCode.ENTER,l.KeyCode.ESC,l.KeyCode.TAB].map(O=>({id:w,binding:O,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:j.DeviceInputEventType.Keyboard,keyCode:O}})).forEach(O=>{$.add(d.registerShortcut(O))}),()=>{$.dispose()}},[p]);function W(w){const $=_.current;if(!$)return;const k=$.children[w];if(!k)return;const A=$.getBoundingClientRect().top,b=$.offsetHeight,P=k.getBoundingClientRect(),V=P.top,H=P.height;if(V>=0&&V>A&&V-A+H<=b)return;const K=k.offsetTop-(b-H)/2;$.scrollTo({top:K,behavior:"smooth"})}const U=I.useMemo(()=>{let w="";return()=>{clearTimeout(w),E.current=!0,w=setTimeout(()=>{E.current=!1},300)}},[]);return p.length>0&&u&&y.jsx(l.RectPopup,{portal:!0,anchorRect$:T,direction:"vertical",children:y.jsx("ul",{ref:w=>{_.current=w,t&&(t.current=w)},"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:p.map((w,$)=>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":m===$}),onMouseEnter:()=>M($),onMouseLeave:x,onMouseMove:U,onClick:()=>{v(w.name,w.functionType),s&&s.focus()},children:[y.jsxs("span",{className:"univer-block univer-overflow-x-hidden univer-text-ellipsis univer-text-xs",children:[y.jsx("span",{className:"univer-text-red-500",children:w.name.substring(0,S.length)}),y.jsx("span",{children:w.name.slice(S.length)})]}),y.jsx("span",{className:"univer-block univer-text-xs univer-text-gray-400",children:w.desc})]},w.name))})})}const Vr=e=>e.startsWith(R.operatorToken.EQUALS)?e.slice(1):"",Wt=()=>{},Ut=I.forwardRef((e,t)=>{var jt,qt,Yt,zt;const{errorText:n,initValue:o,unitId:r,subUnitId:s,isFocus:i=!0,isSupportAcrossSheet:c=!1,onFocus:d=Wt,onBlur:g=Wt,onChange:p,onVerify:S,className:h,editorId:f,moveCursor:u=!0,onFormulaSelectingChange:_,keyboardEventConfig:m,onMoveInEditor:C,resetSelectionOnBlur:E=!0,autoScrollbar:T=!0,isSingle:N=!0,disableSelectionOnClick:v=!1,autofocus:M=!0,disableContextMenu:x,style:W}=e,U=l.useDependency(J.IEditorService),w=I.useRef(null),$=l.useEvent(p);I.useImperativeHandle(t,()=>({isClickOutSide:X=>w.current?!w.current.contains(X.target):!1}));const k=l.useEvent(_),O=I.useRef(null),A=I.useRef(void 0),b=A.current,[P,V]=I.useState(i),H=I.useRef(null),K=I.useMemo(()=>f!=null?f:a.createInternalEditorID(`${D.EMBEDDING_FORMULA_EDITOR}-${a.generateRandomId(4)}`),[]),oe=I.useMemo(()=>n!==void 0,[n]),se=l.useDependency(a.IUniverInstanceService),ae=se.getUnit(K);l.useObservable(ae==null?void 0:ae.change$);const z=yr(),ee=a.BuildTextUtils.transform.getPlainText((qt=(jt=ae==null?void 0:ae.getBody())==null?void 0:jt.dataStream)!=null?qt:""),ke=Te(ee),we=I.useMemo(()=>Vr(ee),[ee]),Xe=I.useMemo(()=>z(we),[we,z]),{isSelecting:fe,isSelectingRef:G}=Er({unitId:r,subUnitId:s,editorId:K,isFocus:P,disableOnClick:v}),Q=I.useRef(""),le=l.useDependency(j.IRenderManagerService).getRenderById(K),te=le==null?void 0:le.with(J.DocSelectionRenderService),ie=te==null?void 0:te.isFocusing,ge=I.useMemo(()=>se.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[se]),be=l.useObservable(ge),me=(be==null?void 0:be.getUnitId())===K,Z=I.useRef([]),ue=fe,Me=(zt=(Yt=l.useDependency(a.IConfigService).getConfig(_t))==null?void 0:Yt.functionScreenTips)!=null?zt:!0;l.useUpdateEffect(()=>{$(ee)},[ee,$]);const Oe=Ft("="),Ne=Tr(r,s),ne=l.useEvent((X,re=!0,Ce,pe)=>{if(!A.current)return;Q.current=X;const et=X[0]==="="?X.slice(1):"",_e=z(et),eo=_e.reduce((De,nt)=>typeof nt=="object"?`${De}${nt.token}`:`${De}${nt}`,""),tt=Oe(A.current,eo===et?_e:[],re,pe);if(Z.current=tt,Ce){const De=pe!=null?pe:b==null?void 0:b.getSelectionRanges();if((De==null?void 0:De.length)!==1)return;const to=De[0].startOffset-1,no=at(_e,to,!1),Gt=At(_e,no);if(Gt>=0){const Zt=tt.splice(Gt,1)[0];Zt&&tt.push(Zt)}Ne(P?tt:[],A.current)}});I.useEffect(()=>{P&&ne(ee,!1,!0)},[P]),I.useEffect(()=>{if(P){if(Q.current===ee)return;ne(ee,!1,!0)}},[ee]),Lr(P,S,ee);const Se=_r(b),Qe=Dr(P,r,s);I.useEffect(()=>{var X;k(fe,(X=te==null?void 0:te.isFocusing)!=null?X:!0)},[k,fe]),J.useKeyboardEvent(P,m,b),I.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);A.current=re,ne(o,!1,!0)}return()=>{X==null||X.dispose()}},[]),I.useLayoutEffect(()=>{i?(V(i),Se()):(E&&(b==null||b.blur(),Qe()),V(i))},[i,b,Se,Qe,E]);const{checkScrollBar:Je}=J.useResize(b,N,T);Nr(P,!!(fe&&me),r,K,x),Or(!!(P&&ie&&u),ue,b,C);const Ht=l.useEvent((X,re,Ce)=>{if(!ie)return;const pe=re!==-1?[{startOffset:re+1,endOffset:re+1,collapsed:!0}]:void 0;ne(`=${X}`,!0,Ce,pe),Ce&&(Se(),re!==-1&&setTimeout(()=>{const et={startOffset:re+1,endOffset:re+1},_e=b==null?void 0:b.render.with(J.DocBackScrollRenderController);_e==null||_e.scrollToRange({...et,collapsed:!0})},50),Je())});Ar(P&&!!(fe&&me),P,G,r,s,Z,c,!!ue,b,Ht),Pr(P&&!!(fe&&me),r,c,V,g,()=>{ne(ke.current,!1,!0)});const Kt=X=>{if(X){const re=b==null?void 0:b.getSelectionRanges();if(re&&re.length===1){const Ce=re[0];if(Ce.collapsed){const pe=X.offset;setTimeout(()=>{b==null||b.setSelectionRanges([{startOffset:Ce.startOffset-pe,endOffset:Ce.endOffset-pe}])},30)}}Se(),ne(`=${X.text}`)}},Jr=()=>{V(!0),d(),Se()};return y.jsxs("div",{className:h,children:[y.jsx("div",{ref:w,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":P,"univer-ring-red-500":oe}),children:y.jsx("div",{ref:H,className:"univer-relative univer-h-full univer-w-full",onMouseUp:Jr})}),n!==void 0&&y.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),Me&&b&&we!==""&&y.jsx(Cr,{editor:b,isFocus:P,formulaText:ee,onClose:()=>Se()}),Me&&!!b&&y.jsx(Wr,{isFocus:P,sequenceNodes:Xe,onSelect:Kt,ref:O,editor:b})]})});function Br(e,t,n,o){const r=l.useDependency(R.LexerTreeBuilder),s=Ft(""),i=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[c,d]=I.useState([]),g=l.useDependency(D.IMarkSelectionService),p=I.useRef(""),S=l.useDependency(a.IUniverInstanceService);return I.useEffect(()=>{if(!e)return;const h=e.getDocumentDataModel().getPlainText();if(p.current===h)return;p.current=h;const f=r.sequenceNodesBuilder(h);d(f!=null?f:[])},[i,e,r]),I.useEffect(()=>{var u,_;if(!e)return;if(!t){const m=e.getDocumentData();e.setDocumentData({...m,body:{...m.body,dataStream:(_=(u=m.body)==null?void 0:u.dataStream)!=null?_:"",textRuns:[]}});return}const h=s(e,c,!1),f=new a.DisposableCollection;return h.forEach(m=>{const C=R.deserializeRangeWithSheet(m.token),E=S.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),T=E==null?void 0:E.getActiveSheet();if(!C.sheetName&&o!==(T==null?void 0:T.getSheetId())||C.sheetName&&(T==null?void 0:T.getName())!==C.sheetName)return;const N=new a.ColorKit(m.themeColor).toRgb(),v=g.addShape({range:C.range,style:{stroke:m.themeColor,fill:`rgba(${N.r}, ${N.g}, ${N.b}, 0.1)`,strokeDash:12},primary:null});v&&f.add(()=>g.removeShape(v))}),()=>{f.dispose()}},[e,t,s,g,c]),{sequenceNodes:c}}function Hr(e){const t=l.useDependency(L.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),g=l.useEvent(i),p=l.useEvent((S,h)=>{const f=d==null?void 0:d.getActiveSheet();if(!f||!n&&f.getSheetId()!==s||!(S!=null&&S.length))return;const u=o?f.getName():f.getSheetId()===s?"":f.getName(),_=S.map(m=>({range:m.range,unitId:r,sheetName:u}));g(_,h)});I.useEffect(()=>{const S=new a.DisposableCollection;return S.add(t.selectionMoveStart$.subscribe(h=>{p(h,!0)})),S.add(t.selectionMoving$.subscribe(h=>{p(h,!1)})),S.add(t.selectionMoveEnd$.subscribe(h=>{p(h,!1)})),()=>{S.dispose()}},[p,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const Vt=e=>!e.some(n=>{if(typeof n=="string"){if(n!==R.matchToken.COMMA)return!0}else if(n.nodeType!==R.sequenceNodeType.REFERENCE)return!0;return!1}),Kr=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 jr(e){const{visible:t,initialValue:n,unitId:o,subUnitId:r,maxRangeCount:s=1/0,supportAcrossSheet:i,keepSheetReference:c,onConfirm:d,onClose:g,onShowBySelection:p}=e,S=l.useDependency(a.LocaleService),h=l.useDependency(R.LexerTreeBuilder),[f,u]=I.useState([]),[_,m]=I.useState(0),C=I.useRef(null);I.useEffect(()=>{if(t&&n.length){const v=n.map(M=>M.sheetName?R.serializeRangeWithSheet(M.sheetName,M.range):R.serializeRange(M.range));u(v),m(v.length-1)}else u([""]),m(0)},[t]);const E=(v,M)=>{const x=[...f];x[v]=M,u(x)},T=()=>{u([...f,""]),m(f.length)},N=v=>{f.splice(v,1),u([...f])};return Hr({unitId:o,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(v,M)=>{if(!t&&p!=null&&p(v))return;const x=new Set(f),W=v.map($=>$.sheetName?R.serializeRangeWithSheet($.sheetName,$.range):R.serializeRange($.range)),U=W.filter($=>!x.has($));if(!U.length)return;const w=[...f];if(W.length>1){M||w.splice(_,1),w.push(...U);const $=w.slice(0,s);u($),m($.length-1),requestAnimationFrame(()=>{var k;(k=C.current)==null||k.scrollTo({top:C.current.scrollHeight})})}else{w.splice(_,1,...U);const $=w.slice(0,s);u($),m(_+U.length-1)}}}),y.jsx(B.Dialog,{width:"328px",open:t,title:S.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:g,children:S.t("rangeSelector.cancel")}),y.jsx(B.Button,{variant:"primary",onClick:()=>{d(f.filter(v=>{const M=h.sequenceNodesBuilder(v);return M&&M.length===1&&typeof M[0]!="string"&&M[0].nodeType===R.sequenceNodeType.REFERENCE}).map(v=>R.deserializeRangeWithSheet(v)).map(v=>({...v,range:Kr(v.range)})))},children:S.t("rangeSelector.confirm")})]}),onClose:g,children:y.jsxs("div",{ref:C,className:B.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",B.scrollbarClassName),children:[f.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}),placeholder:S.t("rangeSelector.placeHolder"),onFocus:()=>m(M),value:v,onChange:x=>E(M,x)}),f.length>1&&y.jsx(Dt,{className:"univer-cursor-pointer",onClick:()=>N(M)})]},M)),f.length<s&&y.jsx("div",{children:y.jsxs(B.Button,{variant:"link",onClick:T,children:[y.jsx(xt,{}),y.jsx("span",{children:S.t("rangeSelector.addAnotherRange")})]})})]})})}function qr(e){return e.split(R.matchToken.COMMA).filter(t=>!!t).map(t=>R.deserializeRangeWithSheet(t))}function Yr(e){return e.map(t=>t.sheetName?R.serializeRangeWithSheet(t.sheetName,t.range):R.serializeRange(t.range)).join(R.matchToken.COMMA)}function dt(e){const[t,n]=I.useState(null),{onVerify:o,selectorRef:r,unitId:s,subUnitId:i,maxRangeCount:c,supportAcrossSheet:d,keepSheetReference:g,autoFocus:p,onChange:S,onRangeSelectorDialogVisibleChange:h,onClickOutside:f,onFocusChange:u,forceShowDialogWhenSelectionChanged:_,hideEditor:m,resetRange:C}=e,[E,T]=I.useState(p!=null?p:!1),[N,v]=I.useState(!1),[M,x]=I.useState([]),W=l.useDependency(a.LocaleService),U=l.useDependency(J.IEditorService),{sequenceNodes:w}=Br(t,E,s,i),$=Te(w),k=l.useDependency(a.ICommandService),O=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),U.blur()}),A=l.useEvent(()=>{var b;O(),x(qr((b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")),v(!0)});return I.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){U.focus(t.getEditorId())},blur:O,verify:()=>Vt($.current),showDialog:b=>{O(),x(b),v(!0)},hideDialog:()=>{x([]),v(!1)},getValue:()=>{var b;return(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:""}})},[O,t,U,r,$]),I.useEffect(()=>{var b;o==null||o(Vt(w),(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")},[w]),I.useEffect(()=>{h==null||h(N)},[N]),I.useEffect(()=>{if(N&&C)return()=>{const b={unitId:s,subUnitId:i,selections:C};k.executeCommand(L.SetSelectionsOperation.id,b)}},[N]),y.jsxs(y.Fragment,{children:[m?null:y.jsx(J.RichTextEditor,{isSingle:!0,...e,onFocusChange:(b,P)=>{T(b),u==null||u(b,P)},editorRef:n,onClickOutside:()=>{T(!1),O(),f==null||f()},icon:y.jsx(B.Tooltip,{title:W.t("rangeSelector.buttonTooltip"),placement:"bottom",children:y.jsx(wt,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:A})})}),y.jsx(jr,{initialValue:M,unitId:s,subUnitId:i,visible:N,maxRangeCount:c,onConfirm:b=>{const P=Yr(b),V=a.RichTextBuilder.newEmptyData();V.body.dataStream=P,t==null||t.replaceText(P,!1),S==null||S(V,P),v(!1),x([]),requestAnimationFrame(()=>{O()})},onClose:()=>{v(!1),x([])},supportAcrossSheet:d,keepSheetReference:g,onShowBySelection:b=>E||_?(x(b),v(!0),!1):!0})]})}const zr=()=>{var o,r;const e=l.useDependency(ct),t=l.useObservable(e.currentSelector$),n=I.useRef(null);return I.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(dt,{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=>R.deserializeRangeWithSheet(d)))!=null?c:[])}})};var Gr=Object.defineProperty,Zr=Object.getOwnPropertyDescriptor,Xr=(e,t,n)=>t in e?Gr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Qr=(e,t,n,o)=>{for(var r=o>1?void 0:o?Zr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Ze=(e,t)=>(n,o)=>t(n,o,e),Bt=(e,t,n)=>Xr(e,typeof t!="symbol"?t+"":t,n);F.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=It,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(It,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(_t,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[Ue,{useClass:rt}],[ct],[ze],[He],[Ke],[je],[qe],[F.FormulaReorderController]]),this._initUIPart()}onReady(){[[F.RefSelectionsRenderService]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))})}onRendered(){[[it]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))}),a.touchDependencies(this._injector,[[ze],[Ke],[qe]])}onSteady(){this._injector.get(He),this._injector.get(F.FormulaReorderController)}_initUIPart(){const t=this._injector.get(l.ComponentManager);this.disposeWithMe(t.register(D.RANGE_SELECTOR_COMPONENT_KEY,dt)),this.disposeWithMe(t.register(D.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Ut)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(zr,this._injector)))}},Bt(F.UniverSheetsFormulaUIPlugin,"pluginName",vt),Bt(F.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET),F.UniverSheetsFormulaUIPlugin=Qr([a.DependentOn(R.UniverFormulaEnginePlugin,ve.UniverSheetsFormulaPlugin),Ze(1,a.Inject(a.Injector)),Ze(2,j.IRenderManagerService),Ze(3,a.IConfigService),Ze(4,l.IUIPartsService)],F.UniverSheetsFormulaUIPlugin),F.FORMULA_PROMPT_ACTIVATED=ht,F.FormulaEditor=Ut,F.GlobalRangeSelectorService=ct,F.HelpFunctionOperation=gt,F.InsertFunctionOperation=ce,F.MoreFunctionsOperation=Ve,F.RangeSelector=dt,F.ReferenceAbsoluteOperation=ot,F.SearchFunctionOperation=Ct,F.SelectEditorFormulaOperation=Ie,F.SheetOnlyPasteFormulaCommand=We,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/sheets-formula-ui",
3
- "version": "0.10.12",
3
+ "version": "0.10.13",
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": "^0.4.9",
67
- "@univerjs/core": "0.10.12",
68
- "@univerjs/design": "0.10.12",
69
- "@univerjs/docs": "0.10.12",
70
- "@univerjs/docs-ui": "0.10.12",
71
- "@univerjs/engine-render": "0.10.12",
72
- "@univerjs/sheets": "0.10.12",
73
- "@univerjs/sheets-formula": "0.10.12",
74
- "@univerjs/engine-formula": "0.10.12",
75
- "@univerjs/sheets-ui": "0.10.12",
76
- "@univerjs/ui": "0.10.12"
66
+ "@univerjs/icons": "^1.0.2",
67
+ "@univerjs/core": "0.10.13",
68
+ "@univerjs/design": "0.10.13",
69
+ "@univerjs/engine-render": "0.10.13",
70
+ "@univerjs/docs": "0.10.13",
71
+ "@univerjs/engine-formula": "0.10.13",
72
+ "@univerjs/docs-ui": "0.10.13",
73
+ "@univerjs/sheets-formula": "0.10.13",
74
+ "@univerjs/sheets": "0.10.13",
75
+ "@univerjs/sheets-ui": "0.10.13",
76
+ "@univerjs/ui": "0.10.13"
77
77
  },
78
78
  "devDependencies": {
79
79
  "postcss": "^8.5.6",
@@ -83,7 +83,7 @@
83
83
  "typescript": "^5.9.3",
84
84
  "vite": "^7.1.10",
85
85
  "vitest": "^3.2.4",
86
- "@univerjs-infra/shared": "0.10.12"
86
+ "@univerjs-infra/shared": "0.10.13"
87
87
  },
88
88
  "scripts": {
89
89
  "test": "vitest run",