@univerjs/sheets-formula-ui 0.8.3 → 0.9.0

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