@univerjs/sheets-formula-ui 0.12.2 → 0.12.3

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