@univerjs/sheets-formula-ui 0.5.3 → 0.5.4

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,4 +1,4 @@
1
- "use strict";var fn=Object.defineProperty;var mn=(r,e,t)=>e in r?fn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var V=(r,e,t)=>mn(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),P=require("@univerjs/sheets-ui"),I=require("@univerjs/engine-formula"),q=require("rxjs"),ee=require("@univerjs/docs-ui"),$=require("@univerjs/sheets"),ge=require("@univerjs/sheets-formula"),F=require("@univerjs/ui"),m=require("react"),ie=require("@univerjs/design"),z=require("@univerjs/engine-render"),je=require("@univerjs/docs"),Ue=require("rxjs/operators"),Xe={id:"sheet.command.paste-formula",type:c.CommandType.COMMAND,handler:async r=>r.get(c.ICommandService).executeCommand(P.SheetPasteCommand.id,{value:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Ie={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(r,e)=>!0};var Sn=Object.defineProperty,gn=Object.getOwnPropertyDescriptor,pn=(r,e,t,n)=>{for(var o=n>1?void 0:n?gn(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Sn(e,t,o),o},vn=(r,e)=>(t,n)=>e(t,n,r);const Pt="FORMULA_PROMPT_ACTIVATED",Fe=c.createIdentifier("formula-ui.prompt-service");let ft=class{constructor(r){V(this,"_search$",new q.Subject);V(this,"_help$",new q.Subject);V(this,"_navigate$",new q.Subject);V(this,"_accept$",new q.Subject);V(this,"_acceptFormulaName$",new q.Subject);V(this,"search$",this._search$.asObservable());V(this,"help$",this._help$.asObservable());V(this,"navigate$",this._navigate$.asObservable());V(this,"accept$",this._accept$.asObservable());V(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());V(this,"_searching",!1);V(this,"_helping",!1);V(this,"_sequenceNodes",[]);V(this,"_isLockedOnSelectionChangeRefString",!1);V(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=r}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(r){this._contextService.setContextValue(Pt,r.visible),this._searching=r.visible,this._search$.next(r)}isSearching(){return this._searching}help(r){this._helping=r.visible,this._help$.next(r)}isHelping(){return this._helping}navigate(r){this._navigate$.next(r)}accept(r){this._accept$.next(r)}acceptFormulaName(r){this._acceptFormulaName$.next(r)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(r){this._sequenceNodes=r}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(r){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(r)]}getCurrentSequenceNodeByIndex(r){return this._sequenceNodes[r]}getCurrentSequenceNodeIndex(r){let e=0;const t=this._sequenceNodes[0];for(let n=0,o=this._sequenceNodes.length;n<o;n++){const s=this._sequenceNodes[n];if(typeof s=="string")e++;else{const{endIndex:i}=s;e=i}if(r<=e)return typeof t=="string"&&r!==0?n+1:n}return this._sequenceNodes.length}updateSequenceRef(r,e){const t=this._sequenceNodes[r];if(typeof t=="string"||t.nodeType!==I.sequenceNodeType.REFERENCE)return;const n=e.length-t.token.length,o={...t};o.token=e,o.endIndex+=n,this._sequenceNodes[r]=o;for(let s=r+1,i=this._sequenceNodes.length;s<i;s++){const a=this._sequenceNodes[s];if(typeof a=="string")continue;const l={...a};l.startIndex+=n,l.endIndex+=n,this._sequenceNodes[s]=l}}insertSequenceRef(r,e){const t=e.length,n=this.getCurrentSequenceNodeIndex(r);this._sequenceNodes.splice(n,0,{token:e,startIndex:r,endIndex:r+t-1,nodeType:I.sequenceNodeType.REFERENCE});for(let o=n+1,s=this._sequenceNodes.length;o<s;o++){const i=this._sequenceNodes[o];if(typeof i=="string")continue;const a={...i};a.startIndex+=t,a.endIndex+=t,this._sequenceNodes[o]=a}}insertSequenceString(r,e){const t=this.getCurrentSequenceNodeIndex(r),n=e.split("");this._sequenceNodes.splice(t,0,...n);const o=n.length;for(let s=t+o,i=this._sequenceNodes.length;s<i;s++){const a=this._sequenceNodes[s];if(typeof a=="string")continue;const l={...a};l.startIndex+=o,l.endIndex+=o,this._sequenceNodes[s]=l}}enableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!0}disableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!1}isLockedSelectionChange(){return this._isLockedOnSelectionChangeRefString}enableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!0}disableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!1}isLockedSelectionInsert(){return this._isLockedOnSelectionInsertRefString}};ft=pn([vn(0,c.IContextService)],ft);const He={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(r,e)=>(r.get(Fe).help(e),!0)},Qe={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(r,e)=>{var E,_;const t=r.get($.SheetsSelectionsService),n=r.get(ee.IEditorService),o=t.getCurrentSelections();if(!o||!o.length)return!1;const s=$.getSheetCommandTarget(r.get(c.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:a,subUnitId:l}=s,d=i.getCellMatrix(),{value:f}=e,h=r.get(c.ICommandService),u=[];let S=null,p=0,C=0,g="";if(o.length===1&&(Rn(o[0].range)||In(o[0].range))){const{range:v,primary:y}=o[0],b=(E=y==null?void 0:y.actualRow)!=null?E:v.startRow,N=(_=y==null?void 0:y.actualColumn)!=null?_:v.startColumn;S=v,p=b,C=N;const T=Et(d,b,N);T&&(g=I.serializeRange(T))}else o.some(v=>{var D,k;const{range:y,primary:b}=v,N=(D=b==null?void 0:b.actualRow)!=null?D:y.startRow,T=(k=b==null?void 0:b.actualColumn)!=null?k:y.startColumn,M=Et(d,N,T);if(!M)return S=y,p=N,C=T,!0;const x=I.serializeRange(M),w=`=${f}(${x})`;return u.push({range:y,primary:{row:N,column:T},formula:w}),!1});if(S){const v=$.getCellAtRowCol(p,C,i),y={range:c.Rectangle.clone(S),primary:{startRow:v.startRow,startColumn:v.startColumn,endRow:v.endRow,endColumn:v.endColumn,actualRow:p,actualColumn:C,isMerged:v.isMerged,isMergedMainCell:v.startRow===p&&v.startColumn===C}},b={unitId:a,subUnitId:l,selections:[y]};await h.executeCommand($.SetSelectionsOperation.id,b),setTimeout(()=>{n.setFormula(`=${f}(${g}`)},0)}return u.length===0?!1:h.executeCommand(ge.InsertFunctionCommand.id,{list:u})}};function Et(r,e,t){const n=_n(r,e,t);if(n!==e)return{startRow:n,endRow:e-1,startColumn:t,endColumn:t};const o=Cn(r,e,t);return o!==t?{startRow:e,endRow:e,startColumn:o,endColumn:t-1}:null}function _n(r,e,t){let n=!1;if(e===0)return e;for(let o=e-1;o>=0;o--){const s=r.getValue(o,t);if(We(s)&&!n){if(o===0)return 0;n=!0}else{if(n&&!We(s))return o+1;if(n&&o===0)return 0}}return e}function Cn(r,e,t){let n=!1;if(t===0)return t;for(let o=t-1;o>=0;o--){const s=r.getValue(e,o);if(We(s)&&!n){if(o===0)return 0;n=!0}else{if(n&&!We(s))return o+1;if(n&&o===0)return 0}}return t}function We(r){if(r!=null&&r.p){const e=r==null?void 0:r.p.body;if(e==null)return!1;const t=e.dataStream,o=t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t;return c.isRealNum(o)}return r&&(r.t===c.CellValueType.NUMBER||c.getCellValueType(r)===c.CellValueType.NUMBER)}function Rn(r){return r.startRow===r.endRow&&r.startColumn===r.endColumn}function In(r){return r.startRow!==r.endRow&&r.startColumn!==r.endColumn}const Lt="SHEET_FORMULA_UI_PLUGIN",wt=`${Lt}_MORE_FUNCTIONS_COMPONENT`,Je={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async r=>(r.get(F.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:wt}}),!0)},et={id:"formula-ui.operation.change-ref-to-absolute",type:c.CommandType.OPERATION,handler:async r=>!0},Be={id:"formula-ui.operation.search-function",type:c.CommandType.OPERATION,handler:async(r,e)=>(r.get(Fe).search(e),!0)};var st={exports:{}},Ae={};/**
1
+ "use strict";var hn=Object.defineProperty;var mn=(r,e,t)=>e in r?hn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var V=(r,e,t)=>mn(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),P=require("@univerjs/sheets-ui"),I=require("@univerjs/engine-formula"),q=require("rxjs"),ee=require("@univerjs/docs-ui"),$=require("@univerjs/sheets"),ge=require("@univerjs/sheets-formula"),F=require("@univerjs/ui"),S=require("react"),ie=require("@univerjs/design"),z=require("@univerjs/engine-render"),je=require("@univerjs/docs"),Ue=require("rxjs/operators"),Xe={id:"sheet.command.paste-formula",type:c.CommandType.COMMAND,handler:async r=>r.get(c.ICommandService).executeCommand(P.SheetPasteCommand.id,{value:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Ie={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(r,e)=>!0};var Sn=Object.defineProperty,gn=Object.getOwnPropertyDescriptor,pn=(r,e,t,n)=>{for(var o=n>1?void 0:n?gn(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Sn(e,t,o),o},_n=(r,e)=>(t,n)=>e(t,n,r);const Pt="FORMULA_PROMPT_ACTIVATED",Fe=c.createIdentifier("formula-ui.prompt-service");let ht=class{constructor(r){V(this,"_search$",new q.Subject);V(this,"_help$",new q.Subject);V(this,"_navigate$",new q.Subject);V(this,"_accept$",new q.Subject);V(this,"_acceptFormulaName$",new q.Subject);V(this,"search$",this._search$.asObservable());V(this,"help$",this._help$.asObservable());V(this,"navigate$",this._navigate$.asObservable());V(this,"accept$",this._accept$.asObservable());V(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());V(this,"_searching",!1);V(this,"_helping",!1);V(this,"_sequenceNodes",[]);V(this,"_isLockedOnSelectionChangeRefString",!1);V(this,"_isLockedOnSelectionInsertRefString",!1);this._contextService=r}dispose(){this._search$.complete(),this._help$.complete(),this._navigate$.complete(),this._accept$.complete(),this._acceptFormulaName$.complete(),this._sequenceNodes=[]}search(r){this._contextService.setContextValue(Pt,r.visible),this._searching=r.visible,this._search$.next(r)}isSearching(){return this._searching}help(r){this._helping=r.visible,this._help$.next(r)}isHelping(){return this._helping}navigate(r){this._navigate$.next(r)}accept(r){this._accept$.next(r)}acceptFormulaName(r){this._acceptFormulaName$.next(r)}getSequenceNodes(){return[...this._sequenceNodes]}setSequenceNodes(r){this._sequenceNodes=r}clearSequenceNodes(){this._sequenceNodes=[]}getCurrentSequenceNode(r){return this._sequenceNodes[this.getCurrentSequenceNodeIndex(r)]}getCurrentSequenceNodeByIndex(r){return this._sequenceNodes[r]}getCurrentSequenceNodeIndex(r){let e=0;const t=this._sequenceNodes[0];for(let n=0,o=this._sequenceNodes.length;n<o;n++){const s=this._sequenceNodes[n];if(typeof s=="string")e++;else{const{endIndex:i}=s;e=i}if(r<=e)return typeof t=="string"&&r!==0?n+1:n}return this._sequenceNodes.length}updateSequenceRef(r,e){const t=this._sequenceNodes[r];if(typeof t=="string"||t.nodeType!==I.sequenceNodeType.REFERENCE)return;const n=e.length-t.token.length,o={...t};o.token=e,o.endIndex+=n,this._sequenceNodes[r]=o;for(let s=r+1,i=this._sequenceNodes.length;s<i;s++){const a=this._sequenceNodes[s];if(typeof a=="string")continue;const l={...a};l.startIndex+=n,l.endIndex+=n,this._sequenceNodes[s]=l}}insertSequenceRef(r,e){const t=e.length,n=this.getCurrentSequenceNodeIndex(r);this._sequenceNodes.splice(n,0,{token:e,startIndex:r,endIndex:r+t-1,nodeType:I.sequenceNodeType.REFERENCE});for(let o=n+1,s=this._sequenceNodes.length;o<s;o++){const i=this._sequenceNodes[o];if(typeof i=="string")continue;const a={...i};a.startIndex+=t,a.endIndex+=t,this._sequenceNodes[o]=a}}insertSequenceString(r,e){const t=this.getCurrentSequenceNodeIndex(r),n=e.split("");this._sequenceNodes.splice(t,0,...n);const o=n.length;for(let s=t+o,i=this._sequenceNodes.length;s<i;s++){const a=this._sequenceNodes[s];if(typeof a=="string")continue;const l={...a};l.startIndex+=o,l.endIndex+=o,this._sequenceNodes[s]=l}}enableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!0}disableLockedSelectionChange(){this._isLockedOnSelectionChangeRefString=!1}isLockedSelectionChange(){return this._isLockedOnSelectionChangeRefString}enableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!0}disableLockedSelectionInsert(){this._isLockedOnSelectionInsertRefString=!1}isLockedSelectionInsert(){return this._isLockedOnSelectionInsertRefString}};ht=pn([_n(0,c.IContextService)],ht);const He={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(r,e)=>(r.get(Fe).help(e),!0)},Qe={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(r,e)=>{var E,v;const t=r.get($.SheetsSelectionsService),n=r.get(ee.IEditorService),o=t.getCurrentSelections();if(!o||!o.length)return!1;const s=$.getSheetCommandTarget(r.get(c.IUniverInstanceService));if(!s)return!1;const{worksheet:i,unitId:a,subUnitId:l}=s,d=i.getCellMatrix(),{value:h}=e,f=r.get(c.ICommandService),u=[];let m=null,p=0,C=0,g="";if(o.length===1&&(Rn(o[0].range)||In(o[0].range))){const{range:_,primary:y}=o[0],b=(E=y==null?void 0:y.actualRow)!=null?E:_.startRow,N=(v=y==null?void 0:y.actualColumn)!=null?v:_.startColumn;m=_,p=b,C=N;const T=Et(d,b,N);T&&(g=I.serializeRange(T))}else o.some(_=>{var D,k;const{range:y,primary:b}=_,N=(D=b==null?void 0:b.actualRow)!=null?D:y.startRow,T=(k=b==null?void 0:b.actualColumn)!=null?k:y.startColumn,M=Et(d,N,T);if(!M)return m=y,p=N,C=T,!0;const x=I.serializeRange(M),w=`=${h}(${x})`;return u.push({range:y,primary:{row:N,column:T},formula:w}),!1});if(m){const _=$.getCellAtRowCol(p,C,i),y={range:c.Rectangle.clone(m),primary:{startRow:_.startRow,startColumn:_.startColumn,endRow:_.endRow,endColumn:_.endColumn,actualRow:p,actualColumn:C,isMerged:_.isMerged,isMergedMainCell:_.startRow===p&&_.startColumn===C}},b={unitId:a,subUnitId:l,selections:[y]};await f.executeCommand($.SetSelectionsOperation.id,b),setTimeout(()=>{n.setFormula(`=${h}(${g}`)},0)}return u.length===0?!1:f.executeCommand(ge.InsertFunctionCommand.id,{list:u})}};function Et(r,e,t){const n=vn(r,e,t);if(n!==e)return{startRow:n,endRow:e-1,startColumn:t,endColumn:t};const o=Cn(r,e,t);return o!==t?{startRow:e,endRow:e,startColumn:o,endColumn:t-1}:null}function vn(r,e,t){let n=!1;if(e===0)return e;for(let o=e-1;o>=0;o--){const s=r.getValue(o,t);if(We(s)&&!n){if(o===0)return 0;n=!0}else{if(n&&!We(s))return o+1;if(n&&o===0)return 0}}return e}function Cn(r,e,t){let n=!1;if(t===0)return t;for(let o=t-1;o>=0;o--){const s=r.getValue(e,o);if(We(s)&&!n){if(o===0)return 0;n=!0}else{if(n&&!We(s))return o+1;if(n&&o===0)return 0}}return t}function We(r){if(r!=null&&r.p){const e=r==null?void 0:r.p.body;if(e==null)return!1;const t=e.dataStream,o=t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t;return c.isRealNum(o)}return r&&(r.t===c.CellValueType.NUMBER||c.getCellValueType(r)===c.CellValueType.NUMBER)}function Rn(r){return r.startRow===r.endRow&&r.startColumn===r.endColumn}function In(r){return r.startRow!==r.endRow&&r.startColumn!==r.endColumn}const Lt="SHEET_FORMULA_UI_PLUGIN",wt=`${Lt}_MORE_FUNCTIONS_COMPONENT`,Je={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async r=>(r.get(F.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:wt}}),!0)},et={id:"formula-ui.operation.change-ref-to-absolute",type:c.CommandType.OPERATION,handler:async r=>!0},Be={id:"formula-ui.operation.search-function",type:c.CommandType.OPERATION,handler:async(r,e)=>(r.get(Fe).search(e),!0)};var st={exports:{}},Ae={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,30 +6,30 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var yt;function En(){if(yt)return Ae;yt=1;var r=m,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,l,d){var f,h={},u=null,S=null;d!==void 0&&(u=""+d),l.key!==void 0&&(u=""+l.key),l.ref!==void 0&&(S=l.ref);for(f in l)n.call(l,f)&&!s.hasOwnProperty(f)&&(h[f]=l[f]);if(a&&a.defaultProps)for(f in l=a.defaultProps,l)h[f]===void 0&&(h[f]=l[f]);return{$$typeof:e,type:a,key:u,ref:S,props:h,_owner:o.current}}return Ae.Fragment=t,Ae.jsx=i,Ae.jsxs=i,Ae}var Tt;function yn(){return Tt||(Tt=1,st.exports=En()),st.exports}var R=yn(),ue=function(){return ue=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ue.apply(this,arguments)},Tn=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(r);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(r,n[o])&&(t[n[o]]=r[n[o]]);return t},Ee=m.forwardRef(function(r,e){var t=r.icon,n=r.id,o=r.className,s=r.extend,i=Tn(r,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(n," ").concat(o||"").trim(),l=m.useRef("_".concat(xn()));return kt(t,"".concat(n),{defIds:t.defIds,idSuffix:l.current},ue({ref:e,className:a},i),s)});function kt(r,e,t,n,o){return m.createElement(r.tag,ue(ue({key:e},bn(r,t,o)),n),(Nn(r,t).children||[]).map(function(s,i){return kt(s,"".concat(e,"-").concat(r.tag,"-").concat(i),t,void 0,o)}))}function bn(r,e,t){var n=ue({},r.attrs);t!=null&&t.colorChannel1&&n.fill==="colorChannel1"&&(n.fill=t.colorChannel1);var o=e.defIds;return!o||o.length===0||(r.tag==="use"&&n["xlink:href"]&&(n["xlink:href"]=n["xlink:href"]+e.idSuffix),Object.entries(n).forEach(function(s){var i=s[0],a=s[1];typeof a=="string"&&(n[i]=a.replace(/url\(#(.*)\)/,"url(#$1".concat(e.idSuffix,")")))})),n}function Nn(r,e){var t,n=e.defIds;return!n||n.length===0?r:r.tag==="defs"&&(!((t=r.children)===null||t===void 0)&&t.length)?ue(ue({},r),{children:r.children.map(function(o){return typeof o.attrs.id=="string"&&n&&n.indexOf(o.attrs.id)>-1?ue(ue({},o),{attrs:ue(ue({},o.attrs),{id:o.attrs.id+e.idSuffix})}):o})}):r}function xn(){return Math.random().toString(36).substring(2,8)}Ee.displayName="UniverIcon";var Mn={tag:"svg",attrs:{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"}}]},Ut=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"check-mark-single",ref:e,icon:Mn}))});Ut.displayName="CheckMarkSingle";var Fn={tag:"svg",attrs:{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"}}]},tt=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"close-single",ref:e,icon:Fn}))});tt.displayName="CloseSingle";var On={tag:"svg",attrs:{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.866699 5.9313.866699H10.069C10.4004.866699 10.669 1.13533 10.669 1.4667 10.669 1.79807 10.4004 2.0667 10.069 2.0667H5.9313C5.59993 2.0667 5.3313 1.79807 5.3313 1.4667zM1.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.64443 14.8999 3.9758 14.6312 4.24443 14.2999 4.24443H1.69985C1.36848 4.24443 1.09985 3.9758 1.09985 3.64443zM6.12398 8.30171C6.35829 8.0674 6.73819 8.0674 6.97251 8.30171L8.00007 9.32928 9.02764 8.30171C9.26195 8.0674 9.64185 8.0674 9.87617 8.30171 10.1105 8.53603 10.1105 8.91593 9.87617 9.15024L8.8486 10.1778 9.87617 11.2054C10.1105 11.4397 10.1105 11.8196 9.87617 12.0539 9.64185 12.2882 9.26195 12.2882 9.02764 12.0539L8.00007 11.0263 6.97251 12.0539C6.73819 12.2882 6.35829 12.2882 6.12398 12.0539 5.88966 11.8196 5.88966 11.4397 6.12398 11.2054L7.15154 10.1778 6.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"}}]},$t=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"delete-single",ref:e,icon:On}))});$t.displayName="DeleteSingle";var An={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M8.75 5.32495C8.75 5.73916 8.41421 6.07495 8 6.07495 7.58579 6.07495 7.25 5.73916 7.25 5.32495 7.25 4.91074 7.58579 4.57495 8 4.57495 8.41421 4.57495 8.75 4.91074 8.75 5.32495zM8.5999 7.52505C8.5999 7.19368 8.33127 6.92505 7.9999 6.92505 7.66853 6.92505 7.3999 7.19368 7.3999 7.52505V11.425C7.3999 11.7564 7.66853 12.025 7.9999 12.025 8.33127 12.025 8.5999 11.7564 8.5999 11.425V7.52505z"}},{tag:"path",attrs:{fill:"currentColor",d:"M0.899902 8.00002C0.899902 4.0788 4.07868 0.900024 7.9999 0.900024C11.9211 0.900024 15.0999 4.0788 15.0999 8.00002C15.0999 11.9212 11.9211 15.1 7.9999 15.1C4.07868 15.1 0.899902 11.9212 0.899902 8.00002ZM7.9999 2.10002C4.74142 2.10002 2.0999 4.74154 2.0999 8.00002C2.0999 11.2585 4.74142 13.9 7.9999 13.9C11.2584 13.9 13.8999 11.2585 13.8999 8.00002C13.8999 4.74154 11.2584 2.10002 7.9999 2.10002Z",fillRule:"evenodd",clipRule:"evenodd"}}]},jt=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"details-single",ref:e,icon:An}))});jt.displayName="DetailsSingle";var Dn={tag:"svg",attrs:{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"}}]},Ht=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"increase-single",ref:e,icon:Dn}))});Ht.displayName="IncreaseSingle";var Pn={tag:"svg",attrs:{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"}}]},gt=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"more-single",ref:e,icon:Pn}))});gt.displayName="MoreSingle";var Ln={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M12.6185 12.4423C12.5907 12.2749 12.7773 12.15 12.9343 12.2308L15.4242 13.5126C15.6102 13.6084 15.5544 13.8745 15.3439 13.8955L14.2456 14.184L13.4521 15.1286C13.3495 15.2939 13.085 15.2463 13.0534 15.0568L12.6185 12.4423Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M1 3.6C1 2.16406 2.16406 1 3.6 1H12.3C13.7359 1 14.9 2.16406 14.9 3.6V5.81156C14.9003 5.81881 14.9004 5.82609 14.9004 5.8334C14.9004 5.84071 14.9003 5.84799 14.9 5.85524V10.045C14.9003 10.0522 14.9004 10.0595 14.9004 10.0668C14.9004 10.3982 14.6318 10.6668 14.3004 10.6668H11.1668C10.8907 10.6668 10.6668 10.8907 10.6668 11.1668V14.3C10.6668 14.6314 10.3982 14.9 10.0668 14.9L10.05 14.8998L3.6 14.9C2.16406 14.9 1 13.7359 1 12.3V3.6ZM13.2 5.2334C13.4761 5.2334 13.7 5.00954 13.7 4.7334V3.6C13.7 2.8268 13.0732 2.2 12.3 2.2H11.1668C10.8907 2.2 10.6668 2.42386 10.6668 2.7V4.7334C10.6668 5.00954 10.8907 5.2334 11.1668 5.2334H13.2ZM10.6668 6.9334C10.6668 6.65726 10.8907 6.4334 11.1668 6.4334H13.2C13.4761 6.4334 13.7 6.65726 13.7 6.9334V8.9668C13.7 9.24294 13.4761 9.4668 13.2 9.4668H11.1668C10.8907 9.4668 10.6668 9.24294 10.6668 8.9668V6.9334ZM8.9668 5.2334C9.24294 5.2334 9.4668 5.00954 9.4668 4.7334V2.7C9.4668 2.42386 9.24294 2.2 8.9668 2.2H6.9334C6.65726 2.2 6.4334 2.42386 6.4334 2.7V4.7334C6.4334 5.00954 6.65726 5.2334 6.9334 5.2334L8.9668 5.2334ZM6.4334 6.9334C6.4334 6.65726 6.65726 6.4334 6.9334 6.4334L8.9668 6.4334C9.24294 6.4334 9.4668 6.65726 9.4668 6.9334V8.9668C9.4668 9.24294 9.24294 9.4668 8.9668 9.4668L6.9334 9.4668C6.65726 9.4668 6.4334 9.24294 6.4334 8.9668V6.9334ZM4.7334 5.2334C5.00954 5.2334 5.2334 5.00954 5.2334 4.7334V2.7C5.2334 2.42386 5.00954 2.2 4.7334 2.2H3.6C2.8268 2.2 2.2 2.8268 2.2 3.6V4.7334C2.2 5.00954 2.42386 5.2334 2.7 5.2334H4.7334ZM2.2 6.9334C2.2 6.65726 2.42386 6.4334 2.7 6.4334H4.7334C5.00954 6.4334 5.2334 6.65725 5.2334 6.9334V8.9668C5.2334 9.24294 5.00954 9.4668 4.7334 9.4668H2.7C2.42386 9.4668 2.2 9.24294 2.2 8.9668V6.9334ZM5.2334 11.1668C5.2334 10.8907 5.00954 10.6668 4.7334 10.6668H2.7C2.42386 10.6668 2.2 10.8907 2.2 11.1668V12.3C2.2 13.0732 2.8268 13.7 3.6 13.7H4.7334C5.00954 13.7 5.2334 13.4761 5.2334 13.2V11.1668ZM9.4668 11.1668C9.4668 10.8907 9.24294 10.6668 8.9668 10.6668H6.9334C6.65726 10.6668 6.4334 10.8907 6.4334 11.1668V13.2C6.4334 13.4761 6.65726 13.7 6.9334 13.7H8.9668C9.24294 13.7 9.4668 13.4761 9.4668 13.2V11.1668Z",fillRule:"evenodd",clipRule:"evenodd"}}]},Wt=m.forwardRef(function(r,e){return m.createElement(Ee,Object.assign({},r,{id:"select-range-single",ref:e,icon:Ln}))});Wt.displayName="SelectRangeSingle";function Bt(r){var e,t,n="";if(typeof r=="string"||typeof r=="number")n+=r;else if(typeof r=="object")if(Array.isArray(r)){var o=r.length;for(e=0;e<o;e++)r[e]&&(t=Bt(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Vt(){for(var r,e,t=0,n="",o=arguments.length;t<o;t++)(r=arguments[t])&&(e=Bt(r))&&(n&&(n+=" "),n+=e);return n}var wn=Object.defineProperty,kn=Object.getOwnPropertyDescriptor,Un=(r,e,t,n)=>{for(var o=n>1?void 0:n?kn(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&wn(e,t,o),o},Ne=(r,e)=>(t,n)=>e(t,n,r);exports.RefSelectionsRenderService=class extends P.BaseSelectionRenderService{constructor(t,n,o,s,i,a,l){super(n,o,s,i,a);V(this,"_workbookSelections");V(this,"_eventDisposables");this._context=t,this._contextService=a,this._refSelectionsService=l,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle($n(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(t){this._remainLastEnabled=t}setSkipLastEnabled(t){this._skipLastEnabled=t}clearLastSelection(){const t=this._selectionControls[this._selectionControls.length-1];t&&(t.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),c.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var t;(t=this._eventDisposables)==null||t.dispose(),this._eventDisposables=null}_initCanvasEventListeners(){const t=this._getSheetObject(),{spreadsheetRowHeader:n,spreadsheetColumnHeader:o,spreadsheet:s,spreadsheetLeftTopPlaceholder:i}=t,{scene:a}=this._context,l=new c.DisposableCollection;return l.add(s==null?void 0:s.onPointerDown$.subscribeEvent((d,f)=>{this.inRefSelectionMode()&&(this._onPointerDown(d,s.zIndex+1,c.RANGE_TYPE.NORMAL,this._getActiveViewport(d)),d.button!==2&&f.stopPropagation())})),l.add(n==null?void 0:n.onPointerDown$.subscribeEvent((d,f)=>{if(!this.inRefSelectionMode())return;const h=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:u}=P.getCoordByOffset(d.offsetX,d.offsetY,a,h);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.ROW)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(d),z.ScrollTimerType.Y),d.button!==2&&f.stopPropagation())})),l.add(o==null?void 0:o.onPointerDown$.subscribeEvent((d,f)=>{if(!this.inRefSelectionMode())return;const h=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:u}=P.getCoordByOffset(d.offsetX,d.offsetY,a,h);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(d),z.ScrollTimerType.X),d.button!==2&&f.stopPropagation())})),l.add(i==null?void 0:i.onPointerDown$.subscribeEvent((d,f)=>{if(this._reset(),!this.inRefSelectionMode())return;const h=this._sheetSkeletonManagerService.getCurrent().skeleton,u=P.getAllSelection(h);this._addSelectionControlByModelData(u),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const S=a.onPointerUp$.subscribeEvent(()=>{S.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});d.button!==2&&f.stopPropagation()})),l}_addSelectionControlByModelData(t){var a;const n=this._skeleton,o=(a=t.style)!=null?a:P.genNormalSelectionStyle(this._themeService),s=this._scene;return t.style=o,this.newSelectionControl(s,n,t)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(t=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(t||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(t=>{this._updateSelections(t,$.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(t=>{this._updateSelections(t,$.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(t=>{this._updateSelections(t,$.SelectionMoveType.MOVE_END)}))}_updateSelections(t,n){const s=this._context.unit.getActiveSheet().getSheetId();t.length!==0&&this._workbookSelections.setSelections(s,t.map(i=>$.convertSelectionDataToRange(i)),n)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{if(!t)return;const{skeleton:n}=t,{scene:o}=this._context,s=o.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&this._skeleton.worksheet.getSheetId()!==n.worksheet.getSheetId()&&this._reset(),this._changeRuntime(n,o,s);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(t){const n=this._getSheetObject();return n==null?void 0:n.scene.getActiveViewportByCoord(z.Vector2.FromArray([t.offsetX,t.offsetY]))}_getSheetObject(){return P.getSheetObject(this._context.unit,this._context)}_onPointerDown(t,n=0,o=c.RANGE_TYPE.NORMAL,s,i=z.ScrollTimerType.ALL){var D;this._rangeType=o;const a=this._skeleton,l=this._scene;if(!l||!a)return;s&&(this._activeViewport=s);const{offsetX:d,offsetY:f}=t,h=l.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!h)return;const u=l.getCoordRelativeToViewport(z.Vector2.FromArray([d,f])),{x:S,y:p}=u;this._startViewportPosX=S,this._startViewportPosY=p;const C=l.getScrollXYInfoByViewport(u),{scaleX:g,scaleY:E}=l.getAncestorScale(),_=this._skeleton.getCellByOffset(S,p,g,E,C);if(!_)return;switch(o){case c.RANGE_TYPE.NORMAL:break;case c.RANGE_TYPE.ROW:_.startColumn=0,_.endColumn=this._skeleton.getColumnCount()-1;break;case c.RANGE_TYPE.COLUMN:_.startRow=0,_.endRow=this._skeleton.getRowCount()-1;break;case c.RANGE_TYPE.ALL:_.startRow=0,_.startColumn=0,_.endRow=this._skeleton.getRowCount()-1,_.endColumn=this._skeleton.getColumnCount()-1}const v={range:_,primary:_,style:null};v.range.rangeType=o;const y=P.attachSelectionWithCoord(v,this._skeleton);this._startRangeWhenPointerDown={...y.rangeWithCoord};const b={...y.rangeWithCoord,rangeType:o};let N=this.getActiveSelectionControl();const T=this.getSelectionControls();for(const k of T){if(t.button===2&&k.model.isInclude(b)){N=k;return}if(k.model.isEqual(b)){N=k;break}}this._checkClearPreviousControls(t);const M=N==null?void 0:N.model.currentCell,x=t.shiftKey&&M,w=this._remainLastEnabled&&!t.ctrlKey&&!t.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;x&&M?this._makeSelectionByTwoCells(M,b,a,o,N):w&&N?N.updateRangeBySelectionWithCoord(y):N=this.newSelectionControl(l,a,v);for(let k=0;k<this.getSelectionControls().length-1;k++)this.getSelectionControls()[k].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),l.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(D=l.getTransformer())==null||D.clearSelectedObjects(),this._setupPointerMoveListener(h,N,o,i,S,p),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=l.onPointerUp$.subscribeEvent(()=>{var k;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(k=this._escapeShortcutDisposable)==null||k.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(t,n,o){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:a}=n,l=new P.SelectionControl(t,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:a}),d=P.attachSelectionWithCoord(o,n);return l.updateRangeBySelectionWithCoord(d),this._selectionControls.push(l),l.setControlExtension({skeleton:n,scene:t,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),l}};exports.RefSelectionsRenderService=Un([Ne(1,c.Inject(c.Injector)),Ne(2,c.Inject(c.ThemeService)),Ne(3,F.IShortcutService),Ne(4,c.Inject(P.SheetSkeletonManagerService)),Ne(5,c.IContextService),Ne(6,$.IRefSelectionsService)],exports.RefSelectionsRenderService);function $n(r){const e=P.genNormalSelectionStyle(r);return e.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},e}const jn=(r,e,t)=>{const o=c.useDependency(z.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService);m.useEffect(()=>{if(t&&s){const i=t.input$.subscribe(a=>{a.content===I.matchToken.COMMA?s.setSkipLastEnabled(!0):s.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[t,s]),m.useEffect(()=>{s&&(e.endsWith(I.matchToken.COMMA)||s.setSkipLastEnabled(!1))},[e,s])},me=r=>r.map(e=>typeof e=="string"?e:e.token).join(""),qt=(r,e,t)=>{const n=m.useRef(!1);return m.useEffect(()=>{if(t){const s=t.input$.subscribe(()=>{n.current=!0});return()=>{s.unsubscribe()}}},[t]),m.useEffect(()=>{if(n.current&&r){n.current=!1;const s=me(r);e(s)}},[r]),()=>n.current=!0},nt=()=>{const r=c.useDependency(I.LexerTreeBuilder);return t=>r.sequenceNodesBuilder(t)||[]},Kt=(r,e,t,n,o,s)=>{const i=nt(),a=m.useRef(!0);m.useEffect(()=>{var l,d;if(s){if(a.current){const f=i(r);if(f.length){const h=n(s,f);t&&o(h)}else{const h=s.getDocumentData(),S={dataStream:(d=(l=h.body)==null?void 0:l.dataStream)!=null?d:`${e}\r
10
- `,...h.body};s.setDocumentData({...h,body:S})}a.current=!1}else if(t){const f=i(r),h=n(s,f);o(h)}}},[s,t])},zt=r=>m.useMemo(()=>()=>{var t,n;if(r){r.focus();const o=[...r.getSelectionRanges()];if(o.length&&r.setSelectionRanges(o),!o.length){const s=(n=(t=r.getDocumentData().body)==null?void 0:t.dataStream)!=null?n:`\r
11
- `,i=Math.max(s.length-2,0);r.setSelectionRanges([{startOffset:i,endOffset:i}])}}},[r]);function $e(r,e,t){const n=r.getCurrentTheme(),o=new c.ColorKit(e).setAlpha(.05).toRgbString();return{id:t,strokeWidth:1,stroke:e,fill:o,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:n.colorWhite}}function pt(r){const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(c.ThemeService),n=c.useDependency($.IRefSelectionsService),s=c.useDependency(z.IRenderManagerService).getRenderById(r),i=s==null?void 0:s.with(exports.RefSelectionsRenderService),a=s==null?void 0:s.with(P.SheetSkeletonManagerService);return d=>{var E;const f=e.getUnit(r),h=f==null?void 0:f.getActiveSheet(),u=[];if(!f||!h){n.setSelections(u);return}const S=h.getSheetId(),p=_=>{var v;return(v=f==null?void 0:f.getSheetBySheetName(_))==null?void 0:v.getSheetId()};if(!((E=a==null?void 0:a.getWorksheetSkeleton(S))==null?void 0:E.skeleton))return;for(let _=0,v=d.length;_<v;_++){const y=d[_],{themeColor:b,token:N,refIndex:T}=y,M=I.deserializeRangeWithSheet(N),{unitId:x,sheetName:w,range:D}=M;if(x&&r!==x)continue;const k=p(w);if(k&&k!==S)continue;const A=$.setEndForRange(D,h.getRowCount(),h.getColumnCount());u.push({range:A,primary:null,style:$e(t,b,T.toString())})}((i==null?void 0:i.getSelectionControls())||[]).length===u.length?i==null||i.resetSelectionsByModelData(u):n.setSelections(u)}}function Yt(r=""){const e=c.useDependency(ge.IDescriptionService),t=Gt(),n=m.useMemo(()=>r.length,[r]);return(s,i,a=!0)=>{const l=s.getDocumentData();if(!l)return[];if(!l.body)return[];const f={dataStream:"",...l.body};if(i==null||i.length===0){f.textRuns=[];const h={...l,body:f};return s.setDocumentData(h),[]}else{const{textRuns:h,refSelections:u}=Zt(e,t,i);n&&h.forEach(g=>{g.ed=g.ed+n,g.st=g.st+n}),f.textRuns=h;const S=i.reduce((g,E)=>typeof E=="string"?`${g}${E}`:`${g}${E.token}`,"");f.dataStream=`${r}${S}\r
12
- `;let p;if(a){p=s.getSelectionRanges();const g=f.dataStream.length-2+n;p.forEach(E=>{E.startOffset=Math.max(0,Math.min(E.startOffset,g)),E.endOffset=Math.max(0,Math.min(E.endOffset,g))})}const C={...l,body:f};return s.setDocumentData(C,p),u}}}function Gt(){const e=c.useDependency(c.ThemeService).getCurrentTheme();return m.useMemo(()=>{const n=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],o=e.hyacinth700,s=e.verdancy800;return{formulaRefColors:n,numberColor:o,stringColor:s}},[e])}function Zt(r,e,t){const{formulaRefColors:n,numberColor:o,stringColor:s}=e,i=[],a=[],l=new Map;let d=0;for(let f=0,h=t.length;f<h;f++){const u=t[f];if(typeof u=="string"){const _=i[i.length-1],v=_?_.ed:0,y=v+u.length;i.push({st:v,ed:y});continue}if(r.hasDefinedNameDescription(u.token.trim()))continue;const{startIndex:S,endIndex:p,nodeType:C,token:g}=u;let E="";if(C===I.sequenceNodeType.REFERENCE){if(l.has(g))E=l.get(g);else{const _=d%n.length;E=n[_],l.set(g,E),d++}a.push({refIndex:f,themeColor:E,token:g})}else C===I.sequenceNodeType.NUMBER?E=o:(C===I.sequenceNodeType.STRING||C===I.sequenceNodeType.ARRAY)&&(E=s);E&&E.length>0&&i.push({st:S,ed:p+1,ts:{cl:{rgb:E}}})}return{textRuns:i,refSelections:a}}const Xt=(r,e)=>{const t=c.useDependency(c.ICommandService),n=c.useDependency(F.IShortcutService);m.useEffect(()=>{if(!e||!r)return;const s=`sheet.formula-embedding-editor.${e.getEditorId()}`,i=new c.DisposableCollection,a=l=>{var f;const d=e.getSelectionRanges();if(d.length===1){const h=d[0];switch(l){case F.KeyCode.ARROW_LEFT:{const u=Math.max(h.startOffset-1,0);e.setSelectionRanges([{startOffset:u,endOffset:u}]);break}case F.KeyCode.ARROW_RIGHT:{const u=(((f=e.getDocumentData().body)==null?void 0:f.dataStream)||",,").length-2,S=Math.min(h.endOffset+1,u);e.setSelectionRanges([{startOffset:S,endOffset:S}]);break}}}};return i.add(t.registerCommand({id:s,type:c.CommandType.OPERATION,handler(l,d){const{keyCode:f}=d;a(f)}})),[F.KeyCode.ARROW_LEFT,F.KeyCode.ARROW_RIGHT,F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP].map(l=>({id:s,binding:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:l}})).forEach(l=>{i.add(n.registerShortcut(l))}),()=>{i.dispose()}},[e,r])},Qt=(r,e)=>{const n=c.useDependency(z.IRenderManagerService).getRenderById(r),o=n==null?void 0:n.with(exports.RefSelectionsRenderService);m.useEffect(()=>{o&&(e?o==null||o.setRemainLastEnabled(!1):o==null||o.setRemainLastEnabled(!0))},[e,o])},vt=(r,e)=>{const t=c.useDependency(z.IRenderManagerService),n=c.useDependency(c.IContextService),o=c.useDependency(F.IContextMenuService),s=c.useDependency($.IRefSelectionsService),i=t.getRenderById(e),a=i==null?void 0:i.with(exports.RefSelectionsRenderService);m.useLayoutEffect(()=>{if(r){const l=a==null?void 0:a.enableSelectionChanging();return n.setContextValue($.REF_SELECTIONS_ENABLED,!0),n.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{n.setContextValue(c.EDITOR_ACTIVATED,!1),n.setContextValue($.REF_SELECTIONS_ENABLED,!1),l==null||l.dispose()}}},[r]),m.useLayoutEffect(()=>{if(r)return()=>{s.clear()}},[r]),m.useEffect(()=>{if(r)return o.disable(),()=>{o.enable()}},[r]),m.useEffect(()=>{r&&(a==null||a.setSkipLastEnabled(!1))},[r])},Jt=()=>{m.useEffect(()=>()=>{},[])},en=r=>{const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency($.SheetsSelectionsService);return m.useMemo(()=>{if(r){const o=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),s=o==null?void 0:o.getActiveSheet(),i=[...t.getCurrentSelections()];return()=>{const a=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),l=a==null?void 0:a.getActiveSheet();l&&l===s&&t.setSelections(i)}}return()=>{}},[r])},tn=r=>{const e=()=>{if(r){const{scene:n,mainComponent:o}=r.render,s=r.render.with(je.DocSkeletonManagerService),{width:i,height:a}=r.getBoundingClientRect();s.getViewModel().getDataModel().updateDocumentDataPageSize(1/0),n.transformByState({width:i,height:a}),o==null||o.resize(i,a)}},t=m.useMemo(()=>c.debounce(()=>{var p;if(!r)return;const o=r.render.with(je.DocSkeletonManagerService).getSkeleton(),{scene:s,mainComponent:i}=r.render,a=s.getViewport(ee.VIEWPORT_KEY.VIEW_MAIN),{actualWidth:l}=o.getActualSize(),{width:d,height:f}=r.getBoundingClientRect();let h=a==null?void 0:a.getScrollBar();const u=Math.max(l,d),S=f;s.transformByState({width:u,height:S}),i==null||i.resize(u,S),l>d?h==null?a&&new z.ScrollBar(a,{barSize:8,enableVertical:!1}):a==null||a.resetCanvasSizeAndUpdateScroll():(h=null,a==null||a.scrollToBarPos({x:0,y:0}),(p=a==null?void 0:a.getScrollBar())==null||p.dispose())},30),[r]);return m.useEffect(()=>{if(r){const n=setTimeout(()=>{e(),t()},500);return()=>{clearTimeout(n)}}},[r]),m.useEffect(()=>{if(r){const n=r.input$.subscribe(()=>{t()});return()=>{n.unsubscribe()}}},[r]),{resize:e,checkScrollBar:t}},mt=r=>typeof r=="string"?r===I.matchToken.COMMA:!1,Hn=r=>{if(typeof r=="object")return r.nodeType===I.sequenceNodeType.REFERENCE},Wn=r=>r.filter(e=>mt(e)||Hn(e)),rt=r=>{if(r.endColumn<r.startColumn){const e=r.endColumn;r.endColumn=r.startColumn,r.startColumn=e}if(r.endRow<r.startRow){const e=r.endRow;r.endRow=r.startRow,r.startRow=e}return r};function bt(r,e,t){var n,o;return((o=(n=r.getUnit(e))==null?void 0:n.getSheetBySheetId(t))==null?void 0:o.getName())||""}const he=(r,e=!1)=>e?r.map(t=>t.sheetName!==""?I.serializeRangeWithSheet(t.sheetName,t.range):I.serializeRange(t.range)):r.map(t=>I.serializeRange(t.range)),nn=(r,e,t,n,o,s,i)=>{const a=c.useDependency(z.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=m.useRef(!1),f=a.getRenderById(e),h=f==null?void 0:f.with(exports.RefSelectionsRenderService),u=m.useRef([]),S=m.useMemo(()=>{const C=Wn(n),g=u.current;return C.length===g.length?(g.splice(0),g.push(...C),g):C},[n]);u.current=S;const p=m.useRef();m.useEffect(()=>{if(r&&h){let C=!0;const g=(v,y)=>{var A;if(C||d.current){C=!1;return}const b=[...v],N=l.getUnit(e),T=((A=N==null?void 0:N.getActiveSheet())==null?void 0:A.getName())||"",M=S.map((O,K)=>{if(typeof O=="string"){if(!S[K-1])return null;const U=S[K+1];return mt(O)&&(mt(U)||K===S.length-1)?null:O}else if(O.nodeType===I.sequenceNodeType.REFERENCE){const L=I.deserializeRangeWithSheet(O.token);L.unitId=L.unitId===""?e:L.unitId,L.sheetName=L.sheetName===""?T:L.sheetName;const{unitId:U,sheetName:j}=L;if(s&&(U!==e||T!==j))return null;if(U===e&&T===j){const B=b.shift();if(B&&bt(l,e,B.rangeWithCoord.sheetId||"")===j){const Z={...O};return rt(B.rangeWithCoord),o?Z.token=I.serializeRangeWithSheet(T,B.rangeWithCoord):Z.token=I.serializeRange(B.rangeWithCoord),Z}}return O}return null}).filter(O=>!!O),x=he(b.map(O=>{var K,L,U;return{range:O.rangeWithCoord,unitId:(K=O.rangeWithCoord.unitId)!=null?K:"",sheetName:bt(l,(L=O.rangeWithCoord.unitId)!=null?L:"",(U=O.rangeWithCoord.sheetId)!=null?U:"")}}),o).join(I.matchToken.COMMA),w=me(M),D=`${w}${w&&x?I.matchToken.COMMA:""}${x}`,k=d.current;i(D,k?-1:D.length,y)},E=h.selectionMoveEnd$.subscribe(v=>{if(g(v,!0),d.current=!1,p.current){const{result:y,offset:b}=p.current;i(y,b,!0),p.current=void 0}}),_=h.selectionMoving$.pipe(Ue.throttleTime(50)).subscribe(v=>{g(v,!1)});return()=>{E.unsubscribe(),_.unsubscribe()}}},[r,S,h,o,s,i]),m.useEffect(()=>{if(r&&h){const C=new c.DisposableCollection,g=(v,y)=>{var k;let b=0,N=0,T=!1;const M=l.getUnit(e),x=((k=M==null?void 0:M.getActiveSheet())==null?void 0:k.getName())||"",w=S.map(A=>{if(typeof A=="string")return T||(N+=A.length),A;if(A.nodeType===I.sequenceNodeType.REFERENCE){const O=I.deserializeRangeWithSheet(v);if(O.unitId=O.unitId===""?e:O.unitId,O.sheetName=O.sheetName===""?x:O.sheetName,b===y){T=!0;const K={...A,token:v};return o?K.token=I.serializeRangeWithSheet(O.sheetName,O.range):K.token=I.serializeRange(O.range),b++,N+=K.token.length,K}return b++,T||(N+=A.token.length),A}return A}),D=me(w);p.current={result:D,offset:N},i(D,-1,!1)};let E=0;const _=h.selectionMoveEnd$.subscribe(()=>{E=setTimeout(()=>{C.dispose(),h.getSelectionControls().forEach((y,b)=>{C.add(q.merge(y.selectionMoving$,y.selectionScaling$).pipe(q.map(N=>I.serializeRange(N)),q.distinctUntilChanged()).subscribe(N=>{d.current=!0,g(N,b)}))})},30)});return()=>{_.unsubscribe(),C.dispose(),clearTimeout(E)}}},[r,h,S,i])},_t=(r,e,t,n,o,s)=>{const i=c.useDependency(c.ICommandService),a=c.useDependency(ee.IEditorService),d=c.useDependency(z.IRenderManagerService).getRenderById(e),f=d==null?void 0:d.with(exports.RefSelectionsRenderService);m.useEffect(()=>{if(r&&f)if(t){const h=i.onCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){const S=f.getSelectionControls().length;for(let p=1;p<=S;p++)f.clearLastSelection();setTimeout(()=>{s()},30)}});return()=>{h.dispose()}}else{const h=i.beforeCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){n(!1),o(),s();const S=a.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);S==null||S.focus()}});return()=>{h.dispose()}}},[r,f])},rn=r=>!r.some(t=>{if(typeof t=="string"){if(t!==I.matchToken.COMMA)return!0}else if(t.nodeType!==I.sequenceNodeType.REFERENCE)return!0;return!1}),Bn=(r,e,t)=>{const n=m.useRef(!0);m.useEffect(()=>{if(r){const o=setTimeout(()=>{n.current=!1},500);return()=>{clearTimeout(o)}}},[r]),m.useEffect(()=>{if(!n.current&&e){const o=rn(t);e(o,me(t))}},[t,e])},Vn="univer-sheet-range-selector-text-wrap",qn="univer-sheet-range-selector-placeholder",Kn="univer-sheet-range-selector-error",zn="univer-sheet-range-selector-error-wrap",Yn="univer-sheet-range-selector-text",Gn="univer-sheet-range-selector-active",Zn="univer-sheet-range-selector-icon",Xn="univer-sheet-range-selector-dialog-item",Qn="univer-sheet-range-selector-dialog-item-delete",de={sheetRangeSelectorTextWrap:Vn,sheetRangeSelectorPlaceholder:qn,sheetRangeSelectorError:Kn,sheetRangeSelectorErrorWrap:zn,sheetRangeSelectorText:Yn,sheetRangeSelectorActive:Gn,sheetRangeSelectorIcon:Zn,sheetRangeSelectorDialogItem:Xn,sheetRangeSelectorDialogItemDelete:Qn},De=()=>{};function on(r){const{initValue:e,unitId:t,subUnitId:n,errorText:o,placeholder:s,actions:i,onChange:a=De,onVerify:l=De,onRangeSelectorDialogVisibleChange:d=De,onBlur:f=De,onFocus:h=De,isFocus:u=!0,isOnlyOneRange:S=!1,isSupportAcrossSheet:p=!1}=r,C=c.useDependency(ee.IEditorService),g=c.useDependency(c.LocaleService),E=c.useDependency(c.ICommandService),_=c.useDependency(I.LexerTreeBuilder),v=m.useRef(null),[y,b]=m.useState(!1),[N,T]=m.useState(u),M=m.useMemo(()=>c.createInternalEditorID(`${P.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),[x,w]=m.useState(),D=m.useRef(null),k=m.useMemo(()=>!y&&N,[y,N]),[A,O]=m.useState(()=>typeof e=="string"?e:he(e,p).join(I.matchToken.COMMA));i&&(i.handleOutClick=(H,W)=>{v.current&&!y&&!v.current.contains(H.target)&&W()});const K=m.useMemo(()=>A.split(I.matchToken.COMMA).filter(H=>!!H).map(H=>I.deserializeRangeWithSheet(H)),[A]),L=m.useMemo(()=>o!==void 0,[o]),U=en(!y&&N),j=m.useMemo(()=>H=>{const W=_.sequenceNodesBuilder(H);if(W){if(rn(W)){const oe=W.map(be=>{if(typeof be=="string")return be;if(be.nodeType===I.sequenceNodeType.REFERENCE){const It={...be},Oe=I.deserializeRangeWithSheet(be.token);return Oe.range=rt(Oe.range),p||(Oe.sheetName="",Oe.unitId=""),It.token=he([Oe],p)[0],It}return be}),_e=me(oe);a(_e)}}else O("")},[p]),B=zt(x);m.useLayoutEffect(()=>{if(u){const H=setTimeout(()=>{T(u),u&&B()},30);return()=>{clearTimeout(H)}}else U(),T(u),x==null||x.blur()},[u,B]);const{checkScrollBar:Z}=tn(x),ae=nt(),le=m.useMemo(()=>ae(A),[A]),fe=Yt(),X=pt(t),ne=(H,W=!0)=>{if(!x)return;const re=ae(H),oe=fe(x,re,W);X(oe)},ce=qt(le,j,x),pe=m.useMemo(()=>(H,W,re)=>{ne(H),O(H),ce(),re&&(B(),W!==-1&&setTimeout(()=>{const oe={startOffset:W,endOffset:W};x==null||x.setSelectionRanges([oe]);const _e=x==null?void 0:x.render.with(ee.DocBackScrollRenderController);_e==null||_e.scrollToRange({...oe,collapsed:!0})},50),Z())},[x]);nn(k,t,n,le,p,S,pe),vt(k,t),Qt(t,S),jn(t,A,x),Bn(k,l,le),Xt(k,x),Jt(),_t(k,t,p,T,f,()=>{k&&ne(A)}),m.useEffect(()=>{if(x){const H=x.input$.pipe(q.throttleTime(100)).subscribe(W=>{var oe,_e;const re=((_e=(oe=W.data.body)==null?void 0:oe.dataStream)!=null?_e:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");ne(re,!1),O(re),ce()});return()=>{H.unsubscribe()}}},[x]),m.useEffect(()=>{const H=E.onCommandExecuted(W=>{W.id===P.SetCellEditVisibleOperation.id&&(b(!1),d(!1),T(!1),f())});return()=>{H.dispose()}},[p]),m.useLayoutEffect(()=>{let H;if(D.current){H=C.register({autofocus:!0,editorUnitId:M,isSingle:!0,initialSnapshot:{id:M,body:{dataStream:`\r
13
- `},documentStyle:{}}},D.current);const W=C.getEditor(M);w(W)}return()=>{H==null||H.dispose()}},[]),Kt(A,"",N,fe,X,x);const ve=()=>{setTimeout(()=>{h(),B(),T(!0)},30)},Y=H=>{const W=he(H,p).join(I.matchToken.COMMA);W||x==null||x.setDocumentData({...x.getDocumentData(),body:{dataStream:`\r
14
- `,textRuns:[]}}),ne(W),ce(),O(W),b(!1),d(!1),setTimeout(()=>{T(!0),x==null||x.setSelectionRanges([{startOffset:W.length,endOffset:W.length}]),B()},30)},G=()=>{b(!1),d(!1),setTimeout(()=>{T(!0),B()},30)},Q=()=>{L||(B(),setTimeout(()=>{b(!0),d(!0),T(!1)},30))};return R.jsxs("div",{className:de.sheetRangeSelector,ref:v,children:[R.jsxs("div",{className:Vt(de.sheetRangeSelectorTextWrap,{[de.sheetRangeSelectorActive]:N&&!L,[de.sheetRangeSelectorError]:L}),children:[R.jsx("div",{className:de.sheetRangeSelectorText,ref:D,onMouseUp:ve}),R.jsx(ie.Tooltip,{title:g.t("rangeSelector.buttonTooltip"),placement:"bottom",children:R.jsx(Wt,{className:de.sheetRangeSelectorIcon,onClick:Q})}),o!==void 0?R.jsx("div",{className:de.sheetRangeSelectorErrorWrap,children:o}):null,s!==void 0&&!A?R.jsx("div",{className:de.sheetRangeSelectorPlaceholder,children:s}):null]}),y&&R.jsx(Jn,{editorId:M,handleConfirm:Y,handleClose:G,unitId:t,subUnitId:n,initValue:K,visible:y,isOnlyOneRange:S,isSupportAcrossSheet:p})]})}function Jn(r){const{editorId:e,handleConfirm:t,handleClose:n,visible:o,initValue:s,unitId:i,subUnitId:a,isOnlyOneRange:l,isSupportAcrossSheet:d}=r,f=c.useDependency(c.LocaleService),h=c.useDependency(ee.IEditorService),u=c.useDependency(ge.IDescriptionService),S=c.useDependency(I.LexerTreeBuilder),C=c.useDependency(z.IRenderManagerService).getRenderById(i),g=C==null?void 0:C.with(exports.RefSelectionsRenderService),[E,_]=m.useState(()=>{if(l){const L=s[0];return L?he([L],d):[""]}return he(s,d)}),[v,y]=m.useState(()=>E.length-1),b=Gt(),N=m.useMemo(()=>E.join(I.matchToken.COMMA),[E]),T=nt(),M=m.useMemo(()=>T(N),[N]),x=m.useMemo(()=>Zt(u,b,M).refSelections,[M]),w=()=>{_([]),setTimeout(()=>{n()},30)},D=(L,U)=>{U?g==null||g.setSkipLastEnabled(!1):g==null||g.setSkipLastEnabled(!0),_(j=>{const B=[...j];return B[L]=U,B})},k=L=>{g==null||g.setSkipLastEnabled(!1),_(U=>{if(U.length===1)return U;const j=[];return U.forEach((B,Z)=>{L!==Z&&j.push(B)}),j})},A=()=>{g==null||g.setSkipLastEnabled(!0),_(L=>(L.push(""),y(L.length-1),[...L]))},O=m.useCallback(L=>{var j;g==null||g.setSkipLastEnabled(!1);const U=L.split(I.matchToken.COMMA).filter(B=>!!B);_(l?[(j=U[0])!=null?j:""]:U)},[v,l]),K=pt(i);return nn(v>=0,i,a,M,d,l,O),vt(v>=0,i),Qt(i,l),_t(v>=0,i,d,q.noop,q.noop,()=>K(x)),m.useEffect(()=>{K(x)},[x]),m.useEffect(()=>{(E.length===0||E.length===1&&!E[0])&&(g==null||g.setSkipLastEnabled(!0))},[E]),m.useEffect(()=>{const L=h.focusStyle$.pipe(q.filter(U=>!!U&&c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY!==U)).subscribe(U=>{U!==e&&w()});return()=>{L.unsubscribe()}},[h,e]),R.jsx(ie.Dialog,{width:"328px",visible:o,title:f.t("rangeSelector.title"),draggable:!0,closeIcon:R.jsx(tt,{}),footer:R.jsxs("footer",{children:[R.jsx(ie.Button,{onClick:w,children:f.t("rangeSelector.cancel")}),R.jsx(ie.Button,{style:{marginLeft:10},onClick:()=>t(E.filter(L=>{const U=S.sequenceNodesBuilder(L);return U&&U.length===1&&typeof U[0]!="string"&&U[0].nodeType===I.sequenceNodeType.REFERENCE}).map(L=>I.deserializeRangeWithSheet(L)).map(L=>({...L,range:rt(L.range)}))),type:"primary",children:f.t("rangeSelector.confirm")})]}),onClose:w,children:R.jsxs("div",{className:de.sheetRangeSelectorDialog,children:[E.map((L,U)=>R.jsxs("div",{className:de.sheetRangeSelectorDialogItem,children:[R.jsx(ie.Input,{affixWrapperStyle:{width:"100%"},placeholder:f.t("rangeSelector.placeHolder"),onFocus:()=>y(U),value:L,onChange:j=>D(U,j)},`input_${U}`),E.length>1&&!l&&R.jsx($t,{className:de.sheetRangeSelectorDialogItemDelete,onClick:()=>k(U)})]},U)),!l&&R.jsx("div",{children:R.jsxs(ie.Button,{type:"link",size:"small",onClick:A,children:[R.jsx(Ht,{}),R.jsx("span",{children:f.t("rangeSelector.addAnotherRange")})]})})]})})}function er(r,e){return Object.keys(r).filter(t=>isNaN(Number(t))&&t!=="DefinedName").map(t=>({label:e.t(`formula.functionType.${t.toLocaleLowerCase()}`),value:`${r[t]}`}))}function Ct(r){if(!r.require&&!r.repeat)return`[${r.name}]`;if(r.require&&!r.repeat)return r.name;if(!r.require&&r.repeat)return`[${r.name},...]`;if(r.require&&r.repeat)return`${r.name},...`}const tr=(r,e=100)=>{m.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{r(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[r,e])},nr="univer-formula-help-function",rr="univer-formula-help-function-title",or="univer-formula-help-function-title-icons",sr="univer-formula-help-function-title-icon",ir="univer-formula-help-function-content",cr="univer-formula-help-function-content-inner",ar="univer-formula-help-function-content-params",lr="univer-formula-help-function-content-params-title",ur="univer-formula-help-function-content-params-detail",dr="univer-formula-help-function-active",hr="univer-formula-help-decorator",fr="univer-formula-help-param",mr="univer-formula-help-param-prefix",Sr="univer-formula-help-param-item",gr="univer-formula-help-param-active",te={formulaHelpFunction:nr,formulaHelpFunctionTitle:rr,formulaHelpFunctionTitleIcons:or,formulaHelpFunctionTitleIcon:sr,formulaHelpFunctionContent:ir,formulaHelpFunctionContentInner:cr,formulaHelpFunctionContentParams:ar,formulaHelpFunctionContentParamsTitle:lr,formulaHelpFunctionContentParamsDetail:ur,formulaHelpFunctionActive:dr,formulaHelpDecorator:hr,formulaHelpParam:fr,formulaHelpParamPrefix:mr,formulaHelpParamItem:Sr,formulaHelpParamActive:gr},Nt=()=>{};function pr(r){const{functionInfo:e,paramIndex:t,editorId:n,onParamsSwitch:o=Nt,onClose:s=Nt}=r,i=c.useDependency(ee.IEditorService),a=c.useDependency(F.ISidebarService),l=m.useMemo(()=>!!e&&t>=0,[e,t]),[d,f]=m.useState(!0),[h,u]=m.useState([0,0]),S=c.useDependency(c.LocaleService),p=S.t("formula.prompt.required"),C=S.t("formula.prompt.optional");tr(g),m.useEffect(()=>{const _=a.scrollEvent$.pipe(q.throttleTime(100)).subscribe(g);return()=>{_.unsubscribe()}},[]),m.useEffect(()=>{const _=i.getEditor(n);if(!_)return;const v=_.getBoundingClientRect(),{left:y,top:b,height:N}=v;u([y,b+N])},[e,t,n]);function g(){const _=i.getEditor(n);if(!_)return;const v=_.getBoundingClientRect(),{left:y,top:b,height:N}=v;return u([y,b+N]),v}function E(_){o&&o(_)}return R.jsx(ie.Popup,{visible:l,offset:h,children:e?R.jsxs("div",{className:te.formulaHelpFunction,children:[R.jsxs("div",{className:te.formulaHelpFunctionTitle,children:[R.jsx(vr,{prefix:e.functionName,value:e.functionParameter,active:t,onClick:E}),R.jsxs("div",{className:te.formulaHelpFunctionTitleIcons,children:[R.jsx("div",{className:te.formulaHelpFunctionTitleIcon,style:{transform:d?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>f(!d),children:R.jsx(gt,{})}),R.jsx("div",{className:te.formulaHelpFunctionTitleIcon,onClick:s,children:R.jsx(tt,{})})]})]}),R.jsx("div",{className:te.formulaHelpFunctionContent,style:{height:d?"unset":0,padding:d?"revert-layer":0},children:R.jsxs("div",{className:te.formulaHelpFunctionContentInner,children:[R.jsx(it,{title:S.t("formula.prompt.helpExample"),value:`${e.functionName}(${e.functionParameter.map(_=>_.example).join(",")})`}),R.jsx(it,{title:S.t("formula.prompt.helpAbstract"),value:e.description}),e&&e.functionParameter&&e.functionParameter.map((_,v)=>R.jsx(it,{className:t===v?te.formulaHelpFunctionActive:"",title:_.name,value:`${_.require?p:C} ${_.detail}`},v))]})})]}):R.jsx(R.Fragment,{})})}const it=r=>R.jsxs("div",{className:te.formulaHelpFunctionContentParams,children:[R.jsx("div",{className:`
9
+ */var yt;function En(){if(yt)return Ae;yt=1;var r=S,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,l,d){var h,f={},u=null,m=null;d!==void 0&&(u=""+d),l.key!==void 0&&(u=""+l.key),l.ref!==void 0&&(m=l.ref);for(h in l)n.call(l,h)&&!s.hasOwnProperty(h)&&(f[h]=l[h]);if(a&&a.defaultProps)for(h in l=a.defaultProps,l)f[h]===void 0&&(f[h]=l[h]);return{$$typeof:e,type:a,key:u,ref:m,props:f,_owner:o.current}}return Ae.Fragment=t,Ae.jsx=i,Ae.jsxs=i,Ae}var Tt;function yn(){return Tt||(Tt=1,st.exports=En()),st.exports}var R=yn(),ue=function(){return ue=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ue.apply(this,arguments)},Tn=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(r);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(r,n[o])&&(t[n[o]]=r[n[o]]);return t},Ee=S.forwardRef(function(r,e){var t=r.icon,n=r.id,o=r.className,s=r.extend,i=Tn(r,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(n," ").concat(o||"").trim(),l=S.useRef("_".concat(xn()));return kt(t,"".concat(n),{defIds:t.defIds,idSuffix:l.current},ue({ref:e,className:a},i),s)});function kt(r,e,t,n,o){return S.createElement(r.tag,ue(ue({key:e},bn(r,t,o)),n),(Nn(r,t).children||[]).map(function(s,i){return kt(s,"".concat(e,"-").concat(r.tag,"-").concat(i),t,void 0,o)}))}function bn(r,e,t){var n=ue({},r.attrs);t!=null&&t.colorChannel1&&n.fill==="colorChannel1"&&(n.fill=t.colorChannel1);var o=e.defIds;return!o||o.length===0||(r.tag==="use"&&n["xlink:href"]&&(n["xlink:href"]=n["xlink:href"]+e.idSuffix),Object.entries(n).forEach(function(s){var i=s[0],a=s[1];typeof a=="string"&&(n[i]=a.replace(/url\(#(.*)\)/,"url(#$1".concat(e.idSuffix,")")))})),n}function Nn(r,e){var t,n=e.defIds;return!n||n.length===0?r:r.tag==="defs"&&(!((t=r.children)===null||t===void 0)&&t.length)?ue(ue({},r),{children:r.children.map(function(o){return typeof o.attrs.id=="string"&&n&&n.indexOf(o.attrs.id)>-1?ue(ue({},o),{attrs:ue(ue({},o.attrs),{id:o.attrs.id+e.idSuffix})}):o})}):r}function xn(){return Math.random().toString(36).substring(2,8)}Ee.displayName="UniverIcon";var Mn={tag:"svg",attrs:{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"}}]},Ut=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"check-mark-single",ref:e,icon:Mn}))});Ut.displayName="CheckMarkSingle";var Fn={tag:"svg",attrs:{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"}}]},tt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"close-single",ref:e,icon:Fn}))});tt.displayName="CloseSingle";var On={tag:"svg",attrs:{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.866699 5.9313.866699H10.069C10.4004.866699 10.669 1.13533 10.669 1.4667 10.669 1.79807 10.4004 2.0667 10.069 2.0667H5.9313C5.59993 2.0667 5.3313 1.79807 5.3313 1.4667zM1.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.64443 14.8999 3.9758 14.6312 4.24443 14.2999 4.24443H1.69985C1.36848 4.24443 1.09985 3.9758 1.09985 3.64443zM6.12398 8.30171C6.35829 8.0674 6.73819 8.0674 6.97251 8.30171L8.00007 9.32928 9.02764 8.30171C9.26195 8.0674 9.64185 8.0674 9.87617 8.30171 10.1105 8.53603 10.1105 8.91593 9.87617 9.15024L8.8486 10.1778 9.87617 11.2054C10.1105 11.4397 10.1105 11.8196 9.87617 12.0539 9.64185 12.2882 9.26195 12.2882 9.02764 12.0539L8.00007 11.0263 6.97251 12.0539C6.73819 12.2882 6.35829 12.2882 6.12398 12.0539 5.88966 11.8196 5.88966 11.4397 6.12398 11.2054L7.15154 10.1778 6.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"}}]},$t=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"delete-single",ref:e,icon:On}))});$t.displayName="DeleteSingle";var An={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M8.75 5.32495C8.75 5.73916 8.41421 6.07495 8 6.07495 7.58579 6.07495 7.25 5.73916 7.25 5.32495 7.25 4.91074 7.58579 4.57495 8 4.57495 8.41421 4.57495 8.75 4.91074 8.75 5.32495zM8.5999 7.52505C8.5999 7.19368 8.33127 6.92505 7.9999 6.92505 7.66853 6.92505 7.3999 7.19368 7.3999 7.52505V11.425C7.3999 11.7564 7.66853 12.025 7.9999 12.025 8.33127 12.025 8.5999 11.7564 8.5999 11.425V7.52505z"}},{tag:"path",attrs:{fill:"currentColor",d:"M0.899902 8.00002C0.899902 4.0788 4.07868 0.900024 7.9999 0.900024C11.9211 0.900024 15.0999 4.0788 15.0999 8.00002C15.0999 11.9212 11.9211 15.1 7.9999 15.1C4.07868 15.1 0.899902 11.9212 0.899902 8.00002ZM7.9999 2.10002C4.74142 2.10002 2.0999 4.74154 2.0999 8.00002C2.0999 11.2585 4.74142 13.9 7.9999 13.9C11.2584 13.9 13.8999 11.2585 13.8999 8.00002C13.8999 4.74154 11.2584 2.10002 7.9999 2.10002Z",fillRule:"evenodd",clipRule:"evenodd"}}]},jt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"details-single",ref:e,icon:An}))});jt.displayName="DetailsSingle";var Dn={tag:"svg",attrs:{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"}}]},Ht=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"increase-single",ref:e,icon:Dn}))});Ht.displayName="IncreaseSingle";var Pn={tag:"svg",attrs:{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"}}]},gt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"more-single",ref:e,icon:Pn}))});gt.displayName="MoreSingle";var Ln={tag:"svg",attrs:{fill:"none",viewBox:"0 0 16 16",width:"1em",height:"1em"},children:[{tag:"path",attrs:{fill:"currentColor",d:"M12.6185 12.4423C12.5907 12.2749 12.7773 12.15 12.9343 12.2308L15.4242 13.5126C15.6102 13.6084 15.5544 13.8745 15.3439 13.8955L14.2456 14.184L13.4521 15.1286C13.3495 15.2939 13.085 15.2463 13.0534 15.0568L12.6185 12.4423Z"}},{tag:"path",attrs:{fill:"currentColor",d:"M1 3.6C1 2.16406 2.16406 1 3.6 1H12.3C13.7359 1 14.9 2.16406 14.9 3.6V5.81156C14.9003 5.81881 14.9004 5.82609 14.9004 5.8334C14.9004 5.84071 14.9003 5.84799 14.9 5.85524V10.045C14.9003 10.0522 14.9004 10.0595 14.9004 10.0668C14.9004 10.3982 14.6318 10.6668 14.3004 10.6668H11.1668C10.8907 10.6668 10.6668 10.8907 10.6668 11.1668V14.3C10.6668 14.6314 10.3982 14.9 10.0668 14.9L10.05 14.8998L3.6 14.9C2.16406 14.9 1 13.7359 1 12.3V3.6ZM13.2 5.2334C13.4761 5.2334 13.7 5.00954 13.7 4.7334V3.6C13.7 2.8268 13.0732 2.2 12.3 2.2H11.1668C10.8907 2.2 10.6668 2.42386 10.6668 2.7V4.7334C10.6668 5.00954 10.8907 5.2334 11.1668 5.2334H13.2ZM10.6668 6.9334C10.6668 6.65726 10.8907 6.4334 11.1668 6.4334H13.2C13.4761 6.4334 13.7 6.65726 13.7 6.9334V8.9668C13.7 9.24294 13.4761 9.4668 13.2 9.4668H11.1668C10.8907 9.4668 10.6668 9.24294 10.6668 8.9668V6.9334ZM8.9668 5.2334C9.24294 5.2334 9.4668 5.00954 9.4668 4.7334V2.7C9.4668 2.42386 9.24294 2.2 8.9668 2.2H6.9334C6.65726 2.2 6.4334 2.42386 6.4334 2.7V4.7334C6.4334 5.00954 6.65726 5.2334 6.9334 5.2334L8.9668 5.2334ZM6.4334 6.9334C6.4334 6.65726 6.65726 6.4334 6.9334 6.4334L8.9668 6.4334C9.24294 6.4334 9.4668 6.65726 9.4668 6.9334V8.9668C9.4668 9.24294 9.24294 9.4668 8.9668 9.4668L6.9334 9.4668C6.65726 9.4668 6.4334 9.24294 6.4334 8.9668V6.9334ZM4.7334 5.2334C5.00954 5.2334 5.2334 5.00954 5.2334 4.7334V2.7C5.2334 2.42386 5.00954 2.2 4.7334 2.2H3.6C2.8268 2.2 2.2 2.8268 2.2 3.6V4.7334C2.2 5.00954 2.42386 5.2334 2.7 5.2334H4.7334ZM2.2 6.9334C2.2 6.65726 2.42386 6.4334 2.7 6.4334H4.7334C5.00954 6.4334 5.2334 6.65725 5.2334 6.9334V8.9668C5.2334 9.24294 5.00954 9.4668 4.7334 9.4668H2.7C2.42386 9.4668 2.2 9.24294 2.2 8.9668V6.9334ZM5.2334 11.1668C5.2334 10.8907 5.00954 10.6668 4.7334 10.6668H2.7C2.42386 10.6668 2.2 10.8907 2.2 11.1668V12.3C2.2 13.0732 2.8268 13.7 3.6 13.7H4.7334C5.00954 13.7 5.2334 13.4761 5.2334 13.2V11.1668ZM9.4668 11.1668C9.4668 10.8907 9.24294 10.6668 8.9668 10.6668H6.9334C6.65726 10.6668 6.4334 10.8907 6.4334 11.1668V13.2C6.4334 13.4761 6.65726 13.7 6.9334 13.7H8.9668C9.24294 13.7 9.4668 13.4761 9.4668 13.2V11.1668Z",fillRule:"evenodd",clipRule:"evenodd"}}]},Wt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"select-range-single",ref:e,icon:Ln}))});Wt.displayName="SelectRangeSingle";function Bt(r){var e,t,n="";if(typeof r=="string"||typeof r=="number")n+=r;else if(typeof r=="object")if(Array.isArray(r)){var o=r.length;for(e=0;e<o;e++)r[e]&&(t=Bt(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Vt(){for(var r,e,t=0,n="",o=arguments.length;t<o;t++)(r=arguments[t])&&(e=Bt(r))&&(n&&(n+=" "),n+=e);return n}var wn=Object.defineProperty,kn=Object.getOwnPropertyDescriptor,Un=(r,e,t,n)=>{for(var o=n>1?void 0:n?kn(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&wn(e,t,o),o},Ne=(r,e)=>(t,n)=>e(t,n,r);exports.RefSelectionsRenderService=class extends P.BaseSelectionRenderService{constructor(t,n,o,s,i,a,l){super(n,o,s,i,a);V(this,"_workbookSelections");V(this,"_eventDisposables");this._context=t,this._contextService=a,this._refSelectionsService=l,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle($n(this._themeService)),this._remainLastEnabled=!0,this._highlightHeader=!1}getLocation(){return this._skeleton.getLocation()}setRemainLastEnabled(t){this._remainLastEnabled=t}setSkipLastEnabled(t){this._skipLastEnabled=t}clearLastSelection(){const t=this._selectionControls[this._selectionControls.length-1];t&&(t.dispose(),this._selectionControls.pop())}enableSelectionChanging(){return this._disableSelectionChanging(),this._eventDisposables=this._initCanvasEventListeners(),c.toDisposable(()=>this._disableSelectionChanging())}_disableSelectionChanging(){var t;(t=this._eventDisposables)==null||t.dispose(),this._eventDisposables=null}_initCanvasEventListeners(){const t=this._getSheetObject(),{spreadsheetRowHeader:n,spreadsheetColumnHeader:o,spreadsheet:s,spreadsheetLeftTopPlaceholder:i}=t,{scene:a}=this._context,l=new c.DisposableCollection;return l.add(s==null?void 0:s.onPointerDown$.subscribeEvent((d,h)=>{this.inRefSelectionMode()&&(this._onPointerDown(d,s.zIndex+1,c.RANGE_TYPE.NORMAL,this._getActiveViewport(d)),d.button!==2&&h.stopPropagation())})),l.add(n==null?void 0:n.onPointerDown$.subscribeEvent((d,h)=>{if(!this.inRefSelectionMode())return;const f=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:u}=P.getCoordByOffset(d.offsetX,d.offsetY,a,f);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.ROW)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(d),z.ScrollTimerType.Y),d.button!==2&&h.stopPropagation())})),l.add(o==null?void 0:o.onPointerDown$.subscribeEvent((d,h)=>{if(!this.inRefSelectionMode())return;const f=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:u}=P.getCoordByOffset(d.offsetX,d.offsetY,a,f);P.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(d),z.ScrollTimerType.X),d.button!==2&&h.stopPropagation())})),l.add(i==null?void 0:i.onPointerDown$.subscribeEvent((d,h)=>{if(this._reset(),!this.inRefSelectionMode())return;const f=this._sheetSkeletonManagerService.getCurrent().skeleton,u=P.getAllSelection(f);this._addSelectionControlByModelData(u),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const m=a.onPointerUp$.subscribeEvent(()=>{m.unsubscribe(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())});d.button!==2&&h.stopPropagation()})),l}_addSelectionControlByModelData(t){var a;const n=this._skeleton,o=(a=t.style)!=null?a:P.genNormalSelectionStyle(this._themeService),s=this._scene;return t.style=o,this.newSelectionControl(s,n,t)}_initSelectionChangeListener(){this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe(t=>{this._reset(),this._skeleton&&this.resetSelectionsByModelData(t||[])}))}_initUserActionSyncListener(){this.disposeWithMe(this.selectionMoveStart$.subscribe(t=>{this._updateSelections(t,$.SelectionMoveType.MOVE_START)})),this.disposeWithMe(this.selectionMoving$.subscribe(t=>{this._updateSelections(t,$.SelectionMoveType.MOVING)})),this.disposeWithMe(this.selectionMoveEnd$.subscribe(t=>{this._updateSelections(t,$.SelectionMoveType.MOVE_END)}))}_updateSelections(t,n){const s=this._context.unit.getActiveSheet().getSheetId();t.length!==0&&this._workbookSelections.setSelections(s,t.map(i=>$.convertSelectionDataToRange(i)),n)}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{if(!t)return;const{skeleton:n}=t,{scene:o}=this._context,s=o.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);this._skeleton&&this._skeleton.worksheet.getSheetId()!==n.worksheet.getSheetId()&&this._reset(),this._changeRuntime(n,o,s);const i=this._workbookSelections.getCurrentSelections();this.resetSelectionsByModelData(i)}))}_getActiveViewport(t){const n=this._getSheetObject();return n==null?void 0:n.scene.getActiveViewportByCoord(z.Vector2.FromArray([t.offsetX,t.offsetY]))}_getSheetObject(){return P.getSheetObject(this._context.unit,this._context)}_onPointerDown(t,n=0,o=c.RANGE_TYPE.NORMAL,s,i=z.ScrollTimerType.ALL){var D;this._rangeType=o;const a=this._skeleton,l=this._scene;if(!l||!a)return;s&&(this._activeViewport=s);const{offsetX:d,offsetY:h}=t,f=l.getViewport(z.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!f)return;const u=l.getCoordRelativeToViewport(z.Vector2.FromArray([d,h])),{x:m,y:p}=u;this._startViewportPosX=m,this._startViewportPosY=p;const C=l.getScrollXYInfoByViewport(u),{scaleX:g,scaleY:E}=l.getAncestorScale(),v=this._skeleton.getCellByOffset(m,p,g,E,C);if(!v)return;switch(o){case c.RANGE_TYPE.NORMAL:break;case c.RANGE_TYPE.ROW:v.startColumn=0,v.endColumn=this._skeleton.getColumnCount()-1;break;case c.RANGE_TYPE.COLUMN:v.startRow=0,v.endRow=this._skeleton.getRowCount()-1;break;case c.RANGE_TYPE.ALL:v.startRow=0,v.startColumn=0,v.endRow=this._skeleton.getRowCount()-1,v.endColumn=this._skeleton.getColumnCount()-1}const _={range:v,primary:v,style:null};_.range.rangeType=o;const y=P.attachSelectionWithCoord(_,this._skeleton);this._startRangeWhenPointerDown={...y.rangeWithCoord};const b={...y.rangeWithCoord,rangeType:o};let N=this.getActiveSelectionControl();const T=this.getSelectionControls();for(const k of T){if(t.button===2&&k.model.isInclude(b)){N=k;return}if(k.model.isEqual(b)){N=k;break}}this._checkClearPreviousControls(t);const M=N==null?void 0:N.model.currentCell,x=t.shiftKey&&M,w=this._remainLastEnabled&&!t.ctrlKey&&!t.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;x&&M?this._makeSelectionByTwoCells(M,b,a,o,N):w&&N?N.updateRangeBySelectionWithCoord(y):N=this.newSelectionControl(l,a,_);for(let k=0;k<this.getSelectionControls().length-1;k++)this.getSelectionControls()[k].clearHighlight();this._selectionMoveStart$.next(this.getSelectionDataWithStyle()),l.disableObjectsEvent(),this._clearUpdatingListeners(),this._addEndingListeners(),(D=l.getTransformer())==null||D.clearSelectedObjects(),this._setupPointerMoveListener(f,N,o,i,m,p),this._escapeShortcutDisposable=this._shortcutService.forceEscape(),this._scenePointerUpSub=l.onPointerUp$.subscribeEvent(()=>{var k;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(k=this._escapeShortcutDisposable)==null||k.dispose(),this._escapeShortcutDisposable=null})}newSelectionControl(t,n,o){const s=this.getSelectionControls().length,{rowHeaderWidth:i,columnHeaderHeight:a}=n,l=new P.SelectionControl(t,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:a}),d=P.attachSelectionWithCoord(o,n);return l.updateRangeBySelectionWithCoord(d),this._selectionControls.push(l),l.setControlExtension({skeleton:n,scene:t,themeService:this._themeService,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),l}};exports.RefSelectionsRenderService=Un([Ne(1,c.Inject(c.Injector)),Ne(2,c.Inject(c.ThemeService)),Ne(3,F.IShortcutService),Ne(4,c.Inject(P.SheetSkeletonManagerService)),Ne(5,c.IContextService),Ne(6,$.IRefSelectionsService)],exports.RefSelectionsRenderService);function $n(r){const e=P.genNormalSelectionStyle(r);return e.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},e}const jn=(r,e,t)=>{const o=c.useDependency(z.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService);S.useEffect(()=>{if(t&&s){const i=t.input$.subscribe(a=>{a.content===I.matchToken.COMMA?s.setSkipLastEnabled(!0):s.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[t,s]),S.useEffect(()=>{s&&(e.endsWith(I.matchToken.COMMA)||s.setSkipLastEnabled(!1))},[e,s])},me=r=>r.map(e=>typeof e=="string"?e:e.token).join(""),qt=(r,e,t)=>{const n=S.useRef(!1);return S.useEffect(()=>{if(t){const s=t.input$.subscribe(()=>{n.current=!0});return()=>{s.unsubscribe()}}},[t]),S.useEffect(()=>{if(n.current&&r){n.current=!1;const s=me(r);e(s)}},[r]),()=>n.current=!0},nt=()=>{const r=c.useDependency(I.LexerTreeBuilder);return t=>r.sequenceNodesBuilder(t)||[]},Kt=(r,e,t,n,o,s)=>{const i=nt(),a=S.useRef(!0);S.useEffect(()=>{var l,d;if(s){if(a.current){const h=i(r);if(h.length){const f=n(s,h);t&&o(f)}else{const f=s.getDocumentData(),m={dataStream:(d=(l=f.body)==null?void 0:l.dataStream)!=null?d:`${e}\r
10
+ `,...f.body};s.setDocumentData({...f,body:m})}a.current=!1}else if(t){const h=i(r),f=n(s,h);o(f)}}},[s,t])},zt=r=>S.useMemo(()=>()=>{var t,n;if(r){r.focus();const o=[...r.getSelectionRanges()];if(o.length&&r.setSelectionRanges(o),!o.length){const s=(n=(t=r.getDocumentData().body)==null?void 0:t.dataStream)!=null?n:`\r
11
+ `,i=Math.max(s.length-2,0);r.setSelectionRanges([{startOffset:i,endOffset:i}])}}},[r]);function $e(r,e,t){const n=r.getCurrentTheme(),o=new c.ColorKit(e).setAlpha(.05).toRgbString();return{id:t,strokeWidth:1,stroke:e,fill:o,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:n.colorWhite}}function pt(r){const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(c.ThemeService),n=c.useDependency($.IRefSelectionsService),s=c.useDependency(z.IRenderManagerService).getRenderById(r),i=s==null?void 0:s.with(exports.RefSelectionsRenderService),a=s==null?void 0:s.with(P.SheetSkeletonManagerService);return d=>{var E;const h=e.getUnit(r),f=h==null?void 0:h.getActiveSheet(),u=[];if(!h||!f){n.setSelections(u);return}const m=f.getSheetId(),p=v=>{var _;return(_=h==null?void 0:h.getSheetBySheetName(v))==null?void 0:_.getSheetId()};if(!((E=a==null?void 0:a.getWorksheetSkeleton(m))==null?void 0:E.skeleton))return;for(let v=0,_=d.length;v<_;v++){const y=d[v],{themeColor:b,token:N,refIndex:T}=y,M=I.deserializeRangeWithSheet(N),{unitId:x,sheetName:w,range:D}=M;if(x&&r!==x)continue;const k=p(w);if(k&&k!==m)continue;const A=$.setEndForRange(D,f.getRowCount(),f.getColumnCount());u.push({range:A,primary:null,style:$e(t,b,T.toString())})}((i==null?void 0:i.getSelectionControls())||[]).length===u.length?i==null||i.resetSelectionsByModelData(u):n.setSelections(u)}}function Yt(r=""){const e=c.useDependency(ge.IDescriptionService),t=Gt(),n=S.useMemo(()=>r.length,[r]);return(s,i,a=!0)=>{const l=s.getDocumentData();if(!l)return[];if(!l.body)return[];const h={dataStream:"",...l.body};if(i==null||i.length===0){h.textRuns=[];const f={...l,body:h};return s.setDocumentData(f),[]}else{const{textRuns:f,refSelections:u}=Zt(e,t,i);n&&f.forEach(g=>{g.ed=g.ed+n,g.st=g.st+n}),h.textRuns=f;const m=i.reduce((g,E)=>typeof E=="string"?`${g}${E}`:`${g}${E.token}`,"");h.dataStream=`${r}${m}\r
12
+ `;let p;if(a){p=s.getSelectionRanges();const g=h.dataStream.length-2+n;p.forEach(E=>{E.startOffset=Math.max(0,Math.min(E.startOffset,g)),E.endOffset=Math.max(0,Math.min(E.endOffset,g))})}const C={...l,body:h};return s.setDocumentData(C,p),u}}}function Gt(){const e=c.useDependency(c.ThemeService).getCurrentTheme();return S.useMemo(()=>{const n=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],o=e.hyacinth700,s=e.verdancy800;return{formulaRefColors:n,numberColor:o,stringColor:s}},[e])}function Zt(r,e,t){const{formulaRefColors:n,numberColor:o,stringColor:s}=e,i=[],a=[],l=new Map;let d=0;for(let h=0,f=t.length;h<f;h++){const u=t[h];if(typeof u=="string"){const v=i[i.length-1],_=v?v.ed:0,y=_+u.length;i.push({st:_,ed:y});continue}if(r.hasDefinedNameDescription(u.token.trim()))continue;const{startIndex:m,endIndex:p,nodeType:C,token:g}=u;let E="";if(C===I.sequenceNodeType.REFERENCE){if(l.has(g))E=l.get(g);else{const v=d%n.length;E=n[v],l.set(g,E),d++}a.push({refIndex:h,themeColor:E,token:g})}else C===I.sequenceNodeType.NUMBER?E=o:(C===I.sequenceNodeType.STRING||C===I.sequenceNodeType.ARRAY)&&(E=s);E&&E.length>0&&i.push({st:m,ed:p+1,ts:{cl:{rgb:E}}})}return{textRuns:i,refSelections:a}}const Xt=(r,e)=>{const t=c.useDependency(c.ICommandService),n=c.useDependency(F.IShortcutService);S.useEffect(()=>{if(!e||!r)return;const s=`sheet.formula-embedding-editor.${e.getEditorId()}`,i=new c.DisposableCollection,a=l=>{var h;const d=e.getSelectionRanges();if(d.length===1){const f=d[0];switch(l){case F.KeyCode.ARROW_LEFT:{const u=Math.max(f.startOffset-1,0);e.setSelectionRanges([{startOffset:u,endOffset:u}]);break}case F.KeyCode.ARROW_RIGHT:{const u=(((h=e.getDocumentData().body)==null?void 0:h.dataStream)||",,").length-2,m=Math.min(f.endOffset+1,u);e.setSelectionRanges([{startOffset:m,endOffset:m}]);break}}}};return i.add(t.registerCommand({id:s,type:c.CommandType.OPERATION,handler(l,d){const{keyCode:h}=d;a(h)}})),[F.KeyCode.ARROW_LEFT,F.KeyCode.ARROW_RIGHT,F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP].map(l=>({id:s,binding:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:l}})).forEach(l=>{i.add(n.registerShortcut(l))}),()=>{i.dispose()}},[e,r])},Qt=(r,e)=>{const n=c.useDependency(z.IRenderManagerService).getRenderById(r),o=n==null?void 0:n.with(exports.RefSelectionsRenderService);S.useEffect(()=>{o&&(e?o==null||o.setRemainLastEnabled(!1):o==null||o.setRemainLastEnabled(!0))},[e,o])},_t=(r,e)=>{const t=c.useDependency(z.IRenderManagerService),n=c.useDependency(c.IContextService),o=c.useDependency(F.IContextMenuService),s=c.useDependency($.IRefSelectionsService),i=t.getRenderById(e),a=i==null?void 0:i.with(exports.RefSelectionsRenderService);S.useLayoutEffect(()=>{if(r){const l=a==null?void 0:a.enableSelectionChanging();return n.setContextValue($.REF_SELECTIONS_ENABLED,!0),n.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{n.setContextValue(c.EDITOR_ACTIVATED,!1),n.setContextValue($.REF_SELECTIONS_ENABLED,!1),l==null||l.dispose()}}},[r]),S.useLayoutEffect(()=>{if(r)return()=>{s.clear()}},[r]),S.useEffect(()=>{if(r)return o.disable(),()=>{o.enable()}},[r]),S.useEffect(()=>{r&&(a==null||a.setSkipLastEnabled(!1))},[r])},Jt=()=>{S.useEffect(()=>()=>{},[])},en=r=>{const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency($.SheetsSelectionsService);return S.useMemo(()=>{if(r){const o=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),s=o==null?void 0:o.getActiveSheet(),i=[...t.getCurrentSelections()];return()=>{const a=e.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),l=a==null?void 0:a.getActiveSheet();l&&l===s&&t.setSelections(i)}}return()=>{}},[r])},tn=r=>{const e=()=>{if(r){const{scene:n,mainComponent:o}=r.render,s=r.render.with(je.DocSkeletonManagerService),{width:i,height:a}=r.getBoundingClientRect();s.getViewModel().getDataModel().updateDocumentDataPageSize(1/0),n.transformByState({width:i,height:a}),o==null||o.resize(i,a)}},t=S.useMemo(()=>c.debounce(()=>{var p;if(!r)return;const o=r.render.with(je.DocSkeletonManagerService).getSkeleton(),{scene:s,mainComponent:i}=r.render,a=s.getViewport(ee.VIEWPORT_KEY.VIEW_MAIN),{actualWidth:l}=o.getActualSize(),{width:d,height:h}=r.getBoundingClientRect();let f=a==null?void 0:a.getScrollBar();const u=Math.max(l,d),m=h;s.transformByState({width:u,height:m}),i==null||i.resize(u,m),l>d?f==null?a&&new z.ScrollBar(a,{barSize:8,enableVertical:!1}):a==null||a.resetCanvasSizeAndUpdateScroll():(f=null,a==null||a.scrollToBarPos({x:0,y:0}),(p=a==null?void 0:a.getScrollBar())==null||p.dispose())},30),[r]);return S.useEffect(()=>{if(r){const n=setTimeout(()=>{e(),t()},500);return()=>{clearTimeout(n)}}},[r]),S.useEffect(()=>{if(r){const n=r.input$.subscribe(()=>{t()});return()=>{n.unsubscribe()}}},[r]),{resize:e,checkScrollBar:t}},mt=r=>typeof r=="string"?r===I.matchToken.COMMA:!1,Hn=r=>{if(typeof r=="object")return r.nodeType===I.sequenceNodeType.REFERENCE},Wn=r=>r.filter(e=>mt(e)||Hn(e)),rt=r=>{if(r.endColumn<r.startColumn){const e=r.endColumn;r.endColumn=r.startColumn,r.startColumn=e}if(r.endRow<r.startRow){const e=r.endRow;r.endRow=r.startRow,r.startRow=e}return r};function bt(r,e,t){var n,o;return((o=(n=r.getUnit(e))==null?void 0:n.getSheetBySheetId(t))==null?void 0:o.getName())||""}const fe=(r,e=!1)=>e?r.map(t=>t.sheetName!==""?I.serializeRangeWithSheet(t.sheetName,t.range):I.serializeRange(t.range)):r.map(t=>I.serializeRange(t.range)),nn=(r,e,t,n,o,s,i)=>{const a=c.useDependency(z.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=S.useRef(!1),h=a.getRenderById(e),f=h==null?void 0:h.with(exports.RefSelectionsRenderService),u=S.useRef([]),m=S.useMemo(()=>{const C=Wn(n),g=u.current;return C.length===g.length?(g.splice(0),g.push(...C),g):C},[n]);u.current=m;const p=S.useRef();S.useEffect(()=>{if(r&&f){let C=!0;const g=(_,y)=>{var A;if(C||d.current){C=!1;return}const b=[..._],N=l.getUnit(e),T=((A=N==null?void 0:N.getActiveSheet())==null?void 0:A.getName())||"",M=m.map((O,K)=>{if(typeof O=="string"){if(!m[K-1])return null;const U=m[K+1];return mt(O)&&(mt(U)||K===m.length-1)?null:O}else if(O.nodeType===I.sequenceNodeType.REFERENCE){const L=I.deserializeRangeWithSheet(O.token);L.unitId=L.unitId===""?e:L.unitId,L.sheetName=L.sheetName===""?T:L.sheetName;const{unitId:U,sheetName:j}=L;if(s&&(U!==e||T!==j))return null;if(U===e&&T===j){const B=b.shift();if(B&&bt(l,e,B.rangeWithCoord.sheetId||"")===j){const Z={...O};return rt(B.rangeWithCoord),o?Z.token=I.serializeRangeWithSheet(T,B.rangeWithCoord):Z.token=I.serializeRange(B.rangeWithCoord),Z}}return O}return null}).filter(O=>!!O),x=fe(b.map(O=>{var K,L,U;return{range:O.rangeWithCoord,unitId:(K=O.rangeWithCoord.unitId)!=null?K:"",sheetName:bt(l,(L=O.rangeWithCoord.unitId)!=null?L:"",(U=O.rangeWithCoord.sheetId)!=null?U:"")}}),o).join(I.matchToken.COMMA),w=me(M),D=`${w}${w&&x?I.matchToken.COMMA:""}${x}`,k=d.current;i(D,k?-1:D.length,y)},E=f.selectionMoveEnd$.subscribe(_=>{if(g(_,!0),d.current=!1,p.current){const{result:y,offset:b}=p.current;i(y,b,!0),p.current=void 0}}),v=f.selectionMoving$.pipe(Ue.throttleTime(50)).subscribe(_=>{g(_,!1)});return()=>{E.unsubscribe(),v.unsubscribe()}}},[r,m,f,o,s,i]),S.useEffect(()=>{if(r&&f){const C=new c.DisposableCollection,g=(_,y)=>{var k;let b=0,N=0,T=!1;const M=l.getUnit(e),x=((k=M==null?void 0:M.getActiveSheet())==null?void 0:k.getName())||"",w=m.map(A=>{if(typeof A=="string")return T||(N+=A.length),A;if(A.nodeType===I.sequenceNodeType.REFERENCE){const O=I.deserializeRangeWithSheet(_);if(O.unitId=O.unitId===""?e:O.unitId,O.sheetName=O.sheetName===""?x:O.sheetName,b===y){T=!0;const K={...A,token:_};return o?K.token=I.serializeRangeWithSheet(O.sheetName,O.range):K.token=I.serializeRange(O.range),b++,N+=K.token.length,K}return b++,T||(N+=A.token.length),A}return A}),D=me(w);p.current={result:D,offset:N},i(D,-1,!1)};let E=0;const v=f.selectionMoveEnd$.subscribe(()=>{E=setTimeout(()=>{C.dispose(),f.getSelectionControls().forEach((y,b)=>{C.add(q.merge(y.selectionMoving$,y.selectionScaling$).pipe(q.map(N=>I.serializeRange(N)),q.distinctUntilChanged()).subscribe(N=>{d.current=!0,g(N,b)}))})},30)});return()=>{v.unsubscribe(),C.dispose(),clearTimeout(E)}}},[r,f,m,i])},vt=(r,e,t,n,o,s)=>{const i=c.useDependency(c.ICommandService),a=c.useDependency(ee.IEditorService),d=c.useDependency(z.IRenderManagerService).getRenderById(e),h=d==null?void 0:d.with(exports.RefSelectionsRenderService);S.useEffect(()=>{if(r&&h)if(t){const f=i.onCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){const m=h.getSelectionControls().length;for(let p=1;p<=m;p++)h.clearLastSelection();setTimeout(()=>{s()},30)}});return()=>{f.dispose()}}else{const f=i.beforeCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){n(!1),o(),s();const m=a.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);m==null||m.focus()}});return()=>{f.dispose()}}},[r,h])},rn=r=>!r.some(t=>{if(typeof t=="string"){if(t!==I.matchToken.COMMA)return!0}else if(t.nodeType!==I.sequenceNodeType.REFERENCE)return!0;return!1}),Bn=(r,e,t)=>{const n=S.useRef(!0);S.useEffect(()=>{if(r){const o=setTimeout(()=>{n.current=!1},500);return()=>{clearTimeout(o)}}},[r]),S.useEffect(()=>{if(!n.current&&e){const o=rn(t);e(o,me(t))}},[t,e])},Vn="univer-sheet-range-selector-text-wrap",qn="univer-sheet-range-selector-placeholder",Kn="univer-sheet-range-selector-error",zn="univer-sheet-range-selector-error-wrap",Yn="univer-sheet-range-selector-text",Gn="univer-sheet-range-selector-active",Zn="univer-sheet-range-selector-icon",Xn="univer-sheet-range-selector-dialog-item",Qn="univer-sheet-range-selector-dialog-item-delete",de={sheetRangeSelectorTextWrap:Vn,sheetRangeSelectorPlaceholder:qn,sheetRangeSelectorError:Kn,sheetRangeSelectorErrorWrap:zn,sheetRangeSelectorText:Yn,sheetRangeSelectorActive:Gn,sheetRangeSelectorIcon:Zn,sheetRangeSelectorDialogItem:Xn,sheetRangeSelectorDialogItemDelete:Qn},De=()=>{};function on(r){const{initValue:e,unitId:t,subUnitId:n,errorText:o,placeholder:s,actions:i,onChange:a=De,onVerify:l=De,onRangeSelectorDialogVisibleChange:d=De,onBlur:h=De,onFocus:f=De,isFocus:u=!0,isOnlyOneRange:m=!1,isSupportAcrossSheet:p=!1}=r,C=c.useDependency(ee.IEditorService),g=c.useDependency(c.LocaleService),E=c.useDependency(c.ICommandService),v=c.useDependency(I.LexerTreeBuilder),_=S.useRef(null),[y,b]=S.useState(!1),[N,T]=S.useState(u),M=S.useMemo(()=>c.createInternalEditorID(`${P.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),[x,w]=S.useState(),D=S.useRef(null),k=S.useMemo(()=>!y&&N,[y,N]),[A,O]=S.useState(()=>typeof e=="string"?e:fe(e,p).join(I.matchToken.COMMA));i&&(i.handleOutClick=(H,W)=>{_.current&&!y&&!_.current.contains(H.target)&&W()});const K=S.useMemo(()=>A.split(I.matchToken.COMMA).filter(H=>!!H).map(H=>I.deserializeRangeWithSheet(H)),[A]),L=S.useMemo(()=>o!==void 0,[o]),U=en(!y&&N),j=S.useMemo(()=>H=>{const W=v.sequenceNodesBuilder(H);if(W){if(rn(W)){const oe=W.map(be=>{if(typeof be=="string")return be;if(be.nodeType===I.sequenceNodeType.REFERENCE){const It={...be},Oe=I.deserializeRangeWithSheet(be.token);return Oe.range=rt(Oe.range),p||(Oe.sheetName="",Oe.unitId=""),It.token=fe([Oe],p)[0],It}return be}),ve=me(oe);a(ve)}}else O("")},[p]),B=zt(x);S.useLayoutEffect(()=>{if(u){const H=setTimeout(()=>{T(u),u&&B()},30);return()=>{clearTimeout(H)}}else U(),T(u),x==null||x.blur()},[u,B]);const{checkScrollBar:Z}=tn(x),ae=nt(),le=S.useMemo(()=>ae(A),[A]),he=Yt(),X=pt(t),ne=(H,W=!0)=>{if(!x)return;const re=ae(H),oe=he(x,re,W);X(oe)},ce=qt(le,j,x),pe=S.useMemo(()=>(H,W,re)=>{ne(H),O(H),ce(),re&&(B(),W!==-1&&setTimeout(()=>{const oe={startOffset:W,endOffset:W};x==null||x.setSelectionRanges([oe]);const ve=x==null?void 0:x.render.with(ee.DocBackScrollRenderController);ve==null||ve.scrollToRange({...oe,collapsed:!0})},50),Z())},[x]);nn(k,t,n,le,p,m,pe),_t(k,t),Qt(t,m),jn(t,A,x),Bn(k,l,le),Xt(k,x),Jt(),vt(k,t,p,T,h,()=>{k&&ne(A)}),S.useEffect(()=>{if(x){const H=x.input$.pipe(q.throttleTime(100)).subscribe(W=>{var oe,ve;const re=((ve=(oe=W.data.body)==null?void 0:oe.dataStream)!=null?ve:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");ne(re,!1),O(re),ce()});return()=>{H.unsubscribe()}}},[x]),S.useEffect(()=>{const H=E.onCommandExecuted(W=>{W.id===P.SetCellEditVisibleOperation.id&&(b(!1),d(!1),T(!1),h())});return()=>{H.dispose()}},[p]),S.useLayoutEffect(()=>{let H;if(D.current){H=C.register({autofocus:!0,editorUnitId:M,isSingle:!0,initialSnapshot:{id:M,body:{dataStream:`\r
13
+ `},documentStyle:{}}},D.current);const W=C.getEditor(M);w(W)}return()=>{H==null||H.dispose()}},[]),Kt(A,"",N,he,X,x);const _e=()=>{setTimeout(()=>{f(),B(),T(!0)},30)},Y=H=>{const W=fe(H,p).join(I.matchToken.COMMA);W||x==null||x.setDocumentData({...x.getDocumentData(),body:{dataStream:`\r
14
+ `,textRuns:[]}}),ne(W),ce(),O(W),b(!1),d(!1),setTimeout(()=>{T(!0),x==null||x.setSelectionRanges([{startOffset:W.length,endOffset:W.length}]),B()},30)},G=()=>{b(!1),d(!1),setTimeout(()=>{T(!0),B()},30)},Q=()=>{L||(B(),setTimeout(()=>{b(!0),d(!0),T(!1)},30))};return R.jsxs("div",{className:de.sheetRangeSelector,ref:_,children:[R.jsxs("div",{className:Vt(de.sheetRangeSelectorTextWrap,{[de.sheetRangeSelectorActive]:N&&!L,[de.sheetRangeSelectorError]:L}),children:[R.jsx("div",{className:de.sheetRangeSelectorText,ref:D,onMouseUp:_e}),R.jsx(ie.Tooltip,{title:g.t("rangeSelector.buttonTooltip"),placement:"bottom",children:R.jsx(Wt,{className:de.sheetRangeSelectorIcon,onClick:Q})}),o!==void 0?R.jsx("div",{className:de.sheetRangeSelectorErrorWrap,children:o}):null,s!==void 0&&!A?R.jsx("div",{className:de.sheetRangeSelectorPlaceholder,children:s}):null]}),y&&R.jsx(Jn,{editorId:M,handleConfirm:Y,handleClose:G,unitId:t,subUnitId:n,initValue:K,visible:y,isOnlyOneRange:m,isSupportAcrossSheet:p})]})}function Jn(r){const{editorId:e,handleConfirm:t,handleClose:n,visible:o,initValue:s,unitId:i,subUnitId:a,isOnlyOneRange:l,isSupportAcrossSheet:d}=r,h=c.useDependency(c.LocaleService),f=c.useDependency(ee.IEditorService),u=c.useDependency(ge.IDescriptionService),m=c.useDependency(I.LexerTreeBuilder),C=c.useDependency(z.IRenderManagerService).getRenderById(i),g=C==null?void 0:C.with(exports.RefSelectionsRenderService),[E,v]=S.useState(()=>{if(l){const L=s[0];return L?fe([L],d):[""]}return fe(s,d)}),[_,y]=S.useState(()=>E.length-1),b=Gt(),N=S.useMemo(()=>E.join(I.matchToken.COMMA),[E]),T=nt(),M=S.useMemo(()=>T(N),[N]),x=S.useMemo(()=>Zt(u,b,M).refSelections,[M]),w=()=>{v([]),setTimeout(()=>{n()},30)},D=(L,U)=>{U?g==null||g.setSkipLastEnabled(!1):g==null||g.setSkipLastEnabled(!0),v(j=>{const B=[...j];return B[L]=U,B})},k=L=>{g==null||g.setSkipLastEnabled(!1),v(U=>{if(U.length===1)return U;const j=[];return U.forEach((B,Z)=>{L!==Z&&j.push(B)}),j})},A=()=>{g==null||g.setSkipLastEnabled(!0),v(L=>(L.push(""),y(L.length-1),[...L]))},O=S.useCallback(L=>{var j;g==null||g.setSkipLastEnabled(!1);const U=L.split(I.matchToken.COMMA).filter(B=>!!B);v(l?[(j=U[0])!=null?j:""]:U)},[_,l]),K=pt(i);return nn(_>=0,i,a,M,d,l,O),_t(_>=0,i),Qt(i,l),vt(_>=0,i,d,q.noop,q.noop,()=>K(x)),S.useEffect(()=>{K(x)},[x]),S.useEffect(()=>{(E.length===0||E.length===1&&!E[0])&&(g==null||g.setSkipLastEnabled(!0))},[E]),S.useEffect(()=>{const L=f.focusStyle$.pipe(q.filter(U=>!!U&&c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY!==U)).subscribe(U=>{U!==e&&w()});return()=>{L.unsubscribe()}},[f,e]),R.jsx(ie.Dialog,{width:"328px",visible:o,title:h.t("rangeSelector.title"),draggable:!0,closeIcon:R.jsx(tt,{}),footer:R.jsxs("footer",{children:[R.jsx(ie.Button,{onClick:w,children:h.t("rangeSelector.cancel")}),R.jsx(ie.Button,{style:{marginLeft:10},onClick:()=>t(E.filter(L=>{const U=m.sequenceNodesBuilder(L);return U&&U.length===1&&typeof U[0]!="string"&&U[0].nodeType===I.sequenceNodeType.REFERENCE}).map(L=>I.deserializeRangeWithSheet(L)).map(L=>({...L,range:rt(L.range)}))),type:"primary",children:h.t("rangeSelector.confirm")})]}),onClose:w,children:R.jsxs("div",{className:de.sheetRangeSelectorDialog,children:[E.map((L,U)=>R.jsxs("div",{className:de.sheetRangeSelectorDialogItem,children:[R.jsx(ie.Input,{affixWrapperStyle:{width:"100%"},placeholder:h.t("rangeSelector.placeHolder"),onFocus:()=>y(U),value:L,onChange:j=>D(U,j)},`input_${U}`),E.length>1&&!l&&R.jsx($t,{className:de.sheetRangeSelectorDialogItemDelete,onClick:()=>k(U)})]},U)),!l&&R.jsx("div",{children:R.jsxs(ie.Button,{type:"link",size:"small",onClick:A,children:[R.jsx(Ht,{}),R.jsx("span",{children:h.t("rangeSelector.addAnotherRange")})]})})]})})}function er(r,e){return Object.keys(r).filter(t=>isNaN(Number(t))&&t!=="DefinedName").map(t=>({label:e.t(`formula.functionType.${t.toLocaleLowerCase()}`),value:`${r[t]}`}))}function Ct(r){if(!r.require&&!r.repeat)return`[${r.name}]`;if(r.require&&!r.repeat)return r.name;if(!r.require&&r.repeat)return`[${r.name},...]`;if(r.require&&r.repeat)return`${r.name},...`}const tr=(r,e=100)=>{S.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{r(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[r,e])},nr="univer-formula-help-function",rr="univer-formula-help-function-title",or="univer-formula-help-function-title-icons",sr="univer-formula-help-function-title-icon",ir="univer-formula-help-function-content",cr="univer-formula-help-function-content-inner",ar="univer-formula-help-function-content-params",lr="univer-formula-help-function-content-params-title",ur="univer-formula-help-function-content-params-detail",dr="univer-formula-help-function-active",fr="univer-formula-help-decorator",hr="univer-formula-help-param",mr="univer-formula-help-param-prefix",Sr="univer-formula-help-param-item",gr="univer-formula-help-param-active",te={formulaHelpFunction:nr,formulaHelpFunctionTitle:rr,formulaHelpFunctionTitleIcons:or,formulaHelpFunctionTitleIcon:sr,formulaHelpFunctionContent:ir,formulaHelpFunctionContentInner:cr,formulaHelpFunctionContentParams:ar,formulaHelpFunctionContentParamsTitle:lr,formulaHelpFunctionContentParamsDetail:ur,formulaHelpFunctionActive:dr,formulaHelpDecorator:fr,formulaHelpParam:hr,formulaHelpParamPrefix:mr,formulaHelpParamItem:Sr,formulaHelpParamActive:gr},Nt=()=>{};function pr(r){const{functionInfo:e,paramIndex:t,editorId:n,onParamsSwitch:o=Nt,onClose:s=Nt}=r,i=c.useDependency(ee.IEditorService),a=c.useDependency(F.ISidebarService),l=S.useMemo(()=>!!e&&t>=0,[e,t]),[d,h]=S.useState(!0),[f,u]=S.useState([0,0]),m=c.useDependency(c.LocaleService),p=m.t("formula.prompt.required"),C=m.t("formula.prompt.optional");tr(g),S.useEffect(()=>{const v=a.scrollEvent$.pipe(q.throttleTime(100)).subscribe(g);return()=>{v.unsubscribe()}},[]),S.useEffect(()=>{const v=i.getEditor(n);if(!v)return;const _=v.getBoundingClientRect(),{left:y,top:b,height:N}=_;u([y,b+N])},[e,t,n]);function g(){const v=i.getEditor(n);if(!v)return;const _=v.getBoundingClientRect(),{left:y,top:b,height:N}=_;return u([y,b+N]),_}function E(v){o&&o(v)}return R.jsx(ie.Popup,{visible:l,offset:f,children:e?R.jsxs("div",{className:te.formulaHelpFunction,children:[R.jsxs("div",{className:te.formulaHelpFunctionTitle,children:[R.jsx(_r,{prefix:e.functionName,value:e.functionParameter,active:t,onClick:E}),R.jsxs("div",{className:te.formulaHelpFunctionTitleIcons,children:[R.jsx("div",{className:te.formulaHelpFunctionTitleIcon,style:{transform:d?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>h(!d),children:R.jsx(gt,{})}),R.jsx("div",{className:te.formulaHelpFunctionTitleIcon,onClick:s,children:R.jsx(tt,{})})]})]}),R.jsx("div",{className:te.formulaHelpFunctionContent,style:{height:d?"unset":0,padding:d?"revert-layer":0},children:R.jsxs("div",{className:te.formulaHelpFunctionContentInner,children:[R.jsx(it,{title:m.t("formula.prompt.helpExample"),value:`${e.functionName}(${e.functionParameter.map(v=>v.example).join(",")})`}),R.jsx(it,{title:m.t("formula.prompt.helpAbstract"),value:e.description}),e&&e.functionParameter&&e.functionParameter.map((v,_)=>R.jsx(it,{className:t===_?te.formulaHelpFunctionActive:"",title:v.name,value:`${v.require?p:C} ${v.detail}`},_))]})})]}):R.jsx(R.Fragment,{})})}const it=r=>R.jsxs("div",{className:te.formulaHelpFunctionContentParams,children:[R.jsx("div",{className:`
15
15
  ${te.formulaHelpFunctionContentParamsTitle}
16
16
  ${r.className}
17
- `,children:r.title}),R.jsx("div",{className:te.formulaHelpFunctionContentParamsDetail,children:r.value})]}),vr=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return R.jsxs("div",{className:te.formulaHelpParam,children:[R.jsxs("span",{className:te.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>R.jsxs("span",{className:te.formulaHelpParamItem,children:[R.jsx("span",{className:n===i?te.formulaHelpFunctionActive:te.formulaHelpParamActive,onClick:()=>o(i),children:Ct(s)}),i===t.length-1?"":","]},i)),")"]})},Me=r=>{const e=m.useRef();return e.current=r,e},_r=(r,e,t)=>{const n=c.useDependency(ge.IDescriptionService),o=c.useDependency(I.LexerTreeBuilder),[s,i]=m.useState(),[a,l]=m.useState(-1),[d,f]=m.useState(!0),h=Me(d),u=m.useRef(e);u.current=e;const S=()=>{i(void 0),l(-1),f(!1)};return m.useEffect(()=>{if(t&&r){const p=t.selectionChange$.pipe(q.debounceTime(50)).subscribe(g=>{if(g.textRanges.length===1){const[E]=g.textRanges;if(E.collapsed&&h.current){const _=o.getFunctionAndParameter(u.current,E.startOffset-1);if(_){const{functionName:v,paramIndex:y}=_,b=n.getFunctionInfo(v);i(b),l(y);return}}}i(void 0),l(-1)}),C=t.selectionChange$.pipe(q.filter(g=>g.isEditing),q.filter(g=>g.textRanges.length===1),q.map(g=>g.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{f(!0)});return()=>{p.unsubscribe(),C.unsubscribe()}}},[t,r]),m.useEffect(()=>{r||S()},[r]),{functionInfo:s,paramIndex:a,reset:S}},Ve=(r,e,t=!0)=>{let n=-1;return r.reduce((o,s,i)=>{if(o.isFinish)return o;const a=o.currentIndex;if(typeof s!="string")o.currentIndex+=s.token.length;else{const l=s.length;o.currentIndex+=l}return(t?o.currentIndex===e:e>a&&e<=o.currentIndex)&&(n=i,o.isFinish=!0),o},{currentIndex:0,isFinish:!1}),n},Cr=(r,e=[],t)=>{const n=c.useDependency(ge.IDescriptionService),[o,s]=m.useState([]),[i,a]=m.useState(""),l=m.useRef(-1),d=Me({nodes:e}),f=()=>{s([]),a(""),l.current=-1};return m.useEffect(()=>{if(t&&r){const u=t.input$.pipe(q.debounceTime(300)).subscribe(()=>{const S=t.getSelectionRanges();if(S.length===1){const p=d.current.nodes,C=S[0];if(C.collapsed){const g=Ve(p,C.startOffset-1,!1);l.current=g;const E=p[g];if(E&&typeof E!="string"&&E.nodeType===I.sequenceNodeType.FUNCTION){l.current=g;const _=E.token,v=n.getSearchListByNameFirstLetter(_);s(v),a(_);return}}}l.current=-1,a(""),s(p=>p!=null&&p.length?[]:p)});return()=>{u.unsubscribe()}}},[t,r]),m.useEffect(()=>{r||f()},[r]),{searchList:o,searchText:i,handlerFormulaReplace:u=>{const S=[...d.current.nodes];if(l.current!==-1){const p=S.splice(l.current+1),C=S.pop()||"";let g=(typeof C=="string"?C.length:C.token.length)-u.length;return S.push(u),p[0]!==I.matchToken.OPEN_BRACKET&&(S.push(I.matchToken.OPEN_BRACKET),g--),{text:me([...S,...p]),offset:g}}},reset:f}},Rr=r=>r.reduce((e,t)=>typeof t=="string"?e+t.length:e+t.token.length,0),Ir=(r,e=300)=>{let t=r,n=0;const o=()=>t,s=a=>{clearTimeout(n),t=a};function i(){clearTimeout(n),n=setTimeout(()=>{t=r},e)}return{getValue:o,setValue:s,reset:i}},Rt=[I.compareToken.EQUALS,I.compareToken.GREATER_THAN,I.compareToken.GREATER_THAN_OR_EQUAL,I.compareToken.LESS_THAN,I.compareToken.LESS_THAN_OR_EQUAL,I.compareToken.NOT_EQUAL,I.operatorToken.CONCATENATE,I.operatorToken.DIVIDED,I.operatorToken.MINUS,I.operatorToken.MULTIPLY,I.operatorToken.PLUS,I.operatorToken.POWER,I.matchToken.COMMA],xt=[...Rt,I.matchToken.COLON,I.matchToken.OPEN_BRACKET],Er=[...Rt,I.matchToken.CLOSE_BRACKET],ct=r=>typeof r=="string"?r:r.token,yr=(r,e,t)=>{const o=c.useDependency(z.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService),i=m.useRef(!1),a=Me(e),l=m.useMemo(()=>Ir(!1,300),[]),d=h=>{s&&s.setSkipLastEnabled(h),i.current=h},f=()=>i.current;return m.useEffect(()=>{if(t&&s){const h=t.input$.subscribe(S=>{const p=S.content;p.length===1&&xt.includes(p)?(d(!0),l.setValue(!0),l.reset()):(d(!1),l.setValue(!1))}),u=t.selectionChange$.pipe(q.debounceTime(100)).subscribe(S=>{if(l.getValue())return;const p=S.textRanges;if(!p.length)return;if(p.length!==1){d(!1);return}const C=p[0];if(!C.collapsed){d(!1);return}const g=a.current;if(!g.length){d(!0);return}const E=C.startOffset-1;if(E===0){const T=Ve(g,1,!1),M=g[T]||"",x=ct(M);if(Rt.includes(x)){d(!0);return}}const _=Ve(g,E,!1),v=g[_];if(!v){d(!1);return}const y=g[_+1]||"",b=ct(y),N=ct(v);xt.includes(N)&&(!y||Er.includes(b))?d(!0):d(!1)});return s.selectionMoveEnd$.subscribe(()=>{Promise.resolve().then(()=>{d(!1)})}),()=>{h.unsubscribe(),u.unsubscribe()}}},[t,s]),{setIsAddSelection:d,getIsNeedAddSelection:f,isLockSelectionEvent:l}},Tr=()=>{},br=(r,e,t,n,o,s,i=Tr)=>{const a=c.useDependency(z.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=Me(n),{getIsNeedAddSelection:f}=yr(e,n,s),h=l.getUnit(e),u=y=>{var b,N;return(N=(b=h==null?void 0:h.getSheetBySheetId(y))==null?void 0:b.getName())!=null?N:""},S=m.useMemo(()=>u(t),[t]),p=c.useObservable(h==null?void 0:h.activeSheet$),C=Me({activeSheet:p,sheetName:S}),g=a.getRenderById(e),E=g==null?void 0:g.with(exports.RefSelectionsRenderService),_=m.useRef(!1),v=m.useRef();m.useEffect(()=>{if(E&&r){let y=!0;const b=T=>{var k,A,O,K,L,U;if(y||_.current){y=!1;return}const M=s==null?void 0:s.getSelectionRanges();if((M==null?void 0:M.length)!==1)return;const w=M[0].startOffset-1,D=[...d.current];if(f())if(w!==0){const j=Ve(D,w,!1);if(j===-1&&D.length)return;const B=T[T.length-1],Z=D.splice(j+1),ae=(k=B.rangeWithCoord.sheetId)!=null?k:t,le={range:B.rangeWithCoord,unitId:(A=B.rangeWithCoord.unitId)!=null?A:e,sheetName:u(ae)},X=he([le],o&&ae!==t);D.push({token:X[0],nodeType:I.sequenceNodeType.REFERENCE});const ne=[...D,...Z],ce=me(ne);i(ce,Rr(D),!0)}else{const j=T[T.length-1],B=(O=j.rangeWithCoord.sheetId)!=null?O:t,Z={range:j.rangeWithCoord,unitId:(K=j.rangeWithCoord.unitId)!=null?K:e,sheetName:u(B)},le=he([Z],o&&B!==t);D.unshift({token:le[0],nodeType:I.sequenceNodeType.REFERENCE});const fe=me(D);i(fe,le[0].length,!0)}else{let j=0;const B=D.map(X=>{var ne,ce,pe;if(typeof X=="string")return X;if(X.nodeType===I.sequenceNodeType.REFERENCE){const ve=I.deserializeRangeWithSheet(X.token);if(ve.sheetName||(ve.sheetName=S),o&&((ne=C.current.activeSheet)==null?void 0:ne.getName())!==ve.sheetName)return X.token;const Y=T[j];if(j++,!Y)return"";const G=(ce=Y.rangeWithCoord.sheetId)!=null?ce:t,Q={range:Y.rangeWithCoord,unitId:(pe=Y.rangeWithCoord.unitId)!=null?pe:e,sheetName:u(G)};return he([Q],o)[0]}return X.token}).join(""),Z=[];for(let X=j;X<=T.length-1;X++){const ne=T[X],ce=(L=ne.rangeWithCoord.sheetId)!=null?L:t,pe={range:ne.rangeWithCoord,unitId:(U=ne.rangeWithCoord.unitId)!=null?U:e,sheetName:u(ce)},Y=he([pe],o&&ce!==t);Z.push(Y[0])}const ae=D[D.length-1],le=ae&&(typeof ae=="string"?!1:ae.nodeType===I.sequenceNodeType.REFERENCE),fe=`${B}${Z.length&&le?",":""}${Z.join(",")}`;i(fe,fe.length,!0)}},N=E.selectionMoveEnd$.subscribe(T=>{if(b(T),_.current=!1,v.current){const{result:M,offset:x}=v.current;i(M,x||-1,!0),v.current=void 0}});return()=>{N.unsubscribe()}}},[E,s,o,r]),m.useEffect(()=>{if(r&&E&&s){const y=new c.DisposableCollection,b=(M,x)=>{let w=0,D=0,k=!1;const{sheetName:A}=C.current,O=d.current.map(L=>{var U;if(typeof L=="string")return k||(D+=L.length),L;if(L.nodeType===I.sequenceNodeType.REFERENCE){const j=I.deserializeRangeWithSheet(L.token);if(j.unitId||(j.unitId=e),j.sheetName||(j.sheetName=A),o&&((U=C.current.activeSheet)==null?void 0:U.getName())!==j.sheetName)return k||(D+=L.token.length),L;if(w===x){k=!0;const B={...L,token:M};return o&&j.sheetName!==A?B.token=I.serializeRangeWithSheet(j.sheetName,I.deserializeRangeWithSheet(M).range):B.token=M,D+=B.token.length,w++,B}return k||(D+=L.token.length),w++,L}return k||(D+=L.token.length),L}),K=me(O);i(K,-1,!1),v.current={result:K,offset:D}},N=()=>{y.dispose(),E.getSelectionControls().forEach((x,w)=>{y.add(q.merge(x.selectionMoving$,x.selectionScaling$).pipe(Ue.map(D=>I.serializeRange(D)),Ue.distinctUntilChanged()).subscribe(D=>{_.current=!0,b(D,w)}))})},T=q.merge(s.input$,E.selectionMoveEnd$).pipe(Ue.debounceTime(50)).subscribe(()=>{N()});return()=>{T.unsubscribe(),y.dispose()}}},[r,E,s])},Nr=(r,e,t)=>{const n=c.useDependency(I.LexerTreeBuilder),o=m.useRef(!0);m.useEffect(()=>{if(r){const s=setTimeout(()=>{o.current=!1},500);return()=>{clearTimeout(s)}}},[r]),m.useEffect(()=>{if(!o.current&&e){const s=n.checkIfAddBracket(t);e(s===0&&t.startsWith(I.operatorToken.EQUALS),`${t}`)}},[t,e])},xr="univer-sheet-embedding-formula-editor-active",Mr="univer-sheet-embedding-formula-editor-wrap",Fr="univer-sheet-embedding-formula-editor-text",Or="univer-sheet-embedding-formula-editor-error-wrap",Ar="univer-sheet-embedding-formula-editor-error",xe={sheetEmbeddingFormulaEditorActive:xr,sheetEmbeddingFormulaEditorWrap:Mr,sheetEmbeddingFormulaEditorText:Fr,sheetEmbeddingFormulaEditorErrorWrap:Or,sheetEmbeddingFormulaEditorError:Ar},Dr="univer-formula-search-function",Pr="univer-formula-search-function-item",Lr="univer-formula-search-function-item-name",wr="univer-formula-search-function-item-name-light",kr="univer-formula-search-function-item-desc",Ur="univer-formula-search-function-item-active",Ce={formulaSearchFunction:Dr,formulaSearchFunctionItem:Pr,formulaSearchFunctionItemName:Lr,formulaSearchFunctionItemNameLight:wr,formulaSearchFunctionItemDesc:kr,formulaSearchFunctionItemActive:Ur},$r=()=>{},jr=m.forwardRef(Hr);function Hr(r,e){const{searchText:t,searchList:n,onSelect:o,editorId:s,onClose:i=$r}=r,a=c.useDependency(ee.IEditorService),l=c.useDependency(F.IShortcutService),d=c.useDependency(c.ICommandService),f=m.useMemo(()=>!!n.length,[n]),h=m.useRef(),[u,S]=m.useState(0),[p,C]=m.useState([0,0]),g=m.useRef(!1),E=Me({searchList:n,active:u}),_=a.getEditor(s);m.useEffect(()=>{const T=a.getEditor(s),M=T==null?void 0:T.getBoundingClientRect();if(M==null)return;const{left:x,top:w,height:D}=M;C([x,w+D]),S(0)},[t,n]);function v(T){g.current&&S(T)}function y(){g.current&&S(-1)}m.useEffect(()=>{if(!n.length)return;const T=`sheet.formula-embedding-editor.search_function.${s}`,M=new c.DisposableCollection,x=w=>{const{searchList:D,active:k}=E.current;switch(w){case F.KeyCode.ARROW_UP:{S(A=>{const O=Math.max(0,A-1);return b(O),O});break}case F.KeyCode.ARROW_DOWN:{S(A=>{const O=Math.min(D.length-1,A+1);return b(O),O});break}case F.KeyCode.TAB:case F.KeyCode.ENTER:{const A=D[k];o(A.name);break}case F.KeyCode.ESC:{o("");break}}};return M.add(d.registerCommand({id:T,type:c.CommandType.OPERATION,handler(w,D){const{keyCode:k}=D;x(k)}})),[F.KeyCode.ARROW_UP,F.KeyCode.ARROW_DOWN,F.KeyCode.ENTER,F.KeyCode.ESC,F.KeyCode.TAB].map(w=>({id:T,binding:w,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:w}})).forEach(w=>{M.add(l.registerShortcut(w))}),()=>{M.dispose()}},[n]);function b(T){var U;const M=(U=h.current)==null?void 0:U.querySelectorAll(`.${Ce.formulaSearchFunctionItem}`)[T];if(!M)return;const x=M.parentNode;if(!x)return;const D=x.getBoundingClientRect().top,k=x.offsetHeight,A=M.getBoundingClientRect(),O=A.top,K=A.height;if(O>=0&&O>D&&O-D+K<=k)return;const L=M.offsetTop-(k-K)/2;x.scrollTo({top:L,behavior:"smooth"})}const N=m.useMemo(()=>{let T="";return()=>{clearTimeout(T),g.current=!0,T=setTimeout(()=>{g.current=!1},300)}},[]);return n.length>0&&R.jsx(ie.Popup,{visible:f,offset:p,children:R.jsx("ul",{className:Ce.formulaSearchFunction,ref:T=>{h.current=T,e&&(e.current=T)},children:n.map((T,M)=>R.jsxs("li",{className:u===M?`
17
+ `,children:r.title}),R.jsx("div",{className:te.formulaHelpFunctionContentParamsDetail,children:r.value})]}),_r=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return R.jsxs("div",{className:te.formulaHelpParam,children:[R.jsxs("span",{className:te.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>R.jsxs("span",{className:te.formulaHelpParamItem,children:[R.jsx("span",{className:n===i?te.formulaHelpFunctionActive:te.formulaHelpParamActive,onClick:()=>o(i),children:Ct(s)}),i===t.length-1?"":","]},i)),")"]})},Me=r=>{const e=S.useRef();return e.current=r,e},vr=(r,e,t)=>{const n=c.useDependency(ge.IDescriptionService),o=c.useDependency(I.LexerTreeBuilder),[s,i]=S.useState(),[a,l]=S.useState(-1),[d,h]=S.useState(!0),f=Me(d),u=S.useRef(e);u.current=e;const m=()=>{i(void 0),l(-1),h(!1)};return S.useEffect(()=>{if(t&&r){const p=t.selectionChange$.pipe(q.debounceTime(50)).subscribe(g=>{if(g.textRanges.length===1){const[E]=g.textRanges;if(E.collapsed&&f.current){const v=o.getFunctionAndParameter(u.current,E.startOffset-1);if(v){const{functionName:_,paramIndex:y}=v,b=n.getFunctionInfo(_);i(b),l(y);return}}}i(void 0),l(-1)}),C=t.selectionChange$.pipe(q.filter(g=>g.isEditing),q.filter(g=>g.textRanges.length===1),q.map(g=>g.textRanges[0].startOffset),q.distinctUntilChanged()).subscribe(()=>{h(!0)});return()=>{p.unsubscribe(),C.unsubscribe()}}},[t,r]),S.useEffect(()=>{r||m()},[r]),{functionInfo:s,paramIndex:a,reset:m}},Ve=(r,e,t=!0)=>{let n=-1;return r.reduce((o,s,i)=>{if(o.isFinish)return o;const a=o.currentIndex;if(typeof s!="string")o.currentIndex+=s.token.length;else{const l=s.length;o.currentIndex+=l}return(t?o.currentIndex===e:e>a&&e<=o.currentIndex)&&(n=i,o.isFinish=!0),o},{currentIndex:0,isFinish:!1}),n},Cr=(r,e=[],t)=>{const n=c.useDependency(ge.IDescriptionService),[o,s]=S.useState([]),[i,a]=S.useState(""),l=S.useRef(-1),d=Me({nodes:e}),h=()=>{s([]),a(""),l.current=-1};return S.useEffect(()=>{if(t&&r){const u=t.input$.pipe(q.debounceTime(300)).subscribe(()=>{const m=t.getSelectionRanges();if(m.length===1){const p=d.current.nodes,C=m[0];if(C.collapsed){const g=Ve(p,C.startOffset-1,!1);l.current=g;const E=p[g];if(E&&typeof E!="string"&&E.nodeType===I.sequenceNodeType.FUNCTION){l.current=g;const v=E.token,_=n.getSearchListByNameFirstLetter(v);s(_),a(v);return}}}l.current=-1,a(""),s(p=>p!=null&&p.length?[]:p)});return()=>{u.unsubscribe()}}},[t,r]),S.useEffect(()=>{r||h()},[r]),{searchList:o,searchText:i,handlerFormulaReplace:u=>{const m=[...d.current.nodes];if(l.current!==-1){const p=m.splice(l.current+1),C=m.pop()||"";let g=(typeof C=="string"?C.length:C.token.length)-u.length;return m.push(u),p[0]!==I.matchToken.OPEN_BRACKET&&(m.push(I.matchToken.OPEN_BRACKET),g--),{text:me([...m,...p]),offset:g}}},reset:h}},Rr=r=>r.reduce((e,t)=>typeof t=="string"?e+t.length:e+t.token.length,0),Ir=(r,e=300)=>{let t=r,n=0;const o=()=>t,s=a=>{clearTimeout(n),t=a};function i(){clearTimeout(n),n=setTimeout(()=>{t=r},e)}return{getValue:o,setValue:s,reset:i}},Rt=[I.compareToken.EQUALS,I.compareToken.GREATER_THAN,I.compareToken.GREATER_THAN_OR_EQUAL,I.compareToken.LESS_THAN,I.compareToken.LESS_THAN_OR_EQUAL,I.compareToken.NOT_EQUAL,I.operatorToken.CONCATENATE,I.operatorToken.DIVIDED,I.operatorToken.MINUS,I.operatorToken.MULTIPLY,I.operatorToken.PLUS,I.operatorToken.POWER,I.matchToken.COMMA],xt=[...Rt,I.matchToken.COLON,I.matchToken.OPEN_BRACKET],Er=[...Rt,I.matchToken.CLOSE_BRACKET],ct=r=>typeof r=="string"?r:r.token,yr=(r,e,t)=>{const o=c.useDependency(z.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService),i=S.useRef(!1),a=Me(e),l=S.useMemo(()=>Ir(!1,300),[]),d=f=>{s&&s.setSkipLastEnabled(f),i.current=f},h=()=>i.current;return S.useEffect(()=>{if(t&&s){const f=t.input$.subscribe(m=>{const p=m.content;p.length===1&&xt.includes(p)?(d(!0),l.setValue(!0),l.reset()):(d(!1),l.setValue(!1))}),u=t.selectionChange$.pipe(q.debounceTime(100)).subscribe(m=>{if(l.getValue())return;const p=m.textRanges;if(!p.length)return;if(p.length!==1){d(!1);return}const C=p[0];if(!C.collapsed){d(!1);return}const g=a.current;if(!g.length){d(!0);return}const E=C.startOffset-1;if(E===0){const T=Ve(g,1,!1),M=g[T]||"",x=ct(M);if(Rt.includes(x)){d(!0);return}}const v=Ve(g,E,!1),_=g[v];if(!_){d(!1);return}const y=g[v+1]||"",b=ct(y),N=ct(_);xt.includes(N)&&(!y||Er.includes(b))?d(!0):d(!1)});return s.selectionMoveEnd$.subscribe(()=>{Promise.resolve().then(()=>{d(!1)})}),()=>{f.unsubscribe(),u.unsubscribe()}}},[t,s]),{setIsAddSelection:d,getIsNeedAddSelection:h,isLockSelectionEvent:l}},Tr=()=>{},br=(r,e,t,n,o,s,i=Tr)=>{const a=c.useDependency(z.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=Me(n),{getIsNeedAddSelection:h}=yr(e,n,s),f=l.getUnit(e),u=y=>{var b,N;return(N=(b=f==null?void 0:f.getSheetBySheetId(y))==null?void 0:b.getName())!=null?N:""},m=S.useMemo(()=>u(t),[t]),p=c.useObservable(f==null?void 0:f.activeSheet$),C=Me({activeSheet:p,sheetName:m}),g=a.getRenderById(e),E=g==null?void 0:g.with(exports.RefSelectionsRenderService),v=S.useRef(!1),_=S.useRef();S.useEffect(()=>{if(E&&r){let y=!0;const b=T=>{var k,A,O,K,L,U;if(y||v.current){y=!1;return}const M=s==null?void 0:s.getSelectionRanges();if((M==null?void 0:M.length)!==1)return;const w=M[0].startOffset-1,D=[...d.current];if(h())if(w!==0){const j=Ve(D,w,!1);if(j===-1&&D.length)return;const B=T[T.length-1],Z=D.splice(j+1),ae=(k=B.rangeWithCoord.sheetId)!=null?k:t,le={range:B.rangeWithCoord,unitId:(A=B.rangeWithCoord.unitId)!=null?A:e,sheetName:u(ae)},X=fe([le],o&&ae!==t);D.push({token:X[0],nodeType:I.sequenceNodeType.REFERENCE});const ne=[...D,...Z],ce=me(ne);i(ce,Rr(D),!0)}else{const j=T[T.length-1],B=(O=j.rangeWithCoord.sheetId)!=null?O:t,Z={range:j.rangeWithCoord,unitId:(K=j.rangeWithCoord.unitId)!=null?K:e,sheetName:u(B)},le=fe([Z],o&&B!==t);D.unshift({token:le[0],nodeType:I.sequenceNodeType.REFERENCE});const he=me(D);i(he,le[0].length,!0)}else{let j=0;const B=D.map(X=>{var ne,ce,pe;if(typeof X=="string")return X;if(X.nodeType===I.sequenceNodeType.REFERENCE){const _e=I.deserializeRangeWithSheet(X.token);if(_e.sheetName||(_e.sheetName=m),o&&((ne=C.current.activeSheet)==null?void 0:ne.getName())!==_e.sheetName)return X.token;const Y=T[j];if(j++,!Y)return"";const G=(ce=Y.rangeWithCoord.sheetId)!=null?ce:t,Q={range:Y.rangeWithCoord,unitId:(pe=Y.rangeWithCoord.unitId)!=null?pe:e,sheetName:u(G)};return fe([Q],o)[0]}return X.token}).join(""),Z=[];for(let X=j;X<=T.length-1;X++){const ne=T[X],ce=(L=ne.rangeWithCoord.sheetId)!=null?L:t,pe={range:ne.rangeWithCoord,unitId:(U=ne.rangeWithCoord.unitId)!=null?U:e,sheetName:u(ce)},Y=fe([pe],o&&ce!==t);Z.push(Y[0])}const ae=D[D.length-1],le=ae&&(typeof ae=="string"?!1:ae.nodeType===I.sequenceNodeType.REFERENCE),he=`${B}${Z.length&&le?",":""}${Z.join(",")}`;i(he,he.length,!0)}},N=E.selectionMoveEnd$.subscribe(T=>{if(b(T),v.current=!1,_.current){const{result:M,offset:x}=_.current;i(M,x||-1,!0),_.current=void 0}});return()=>{N.unsubscribe()}}},[E,s,o,r]),S.useEffect(()=>{if(r&&E&&s){const y=new c.DisposableCollection,b=(M,x)=>{let w=0,D=0,k=!1;const{sheetName:A}=C.current,O=d.current.map(L=>{var U;if(typeof L=="string")return k||(D+=L.length),L;if(L.nodeType===I.sequenceNodeType.REFERENCE){const j=I.deserializeRangeWithSheet(L.token);if(j.unitId||(j.unitId=e),j.sheetName||(j.sheetName=A),o&&((U=C.current.activeSheet)==null?void 0:U.getName())!==j.sheetName)return k||(D+=L.token.length),L;if(w===x){k=!0;const B={...L,token:M};return o&&j.sheetName!==A?B.token=I.serializeRangeWithSheet(j.sheetName,I.deserializeRangeWithSheet(M).range):B.token=M,D+=B.token.length,w++,B}return k||(D+=L.token.length),w++,L}return k||(D+=L.token.length),L}),K=me(O);i(K,-1,!1),_.current={result:K,offset:D}},N=()=>{y.dispose(),E.getSelectionControls().forEach((x,w)=>{y.add(q.merge(x.selectionMoving$,x.selectionScaling$).pipe(Ue.map(D=>I.serializeRange(D)),Ue.distinctUntilChanged()).subscribe(D=>{v.current=!0,b(D,w)}))})},T=q.merge(s.input$,E.selectionMoveEnd$).pipe(Ue.debounceTime(50)).subscribe(()=>{N()});return()=>{T.unsubscribe(),y.dispose()}}},[r,E,s])},Nr=(r,e,t)=>{const n=c.useDependency(I.LexerTreeBuilder),o=S.useRef(!0);S.useEffect(()=>{if(r){const s=setTimeout(()=>{o.current=!1},500);return()=>{clearTimeout(s)}}},[r]),S.useEffect(()=>{if(!o.current&&e){const s=n.checkIfAddBracket(t);e(s===0&&t.startsWith(I.operatorToken.EQUALS),`${t}`)}},[t,e])},xr="univer-sheet-embedding-formula-editor-active",Mr="univer-sheet-embedding-formula-editor-wrap",Fr="univer-sheet-embedding-formula-editor-text",Or="univer-sheet-embedding-formula-editor-error-wrap",Ar="univer-sheet-embedding-formula-editor-error",xe={sheetEmbeddingFormulaEditorActive:xr,sheetEmbeddingFormulaEditorWrap:Mr,sheetEmbeddingFormulaEditorText:Fr,sheetEmbeddingFormulaEditorErrorWrap:Or,sheetEmbeddingFormulaEditorError:Ar},Dr="univer-formula-search-function",Pr="univer-formula-search-function-item",Lr="univer-formula-search-function-item-name",wr="univer-formula-search-function-item-name-light",kr="univer-formula-search-function-item-desc",Ur="univer-formula-search-function-item-active",Ce={formulaSearchFunction:Dr,formulaSearchFunctionItem:Pr,formulaSearchFunctionItemName:Lr,formulaSearchFunctionItemNameLight:wr,formulaSearchFunctionItemDesc:kr,formulaSearchFunctionItemActive:Ur},$r=()=>{},jr=S.forwardRef(Hr);function Hr(r,e){const{searchText:t,searchList:n,onSelect:o,editorId:s,onClose:i=$r}=r,a=c.useDependency(ee.IEditorService),l=c.useDependency(F.IShortcutService),d=c.useDependency(c.ICommandService),h=S.useMemo(()=>!!n.length,[n]),f=S.useRef(),[u,m]=S.useState(0),[p,C]=S.useState([0,0]),g=S.useRef(!1),E=Me({searchList:n,active:u}),v=a.getEditor(s);S.useEffect(()=>{const T=a.getEditor(s),M=T==null?void 0:T.getBoundingClientRect();if(M==null)return;const{left:x,top:w,height:D}=M;C([x,w+D]),m(0)},[t,n]);function _(T){g.current&&m(T)}function y(){g.current&&m(-1)}S.useEffect(()=>{if(!n.length)return;const T=`sheet.formula-embedding-editor.search_function.${s}`,M=new c.DisposableCollection,x=w=>{const{searchList:D,active:k}=E.current;switch(w){case F.KeyCode.ARROW_UP:{m(A=>{const O=Math.max(0,A-1);return b(O),O});break}case F.KeyCode.ARROW_DOWN:{m(A=>{const O=Math.min(D.length-1,A+1);return b(O),O});break}case F.KeyCode.TAB:case F.KeyCode.ENTER:{const A=D[k];o(A.name);break}case F.KeyCode.ESC:{o("");break}}};return M.add(d.registerCommand({id:T,type:c.CommandType.OPERATION,handler(w,D){const{keyCode:k}=D;x(k)}})),[F.KeyCode.ARROW_UP,F.KeyCode.ARROW_DOWN,F.KeyCode.ENTER,F.KeyCode.ESC,F.KeyCode.TAB].map(w=>({id:T,binding:w,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keyCode:w}})).forEach(w=>{M.add(l.registerShortcut(w))}),()=>{M.dispose()}},[n]);function b(T){var U;const M=(U=f.current)==null?void 0:U.querySelectorAll(`.${Ce.formulaSearchFunctionItem}`)[T];if(!M)return;const x=M.parentNode;if(!x)return;const D=x.getBoundingClientRect().top,k=x.offsetHeight,A=M.getBoundingClientRect(),O=A.top,K=A.height;if(O>=0&&O>D&&O-D+K<=k)return;const L=M.offsetTop-(k-K)/2;x.scrollTo({top:L,behavior:"smooth"})}const N=S.useMemo(()=>{let T="";return()=>{clearTimeout(T),g.current=!0,T=setTimeout(()=>{g.current=!1},300)}},[]);return n.length>0&&R.jsx(ie.Popup,{visible:h,offset:p,children:R.jsx("ul",{className:Ce.formulaSearchFunction,ref:T=>{f.current=T,e&&(e.current=T)},children:n.map((T,M)=>R.jsxs("li",{className:u===M?`
18
18
  ${Ce.formulaSearchFunctionItem}
19
19
  ${Ce.formulaSearchFunctionItemActive}
20
- `:Ce.formulaSearchFunctionItem,onMouseEnter:()=>v(M),onMouseLeave:y,onMouseMove:N,onClick:()=>{o(T.name),_&&_.focus()},children:[R.jsxs("span",{className:Ce.formulaSearchFunctionItemName,children:[R.jsx("span",{className:Ce.formulaSearchFunctionItemNameLight,children:T.name.substring(0,t.length)}),R.jsx("span",{children:T.name.slice(t.length)})]}),R.jsx("span",{className:Ce.formulaSearchFunctionItemDesc,children:T.desc})]},M))})})}const Mt=r=>r.startsWith(I.operatorToken.EQUALS)?r.slice(1):"",at=()=>{};function sn(r){const{errorText:e,initValue:t,unitId:n,subUnitId:o,isFocus:s=!0,isSupportAcrossSheet:i=!1,onFocus:a=at,onBlur:l=at,onChange:d,onVerify:f,actions:h}=r,u=c.useDependency(ee.IEditorService),S=c.useDependency(I.LexerTreeBuilder),p=m.useRef(null),[C,g]=m.useState(()=>t.startsWith(I.operatorToken.EQUALS)?t:"");h&&(h.handleOutClick=(Y,G)=>{p.current&&!p.current.contains(Y.target)&&G()});const E=m.useMemo(()=>Mt(C),[C]),_=m.useRef(null),[v,y]=m.useState(),[b,N]=m.useState(s),T=m.useRef(null),M=m.useMemo(()=>c.createInternalEditorID(`${P.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),x=m.useMemo(()=>e!==void 0,[e]),w=nt(),D=m.useMemo(()=>w(E),[E]),k=qt(D,Y=>{const G=S.sequenceNodesBuilder(Y);if(G){const Q=G.map(W=>{if(typeof W=="string")return W;if(W.nodeType===I.sequenceNodeType.REFERENCE){const re={...W},oe=I.deserializeRangeWithSheet(W.token);return oe.range=rt(oe.range),i||(oe.sheetName="",oe.unitId=""),re.token=he([oe],i)[0],re}return W}),H=me(Q);d(`=${H}`)}},v),A=Yt("="),O=pt(n),K=(Y,G=!0)=>{if(!v)return;const Q=w(Y),H=A(v,Q,G);O(H)};Nr(b,f,C);const L=zt(v),U=en(b);m.useLayoutEffect(()=>{if(s){const Y=setTimeout(()=>{N(s),s&&L()},30);return()=>{clearTimeout(Y)}}else U(),N(s)},[s,L]);const{checkScrollBar:j}=tn(v);vt(b,n),Xt(b,v),br(b,n,o,D,i,v,(Y,G,Q)=>{const H=`=${Y}`;k(),g(H),K(Y),Q&&(L(),G!==-1&&setTimeout(()=>{const W={startOffset:G+1,endOffset:G+1};v==null||v.setSelectionRanges([W]);const re=v==null?void 0:v.render.with(ee.DocBackScrollRenderController);re==null||re.scrollToRange({...W,collapsed:!0})},50),j())}),Jt(),_t(b,n,i,N,l,at);const{searchList:Z,searchText:ae,handlerFormulaReplace:le,reset:fe}=Cr(b,D,v),{functionInfo:X,paramIndex:ne,reset:ce}=_r(b,C,v);m.useEffect(()=>{if(v){const Y=v.input$.subscribe(G=>{var H,W;const Q=((W=(H=G.data.body)==null?void 0:H.dataStream)!=null?W:"").replaceAll(/\n|\r/g,"");k(),g(Q),K(Mt(Q),!1)});return()=>{Y.unsubscribe()}}},[v]),Kt(E,"=",b,A,O,v),m.useLayoutEffect(()=>{let Y;if(T.current){Y=u.register({autofocus:!0,editorUnitId:M,isSingle:!0,initialSnapshot:{id:M,body:{dataStream:`${t}\r
21
- `},documentStyle:{}}},T.current);const G=u.getEditor(M);y(G)}return()=>{Y==null||Y.dispose()}},[]);const pe=Y=>{const G=le(Y);if(G){g(`=${G.text}`);const Q=v==null?void 0:v.getSelectionRanges();if(Q&&Q.length===1){const H=Q[0];if(H.collapsed){const W=G.offset;setTimeout(()=>{v==null||v.setSelectionRanges([{startOffset:H.startOffset-W,endOffset:H.endOffset-W}])},30)}}fe(),L(),K(G.text)}},ve=()=>{setTimeout(()=>{N(!0),a(),L()},30)};return R.jsxs("div",{className:xe.sheetEmbeddingFormulaEditor,children:[R.jsxs("div",{className:Vt(xe.sheetEmbeddingFormulaEditorWrap,{[xe.sheetEmbeddingFormulaEditorActive]:b,[xe.sheetEmbeddingFormulaEditorError]:x}),ref:p,children:[R.jsx("div",{className:xe.sheetEmbeddingFormulaEditorText,ref:T,onMouseUp:ve}),e!==void 0?R.jsx("div",{className:xe.sheetEmbeddingFormulaEditorErrorWrap,children:e}):null]}),R.jsx(pr,{editorId:M,paramIndex:ne,functionInfo:X,onClose:()=>{ce(),L()}}),R.jsx(jr,{searchText:ae,editorId:M,searchList:Z,onSelect:pe,ref:_})]})}const Wr="sheets-formula-ui.base.config",Ft={};function Br(r){return r.getContextValue(c.FOCUSING_DOC)&&r.getContextValue(c.FOCUSING_UNIVER_EDITOR)&&r.getContextValue(c.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)}function cn(r,e=!1){return!e&&!(c.isFormulaString(r==null?void 0:r.f)||c.isFormulaId(r==null?void 0:r.si))?null:typeof(r==null?void 0:r.v)=="string"&&I.ERROR_TYPE_SET.has(r.v)?r.v:null}var Vr=Object.defineProperty,qr=Object.getOwnPropertyDescriptor,Kr=(r,e,t,n)=>{for(var o=n>1?void 0:n?qr(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Vr(e,t,o),o},Pe=(r,e)=>(t,n)=>e(t,n,r);const lt="SHEET_FORMULA_ALERT",zr={[I.ErrorType.DIV_BY_ZERO]:"divByZero",[I.ErrorType.NAME]:"name",[I.ErrorType.VALUE]:"value",[I.ErrorType.NUM]:"num",[I.ErrorType.NA]:"na",[I.ErrorType.CYCLE]:"cycle",[I.ErrorType.REF]:"ref",[I.ErrorType.SPILL]:"spill",[I.ErrorType.CALC]:"calc",[I.ErrorType.ERROR]:"error",[I.ErrorType.CONNECT]:"connect",[I.ErrorType.NULL]:"null"};let St=class extends c.Disposable{constructor(r,e,t,n,o,s){super(),this._context=r,this._hoverManagerService=e,this._cellAlertManagerService=t,this._localeService=n,this._formulaDataModel=o,this._zenZoneService=s,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(q.debounceTime(100)).subscribe(r=>{var e,t,n,o,s;if(r){const a=this._context.unit.getActiveSheet();if(!a)return;const l=a.getCell(r.location.row,r.location.col),d=(o=(n=(t=(e=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:e[r.location.unitId])==null?void 0:t[r.location.subUnitId])==null?void 0:n[r.location.row])==null?void 0:o[r.location.col];if(c.isICellData(l)){const f=cn(l,!!d);if(!f){this._hideAlert();return}const h=this._cellAlertManagerService.currentAlert.get(lt),u=(s=h==null?void 0:h.alert)==null?void 0:s.location;if(u&&u.row===r.location.row&&u.col===r.location.col&&u.subUnitId===r.location.subUnitId&&u.unitId===r.location.unitId)return;this._cellAlertManagerService.showAlert({type:P.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${zr[f]}`),location:r.location,width:200,height:74,key:lt});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(r=>{r&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(lt)}};St=Kr([Pe(1,c.Inject(P.HoverManagerService)),Pe(2,c.Inject(P.CellAlertManagerService)),Pe(3,c.Inject(c.LocaleService)),Pe(4,c.Inject(I.FormulaDataModel)),Pe(5,F.IZenZoneService)],St);var Yr=Object.defineProperty,Gr=Object.getOwnPropertyDescriptor,Zr=(r,e,t,n)=>{for(var o=n>1?void 0:n?Gr(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Yr(e,t,o),o},Ot=(r,e)=>(t,n)=>e(t,n,r);let qe=class extends c.Disposable{constructor(r,e){super(),this._autoFillService=r,this._lexerTreeBuilder=e,this._registerAutoFill()}_registerAutoFill(){const r={type:P.DATA_TYPE.FORMULA,priority:1001,match:e=>c.isFormulaString(e==null?void 0:e.f)||c.isFormulaId(e==null?void 0:e.si),isContinue:(e,t)=>e.type===P.DATA_TYPE.FORMULA,applyFunctions:{[P.APPLY_TYPE.COPY]:(e,t,n,o)=>{const{data:s,index:i}=e;return this._fillCopyFormula(s,t,n,i,o)}}};this._autoFillService.registerRule(r)}_fillCopyFormula(r,e,t,n,o){var l,d;const s=Qr(o),i=[],a=new Map;for(let f=1;f<=e;f++){const h=(f-1)%r.length,u=c.Tools.deepClone(r[h]);if(u){const S=((l=r[h])==null?void 0:l.f)||"",p=((d=r[h])==null?void 0:d.si)||"",C=c.isFormulaString(S);if(c.isFormulaId(p))u.si=p,u.f=null,u.v=null,u.p=null,u.t=null,i.push(u);else if(C){let E=a.get(h);if(E)u.si=E,u.f=null,u.v=null,u.p=null,u.t=null;else{E=c.Tools.generateRandomId(6),a.set(h,E);const{offsetX:_,offsetY:v}=Xr(s,e,t),y=this._lexerTreeBuilder.moveFormulaRefOffset(S,_,v);u.si=E,u.f=y,u.v=null,u.p=null,u.t=null}i.push(u)}}}return i}};qe=Zr([Ot(0,P.IAutoFillService),Ot(1,c.Inject(I.LexerTreeBuilder))],qe);function Xr(r,e,t){let n=0,o=0;switch(t){case c.Direction.UP:o=-r*e;break;case c.Direction.RIGHT:n=r;break;case c.Direction.DOWN:o=r;break;case c.Direction.LEFT:n=-r*e;break}return{offsetX:n,offsetY:o}}function Qr(r){let e=0;for(const t in r)r[t].forEach(n=>{e+=n.data.length});return e}var Jr=Object.defineProperty,eo=Object.getOwnPropertyDescriptor,to=(r,e,t,n)=>{for(var o=n>1?void 0:n?eo(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Jr(e,t,o),o},Le=(r,e)=>(t,n)=>e(t,n,r);const no="default-paste-formula";let Ke=class extends c.Disposable{constructor(r,e,t,n,o){super(),this._currentUniverSheet=r,this._lexerTreeBuilder=e,this._sheetClipboardService=t,this._injector=n,this._formulaDataModel=o,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(r,e,t,n)=>this._onPasteCells(r,e,t,n,!0)}}_pasteWithFormulaHook(){return{id:no,priority:10,onPasteCells:(r,e,t,n)=>this._onPasteCells(r,e,t,n,!1)}}_onPasteCells(r,e,t,n,o){var h;if([P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(n.pasteType))return{undos:[],redos:[]};const s=this._currentUniverSheet.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),i=e.unitId||s.getUnitId(),a=e.subUnitId||((h=s.getActiveSheet())==null?void 0:h.getSheetId());if(!i||!a)return{undos:[],redos:[]};const l=e.range,d=t,f={copyType:n.copyType||P.COPY_TYPE.COPY,copyRange:r==null?void 0:r.range,pasteType:n.pasteType};return this._injector.invoke(u=>ro(i,a,l,d,u,f,this._lexerTreeBuilder,this._formulaDataModel,o,r))}};Ke=to([Le(0,c.IUniverInstanceService),Le(1,c.Inject(I.LexerTreeBuilder)),Le(2,P.ISheetClipboardService),Le(3,c.Inject(c.Injector)),Le(4,c.Inject(I.FormulaDataModel))],Ke);function ro(r,e,t,n,o,s,i,a,l=!1,d){const f=[],h=[],u=oo(r,e,t,n,s,i,a,d),S={unitId:r,subUnitId:e,cellValue:u.getData()};f.push({id:$.SetRangeValuesMutation.id,params:S});const p=$.SetRangeValuesUndoMutationFactory(o,S);return h.push({id:$.SetRangeValuesMutation.id,params:p}),{undos:h,redos:f}}function oo(r,e,t,n,o,s,i,a){return a?o.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?io(r,e,t,n,i,a):o.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?co(r,e,t,n,s,i,a):ao(r,e,t,n,s,i,a):so(r,e,t,n,i)}function so(r,e,t,n,o){const s=new c.ObjectMatrix,i=o.getSheetFormulaData(r,e);return n.forValue((a,l,d)=>{var S;const f=t.rows[a],h=t.cols[l],u={};c.isFormulaString(d.v)?(u.v=null,u.f=`${d.v}`,u.si=null,u.p=null,s.setValue(f,h,u)):(S=i==null?void 0:i[f])!=null&&S[h]&&(u.v=d.v,u.f=null,u.si=null,u.p=null,s.setValue(f,h,u))}),s}function io(r,e,t,n,o,s){var d,f;const i=new c.ObjectMatrix,a=(f=(d=o.getArrayFormulaCellData())==null?void 0:d[s.unitId])==null?void 0:f[s.subUnitId],l=o.getSheetFormulaData(r,e);return n.forValue((h,u,S)=>{var v,y;const p=s.range.rows[h%s.range.rows.length],C=s.range.cols[u%s.range.cols.length],g=t.rows[h],E=t.cols[u],_={};if(c.isFormulaString(S.f)||c.isFormulaId(S.si))_.v=S.v,_.f=null,_.si=null,_.p=null,i.setValue(g,E,_);else if((v=a==null?void 0:a[p])!=null&&v[C]){const b=a[p][C];_.v=b.v,_.f=null,_.si=null,_.p=null,i.setValue(g,E,_)}else if((y=l==null?void 0:l[g])!=null&&y[E]){if(_.v=S.v,_.f=null,_.si=null,_.p=null,S.p){const b=an(S);b&&(_.v=b)}i.setValue(g,E,_)}}),i}function co(r,e,t,n,o,s,i){const a=new c.ObjectMatrix,l=new Map;return n.forValue((d,f,h)=>{const u=t.rows[d],S=t.cols[f],p={};if(c.isFormulaId(h.si)){if(i.unitId!==r||i.subUnitId!==e){const C=s.getFormulaStringByCell(i.range.rows[d%i.range.rows.length],i.range.cols[f%i.range.cols.length],i.subUnitId,i.unitId),g=t.cols[f]-i.range.cols[f%i.range.cols.length],E=t.rows[d]-i.range.rows[d%i.range.rows.length],_=o.moveFormulaRefOffset(C||"",g,E);p.si=null,p.f=_}else p.si=h.si,p.f=null;p.v=null,p.p=null,a.setValue(u,S,p)}else if(c.isFormulaString(h.f)){const C=`${d%i.range.rows.length}_${f%i.range.cols.length}`;let g=l.get(C);if(g)p.si=g,p.f=null;else{g=c.Tools.generateRandomId(6),l.set(C,g);const E=t.cols[f]-i.range.cols[f%i.range.cols.length],_=t.rows[d]-i.range.rows[d%i.range.rows.length],v=o.moveFormulaRefOffset(h.f||"",E,_);p.si=g,p.f=v}p.v=null,p.p=null,a.setValue(u,S,p)}else{if(p.v=h.v,p.f=null,p.si=null,p.p=null,h.p){const C=an(h);C&&(p.v=C)}a.setValue(u,S,p)}}),a}function ao(r,e,t,n,o,s,i){const a=new c.ObjectMatrix,l=new Map,d=s.getSheetFormulaData(r,e);return n.forValue((f,h,u)=>{var g;const S=t.rows[f],p=t.cols[h],C={};if(c.isFormulaId(u.si)){if(i.unitId!==r||i.subUnitId!==e){const E=s.getFormulaStringByCell(i.range.rows[f%i.range.rows.length],i.range.cols[h%i.range.cols.length],i.subUnitId,i.unitId),_=t.cols[h]-i.range.cols[h%i.range.cols.length],v=t.rows[f]-i.range.rows[f%i.range.rows.length],y=o.moveFormulaRefOffset(E||"",_,v);C.si=null,C.f=y}else C.si=u.si,C.f=null;C.v=null,C.p=null,a.setValue(S,p,C)}else if(c.isFormulaString(u.f)){const E=`${f%i.range.rows.length}_${h%i.range.cols.length}`;let _=l.get(E);if(_)C.si=_,C.f=null;else{_=c.Tools.generateRandomId(6),l.set(E,_);const v=t.cols[h]-i.range.cols[h%i.range.cols.length],y=t.rows[f]-i.range.rows[f%i.range.rows.length],b=o.moveFormulaRefOffset(u.f||"",v,y);C.si=_,C.f=b}C.v=null,C.p=null,a.setValue(S,p,C)}else(g=d==null?void 0:d[S])!=null&&g[p]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,a.setValue(S,p,C))}),a}function an(r){if(r!=null&&r.p){const e=r==null?void 0:r.p.body;if(e==null)return;const t=e.dataStream;return t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t}}var lo=Object.defineProperty,uo=Object.getOwnPropertyDescriptor,ho=(r,e,t,n)=>{for(var o=n>1?void 0:n?uo(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&lo(e,t,o),o},ye=(r,e)=>(t,n)=>e(t,n,r);let ze=class extends c.Disposable{constructor(e,t,n,o,s,i,a,l){super();V(this,"_previousShape");V(this,"_skeleton");this._context=e,this._sheetInterceptorService=t,this._formulaDataModel=n,this._themeService=o,this._renderManagerService=s,this._sheetSkeletonManagerService=i,this._commandService=a,this._logService=l,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(e=>{var t,n;if(e==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:o}=e,s=(n=(t=this._skeleton)==null?void 0:t.worksheet)==null?void 0:n.getSheetId();if(this._changeRuntime(o),s!==o.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:a}=e;this._updateArrayFormulaRangeShape(i,a)}}}))}_changeRuntime(e){this._skeleton=e}_initInterceptorEditorStart(){this.disposeWithMe(c.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept($.BEFORE_CELL_EDIT,{handler:(e,t,n)=>{var p,C,g,E;const{row:o,col:s,unitId:i,subUnitId:a,worksheet:l}=t,d=this._formulaDataModel.getArrayFormulaRange(),f=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),e==null)return n(e);let h=null;const u=this._formulaDataModel.getFormulaStringByCell(o,s,a,i);if(u!==null&&(h={f:u}),e.v!=null&&e.v!==""&&((g=(C=(p=f[i])==null?void 0:p[a])==null?void 0:C[o])==null?void 0:g[s])==null)return h?{...e,...h}:n(e);const S=(E=d==null?void 0:d[i])==null?void 0:E[a];return S!=null&&(h=this._displayArrayFormulaRangeShape(S,o,s,i,a,l,h)),h?{...e,...h}:n(e)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{(e.id===I.SetFormulaCalculationResultMutation.id||e.id===I.SetArrayFormulaDataMutation.id&&t&&t.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{$.SetWorksheetRowAutoHeightMutation.id===e.id&&requestIdleCallback(()=>{const t=e.params,{unitId:n,subUnitId:o,rowsAutoHeightInfo:s}=t;this._refreshArrayFormulaRangeShapeByRow(n,o,s)})}))}_displayArrayFormulaRangeShape(e,t,n,o,s,i,a){const l=this._formulaDataModel.getSheetFormulaData(o,s);return new c.ObjectMatrix(e).forValue((d,f,h)=>{var g;if(h==null)return!0;const{startRow:u,startColumn:S,endRow:p,endColumn:C}=h;if(d===t&&f===n)return this._createArrayFormulaRangeShape(h,o),!1;if(t>=u&&t<=p&&n>=S&&n<=C){const E=i.getCell(u,S);if((E==null?void 0:E.v)===I.ErrorType.SPILL)return;const _=(g=l==null?void 0:l[d])==null?void 0:g[f];return _==null||_.f==null?!0:(a==null&&(a={f:_.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(h,o),!1)}}),a}_createArrayFormulaRangeShape(e,t){const n=this._renderManagerService.getRenderById(t),o=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n||!o)return;const{scene:s}=n;if(!s)return;const i=this._themeService.getCurrentTheme(),a={range:e,primary:null,style:{strokeWidth:1,stroke:i.hyacinth700,fill:new c.ColorKit(i.colorWhite).setAlpha(0).toString(),widgets:{}}},l=P.attachSelectionWithCoord(a,o),{rowHeaderWidth:d,columnHeaderHeight:f}=o,h=new P.SelectionControl(s,P.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:f});h.updateRangeBySelectionWithCoord(l),h.setEvent(!1),this._previousShape=h}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(e,t){if(this._previousShape){const{startRow:n,endRow:o,startColumn:s,endColumn:i}=this._previousShape.getRange(),a={startRow:n,endRow:o,startColumn:s,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(a,e)}}_checkCurrentSheet(e,t){const n=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n)return!1;const o=n.worksheet;return o?o.unitId===e&&o.getSheetId()===t:!1}_updateArrayFormulaRangeShape(e,t){this._checkCurrentSheet(e,t)&&this._previousShape&&this._refreshArrayFormulaRangeShape(e)}_refreshArrayFormulaRangeShapeByRow(e,t,n){if(!this._checkCurrentSheet(e,t)||!this._previousShape)return;const{startRow:o,endRow:s,startColumn:i,endColumn:a}=this._previousShape.getRange();for(let l=0;l<n.length;l++){const{row:d}=n[l];if(o>=d){const f={startRow:o,endRow:s,startColumn:i,endColumn:a};this._refreshArrayFormulaRangeShape(e,f);break}}}};ze=ho([ye(1,c.Inject($.SheetInterceptorService)),ye(2,c.Inject(I.FormulaDataModel)),ye(3,c.Inject(c.ThemeService)),ye(4,z.IRenderManagerService),ye(5,c.Inject(P.SheetSkeletonManagerService)),ye(6,c.ICommandService),ye(7,c.ILogService)],ze);var fo=Object.defineProperty,mo=Object.getOwnPropertyDescriptor,So=(r,e,t,n)=>{for(var o=n>1?void 0:n?mo(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&fo(e,t,o),o},At=(r,e)=>(t,n)=>e(t,n,r);const go={tl:{size:6,color:"#409f11"}};let Ye=class extends c.RxDisposable{constructor(r,e){super(),this._sheetInterceptorService=r,this._formulaDataModel=e,this.disposeWithMe(this._sheetInterceptorService.intercept($.INTERCEPTOR_POINT.CELL_CONTENT,{effect:c.InterceptorEffectEnum.Style,handler:(t,n,o)=>{var a,l,d,f;const s=(f=(d=(l=(a=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:a[n.unitId])==null?void 0:l[n.subUnitId])==null?void 0:d[n.row])==null?void 0:f[n.col];return cn(t,!!s)?o({...t,markers:{...t==null?void 0:t.markers,...go}}):o(t)},priority:10}))}};Ye=So([At(0,c.Inject($.SheetInterceptorService)),At(1,c.Inject(I.FormulaDataModel))],Ye);function po(){const r=c.useDependency(ge.TriggerCalculationController),e=c.useDependency(c.ICommandService),t=c.useObservable(r.progress$),n=m.useCallback(()=>{e.executeCommand(I.SetFormulaCalculationStopMutation.id)},[e]),o=m.useCallback(()=>{r.clearProgress()},[r]);return R.jsx(F.ProgressBar,{progress:t,onTerminate:n,onClearProgress:o})}const vo=(r,e=100)=>{m.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{r(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[r,e])},_o="univer-formula-help-function",Co="univer-formula-help-function-title",Ro="univer-formula-help-function-title-icons",Io="univer-formula-help-function-title-icon",Eo="univer-formula-help-function-content",yo="univer-formula-help-function-content-inner",To="univer-formula-help-function-content-params",bo="univer-formula-help-function-content-params-title",No="univer-formula-help-function-content-params-detail",xo="univer-formula-help-function-active",Mo="univer-formula-help-decorator",Fo="univer-formula-help-param",Oo="univer-formula-help-param-prefix",Ao="univer-formula-help-param-item",Do="univer-formula-help-param-active",J={formulaHelpFunction:_o,formulaHelpFunctionTitle:Co,formulaHelpFunctionTitleIcons:Ro,formulaHelpFunctionTitleIcon:Io,formulaHelpFunctionContent:Eo,formulaHelpFunctionContentInner:yo,formulaHelpFunctionContentParams:To,formulaHelpFunctionContentParamsTitle:bo,formulaHelpFunctionContentParamsDetail:No,formulaHelpFunctionActive:xo,formulaHelpDecorator:Mo,formulaHelpParam:Fo,formulaHelpParamPrefix:Oo,formulaHelpParamItem:Ao,formulaHelpParamActive:Do};function Po(){const[r,e]=m.useState(!1),[t,n]=m.useState(!0),[o,s]=m.useState(!0),[i,a]=m.useState(0),[l,d]=m.useState([0,0]),[f,h]=m.useState({left:0,top:0}),[u,S]=m.useState(null),p=c.useDependency(Fe),C=c.useDependency(c.LocaleService),g=C.t("formula.prompt.required"),E=C.t("formula.prompt.optional"),_=c.useDependency(c.IUniverInstanceService),v=c.useDependency(ee.IEditorService),y=c.useDependency(F.ISidebarService),b=c.useInjector();vo(N),m.useEffect(()=>{const w=p.help$.subscribe(k=>{const{visible:A,paramIndex:O,functionInfo:K}=k;if(!A){e(A);return}const L=T();if(L==null)return;const{left:U,top:j,height:B}=L;K.description===""&&K.functionParameter.length===0||(d([U,j+B]),a(O),S(K),h({left:U,top:j}),e(A))}),D=y.scrollEvent$.pipe(q.throttleTime(100)).subscribe(N);return()=>{w==null||w.unsubscribe(),D.unsubscribe()}},[]);function N(){if(!o)return;const w=T();if(w==null)return;const{left:D,top:k,height:A}=w;d([D,k+A])}function T(){const w=_.getCurrentUniverDocInstance();if(!w)return;const D=w.getUnitId();if(!v.isEditor(D))return;const k=v.getEditor(D);return k==null?void 0:k.getBoundingClientRect()}function M(w){a(w)}function x(){s(!o),b.get(F.ILayoutService).focus()}return R.jsx(R.Fragment,{children:o?R.jsx(ie.Popup,{visible:r,offset:l,children:u?R.jsxs("div",{className:J.formulaHelpFunction,children:[R.jsxs("div",{className:J.formulaHelpFunctionTitle,children:[R.jsx(Lo,{prefix:u.functionName,value:u.functionParameter,active:i,onClick:M}),R.jsxs("div",{className:J.formulaHelpFunctionTitleIcons,children:[R.jsx("div",{className:J.formulaHelpFunctionTitleIcon,style:{transform:t?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>n(!t),children:R.jsx(gt,{})}),R.jsx("div",{className:J.formulaHelpFunctionTitleIcon,onClick:x,children:R.jsx(tt,{})})]})]}),R.jsx("div",{className:J.formulaHelpFunctionContent,style:{height:t?"unset":0,padding:t?"revert-layer":0},children:R.jsxs("div",{className:J.formulaHelpFunctionContentInner,children:[R.jsx(ut,{title:C.t("formula.prompt.helpExample"),value:`${u.functionName}(${u.functionParameter.map(w=>w.example).join(",")})`}),R.jsx(ut,{title:C.t("formula.prompt.helpAbstract"),value:u.description}),u&&u.functionParameter&&u.functionParameter.map((w,D)=>R.jsx(ut,{className:i===D?J.formulaHelpFunctionActive:"",title:w.name,value:`${w.require?g:E} ${w.detail}`},D))]})})]}):R.jsx(R.Fragment,{})}):r?R.jsx("div",{className:J.formulaHelpDecorator,onClick:()=>s(!o),style:{left:f.left-24,top:f.top},children:R.jsx(jt,{})}):R.jsx(R.Fragment,{})})}const ut=r=>R.jsxs("div",{className:J.formulaHelpFunctionContentParams,children:[R.jsx("div",{className:`
20
+ `:Ce.formulaSearchFunctionItem,onMouseEnter:()=>_(M),onMouseLeave:y,onMouseMove:N,onClick:()=>{o(T.name),v&&v.focus()},children:[R.jsxs("span",{className:Ce.formulaSearchFunctionItemName,children:[R.jsx("span",{className:Ce.formulaSearchFunctionItemNameLight,children:T.name.substring(0,t.length)}),R.jsx("span",{children:T.name.slice(t.length)})]}),R.jsx("span",{className:Ce.formulaSearchFunctionItemDesc,children:T.desc})]},M))})})}const Mt=r=>r.startsWith(I.operatorToken.EQUALS)?r.slice(1):"",at=()=>{};function sn(r){const{errorText:e,initValue:t,unitId:n,subUnitId:o,isFocus:s=!0,isSupportAcrossSheet:i=!1,onFocus:a=at,onBlur:l=at,onChange:d,onVerify:h,actions:f}=r,u=c.useDependency(ee.IEditorService),m=c.useDependency(I.LexerTreeBuilder),p=S.useRef(null),[C,g]=S.useState(()=>t.startsWith(I.operatorToken.EQUALS)?t:"");f&&(f.handleOutClick=(Y,G)=>{p.current&&!p.current.contains(Y.target)&&G()});const E=S.useMemo(()=>Mt(C),[C]),v=S.useRef(null),[_,y]=S.useState(),[b,N]=S.useState(s),T=S.useRef(null),M=S.useMemo(()=>c.createInternalEditorID(`${P.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),x=S.useMemo(()=>e!==void 0,[e]),w=nt(),D=S.useMemo(()=>w(E),[E]),k=qt(D,Y=>{const G=m.sequenceNodesBuilder(Y);if(G){const Q=G.map(W=>{if(typeof W=="string")return W;if(W.nodeType===I.sequenceNodeType.REFERENCE){const re={...W},oe=I.deserializeRangeWithSheet(W.token);return oe.range=rt(oe.range),i||(oe.sheetName="",oe.unitId=""),re.token=fe([oe],i)[0],re}return W}),H=me(Q);d(`=${H}`)}},_),A=Yt("="),O=pt(n),K=(Y,G=!0)=>{if(!_)return;const Q=w(Y),H=A(_,Q,G);O(H)};Nr(b,h,C);const L=zt(_),U=en(b);S.useLayoutEffect(()=>{if(s){const Y=setTimeout(()=>{N(s),s&&L()},30);return()=>{clearTimeout(Y)}}else U(),N(s)},[s,L]);const{checkScrollBar:j}=tn(_);_t(b,n),Xt(b,_),br(b,n,o,D,i,_,(Y,G,Q)=>{const H=`=${Y}`;k(),g(H),K(Y),Q&&(L(),G!==-1&&setTimeout(()=>{const W={startOffset:G+1,endOffset:G+1};_==null||_.setSelectionRanges([W]);const re=_==null?void 0:_.render.with(ee.DocBackScrollRenderController);re==null||re.scrollToRange({...W,collapsed:!0})},50),j())}),Jt(),vt(b,n,i,N,l,at);const{searchList:Z,searchText:ae,handlerFormulaReplace:le,reset:he}=Cr(b,D,_),{functionInfo:X,paramIndex:ne,reset:ce}=vr(b,C,_);S.useEffect(()=>{if(_){const Y=_.input$.subscribe(G=>{var H,W;const Q=((W=(H=G.data.body)==null?void 0:H.dataStream)!=null?W:"").replaceAll(/\n|\r/g,"");k(),g(Q),K(Mt(Q),!1)});return()=>{Y.unsubscribe()}}},[_]),Kt(E,"=",b,A,O,_),S.useLayoutEffect(()=>{let Y;if(T.current){Y=u.register({autofocus:!0,editorUnitId:M,isSingle:!0,initialSnapshot:{id:M,body:{dataStream:`${t}\r
21
+ `},documentStyle:{}}},T.current);const G=u.getEditor(M);y(G)}return()=>{Y==null||Y.dispose()}},[]);const pe=Y=>{const G=le(Y);if(G){g(`=${G.text}`);const Q=_==null?void 0:_.getSelectionRanges();if(Q&&Q.length===1){const H=Q[0];if(H.collapsed){const W=G.offset;setTimeout(()=>{_==null||_.setSelectionRanges([{startOffset:H.startOffset-W,endOffset:H.endOffset-W}])},30)}}he(),L(),K(G.text)}},_e=()=>{setTimeout(()=>{N(!0),a(),L()},30)};return R.jsxs("div",{className:xe.sheetEmbeddingFormulaEditor,children:[R.jsxs("div",{className:Vt(xe.sheetEmbeddingFormulaEditorWrap,{[xe.sheetEmbeddingFormulaEditorActive]:b,[xe.sheetEmbeddingFormulaEditorError]:x}),ref:p,children:[R.jsx("div",{className:xe.sheetEmbeddingFormulaEditorText,ref:T,onMouseUp:_e}),e!==void 0?R.jsx("div",{className:xe.sheetEmbeddingFormulaEditorErrorWrap,children:e}):null]}),R.jsx(pr,{editorId:M,paramIndex:ne,functionInfo:X,onClose:()=>{ce(),L()}}),R.jsx(jr,{searchText:ae,editorId:M,searchList:Z,onSelect:pe,ref:v})]})}const Wr="sheets-formula-ui.base.config",Ft={};function Br(r){return r.getContextValue(c.FOCUSING_DOC)&&r.getContextValue(c.FOCUSING_UNIVER_EDITOR)&&r.getContextValue(c.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)}function cn(r,e=!1){return!e&&!(c.isFormulaString(r==null?void 0:r.f)||c.isFormulaId(r==null?void 0:r.si))?null:typeof(r==null?void 0:r.v)=="string"&&I.ERROR_TYPE_SET.has(r.v)?r.v:null}var Vr=Object.defineProperty,qr=Object.getOwnPropertyDescriptor,Kr=(r,e,t,n)=>{for(var o=n>1?void 0:n?qr(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Vr(e,t,o),o},Pe=(r,e)=>(t,n)=>e(t,n,r);const lt="SHEET_FORMULA_ALERT",zr={[I.ErrorType.DIV_BY_ZERO]:"divByZero",[I.ErrorType.NAME]:"name",[I.ErrorType.VALUE]:"value",[I.ErrorType.NUM]:"num",[I.ErrorType.NA]:"na",[I.ErrorType.CYCLE]:"cycle",[I.ErrorType.REF]:"ref",[I.ErrorType.SPILL]:"spill",[I.ErrorType.CALC]:"calc",[I.ErrorType.ERROR]:"error",[I.ErrorType.CONNECT]:"connect",[I.ErrorType.NULL]:"null"};let St=class extends c.Disposable{constructor(r,e,t,n,o,s){super(),this._context=r,this._hoverManagerService=e,this._cellAlertManagerService=t,this._localeService=n,this._formulaDataModel=o,this._zenZoneService=s,this._init()}_init(){this._initCellAlertPopup(),this._initZenService()}_initCellAlertPopup(){this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(q.debounceTime(100)).subscribe(r=>{var e,t,n,o,s;if(r){const a=this._context.unit.getActiveSheet();if(!a)return;const l=a.getCell(r.location.row,r.location.col),d=(o=(n=(t=(e=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:e[r.location.unitId])==null?void 0:t[r.location.subUnitId])==null?void 0:n[r.location.row])==null?void 0:o[r.location.col];if(c.isICellData(l)){const h=cn(l,!!d);if(!h){this._hideAlert();return}const f=this._cellAlertManagerService.currentAlert.get(lt),u=(s=f==null?void 0:f.alert)==null?void 0:s.location;if(u&&u.row===r.location.row&&u.col===r.location.col&&u.subUnitId===r.location.subUnitId&&u.unitId===r.location.unitId)return;this._cellAlertManagerService.showAlert({type:P.CellAlertType.ERROR,title:this._localeService.t("formula.error.title"),message:this._localeService.t(`formula.error.${zr[h]}`),location:r.location,width:200,height:74,key:lt});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(r=>{r&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(lt)}};St=Kr([Pe(1,c.Inject(P.HoverManagerService)),Pe(2,c.Inject(P.CellAlertManagerService)),Pe(3,c.Inject(c.LocaleService)),Pe(4,c.Inject(I.FormulaDataModel)),Pe(5,F.IZenZoneService)],St);var Yr=Object.defineProperty,Gr=Object.getOwnPropertyDescriptor,Zr=(r,e,t,n)=>{for(var o=n>1?void 0:n?Gr(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Yr(e,t,o),o},Ot=(r,e)=>(t,n)=>e(t,n,r);let qe=class extends c.Disposable{constructor(r,e){super(),this._autoFillService=r,this._lexerTreeBuilder=e,this._registerAutoFill()}_registerAutoFill(){const r={type:P.DATA_TYPE.FORMULA,priority:1001,match:e=>c.isFormulaString(e==null?void 0:e.f)||c.isFormulaId(e==null?void 0:e.si),isContinue:(e,t)=>e.type===P.DATA_TYPE.FORMULA,applyFunctions:{[P.APPLY_TYPE.COPY]:(e,t,n,o)=>{const{data:s,index:i}=e;return this._fillCopyFormula(s,t,n,i,o)}}};this._autoFillService.registerRule(r)}_fillCopyFormula(r,e,t,n,o){var l,d;const s=Qr(o),i=[],a=new Map;for(let h=1;h<=e;h++){const f=(h-1)%r.length,u=c.Tools.deepClone(r[f]);if(u){const m=((l=r[f])==null?void 0:l.f)||"",p=((d=r[f])==null?void 0:d.si)||"",C=c.isFormulaString(m);if(c.isFormulaId(p))u.si=p,u.f=null,u.v=null,u.p=null,u.t=null,i.push(u);else if(C){let E=a.get(f);if(E)u.si=E,u.f=null,u.v=null,u.p=null,u.t=null;else{E=c.Tools.generateRandomId(6),a.set(f,E);const{offsetX:v,offsetY:_}=Xr(s,e,t),y=this._lexerTreeBuilder.moveFormulaRefOffset(m,v,_);u.si=E,u.f=y,u.v=null,u.p=null,u.t=null}i.push(u)}}}return i}};qe=Zr([Ot(0,P.IAutoFillService),Ot(1,c.Inject(I.LexerTreeBuilder))],qe);function Xr(r,e,t){let n=0,o=0;switch(t){case c.Direction.UP:o=-r*e;break;case c.Direction.RIGHT:n=r;break;case c.Direction.DOWN:o=r;break;case c.Direction.LEFT:n=-r*e;break}return{offsetX:n,offsetY:o}}function Qr(r){let e=0;for(const t in r)r[t].forEach(n=>{e+=n.data.length});return e}var Jr=Object.defineProperty,eo=Object.getOwnPropertyDescriptor,to=(r,e,t,n)=>{for(var o=n>1?void 0:n?eo(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Jr(e,t,o),o},Le=(r,e)=>(t,n)=>e(t,n,r);const no="default-paste-formula";let Ke=class extends c.Disposable{constructor(r,e,t,n,o){super(),this._currentUniverSheet=r,this._lexerTreeBuilder=e,this._sheetClipboardService=t,this._injector=n,this._formulaDataModel=o,this._initialize()}_initialize(){this._registerClipboardHook()}_registerClipboardHook(){this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteFormulaHook())),this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._pasteWithFormulaHook()))}_pasteFormulaHook(){return{id:P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA,priority:10,specialPasteInfo:{label:"specialPaste.formula"},onPasteCells:(r,e,t,n)=>this._onPasteCells(r,e,t,n,!0)}}_pasteWithFormulaHook(){return{id:no,priority:10,onPasteCells:(r,e,t,n)=>this._onPasteCells(r,e,t,n,!1)}}_onPasteCells(r,e,t,n,o){var u;if([P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH].includes(n.pasteType))return{undos:[],redos:[]};const i=this._currentUniverSheet.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),a=e.unitId||i.getUnitId(),l=e.subUnitId||((u=i.getActiveSheet())==null?void 0:u.getSheetId());if(!a||!l)return{undos:[],redos:[]};const d=e.range,h=t,f={copyType:n.copyType||P.COPY_TYPE.COPY,copyRange:r==null?void 0:r.range,pasteType:n.pasteType};return this._injector.invoke(m=>ro(a,l,d,h,m,f,this._lexerTreeBuilder,this._formulaDataModel,o,r))}};Ke=to([Le(0,c.IUniverInstanceService),Le(1,c.Inject(I.LexerTreeBuilder)),Le(2,P.ISheetClipboardService),Le(3,c.Inject(c.Injector)),Le(4,c.Inject(I.FormulaDataModel))],Ke);function ro(r,e,t,n,o,s,i,a,l=!1,d){const h=[],f=[],u=oo(r,e,t,n,s,i,a,d),m={unitId:r,subUnitId:e,cellValue:u.getData()};h.push({id:$.SetRangeValuesMutation.id,params:m});const p=$.SetRangeValuesUndoMutationFactory(o,m);return f.push({id:$.SetRangeValuesMutation.id,params:p}),{undos:f,redos:h}}function oo(r,e,t,n,o,s,i,a){return a?o.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?io(r,e,t,n,i,a):o.pasteType===P.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?co(r,e,t,n,s,i,a):ao(r,e,t,n,s,i,a):so(r,e,t,n,i)}function so(r,e,t,n,o){const s=new c.ObjectMatrix,i=o.getSheetFormulaData(r,e);return n.forValue((a,l,d)=>{var m;const h=t.rows[a],f=t.cols[l],u={};c.isFormulaString(d.v)?(u.v=null,u.f=`${d.v}`,u.si=null,u.p=null,s.setValue(h,f,u)):(m=i==null?void 0:i[h])!=null&&m[f]&&(u.v=d.v,u.f=null,u.si=null,u.p=null,s.setValue(h,f,u))}),s}function io(r,e,t,n,o,s){var d,h;const i=new c.ObjectMatrix,a=(h=(d=o.getArrayFormulaCellData())==null?void 0:d[s.unitId])==null?void 0:h[s.subUnitId],l=o.getSheetFormulaData(r,e);return n.forValue((f,u,m)=>{var _,y;const p=s.range.rows[f%s.range.rows.length],C=s.range.cols[u%s.range.cols.length],g=t.rows[f],E=t.cols[u],v={};if(c.isFormulaString(m.f)||c.isFormulaId(m.si))v.v=m.v,v.f=null,v.si=null,v.p=null,i.setValue(g,E,v);else if((_=a==null?void 0:a[p])!=null&&_[C]){const b=a[p][C];v.v=b.v,v.f=null,v.si=null,v.p=null,i.setValue(g,E,v)}else if((y=l==null?void 0:l[g])!=null&&y[E]){if(v.v=m.v,v.f=null,v.si=null,v.p=null,m.p){const b=an(m);b&&(v.v=b)}i.setValue(g,E,v)}}),i}function co(r,e,t,n,o,s,i){const a=new c.ObjectMatrix,l=new Map;return n.forValue((d,h,f)=>{const u=t.rows[d],m=t.cols[h],p={};if(c.isFormulaId(f.si)){if(i.unitId!==r||i.subUnitId!==e){const C=s.getFormulaStringByCell(i.range.rows[d%i.range.rows.length],i.range.cols[h%i.range.cols.length],i.subUnitId,i.unitId),g=t.cols[h]-i.range.cols[h%i.range.cols.length],E=t.rows[d]-i.range.rows[d%i.range.rows.length],v=o.moveFormulaRefOffset(C||"",g,E);p.si=null,p.f=v}else p.si=f.si,p.f=null;p.v=null,p.p=null,a.setValue(u,m,p)}else if(c.isFormulaString(f.f)){const C=`${d%i.range.rows.length}_${h%i.range.cols.length}`;let g=l.get(C);if(g)p.si=g,p.f=null;else{g=c.Tools.generateRandomId(6),l.set(C,g);const E=t.cols[h]-i.range.cols[h%i.range.cols.length],v=t.rows[d]-i.range.rows[d%i.range.rows.length],_=o.moveFormulaRefOffset(f.f||"",E,v);p.si=g,p.f=_}p.v=null,p.p=null,a.setValue(u,m,p)}else{if(p.v=f.v,p.f=null,p.si=null,p.p=null,f.p){const C=an(f);C&&(p.v=C)}a.setValue(u,m,p)}}),a}function ao(r,e,t,n,o,s,i){const a=new c.ObjectMatrix,l=new Map,d=s.getSheetFormulaData(r,e);return n.forValue((h,f,u)=>{var g;const m=t.rows[h],p=t.cols[f],C={};if(c.isFormulaId(u.si)){if(i.unitId!==r||i.subUnitId!==e){const E=s.getFormulaStringByCell(i.range.rows[h%i.range.rows.length],i.range.cols[f%i.range.cols.length],i.subUnitId,i.unitId),v=t.cols[f]-i.range.cols[f%i.range.cols.length],_=t.rows[h]-i.range.rows[h%i.range.rows.length],y=o.moveFormulaRefOffset(E||"",v,_);C.si=null,C.f=y}else C.si=u.si,C.f=null;C.v=null,C.p=null,a.setValue(m,p,C)}else if(c.isFormulaString(u.f)){const E=`${h%i.range.rows.length}_${f%i.range.cols.length}`;let v=l.get(E);if(v)C.si=v,C.f=null;else{v=c.Tools.generateRandomId(6),l.set(E,v);const _=t.cols[f]-i.range.cols[f%i.range.cols.length],y=t.rows[h]-i.range.rows[h%i.range.rows.length],b=o.moveFormulaRefOffset(u.f||"",_,y);C.si=v,C.f=b}C.v=null,C.p=null,a.setValue(m,p,C)}else(g=d==null?void 0:d[m])!=null&&g[p]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,a.setValue(m,p,C))}),a}function an(r){if(r!=null&&r.p){const e=r==null?void 0:r.p.body;if(e==null)return;const t=e.dataStream;return t.substring(t.length-2,t.length)===c.DEFAULT_EMPTY_DOCUMENT_VALUE?t.substring(0,t.length-2):t}}var lo=Object.defineProperty,uo=Object.getOwnPropertyDescriptor,fo=(r,e,t,n)=>{for(var o=n>1?void 0:n?uo(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&lo(e,t,o),o},ye=(r,e)=>(t,n)=>e(t,n,r);let ze=class extends c.Disposable{constructor(e,t,n,o,s,i,a,l){super();V(this,"_previousShape");V(this,"_skeleton");this._context=e,this._sheetInterceptorService=t,this._formulaDataModel=n,this._themeService=o,this._renderManagerService=s,this._sheetSkeletonManagerService=i,this._commandService=a,this._logService=l,this._initSkeletonChangeListener(),this._initInterceptorEditorStart(),this._commandExecutedListener()}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(e=>{var t,n;if(e==null)this._logService.debug("[FormulaEditorShowController]: should not receive currentSkeleton$ as null!");else{const{skeleton:o}=e,s=(n=(t=this._skeleton)==null?void 0:t.worksheet)==null?void 0:n.getSheetId();if(this._changeRuntime(o),s!==o.worksheet.getSheetId())this._removeArrayFormulaRangeShape();else{const{unitId:i,sheetId:a}=e;this._updateArrayFormulaRangeShape(i,a)}}}))}_changeRuntime(e){this._skeleton=e}_initInterceptorEditorStart(){this.disposeWithMe(c.toDisposable(this._sheetInterceptorService.writeCellInterceptor.intercept($.BEFORE_CELL_EDIT,{handler:(e,t,n)=>{var p,C,g,E;const{row:o,col:s,unitId:i,subUnitId:a,worksheet:l}=t,d=this._formulaDataModel.getArrayFormulaRange(),h=this._formulaDataModel.getArrayFormulaCellData();if(this._removeArrayFormulaRangeShape(),e==null)return n(e);let f=null;const u=this._formulaDataModel.getFormulaStringByCell(o,s,a,i);if(u!==null&&(f={f:u}),e.v!=null&&e.v!==""&&((g=(C=(p=h[i])==null?void 0:p[a])==null?void 0:C[o])==null?void 0:g[s])==null)return f?{...e,...f}:n(e);const m=(E=d==null?void 0:d[i])==null?void 0:E[a];return m!=null&&(f=this._displayArrayFormulaRangeShape(m,o,s,i,a,l,f)),f?{...e,...f}:n(e)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{(e.id===I.SetFormulaCalculationResultMutation.id||e.id===I.SetArrayFormulaDataMutation.id&&t&&t.remove)&&this._removeArrayFormulaRangeShape()})),this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{$.SetWorksheetRowAutoHeightMutation.id===e.id&&requestIdleCallback(()=>{const t=e.params,{unitId:n,subUnitId:o,rowsAutoHeightInfo:s}=t;this._refreshArrayFormulaRangeShapeByRow(n,o,s)})}))}_displayArrayFormulaRangeShape(e,t,n,o,s,i,a){const l=this._formulaDataModel.getSheetFormulaData(o,s);return new c.ObjectMatrix(e).forValue((d,h,f)=>{var g;if(f==null)return!0;const{startRow:u,startColumn:m,endRow:p,endColumn:C}=f;if(d===t&&h===n)return this._createArrayFormulaRangeShape(f,o),!1;if(t>=u&&t<=p&&n>=m&&n<=C){const E=i.getCell(u,m);if((E==null?void 0:E.v)===I.ErrorType.SPILL)return;const v=(g=l==null?void 0:l[d])==null?void 0:g[h];return v==null||v.f==null?!0:(a==null&&(a={f:v.f,isInArrayFormulaRange:!0}),this._createArrayFormulaRangeShape(f,o),!1)}}),a}_createArrayFormulaRangeShape(e,t){const n=this._renderManagerService.getRenderById(t),o=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n||!o)return;const{scene:s}=n;if(!s)return;const i=this._themeService.getCurrentTheme(),a={range:e,primary:null,style:{strokeWidth:1,stroke:i.hyacinth700,fill:new c.ColorKit(i.colorWhite).setAlpha(0).toString(),widgets:{}}},l=P.attachSelectionWithCoord(a,o),{rowHeaderWidth:d,columnHeaderHeight:h}=o,f=new P.SelectionControl(s,P.SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW,this._themeService,{highlightHeader:!1,rowHeaderWidth:d,columnHeaderHeight:h});f.updateRangeBySelectionWithCoord(l),f.setEvent(!1),this._previousShape=f}_removeArrayFormulaRangeShape(){this._previousShape!=null&&(this._previousShape.dispose(),this._previousShape=null)}_refreshArrayFormulaRangeShape(e,t){if(this._previousShape){const{startRow:n,endRow:o,startColumn:s,endColumn:i}=this._previousShape.getRange(),a={startRow:n,endRow:o,startColumn:s,endColumn:i};this._removeArrayFormulaRangeShape(),this._createArrayFormulaRangeShape(a,e)}}_checkCurrentSheet(e,t){const n=this._sheetSkeletonManagerService.getCurrentSkeleton();if(!n)return!1;const o=n.worksheet;return o?o.unitId===e&&o.getSheetId()===t:!1}_updateArrayFormulaRangeShape(e,t){this._checkCurrentSheet(e,t)&&this._previousShape&&this._refreshArrayFormulaRangeShape(e)}_refreshArrayFormulaRangeShapeByRow(e,t,n){if(!this._checkCurrentSheet(e,t)||!this._previousShape)return;const{startRow:o,endRow:s,startColumn:i,endColumn:a}=this._previousShape.getRange();for(let l=0;l<n.length;l++){const{row:d}=n[l];if(o>=d){const h={startRow:o,endRow:s,startColumn:i,endColumn:a};this._refreshArrayFormulaRangeShape(e,h);break}}}};ze=fo([ye(1,c.Inject($.SheetInterceptorService)),ye(2,c.Inject(I.FormulaDataModel)),ye(3,c.Inject(c.ThemeService)),ye(4,z.IRenderManagerService),ye(5,c.Inject(P.SheetSkeletonManagerService)),ye(6,c.ICommandService),ye(7,c.ILogService)],ze);var ho=Object.defineProperty,mo=Object.getOwnPropertyDescriptor,So=(r,e,t,n)=>{for(var o=n>1?void 0:n?mo(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&ho(e,t,o),o},At=(r,e)=>(t,n)=>e(t,n,r);const go={tl:{size:6,color:"#409f11"}};let Ye=class extends c.RxDisposable{constructor(r,e){super(),this._sheetInterceptorService=r,this._formulaDataModel=e,this.disposeWithMe(this._sheetInterceptorService.intercept($.INTERCEPTOR_POINT.CELL_CONTENT,{effect:c.InterceptorEffectEnum.Style,handler:(t,n,o)=>{var a,l,d,h;const s=(h=(d=(l=(a=this._formulaDataModel.getArrayFormulaCellData())==null?void 0:a[n.unitId])==null?void 0:l[n.subUnitId])==null?void 0:d[n.row])==null?void 0:h[n.col];return cn(t,!!s)?o({...t,markers:{...t==null?void 0:t.markers,...go}}):o(t)},priority:10}))}};Ye=So([At(0,c.Inject($.SheetInterceptorService)),At(1,c.Inject(I.FormulaDataModel))],Ye);function po(){const r=c.useDependency(ge.TriggerCalculationController),e=c.useDependency(c.ICommandService),t=c.useObservable(r.progress$),n=S.useCallback(()=>{e.executeCommand(I.SetFormulaCalculationStopMutation.id)},[e]),o=S.useCallback(()=>{r.clearProgress()},[r]);return R.jsx(F.ProgressBar,{progress:t,onTerminate:n,onClearProgress:o})}const _o=(r,e=100)=>{S.useEffect(()=>{let t=null;const n=()=>{t===null&&(t=window.setTimeout(()=>{r(),t=null},e))};return window.addEventListener("scroll",n),window.addEventListener("resize",n),()=>{t!==null&&clearTimeout(t),window.removeEventListener("scroll",n),window.removeEventListener("resize",n)}},[r,e])},vo="univer-formula-help-function",Co="univer-formula-help-function-title",Ro="univer-formula-help-function-title-icons",Io="univer-formula-help-function-title-icon",Eo="univer-formula-help-function-content",yo="univer-formula-help-function-content-inner",To="univer-formula-help-function-content-params",bo="univer-formula-help-function-content-params-title",No="univer-formula-help-function-content-params-detail",xo="univer-formula-help-function-active",Mo="univer-formula-help-decorator",Fo="univer-formula-help-param",Oo="univer-formula-help-param-prefix",Ao="univer-formula-help-param-item",Do="univer-formula-help-param-active",J={formulaHelpFunction:vo,formulaHelpFunctionTitle:Co,formulaHelpFunctionTitleIcons:Ro,formulaHelpFunctionTitleIcon:Io,formulaHelpFunctionContent:Eo,formulaHelpFunctionContentInner:yo,formulaHelpFunctionContentParams:To,formulaHelpFunctionContentParamsTitle:bo,formulaHelpFunctionContentParamsDetail:No,formulaHelpFunctionActive:xo,formulaHelpDecorator:Mo,formulaHelpParam:Fo,formulaHelpParamPrefix:Oo,formulaHelpParamItem:Ao,formulaHelpParamActive:Do};function Po(){const[r,e]=S.useState(!1),[t,n]=S.useState(!0),[o,s]=S.useState(!0),[i,a]=S.useState(0),[l,d]=S.useState([0,0]),[h,f]=S.useState({left:0,top:0}),[u,m]=S.useState(null),p=c.useDependency(Fe),C=c.useDependency(c.LocaleService),g=C.t("formula.prompt.required"),E=C.t("formula.prompt.optional"),v=c.useDependency(c.IUniverInstanceService),_=c.useDependency(ee.IEditorService),y=c.useDependency(F.ISidebarService),b=c.useInjector();_o(N),S.useEffect(()=>{const w=p.help$.subscribe(k=>{const{visible:A,paramIndex:O,functionInfo:K}=k;if(!A){e(A);return}const L=T();if(L==null)return;const{left:U,top:j,height:B}=L;K.description===""&&K.functionParameter.length===0||(d([U,j+B]),a(O),m(K),f({left:U,top:j}),e(A))}),D=y.scrollEvent$.pipe(q.throttleTime(100)).subscribe(N);return()=>{w==null||w.unsubscribe(),D.unsubscribe()}},[]);function N(){if(!o)return;const w=T();if(w==null)return;const{left:D,top:k,height:A}=w;d([D,k+A])}function T(){const w=v.getCurrentUniverDocInstance();if(!w)return;const D=w.getUnitId();if(!_.isEditor(D))return;const k=_.getEditor(D);return k==null?void 0:k.getBoundingClientRect()}function M(w){a(w)}function x(){s(!o),b.get(F.ILayoutService).focus()}return R.jsx(R.Fragment,{children:o?R.jsx(ie.Popup,{visible:r,offset:l,children:u?R.jsxs("div",{className:J.formulaHelpFunction,children:[R.jsxs("div",{className:J.formulaHelpFunctionTitle,children:[R.jsx(Lo,{prefix:u.functionName,value:u.functionParameter,active:i,onClick:M}),R.jsxs("div",{className:J.formulaHelpFunctionTitleIcons,children:[R.jsx("div",{className:J.formulaHelpFunctionTitleIcon,style:{transform:t?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>n(!t),children:R.jsx(gt,{})}),R.jsx("div",{className:J.formulaHelpFunctionTitleIcon,onClick:x,children:R.jsx(tt,{})})]})]}),R.jsx("div",{className:J.formulaHelpFunctionContent,style:{height:t?"unset":0,padding:t?"revert-layer":0},children:R.jsxs("div",{className:J.formulaHelpFunctionContentInner,children:[R.jsx(ut,{title:C.t("formula.prompt.helpExample"),value:`${u.functionName}(${u.functionParameter.map(w=>w.example).join(",")})`}),R.jsx(ut,{title:C.t("formula.prompt.helpAbstract"),value:u.description}),u&&u.functionParameter&&u.functionParameter.map((w,D)=>R.jsx(ut,{className:i===D?J.formulaHelpFunctionActive:"",title:w.name,value:`${w.require?g:E} ${w.detail}`},D))]})})]}):R.jsx(R.Fragment,{})}):r?R.jsx("div",{className:J.formulaHelpDecorator,onClick:()=>s(!o),style:{left:h.left-24,top:h.top},children:R.jsx(jt,{})}):R.jsx(R.Fragment,{})})}const ut=r=>R.jsxs("div",{className:J.formulaHelpFunctionContentParams,children:[R.jsx("div",{className:`
22
22
  ${J.formulaHelpFunctionContentParamsTitle}
23
23
  ${r.className}
24
- `,children:r.title}),R.jsx("div",{className:J.formulaHelpFunctionContentParamsDetail,children:r.value})]}),Lo=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return R.jsxs("div",{className:J.formulaHelpParam,children:[R.jsxs("span",{className:J.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>R.jsxs("span",{className:J.formulaHelpParamItem,children:[R.jsx("span",{className:n===i?J.formulaHelpFunctionActive:J.formulaHelpParamActive,onClick:()=>o(i),children:Ct(s)}),i===t.length-1?"":","]},i)),")"]})},wo="univer-formula-search-function",ko="univer-formula-search-function-item",Uo="univer-formula-search-function-item-name",$o="univer-formula-search-function-item-name-light",jo="univer-formula-search-function-item-desc",Ho="univer-formula-search-function-item-active",Re={formulaSearchFunction:wo,formulaSearchFunctionItem:ko,formulaSearchFunctionItemName:Uo,formulaSearchFunctionItemNameLight:$o,formulaSearchFunctionItemDesc:jo,formulaSearchFunctionItemActive:Ho};function Wo(){const[r,e]=m.useState(!1),[t,n]=m.useState(0),[o,s]=m.useState([0,0]),[i,a]=m.useState([]),[l,d]=m.useState(""),f=m.useRef(null),h=c.useDependency(Fe),u=c.useDependency(c.IUniverInstanceService),S=c.useDependency(ee.IEditorService);m.useEffect(()=>{let _=[],v=0;const y=h.search$.subscribe(T=>{const{visible:M,searchText:x,searchList:w}=T;if(!M){e(M);return}const D=p();if(D==null)return;const{left:k,top:A,height:O}=D;d(x),a(w),_=w,s([k,A+O]),e(M),n(0),v=0}),b=h.navigate$.subscribe(T=>{const{direction:M}=T;if(M===c.Direction.UP){let x=v-1;x=x<0?_.length-1:x,n(x),v=x}else if(M===c.Direction.DOWN){let x=v+1;x=x>=_.length?0:x,n(x),v=x}E(v)}),N=h.accept$.subscribe(T=>{const M=_[v].name;h.acceptFormulaName(M)});return()=>{y==null||y.unsubscribe(),b==null||b.unsubscribe(),N==null||N.unsubscribe()}},[]);function p(){const v=u.getCurrentUniverDocInstance().getUnitId();if(!S.isEditor(v))return;const y=S.getEditor(v);return y==null?void 0:y.getBoundingClientRect()}function C(_){n(_)}function g(){n(-1)}function E(_){var k;const v=(k=f.current)==null?void 0:k.querySelectorAll(`.${Re.formulaSearchFunctionItem}`)[_];if(!v)return;const y=v.parentNode;if(!y)return;const N=y.getBoundingClientRect().top,T=y.offsetHeight,M=v.getBoundingClientRect(),x=M.top,w=M.height;if(x>=0&&x>N&&x-N+w<=T)return;const D=v.offsetTop-(T-w)/2;y.scrollTo({top:D,behavior:"smooth"})}return i.length>0&&R.jsx(ie.Popup,{visible:r,offset:o,children:R.jsx("ul",{className:Re.formulaSearchFunction,ref:f,children:i.map((_,v)=>R.jsxs("li",{className:t===v?`
24
+ `,children:r.title}),R.jsx("div",{className:J.formulaHelpFunctionContentParamsDetail,children:r.value})]}),Lo=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return R.jsxs("div",{className:J.formulaHelpParam,children:[R.jsxs("span",{className:J.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>R.jsxs("span",{className:J.formulaHelpParamItem,children:[R.jsx("span",{className:n===i?J.formulaHelpFunctionActive:J.formulaHelpParamActive,onClick:()=>o(i),children:Ct(s)}),i===t.length-1?"":","]},i)),")"]})},wo="univer-formula-search-function",ko="univer-formula-search-function-item",Uo="univer-formula-search-function-item-name",$o="univer-formula-search-function-item-name-light",jo="univer-formula-search-function-item-desc",Ho="univer-formula-search-function-item-active",Re={formulaSearchFunction:wo,formulaSearchFunctionItem:ko,formulaSearchFunctionItemName:Uo,formulaSearchFunctionItemNameLight:$o,formulaSearchFunctionItemDesc:jo,formulaSearchFunctionItemActive:Ho};function Wo(){const[r,e]=S.useState(!1),[t,n]=S.useState(0),[o,s]=S.useState([0,0]),[i,a]=S.useState([]),[l,d]=S.useState(""),h=S.useRef(null),f=c.useDependency(Fe),u=c.useDependency(c.IUniverInstanceService),m=c.useDependency(ee.IEditorService);S.useEffect(()=>{let v=[],_=0;const y=f.search$.subscribe(T=>{const{visible:M,searchText:x,searchList:w}=T;if(!M){e(M);return}const D=p();if(D==null)return;const{left:k,top:A,height:O}=D;d(x),a(w),v=w,s([k,A+O]),e(M),n(0),_=0}),b=f.navigate$.subscribe(T=>{const{direction:M}=T;if(M===c.Direction.UP){let x=_-1;x=x<0?v.length-1:x,n(x),_=x}else if(M===c.Direction.DOWN){let x=_+1;x=x>=v.length?0:x,n(x),_=x}E(_)}),N=f.accept$.subscribe(T=>{const M=v[_].name;f.acceptFormulaName(M)});return()=>{y==null||y.unsubscribe(),b==null||b.unsubscribe(),N==null||N.unsubscribe()}},[]);function p(){const _=u.getCurrentUniverDocInstance().getUnitId();if(!m.isEditor(_))return;const y=m.getEditor(_);return y==null?void 0:y.getBoundingClientRect()}function C(v){n(v)}function g(){n(-1)}function E(v){var k;const _=(k=h.current)==null?void 0:k.querySelectorAll(`.${Re.formulaSearchFunctionItem}`)[v];if(!_)return;const y=_.parentNode;if(!y)return;const N=y.getBoundingClientRect().top,T=y.offsetHeight,M=_.getBoundingClientRect(),x=M.top,w=M.height;if(x>=0&&x>N&&x-N+w<=T)return;const D=_.offsetTop-(T-w)/2;y.scrollTo({top:D,behavior:"smooth"})}return i.length>0&&R.jsx(ie.Popup,{visible:r,offset:o,children:R.jsx("ul",{className:Re.formulaSearchFunction,ref:h,children:i.map((v,_)=>R.jsxs("li",{className:t===_?`
25
25
  ${Re.formulaSearchFunctionItem}
26
26
  ${Re.formulaSearchFunctionItemActive}
27
- `:Re.formulaSearchFunctionItem,onMouseEnter:()=>C(v),onMouseLeave:g,onClick:()=>h.acceptFormulaName(_.name),children:[R.jsxs("span",{className:Re.formulaSearchFunctionItemName,children:[R.jsx("span",{className:Re.formulaSearchFunctionItemNameLight,children:_.name.substring(0,l.length)}),R.jsx("span",{children:_.name.slice(l.length)})]}),R.jsx("span",{className:Re.formulaSearchFunctionItemDesc,children:_.desc})]},v))})})}function Bo(){return R.jsxs(R.Fragment,{children:[R.jsx(Wo,{}),R.jsx(Po,{})]})}const Vo="univer-formula-more-functions",qo="univer-formula-more-functions-operation",Dt={formulaMoreFunctions:Vo,formulaMoreFunctionsOperation:qo};function ln(r){const{prefix:e,value:t}=r;return R.jsxs("div",{children:[R.jsxs("span",{children:[e,"("]}),t&&t.map((n,o)=>R.jsxs("span",{children:[R.jsx("span",{children:Ct(n)}),o===t.length-1?"":","]},o)),")"]})}const Ko="univer-formula-function-params",zo="univer-formula-function-params-title",Yo="univer-formula-function-params-detail",dt={formulaFunctionParams:Ko,formulaFunctionParamsTitle:zo,formulaFunctionParamsDetail:Yo};function ke(r){const{className:e,value:t,title:n}=r;return R.jsxs("div",{className:dt.formulaFunctionParams,children:[R.jsx("div",{className:`
27
+ `:Re.formulaSearchFunctionItem,onMouseEnter:()=>C(_),onMouseLeave:g,onClick:()=>f.acceptFormulaName(v.name),children:[R.jsxs("span",{className:Re.formulaSearchFunctionItemName,children:[R.jsx("span",{className:Re.formulaSearchFunctionItemNameLight,children:v.name.substring(0,l.length)}),R.jsx("span",{children:v.name.slice(l.length)})]}),R.jsx("span",{className:Re.formulaSearchFunctionItemDesc,children:v.desc})]},_))})})}function Bo(){return R.jsxs(R.Fragment,{children:[R.jsx(Wo,{}),R.jsx(Po,{})]})}const Vo="univer-formula-more-functions",qo="univer-formula-more-functions-operation",Dt={formulaMoreFunctions:Vo,formulaMoreFunctionsOperation:qo};function ln(r){const{prefix:e,value:t}=r;return R.jsxs("div",{children:[R.jsxs("span",{children:[e,"("]}),t&&t.map((n,o)=>R.jsxs("span",{children:[R.jsx("span",{children:Ct(n)}),o===t.length-1?"":","]},o)),")"]})}const Ko="univer-formula-function-params",zo="univer-formula-function-params-title",Yo="univer-formula-function-params-detail",dt={formulaFunctionParams:Ko,formulaFunctionParamsTitle:zo,formulaFunctionParamsDetail:Yo};function ke(r){const{className:e,value:t,title:n}=r;return R.jsxs("div",{className:dt.formulaFunctionParams,children:[R.jsx("div",{className:`
28
28
  ${dt.formulaFunctionParamsTitle}
29
29
  ${e}
30
- `,children:n}),R.jsx("div",{className:dt.formulaFunctionParamsDetail,children:t})]})}const Go="univer-formula-input-params-list",Zo="univer-formula-input-params-list-item-name",Xo="univer-formula-input-params-list-item-selector",we={formulaInputParamsList:Go,formulaInputParamsListItemName:Zo,formulaInputParamsListItemSelector:Xo};function Qo(r){const{functionInfo:e,onChange:t}=r;if(!e)return null;m.useState([]);const[n,o]=m.useState(e.functionParameter),[s,i]=m.useState(-1);return R.jsxs("div",{className:we.formulaInputParams,children:[R.jsx("div",{className:we.formulaInputParamsList,children:n.map((a,l)=>R.jsxs("div",{children:[R.jsx("div",{className:we.formulaInputParamsListItemName,children:a.name}),R.jsx("div",{className:we.formulaInputParamsListItemSelector})]},l))}),R.jsx("div",{className:we.formulaInputParamsInfo,children:R.jsx(ke,{title:s===-1?R.jsx(ln,{prefix:e.functionName,value:n}):n[s].name,value:s===-1?e.description:n[s].detail})})]})}const Jo="univer-formula-select-function-select",es="univer-formula-select-function-result",ts="univer-formula-select-function-result-item",ns="univer-formula-select-function-result-item-name-light",rs="univer-formula-select-function-result-item-selected",os="univer-formula-select-function-result-item-active",ss="univer-formula-select-function-content",Se={formulaSelectFunctionSelect:Jo,formulaSelectFunctionResult:es,formulaSelectFunctionResultItem:ts,formulaSelectFunctionResultItemNameLight:ns,formulaSelectFunctionResultItemSelected:rs,formulaSelectFunctionResultItemActive:os,formulaSelectFunctionContent:ss};function is(r){const{onChange:e}=r,t="-1",[n,o]=m.useState(""),[s,i]=m.useState([]),[a,l]=m.useState(0),[d,f]=m.useState(t),[h,u]=m.useState(0),[S,p]=m.useState(null),C=c.useDependency(ge.IDescriptionService),g=c.useDependency(c.LocaleService),E=c.useDependency(F.ISidebarService),_=c.useObservable(E.sidebarOptions$),v=er(I.FunctionType,g);v.unshift({label:g.t("formula.moreFunctions.allFunctions"),value:t});const y=g.t("formula.prompt.required"),b=g.t("formula.prompt.optional");m.useEffect(()=>{M(t)},[]),m.useEffect(()=>{T(0)},[s]),m.useEffect(()=>{_!=null&&_.visible&&(o(""),i([]),l(0),f(t),u(0),p(null),M(t))},[_]);const N=A=>{if(n.trim()==="")return A;const O=new RegExp(`(${n.toLocaleUpperCase()})`);return A.split(O).filter(Boolean).map((L,U)=>L.match(O)?R.jsx("span",{className:Se.formulaSelectFunctionResultItemNameLight,children:L},U):L)},T=A=>{if(s.length===0){p(null);return}u(A);const O=C.getFunctionInfo(s[A].name);if(!O){p(null);return}p(O),e(O)};function M(A){f(A);const O=C.getSearchListByType(+A);i(O)}function x(A){o(A);const O=C.getSearchListByName(A);i(O)}function w(A){if(A.stopPropagation(),A.key==="ArrowDown"){const O=a+1;l(O===s.length?0:O)}else if(A.key==="ArrowUp"){const O=a-1;l(O===-1?s.length-1:O)}else A.key==="Enter"&&T(a)}const D=A=>{l(A)},k=()=>{l(-1)};return R.jsxs("div",{children:[R.jsxs("div",{className:Se.formulaSelectFunctionSelect,children:[R.jsx(ie.Select,{value:d,options:v,onChange:M}),R.jsx(ie.Input,{placeholder:g.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:w,value:n,onChange:x,size:"large",allowClear:!0})]}),R.jsx("ul",{className:Se.formulaSelectFunctionResult,onKeyDown:w,tabIndex:-1,children:s.map(({name:A},O)=>R.jsxs("li",{className:a===O?`
30
+ `,children:n}),R.jsx("div",{className:dt.formulaFunctionParamsDetail,children:t})]})}const Go="univer-formula-input-params-list",Zo="univer-formula-input-params-list-item-name",Xo="univer-formula-input-params-list-item-selector",we={formulaInputParamsList:Go,formulaInputParamsListItemName:Zo,formulaInputParamsListItemSelector:Xo};function Qo(r){const{functionInfo:e,onChange:t}=r;if(!e)return null;S.useState([]);const[n,o]=S.useState(e.functionParameter),[s,i]=S.useState(-1);return R.jsxs("div",{className:we.formulaInputParams,children:[R.jsx("div",{className:we.formulaInputParamsList,children:n.map((a,l)=>R.jsxs("div",{children:[R.jsx("div",{className:we.formulaInputParamsListItemName,children:a.name}),R.jsx("div",{className:we.formulaInputParamsListItemSelector})]},l))}),R.jsx("div",{className:we.formulaInputParamsInfo,children:R.jsx(ke,{title:s===-1?R.jsx(ln,{prefix:e.functionName,value:n}):n[s].name,value:s===-1?e.description:n[s].detail})})]})}const Jo="univer-formula-select-function-select",es="univer-formula-select-function-result",ts="univer-formula-select-function-result-item",ns="univer-formula-select-function-result-item-name-light",rs="univer-formula-select-function-result-item-selected",os="univer-formula-select-function-result-item-active",ss="univer-formula-select-function-content",Se={formulaSelectFunctionSelect:Jo,formulaSelectFunctionResult:es,formulaSelectFunctionResultItem:ts,formulaSelectFunctionResultItemNameLight:ns,formulaSelectFunctionResultItemSelected:rs,formulaSelectFunctionResultItemActive:os,formulaSelectFunctionContent:ss};function is(r){const{onChange:e}=r,t="-1",[n,o]=S.useState(""),[s,i]=S.useState([]),[a,l]=S.useState(0),[d,h]=S.useState(t),[f,u]=S.useState(0),[m,p]=S.useState(null),C=c.useDependency(ge.IDescriptionService),g=c.useDependency(c.LocaleService),E=c.useDependency(F.ISidebarService),v=c.useObservable(E.sidebarOptions$),_=er(I.FunctionType,g);_.unshift({label:g.t("formula.moreFunctions.allFunctions"),value:t});const y=g.t("formula.prompt.required"),b=g.t("formula.prompt.optional");S.useEffect(()=>{M(t)},[]),S.useEffect(()=>{T(0)},[s]),S.useEffect(()=>{v!=null&&v.visible&&(o(""),i([]),l(0),h(t),u(0),p(null),M(t))},[v]);const N=A=>{if(n.trim()==="")return A;const O=new RegExp(`(${n.toLocaleUpperCase()})`);return A.split(O).filter(Boolean).map((L,U)=>L.match(O)?R.jsx("span",{className:Se.formulaSelectFunctionResultItemNameLight,children:L},U):L)},T=A=>{if(s.length===0){p(null);return}u(A);const O=C.getFunctionInfo(s[A].name);if(!O){p(null);return}p(O),e(O)};function M(A){h(A);const O=C.getSearchListByType(+A);i(O)}function x(A){o(A);const O=C.getSearchListByName(A);i(O)}function w(A){if(A.stopPropagation(),A.key==="ArrowDown"){const O=a+1;l(O===s.length?0:O)}else if(A.key==="ArrowUp"){const O=a-1;l(O===-1?s.length-1:O)}else A.key==="Enter"&&T(a)}const D=A=>{l(A)},k=()=>{l(-1)};return R.jsxs("div",{children:[R.jsxs("div",{className:Se.formulaSelectFunctionSelect,children:[R.jsx(ie.Select,{value:d,options:_,onChange:M}),R.jsx(ie.Input,{placeholder:g.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:w,value:n,onChange:x,size:"large",allowClear:!0})]}),R.jsx("ul",{className:Se.formulaSelectFunctionResult,onKeyDown:w,tabIndex:-1,children:s.map(({name:A},O)=>R.jsxs("li",{className:a===O?`
31
31
  ${Se.formulaSelectFunctionResultItem}
32
32
  ${Se.formulaSelectFunctionResultItemActive}
33
- `:Se.formulaSelectFunctionResultItem,onMouseEnter:()=>D(O),onMouseLeave:k,onClick:()=>T(O),children:[h===O&&R.jsx(Ut,{className:Se.formulaSelectFunctionResultItemSelected}),R.jsx("span",{className:Se.formulaSelectFunctionResultItemName,children:N(A)})]},O))}),S&&R.jsxs("div",{className:Se.formulaSelectFunctionContent,children:[R.jsx(ke,{title:S.functionName,value:S.description}),R.jsx(ke,{title:g.t("formula.moreFunctions.syntax"),value:R.jsx(ln,{prefix:S.functionName,value:S.functionParameter})}),R.jsx(ke,{title:g.t("formula.prompt.helpExample"),value:`${S.functionName}(${S.functionParameter.map(A=>A.example).join(",")})`}),S.functionParameter&&S.functionParameter.map((A,O)=>R.jsx(ke,{title:A.name,value:`${A.require?y:b} ${A.detail}`},O))]})]})}function cs(){const r=P.useActiveWorkbook(),[e,t]=m.useState(!0),[n,o]=m.useState(!1),[s,i]=m.useState(null),a=c.useDependency(c.LocaleService),l=c.useDependency(ee.IEditorService);function d(){t(!e),o(!n)}function f(){l.setFormula(`=${s==null?void 0:s.functionName}(`)}return R.jsxs("div",{className:Dt.formulaMoreFunctions,children:[e&&R.jsx(is,{onChange:i}),n&&R.jsx(Qo,{functionInfo:s,onChange:()=>{}}),R.jsxs("div",{className:Dt.formulaMoreFunctionsOperation,children:[n&&R.jsx(ie.Button,{type:"primary",size:"small",onClick:d,children:a.t("formula.moreFunctions.next")}),n&&R.jsx(ie.Button,{size:"small",onClick:d,children:a.t("formula.moreFunctions.prev")}),e&&!!r&&R.jsx(ie.Button,{type:"primary",size:"small",onClick:f,children:a.t("formula.moreFunctions.confirm")})]})]})}function as(r){return{id:Qe.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:F.MenuItemType.SELECTOR,selections:[{label:"SUM",value:"SUM",icon:"SumSingle"},{label:"AVERAGE",value:"AVERAGE",icon:"AvgSingle"},{label:"COUNT",value:"COUNT",icon:"CntSingle"},{label:"MAX",value:"MAX",icon:"MaxSingle"},{label:"MIN",value:"MIN",icon:"MinSingle"}],hidden$:F.getMenuHiddenObservable(r,c.UniverInstanceType.UNIVER_SHEET),disabled$:P.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],worksheetTypes:[$.WorksheetEditPermission,$.WorksheetSetCellValuePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint]})}}function ls(r){return{id:Je.id,title:"formula.insert.more",type:F.MenuItemType.BUTTON}}function us(r){return r.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(q.switchMap(n=>n&&r.get(F.IClipboardInterfaceService)?new q.Observable(s=>s.next(!r.get(F.IClipboardInterfaceService).supportClipboard)):q.of(!0)))}function ds(r){return{id:Xe.id,type:F.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:us(r).pipe(q.combineLatestWith(P.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint],worksheetTypes:[$.WorksheetSetCellValuePermission,$.WorksheetEditPermission]})),q.map(([e,t])=>e||t))}}const hs={[F.RibbonStartGroup.FORMULAS_INSERT]:{[Qe.id]:{order:1,menuItemFactory:as,[Je.id]:{order:1,menuItemFactory:ls}}},[P.PASTE_SPECIAL_MENU_ID]:{[Xe.id]:{order:4,menuItemFactory:ds}}},un="meta_key_ctrl_And_Shift",ot=[F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP,F.KeyCode.ARROW_LEFT,F.KeyCode.ARROW_RIGHT],fs=[...ot,F.KeyCode.ENTER,F.KeyCode.TAB,F.KeyCode.ESC];function ms(){const r=[];for(const e of fs)r.push({id:Ie.id,binding:e,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e}});return r}function Ss(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|F.MetaKeys.SHIFT,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,metaKey:F.MetaKeys.SHIFT}});return r}function gs(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|F.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,metaKey:F.MetaKeys.CTRL_COMMAND}});return r}function ps(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|F.MetaKeys.SHIFT|F.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,metaKey:un}});return r}const vs={id:et.id,binding:F.KeyCode.F4,preconditions:r=>P.whenFormulaEditorActivated(r)};function _s(){const r=[];for(const e of[F.KeyCode.ENTER,F.KeyCode.TAB,F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP])r.push({id:Ie.id,binding:e,preconditions:t=>Br(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,isSingleEditor:!0}});return r}var Cs=Object.defineProperty,Rs=Object.getOwnPropertyDescriptor,Is=(r,e,t,n)=>{for(var o=n>1?void 0:n?Rs(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Cs(e,t,o),o},Te=(r,e)=>(t,n)=>e(t,n,r);let Ge=class extends c.Disposable{constructor(r,e,t,n,o,s,i){super(),this._injector=r,this._menuManagerService=e,this._commandService=t,this._shortcutService=n,this._uiPartsService=o,this._renderManagerService=s,this._componentManager=i,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(hs)}_registerCommands(){[Xe,Qe,Je,Be,He,Ie,et].forEach(r=>this.disposeWithMe(this._commandService.registerCommand(r)))}_registerShortcuts(){[...ms(),...Ss(),...gs(),...ps(),..._s(),vs].forEach(r=>{this.disposeWithMe(this._shortcutService.registerShortcut(r))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(F.BuiltInUIPart.CONTENT,()=>c.connectInjector(Bo,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent(P.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(po,this._injector))),this._componentManager.register(wt,cs)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[ze]))}};Ge=Is([Te(0,c.Inject(c.Injector)),Te(1,F.IMenuManagerService),Te(2,c.ICommandService),Te(3,F.IShortcutService),Te(4,F.IUIPartsService),Te(5,z.IRenderManagerService),Te(6,c.Inject(F.ComponentManager))],Ge);var Es=Object.defineProperty,ys=Object.getOwnPropertyDescriptor,Ts=(r,e,t,n)=>{for(var o=n>1?void 0:n?ys(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Es(e,t,o),o},se=(r,e)=>(t,n)=>e(t,n,r);const bs=[c.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let Ze=class extends c.Disposable{constructor(e,t,n,o,s,i,a,l,d,f,h,u,S,p,C){super();V(this,"_listenInputCache",new Set);V(this,"_formulaRefColors",[]);V(this,"_previousSequenceNodes");V(this,"_previousRangesCount",0);V(this,"_previousInsertRefStringIndex");V(this,"_currentInsertRefStringIndex",-1);V(this,"_arrowMoveActionState",0);V(this,"_isSelectionMovingRefSelections",[]);V(this,"_stringColor","");V(this,"_numberColor","");V(this,"_insertSelections",[]);V(this,"_inputPanelState",0);V(this,"_userCursorMove",!1);V(this,"_previousEditorUnitId");V(this,"_existsSequenceNode",!1);V(this,"_currentlyWorkingRefRenderer",null);V(this,"_selectionsChangeDisposables");V(this,"_isSelectingMode",!1);this._commandService=e,this._contextService=t,this._editorBridgeService=n,this._formulaPromptService=o,this._lexerTreeBuilder=s,this._renderManagerService=i,this._themeService=a,this._sheetsSelectionsService=l,this._refSelectionsService=d,this._univerInstanceService=f,this._descriptionService=h,this._docSelectionManagerService=u,this._contextMenuService=S,this._editorService=p,this._layoutService=C,this._initialize()}get _selectionRenderService(){return this._renderManagerService.getRenderById(this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(exports.RefSelectionsRenderService)}get _allSelectionRenderServices(){return this._renderManagerService.getAllRenderersOfType(c.UniverInstanceType.UNIVER_SHEET).map(e=>e.with(exports.RefSelectionsRenderService))}dispose(){this._formulaRefColors=[],this._resetTemp()}_resetTemp(){this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._isSelectionMovingRefSelections=[],this._previousRangesCount=0,this._currentInsertRefStringIndex=-1}_initialize(){this._initialCursorSync(),this._initAcceptFormula(),this._initialFormulaTheme(),this._initSelectionsEndListener(),this._closeRangePromptWhenEditorInvisible(),this._initialEditorInputChange(),this._commandExecutedListener(),this._cursorStateListener(),this._inputFormulaListener(),this._userMouseListener(),this._initialChangeEditor()}_initialFormulaTheme(){const e=this._themeService.getCurrentTheme();this._formulaRefColors=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],this._numberColor=e.hyacinth700,this._stringColor=e.verdancy800}_initialCursorSync(){this.disposeWithMe(this._docSelectionManagerService.textSelection$.pipe(q.filter(e=>!P.isRangeSelector(e.unitId)&&!P.isEmbeddingFormulaEditor(e.unitId))).subscribe(e=>{var o;if((e==null?void 0:e.unitId)==null)return;const t=this._editorService.getEditor(e.unitId);if(!t||t.onlyInputContent()||t.isSheetEditor()&&!this._isFormulaEditorActivated()||t.params.scrollBar)return;const n=t.onlyInputRange();(o=e==null?void 0:e.options)!=null&&o.fromSelection||(this._quitSelectingMode(),this._contextSwitch(),this._checkShouldEnterSelectingMode(n),!this._formulaPromptService.isLockedSelectionChange()&&(this._highlightFormula(),!n&&this._changeFunctionPanelState()))}))}_initialEditorInputChange(){const e=[F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP,F.KeyCode.ARROW_LEFT,F.KeyCode.ARROW_RIGHT,F.KeyCode.CTRL,F.KeyCode.SHIFT];this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(q.filter(t=>{const n=(t==null?void 0:t.getUnitId())||"";return!P.isRangeSelector(n)&&!P.isEmbeddingFormulaEditor(n)})).subscribe(t=>{var i;const n=t==null?void 0:t.getUnitId();if(n==null||this._listenInputCache.has(n)||this._editorService.getEditor(n)==null)return;const s=(i=this._renderManagerService.getRenderById(n))==null?void 0:i.with(ee.DocSelectionRenderService);s&&this.disposeWithMe(s.onInputBefore$.subscribe(a=>{this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._selectionRenderService.setSkipLastEnabled(!0);const l=a==null?void 0:a.event;l&&(e.includes(l.which)?this._inputPanelState=2:(this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._inputPanelState=1),l.which!==F.KeyCode.F4&&(this._userCursorMove=!1))})),this._listenInputCache.add(n)})}_closeRangePromptWhenEditorInvisible(){this.disposeWithMe(this._editorBridgeService.afterVisible$.pipe(q.distinctUntilKeyChanged("visible")).subscribe(e=>{e.visible||this._closeRangePrompt()})),this.disposeWithMe(this._contextService.subscribeContextValue$(c.FORMULA_EDITOR_ACTIVATED).pipe(q.distinctUntilChanged()).subscribe(e=>{e||this._closeRangePrompt()}))}_initialChangeEditor(){this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(q.filter(e=>{const t=(e==null?void 0:e.getUnitId())||"";return!P.isRangeSelector(t)&&!P.isEmbeddingFormulaEditor(t)})).subscribe(e=>{if(e==null)return;const t=e.getUnitId();!this._editorService.isEditor(t)||this._previousEditorUnitId===t||this._editorService.isSheetEditor(t)||(this._closeRangePrompt(t),this._previousEditorUnitId=t)})),this.disposeWithMe(this._editorService.closeRangePrompt$.subscribe(()=>{(!this._editorService.getSpreadsheetFocusState()||!this._formulaPromptService.isLockedSelectionInsert())&&this._closeRangePrompt()}))}_closeRangePrompt(e){var n;const t=e||((n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:n.getUnitId())||"";P.isRangeSelector(t)||P.isEmbeddingFormulaEditor(t)||t===c.DOCS_ZEN_EDITOR_UNIT_ID_KEY||(this._insertSelections=[],this._refSelectionsService.clear(),e&&this._editorService.isSheetEditor(e)&&this._updateEditorModel(`\r
34
- `,[]),this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue($.REF_SELECTIONS_ENABLED,!1),this._contextService.setContextValue(F.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._quitSelectingMode(),this._resetTemp(),this._hideFunctionPanel())}_initSelectionsEndListener(){const e=new c.DisposableCollection;this.disposeWithMe(q.merge(this._refSelectionsService.selectionSet$,this._refSelectionsService.selectionMoveEnd$).subscribe(t=>{var s;if(e.dispose(),!t||t.length===0)return;const n=((s=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:s.getUnitId())||"";if(P.isRangeSelector(n)||P.isEmbeddingFormulaEditor(n))return;this._allSelectionRenderServices.map(i=>i.getSelectionControls()).flat().forEach(i=>{i.disableHelperSelection(),e.add(q.merge(i.selectionMoving$,i.selectionScaling$).subscribe(a=>{var d;const l=((d=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:d.getUnitId())||"";if(P.isRangeSelector(l)||P.isEmbeddingFormulaEditor(l)){e.dispose(),this._formulaPromptService.disableLockedSelectionChange();return}this._onSelectionControlChange(a,i)})),e.add(q.merge(i.selectionMoveEnd$,i.selectionScaled$).subscribe(()=>{this._formulaPromptService.disableLockedSelectionChange()}))})}))}_updateSelecting(e,t=!1){if(e.length!==0&&!(this._editorService.selectionChangingState()&&!this._formulaPromptService.isLockedSelectionInsert())&&(this._insertControlSelections(e),t)){const n=e[e.length-1];this._insertControlSelectionReplace(n)}}_enableRefSelectionsRenderService(){const e=this._selectionsChangeDisposables=new c.DisposableCollection;this._allSelectionRenderServices.forEach(t=>{e.add(t.enableSelectionChanging()),e.add(t.selectionMoving$.subscribe(n=>{this._updateSelecting(n.map(o=>$.convertSelectionDataToRange(o)))})),e.add(t.selectionMoveStart$.subscribe(n=>{const o=this._checkClearingLastSelection(t);this._currentlyWorkingRefRenderer=t,this._updateSelecting(n.map(s=>$.convertSelectionDataToRange(s)),o)}))})}_checkClearingLastSelection(e){return this._currentlyWorkingRefRenderer&&this._currentlyWorkingRefRenderer!==e?(this._currentlyWorkingRefRenderer.clearLastSelection(),!1):!0}_disposeSelectionsChangeListeners(){var e;(e=this._selectionsChangeDisposables)==null||e.dispose(),this._selectionsChangeDisposables=null}_insertControlSelections(e){const t=e[e.length-1];if(this._resetSequenceNodes(e.length),(e.length===this._previousRangesCount||this._previousRangesCount===0)&&this._previousSequenceNodes!=null)this._insertControlSelectionReplace(t);else{let n=this._formulaPromptService.getSequenceNodes();const o=this._getCurrentChar();n.length===0&&this._currentInsertRefStringIndex>0&&(this._currentInsertRefStringIndex=-1),this._previousInsertRefStringIndex=this._currentInsertRefStringIndex,!I.matchRefDrawToken(o)&&this._focusIsOnlyRange(e.length)&&(this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex,I.matchToken.COMMA),n=this._formulaPromptService.getSequenceNodes(),this._previousInsertRefStringIndex+=1),this._previousSequenceNodes=c.Tools.deepClone(n),this._formulaPromptService.setSequenceNodes(n);const s=this._generateRefString(t);this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,s),this._selectionRenderService.setSkipLastEnabled(!1)}this._arrowMoveActionState=2,this._previousRangesCount=e.length}_initAcceptFormula(){this.disposeWithMe(this._formulaPromptService.acceptFormulaName$.subscribe(e=>{const t=this._docSelectionManagerService.getActiveTextRange();if(t==null){this._hideFunctionPanel();return}const{startOffset:n}=t,o=this._formulaPromptService.getSequenceNodes(),s=this._formulaPromptService.getCurrentSequenceNodeIndex(n-2),i=o[s];if(i==null||typeof i=="string"){this._hideFunctionPanel();return}const a=e.length-i.token.length,l={...i};l.token=e,l.endIndex+=a,o[s]=l;const d=this._descriptionService.hasDefinedNameDescription(e),f=this._descriptionService.isFormulaDefinedName(e),h=e.length+1,u=!d||f;u&&o.splice(s+1,0,I.matchToken.OPEN_BRACKET);for(let p=s+2,C=o.length;p<C;p++){const g=o[p];if(typeof g=="string")continue;const E={...g};E.startIndex+=h,E.endIndex+=h,o[p]=E}let S=l.endIndex+1;u&&(S+=1),this._syncToEditor(o,S,void 0,!0,!1)}))}_changeFunctionPanelState(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null){this._hideFunctionPanel();return}const{startOffset:t}=e,n=this._formulaPromptService.getCurrentSequenceNode(t-2);if(n==null){this._hideFunctionPanel();return}if(typeof n!="string"&&n.nodeType===I.sequenceNodeType.FUNCTION&&!this._descriptionService.hasDefinedNameDescription(n.token.trim())){const l=n.token.toUpperCase();if(this._inputPanelState===1){const d=this._descriptionService.getSearchListByNameFirstLetter(l);if(this._hideFunctionPanel(),d==null||d.length===0)return;this._commandService.executeCommand(Be.id,{visible:!0,searchText:l,searchList:d})}else this._changeHelpFunctionPanelState(l,-1);return}const o=this._getCurrentBodyDataStreamAndOffset(),s=this._lexerTreeBuilder.getFunctionAndParameter((o==null?void 0:o.dataStream)||"",t-1+((o==null?void 0:o.offset)||0));if(!s){this._hideFunctionPanel();return}const{functionName:i,paramIndex:a}=s;this._changeHelpFunctionPanelState(i.toUpperCase(),a)}_changeHelpFunctionPanelState(e,t){const n=this._descriptionService.getFunctionInfo(e);this._hideFunctionPanel(),n!=null&&this._commandService.executeCommand(He.id,{visible:!0,paramIndex:t,functionInfo:n})}_hideFunctionPanel(){this._commandService.executeCommand(Be.id,{visible:!1,searchText:""}),this._commandService.executeCommand(He.id,{visible:!1,paramIndex:-1})}_checkShouldEnterSelectingMode(e=!1){if(e){this._enterSelectingMode();return}const t=this._getCurrentChar(),n=this._getCurrentDataStream();(n==null?void 0:n.substring(0,1))==="="&&t&&I.matchRefDrawToken(t)?this._enterSelectingMode():this._quitSelectingMode()}_getCurrentChar(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=this._getCurrentBodyDataStreamAndOffset();return n==null||t==null?void 0:n.dataStream[t-1+n.offset]}_getCurrentDataStream(){const e=this._getCurrentBodyDataStreamAndOffset();return e==null?void 0:e.dataStream}_enterSelectingMode(){this._isSelectingMode||(this._editorBridgeService.enableForceKeepVisible(),this._contextMenuService.disable(),this._formulaPromptService.enableLockedSelectionInsert(),this._selectionRenderService.setRemainLastEnabled(!0),this._enableRefSelectionsRenderService(),this._currentlyWorkingRefRenderer=null,this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._isSelectingMode=!0)}_quitSelectingMode(){this._isSelectingMode&&(this._editorBridgeService.disableForceKeepVisible(),this._contextMenuService.enable(),this._formulaPromptService.disableLockedSelectionInsert(),this._currentInsertRefStringIndex=-1,this._disposeSelectionsChangeListeners(),this._arrowMoveActionState===2&&(this._arrowMoveActionState=4),this._isSelectingMode=!1)}_getCurrentBodyDataStreamAndOffset(){var s,i;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!(e!=null&&e.getBody()))return;const t=e.getUnitId(),n=this._editorService.getEditor(t),o=(i=(s=e.getBody())==null?void 0:s.dataStream)!=null?i:"";return!n||!n.onlyInputRange()?{dataStream:o,offset:0}:{dataStream:I.compareToken.EQUALS+o,offset:1}}_getFormulaAndCellEditorBody(e){return e.map(t=>{const n=this._univerInstanceService.getUniverDocInstance(t);return n==null?void 0:n.getBody()})}_editorModelUnitIds(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();return this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t)?[t]:bs}_contextSwitch(){const e=this._getCurrentBodyDataStreamAndOffset();if(e&&c.isFormulaString(e.dataStream)){this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!0),this._contextService.setContextValue($.REF_SELECTIONS_ENABLED,!0),this._contextService.setContextValue(F.UNI_DISABLE_CHANGING_FOCUS_KEY,!0);const t=this._lexerTreeBuilder.sequenceNodesBuilder(e.dataStream)||[];this._formulaPromptService.setSequenceNodes(t);const n=this._docSelectionManagerService.getActiveTextRange();if(n==null)return;const{startOffset:o}=n;this._currentInsertRefStringIndex=o-1+e.offset;return}this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue($.REF_SELECTIONS_ENABLED,!1),this._contextService.setContextValue(F.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._formulaPromptService.disableLockedSelectionChange(),this._formulaPromptService.disableLockedSelectionInsert(),this._formulaPromptService.clearSequenceNodes(),this._hideFunctionPanel()}_getContextState(){return this._contextService.getContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA)}_highlightFormula(){if(this._getContextState()===!1)return;const e=this._formulaPromptService.getSequenceNodes(),t=this._editorModelUnitIds(),n=this._getFormulaAndCellEditorBody(t).filter(o=>!!o);if(e==null||e.length===0)this._existsSequenceNode=!1,n.forEach(o=>o.textRuns=[]);else{this._existsSequenceNode=!0;const{textRuns:o,refSelections:s}=this._buildTextRuns(e);n.forEach(i=>i.textRuns=o),this._allSelectionRenderServices.forEach(i=>this._refreshSelectionForReference(i,s))}this._refreshFormulaAndCellEditor(t)}_buildTextRuns(e){var a;const t=[],n=[],o=new Map;let s=0;const i=((a=this._getCurrentBodyDataStreamAndOffset())==null?void 0:a.offset)||0;for(let l=0,d=e.length;l<d;l++){const f=e[l];if(typeof f=="string"||this._descriptionService.hasDefinedNameDescription(f.token.trim()))continue;const{startIndex:h,endIndex:u,nodeType:S,token:p}=f;let C="";if(S===I.sequenceNodeType.REFERENCE){if(o.has(p))C=o.get(p);else{const g=s%this._formulaRefColors.length;C=this._formulaRefColors[g],o.set(p,C),s++}n.push({refIndex:l,themeColor:C,token:p})}else S===I.sequenceNodeType.NUMBER?C=this._numberColor:S===I.sequenceNodeType.STRING?C=this._stringColor:S===I.sequenceNodeType.ARRAY&&(C=this._stringColor);C&&C.length>0&&t.push({st:h+1-i,ed:u+2-i,ts:{cl:{rgb:C}}})}return{textRuns:t,refSelections:n}}_exceedCurrentRange(e,t,n){const{startRow:o,startColumn:s}=e;return o>t-1||s>n-1}_refreshSelectionForReference(e,t){const{unitId:n,sheetId:o}=this._editorBridgeService.getEditCellState(),{unitId:s,sheetId:i}=this._getCurrentUnitIdAndSheetId(),a=o===i,d=this._univerInstanceService.getUniverSheetInstance(n).getSheetBySheetId(o);let f=null;const h=[];for(let u=0,S=t.length;u<S;u++){const p=t[u],{themeColor:C,token:g,refIndex:E}=p,_=I.deserializeRangeWithSheet(g),{unitId:v,sheetName:y,range:b}=_,N=$.setEndForRange(b,d.getRowCount(),d.getColumnCount());if(v!=null&&v.length>0&&n!==v)continue;const T=this._getSheetIdByName(n,y.trim());if(!a&&T!==i||a&&y.length!==0&&T!==o||this._exceedCurrentRange(N,d.getRowCount(),d.getColumnCount()))continue;const M=this._getPrimary(N,C,E);if(M){f=M,h.push(f);continue}const x=$.getPrimaryForRange(N,d);!c.Rectangle.equals(x,N)&&N.startRow===N.endRow&&N.startColumn===N.endColumn&&(N.startRow=x.startRow,N.endRow=x.endRow,N.startColumn=x.startColumn,N.endColumn=x.endColumn),h.push({range:N,primary:x,style:$e(this._themeService,C,E.toString())})}h.length&&this._refSelectionsService.setSelections(n,o,h,$.SelectionMoveType.ONLY_SET)}_getPrimary(e,t,n){const o=this._insertSelections.find(h=>{const{startRow:u,startColumn:S,endRow:p,endColumn:C}=h.range;return u===e.startRow&&S===e.startColumn&&p===e.endRow&&C===e.endColumn||u===e.startRow&&S===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn});if((o==null?void 0:o.primary)==null)return;const{isMerged:s,isMergedMainCell:i,startRow:a,endRow:l,startColumn:d,endColumn:f}=o.primary;return(s||i)&&a===e.startRow&&d===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn&&(e.endRow=l,e.endColumn=f),{range:e,primary:o.primary,style:$e(this._themeService,t,n.toString())}}_getSheetIdByName(e,t){var o;const n=this._univerInstanceService.getUniverSheetInstance(e);return(o=n==null?void 0:n.getSheetBySheetName(I.normalizeSheetName(t)))==null?void 0:o.getSheetId()}_getSheetNameById(e,t){var s;const n=this._univerInstanceService.getUniverSheetInstance(e);return((s=n==null?void 0:n.getSheetBySheetId(t))==null?void 0:s.getName())||""}_getCurrentUnitIdAndSheetId(){var o,s;const e=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),t=e.getActiveSheet(),n=(s=(o=this._renderManagerService.getRenderById(e.getUnitId()))==null?void 0:o.with(P.SheetSkeletonManagerService))==null?void 0:s.getCurrentSkeleton();return{unitId:e.getUnitId(),sheetId:(t==null?void 0:t.getSheetId())||"",skeleton:n}}_getEditorOpenedForSheet(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),n=this._editorService.getEditor(t);return n?{openUnitId:n.getOpenForSheetUnitId(),openSheetId:n.getOpenForSheetSubUnitId()}:{openUnitId:null,openSheetId:null}}_generateRefString(e){let t="",n="";const{unitId:o,sheetId:s}=e.range,{openUnitId:i,openSheetId:a}=this._getEditorOpenedForSheet();o!==i&&o&&(t=o),s!==a&&o&&s&&(n=this._getSheetNameById(o,s));const{range:l,primary:d}=e;let{startRow:f,endRow:h,startColumn:u,endColumn:S}=l;const{startAbsoluteRefType:p,endAbsoluteRefType:C,rangeType:g}=l;if(d){const{isMerged:E,isMergedMainCell:_,startRow:v,endRow:y,startColumn:b,endColumn:N}=d;(E||_)&&v===f&&b===u&&y===h&&N===S&&(f=v,u=b,h=v,S=b)}return I.serializeRangeToRefString({sheetName:n,unitId:t,range:{startRow:f,endRow:h,startColumn:u,endColumn:S,rangeType:g,startAbsoluteRefType:p,endAbsoluteRefType:C}})}_syncToEditor(e,t,n,o=!0,s=!0){let i=I.generateStringWithSequence(e);const{textRuns:a,refSelections:l}=this._buildTextRuns(e);this._isSelectionMovingRefSelections=l,this._allSelectionRenderServices.forEach(C=>this._updateRefSelectionStyle(C,this._isSelectionMovingRefSelections));const d=this._docSelectionManagerService.getActiveTextRange();if(d==null)return;this._currentInsertRefStringIndex=t,n==null&&(n=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId()),this._fitEditorSize();const f=this._editorService.getEditor(n);f!=null&&f.isSingleChoice()?(i=i.split(",")[0],this._selectionRenderService.setSingleSelectionEnabled(!0)):this._selectionRenderService.setSingleSelectionEnabled(!1);let h=i,u=1;(!f||!f.onlyInputRange())&&(h=`${I.compareToken.EQUALS}${i}`,u=0);const{collapsed:S,style:p}=d;o?(this._commandService.executeCommand(ee.ReplaceContentCommand.id,{unitId:n,body:{dataStream:h,textRuns:a},textRanges:[{startOffset:t+1-u,endOffset:t+1-u,collapsed:S,style:p}],segmentId:null,options:{fromSelection:s}}),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:p}],!0,{fromSelection:s})):(this._updateEditorModel(`${h}\r
35
- `,a),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:p}],!0,{fromSelection:s})),this._layoutService.focus()}_fitEditorSize(){var n;const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();if(!(this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t))&&(this._editorBridgeService.changeEditorDirty(!0),!!this._editorBridgeService.isVisible().visible&&t===c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY)){const o=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),s=(n=o==null?void 0:o.getUnitId())!=null?n:"",i=this._renderManagerService.getRenderById(s);if(!i)return;i.with(P.SheetCellEditorResizeService).fitTextSize()}}_updateEditorModel(e,t){var l;const n=this._univerInstanceService.getCurrentUniverDocInstance(),o=n.getUnitId();if(!this._editorService.isEditor(o))return;const s=(l=this._renderManagerService.getRenderById(o))==null?void 0:l.with(je.DocSkeletonManagerService).getViewModel();if(s==null||n==null)return;const i=n==null?void 0:n.getSnapshot();if(i==null)return;const a={dataStream:e,textRuns:t};i.body=a,s.reset(n)}_insertControlSelectionReplace(e){this._previousSequenceNodes==null&&(this._previousSequenceNodes=this._formulaPromptService.getSequenceNodes()),this._previousInsertRefStringIndex==null&&(this._previousInsertRefStringIndex=this._currentInsertRefStringIndex);const t=c.Tools.deepClone(this._previousSequenceNodes);if(t==null)return;const{skeleton:n}=this._getCurrentUnitIdAndSheetId(),o=n==null?void 0:n.worksheet.getUnitId(),s=n==null?void 0:n.worksheet.getSheetId();e.range.sheetId=s,e.range.unitId=o;const i=this._generateRefString(e);this._formulaPromptService.setSequenceNodes(t),this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,i),this._syncToEditor(t,this._previousInsertRefStringIndex+i.length);const a=this._selectionRenderService.getSelectionDataWithStyle()||[];this._insertSelections=[];const l=a[a.length-1];if(l){const d=$.convertSelectionDataToRange(l);this._insertSelections.push(d)}}_focusIsOnlyRange(e){const t=this._editorService.getFocusEditor();return!t||!t.onlyInputRange()||this._existsSequenceNode||e>1||this._previousSequenceNodes!=null&&this._previousSequenceNodes.length>0?!0:(this._previousInsertRefStringIndex!=null&&(this._previousInsertRefStringIndex+=1),!1)}_resetSequenceNodes(e){const t=this._editorService.getFocusEditor();t&&t.onlyInputRange()&&(e>1||this._existsSequenceNode&&(this._formulaPromptService.clearSequenceNodes(),this._previousRangesCount=0,this._existsSequenceNode=!1))}_updateRefSelectionStyle(e,t){const n=e.getSelectionControls(),[o,s]=e.getLocation(),i=new Set;for(let a=0,l=t.length;a<l;a++){const d=t[a],{refIndex:f,themeColor:h,token:u}=d,S=I.deserializeRangeWithSheet(u),{unitId:p,sheetName:C,range:g}=S;if(!p&&p.length>0&&o!==p)continue;const E=this._getSheetIdByName(o,C.trim());if(E&&E!==s)continue;const _=n.find(v=>{const{startRow:y,startColumn:b,endRow:N,endColumn:T,rangeType:M}=v.getRange();return M===c.RANGE_TYPE.COLUMN&&b===g.startColumn&&T===g.endColumn||M===c.RANGE_TYPE.ROW&&y===g.startRow&&N===g.endRow||y===g.startRow&&b===g.startColumn&&N===g.endRow&&T===g.endColumn||y===g.startRow&&b===g.startColumn&&g.startRow===g.endRow&&g.startColumn===g.endColumn});if(_){const v=$e(this._themeService,h,f.toString());_.updateStyle(v),i.add(_)}}}_onSelectionControlChange(e,t){var _;const{skeleton:n}=this._getCurrentUnitIdAndSheetId();if(!n)return;this._formulaPromptService.enableLockedSelectionChange();const o=(_=t.currentStyle)==null?void 0:_.id;if(!o||!c.Tools.isStringNumber(o))return;let{startRow:s,endRow:i,startColumn:a,endColumn:l}=e;const d=n?n.worksheet.getCellInfoInMergeData(s,a):{actualRow:s,actualColumn:a,isMergedMainCell:!1,isMerged:!1,endRow:s,endColumn:a,startRow:s,startColumn:a};if(d){const{isMerged:v,isMergedMainCell:y,startRow:b,endRow:N,startColumn:T,endColumn:M}=d;(v||y)&&b===s&&T===a&&N===i&&M===l&&(s=b,a=T,i=b,l=T)}const f=Number(o),h=this._formulaPromptService.getCurrentSequenceNodeByIndex(f);if(!h)return;let u={startAbsoluteRefType:c.AbsoluteRefType.NONE};if(typeof h!="string"){const v=h.token;u=I.getAbsoluteRefTypeWitString(v),u.endAbsoluteRefType==null&&(u.endAbsoluteRefType=u.startAbsoluteRefType)}const S=n==null?void 0:n.worksheet.getUnitId(),p=n==null?void 0:n.worksheet.getSheetId(),C=this._generateRefString({range:{startRow:Math.min(s,i),endRow:Math.max(s,i),startColumn:Math.min(a,l),endColumn:Math.max(a,l),...u,sheetId:p,unitId:S},primary:d,style:null});this._formulaPromptService.updateSequenceRef(f,C);const g=this._formulaPromptService.getSequenceNodes(),E=g[f];typeof E!="string"&&(this._syncToEditor(g,E.endIndex+1),t.updateRange(e,this._selectionRenderService.attachPrimaryWithCoord(d)))}_refreshFormulaAndCellEditor(e){var t;for(const n of e){const o=P.getEditorObject(n,this._renderManagerService),s=o==null?void 0:o.document;s!=null&&((t=s.getSkeleton())==null||t.calculate(),s.makeDirty())}}_cursorStateListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t.onPointerDown$.subscribeEvent(()=>{this._arrowMoveActionState=1,this._inputPanelState=3}))}_pressEnter(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressTab(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressEsc(e){const{keycode:t}=e,n=this._editorService.getFocusEditor();(!n||(n==null?void 0:n.isSheetEditor())===!0)&&this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressArrowKey(e){const{keycode:t,metaKey:n}=e;let o=c.Direction.DOWN;t===F.KeyCode.ARROW_DOWN?o=c.Direction.DOWN:t===F.KeyCode.ARROW_UP?o=c.Direction.UP:t===F.KeyCode.ARROW_LEFT?o=c.Direction.LEFT:t===F.KeyCode.ARROW_RIGHT&&(o=c.Direction.RIGHT),n===F.MetaKeys.CTRL_COMMAND?this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:o,jumpOver:P.JumpOver.moveGap}):n===F.MetaKeys.SHIFT?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:o}):n===un?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:o,jumpOver:P.JumpOver.moveGap}):this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:o})}_commandExecutedListener(){const e=[Ie.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC),o=(n==null?void 0:n.getUnitId())||"";if(!(P.isRangeSelector(o)||P.isEmbeddingFormulaEditor(o))){if(t.id===et.id)this._changeRefString();else if(e.includes(t.id)){const s=t.params,{keycode:i,isSingleEditor:a=!1}=s;if(i===F.KeyCode.ENTER){this._pressEnter(s);return}if(i===F.KeyCode.TAB){this._pressTab(s);return}if(i===F.KeyCode.ESC){this._pressEsc(s);return}if(this._formulaPromptService.isSearching()){if(i===F.KeyCode.ARROW_DOWN){this._formulaPromptService.navigate({direction:c.Direction.DOWN});return}if(i===F.KeyCode.ARROW_UP){this._formulaPromptService.navigate({direction:c.Direction.UP});return}}if(a===!0)return;if(this._arrowMoveActionState===1){this._moveInEditor(i);return}if(this._arrowMoveActionState===4){this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:i,unitId:""});return}if(this._arrowMoveActionState===2&&(this._arrowMoveActionState=3),this._refSelectionsService.getCurrentSelections().length===0){const h=this._sheetsSelectionsService.getCurrentLastSelection();if(h!=null){const u=c.Tools.deepClone(h);this._refSelectionsService.setSelections([u])}}this._pressArrowKey(s);const d=this._refSelectionsService.getCurrentSelections(),f=d[d.length-1];this._insertControlSelectionReplace(f),this._highlightFormula()}}}))}_moveInEditor(e){if(e==null)return;let t=c.Direction.LEFT;e===F.KeyCode.ARROW_DOWN?t=c.Direction.DOWN:e===F.KeyCode.ARROW_UP?t=c.Direction.UP:e===F.KeyCode.ARROW_RIGHT&&(t=c.Direction.RIGHT),this._commandService.executeCommand(ee.MoveCursorOperation.id,{direction:t})}_userMouseListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t==null?void 0:t.onPointerDown$.subscribeEvent(()=>{this._userCursorMove=!0}))}_inputFormulaListener(){this.disposeWithMe(this._editorService.inputFormula$.subscribe(e=>{const{formulaString:t,editorUnitId:n}=e;if(t.substring(0,1)!==I.compareToken.EQUALS)return;const{unitId:o}=this._getCurrentUnitIdAndSheetId();this._editorBridgeService.isVisible().visible===!1&&this._editorBridgeService.changeVisible({visible:!0,eventType:z.DeviceInputEventType.Dblclick,unitId:o});const i=this._lexerTreeBuilder.sequenceNodesBuilder(t)||[];this._formulaPromptService.setSequenceNodes(i),this._syncToEditor(i,t.length-1,n,!0,!1)}))}_changeRefString(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=t-2,o=this._formulaPromptService.getCurrentSequenceNodeIndex(n),s=this._formulaPromptService.getCurrentSequenceNodeByIndex(o);if(s==null||typeof s=="string"||s.nodeType!==I.sequenceNodeType.REFERENCE)return;const i=s.token.split("!");let a=s.token;i.length>1&&(a=i[i.length-1]);let l="";for(let h=0,u=i.length;h<u-1;h++)l+=i[h];let d=a;if(a.indexOf(I.matchToken.COLON)>-1)if(!this._userCursorMove)d=this._changeRangeRef(a);else{const h=a.split(I.matchToken.COLON),u=h[0],S=h[1];n-s.startIndex<=u.length?d=this._changeSingleRef(u)+I.matchToken.COLON+S:d=u+I.matchToken.COLON+this._changeSingleRef(S)}else d=this._changeSingleRef(a);d=l+d;const f=d.length-s.token.length;this._formulaPromptService.updateSequenceRef(o,d),this._syncToEditor(this._formulaPromptService.getSequenceNodes(),n+f+1)}_changeRangeRef(e){const t=I.deserializeRangeWithSheet(e).range;let n="";return t.startAbsoluteRefType===c.AbsoluteRefType.NONE||t.startAbsoluteRefType==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),n=I.serializeRange(t),n}_changeSingleRef(e){const t=I.deserializeRangeWithSheet(e).range,n=t.startAbsoluteRefType;let o="";return n===c.AbsoluteRefType.NONE||n==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):n===c.AbsoluteRefType.ALL?(t.startAbsoluteRefType=c.AbsoluteRefType.ROW,t.endAbsoluteRefType=c.AbsoluteRefType.ROW):n===c.AbsoluteRefType.ROW?(t.startAbsoluteRefType=c.AbsoluteRefType.COLUMN,t.endAbsoluteRefType=c.AbsoluteRefType.COLUMN):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),o=I.serializeRange(t),o}_getEditorObject(){const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const t=e.getUnitId(),n=this._editorService.getEditor(t);return n==null?void 0:n.render}_isFormulaEditorActivated(){return this._editorBridgeService.isVisible().visible===!0||this._contextService.getContextValue(c.FORMULA_EDITOR_ACTIVATED)}_isSheetOrFormulaEditor(e){return e.isSheetEditor()||e.isFormulaEditor()}};Ze=Ts([se(0,c.ICommandService),se(1,c.IContextService),se(2,c.Inject(P.IEditorBridgeService)),se(3,c.Inject(Fe)),se(4,c.Inject(I.LexerTreeBuilder)),se(5,z.IRenderManagerService),se(6,c.Inject(c.ThemeService)),se(7,c.Inject($.SheetsSelectionsService)),se(8,$.IRefSelectionsService),se(9,c.IUniverInstanceService),se(10,c.Inject(ge.IDescriptionService)),se(11,c.Inject(je.DocSelectionManagerService)),se(12,F.IContextMenuService),se(13,ee.IEditorService),se(14,F.ILayoutService)],Ze);var dn=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,xs=(r,e,t)=>e in r?dn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ms=(r,e,t,n)=>{for(var o=n>1?void 0:n?Ns(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&dn(e,t,o),o},ht=(r,e)=>(t,n)=>e(t,n,r),hn=(r,e,t)=>xs(r,typeof e!="symbol"?e+"":e,t);exports.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(e=Ft,t,n,o){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=o;const{menu:s,...i}=c.merge(Ft,this._config);s&&this._configService.setConfig("menu",s,{merge:!0}),this._configService.setConfig(Wr,i)}onStarting(){const e=this._injector;[[Fe,{useClass:ft}],[Ge],[qe],[Ke],[ze],[Ye],[Ze]].forEach(n=>e.add(n))}onRendered(){[[exports.RefSelectionsRenderService],[St]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[Ge],[Ke],[Ye]]);const e=this._injector.get(F.ComponentManager);e.register(P.RANGE_SELECTOR_COMPONENT_KEY,on),e.register(P.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,sn)}onSteady(){this._injector.get(qe),this._injector.get(Ze)}};hn(exports.UniverSheetsFormulaUIPlugin,"pluginName",Lt);hn(exports.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=Ms([c.DependentOn(I.UniverFormulaEnginePlugin,ge.UniverSheetsFormulaPlugin),ht(1,c.Inject(c.Injector)),ht(2,z.IRenderManagerService),ht(3,c.IConfigService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=Pt;exports.FormulaEditor=sn;exports.HelpFunctionOperation=He;exports.InsertFunctionOperation=Qe;exports.MoreFunctionsOperation=Je;exports.RangeSelector=on;exports.ReferenceAbsoluteOperation=et;exports.SearchFunctionOperation=Be;exports.SelectEditorFormulaOperation=Ie;exports.SheetOnlyPasteFormulaCommand=Xe;
33
+ `:Se.formulaSelectFunctionResultItem,onMouseEnter:()=>D(O),onMouseLeave:k,onClick:()=>T(O),children:[f===O&&R.jsx(Ut,{className:Se.formulaSelectFunctionResultItemSelected}),R.jsx("span",{className:Se.formulaSelectFunctionResultItemName,children:N(A)})]},O))}),m&&R.jsxs("div",{className:Se.formulaSelectFunctionContent,children:[R.jsx(ke,{title:m.functionName,value:m.description}),R.jsx(ke,{title:g.t("formula.moreFunctions.syntax"),value:R.jsx(ln,{prefix:m.functionName,value:m.functionParameter})}),R.jsx(ke,{title:g.t("formula.prompt.helpExample"),value:`${m.functionName}(${m.functionParameter.map(A=>A.example).join(",")})`}),m.functionParameter&&m.functionParameter.map((A,O)=>R.jsx(ke,{title:A.name,value:`${A.require?y:b} ${A.detail}`},O))]})]})}function cs(){const r=P.useActiveWorkbook(),[e,t]=S.useState(!0),[n,o]=S.useState(!1),[s,i]=S.useState(null),a=c.useDependency(c.LocaleService),l=c.useDependency(ee.IEditorService);function d(){t(!e),o(!n)}function h(){l.setFormula(`=${s==null?void 0:s.functionName}(`)}return R.jsxs("div",{className:Dt.formulaMoreFunctions,children:[e&&R.jsx(is,{onChange:i}),n&&R.jsx(Qo,{functionInfo:s,onChange:()=>{}}),R.jsxs("div",{className:Dt.formulaMoreFunctionsOperation,children:[n&&R.jsx(ie.Button,{type:"primary",size:"small",onClick:d,children:a.t("formula.moreFunctions.next")}),n&&R.jsx(ie.Button,{size:"small",onClick:d,children:a.t("formula.moreFunctions.prev")}),e&&!!r&&R.jsx(ie.Button,{type:"primary",size:"small",onClick:h,children:a.t("formula.moreFunctions.confirm")})]})]})}function as(r){return{id:Qe.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:F.MenuItemType.SELECTOR,selections:[{label:"SUM",value:"SUM",icon:"SumSingle"},{label:"AVERAGE",value:"AVERAGE",icon:"AvgSingle"},{label:"COUNT",value:"COUNT",icon:"CntSingle"},{label:"MAX",value:"MAX",icon:"MaxSingle"},{label:"MIN",value:"MIN",icon:"MinSingle"}],hidden$:F.getMenuHiddenObservable(r,c.UniverInstanceType.UNIVER_SHEET),disabled$:P.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],worksheetTypes:[$.WorksheetEditPermission,$.WorksheetSetCellValuePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint]})}}function ls(r){return{id:Je.id,title:"formula.insert.more",type:F.MenuItemType.BUTTON}}function us(r){return r.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(q.switchMap(n=>n&&r.get(F.IClipboardInterfaceService)?new q.Observable(s=>s.next(!r.get(F.IClipboardInterfaceService).supportClipboard)):q.of(!0)))}function ds(r){return{id:Xe.id,type:F.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:us(r).pipe(q.combineLatestWith(P.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint],worksheetTypes:[$.WorksheetSetCellValuePermission,$.WorksheetEditPermission]})),q.map(([e,t])=>e||t))}}const fs={[F.RibbonStartGroup.FORMULAS_INSERT]:{[Qe.id]:{order:1,menuItemFactory:as,[Je.id]:{order:1,menuItemFactory:ls}}},[P.PASTE_SPECIAL_MENU_ID]:{[Xe.id]:{order:4,menuItemFactory:ds}}},un="meta_key_ctrl_And_Shift",ot=[F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP,F.KeyCode.ARROW_LEFT,F.KeyCode.ARROW_RIGHT],hs=[...ot,F.KeyCode.ENTER,F.KeyCode.TAB,F.KeyCode.ESC];function ms(){const r=[];for(const e of hs)r.push({id:Ie.id,binding:e,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e}});return r}function Ss(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|F.MetaKeys.SHIFT,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,metaKey:F.MetaKeys.SHIFT}});return r}function gs(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|F.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,metaKey:F.MetaKeys.CTRL_COMMAND}});return r}function ps(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|F.MetaKeys.SHIFT|F.MetaKeys.CTRL_COMMAND,preconditions:t=>P.whenFormulaEditorActivated(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,metaKey:un}});return r}const _s={id:et.id,binding:F.KeyCode.F4,preconditions:r=>P.whenFormulaEditorActivated(r)};function vs(){const r=[];for(const e of[F.KeyCode.ENTER,F.KeyCode.TAB,F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP])r.push({id:Ie.id,binding:e,preconditions:t=>Br(t),staticParameters:{eventType:z.DeviceInputEventType.Keyboard,keycode:e,isSingleEditor:!0}});return r}var Cs=Object.defineProperty,Rs=Object.getOwnPropertyDescriptor,Is=(r,e,t,n)=>{for(var o=n>1?void 0:n?Rs(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Cs(e,t,o),o},Te=(r,e)=>(t,n)=>e(t,n,r);let Ge=class extends c.Disposable{constructor(r,e,t,n,o,s,i){super(),this._injector=r,this._menuManagerService=e,this._commandService=t,this._shortcutService=n,this._uiPartsService=o,this._renderManagerService=s,this._componentManager=i,this._initialize()}_initialize(){this._registerCommands(),this._registerMenus(),this._registerShortcuts(),this._registerComponents(),this._registerRenderModules()}_registerMenus(){this._menuManagerService.mergeMenu(fs)}_registerCommands(){[Xe,Qe,Je,Be,He,Ie,et].forEach(r=>this.disposeWithMe(this._commandService.registerCommand(r)))}_registerShortcuts(){[...ms(),...Ss(),...gs(),...ps(),...vs(),_s].forEach(r=>{this.disposeWithMe(this._shortcutService.registerShortcut(r))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(F.BuiltInUIPart.CONTENT,()=>c.connectInjector(Bo,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent(P.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(po,this._injector))),this._componentManager.register(wt,cs)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[ze]))}};Ge=Is([Te(0,c.Inject(c.Injector)),Te(1,F.IMenuManagerService),Te(2,c.ICommandService),Te(3,F.IShortcutService),Te(4,F.IUIPartsService),Te(5,z.IRenderManagerService),Te(6,c.Inject(F.ComponentManager))],Ge);var Es=Object.defineProperty,ys=Object.getOwnPropertyDescriptor,Ts=(r,e,t,n)=>{for(var o=n>1?void 0:n?ys(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&Es(e,t,o),o},se=(r,e)=>(t,n)=>e(t,n,r);const bs=[c.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let Ze=class extends c.Disposable{constructor(e,t,n,o,s,i,a,l,d,h,f,u,m,p,C){super();V(this,"_listenInputCache",new Set);V(this,"_formulaRefColors",[]);V(this,"_previousSequenceNodes");V(this,"_previousRangesCount",0);V(this,"_previousInsertRefStringIndex");V(this,"_currentInsertRefStringIndex",-1);V(this,"_arrowMoveActionState",0);V(this,"_isSelectionMovingRefSelections",[]);V(this,"_stringColor","");V(this,"_numberColor","");V(this,"_insertSelections",[]);V(this,"_inputPanelState",0);V(this,"_userCursorMove",!1);V(this,"_previousEditorUnitId");V(this,"_existsSequenceNode",!1);V(this,"_currentlyWorkingRefRenderer",null);V(this,"_selectionsChangeDisposables");V(this,"_isSelectingMode",!1);this._commandService=e,this._contextService=t,this._editorBridgeService=n,this._formulaPromptService=o,this._lexerTreeBuilder=s,this._renderManagerService=i,this._themeService=a,this._sheetsSelectionsService=l,this._refSelectionsService=d,this._univerInstanceService=h,this._descriptionService=f,this._docSelectionManagerService=u,this._contextMenuService=m,this._editorService=p,this._layoutService=C,this._initialize()}get _selectionRenderService(){return this._renderManagerService.getRenderById(this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(exports.RefSelectionsRenderService)}get _allSelectionRenderServices(){return this._renderManagerService.getAllRenderersOfType(c.UniverInstanceType.UNIVER_SHEET).map(e=>e.with(exports.RefSelectionsRenderService))}dispose(){this._formulaRefColors=[],this._resetTemp()}_resetTemp(){this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._isSelectionMovingRefSelections=[],this._previousRangesCount=0,this._currentInsertRefStringIndex=-1}_initialize(){this._initialCursorSync(),this._initAcceptFormula(),this._initialFormulaTheme(),this._initSelectionsEndListener(),this._closeRangePromptWhenEditorInvisible(),this._initialEditorInputChange(),this._commandExecutedListener(),this._cursorStateListener(),this._inputFormulaListener(),this._userMouseListener(),this._initialChangeEditor()}_initialFormulaTheme(){const e=this._themeService.getCurrentTheme();this._formulaRefColors=[e.loopColor1,e.loopColor2,e.loopColor3,e.loopColor4,e.loopColor5,e.loopColor6,e.loopColor7,e.loopColor8,e.loopColor9,e.loopColor10,e.loopColor11,e.loopColor12],this._numberColor=e.hyacinth700,this._stringColor=e.verdancy800}_initialCursorSync(){this.disposeWithMe(this._docSelectionManagerService.textSelection$.pipe(q.filter(e=>!P.isRangeSelector(e.unitId)&&!P.isEmbeddingFormulaEditor(e.unitId))).subscribe(e=>{var o;if((e==null?void 0:e.unitId)==null)return;const t=this._editorService.getEditor(e.unitId);if(!t||t.onlyInputContent()||t.isSheetEditor()&&!this._isFormulaEditorActivated()||t.params.scrollBar)return;const n=t.onlyInputRange();(o=e==null?void 0:e.options)!=null&&o.fromSelection||(this._quitSelectingMode(),this._contextSwitch(),this._checkShouldEnterSelectingMode(n),!this._formulaPromptService.isLockedSelectionChange()&&(this._highlightFormula(),!n&&this._changeFunctionPanelState()))}))}_initialEditorInputChange(){const e=[F.KeyCode.ARROW_DOWN,F.KeyCode.ARROW_UP,F.KeyCode.ARROW_LEFT,F.KeyCode.ARROW_RIGHT,F.KeyCode.CTRL,F.KeyCode.SHIFT];this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(q.filter(t=>{const n=(t==null?void 0:t.getUnitId())||"";return!P.isRangeSelector(n)&&!P.isEmbeddingFormulaEditor(n)})).subscribe(t=>{var i;const n=t==null?void 0:t.getUnitId();if(n==null||this._listenInputCache.has(n)||this._editorService.getEditor(n)==null)return;const s=(i=this._renderManagerService.getRenderById(n))==null?void 0:i.with(ee.DocSelectionRenderService);s&&this.disposeWithMe(s.onInputBefore$.subscribe(a=>{this._previousSequenceNodes=null,this._previousInsertRefStringIndex=null,this._selectionRenderService.setSkipLastEnabled(!0);const l=a==null?void 0:a.event;l&&(e.includes(l.which)?this._inputPanelState=2:(this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._inputPanelState=1),l.which!==F.KeyCode.F4&&(this._userCursorMove=!1))})),this._listenInputCache.add(n)})}_closeRangePromptWhenEditorInvisible(){this.disposeWithMe(this._editorBridgeService.afterVisible$.pipe(q.distinctUntilKeyChanged("visible")).subscribe(e=>{e.visible||this._closeRangePrompt()})),this.disposeWithMe(this._contextService.subscribeContextValue$(c.FORMULA_EDITOR_ACTIVATED).pipe(q.distinctUntilChanged()).subscribe(e=>{e||this._closeRangePrompt()}))}_initialChangeEditor(){this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(q.filter(e=>{const t=(e==null?void 0:e.getUnitId())||"";return!P.isRangeSelector(t)&&!P.isEmbeddingFormulaEditor(t)})).subscribe(e=>{if(e==null)return;const t=e.getUnitId();!this._editorService.isEditor(t)||this._previousEditorUnitId===t||this._editorService.isSheetEditor(t)||(this._closeRangePrompt(t),this._previousEditorUnitId=t)})),this.disposeWithMe(this._editorService.closeRangePrompt$.subscribe(()=>{(!this._editorService.getSpreadsheetFocusState()||!this._formulaPromptService.isLockedSelectionInsert())&&this._closeRangePrompt()}))}_closeRangePrompt(e){var n;const t=e||((n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:n.getUnitId())||"";P.isRangeSelector(t)||P.isEmbeddingFormulaEditor(t)||t===c.DOCS_ZEN_EDITOR_UNIT_ID_KEY||(this._insertSelections=[],this._refSelectionsService.clear(),e&&this._editorService.isSheetEditor(e)&&this._updateEditorModel(`\r
34
+ `,[]),this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue($.REF_SELECTIONS_ENABLED,!1),this._contextService.setContextValue(F.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._quitSelectingMode(),this._resetTemp(),this._hideFunctionPanel())}_initSelectionsEndListener(){const e=new c.DisposableCollection;this.disposeWithMe(q.merge(this._refSelectionsService.selectionSet$,this._refSelectionsService.selectionMoveEnd$).subscribe(t=>{var s;if(e.dispose(),!t||t.length===0)return;const n=((s=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:s.getUnitId())||"";if(P.isRangeSelector(n)||P.isEmbeddingFormulaEditor(n))return;this._allSelectionRenderServices.map(i=>i.getSelectionControls()).flat().forEach(i=>{i.disableHelperSelection(),e.add(q.merge(i.selectionMoving$,i.selectionScaling$).subscribe(a=>{var d;const l=((d=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:d.getUnitId())||"";if(P.isRangeSelector(l)||P.isEmbeddingFormulaEditor(l)){e.dispose(),this._formulaPromptService.disableLockedSelectionChange();return}this._onSelectionControlChange(a,i)})),e.add(q.merge(i.selectionMoveEnd$,i.selectionScaled$).subscribe(()=>{this._formulaPromptService.disableLockedSelectionChange()}))})}))}_updateSelecting(e,t=!1){if(e.length!==0&&!(this._editorService.selectionChangingState()&&!this._formulaPromptService.isLockedSelectionInsert())&&(this._insertControlSelections(e),t)){const n=e[e.length-1];this._insertControlSelectionReplace(n)}}_enableRefSelectionsRenderService(){const e=this._selectionsChangeDisposables=new c.DisposableCollection;this._allSelectionRenderServices.forEach(t=>{e.add(t.enableSelectionChanging()),e.add(t.selectionMoving$.subscribe(n=>{this._updateSelecting(n.map(o=>$.convertSelectionDataToRange(o)))})),e.add(t.selectionMoveStart$.subscribe(n=>{const o=this._checkClearingLastSelection(t);this._currentlyWorkingRefRenderer=t,this._updateSelecting(n.map(s=>$.convertSelectionDataToRange(s)),o)}))})}_checkClearingLastSelection(e){return this._currentlyWorkingRefRenderer&&this._currentlyWorkingRefRenderer!==e?(this._currentlyWorkingRefRenderer.clearLastSelection(),!1):!0}_disposeSelectionsChangeListeners(){var e;(e=this._selectionsChangeDisposables)==null||e.dispose(),this._selectionsChangeDisposables=null}_insertControlSelections(e){const t=e[e.length-1];if(this._resetSequenceNodes(e.length),(e.length===this._previousRangesCount||this._previousRangesCount===0)&&this._previousSequenceNodes!=null)this._insertControlSelectionReplace(t);else{let n=this._formulaPromptService.getSequenceNodes();const o=this._getCurrentChar();n.length===0&&this._currentInsertRefStringIndex>0&&(this._currentInsertRefStringIndex=-1),this._previousInsertRefStringIndex=this._currentInsertRefStringIndex,!I.matchRefDrawToken(o)&&this._focusIsOnlyRange(e.length)&&(this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex,I.matchToken.COMMA),n=this._formulaPromptService.getSequenceNodes(),this._previousInsertRefStringIndex+=1),this._previousSequenceNodes=c.Tools.deepClone(n),this._formulaPromptService.setSequenceNodes(n);const s=this._generateRefString(t);this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,s),this._selectionRenderService.setSkipLastEnabled(!1)}this._arrowMoveActionState=2,this._previousRangesCount=e.length}_initAcceptFormula(){this.disposeWithMe(this._formulaPromptService.acceptFormulaName$.subscribe(e=>{const t=this._docSelectionManagerService.getActiveTextRange();if(t==null){this._hideFunctionPanel();return}const{startOffset:n}=t,o=this._formulaPromptService.getSequenceNodes(),s=this._formulaPromptService.getCurrentSequenceNodeIndex(n-2),i=o[s];if(i==null||typeof i=="string"){this._hideFunctionPanel();return}const a=e.length-i.token.length,l={...i};l.token=e,l.endIndex+=a,o[s]=l;const d=this._descriptionService.hasDefinedNameDescription(e),h=this._descriptionService.isFormulaDefinedName(e),f=e.length+1,u=!d||h;u&&o.splice(s+1,0,I.matchToken.OPEN_BRACKET);for(let p=s+2,C=o.length;p<C;p++){const g=o[p];if(typeof g=="string")continue;const E={...g};E.startIndex+=f,E.endIndex+=f,o[p]=E}let m=l.endIndex+1;u&&(m+=1),this._syncToEditor(o,m,void 0,!0,!1)}))}_changeFunctionPanelState(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null){this._hideFunctionPanel();return}const{startOffset:t}=e,n=this._formulaPromptService.getCurrentSequenceNode(t-2);if(n==null){this._hideFunctionPanel();return}if(typeof n!="string"&&n.nodeType===I.sequenceNodeType.FUNCTION&&!this._descriptionService.hasDefinedNameDescription(n.token.trim())){const l=n.token.toUpperCase();if(this._inputPanelState===1){const d=this._descriptionService.getSearchListByNameFirstLetter(l);if(this._hideFunctionPanel(),d==null||d.length===0)return;this._commandService.executeCommand(Be.id,{visible:!0,searchText:l,searchList:d})}else this._changeHelpFunctionPanelState(l,-1);return}const o=this._getCurrentBodyDataStreamAndOffset(),s=this._lexerTreeBuilder.getFunctionAndParameter((o==null?void 0:o.dataStream)||"",t-1+((o==null?void 0:o.offset)||0));if(!s){this._hideFunctionPanel();return}const{functionName:i,paramIndex:a}=s;this._changeHelpFunctionPanelState(i.toUpperCase(),a)}_changeHelpFunctionPanelState(e,t){const n=this._descriptionService.getFunctionInfo(e);this._hideFunctionPanel(),n!=null&&this._commandService.executeCommand(He.id,{visible:!0,paramIndex:t,functionInfo:n})}_hideFunctionPanel(){this._commandService.executeCommand(Be.id,{visible:!1,searchText:""}),this._commandService.executeCommand(He.id,{visible:!1,paramIndex:-1})}_checkShouldEnterSelectingMode(e=!1){if(e){this._enterSelectingMode();return}const t=this._getCurrentChar(),n=this._getCurrentDataStream();(n==null?void 0:n.substring(0,1))==="="&&t&&I.matchRefDrawToken(t)?this._enterSelectingMode():this._quitSelectingMode()}_getCurrentChar(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=this._getCurrentBodyDataStreamAndOffset();return n==null||t==null?void 0:n.dataStream[t-1+n.offset]}_getCurrentDataStream(){const e=this._getCurrentBodyDataStreamAndOffset();return e==null?void 0:e.dataStream}_enterSelectingMode(){this._isSelectingMode||(this._editorBridgeService.enableForceKeepVisible(),this._contextMenuService.disable(),this._formulaPromptService.enableLockedSelectionInsert(),this._selectionRenderService.setRemainLastEnabled(!0),this._enableRefSelectionsRenderService(),this._currentlyWorkingRefRenderer=null,this._arrowMoveActionState!==1&&(this._arrowMoveActionState=2),this._isSelectingMode=!0)}_quitSelectingMode(){this._isSelectingMode&&(this._editorBridgeService.disableForceKeepVisible(),this._contextMenuService.enable(),this._formulaPromptService.disableLockedSelectionInsert(),this._currentInsertRefStringIndex=-1,this._disposeSelectionsChangeListeners(),this._arrowMoveActionState===2&&(this._arrowMoveActionState=4),this._isSelectingMode=!1)}_getCurrentBodyDataStreamAndOffset(){var s,i;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!(e!=null&&e.getBody()))return;const t=e.getUnitId(),n=this._editorService.getEditor(t),o=(i=(s=e.getBody())==null?void 0:s.dataStream)!=null?i:"";return!n||!n.onlyInputRange()?{dataStream:o,offset:0}:{dataStream:I.compareToken.EQUALS+o,offset:1}}_getFormulaAndCellEditorBody(e){return e.map(t=>{const n=this._univerInstanceService.getUniverDocInstance(t);return n==null?void 0:n.getBody()})}_editorModelUnitIds(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();return this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t)?[t]:bs}_contextSwitch(){const e=this._getCurrentBodyDataStreamAndOffset();if(e&&c.isFormulaString(e.dataStream)){this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!0),this._contextService.setContextValue($.REF_SELECTIONS_ENABLED,!0),this._contextService.setContextValue(F.UNI_DISABLE_CHANGING_FOCUS_KEY,!0);const t=this._lexerTreeBuilder.sequenceNodesBuilder(e.dataStream)||[];this._formulaPromptService.setSequenceNodes(t);const n=this._docSelectionManagerService.getActiveTextRange();if(n==null)return;const{startOffset:o}=n;this._currentInsertRefStringIndex=o-1+e.offset;return}this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue($.REF_SELECTIONS_ENABLED,!1),this._contextService.setContextValue(F.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._formulaPromptService.disableLockedSelectionChange(),this._formulaPromptService.disableLockedSelectionInsert(),this._formulaPromptService.clearSequenceNodes(),this._hideFunctionPanel()}_getContextState(){return this._contextService.getContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA)}_highlightFormula(){if(this._getContextState()===!1)return;const e=this._formulaPromptService.getSequenceNodes(),t=this._editorModelUnitIds(),n=this._getFormulaAndCellEditorBody(t).filter(o=>!!o);if(e==null||e.length===0)this._existsSequenceNode=!1,n.forEach(o=>o.textRuns=[]);else{this._existsSequenceNode=!0;const{textRuns:o,refSelections:s}=this._buildTextRuns(e);n.forEach(i=>i.textRuns=o),this._allSelectionRenderServices.forEach(i=>this._refreshSelectionForReference(i,s))}this._refreshFormulaAndCellEditor(t)}_buildTextRuns(e){var a;const t=[],n=[],o=new Map;let s=0;const i=((a=this._getCurrentBodyDataStreamAndOffset())==null?void 0:a.offset)||0;for(let l=0,d=e.length;l<d;l++){const h=e[l];if(typeof h=="string"||this._descriptionService.hasDefinedNameDescription(h.token.trim()))continue;const{startIndex:f,endIndex:u,nodeType:m,token:p}=h;let C="";if(m===I.sequenceNodeType.REFERENCE){if(o.has(p))C=o.get(p);else{const g=s%this._formulaRefColors.length;C=this._formulaRefColors[g],o.set(p,C),s++}n.push({refIndex:l,themeColor:C,token:p})}else m===I.sequenceNodeType.NUMBER?C=this._numberColor:m===I.sequenceNodeType.STRING?C=this._stringColor:m===I.sequenceNodeType.ARRAY&&(C=this._stringColor);C&&C.length>0&&t.push({st:f+1-i,ed:u+2-i,ts:{cl:{rgb:C}}})}return{textRuns:t,refSelections:n}}_exceedCurrentRange(e,t,n){const{startRow:o,startColumn:s}=e;return o>t-1||s>n-1}_refreshSelectionForReference(e,t){const{unitId:n,sheetId:o}=this._editorBridgeService.getEditCellState(),{unitId:s,sheetId:i}=this._getCurrentUnitIdAndSheetId(),a=o===i,d=this._univerInstanceService.getUniverSheetInstance(n).getSheetBySheetId(o);let h=null;const f=[];for(let u=0,m=t.length;u<m;u++){const p=t[u],{themeColor:C,token:g,refIndex:E}=p,v=I.deserializeRangeWithSheet(g),{unitId:_,sheetName:y,range:b}=v,N=$.setEndForRange(b,d.getRowCount(),d.getColumnCount());if(_!=null&&_.length>0&&n!==_)continue;const T=this._getSheetIdByName(n,y.trim());if(!a&&T!==i||a&&y.length!==0&&T!==o||this._exceedCurrentRange(N,d.getRowCount(),d.getColumnCount()))continue;const M=this._getPrimary(N,C,E);if(M){h=M,f.push(h);continue}const x=$.getPrimaryForRange(N,d);!c.Rectangle.equals(x,N)&&N.startRow===N.endRow&&N.startColumn===N.endColumn&&(N.startRow=x.startRow,N.endRow=x.endRow,N.startColumn=x.startColumn,N.endColumn=x.endColumn),f.push({range:N,primary:x,style:$e(this._themeService,C,E.toString())})}f.length&&this._refSelectionsService.setSelections(n,o,f,$.SelectionMoveType.ONLY_SET)}_getPrimary(e,t,n){const o=this._insertSelections.find(f=>{const{startRow:u,startColumn:m,endRow:p,endColumn:C}=f.range;return u===e.startRow&&m===e.startColumn&&p===e.endRow&&C===e.endColumn||u===e.startRow&&m===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn});if((o==null?void 0:o.primary)==null)return;const{isMerged:s,isMergedMainCell:i,startRow:a,endRow:l,startColumn:d,endColumn:h}=o.primary;return(s||i)&&a===e.startRow&&d===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn&&(e.endRow=l,e.endColumn=h),{range:e,primary:o.primary,style:$e(this._themeService,t,n.toString())}}_getSheetIdByName(e,t){var o;const n=this._univerInstanceService.getUniverSheetInstance(e);return(o=n==null?void 0:n.getSheetBySheetName(I.normalizeSheetName(t)))==null?void 0:o.getSheetId()}_getSheetNameById(e,t){var s;const n=this._univerInstanceService.getUniverSheetInstance(e);return((s=n==null?void 0:n.getSheetBySheetId(t))==null?void 0:s.getName())||""}_getCurrentUnitIdAndSheetId(){var o,s;const e=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),t=e.getActiveSheet(),n=(s=(o=this._renderManagerService.getRenderById(e.getUnitId()))==null?void 0:o.with(P.SheetSkeletonManagerService))==null?void 0:s.getCurrentSkeleton();return{unitId:e.getUnitId(),sheetId:(t==null?void 0:t.getSheetId())||"",skeleton:n}}_getEditorOpenedForSheet(){const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),n=this._editorService.getEditor(t);return n?{openUnitId:n.getOpenForSheetUnitId(),openSheetId:n.getOpenForSheetSubUnitId()}:{openUnitId:null,openSheetId:null}}_generateRefString(e){let t="",n="";const{unitId:o,sheetId:s}=e.range,{openUnitId:i,openSheetId:a}=this._getEditorOpenedForSheet();o!==i&&o&&(t=o),s!==a&&o&&s&&(n=this._getSheetNameById(o,s));const{range:l,primary:d}=e;let{startRow:h,endRow:f,startColumn:u,endColumn:m}=l;const{startAbsoluteRefType:p,endAbsoluteRefType:C,rangeType:g}=l;if(d){const{isMerged:E,isMergedMainCell:v,startRow:_,endRow:y,startColumn:b,endColumn:N}=d;(E||v)&&_===h&&b===u&&y===f&&N===m&&(h=_,u=b,f=_,m=b)}return I.serializeRangeToRefString({sheetName:n,unitId:t,range:{startRow:h,endRow:f,startColumn:u,endColumn:m,rangeType:g,startAbsoluteRefType:p,endAbsoluteRefType:C}})}_syncToEditor(e,t,n,o=!0,s=!0){let i=I.generateStringWithSequence(e);const{textRuns:a,refSelections:l}=this._buildTextRuns(e);this._isSelectionMovingRefSelections=l,this._allSelectionRenderServices.forEach(C=>this._updateRefSelectionStyle(C,this._isSelectionMovingRefSelections));const d=this._docSelectionManagerService.getActiveTextRange();if(d==null)return;this._currentInsertRefStringIndex=t,n==null&&(n=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId()),this._fitEditorSize();const h=this._editorService.getEditor(n);h!=null&&h.isSingleChoice()?(i=i.split(",")[0],this._selectionRenderService.setSingleSelectionEnabled(!0)):this._selectionRenderService.setSingleSelectionEnabled(!1);let f=i,u=1;(!h||!h.onlyInputRange())&&(f=`${I.compareToken.EQUALS}${i}`,u=0);const{collapsed:m,style:p}=d;o?(this._commandService.executeCommand(ee.ReplaceContentCommand.id,{unitId:n,body:{dataStream:f,textRuns:a},textRanges:[{startOffset:t+1-u,endOffset:t+1-u,collapsed:m,style:p}],segmentId:null,options:{fromSelection:s}}),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:p}],!0,{fromSelection:s})):(this._updateEditorModel(`${f}\r
35
+ `,a),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:p}],!0,{fromSelection:s})),this._layoutService.focus()}_fitEditorSize(){var n;const t=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId();if(!(this._editorService.isEditor(t)&&!this._editorService.isSheetEditor(t))&&(this._editorBridgeService.changeEditorDirty(!0),!!this._editorBridgeService.isVisible().visible&&t===c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY)){const o=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET),s=(n=o==null?void 0:o.getUnitId())!=null?n:"",i=this._renderManagerService.getRenderById(s);if(!i)return;i.with(P.SheetCellEditorResizeService).fitTextSize()}}_updateEditorModel(e,t){var l;const n=this._univerInstanceService.getCurrentUniverDocInstance(),o=n.getUnitId();if(!this._editorService.isEditor(o))return;const s=(l=this._renderManagerService.getRenderById(o))==null?void 0:l.with(je.DocSkeletonManagerService).getViewModel();if(s==null||n==null)return;const i=n==null?void 0:n.getSnapshot();if(i==null)return;const a={dataStream:e,textRuns:t};i.body=a,s.reset(n)}_insertControlSelectionReplace(e){this._previousSequenceNodes==null&&(this._previousSequenceNodes=this._formulaPromptService.getSequenceNodes()),this._previousInsertRefStringIndex==null&&(this._previousInsertRefStringIndex=this._currentInsertRefStringIndex);const t=c.Tools.deepClone(this._previousSequenceNodes);if(t==null)return;const{skeleton:n}=this._getCurrentUnitIdAndSheetId(),o=n==null?void 0:n.worksheet.getUnitId(),s=n==null?void 0:n.worksheet.getSheetId();e.range.sheetId=s,e.range.unitId=o;const i=this._generateRefString(e);this._formulaPromptService.setSequenceNodes(t),this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,i),this._syncToEditor(t,this._previousInsertRefStringIndex+i.length);const a=this._selectionRenderService.getSelectionDataWithStyle()||[];this._insertSelections=[];const l=a[a.length-1];if(l){const d=$.convertSelectionDataToRange(l);this._insertSelections.push(d)}}_focusIsOnlyRange(e){const t=this._editorService.getFocusEditor();return!t||!t.onlyInputRange()||this._existsSequenceNode||e>1||this._previousSequenceNodes!=null&&this._previousSequenceNodes.length>0?!0:(this._previousInsertRefStringIndex!=null&&(this._previousInsertRefStringIndex+=1),!1)}_resetSequenceNodes(e){const t=this._editorService.getFocusEditor();t&&t.onlyInputRange()&&(e>1||this._existsSequenceNode&&(this._formulaPromptService.clearSequenceNodes(),this._previousRangesCount=0,this._existsSequenceNode=!1))}_updateRefSelectionStyle(e,t){const n=e.getSelectionControls(),[o,s]=e.getLocation(),i=new Set;for(let a=0,l=t.length;a<l;a++){const d=t[a],{refIndex:h,themeColor:f,token:u}=d,m=I.deserializeRangeWithSheet(u),{unitId:p,sheetName:C,range:g}=m;if(!p&&p.length>0&&o!==p)continue;const E=this._getSheetIdByName(o,C.trim());if(E&&E!==s)continue;const v=n.find(_=>{const{startRow:y,startColumn:b,endRow:N,endColumn:T,rangeType:M}=_.getRange();return M===c.RANGE_TYPE.COLUMN&&b===g.startColumn&&T===g.endColumn||M===c.RANGE_TYPE.ROW&&y===g.startRow&&N===g.endRow||y===g.startRow&&b===g.startColumn&&N===g.endRow&&T===g.endColumn||y===g.startRow&&b===g.startColumn&&g.startRow===g.endRow&&g.startColumn===g.endColumn});if(v){const _=$e(this._themeService,f,h.toString());v.updateStyle(_),i.add(v)}}}_onSelectionControlChange(e,t){var v;const{skeleton:n}=this._getCurrentUnitIdAndSheetId();if(!n)return;this._formulaPromptService.enableLockedSelectionChange();const o=(v=t.currentStyle)==null?void 0:v.id;if(!o||!c.Tools.isStringNumber(o))return;let{startRow:s,endRow:i,startColumn:a,endColumn:l}=e;const d=n?n.worksheet.getCellInfoInMergeData(s,a):{actualRow:s,actualColumn:a,isMergedMainCell:!1,isMerged:!1,endRow:s,endColumn:a,startRow:s,startColumn:a};if(d){const{isMerged:_,isMergedMainCell:y,startRow:b,endRow:N,startColumn:T,endColumn:M}=d;(_||y)&&b===s&&T===a&&N===i&&M===l&&(s=b,a=T,i=b,l=T)}const h=Number(o),f=this._formulaPromptService.getCurrentSequenceNodeByIndex(h);if(!f)return;let u={startAbsoluteRefType:c.AbsoluteRefType.NONE};if(typeof f!="string"){const _=f.token;u=I.getAbsoluteRefTypeWitString(_),u.endAbsoluteRefType==null&&(u.endAbsoluteRefType=u.startAbsoluteRefType)}const m=n==null?void 0:n.worksheet.getUnitId(),p=n==null?void 0:n.worksheet.getSheetId(),C=this._generateRefString({range:{startRow:Math.min(s,i),endRow:Math.max(s,i),startColumn:Math.min(a,l),endColumn:Math.max(a,l),...u,sheetId:p,unitId:m},primary:d,style:null});this._formulaPromptService.updateSequenceRef(h,C);const g=this._formulaPromptService.getSequenceNodes(),E=g[h];typeof E!="string"&&(this._syncToEditor(g,E.endIndex+1),t.updateRange(e,this._selectionRenderService.attachPrimaryWithCoord(d)))}_refreshFormulaAndCellEditor(e){var t;for(const n of e){const o=P.getEditorObject(n,this._renderManagerService),s=o==null?void 0:o.document;s!=null&&((t=s.getSkeleton())==null||t.calculate(),s.makeDirty())}}_cursorStateListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t.onPointerDown$.subscribeEvent(()=>{this._arrowMoveActionState=1,this._inputPanelState=3}))}_pressEnter(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressTab(e){const{keycode:t,isSingleEditor:n=!1}=e;if(this._formulaPromptService.isSearching()){this._formulaPromptService.accept(!0);return}n!==!0&&this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressEsc(e){const{keycode:t}=e,n=this._editorService.getFocusEditor();(!n||(n==null?void 0:n.isSheetEditor())===!0)&&this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressArrowKey(e){const{keycode:t,metaKey:n}=e;let o=c.Direction.DOWN;t===F.KeyCode.ARROW_DOWN?o=c.Direction.DOWN:t===F.KeyCode.ARROW_UP?o=c.Direction.UP:t===F.KeyCode.ARROW_LEFT?o=c.Direction.LEFT:t===F.KeyCode.ARROW_RIGHT&&(o=c.Direction.RIGHT),n===F.MetaKeys.CTRL_COMMAND?this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:o,jumpOver:P.JumpOver.moveGap}):n===F.MetaKeys.SHIFT?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:o}):n===un?this._commandService.executeCommand(P.ExpandSelectionCommand.id,{direction:o,jumpOver:P.JumpOver.moveGap}):this._commandService.executeCommand(P.MoveSelectionCommand.id,{direction:o})}_commandExecutedListener(){const e=[Ie.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC),o=(n==null?void 0:n.getUnitId())||"";if(!(P.isRangeSelector(o)||P.isEmbeddingFormulaEditor(o))){if(t.id===et.id)this._changeRefString();else if(e.includes(t.id)){const s=t.params,{keycode:i,isSingleEditor:a=!1}=s;if(i===F.KeyCode.ENTER){this._pressEnter(s);return}if(i===F.KeyCode.TAB){this._pressTab(s);return}if(i===F.KeyCode.ESC){this._pressEsc(s);return}if(this._formulaPromptService.isSearching()){if(i===F.KeyCode.ARROW_DOWN){this._formulaPromptService.navigate({direction:c.Direction.DOWN});return}if(i===F.KeyCode.ARROW_UP){this._formulaPromptService.navigate({direction:c.Direction.UP});return}}if(a===!0)return;if(this._arrowMoveActionState===1){this._moveInEditor(i);return}if(this._arrowMoveActionState===4){this._editorBridgeService.changeVisible({visible:!1,eventType:z.DeviceInputEventType.Keyboard,keycode:i,unitId:""});return}if(this._arrowMoveActionState===2&&(this._arrowMoveActionState=3),this._refSelectionsService.getCurrentSelections().length===0){const f=this._sheetsSelectionsService.getCurrentLastSelection();if(f!=null){const u=c.Tools.deepClone(f);this._refSelectionsService.setSelections([u])}}this._pressArrowKey(s);const d=this._refSelectionsService.getCurrentSelections(),h=d[d.length-1];this._insertControlSelectionReplace(h),this._highlightFormula()}}}))}_moveInEditor(e){if(e==null)return;let t=c.Direction.LEFT;e===F.KeyCode.ARROW_DOWN?t=c.Direction.DOWN:e===F.KeyCode.ARROW_UP?t=c.Direction.UP:e===F.KeyCode.ARROW_RIGHT&&(t=c.Direction.RIGHT),this._commandService.executeCommand(ee.MoveCursorOperation.id,{direction:t})}_userMouseListener(){const e=this._getEditorObject();if(e==null)return;const{mainComponent:t}=e;t&&this.disposeWithMe(t==null?void 0:t.onPointerDown$.subscribeEvent(()=>{this._userCursorMove=!0}))}_inputFormulaListener(){this.disposeWithMe(this._editorService.inputFormula$.subscribe(e=>{const{formulaString:t,editorUnitId:n}=e;if(t.substring(0,1)!==I.compareToken.EQUALS)return;const{unitId:o}=this._getCurrentUnitIdAndSheetId();this._editorBridgeService.isVisible().visible===!1&&this._editorBridgeService.changeVisible({visible:!0,eventType:z.DeviceInputEventType.Dblclick,unitId:o});const i=this._lexerTreeBuilder.sequenceNodesBuilder(t)||[];this._formulaPromptService.setSequenceNodes(i),this._syncToEditor(i,t.length-1,n,!0,!1)}))}_changeRefString(){const e=this._docSelectionManagerService.getActiveTextRange();if(e==null)return;const{startOffset:t}=e,n=t-2,o=this._formulaPromptService.getCurrentSequenceNodeIndex(n),s=this._formulaPromptService.getCurrentSequenceNodeByIndex(o);if(s==null||typeof s=="string"||s.nodeType!==I.sequenceNodeType.REFERENCE)return;const i=s.token.split("!");let a=s.token;i.length>1&&(a=i[i.length-1]);let l="";for(let f=0,u=i.length;f<u-1;f++)l+=i[f];let d=a;if(a.indexOf(I.matchToken.COLON)>-1)if(!this._userCursorMove)d=this._changeRangeRef(a);else{const f=a.split(I.matchToken.COLON),u=f[0],m=f[1];n-s.startIndex<=u.length?d=this._changeSingleRef(u)+I.matchToken.COLON+m:d=u+I.matchToken.COLON+this._changeSingleRef(m)}else d=this._changeSingleRef(a);d=l+d;const h=d.length-s.token.length;this._formulaPromptService.updateSequenceRef(o,d),this._syncToEditor(this._formulaPromptService.getSequenceNodes(),n+h+1)}_changeRangeRef(e){const t=I.deserializeRangeWithSheet(e).range;let n="";return t.startAbsoluteRefType===c.AbsoluteRefType.NONE||t.startAbsoluteRefType==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),n=I.serializeRange(t),n}_changeSingleRef(e){const t=I.deserializeRangeWithSheet(e).range,n=t.startAbsoluteRefType;let o="";return n===c.AbsoluteRefType.NONE||n==null?(t.startAbsoluteRefType=c.AbsoluteRefType.ALL,t.endAbsoluteRefType=c.AbsoluteRefType.ALL):n===c.AbsoluteRefType.ALL?(t.startAbsoluteRefType=c.AbsoluteRefType.ROW,t.endAbsoluteRefType=c.AbsoluteRefType.ROW):n===c.AbsoluteRefType.ROW?(t.startAbsoluteRefType=c.AbsoluteRefType.COLUMN,t.endAbsoluteRefType=c.AbsoluteRefType.COLUMN):(t.startAbsoluteRefType=c.AbsoluteRefType.NONE,t.endAbsoluteRefType=c.AbsoluteRefType.NONE),o=I.serializeRange(t),o}_getEditorObject(){const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const t=e.getUnitId(),n=this._editorService.getEditor(t);return n==null?void 0:n.render}_isFormulaEditorActivated(){return this._editorBridgeService.isVisible().visible===!0||this._contextService.getContextValue(c.FORMULA_EDITOR_ACTIVATED)}_isSheetOrFormulaEditor(e){return e.isSheetEditor()||e.isFormulaEditor()}};Ze=Ts([se(0,c.ICommandService),se(1,c.IContextService),se(2,c.Inject(P.IEditorBridgeService)),se(3,c.Inject(Fe)),se(4,c.Inject(I.LexerTreeBuilder)),se(5,z.IRenderManagerService),se(6,c.Inject(c.ThemeService)),se(7,c.Inject($.SheetsSelectionsService)),se(8,$.IRefSelectionsService),se(9,c.IUniverInstanceService),se(10,c.Inject(ge.IDescriptionService)),se(11,c.Inject(je.DocSelectionManagerService)),se(12,F.IContextMenuService),se(13,ee.IEditorService),se(14,F.ILayoutService)],Ze);var dn=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,xs=(r,e,t)=>e in r?dn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ms=(r,e,t,n)=>{for(var o=n>1?void 0:n?Ns(e,t):e,s=r.length-1,i;s>=0;s--)(i=r[s])&&(o=(n?i(e,t,o):i(o))||o);return n&&o&&dn(e,t,o),o},ft=(r,e)=>(t,n)=>e(t,n,r),fn=(r,e,t)=>xs(r,typeof e!="symbol"?e+"":e,t);exports.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(e=Ft,t,n,o){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=o;const{menu:s,...i}=c.merge(Ft,this._config);s&&this._configService.setConfig("menu",s,{merge:!0}),this._configService.setConfig(Wr,i)}onStarting(){const e=this._injector;[[Fe,{useClass:ht}],[Ge],[qe],[Ke],[ze],[Ye],[Ze]].forEach(n=>e.add(n))}onRendered(){[[exports.RefSelectionsRenderService],[St]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[Ge],[Ke],[Ye]]);const e=this._injector.get(F.ComponentManager);e.register(P.RANGE_SELECTOR_COMPONENT_KEY,on),e.register(P.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,sn)}onSteady(){this._injector.get(qe),this._injector.get(Ze)}};fn(exports.UniverSheetsFormulaUIPlugin,"pluginName",Lt);fn(exports.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=Ms([c.DependentOn(I.UniverFormulaEnginePlugin,ge.UniverSheetsFormulaPlugin),ft(1,c.Inject(c.Injector)),ft(2,z.IRenderManagerService),ft(3,c.IConfigService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=Pt;exports.FormulaEditor=sn;exports.HelpFunctionOperation=He;exports.InsertFunctionOperation=Qe;exports.MoreFunctionsOperation=Je;exports.RangeSelector=on;exports.ReferenceAbsoluteOperation=et;exports.SearchFunctionOperation=Be;exports.SelectEditorFormulaOperation=Ie;exports.SheetOnlyPasteFormulaCommand=Xe;