@univerjs/sheets-formula-ui 0.12.2 → 0.12.3

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.
@@ -1,6 +1,6 @@
1
1
  import { LocaleService } from '@univerjs/core';
2
- import { IFunctionInfo, IFunctionParam } from '@univerjs/engine-formula';
3
- export declare function getFunctionTypeValues(enumObj: any, localeService: LocaleService): Array<{
2
+ import { FunctionType, IFunctionInfo, IFunctionParam } from '@univerjs/engine-formula';
3
+ export declare function getFunctionTypeValues(enumObj: typeof FunctionType, localeService: LocaleService): Array<{
4
4
  label: string;
5
5
  value: string;
6
6
  }>;
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,K,L,de,l,y,I,B,gt,Jt){"use strict";var co=Object.defineProperty;var ao=(F,a,D)=>a in F?co(F,a,{enumerable:!0,configurable:!0,writable:!0,value:D}):F[a]=D;var Y=(F,a,D)=>ao(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 en=Object.getOwnPropertyDescriptor,tn=(e,t,n,o)=>{for(var r=o>1?void 0:o?en(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},nn=(e,t)=>(n,o)=>t(n,o,e);const St="FORMULA_PROMPT_ACTIVATED",Ue=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(St,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}};ot=tn([nn(0,a.IContextService)],ot);const pt={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&&(sn(r[0].range)||cn(r[0].range)&&mt(g,r[0].range))){const{range:N,primary:v}=r[0],M=(E=v==null?void 0:v.actualRow)!=null?E:N.startRow,k=(T=v==null?void 0:v.actualColumn)!=null?T:N.startColumn;u=N,_=M,m=k;const W=vt(g,M,k);W&&(C=R.serializeRange(W))}else r.some(N=>{var k,W;const{range:v,primary:M}=N;if(mt(g,v)){const U=(k=M==null?void 0:M.actualRow)!=null?k:v.startRow,w=(W=M==null?void 0:M.actualColumn)!=null?W:v.startColumn,$=vt(g,U,w);if(!$)return u=v,_=U,m=w,!0;const x=R.serializeRange($),O=`=${p}(${x})`;h.push({range:v,primary:{row:U,column:w},formula:O})}else{const{startRow:U,startColumn:w,endRow:$,endColumn:x}=v;if(U===$){const O=an(g,U,x,i.getColumnCount()-1),A=O===x?x-1:x,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<=x;b++){const P=ln(g,b,$,i.getRowCount()-1);O=Math.max(O,P)}const A=O===$?$-1:$;for(let b=w;b<=x;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 k=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:K.DeviceInputEventType.Dblclick});const U=`=${p}(${C}`;k==null||k.replaceText(U),W==null||W.replaceText(U,!1)}return h.length===0&&f.length===0?!1:S.executeCommand(de.InsertFunctionCommand.id,{list:h,listOfRangeHasNumber:f})}};function vt(e,t,n){const o=rn(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=on(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function rn(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 on(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 sn(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function cn(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function mt(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 an(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function ln(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const Ct="SHEET_FORMULA_UI_PLUGIN",_t=`${Ct}_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:_t}}),!0)},st={id:"formula-ui.operation.change-ref-to-absolute",type:a.CommandType.OPERATION,handler:async e=>!0},It={id:"formula-ui.operation.search-function",type:a.CommandType.OPERATION,handler:async(e,t)=>(e.get(Ue).search(t),!0)};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},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=dn([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 Et="sheets-formula-ui.base.config",yt={};var fn=Object.getOwnPropertyDescriptor,hn=(e,t,n,o)=>{for(var r=o>1?void 0:o?fn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Le=(e,t)=>(n,o)=>t(n,o,e);const it="SHEET_FORMULA_ALERT",gn={[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 c=this._context.unit.getActiveSheet();if(!c)return this._hideAlert();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(it),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){this._hideAlert();return}this._cellAlertManagerService.showAlert({type:D.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${gn[p]}`),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=hn([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)],ct);var Sn=Object.getOwnPropertyDescriptor,pn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Sn(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);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=mn(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}=vn(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=pn([Rt(0,D.IAutoFillService),Rt(1,a.Inject(R.LexerTreeBuilder))],He);function vn(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 mn(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}var Cn=Object.getOwnPropertyDescriptor,_n=(e,t,n,o)=>{for(var r=o>1?void 0:o?Cn(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 In="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:In,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=>En(c,d,g,p,f,S,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};Ke=_n([$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 En(e,t,n,o,r,s,i,c,d=!1,g){const p=[],S=[],h=yn(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 yn(e,t,n,o,r,s,i,c){return c?r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?Tn(e,t,n,o,i,c):r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?bn(e,t,n,o,s,i,c):Mn(e,t,n,o,r.copyType,s,i,c):Rn(e,t,n,o,i)}function Rn(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 Tn(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=Tt(f);v&&(E.v=v)}i.setValue(m,C,E)}}),i}function bn(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 _=Tt(S);_&&(u.v=_)}c.setValue(h,f,u)}}),c}function Mn(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],k=s.moveFormulaRefOffset(u.f||"",v,M);C.si=N,C.f=k}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 Tt(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 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},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=Nn([Ee(1,a.Inject(L.SheetInterceptorService)),Ee(2,a.Inject(R.FormulaDataModel)),Ee(3,a.Inject(a.ThemeService)),Ee(4,K.IRenderManagerService),Ee(5,a.Inject(D.SheetSkeletonManagerService)),Ee(6,a.ICommandService),Ee(7,a.ILogService)],je);var Dn=Object.getOwnPropertyDescriptor,kn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Dn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},bt=(e,t)=>(n,o)=>t(n,o,e);const xn={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,...xn}),r(n)},priority:10}))}};qe=kn([bt(0,a.Inject(L.SheetInterceptorService)),bt(1,a.Inject(R.FormulaDataModel))],qe);function wn(){const e=l.useDependency(de.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 An(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 Mt(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 Ot(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:Mt(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 Pn(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(Ot,{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(`_${Fn()}`);return Nt(n,`${o}`,{defIds:n.defIds,idSuffix:d.current},{ref:e,className:c,...i},s)}function Nt(e,t,n,o,r){return I.createElement(e.tag,{key:t,...Ln(e,n,r),...o},($n(e,n).children||[]).map((s,i)=>Nt(s,`${t}-${e.tag}-${i}`,n,void 0,r)))}function Ln(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 $n(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 Fn(){return Math.random().toString(36).substring(2,8)}ye.displayName="UniverIcon";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:"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"}}]},Dt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"check-mark-icon",ref:n,icon:Wn}))});Dt.displayName="CheckMarkIcon";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:"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"}}]},kt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"close-icon",ref:n,icon:Un}))});kt.displayName="CloseIcon";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.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=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"delete-icon",ref:n,icon:Vn}))});xt.displayName="DeleteIcon";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:"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"}}]},wt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"increase-icon",ref:n,icon:Bn}))});wt.displayName="IncreaseIcon";const Hn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"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"}}]},At=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"more-icon",ref:n,icon:Hn}))});At.displayName="MoreIcon";const Kn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"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"}}]},Pt=I.forwardRef(function(t,n){return I.createElement(ye,Object.assign({},t,{id:"select-range-icon",ref:n,icon:Kn}))});Pt.displayName="SelectRangeIcon";function jn(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(de.IDescriptionService),m=l.useDependency(a.LocaleService),C=l.useDependency(l.ISidebarService),E=l.useObservable(C.sidebarOptions$),T=An(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(()=>{k(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)},k=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"&&k(c)}const $=O=>{d(O)},x=()=>{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:x,onClick:()=>k(A),children:[S===A&&y.jsx(Dt,{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(Ot,{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 qn(){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:K.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(jn,{onChange:i}),o&&y.jsx(Pn,{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 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: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 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:We.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]:{[Ve.id]:{order:0,menuItemFactory:Qn}},[D.PASTE_SPECIAL_MENU_ID]:{[We.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 Ye=[l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP,l.KeyCode.ARROW_LEFT,l.KeyCode.ARROW_RIGHT],or=[...Ye,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:K.DeviceInputEventType.Keyboard,keycode:t}});return e}function ir(){const e=[];for(const t of Ye)e.push({id:Ie.id,binding:t|l.MetaKeys.SHIFT,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.SHIFT}});return e}function cr(){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:K.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.CTRL_COMMAND}});return e}function ar(){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:K.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:K.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}const dr={id:de.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,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(tr)}_registerCommands(){[We,ce,Ve,It,pt,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(wn,this._injector))),this._componentManager.register(_t,qn)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,[je]))}};ze=hr([Re(0,a.Inject(a.Injector)),Re(1,l.IMenuManagerService),Re(2,a.ICommandService),Re(3,l.IShortcutService),Re(4,l.IUIPartsService),Re(5,K.IRenderManagerService),Re(6,a.Inject(l.ComponentManager))],ze);var gr=Object.getOwnPropertyDescriptor,Sr=(e,t,n,o)=>{for(var r=o>1?void 0:o?gr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},at=(e,t)=>(n,o)=>t(n,o,e);let Ge=class extends a.Disposable{constructor(e,t,n){super(),this._imageFormulaCellInterceptorController=e,this._renderManagerService=t,this._univerInstanceService=n,this._imageFormulaCellInterceptorController.registerRefreshRenderFunction(()=>{const o=this._univerInstanceService.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;const r=this._renderManagerService.getRenderById(o.getUnitId());if(!r)return;r.with(D.SheetSkeletonManagerService).reCalculate();const s=r.mainComponent;s&&s.makeDirty()})}};Ge=Sr([at(0,a.Inject(de.ImageFormulaCellInterceptorController)),at(1,K.IRenderManagerService),at(2,a.IUniverInstanceService)],Ge);class lt{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 pr=Object.getOwnPropertyDescriptor,vr=(e,t,n,o)=>{for(var r=o>1?void 0:o?pr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},ke=(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(mr(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),K.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),K.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(K.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(K.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=K.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(K.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!S)return;const h=d.getCoordRelativeToViewport(K.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 k=this.getSelectionControls();for(const x of k){if(n.button===2&&a.Rectangle.contains(x.model,v)){M=x;return}if(x.model.isEqual(v)){M=x;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 x=0;x<this.getSelectionControls().length-1;x++)this.getSelectionControls()[x].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 x;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(x=this._escapeShortcutDisposable)==null||x.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=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 mr(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 ut=(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},Lt=(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},Cr=(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 $t(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:[]]),Cr(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},_r=(e,t,n)=>{const o=l.useDependency(Ue),r=l.useDependency(de.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 k=r.getFunctionInfo(v.token);c(k),g(-1);return}else{const k=s.getFunctionAndParameter(`${f.current}A`,T-1);if(k){const{functionName:W,paramIndex:U}=k,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}},Ir=({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:"?"}),dt=({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})]}),Er=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:Mt(s)}),i===n.length-1?"":","]},s.name)),")"]})},Ft=()=>{};function yr(e){const{onParamsSwitch:t=Ft,onClose:n=Ft,isFocus:o,editor:r,formulaText:s}=e,{functionInfo:i,paramIndex:c,reset:d}=_r(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]=$t(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(Ir,{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(Er,{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(At,{})}),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(kt,{})})]})]}),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(dt,{title:f.t("formula.prompt.helpExample"),value:`${i.functionName}(${i.functionParameter.map(v=>v.example).join(",")})`}),y.jsx(dt,{title:f.t("formula.prompt.helpAbstract"),value:i.description}),i&&i.functionParameter&&i.functionParameter.map((v,M)=>y.jsx(dt,{className:c===M?"univer-text-primary-500":"",title:v.name,value:`${v.require?u:_} ${v.detail}`},M))]})})]})},"show"):null}const Rr=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 Tr(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 br(e){var k;const{editorId:t,isFocus:n,disableOnClick:o,unitId:r,subUnitId:s}=e,i=l.useDependency(K.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(gt.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,x=Tr(h);if(!x)return;const O=(oe=x==null?void 0:x.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),j=!!V;if((O==null?void 0:O.substring(0,1))==="="&&(H||j))if(j){if(m.current)return;const{sheetName:z,unitId:ee}=V.range,xe=(ae=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:ae.getUnitId();ee&&ee!==xe?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,(k=g==null?void 0:g.mainComponent)==null?void 0:k.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 Mr=()=>{const e=l.useDependency(R.LexerTreeBuilder);return I.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function Or(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 Wt(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 k;return(k=h==null?void 0:h.getSheetBySheetName(M))==null?void 0:k.getSheetId()};if(!((T=d==null?void 0:d.getWorksheetSkeleton(_))==null?void 0:T.skeleton))return;const E=[];for(let M=0,k=r.length;M<k;M++){const W=r[M],{themeColor:U,token:w,refIndex:$,endIndex:x}=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:Or(g,U,$.toString())}),E.push(x)}if(s){const M=(v=(N=s.getSelectionRanges())==null?void 0:N[0])==null?void 0:v.startOffset,k=E.findIndex(W=>W+2===M);k!==-1?c==null||c.setActiveSelectionIndex(k):c==null||c.resetActiveSelectionIndex()}return u}function Nr(e,t){const n=l.useDependency(a.IUniverInstanceService),o=l.useDependency(a.ThemeService),r=l.useDependency(L.IRefSelectionsService),s=l.useDependency(K.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=Wt({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 Ut(e=""){const t=l.useDependency(de.IDescriptionService),n=Dr(),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}=kr(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 Dr(){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 kr(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 xr=(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===fe.NEED_ADD||i.current===fe.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===fe.NEED_ADD||i.current===fe.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:K.DeviceInputEventType.Keyboard,keyCode:u,metaKey:_}})).forEach(u=>{p.add(s.registerShortcut(u))}),()=>{p.dispose()}},[r,n,e,s])},wr=(e,t,n,o,r=!0)=>{var f;const s=l.useDependency(K.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])},Ar=(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])},Pr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),ft=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)),Lr=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=ut(c,s,!1),g=Lt(c,d);return{nodeIndex:d,updatingRefIndex:g,sequenceNodes:c,offset:s}},$r=(()=>{}),Fr=(e,t,n,o,r,s,i,c,d,g=$r)=>{var $;const p=l.useDependency(K.IRenderManagerService),S=l.useDependency(a.IUniverInstanceService),h=l.useDependency(a.ICommandService),f=l.useDependency(gt.DocSelectionManagerService),u=l.useDependency(a.ThemeService),_=l.useDependency(R.LexerTreeBuilder),m=S.getUnit(o),C=l.useEvent((x,O)=>{var A,b,P;return(P=(b=(A=S.getUnit(x))==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?$:""),k=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((x,O)=>{var j,oe,se,ae,z,ee,xe,we,Qe,he;const A=Lr({editor:d,lexerTreeBuilder:_});if(!A)return;const{nodeIndex:b,updatingRefIndex:P,sequenceNodes:V,offset:H}=A;if(n.current===fe.NEED_ADD)if(H!==0){if(b===-1&&V.length)return;const G=x[x.length-1],Q=V.splice(b+1),ge=(j=G.sheetId)!=null?j:r,le={range:G,unitId:(oe=G.unitId)!=null?oe:v.getUnitId(),sheetName:C((se=G.unitId)!=null?se:v.getUnitId(),ge)},te=ge!==r,ie=(v==null?void 0:v.getUnitId())!==o,Se=Ze([le],i&&(te||ie),E,ie);V.push({token:Se[0],nodeType:R.sequenceNodeType.REFERENCE});const be=[...V,...Q],me=ft(be);g(me,Pr(V),O)}else{const G=x[x.length-1],Q=(ae=G.sheetId)!=null?ae:r,ge={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=Ze([ge],i&&(le||te),E,te);V.unshift({token:ie[0],nodeType:R.sequenceNodeType.REFERENCE});const Se=ft(V);g(Se,ie[0].length,O)}else if(n.current===fe.EDIT_OTHER_SHEET_REFERENCE||n.current===fe.EDIT_OTHER_WORKBOOK_REFERENCE){const G=x.pop();if(!G)return;const Q=V[b];if(typeof Q=="object"&&Q.nodeType===R.sequenceNodeType.REFERENCE){const ge=Q.token;(v==null?void 0:v.getUnitId())!==o?Q.token=R.serializeRangeWithSpreadsheet((xe=v==null?void 0:v.getUnitId())!=null?xe:"",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-ge.length);g(R.generateStringWithSequence(V),te,O)}}else{const G=[...x];if(P!==-1){const Z=G.pop();Z&&G.splice(P,0,Z)}let Q=0;const ge=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 pe=(Ae=ne.sheetId)!=null?Ae:r,Je={range:ne,unitId:(Me=ne.unitId)!=null?Me:v.getUnitId(),sheetName:C((Oe=ne.unitId)!=null?Oe:v.getUnitId(),pe)},et=(v==null?void 0:v.getUnitId())!==o;return Ze([Je],i&&(pe!==r||et),E,et)[0]}return Z.token});let le="",te;ge.forEach((Z,ue)=>{le+=Z,ue===b&&(te=le.length)});const ie=[];for(let Z=Q;Z<=x.length-1;Z++){const ue=x[Z],Ae=(we=ue.sheetId)!=null?we:r,Me={range:ue,unitId:(Qe=ue.unitId)!=null?Qe:v.getUnitId(),sheetName:C((he=ue.unitId)!=null?he:v.getUnitId(),Ae)},Oe=(v==null?void 0:v.getUnitId())!==o,ne=Ze([Me],i&&(Ae!==r||Oe),E,Oe);ie.push(ne[0])}const Se=V[V.length-1],be=Se&&(typeof Se=="string"?!1:Se.nodeType===R.sequenceNodeType.REFERENCE),me=`${le}${ie.length&&be?",":""}${ie.join(",")}`;g(me,!ie.length&&te?te:me.length,O)}});I.useEffect(()=>{if(k&&e){let x=!0;const O=(b,P)=>{if(x){x=!1;return}w(b.map(V=>V.rangeWithCoord),P)},A=new a.DisposableCollection;return A.add(k.selectionMoving$.subscribe(b=>{O(b,!1)})),A.add(k.selectionMoveEnd$.subscribe(b=>{O(b,!0)})),()=>{A.dispose()}}},[e,w,k]),I.useEffect(()=>{if(t&&k&&d){const x=new a.DisposableCollection,O=()=>{x.dispose(),k.getSelectionControls().forEach((P,V)=>{x.add(P.selectionScaling$.subscribe(H=>{const j=k.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=j[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,j[V]=H,w(j,!1)})),x.add(P.selectionMoving$.subscribe(H=>{const j=k.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=j[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,j[V]=H,w(j,!0)}))})},A=q.merge(d.input$,U.selectionSet$,k.selectionMoveEnd$).pipe(Jt.debounceTime(50)).subscribe(()=>{O()});return()=>{A.unsubscribe(),x.dispose()}}},[d,t,w,k,U.selectionSet$]),k==null||k.getSelectionDataWithStyle(),I.useEffect(()=>{if(c){const x=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===fe.NEED_ADD,H=((b=k==null?void 0:k.getSelectionDataWithStyle())!=null?b:[]).map(j=>j.rangeWithCoord);V?H.push(P.range):H[H.length-1]=P.range,w(H,!0)}}});return()=>{x.dispose()}}},[h,d,n,_,c,w,k]),I.useEffect(()=>{if(!d)return;const x=f.textSelection$.subscribe(O=>{O.unitId===d.getEditorId()&&Wt({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:U,refSelectionsRenderService:k,sheetSkeletonManagerService:W,themeService:u,univerInstanceService:S,currentWorkbook:v})});return()=>x.unsubscribe()},[f.textSelection$,d,s,k,U,W,r,u,o,S])},Wr=(e,t,n,o,r,s)=>{const i=l.useDependency(a.ICommandService),c=l.useDependency(J.IEditorService),g=l.useDependency(K.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])},Ur=(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])},Vr=(e,t=[],n)=>{const o=l.useDependency(de.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=ut(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:ft([...u,..._]),offset:C}}},reset:p}},Br=()=>{},Hr=I.forwardRef(Kr);function Kr(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:s,onClose:i=Br}=e,c=s.getEditorId(),d=l.useDependency(l.IShortcutService),g=l.useDependency(a.ICommandService),{searchList:p,searchText:S,handlerFormulaReplace:h,reset:f}=Vr(n,o,s),u=I.useMemo(()=>!!p.length,[p]),_=I.useRef(void 0),[m,C]=I.useState(0),E=I.useRef(!1),[T]=$t(c,u,[S,p]),N=Te({searchList:p,active:m}),v=(w,$)=>{const x=h(w,$);x&&(f(),r(x))};function M(w){E.current&&C(w)}function k(){E.current&&C(-1)}I.useEffect(()=>{if(!p.length)return;const w=`sheet.formula-embedding-editor.search_function.${c}`,$=new a.DisposableCollection,x=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;x(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:K.DeviceInputEventType.Keyboard,keyCode:O}})).forEach(O=>{$.add(d.registerShortcut(O))}),()=>{$.dispose()}},[p]);function W(w){const $=_.current;if(!$)return;const x=$.children[w];if(!x)return;const A=$.getBoundingClientRect().top,b=$.offsetHeight,P=x.getBoundingClientRect(),V=P.top,H=P.height;if(V>=0&&V>A&&V-A+H<=b)return;const j=x.offsetTop-(b-H)/2;$.scrollTo({top:j,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:k,onMouseMove:U,onClick:()=>{v(w.name,w.functionType),s&&s.focus()},children:[y.jsxs("span",{className:"univer-block univer-truncate univer-text-xs",children:[y.jsx("span",{className:"univer-text-red-500",children: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 jr=e=>e.startsWith(R.operatorToken.EQUALS)?e.slice(1):"",Vt=()=>{},Bt=I.forwardRef((e,t)=>{var Yt,zt,Gt,Zt;const{errorText:n,initValue:o,unitId:r,subUnitId:s,isFocus:i=!0,isSupportAcrossSheet:c=!1,onFocus:d=Vt,onBlur:g=Vt,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:k,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 x=l.useEvent(_),O=I.useRef(null),A=I.useRef(void 0),b=A.current,[P,V]=I.useState(i),H=I.useRef(null),j=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(j);l.useObservable(ae==null?void 0:ae.change$);const z=Mr(),ee=a.BuildTextUtils.transform.getPlainText((zt=(Yt=ae==null?void 0:ae.getBody())==null?void 0:Yt.dataStream)!=null?zt:""),xe=Te(ee),we=I.useMemo(()=>jr(ee),[ee]),Qe=I.useMemo(()=>z(we),[we,z]),{isSelecting:he,isSelectingRef:G}=br({unitId:r,subUnitId:s,editorId:j,isFocus:P,disableOnClick:v}),Q=I.useRef(""),le=l.useDependency(K.IRenderManagerService).getRenderById(j),te=le==null?void 0:le.with(J.DocSelectionRenderService),ie=te==null?void 0:te.isFocusing,Se=I.useMemo(()=>se.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[se]),be=l.useObservable(Se),me=(be==null?void 0:be.getUnitId())===j,Z=I.useRef([]),ue=he,Me=(Zt=(Gt=l.useDependency(a.IConfigService).getConfig(Et))==null?void 0:Gt.functionScreenTips)!=null?Zt:!0;l.useUpdateEffect(()=>{$(ee)},[ee,$]);const Oe=Ut("="),Ne=Nr(r,s),ne=l.useEvent((X,re=!0,Ce,ve)=>{if(!A.current)return;Q.current=X;const tt=X[0]==="="?X.slice(1):"",_e=z(tt),oo=_e.reduce((De,rt)=>typeof rt=="object"?`${De}${rt.token}`:`${De}${rt}`,""),nt=Oe(A.current,oo===tt?_e:[],re,ve);if(Z.current=nt,Ce){const De=ve!=null?ve:b==null?void 0:b.getSelectionRanges();if((De==null?void 0:De.length)!==1)return;const so=De[0].startOffset-1,io=ut(_e,so,!1),Xt=Lt(_e,io);if(Xt>=0){const Qt=nt.splice(Xt,1)[0];Qt&&nt.push(Qt)}Ne(P?nt:[],A.current)}});I.useEffect(()=>{P&&ne(ee,!1,!0)},[P]),I.useEffect(()=>{if(P){if(Q.current===ee)return;ne(ee,!1,!0)}},[ee]),Ur(P,S,ee);const pe=Rr(b),Je=Ar(P,r,s);I.useEffect(()=>{var X;x(he,(X=te==null?void 0:te.isFocusing)!=null?X:!0)},[x,he]),J.useKeyboardEvent(P,m,b),I.useLayoutEffect(()=>{let X;if(H.current){X=U.register({autofocus:M,editorUnitId:j,initialSnapshot:{id:j,body:{dataStream:`${o}\r
5
- `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},H.current);const re=U.getEditor(j);A.current=re,ne(o,!1,!0)}return()=>{X==null||X.dispose()}},[]),I.useLayoutEffect(()=>{i?(V(i),pe()):(E&&(b==null||b.blur(),Je()),V(i))},[i,b,pe,Je,E]);const{checkScrollBar:et}=J.useResize(b,N,T);wr(P,!!(he&&me),r,j,k),xr(!!(P&&ie&&u),ue,b,C);const jt=l.useEvent((X,re,Ce)=>{if(!ie)return;const ve=re!==-1?[{startOffset:re+1,endOffset:re+1,collapsed:!0}]:void 0;ne(`=${X}`,!0,Ce,ve),Ce&&(pe(),re!==-1&&setTimeout(()=>{const tt={startOffset:re+1,endOffset:re+1},_e=b==null?void 0:b.render.with(J.DocBackScrollRenderController);_e==null||_e.scrollToRange({...tt,collapsed:!0})},50),et())});Fr(P&&!!(he&&me),P,G,r,s,Z,c,!!ue,b,jt),Wr(P&&!!(he&&me),r,c,V,g,()=>{ne(xe.current,!1,!0)});const qt=X=>{if(X){const re=b==null?void 0:b.getSelectionRanges();if(re&&re.length===1){const Ce=re[0];if(Ce.collapsed){const ve=X.offset;setTimeout(()=>{b==null||b.setSelectionRanges([{startOffset:Ce.startOffset-ve,endOffset:Ce.endOffset-ve}])},30)}}pe(),ne(`=${X.text}`)}},ro=()=>{V(!0),d(),pe()};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:ro})}),n!==void 0&&y.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),Me&&b&&we!==""&&y.jsx(yr,{editor:b,isFocus:P,formulaText:ee,onClose:()=>pe()}),Me&&!!b&&y.jsx(Hr,{isFocus:P,sequenceNodes:Qe,onSelect:qt,ref:O,editor:b})]})});function qr(e,t,n,o){const r=l.useDependency(R.LexerTreeBuilder),s=Ut(""),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 Yr(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 Ht=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}),zr=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 Gr(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 k=[...f];k[v]=M,u(k)},T=()=>{u([...f,""]),m(f.length)},N=v=>{f.splice(v,1),u([...f])};return Yr({unitId:o,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(v,M)=>{if(!t&&p!=null&&p(v))return;const k=new Set(f),W=v.map($=>$.sheetName?R.serializeRangeWithSheet($.sheetName,$.range):R.serializeRange($.range)),U=W.filter($=>!k.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 x;(x=C.current)==null||x.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:zr(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:k=>E(M,k)}),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:T,children:[y.jsx(wt,{}),y.jsx("span",{children:S.t("rangeSelector.addAnotherRange")})]})})]})})}function Zr(e){return e.split(R.matchToken.COMMA).filter(t=>!!t).map(t=>R.deserializeRangeWithSheet(t))}function Xr(e){return e.map(t=>t.sheetName?R.serializeRangeWithSheet(t.sheetName,t.range):R.serializeRange(t.range)).join(R.matchToken.COMMA)}function ht(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,k]=I.useState([]),W=l.useDependency(a.LocaleService),U=l.useDependency(J.IEditorService),{sequenceNodes:w}=qr(t,E,s,i),$=Te(w),x=l.useDependency(a.ICommandService),O=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),U.blur()}),A=l.useEvent(()=>{var b;O(),k(Zr((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:()=>Ht($.current),showDialog:b=>{O(),k(b),v(!0)},hideDialog:()=>{k([]),v(!1)},getValue:()=>{var b;return(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:""}})},[O,t,U,r,$]),I.useEffect(()=>{var b;o==null||o(Ht(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};x.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(Pt,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:A})})}),y.jsx(Gr,{initialValue:M,unitId:s,subUnitId:i,visible:N,maxRangeCount:c,onConfirm:b=>{const P=Xr(b),V=a.RichTextBuilder.newEmptyData();V.body.dataStream=P,t==null||t.replaceText(P,!1),S==null||S(V,P),v(!1),k([]),requestAnimationFrame(()=>{O()})},onClose:()=>{v(!1),k([])},supportAcrossSheet:d,keepSheetReference:g,onShowBySelection:b=>E||_?(k(b),v(!0),!1):!0})]})}const Qr=()=>{var o,r;const e=l.useDependency(lt),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(ht,{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 Jr=Object.defineProperty,eo=Object.getOwnPropertyDescriptor,to=(e,t,n)=>t in e?Jr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,no=(e,t,n,o)=>{for(var r=o>1?void 0:o?eo(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),Kt=(e,t,n)=>to(e,typeof t!="symbol"?t+"":t,n);F.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=yt,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(yt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(Et,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[Ue,{useClass:ot}],[lt],[ze],[He],[Ke],[je],[qe],[F.FormulaReorderController],[Ge]]),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,[[ze],[Ke],[qe],[Ge]])}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,ht)),this.disposeWithMe(t.register(D.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Bt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(Qr,this._injector)))}},Kt(F.UniverSheetsFormulaUIPlugin,"pluginName",Ct),Kt(F.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET),F.UniverSheetsFormulaUIPlugin=no([a.DependentOn(R.UniverFormulaEnginePlugin,de.UniverSheetsFormulaPlugin),Xe(1,a.Inject(a.Injector)),Xe(2,K.IRenderManagerService),Xe(3,a.IConfigService),Xe(4,l.IUIPartsService)],F.UniverSheetsFormulaUIPlugin),F.FORMULA_PROMPT_ACTIVATED=St,F.FormulaEditor=Bt,F.GlobalRangeSelectorService=lt,F.HelpFunctionOperation=pt,F.InsertFunctionOperation=ce,F.MoreFunctionsOperation=Ve,F.RangeSelector=ht,F.ReferenceAbsoluteOperation=st,F.SearchFunctionOperation=It,F.SelectEditorFormulaOperation=Ie,F.SheetOnlyPasteFormulaCommand=We,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,K,L,de,l,y,_,B,gt,Jt){"use strict";var co=Object.defineProperty;var ao=(F,a,D)=>a in F?co(F,a,{enumerable:!0,configurable:!0,writable:!0,value:D}):F[a]=D;var Y=(F,a,D)=>ao(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})},_e={id:"formula-ui.operation.select-editor-formula",type:a.CommandType.OPERATION,handler:(e,t)=>!0};var en=Object.getOwnPropertyDescriptor,tn=(e,t,n,o)=>{for(var r=o>1?void 0:o?en(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},nn=(e,t)=>(n,o)=>t(n,o,e);const St="FORMULA_PROMPT_ACTIVATED",Ue=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(St,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}};ot=tn([nn(0,a.IContextService)],ot);const pt={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 f=[],h=[];let u=null,m=0,C=0,I="";if(r.length===1&&(sn(r[0].range)||cn(r[0].range)&&mt(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,C=x;const W=vt(g,M,x);W&&(I=R.serializeRange(W))}else r.some(N=>{var x,W;const{range:v,primary:M}=N;if(mt(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,$=vt(g,U,w);if(!$)return u=v,m=U,C=w,!0;const k=R.serializeRange($),O=`=${p}(${k})`;f.push({range:v,primary:{row:U,column:w},formula:O})}else{const{startRow:U,startColumn:w,endRow:$,endColumn:k}=v;if(U===$){const O=an(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})`;h.push({range:v,primary:{row:U,column:O},formula:P})}else{let O=-1;for(let b=w;b<=k;b++){const P=ln(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})`;h.push({range:v,primary:{row:O,column:b},formula:V})}}}return!1});if(u){const N=L.getCellAtRowCol(m,C,i),v={range:a.Rectangle.clone(u),primary:{startRow:N.startRow,startColumn:N.startColumn,endRow:N.endRow,endColumn:N.endColumn,actualRow:m,actualColumn:C,isMerged:N.isMerged,isMergedMainCell:N.startRow===m&&N.startColumn===C}},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:K.DeviceInputEventType.Dblclick});const U=`=${p}(${I}`;x==null||x.replaceText(U),W==null||W.replaceText(U,!1)}return f.length===0&&h.length===0?!1:S.executeCommand(de.InsertFunctionCommand.id,{list:f,listOfRangeHasNumber:h})}};function vt(e,t,n){const o=rn(e,t,n);if(o!==t)return{startRow:o,endRow:t-1,startColumn:n,endColumn:n};const r=on(e,t,n);return r!==n?{startRow:t,endRow:t,startColumn:r,endColumn:n-1}:null}function rn(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 on(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 sn(e){return e.startRow===e.endRow&&e.startColumn===e.endColumn}function cn(e){return e.startRow!==e.endRow&&e.startColumn!==e.endColumn}function mt(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 an(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(t,r))return r;return o}function ln(e,t,n,o){for(let r=n;r<=o;r++)if(!e.getValue(r,t))return r;return o}const Ct="SHEET_FORMULA_UI_PLUGIN",It=`${Ct}_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:It}}),!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(Ue).search(t),!0)};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},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,f=new a.ObjectMatrix;let h=!1;return a.Range.foreach(i,(u,m)=>{let C=u;c.hasOwnProperty(u)&&(C=c[u]);const I=p.getValue(C,m);if(I!=null&&I.f||I!=null&&I.si){h=!0;const E=this._formulaDataModel.getFormulaStringByCell(C,m,s,r),T=this._lexerTreeBuilder.moveFormulaRefOffset(E,0,u-C),N=a.Tools.deepClone(I);N.f=T,N.si=null,S.setValue(u,m,N)}else S.setValue(u,m,I);f.setValue(u,m,p.getValue(u,m))}),h?(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:f.getMatrix()}}),{redos:n,undos:o}):{redos:n,undos:o}}},F.FormulaReorderController=dn([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 Et="sheets-formula-ui.base.config",yt={};var fn=Object.getOwnPropertyDescriptor,hn=(e,t,n,o)=>{for(var r=o>1?void 0:o?fn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},Le=(e,t)=>(n,o)=>t(n,o,e);const it="SHEET_FORMULA_ALERT",gn={[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 c=this._context.unit.getActiveSheet();if(!c)return this._hideAlert();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(it),f=(s=S==null?void 0:S.alert)==null?void 0:s.location;if(f&&f.row===e.location.row&&f.col===e.location.col&&f.subUnitId===e.location.subUnitId&&f.unitId===e.location.unitId){this._hideAlert();return}this._cellAlertManagerService.showAlert({type:D.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${gn[p]}`),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=hn([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)],ct);var Sn=Object.getOwnPropertyDescriptor,pn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Sn(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);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=mn(r),c=[],d=new Map;for(let S=1;S<=t;S++){const f=(S-1)%e.length,h=o[f],u=a.Tools.deepClone(e[f]);if(u){const m=((g=e[f])==null?void 0:g.f)||"",C=((p=e[f])==null?void 0:p.si)||"",I=a.isFormulaString(m);if(a.isFormulaId(C))u.si=C,u.f=null,u.v=null,u.p=null,u.t=null,c.push(u);else if(I){let T=d.get(f);if(T)u.si=T,u.f=null,u.v=null,u.p=null,u.t=null;else{T=a.generateRandomId(6),d.set(f,T);const{offsetX:N,offsetY:v}=vn(i,t,n,s,h),M=this._lexerTreeBuilder.moveFormulaRefOffset(m,N,v);u.si=T,u.f=M,u.v=null,u.p=null,u.t=null}c.push(u)}}}return c}};He=pn([Rt(0,D.IAutoFillService),Rt(1,a.Inject(R.LexerTreeBuilder))],He);function vn(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 mn(e){let t=0;for(const n in e)e[n].forEach(o=>{t+=o.data.length});return t}var Cn=Object.getOwnPropertyDescriptor,In=(e,t,n,o)=>{for(var r=o>1?void 0:o?Cn(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 _n="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:_n,priority:10,onPasteCells:(e,t,n,o)=>this._onPasteCells(e,t,n,o,!1)}}_onPasteCells(e,t,n,o,r){var f;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||((f=i.getActiveSheet())==null?void 0:f.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(h=>En(c,d,g,p,h,S,this._lexerTreeBuilder,this._formulaDataModel,r,e))}};Ke=In([$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 En(e,t,n,o,r,s,i,c,d=!1,g){const p=[],S=[],f=yn(e,t,n,o,s,i,c,g);if(!f.hasValue())return{undos:[],redos:[]};const h={unitId:e,subUnitId:t,cellValue:f.getData()};p.push({id:L.SetRangeValuesMutation.id,params:h});const u=L.SetRangeValuesUndoMutationFactory(r,h);return S.push({id:L.SetRangeValuesMutation.id,params:u}),{undos:S,redos:p}}function yn(e,t,n,o,r,s,i,c){return c?r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?Tn(e,t,n,o,i,c):r.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?bn(e,t,n,o,s,i,c):Mn(e,t,n,o,r.copyType,s,i,c):Rn(e,t,n,o,i)}function Rn(e,t,n,o,r){const s=new a.ObjectMatrix,i=r.getSheetFormulaData(e,t);return o.forValue((c,d,g)=>{var h;const p=n.rows[c],S=n.cols[d],f={};a.isFormulaString(g.v)?(f.v=null,f.f=`${g.v}`,f.si=null,f.p=null,s.setValue(p,S,f)):(h=i==null?void 0:i[p])!=null&&h[S]&&(f.v=g.v,f.f=null,f.si=null,f.p=null,s.setValue(p,S,f))}),s}function Tn(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,f,h)=>{var T,N;const u=s.range.rows[S%s.range.rows.length],m=s.range.cols[f%s.range.cols.length],C=n.rows[S],I=n.cols[f],E={};if(a.isFormulaString(h.f)||a.isFormulaId(h.si))E.v=h.v,E.f=null,E.si=null,E.p=null,i.setValue(C,I,E);else if((T=c==null?void 0:c[u])!=null&&T[m]){const v=c[u][m];E.v=v.v,E.f=null,E.si=null,E.p=null,i.setValue(C,I,E)}else if((N=d==null?void 0:d[C])!=null&&N[I]){if(E.v=h.v,E.f=null,E.si=null,E.p=null,h.p){const v=Tt(h);v&&(E.v=v)}i.setValue(C,I,E)}}),i}function bn(e,t,n,o,r,s,i){const c=new a.ObjectMatrix,d=new Map;return o.forValue((g,p,S)=>{const f=n.rows[g],h=n.cols[p],u={};if(a.isFormulaId(S.si)){if(i.unitId!==e||i.subUnitId!==t){const m=s.getFormulaStringByCell(i.range.rows[g%i.range.rows.length],i.range.cols[p%i.range.cols.length],i.subUnitId,i.unitId),C=n.cols[p]-i.range.cols[p%i.range.cols.length],I=n.rows[g]-i.range.rows[g%i.range.rows.length],E=r.moveFormulaRefOffset(m||"",C,I);u.si=null,u.f=E}else u.si=S.si,u.f=null;u.v=null,u.p=null,c.setValue(f,h,u)}else if(a.isFormulaString(S.f)){const m=`${g%i.range.rows.length}_${p%i.range.cols.length}`;let C=d.get(m);if(C)u.si=C,u.f=null;else{C=a.generateRandomId(6),d.set(m,C);const I=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||"",I,E);u.si=C,u.f=T}u.v=null,u.p=null,c.setValue(f,h,u)}else{if(u.v=S.v,u.f=null,u.si=null,u.p=null,S.p){const m=Tt(S);m&&(u.v=m)}c.setValue(f,h,u)}}),c}function Mn(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((f,h,u)=>{const m=n.rows[f],C=n.cols[h],I={};if(a.isFormulaId(u.si)){if(a.isFormulaString(u.f))S.push(u.si),I.f=u.f,I.si=u.si;else if(S.includes(u.si))I.f=null,I.si=u.si;else{const E=i.getFormulaStringByCell(c.range.rows[f%c.range.rows.length],c.range.cols[h%c.range.cols.length],c.subUnitId,c.unitId);I.f=E,I.si=null}I.v=null,I.p=null,d.setValue(m,C,I)}else a.isFormulaString(u.f)&&(I.f=u.f,I.si=null,I.v=null,I.p=null,d.setValue(m,C,I))}):o.forValue((f,h,u)=>{var E;const m=n.rows[f],C=n.cols[h],I={};if(a.isFormulaId(u.si)){if(c.unitId!==e||c.subUnitId!==t){const T=i.getFormulaStringByCell(c.range.rows[f%c.range.rows.length],c.range.cols[h%c.range.cols.length],c.subUnitId,c.unitId),N=n.cols[h]-c.range.cols[h%c.range.cols.length],v=n.rows[f]-c.range.rows[f%c.range.rows.length],M=s.moveFormulaRefOffset(T||"",N,v);I.si=null,I.f=M}else I.si=u.si,I.f=null;I.v=null,I.p=null,d.setValue(m,C,I)}else if(a.isFormulaString(u.f)){const T=`${f%c.range.rows.length}_${h%c.range.cols.length}`;let N=g.get(T);if(N)I.si=N,I.f=null;else{N=a.generateRandomId(6),g.set(T,N);const v=n.cols[h]-c.range.cols[h%c.range.cols.length],M=n.rows[f]-c.range.rows[f%c.range.rows.length],x=s.moveFormulaRefOffset(u.f||"",v,M);I.si=N,I.f=x}I.v=null,I.p=null,d.setValue(m,C,I)}else(E=p==null?void 0:p[m])!=null&&E[C]&&(I.v=u.v,I.f=null,I.si=null,I.p=u.p,d.setValue(m,C,I))}),S.length>0&&new a.ObjectMatrix(p).forValue((f,h,u)=>{if(!(c.range.rows.includes(f)&&c.range.cols.includes(h))&&!(n.rows.includes(f)&&n.cols.includes(h))&&S.includes(u==null?void 0:u.si)){const m=i.getFormulaStringByCell(f,h,c.subUnitId,c.unitId);d.setValue(f,h,{f:m,si:null,v:null,p:null})}}),d}function Tt(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 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},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,I;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 f=this._formulaDataModel.getFormulaStringByCell(r,s,c,i);if(f!==null&&(S={f}),t.v!=null&&t.v!==""&&((C=(m=(u=p[i])==null?void 0:u[c])==null?void 0:m[r])==null?void 0:C[s])==null)return S?{...t,...S}:o(t);const h=(I=g==null?void 0:g[i])==null?void 0:I[c];return h!=null&&(S=this._displayArrayFormulaRangeShape(h,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){return new a.ObjectMatrix(t).forValue((d,g,p)=>{if(p==null)return!0;const{startRow:S,startColumn:f,endRow:h,endColumn:u}=p;if(d===n&&g===o)return this._createArrayFormulaRangeShape(p,r),!1;if(n>=S&&n<=h&&o>=f&&o<=u){const m=i.getCell(S,f);return(m==null?void 0:m.v)===R.ErrorType.SPILL||(m==null?void 0:m.f)==null?void 0:(c==null&&(c={f:m.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(p,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=Nn([Ee(1,a.Inject(L.SheetInterceptorService)),Ee(2,a.Inject(R.FormulaDataModel)),Ee(3,a.Inject(a.ThemeService)),Ee(4,K.IRenderManagerService),Ee(5,a.Inject(D.SheetSkeletonManagerService)),Ee(6,a.ICommandService),Ee(7,a.ILogService)],je);var Dn=Object.getOwnPropertyDescriptor,xn=(e,t,n,o)=>{for(var r=o>1?void 0:o?Dn(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},bt=(e,t)=>(n,o)=>t(n,o,e);const kn={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,...kn}),r(n)},priority:10}))}};qe=xn([bt(0,a.Inject(L.SheetInterceptorService)),bt(1,a.Inject(R.FormulaDataModel))],qe);function wn(){const e=l.useDependency(de.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 An(e,t){return Object.keys(e).filter(n=>isNaN(Number(n))&&n!=="DefinedName"&&n!=="Table").map(n=>({label:t.t(`formula.functionType.${n.toLocaleLowerCase()}`),value:`${e[n]}`}))}function Mt(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 Ot(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:Mt(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 Pn(e){const{functionInfo:t,onChange:n}=e;if(!t)return null;const[o,r]=_.useState([]),[s,i]=_.useState(t.functionParameter),[c,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,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(Ot,{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=_.useRef(`_${Fn()}`);return Nt(n,`${o}`,{defIds:n.defIds,idSuffix:d.current},{ref:e,className:c,...i},s)}function Nt(e,t,n,o,r){return _.createElement(e.tag,{key:t,...Ln(e,n,r),...o},($n(e,n).children||[]).map((s,i)=>Nt(s,`${t}-${e.tag}-${i}`,n,void 0,r)))}function Ln(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 $n(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 Fn(){return Math.random().toString(36).substring(2,8)}ye.displayName="UniverIcon";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:"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"}}]},Dt=_.forwardRef(function(t,n){return _.createElement(ye,Object.assign({},t,{id:"check-mark-icon",ref:n,icon:Wn}))});Dt.displayName="CheckMarkIcon";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:"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"}}]},xt=_.forwardRef(function(t,n){return _.createElement(ye,Object.assign({},t,{id:"close-icon",ref:n,icon:Un}))});xt.displayName="CloseIcon";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.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"}}]},kt=_.forwardRef(function(t,n){return _.createElement(ye,Object.assign({},t,{id:"delete-icon",ref:n,icon:Vn}))});kt.displayName="DeleteIcon";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:"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"}}]},wt=_.forwardRef(function(t,n){return _.createElement(ye,Object.assign({},t,{id:"increase-icon",ref:n,icon:Bn}))});wt.displayName="IncreaseIcon";const Hn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"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"}}]},At=_.forwardRef(function(t,n){return _.createElement(ye,Object.assign({},t,{id:"more-icon",ref:n,icon:Hn}))});At.displayName="MoreIcon";const Kn={tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"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"}}]},Pt=_.forwardRef(function(t,n){return _.createElement(ye,Object.assign({},t,{id:"select-range-icon",ref:n,icon:Kn}))});Pt.displayName="SelectRangeIcon";function jn(e){const{onChange:t}=e,n="-1",[o,r]=_.useState(""),[s,i]=_.useState([]),[c,d]=_.useState(0),[g,p]=_.useState(n),[S,f]=_.useState(0),[h,u]=_.useState(null),m=l.useDependency(de.IDescriptionService),C=l.useDependency(a.LocaleService),I=l.useDependency(l.ISidebarService),E=l.useObservable(I.sidebarOptions$),T=An(R.FunctionType,C);T.unshift({label:C.t("formula.moreFunctions.allFunctions"),value:n});const N=C.t("formula.prompt.required"),v=C.t("formula.prompt.optional");_.useEffect(()=>{W(n)},[]),_.useEffect(()=>{x(0)},[s]),_.useEffect(()=>{E!=null&&E.visible&&(r(""),i([]),d(0),p(n),f(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}f(O);const A=m.getFunctionInfo(s[O].name);if(!A){u(null);return}u(A),t(A)};function W(O){p(O);const A=m.getSearchListByType(+O);i(A)}function U(O){r(O);const A=m.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:C.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(Dt,{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))}),h&&y.jsxs("div",{className:B.clsx("univer-mx-0 univer-my-2 univer-overflow-y-auto",B.scrollbarClassName),children:[y.jsx(Fe,{title:h.functionName,value:h.description}),y.jsx(Fe,{title:C.t("formula.moreFunctions.syntax"),value:y.jsx(Ot,{prefix:h.functionName,value:h.functionParameter})}),y.jsx(Fe,{title:C.t("formula.prompt.helpExample"),value:`${h.functionName}(${h.functionParameter.map(O=>O.example).join(",")})`}),h.functionParameter&&h.functionParameter.map(O=>y.jsx(Fe,{title:O.name,value:`${O.require?N:v} ${O.detail}`},O.name))]})]})}function qn(){const e=D.useActiveWorkbook(),[t,n]=_.useState(!0),[o,r]=_.useState(!1),[s,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 f(){const h=L.getSheetCommandTarget(g);if(!h)return;p.executeCommand(D.SetCellEditVisibleOperation.id,{visible:!0,unitId:h.unitId,eventType:K.DeviceInputEventType.Dblclick});const u=d.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),m=d.getEditor(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),C=`=${s==null?void 0:s.functionName}(`;u==null||u.replaceText(C),m==null||m.replaceText(C,!1)}return y.jsxs("div",{"data-u-comp":"sheets-formula-functions-panel",className:"univer-box-border univer-flex univer-h-full univer-flex-col univer-justify-between univer-py-2",children:[t&&y.jsx(jn,{onChange:i}),o&&y.jsx(Pn,{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:f,className:"univer-mb-5 univer-ml-4 univer-mr-0 univer-mt-0",children:c.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: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 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:We.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]:{[Ve.id]:{order:0,menuItemFactory:Qn}},[D.PASTE_SPECIAL_MENU_ID]:{[We.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 Ye=[l.KeyCode.ARROW_DOWN,l.KeyCode.ARROW_UP,l.KeyCode.ARROW_LEFT,l.KeyCode.ARROW_RIGHT],or=[...Ye,l.KeyCode.ENTER,l.KeyCode.TAB,l.KeyCode.ESC];function sr(){const e=[];for(const t of or)e.push({id:_e.id,binding:t,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:t}});return e}function ir(){const e=[];for(const t of Ye)e.push({id:_e.id,binding:t|l.MetaKeys.SHIFT,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.SHIFT}});return e}function cr(){const e=[];for(const t of Ye)e.push({id:_e.id,binding:t|l.MetaKeys.CTRL_COMMAND,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:t,metaKey:l.MetaKeys.CTRL_COMMAND}});return e}function ar(){const e=[];for(const t of Ye)e.push({id:_e.id,binding:t|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:n=>D.whenFormulaEditorActivated(n),staticParameters:{eventType:K.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:_e.id,binding:t,preconditions:n=>rr(n),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:t,isSingleEditor:!0}});return e}const dr={id:de.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,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(tr)}_registerCommands(){[We,ce,Ve,_t,pt,_e,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(wn,this._injector))),this._componentManager.register(It,qn)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,[je]))}};ze=hr([Re(0,a.Inject(a.Injector)),Re(1,l.IMenuManagerService),Re(2,a.ICommandService),Re(3,l.IShortcutService),Re(4,l.IUIPartsService),Re(5,K.IRenderManagerService),Re(6,a.Inject(l.ComponentManager))],ze);var gr=Object.getOwnPropertyDescriptor,Sr=(e,t,n,o)=>{for(var r=o>1?void 0:o?gr(t,n):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(r=i(r)||r);return r},at=(e,t)=>(n,o)=>t(n,o,e);let Ge=class extends a.Disposable{constructor(e,t,n){super(),this._imageFormulaCellInterceptorController=e,this._renderManagerService=t,this._univerInstanceService=n,this._imageFormulaCellInterceptorController.registerRefreshRenderFunction(()=>{const o=this._univerInstanceService.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;const r=this._renderManagerService.getRenderById(o.getUnitId());if(!r)return;r.with(D.SheetSkeletonManagerService).reCalculate();const s=r.mainComponent;s&&s.makeDirty()})}};Ge=Sr([at(0,a.Inject(de.ImageFormulaCellInterceptorController)),at(1,K.IRenderManagerService),at(2,a.IUniverInstanceService)],Ge);class lt{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 pr=Object.getOwnPropertyDescriptor,vr=(e,t,n,o)=>{for(var r=o>1?void 0:o?pr(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(mr(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:f}=D.getCoordByOffset(g.offsetX,g.offsetY,c,S);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),f,a.RANGE_TYPE.ROW)||(this._onPointerDown(g,(s.zIndex||1)+1,a.RANGE_TYPE.ROW,this._getActiveViewport(g),K.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:f}=D.getCoordByOffset(g.offsetX,g.offsetY,c,S);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),f,a.RANGE_TYPE.COLUMN)||(this._onPointerDown(g,(s.zIndex||1)+1,a.RANGE_TYPE.COLUMN,this._getActiveViewport(g),K.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,f=D.getAllSelection(S);this._addSelectionControlByModelData(f),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const h=c.onPointerUp$.subscribeEvent(()=>{h.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(K.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(K.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=K.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(K.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!S)return;const f=d.getCoordRelativeToViewport(K.Vector2.FromArray([g,p])),{x:h,y:u}=f;this._startViewportPosX=h,this._startViewportPosY=u;const m=d.getScrollXYInfoByViewport(f),{scaleX:C,scaleY:I}=d.getAncestorScale(),E=this._skeleton.getCellByOffset(h,u,C,I,m);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,h,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=vr([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 mr(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 ut=(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},Lt=(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},Cr=(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 $t(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),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,f=d.getSkeleton();if(!f)return;const h=(T=f.getSkeletonData())==null?void 0:T.pages[0].height;let{left:u,top:m,right:C,bottom:I}=g;m=m+p,I=h?m+h:I-S;const E=r.getValue();if(!(E.left===u&&E.top===m&&E.right===C&&E.bottom===I))return r.next({left:u-1,right:C+1,top:m-1,bottom:I+1}),g});return _.useEffect(()=>{t&&c()},[e,o,i.unitAdded$,c,t,...n!=null?n:[]]),Cr(c),_.useEffect(()=>{const d=s.scrollEvent$.pipe(q.throttleTime(100)).subscribe(c);return()=>{d.unsubscribe()}},[]),[r,c]}const Te=e=>{const t=_.useRef(e);return t.current=e,t},Ir=(e,t,n)=>{const o=l.useDependency(Ue),r=l.useDependency(de.IDescriptionService),s=l.useDependency(R.LexerTreeBuilder),[i,c]=_.useState(),[d,g]=_.useState(-1),[p,S]=_.useState(!0),f=Te(p),h=_.useRef(t);h.current=t;const u=()=>{c(void 0),g(-1),S(!1)};return _.useEffect(()=>{const m=s.sequenceNodesBuilder(t.slice(1));o.setSequenceNodes(m!=null?m:[])},[t]),_.useEffect(()=>{if(n&&e){const m=n.selectionChange$.pipe(q.debounceTime(50)).subscribe(I=>{if(I.textRanges.length===1){const[E]=I.textRanges;if(E.collapsed&&f.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(`${h.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)}),C=n.selectionChange$.pipe(q.filter(I=>I.textRanges.length===1),q.map(I=>I.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{S(!0)});return()=>{m.unsubscribe(),C.unsubscribe()}}},[n,e]),_.useEffect(()=>{e||u()},[e]),{functionInfo:i,paramIndex:d,reset:u}},_r=({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:"?"}),dt=({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})]}),Er=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:Mt(s)}),i===n.length-1?"":","]},s.name)),")"]})},Ft=()=>{};function yr(e){const{onParamsSwitch:t=Ft,onClose:n=Ft,isFocus:o,editor:r,formulaText:s}=e,{functionInfo:i,paramIndex:c,reset:d}=Ir(o,s,r),g=l.useDependency(D.IEditorBridgeService),p=!l.useObservable(g.helpFunctionVisible$),[S,f]=_.useState(!0),h=l.useDependency(a.LocaleService),u=h.t("formula.prompt.required"),m=h.t("formula.prompt.optional"),C=r.getEditorId(),[I]=$t(C,!!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$:I,direction:"left-center",children:y.jsx(_r,{onClick:()=>T(!1)})},"hidden"):y.jsx(l.RectPopup,{portal:!0,onClickOutside:()=>d(),anchorRect$:I,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(Er,{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:()=>f(!S),children:y.jsx(At,{})}),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(xt,{})})]})]}),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(dt,{title:h.t("formula.prompt.helpExample"),value:`${i.functionName}(${i.functionParameter.map(v=>v.example).join(",")})`}),y.jsx(dt,{title:h.t("formula.prompt.helpAbstract"),value:i.description}),i&&i.functionParameter&&i.functionParameter.map((v,M)=>y.jsx(dt,{className:c===M?"univer-text-primary-500":"",title:v.name,value:`${v.require?u:m} ${v.detail}`},M))]})})]})},"show"):null}const Rr=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 Tr(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 br(e){var x;const{editorId:t,isFocus:n,disableOnClick:o,unitId:r,subUnitId:s}=e,i=l.useDependency(K.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(gt.DocSelectionManagerService),f=l.useDependency(a.Injector),[h,u]=_.useState(0),m=l.useDependency(R.LexerTreeBuilder),C=_.useRef(!0),I=d==null?void 0:d.with(F.RefSelectionsRenderService),E=Te(h),T=c.getUnit(r,a.UniverInstanceType.UNIVER_SHEET),N=T==null?void 0:T.getSheetBySheetId(s),v=l.useEvent(W=>{I&&I.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=Tr(f);if(!k)return;const O=(oe=k==null?void 0:k.dataStream)==null?void 0:oe.slice(0,-2),A=((se=m.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),j=!!V;if((O==null?void 0:O.substring(0,1))==="="&&(H||j))if(j){if(C.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 C.current=!1,v(1);else v(0)});return _.useEffect(()=>{const W=S.textSelection$.pipe(q.filter(U=>U.unitId===t)).subscribe(()=>{M()});return()=>W.unsubscribe()},[M,S.textSelection$,t]),_.useEffect(()=>{n||(v(0),C.current=!0)},[n,v]),_.useEffect(()=>{var U;if(!o)return;const W=(U=g==null?void 0:g.mainComponent)==null?void 0:U.onPointerDown$.subscribeEvent(()=>{v(0),C.current=!0});return()=>W==null?void 0:W.unsubscribe()},[o,(x=g==null?void 0:g.mainComponent)==null?void 0:x.onPointerDown$,v]),_.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:h,isSelectingRef:E}}const Mr=()=>{const e=l.useDependency(R.LexerTreeBuilder);return _.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function Or(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 Wt(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(),f=p.getUnit(t,a.UniverInstanceType.UNIVER_SHEET),h=f==null?void 0:f.getActiveSheet(),u=[];if(!f||!h){i.setSelections(u);return}const m=h.getSheetId(),C=M=>{var x;return(x=f==null?void 0:f.getSheetBySheetName(M))==null?void 0:x.getSheetId()};if(!((T=d==null?void 0:d.getWorksheetSkeleton(m))==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=C(b);if(!V&&b||S!==t&&A!==S||A&&A!==S||V&&V!==m||!V&&m!==n)continue;const H=L.setEndForRange(P,h.getRowCount(),h.getColumnCount());H.unitId=t,H.sheetId=m,u.push({range:H,primary:null,style:Or(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 Nr(e,t){const n=l.useDependency(a.IUniverInstanceService),o=l.useDependency(a.ThemeService),r=l.useDependency(L.IRefSelectionsService),s=l.useDependency(K.IRenderManagerService),i=l.useObservable(_.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,f)=>{const h=n.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!h||d!=null&&d.selectionMoving)return;const u=Wt({unitId:e,subUnitId:t,currentWorkbook:h,refSelections:S,editor:f,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]),p}function Ut(e=""){const t=l.useDependency(de.IDescriptionService),n=Dr(),o=l.useDependency(a.ICommandService),r=_.useMemo(()=>e.length,[e]);return l.useEvent((i,c,d=!0,g)=>{const p=i.getDocumentData(),S=i.getEditorId();if(!p)return[];const f=p.body;if(!f)return[];const h=f.dataStream.slice(0,f.dataStream.length-2),u={dataStream:"",...p.body};if(!h.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:m,refSelections:C}=xr(t,n,c);r&&m.forEach(T=>{T.ed=T.ed+r,T.st=T.st+r}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},...m];const I=c.reduce((T,N)=>typeof N=="string"?`${T}${N}`:`${T}${N.token}`,"");u.dataStream=`${e}${I}\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}),C}})}function Dr(){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(c=>e.isValidThemeColor(c)?e.getColorFromTheme(c):c),r=e.getColorFromTheme("blue.700"),s=e.getColorFromTheme("jiqing.800"),i=e.getColorFromTheme("black");return{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}},[t])}function xr(e,t,n){const{formulaRefColors:o,numberColor:r,stringColor:s,plainTextColor:i}=t,c=[],d=[],g=new Map;let p=0;for(let S=0,f=n.length;S<f;S++){const h=n[S];if(typeof h=="string"){const T=c[c.length-1],N=T?T.ed:0,v=N+h.length;c.push({st:N,ed:v,ts:{cl:{rgb:i},fs:11}});continue}if(e.hasDefinedNameDescription(h.token.trim())){c.push({st:h.startIndex,ed:h.endIndex+1,ts:{cl:{rgb:i},fs:11}});continue}const{startIndex:u,endIndex:m,nodeType:C,token:I}=h;let E="";if(C===R.sequenceNodeType.REFERENCE){if(g.has(I))E=g.get(I);else{const T=p%o.length;E=o[T],g.set(I,E),p++}d.push({refIndex:S,themeColor:E,token:I,startIndex:h.startIndex,endIndex:h.endIndex,index:d.length})}else C===R.sequenceNodeType.NUMBER?E=r:(C===R.sequenceNodeType.STRING||C===R.sequenceNodeType.ARRAY)&&(E=s);E&&E.length>0?c.push({st:u,ed:m+1,ts:{cl:{rgb:E},fs:11}}):c.push({st:u,ed:m+1,ts:{cl:{rgb:i},fs:11}})}return{textRuns:c,refSelections:d}}const kr=(e,t,n,o)=>{const r=l.useDependency(a.ICommandService),s=l.useDependency(l.IShortcutService),i=_.useRef(t);i.current=t;const c=_.useRef(o);c.current=o,_.useEffect(()=>{if(!n||!e)return;const g=`sheet.formula-embedding-editor.${n.getEditorId()}`,p=new a.DisposableCollection,S=(u,m)=>{if(c.current){c.current(u,m);return}let C=a.Direction.LEFT;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),m===l.MetaKeys.SHIFT?r.executeCommand(J.MoveSelectionOperation.id,{direction:C}):r.executeCommand(J.MoveCursorOperation.id,{direction:C})},f=(u,m)=>{let C=a.Direction.DOWN;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_LEFT?C=a.Direction.LEFT:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),i.current?m===l.MetaKeys.CTRL_COMMAND?r.executeCommand(D.MoveSelectionCommand.id,{direction:C,jumpOver:D.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:i.current===fe.NEED_ADD||i.current===fe.EDIT_OTHER_SHEET_REFERENCE}):m===l.MetaKeys.SHIFT?r.executeCommand(D.ExpandSelectionCommand.id,{direction:C,extra:"formula-editor"}):m===(l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT)?r.executeCommand(D.ExpandSelectionCommand.id,{direction:C,jumpOver:D.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand(D.MoveSelectionCommand.id,{direction:C,extra:"formula-editor",fromCurrentSelection:i.current===fe.NEED_ADD||i.current===fe.EDIT_OTHER_SHEET_REFERENCE}):S(u,m)};return p.add(r.registerCommand({id:g,type:a.CommandType.OPERATION,handler(u,m){const{keyCode:C,metaKey:I}=m;f(C,I)}})),[{keyCode:l.KeyCode.ARROW_DOWN},{keyCode:l.KeyCode.ARROW_LEFT},{keyCode:l.KeyCode.ARROW_RIGHT},{keyCode:l.KeyCode.ARROW_UP},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT}].map(({keyCode:u,metaKey:m})=>({id:g,binding:m?u|m:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keyCode:u,metaKey:m}})).forEach(u=>{p.add(s.registerShortcut(u))}),()=>{p.dispose()}},[r,n,e,s])},wr=(e,t,n,o,r=!0)=>{var h;const s=l.useDependency(K.IRenderManagerService),i=l.useDependency(a.IContextService),c=l.useDependency(l.IContextMenuService),d=l.useDependency(L.IRefSelectionsService),g=l.useDependency(a.IUniverInstanceService),p=l.useObservable(_.useMemo(()=>g.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[g])),S=s.getRenderById((h=p==null?void 0:p.getUnitId())!=null?h:""),f=S==null?void 0:S.with(F.RefSelectionsRenderService);_.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]),_.useLayoutEffect(()=>{if(e&&t){const u=f==null?void 0:f.enableSelectionChanging();return i.setContextValue(L.REF_SELECTIONS_ENABLED,!0),()=>{i.setContextValue(L.REF_SELECTIONS_ENABLED,!1),u==null||u.dispose()}}},[i,e,f,t]),_.useEffect(()=>{e&&(f==null||f.setSkipLastEnabled(!1))},[e,f])},Ar=(e,t,n)=>{const o=l.useDependency(a.IUniverInstanceService),r=l.useDependency(L.SheetsSelectionsService);return _.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])},Pr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),ft=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)),Lr=e=>{var p,S,f;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=(f=n.sequenceNodesBuilder(i.slice(1)))!=null?f:[],d=ut(c,s,!1),g=Lt(c,d);return{nodeIndex:d,updatingRefIndex:g,sequenceNodes:c,offset:s}},$r=(()=>{}),Fr=(e,t,n,o,r,s,i,c,d,g=$r)=>{var $;const p=l.useDependency(K.IRenderManagerService),S=l.useDependency(a.IUniverInstanceService),f=l.useDependency(a.ICommandService),h=l.useDependency(gt.DocSelectionManagerService),u=l.useDependency(a.ThemeService),m=l.useDependency(R.LexerTreeBuilder),C=S.getUnit(o),I=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=_.useMemo(()=>I(o,r),[I,r,o]),T=l.useObservable(C==null?void 0:C.activeSheet$),N=Te({activeSheet:T,sheetName:E}),v=l.useObservable(_.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 j,oe,se,ae,z,ee,ke,we,Qe,he;const A=Lr({editor:d,lexerTreeBuilder:m});if(!A)return;const{nodeIndex:b,updatingRefIndex:P,sequenceNodes:V,offset:H}=A;if(n.current===fe.NEED_ADD)if(H!==0){if(b===-1&&V.length)return;const G=k[k.length-1],Q=V.splice(b+1),ge=(j=G.sheetId)!=null?j:r,le={range:G,unitId:(oe=G.unitId)!=null?oe:v.getUnitId(),sheetName:I((se=G.unitId)!=null?se:v.getUnitId(),ge)},te=ge!==r,ie=(v==null?void 0:v.getUnitId())!==o,Se=Ze([le],i&&(te||ie),E,ie);V.push({token:Se[0],nodeType:R.sequenceNodeType.REFERENCE});const be=[...V,...Q],me=ft(be);g(me,Pr(V),O)}else{const G=k[k.length-1],Q=(ae=G.sheetId)!=null?ae:r,ge={range:G,unitId:(z=G.unitId)!=null?z:v.getUnitId(),sheetName:I((ee=G.unitId)!=null?ee:v.getUnitId(),Q)},le=Q!==r,te=(v==null?void 0:v.getUnitId())!==o,ie=Ze([ge],i&&(le||te),E,te);V.unshift({token:ie[0],nodeType:R.sequenceNodeType.REFERENCE});const Se=ft(V);g(Se,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[b];if(typeof Q=="object"&&Q.nodeType===R.sequenceNodeType.REFERENCE){const ge=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-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 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 pe=(Ae=ne.sheetId)!=null?Ae:r,Je={range:ne,unitId:(Me=ne.unitId)!=null?Me:v.getUnitId(),sheetName:I((Oe=ne.unitId)!=null?Oe:v.getUnitId(),pe)},et=(v==null?void 0:v.getUnitId())!==o;return Ze([Je],i&&(pe!==r||et),E,et)[0]}return Z.token});let le="",te;ge.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:(Qe=ue.unitId)!=null?Qe:v.getUnitId(),sheetName:I((he=ue.unitId)!=null?he:v.getUnitId(),Ae)},Oe=(v==null?void 0:v.getUnitId())!==o,ne=Ze([Me],i&&(Ae!==r||Oe),E,Oe);ie.push(ne[0])}const Se=V[V.length-1],be=Se&&(typeof Se=="string"?!1:Se.nodeType===R.sequenceNodeType.REFERENCE),me=`${le}${ie.length&&be?",":""}${ie.join(",")}`;g(me,!ie.length&&te?te:me.length,O)}});_.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]),_.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 j=x.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=j[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,j[V]=H,w(j,!1)})),k.add(P.selectionMoving$.subscribe(H=>{const j=x.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),oe=j[V];H.sheetId=oe.sheetId,H.unitId=oe.unitId,j[V]=H,w(j,!0)}))})},A=q.merge(d.input$,U.selectionSet$,x.selectionMoveEnd$).pipe(Jt.debounceTime(50)).subscribe(()=>{O()});return()=>{A.unsubscribe(),k.dispose()}}},[d,t,w,x,U.selectionSet$]),x==null||x.getSelectionDataWithStyle(),_.useEffect(()=>{if(c){const k=f.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===fe.NEED_ADD,H=((b=x==null?void 0:x.getSelectionDataWithStyle())!=null?b:[]).map(j=>j.rangeWithCoord);V?H.push(P.range):H[H.length-1]=P.range,w(H,!0)}}});return()=>{k.dispose()}}},[f,d,n,m,c,w,x]),_.useEffect(()=>{if(!d)return;const k=h.textSelection$.subscribe(O=>{O.unitId===d.getEditorId()&&Wt({unitId:o,subUnitId:r,refSelections:s.current,editor:d,refSelectionsService:U,refSelectionsRenderService:x,sheetSkeletonManagerService:W,themeService:u,univerInstanceService:S,currentWorkbook:v})});return()=>k.unsubscribe()},[h.textSelection$,d,s,x,U,W,r,u,o,S])},Wr=(e,t,n,o,r,s)=>{const i=l.useDependency(a.ICommandService),c=l.useDependency(J.IEditorService),g=l.useDependency(K.IRenderManagerService).getRenderById(t),p=l.useDependency(a.IUniverInstanceService),S=g==null?void 0:g.with(F.RefSelectionsRenderService);_.useEffect(()=>{if(e&&S)if(n){const f=()=>{const m=S.getSelectionControls().length;for(let C=1;C<=m;C++)S.clearLastSelection();return setTimeout(()=>{s()},30)},h=i.onCommandExecuted(m=>{m.id===L.SetWorksheetActiveOperation.id&&f()}),u=p.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(m=>{f()});return()=>{h.dispose(),u.unsubscribe()}}else{const f=i.beforeCommandExecuted(h=>{if(h.id===L.SetWorksheetActiveOperation.id){o(!1),r(),s();const u=c.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);u==null||u.focus()}});return()=>{f.dispose()}}},[e,S])},Ur=(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])},Vr=(e,t=[],n)=>{const o=l.useDependency(de.IDescriptionService),[r,s]=_.useState([]),[i,c]=_.useState(""),d=_.useRef(-1),g=Te({nodes:t}),p=()=>{s([]),c(""),d.current=-1};return _.useEffect(()=>{if(n&&e){const f=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const h=n.getSelectionRanges();if(h.length===1){const u=g.current.nodes,m=h[0];if(m.collapsed){const C=ut(u,m.startOffset-1,!1);d.current=C;const I=u[C];if(I&&typeof I!="string"&&I.nodeType===R.sequenceNodeType.FUNCTION){d.current=C;const E=I.token,T=o.getSearchListByNameFirstLetter(E);s(T),c(E);return}}}d.current=-1,c(""),s(u=>u!=null&&u.length?[]:u)});return()=>{f.unsubscribe()}}},[n,e]),_.useEffect(()=>{e||p()},[e]),{searchList:r,searchText:i,handlerFormulaReplace:(f,h)=>{const u=[...g.current.nodes];if(d.current!==-1){const m=u.splice(d.current+1),C=u.pop()||"";let I=(typeof C=="string"?C.length:C.token.length)-f.length;return u.push(f),m[0]!==R.matchToken.OPEN_BRACKET&&h!==R.FunctionType.DefinedName&&(u.push(R.matchToken.OPEN_BRACKET),I--),{text:ft([...u,...m]),offset:I}}},reset:p}},Br=()=>{},Hr=_.forwardRef(Kr);function Kr(e,t){const{isFocus:n,sequenceNodes:o,onSelect:r,editor:s,onClose:i=Br}=e,c=s.getEditorId(),d=l.useDependency(l.IShortcutService),g=l.useDependency(a.ICommandService),{searchList:p,searchText:S,handlerFormulaReplace:f,reset:h}=Vr(n,o,s),u=_.useMemo(()=>!!p.length,[p]),m=_.useRef(void 0),[C,I]=_.useState(0),E=_.useRef(!1),[T]=$t(c,u,[S,p]),N=Te({searchList:p,active:C}),v=(w,$)=>{const k=f(w,$);k&&(h(),r(k))};function M(w){E.current&&I(w)}function x(){E.current&&I(-1)}_.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:{I(P=>{const V=Math.max(0,P-1);return W(V),V});break}case l.KeyCode.ARROW_DOWN:{I(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:{h(),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:K.DeviceInputEventType.Keyboard,keyCode:O}})).forEach(O=>{$.add(d.registerShortcut(O))}),()=>{$.dispose()}},[p]);function W(w){const $=m.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 j=k.offsetTop-(b-H)/2;$.scrollTo({top:j,behavior:"smooth"})}const U=_.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=>{m.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":C===$}),onMouseEnter:()=>M($),onMouseLeave:x,onMouseMove:U,onClick:()=>{v(w.name,w.functionType),s&&s.focus()},children:[y.jsxs("span",{className:"univer-block univer-truncate univer-text-xs",children:[y.jsx("span",{className:"univer-text-red-500",children: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 jr=e=>e.startsWith(R.operatorToken.EQUALS)?e.slice(1):"",Vt=()=>{},Bt=_.forwardRef((e,t)=>{var Yt,zt,Gt,Zt;const{errorText:n,initValue:o,unitId:r,subUnitId:s,isFocus:i=!0,isSupportAcrossSheet:c=!1,onFocus:d=Vt,onBlur:g=Vt,onChange:p,onVerify:S,className:f,editorId:h,moveCursor:u=!0,onFormulaSelectingChange:m,keyboardEventConfig:C,onMoveInEditor:I,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=_.useRef(null),$=l.useEvent(p);_.useImperativeHandle(t,()=>({isClickOutSide:X=>w.current?!w.current.contains(X.target):!1}));const k=l.useEvent(m),O=_.useRef(null),A=_.useRef(void 0),b=A.current,[P,V]=_.useState(i),H=_.useRef(null),j=_.useMemo(()=>h!=null?h:a.createInternalEditorID(`${D.EMBEDDING_FORMULA_EDITOR}-${a.generateRandomId(4)}`),[]),oe=_.useMemo(()=>n!==void 0,[n]),se=l.useDependency(a.IUniverInstanceService),ae=se.getUnit(j);l.useObservable(ae==null?void 0:ae.change$);const z=Mr(),ee=a.BuildTextUtils.transform.getPlainText((zt=(Yt=ae==null?void 0:ae.getBody())==null?void 0:Yt.dataStream)!=null?zt:""),ke=Te(ee),we=_.useMemo(()=>jr(ee),[ee]),Qe=_.useMemo(()=>z(we),[we,z]),{isSelecting:he,isSelectingRef:G}=br({unitId:r,subUnitId:s,editorId:j,isFocus:P,disableOnClick:v}),Q=_.useRef(""),le=l.useDependency(K.IRenderManagerService).getRenderById(j),te=le==null?void 0:le.with(J.DocSelectionRenderService),ie=te==null?void 0:te.isFocusing,Se=_.useMemo(()=>se.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[se]),be=l.useObservable(Se),me=(be==null?void 0:be.getUnitId())===j,Z=_.useRef([]),ue=he,Me=(Zt=(Gt=l.useDependency(a.IConfigService).getConfig(Et))==null?void 0:Gt.functionScreenTips)!=null?Zt:!0;l.useUpdateEffect(()=>{$(ee)},[ee,$]);const Oe=Ut("="),Ne=Nr(r,s),ne=l.useEvent((X,re=!0,Ce,ve)=>{if(!A.current)return;Q.current=X;const tt=X[0]==="="?X.slice(1):"",Ie=z(tt),oo=Ie.reduce((De,rt)=>typeof rt=="object"?`${De}${rt.token}`:`${De}${rt}`,""),nt=Oe(A.current,oo===tt?Ie:[],re,ve);if(Z.current=nt,Ce){const De=ve!=null?ve:b==null?void 0:b.getSelectionRanges();if((De==null?void 0:De.length)!==1)return;const so=De[0].startOffset-1,io=ut(Ie,so,!1),Xt=Lt(Ie,io);if(Xt>=0){const Qt=nt.splice(Xt,1)[0];Qt&&nt.push(Qt)}Ne(P?nt:[],A.current)}});_.useEffect(()=>{P&&ne(ee,!1,!0)},[P]),_.useEffect(()=>{if(P){if(Q.current===ee)return;ne(ee,!1,!0)}},[ee]),Ur(P,S,ee);const pe=Rr(b),Je=Ar(P,r,s);_.useEffect(()=>{var X;k(he,(X=te==null?void 0:te.isFocusing)!=null?X:!0)},[k,he]),J.useKeyboardEvent(P,C,b),_.useLayoutEffect(()=>{let X;if(H.current){X=U.register({autofocus:M,editorUnitId:j,initialSnapshot:{id:j,body:{dataStream:`${o}\r
5
+ `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},H.current);const re=U.getEditor(j);A.current=re,ne(o,!1,!0)}return()=>{X==null||X.dispose()}},[]),_.useLayoutEffect(()=>{i?(V(i),pe()):(E&&(b==null||b.blur(),Je()),V(i))},[i,b,pe,Je,E]);const{checkScrollBar:et}=J.useResize(b,N,T);wr(P,!!(he&&me),r,j,x),kr(!!(P&&ie&&u),ue,b,I);const jt=l.useEvent((X,re,Ce)=>{if(!ie)return;const ve=re!==-1?[{startOffset:re+1,endOffset:re+1,collapsed:!0}]:void 0;ne(`=${X}`,!0,Ce,ve),Ce&&(pe(),re!==-1&&setTimeout(()=>{const tt={startOffset:re+1,endOffset:re+1},Ie=b==null?void 0:b.render.with(J.DocBackScrollRenderController);Ie==null||Ie.scrollToRange({...tt,collapsed:!0})},50),et())});Fr(P&&!!(he&&me),P,G,r,s,Z,c,!!ue,b,jt),Wr(P&&!!(he&&me),r,c,V,g,()=>{ne(ke.current,!1,!0)});const qt=X=>{if(X){const re=b==null?void 0:b.getSelectionRanges();if(re&&re.length===1){const Ce=re[0];if(Ce.collapsed){const ve=X.offset;setTimeout(()=>{b==null||b.setSelectionRanges([{startOffset:Ce.startOffset-ve,endOffset:Ce.endOffset-ve}])},30)}}pe(),ne(`=${X.text}`)}},ro=()=>{V(!0),d(),pe()};return y.jsxs("div",{className:f,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:ro})}),n!==void 0&&y.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),Me&&b&&we!==""&&y.jsx(yr,{editor:b,isFocus:P,formulaText:ee,onClose:()=>pe()}),Me&&!!b&&y.jsx(Hr,{isFocus:P,sequenceNodes:Qe,onSelect:qt,ref:O,editor:b})]})});function qr(e,t,n,o){const r=l.useDependency(R.LexerTreeBuilder),s=Ut(""),i=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[c,d]=_.useState([]),g=l.useDependency(D.IMarkSelectionService),p=_.useRef(""),S=l.useDependency(a.IUniverInstanceService);return _.useEffect(()=>{if(!e)return;const f=e.getDocumentDataModel().getPlainText();if(p.current===f)return;p.current=f;const h=r.sequenceNodesBuilder(f);d(h!=null?h:[])},[i,e,r]),_.useEffect(()=>{var u,m;if(!e)return;if(!t){const C=e.getDocumentData();e.setDocumentData({...C,body:{...C.body,dataStream:(m=(u=C.body)==null?void 0:u.dataStream)!=null?m:"",textRuns:[]}});return}const f=s(e,c,!1),h=new a.DisposableCollection;return f.forEach(C=>{const I=R.deserializeRangeWithSheet(C.token),E=S.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),T=E==null?void 0:E.getActiveSheet();if(!I.sheetName&&o!==(T==null?void 0:T.getSheetId())||I.sheetName&&(T==null?void 0:T.getName())!==I.sheetName)return;const N=new a.ColorKit(C.themeColor).toRgb(),v=g.addShape({range:I.range,style:{stroke:C.themeColor,fill:`rgba(${N.r}, ${N.g}, ${N.b}, 0.1)`,strokeDash:12},primary:null});v&&h.add(()=>g.removeShape(v))}),()=>{h.dispose()}},[e,t,s,g,c]),{sequenceNodes:c}}function Yr(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,f)=>{const h=d==null?void 0:d.getActiveSheet();if(!h||!n&&h.getSheetId()!==s||!(S!=null&&S.length))return;const u=o?h.getName():h.getSheetId()===s?"":h.getName(),m=S.map(C=>({range:C.range,unitId:r,sheetName:u}));g(m,f)});_.useEffect(()=>{const S=new a.DisposableCollection;return S.add(t.selectionMoveStart$.subscribe(f=>{p(f,!0)})),S.add(t.selectionMoving$.subscribe(f=>{p(f,!1)})),S.add(t.selectionMoveEnd$.subscribe(f=>{p(f,!1)})),()=>{S.dispose()}},[p,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const Ht=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}),zr=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 Gr(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),f=l.useDependency(R.LexerTreeBuilder),[h,u]=_.useState([]),[m,C]=_.useState(0),I=_.useRef(null);_.useEffect(()=>{if(t&&n.length){const v=n.map(M=>M.sheetName?R.serializeRangeWithSheet(M.sheetName,M.range):R.serializeRange(M.range));u(v),C(v.length-1)}else u([""]),C(0)},[t]);const E=(v,M)=>{const x=[...h];x[v]=M,u(x)},T=()=>{u([...h,""]),C(h.length)},N=v=>{h.splice(v,1),u([...h])};return Yr({unitId:o,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(v,M)=>{if(!t&&p!=null&&p(v))return;const x=new Set(h),W=v.map($=>$.sheetName?R.serializeRangeWithSheet($.sheetName,$.range):R.serializeRange($.range)),U=W.filter($=>!x.has($));if(!U.length)return;const w=[...h];if(W.length>1){M||w.splice(m,1),w.push(...U);const $=w.slice(0,s);u($),C($.length-1),requestAnimationFrame(()=>{var k;(k=I.current)==null||k.scrollTo({top:I.current.scrollHeight})})}else{w.splice(m,1,...U);const $=w.slice(0,s);u($),C(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(h.filter(v=>{const M=f.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:zr(v.range)})))},children:S.t("rangeSelector.confirm")})]}),onClose:g,children:y.jsxs("div",{ref:I,className:B.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",B.scrollbarClassName),children:[h.map((v,M)=>y.jsxs("div",{className:"univer-mb-2 univer-flex univer-items-center univer-gap-4",children:[y.jsx(B.Input,{className:B.clsx("univer-w-full",{"univer-border-primary-600":m===M}),placeholder:S.t("rangeSelector.placeHolder"),onFocus:()=>C(M),value:v,onChange:x=>E(M,x)}),h.length>1&&y.jsx(kt,{className:"univer-cursor-pointer",onClick:()=>N(M)})]},M)),h.length<s&&y.jsx("div",{children:y.jsxs(B.Button,{variant:"link",onClick:T,children:[y.jsx(wt,{}),y.jsx("span",{children:S.t("rangeSelector.addAnotherRange")})]})})]})})}function Zr(e){return e.split(R.matchToken.COMMA).filter(t=>!!t).map(t=>R.deserializeRangeWithSheet(t))}function Xr(e){return e.map(t=>t.sheetName?R.serializeRangeWithSheet(t.sheetName,t.range):R.serializeRange(t.range)).join(R.matchToken.COMMA)}function ht(e){const[t,n]=_.useState(null),{onVerify:o,selectorRef:r,unitId:s,subUnitId:i,maxRangeCount:c,supportAcrossSheet:d,keepSheetReference:g,autoFocus:p,onChange:S,onRangeSelectorDialogVisibleChange:f,onClickOutside:h,onFocusChange:u,forceShowDialogWhenSelectionChanged:m,hideEditor:C,resetRange:I}=e,[E,T]=_.useState(p!=null?p:!1),[N,v]=_.useState(!1),[M,x]=_.useState([]),W=l.useDependency(a.LocaleService),U=l.useDependency(J.IEditorService),{sequenceNodes:w}=qr(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(Zr((b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")),v(!0)});return _.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){U.focus(t.getEditorId())},blur:O,verify:()=>Ht($.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,$]),_.useEffect(()=>{var b;o==null||o(Ht(w),(b=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?b:"")},[w]),_.useEffect(()=>{f==null||f(N)},[N]),_.useEffect(()=>{if(N&&I)return()=>{const b={unitId:s,subUnitId:i,selections:I};k.executeCommand(L.SetSelectionsOperation.id,b)}},[N]),y.jsxs(y.Fragment,{children:[C?null:y.jsx(J.RichTextEditor,{isSingle:!0,...e,onFocusChange:(b,P)=>{T(b),u==null||u(b,P)},editorRef:n,onClickOutside:()=>{T(!1),O(),h==null||h()},icon:y.jsx(B.Tooltip,{title:W.t("rangeSelector.buttonTooltip"),placement:"bottom",children:y.jsx(Pt,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:A})})}),y.jsx(Gr,{initialValue:M,unitId:s,subUnitId:i,visible:N,maxRangeCount:c,onConfirm:b=>{const P=Xr(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||m?(x(b),v(!0),!1):!0})]})}const Qr=()=>{var o,r;const e=l.useDependency(lt),t=l.useObservable(e.currentSelector$),n=_.useRef(null);return _.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(ht,{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 Jr=Object.defineProperty,eo=Object.getOwnPropertyDescriptor,to=(e,t,n)=>t in e?Jr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,no=(e,t,n,o)=>{for(var r=o>1?void 0:o?eo(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),Kt=(e,t,n)=>to(e,typeof t!="symbol"?t+"":t,n);F.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=yt,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(yt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(Et,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[Ue,{useClass:ot}],[lt],[ze],[He],[Ke],[je],[qe],[F.FormulaReorderController],[Ge]]),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,[[ze],[Ke],[qe],[Ge]])}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,ht)),this.disposeWithMe(t.register(D.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Bt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(Qr,this._injector)))}},Kt(F.UniverSheetsFormulaUIPlugin,"pluginName",Ct),Kt(F.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET),F.UniverSheetsFormulaUIPlugin=no([a.DependentOn(R.UniverFormulaEnginePlugin,de.UniverSheetsFormulaPlugin),Xe(1,a.Inject(a.Injector)),Xe(2,K.IRenderManagerService),Xe(3,a.IConfigService),Xe(4,l.IUIPartsService)],F.UniverSheetsFormulaUIPlugin),F.FORMULA_PROMPT_ACTIVATED=St,F.FormulaEditor=Bt,F.GlobalRangeSelectorService=lt,F.HelpFunctionOperation=pt,F.InsertFunctionOperation=ce,F.MoreFunctionsOperation=Ve,F.RangeSelector=ht,F.ReferenceAbsoluteOperation=st,F.SearchFunctionOperation=_t,F.SelectEditorFormulaOperation=_e,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.12.2",
3
+ "version": "0.12.3",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -64,16 +64,16 @@
64
64
  },
65
65
  "dependencies": {
66
66
  "@univerjs/icons": "^1.0.2",
67
- "@univerjs/core": "0.12.2",
68
- "@univerjs/design": "0.12.2",
69
- "@univerjs/docs-ui": "0.12.2",
70
- "@univerjs/engine-formula": "0.12.2",
71
- "@univerjs/engine-render": "0.12.2",
72
- "@univerjs/sheets": "0.12.2",
73
- "@univerjs/sheets-formula": "0.12.2",
74
- "@univerjs/sheets-ui": "0.12.2",
75
- "@univerjs/docs": "0.12.2",
76
- "@univerjs/ui": "0.12.2"
67
+ "@univerjs/core": "0.12.3",
68
+ "@univerjs/design": "0.12.3",
69
+ "@univerjs/docs": "0.12.3",
70
+ "@univerjs/docs-ui": "0.12.3",
71
+ "@univerjs/engine-formula": "0.12.3",
72
+ "@univerjs/engine-render": "0.12.3",
73
+ "@univerjs/sheets": "0.12.3",
74
+ "@univerjs/sheets-formula": "0.12.3",
75
+ "@univerjs/sheets-ui": "0.12.3",
76
+ "@univerjs/ui": "0.12.3"
77
77
  },
78
78
  "devDependencies": {
79
79
  "postcss": "^8.5.6",
@@ -81,9 +81,9 @@
81
81
  "rxjs": "^7.8.2",
82
82
  "tailwindcss": "3.4.18",
83
83
  "typescript": "^5.9.3",
84
- "vite": "^7.2.2",
85
- "vitest": "^3.2.4",
86
- "@univerjs-infra/shared": "0.12.2"
84
+ "vite": "^7.2.4",
85
+ "vitest": "^4.0.14",
86
+ "@univerjs-infra/shared": "0.12.3"
87
87
  },
88
88
  "scripts": {
89
89
  "test": "vitest run",