@univerjs/sheets-formula-ui 0.5.0 → 0.5.1

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.
Files changed (27) hide show
  1. package/lib/cjs/index.js +27 -9
  2. package/lib/cjs/locale/fr-FR.js +43 -0
  3. package/lib/es/index.js +1318 -1277
  4. package/lib/es/locale/fr-FR.js +7889 -0
  5. package/lib/types/controllers/__tests__/create-command-test-bed.d.ts +1 -0
  6. package/lib/types/controllers/formula-alert-render.controller.d.ts +1 -0
  7. package/lib/types/index.d.ts +1 -1
  8. package/lib/types/locale/fr-FR.d.ts +10504 -0
  9. package/lib/types/locale/function-list/array/fr-FR.d.ts +17 -0
  10. package/lib/types/locale/function-list/compatibility/fr-FR.d.ts +706 -0
  11. package/lib/types/locale/function-list/cube/fr-FR.d.ts +144 -0
  12. package/lib/types/locale/function-list/database/fr-FR.d.ts +234 -0
  13. package/lib/types/locale/function-list/date/fr-FR.d.ts +458 -0
  14. package/lib/types/locale/function-list/engineering/fr-FR.d.ts +894 -0
  15. package/lib/types/locale/function-list/financial/fr-FR.d.ts +1608 -0
  16. package/lib/types/locale/function-list/information/fr-FR.d.ts +327 -0
  17. package/lib/types/locale/function-list/logical/fr-FR.d.ts +390 -0
  18. package/lib/types/locale/function-list/lookup/fr-FR.d.ts +812 -0
  19. package/lib/types/locale/function-list/math/fr-FR.d.ts +1388 -0
  20. package/lib/types/locale/function-list/statistical/fr-FR.d.ts +2068 -0
  21. package/lib/types/locale/function-list/text/fr-FR.d.ts +904 -0
  22. package/lib/types/locale/function-list/univer/fr-FR.d.ts +17 -0
  23. package/lib/types/locale/function-list/web/fr-FR.d.ts +72 -0
  24. package/lib/umd/index.js +27 -9
  25. package/lib/umd/locale/fr-FR.js +43 -0
  26. package/package.json +19 -17
  27. package/lib/types/services/formula-common.d.ts +0 -18
package/lib/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var dn=Object.defineProperty;var hn=(r,e,t)=>e in r?dn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var W=(r,e,t)=>hn(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),D=require("@univerjs/sheets-ui"),C=require("@univerjs/engine-formula"),V=require("rxjs"),J=require("@univerjs/docs-ui"),$=require("@univerjs/sheets"),ge=require("@univerjs/sheets-formula"),x=require("@univerjs/ui"),S=require("react"),oe=require("@univerjs/design"),K=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(D.SheetPasteCommand.id,{value:D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Ie={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(r,e)=>!0};var fn=Object.defineProperty,mn=Object.getOwnPropertyDescriptor,Sn=(r,e,t,n)=>{for(var o=n>1?void 0:n?mn(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&&fn(e,t,o),o},gn=(r,e)=>(t,n)=>e(t,n,r);const Ft="FORMULA_PROMPT_ACTIVATED",xe=c.createIdentifier("formula-ui.prompt-service");let dt=class{constructor(r){W(this,"_search$",new V.Subject);W(this,"_help$",new V.Subject);W(this,"_navigate$",new V.Subject);W(this,"_accept$",new V.Subject);W(this,"_acceptFormulaName$",new V.Subject);W(this,"search$",this._search$.asObservable());W(this,"help$",this._help$.asObservable());W(this,"navigate$",this._navigate$.asObservable());W(this,"accept$",this._accept$.asObservable());W(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());W(this,"_searching",!1);W(this,"_helping",!1);W(this,"_sequenceNodes",[]);W(this,"_isLockedOnSelectionChangeRefString",!1);W(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(Ft,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!==C.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:C.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}};dt=Sn([gn(0,c.IContextService)],dt);const He={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(r,e)=>(r.get(xe).help(e),!0)},Qe={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(r,e)=>{var I,v;const t=r.get($.SheetsSelectionsService),n=r.get(J.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 p=null,m=0,R=0,g="";if(o.length===1&&(_n(o[0].range)||Cn(o[0].range))){const{range:y,primary:E}=o[0],M=(I=E==null?void 0:E.actualRow)!=null?I:y.startRow,b=(v=E==null?void 0:E.actualColumn)!=null?v:y.startColumn;p=y,m=M,R=b;const T=It(d,M,b);T&&(g=C.serializeRange(T))}else o.some(y=>{var P,k;const{range:E,primary:M}=y,b=(P=M==null?void 0:M.actualRow)!=null?P:E.startRow,T=(k=M==null?void 0:M.actualColumn)!=null?k:E.startColumn,F=It(d,b,T);if(!F)return p=E,m=b,R=T,!0;const N=C.serializeRange(F),L=`=${f}(${N})`;return u.push({range:E,primary:{row:b,column:T},formula:L}),!1});if(p){const y=$.getCellAtRowCol(m,R,i),E={range:c.Rectangle.clone(p),primary:{startRow:y.startRow,startColumn:y.startColumn,endRow:y.endRow,endColumn:y.endColumn,actualRow:m,actualColumn:R,isMerged:y.isMerged,isMergedMainCell:y.startRow===m&&y.startColumn===R}},M={unitId:a,subUnitId:l,selections:[E]};await h.executeCommand($.SetSelectionsOperation.id,M),setTimeout(()=>{n.setFormula(`=${f}(${g}`)},0)}return u.length===0?!1:h.executeCommand(ge.InsertFunctionCommand.id,{list:u})}};function It(r,e,t){const n=pn(r,e,t);if(n!==e)return{startRow:n,endRow:e-1,startColumn:t,endColumn:t};const o=vn(r,e,t);return o!==t?{startRow:e,endRow:e,startColumn:o,endColumn:t-1}:null}function pn(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 vn(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 _n(r){return r.startRow===r.endRow&&r.startColumn===r.endColumn}function Cn(r){return r.startRow!==r.endRow&&r.startColumn!==r.endColumn}const Ot="SHEET_FORMULA_UI_PLUGIN",At=`${Ot}_MORE_FUNCTIONS_COMPONENT`,Je={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async r=>(r.get(x.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:At}}),!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(xe).search(e),!0)};var Dt={exports:{}},tt={};/**
1
+ "use strict";var hn=Object.defineProperty;var fn=(r,e,t)=>e in r?hn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var W=(r,e,t)=>fn(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),D=require("@univerjs/sheets-ui"),R=require("@univerjs/engine-formula"),V=require("rxjs"),J=require("@univerjs/docs-ui"),$=require("@univerjs/sheets"),ge=require("@univerjs/sheets-formula"),M=require("@univerjs/ui"),g=require("react"),oe=require("@univerjs/design"),K=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(D.SheetPasteCommand.id,{value:D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA})},Ie={id:"formula-ui.operation.select-editor-formula",type:c.CommandType.OPERATION,handler:(r,e)=>!0};var mn=Object.defineProperty,Sn=Object.getOwnPropertyDescriptor,gn=(r,e,t,n)=>{for(var o=n>1?void 0:n?Sn(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&&mn(e,t,o),o},pn=(r,e)=>(t,n)=>e(t,n,r);const Dt="FORMULA_PROMPT_ACTIVATED",Me=c.createIdentifier("formula-ui.prompt-service");let ht=class{constructor(r){W(this,"_search$",new V.Subject);W(this,"_help$",new V.Subject);W(this,"_navigate$",new V.Subject);W(this,"_accept$",new V.Subject);W(this,"_acceptFormulaName$",new V.Subject);W(this,"search$",this._search$.asObservable());W(this,"help$",this._help$.asObservable());W(this,"navigate$",this._navigate$.asObservable());W(this,"accept$",this._accept$.asObservable());W(this,"acceptFormulaName$",this._acceptFormulaName$.asObservable());W(this,"_searching",!1);W(this,"_helping",!1);W(this,"_sequenceNodes",[]);W(this,"_isLockedOnSelectionChangeRefString",!1);W(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(Dt,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!==R.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:R.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=gn([pn(0,c.IContextService)],ht);const He={id:"formula-ui.operation.help-function",type:c.CommandType.OPERATION,handler:async(r,e)=>(r.get(Me).help(e),!0)},Qe={id:"formula-ui.operation.insert-function",type:c.CommandType.OPERATION,handler:async(r,e)=>{var E,m;const t=r.get($.SheetsSelectionsService),n=r.get(J.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,v=0,C=0,p="";if(o.length===1&&(Cn(o[0].range)||Rn(o[0].range))){const{range:I,primary:y}=o[0],x=(E=y==null?void 0:y.actualRow)!=null?E:I.startRow,b=(m=y==null?void 0:y.actualColumn)!=null?m:I.startColumn;S=I,v=x,C=b;const T=Et(d,x,b);T&&(p=R.serializeRange(T))}else o.some(I=>{var P,k;const{range:y,primary:x}=I,b=(P=x==null?void 0:x.actualRow)!=null?P:y.startRow,T=(k=x==null?void 0:x.actualColumn)!=null?k:y.startColumn,F=Et(d,b,T);if(!F)return S=y,v=b,C=T,!0;const N=R.serializeRange(F),L=`=${f}(${N})`;return u.push({range:y,primary:{row:b,column:T},formula:L}),!1});if(S){const I=$.getCellAtRowCol(v,C,i),y={range:c.Rectangle.clone(S),primary:{startRow:I.startRow,startColumn:I.startColumn,endRow:I.endRow,endColumn:I.endColumn,actualRow:v,actualColumn:C,isMerged:I.isMerged,isMergedMainCell:I.startRow===v&&I.startColumn===C}},x={unitId:a,subUnitId:l,selections:[y]};await h.executeCommand($.SetSelectionsOperation.id,x),setTimeout(()=>{n.setFormula(`=${f}(${p}`)},0)}return u.length===0?!1:h.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=_n(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 _n(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 Cn(r){return r.startRow===r.endRow&&r.startColumn===r.endColumn}function Rn(r){return r.startRow!==r.endRow&&r.startColumn!==r.endColumn}const Pt="SHEET_FORMULA_UI_PLUGIN",Lt=`${Pt}_MORE_FUNCTIONS_COMPONENT`,Je={id:"formula-ui.operation.more-functions",type:c.CommandType.OPERATION,handler:async r=>(r.get(M.ISidebarService).open({header:{title:"formula.insert.tooltip"},children:{label:Lt}}),!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(Me).search(e),!0)};var ot={exports:{}},Oe={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,11 +6,29 @@
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 Rn=S,In=Symbol.for("react.element"),En=Symbol.for("react.fragment"),yn=Object.prototype.hasOwnProperty,Tn=Rn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,bn={key:!0,ref:!0,__self:!0,__source:!0};function Pt(r,e,t){var n,o={},s=null,i=null;t!==void 0&&(s=""+t),e.key!==void 0&&(s=""+e.key),e.ref!==void 0&&(i=e.ref);for(n in e)yn.call(e,n)&&!bn.hasOwnProperty(n)&&(o[n]=e[n]);if(r&&r.defaultProps)for(n in e=r.defaultProps,e)o[n]===void 0&&(o[n]=e[n]);return{$$typeof:In,type:r,key:s,ref:i,props:o,_owner:Tn.current}}tt.Fragment=En;tt.jsx=Pt;tt.jsxs=Pt;Dt.exports=tt;var _=Dt.exports,le=function(){return le=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},le.apply(this,arguments)},Nn=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=Nn(r,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(n," ").concat(o||"").trim(),l=S.useRef("_".concat(Fn()));return Lt(t,"".concat(n),{defIds:t.defIds,idSuffix:l.current},le({ref:e,className:a},i),s)});function Lt(r,e,t,n,o){return S.createElement(r.tag,le(le({key:e},Mn(r,t,o)),n),(xn(r,t).children||[]).map(function(s,i){return Lt(s,"".concat(e,"-").concat(r.tag,"-").concat(i),t,void 0,o)}))}function Mn(r,e,t){var n=le({},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 xn(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)?le(le({},r),{children:r.children.map(function(o){return typeof o.attrs.id=="string"&&n&&n.indexOf(o.attrs.id)>-1?le(le({},o),{attrs:le(le({},o.attrs),{id:o.attrs.id+e.idSuffix})}):o})}):r}function Fn(){return Math.random().toString(36).substring(2,8)}Ee.displayName="UniverIcon";var On={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"}}]},wt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"check-mark-single",ref:e,icon:On}))});wt.displayName="CheckMarkSingle";var An={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"}}]},nt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"close-single",ref:e,icon:An}))});nt.displayName="CloseSingle";var Dn={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"}}]},kt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"delete-single",ref:e,icon:Dn}))});kt.displayName="DeleteSingle";var Pn={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"}}]},Ut=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"details-single",ref:e,icon:Pn}))});Ut.displayName="DetailsSingle";var Ln={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"}}]},$t=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"increase-single",ref:e,icon:Ln}))});$t.displayName="IncreaseSingle";var wn={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"}}]},mt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"more-single",ref:e,icon:wn}))});mt.displayName="MoreSingle";var kn={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"}}]},jt=S.forwardRef(function(r,e){return S.createElement(Ee,Object.assign({},r,{id:"select-range-single",ref:e,icon:kn}))});jt.displayName="SelectRangeSingle";function Ht(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=Ht(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Wt(){for(var r,e,t=0,n="",o=arguments.length;t<o;t++)(r=arguments[t])&&(e=Ht(r))&&(n&&(n+=" "),n+=e);return n}var Un=Object.defineProperty,$n=Object.getOwnPropertyDescriptor,jn=(r,e,t,n)=>{for(var o=n>1?void 0:n?$n(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&&Un(e,t,o),o},Oe=(r,e)=>(t,n)=>e(t,n,r);exports.RefSelectionsRenderService=class extends D.BaseSelectionRenderService{constructor(t,n,o,s,i,a){super(n,o,s,i);W(this,"_workbookSelections");W(this,"_eventDisposables");this._context=t,this._refSelectionsService=a,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Hn(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._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)=>{const h=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:u}=D.getCoordByOffset(d.offsetX,d.offsetY,a,h);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.ROW)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(d),K.ScrollTimerType.Y),d.button!==2&&f.stopPropagation())})),l.add(o==null?void 0:o.onPointerDown$.subscribeEvent((d,f)=>{const h=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:u}=D.getCoordByOffset(d.offsetX,d.offsetY,a,h);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(d),K.ScrollTimerType.X),d.button!==2&&f.stopPropagation())})),l.add(i==null?void 0:i.onPointerDown$.subscribeEvent((d,f)=>{this._reset();const h=this._sheetSkeletonManagerService.getCurrent().skeleton,u=D.getAllSelection(h);this._addSelectionControlByModelData(u),this._selectionMoveStart$.next(this.getSelectionDataWithStyle());const p=a.onPointerUp$.subscribeEvent(()=>{p.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:D.genNormalSelectionStyle(this._themeService),s=this._scene;return t.style=o,this.newSelectionControl(s,n,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)}_initSelectionChangeListener(){this.disposeWithMe(this._workbookSelections.selectionSet$.subscribe(t=>{if(this._reset(),!!this._skeleton)for(const o of t)this._addSelectionControlByModelData(o)}))}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{if(!t)return;const{skeleton:n}=t,{scene:o}=this._context,s=o.getViewport(K.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(K.Vector2.FromArray([t.offsetX,t.offsetY]))}_getSheetObject(){return D.getSheetObject(this._context.unit,this._context)}_onPointerDown(t,n=0,o=c.RANGE_TYPE.NORMAL,s,i=K.ScrollTimerType.ALL){var P;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(K.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!h)return;const u=l.getCoordRelativeToViewport(K.Vector2.FromArray([d,f])),{x:p,y:m}=u;this._startViewportPosX=p,this._startViewportPosY=m;const R=l.getScrollXYInfoByViewport(u),{scaleX:g,scaleY:I}=l.getAncestorScale(),v=this._skeleton.getCellByOffset(p,m,g,I,R);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 y={range:v,primary:v,style:null};y.range.rangeType=o;const E=D.attachSelectionWithCoord(y,this._skeleton);this._startRangeWhenPointerDown={...E.rangeWithCoord};const M={...E.rangeWithCoord,rangeType:o};let b=this.getActiveSelectionControl();const T=this.getSelectionControls();for(const k of T){if(t.button===2&&k.model.isInclude(M)){b=k;return}if(k.model.isEqual(M)){b=k;break}}this._checkClearPreviousControls(t);const F=b==null?void 0:b.model.currentCell,N=t.shiftKey&&F,L=this._remainLastEnabled&&!t.ctrlKey&&!t.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;N&&F?this._makeSelectionByTwoCells(F,M,a,o,b):L&&b?b.updateRangeBySelectionWithCoord(E):b=this.newSelectionControl(l,a,y);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(),(P=l.getTransformer())==null||P.clearSelectedObjects(),this._setupPointerMoveListener(h,b,o,i,p,m),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 D.SelectionControl(t,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:a}),d=D.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=jn([Oe(1,c.Inject(c.Injector)),Oe(2,c.Inject(c.ThemeService)),Oe(3,x.IShortcutService),Oe(4,c.Inject(D.SheetSkeletonManagerService)),Oe(5,$.IRefSelectionsService)],exports.RefSelectionsRenderService);function Hn(r){const e=D.genNormalSelectionStyle(r);return e.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},e}const Wn=(r,e,t)=>{const o=c.useDependency(K.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===C.matchToken.COMMA?s.setSkipLastEnabled(!0):s.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[t,s]),S.useEffect(()=>{s&&(e.endsWith(C.matchToken.COMMA)||s.setSkipLastEnabled(!1))},[e,s])},Se=r=>r.map(e=>typeof e=="string"?e:e.token).join(""),Bt=(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=Se(r);e(s)}},[r]),()=>n.current=!0},rt=()=>{const r=c.useDependency(C.LexerTreeBuilder);return t=>r.sequenceNodesBuilder(t)||[]},Vt=(r,e,t,n,o,s)=>{const i=rt(),a=S.useRef(!0);S.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(),p={dataStream:(d=(l=h.body)==null?void 0:l.dataStream)!=null?d:`${e}\r
10
- `,...h.body};s.setDocumentData({...h,body:p})}a.current=!1}else if(t){const f=i(r),h=n(s,f);o(h)}}},[s,t])},qt=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 St(r){const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(c.ThemeService),n=c.useDependency($.IRefSelectionsService),s=c.useDependency(K.IRenderManagerService).getRenderById(r),i=s==null?void 0:s.with(exports.RefSelectionsRenderService),a=s==null?void 0:s.with(D.SheetSkeletonManagerService);return d=>{var I;const f=e.getUnit(r),h=f==null?void 0:f.getActiveSheet(),u=[];if(!f||!h){n.setSelections(u);return}const p=h.getSheetId(),m=v=>{var y;return(y=f==null?void 0:f.getSheetBySheetName(v))==null?void 0:y.getSheetId()};if(!((I=a==null?void 0:a.getWorksheetSkeleton(p))==null?void 0:I.skeleton))return;for(let v=0,y=d.length;v<y;v++){const E=d[v],{themeColor:M,token:b,refIndex:T}=E,F=C.deserializeRangeWithSheet(b),{unitId:N,sheetName:L,range:P}=F;if(N&&r!==N)continue;const k=m(L);if(k&&k!==p)continue;const A=$.setEndForRange(P,h.getRowCount(),h.getColumnCount());u.push({range:A,primary:null,style:$e(t,M,T.toString())})}((i==null?void 0:i.getSelectionControls())||[]).length===u.length?i==null||i.resetSelectionsByModelData(u):n.setSelections(u)}}function Kt(r=""){const e=c.useDependency(ge.IDescriptionService),t=zt(),n=S.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}=Yt(e,t,i);n&&h.forEach(g=>{g.ed=g.ed+n,g.st=g.st+n}),f.textRuns=h;const p=i.reduce((g,I)=>typeof I=="string"?`${g}${I}`:`${g}${I.token}`,"");f.dataStream=`${r}${p}\r
12
- `;let m;if(a){m=s.getSelectionRanges();const g=f.dataStream.length-2+n;m.forEach(I=>{I.startOffset=Math.max(0,Math.min(I.startOffset,g)),I.endOffset=Math.max(0,Math.min(I.endOffset,g))})}const R={...l,body:f};return s.setDocumentData(R,m),u}}}function zt(){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 Yt(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 v=i[i.length-1],y=v?v.ed:0,E=y+u.length;i.push({st:y,ed:E});continue}if(r.hasDefinedNameDescription(u.token.trim()))continue;const{startIndex:p,endIndex:m,nodeType:R,token:g}=u;let I="";if(R===C.sequenceNodeType.REFERENCE){if(l.has(g))I=l.get(g);else{const v=d%n.length;I=n[v],l.set(g,I),d++}a.push({refIndex:f,themeColor:I,token:g})}else R===C.sequenceNodeType.NUMBER?I=o:(R===C.sequenceNodeType.STRING||R===C.sequenceNodeType.ARRAY)&&(I=s);I&&I.length>0&&i.push({st:p,ed:m+1,ts:{cl:{rgb:I}}})}return{textRuns:i,refSelections:a}}const Gt=(r,e)=>{const t=c.useDependency(c.ICommandService),n=c.useDependency(x.IShortcutService);S.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 x.KeyCode.ARROW_LEFT:{const u=Math.max(h.startOffset-1,0);e.setSelectionRanges([{startOffset:u,endOffset:u}]);break}case x.KeyCode.ARROW_RIGHT:{const u=(((f=e.getDocumentData().body)==null?void 0:f.dataStream)||",,").length-2,p=Math.min(h.endOffset+1,u);e.setSelectionRanges([{startOffset:p,endOffset:p}]);break}}}};return i.add(t.registerCommand({id:s,type:c.CommandType.OPERATION,handler(l,d){const{keyCode:f}=d;a(f)}})),[x.KeyCode.ARROW_LEFT,x.KeyCode.ARROW_RIGHT,x.KeyCode.ARROW_DOWN,x.KeyCode.ARROW_UP].map(l=>({id:s,binding:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keyCode:l}})).forEach(l=>{i.add(n.registerShortcut(l))}),()=>{i.dispose()}},[e,r])},Zt=(r,e)=>{const n=c.useDependency(K.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])},gt=(r,e)=>{const t=c.useDependency(K.IRenderManagerService),n=c.useDependency(c.IContextService),o=c.useDependency(x.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($.DISABLE_NORMAL_SELECTIONS,!0),n.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{n.setContextValue(c.EDITOR_ACTIVATED,!1),n.setContextValue($.DISABLE_NORMAL_SELECTIONS,!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])},Xt=()=>{S.useEffect(()=>()=>{},[])},Qt=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])},Jt=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 m;if(!r)return;const o=r.render.with(je.DocSkeletonManagerService).getSkeleton(),{scene:s,mainComponent:i}=r.render,a=s.getViewport(J.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),p=f;s.transformByState({width:u,height:p}),i==null||i.resize(u,p),l>d?h==null?a&&new K.ScrollBar(a,{barSize:8,enableVertical:!1}):a==null||a.resetCanvasSizeAndUpdateScroll():(h=null,a==null||a.scrollToBarPos({x:0,y:0}),(m=a==null?void 0:a.getScrollBar())==null||m.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}},ht=r=>typeof r=="string"?r===C.matchToken.COMMA:!1,Bn=r=>{if(typeof r=="object")return r.nodeType===C.sequenceNodeType.REFERENCE},Vn=r=>r.filter(e=>ht(e)||Bn(e)),pt=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 Et(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!==""?C.serializeRangeWithSheet(t.sheetName,t.range):C.serializeRange(t.range)):r.map(t=>C.serializeRange(t.range)),en=(r,e,t,n,o,s,i)=>{const a=c.useDependency(K.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=S.useRef(!1),f=a.getRenderById(e),h=f==null?void 0:f.with(exports.RefSelectionsRenderService),u=S.useRef([]),p=S.useMemo(()=>{const R=Vn(n),g=u.current;return R.length===g.length?(g.splice(0),g.push(...R),g):R},[n]);u.current=p;const m=S.useRef();S.useEffect(()=>{if(r&&h){let R=!0;const g=(y,E)=>{var A;if(R||d.current){R=!1;return}const M=[...y],b=l.getUnit(e),T=((A=b==null?void 0:b.getActiveSheet())==null?void 0:A.getName())||"",F=p.map((O,B)=>{if(typeof O=="string"){if(!p[B-1])return null;const U=p[B+1];return ht(O)&&(ht(U)||B===p.length-1)?null:O}else if(O.nodeType===C.sequenceNodeType.REFERENCE){const w=C.deserializeRangeWithSheet(O.token);w.unitId=w.unitId===""?e:w.unitId,w.sheetName=w.sheetName===""?T:w.sheetName;const{unitId:U,sheetName:H}=w;if(s&&(U!==e||T!==H))return null;if(U===e&&T===H){const j=M.shift();if(j&&Et(l,e,j.rangeWithCoord.sheetId||"")===H){const Z={...O};return pt(j.rangeWithCoord),o?Z.token=C.serializeRangeWithSheet(T,j.rangeWithCoord):Z.token=C.serializeRange(j.rangeWithCoord),Z}}return O}return null}).filter(O=>!!O),N=he(M.map(O=>{var B,w,U;return{range:O.rangeWithCoord,unitId:(B=O.rangeWithCoord.unitId)!=null?B:"",sheetName:Et(l,(w=O.rangeWithCoord.unitId)!=null?w:"",(U=O.rangeWithCoord.sheetId)!=null?U:"")}}),o).join(C.matchToken.COMMA),L=Se(F),P=`${L}${L&&N?C.matchToken.COMMA:""}${N}`,k=d.current;i(P,k?-1:P.length,E)},I=h.selectionMoveEnd$.subscribe(y=>{if(g(y,!0),d.current=!1,m.current){const{result:E,offset:M}=m.current;i(E,M,!0),m.current=void 0}}),v=h.selectionMoving$.pipe(Ue.throttleTime(50)).subscribe(y=>{g(y,!1)});return()=>{I.unsubscribe(),v.unsubscribe()}}},[r,p,h,o,s,i]),S.useEffect(()=>{if(r&&h){const R=new c.DisposableCollection,g=(y,E)=>{var k;let M=0,b=0,T=!1;const F=l.getUnit(e),N=((k=F==null?void 0:F.getActiveSheet())==null?void 0:k.getName())||"",L=p.map(A=>{if(typeof A=="string")return T||(b+=A.length),A;if(A.nodeType===C.sequenceNodeType.REFERENCE){const O=C.deserializeRangeWithSheet(y);if(O.unitId=O.unitId===""?e:O.unitId,O.sheetName=O.sheetName===""?N:O.sheetName,M===E){T=!0;const B={...A,token:y};return o?B.token=C.serializeRangeWithSheet(O.sheetName,O.range):B.token=C.serializeRange(O.range),M++,b+=B.token.length,B}return M++,T||(b+=A.token.length),A}return A}),P=Se(L);m.current={result:P,offset:b},i(P,-1,!1)};let I=0;const v=h.selectionMoveEnd$.subscribe(()=>{I=setTimeout(()=>{R.dispose(),h.getSelectionControls().forEach((E,M)=>{R.add(V.merge(E.selectionMoving$,E.selectionScaling$).pipe(V.map(b=>C.serializeRange(b)),V.distinctUntilChanged()).subscribe(b=>{d.current=!0,g(b,M)}))})},30)});return()=>{v.unsubscribe(),R.dispose(),clearTimeout(I)}}},[r,h,p,i])},vt=(r,e,t,n,o,s)=>{const i=c.useDependency(c.ICommandService),a=c.useDependency(J.IEditorService),d=c.useDependency(K.IRenderManagerService).getRenderById(e),f=d==null?void 0:d.with(exports.RefSelectionsRenderService);S.useEffect(()=>{if(r&&f)if(t){const h=i.onCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){const p=f.getSelectionControls().length;for(let m=1;m<=p;m++)f.clearLastSelection();setTimeout(()=>{s()},30)}});return()=>{h.dispose()}}else{const h=i.beforeCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){n(!1),o(),s();const p=a.getEditor(c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);p==null||p.focus()}});return()=>{h.dispose()}}},[r,f])},tn=r=>!r.some(t=>{if(typeof t=="string"){if(t!==C.matchToken.COMMA)return!0}else if(t.nodeType!==C.sequenceNodeType.REFERENCE)return!0;return!1}),qn=(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=tn(t);e(o,Se(t))}},[t,e])},Kn="univer-sheet-range-selector-text-wrap",zn="univer-sheet-range-selector-placeholder",Yn="univer-sheet-range-selector-error",Gn="univer-sheet-range-selector-error-wrap",Zn="univer-sheet-range-selector-text",Xn="univer-sheet-range-selector-active",Qn="univer-sheet-range-selector-icon",Jn="univer-sheet-range-selector-dialog-item",er="univer-sheet-range-selector-dialog-item-delete",ue={sheetRangeSelectorTextWrap:Kn,sheetRangeSelectorPlaceholder:zn,sheetRangeSelectorError:Yn,sheetRangeSelectorErrorWrap:Gn,sheetRangeSelectorText:Zn,sheetRangeSelectorActive:Xn,sheetRangeSelectorIcon:Qn,sheetRangeSelectorDialogItem:Jn,sheetRangeSelectorDialogItemDelete:er},Ae=()=>{};function nn(r){const{initValue:e,unitId:t,subUnitId:n,errorText:o,placeholder:s,actions:i,onChange:a=Ae,onVerify:l=Ae,onRangeSelectorDialogVisibleChange:d=Ae,onBlur:f=Ae,onFocus:h=Ae,isFocus:u=!0,isOnlyOneRange:p=!1,isSupportAcrossSheet:m=!1}=r,R=c.useDependency(J.IEditorService),g=c.useDependency(c.LocaleService),I=c.useDependency(c.ICommandService),v=c.useDependency(C.LexerTreeBuilder),y=S.useRef(null),[E,M]=S.useState(!1),[b,T]=S.useState(u),F=S.useMemo(()=>c.createInternalEditorID(`${D.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),[N,L]=S.useState(),P=S.useRef(null),k=S.useMemo(()=>!E&&b,[E,b]),[A,O]=S.useState(()=>typeof e=="string"?e:he(e,m).join(C.matchToken.COMMA));i&&(i.handleOutClick=(q,Y)=>{y.current&&!E&&!y.current.contains(q.target)&&Y()});const B=S.useMemo(()=>A.split(C.matchToken.COMMA).filter(q=>!!q).map(q=>C.deserializeRangeWithSheet(q)),[A]),w=S.useMemo(()=>o!==void 0,[o]),U=Qt(!E&&b),H=S.useMemo(()=>q=>{const Y=v.sequenceNodesBuilder(q);if(Y){if(tn(Y)){const fe=Y.map(be=>{if(typeof be=="string")return be;if(be.nodeType===C.sequenceNodeType.REFERENCE){const Rt={...be},Fe=C.deserializeRangeWithSheet(be.token);return Fe.range=pt(Fe.range),m||(Fe.sheetName="",Fe.unitId=""),Rt.token=he([Fe],m)[0],Rt}return be}),_e=Se(fe);a(_e)}}else O("")},[m]),j=qt(N);S.useLayoutEffect(()=>{if(u){const q=setTimeout(()=>{T(u),u&&j()},30);return()=>{clearTimeout(q)}}else U(),T(u),N==null||N.blur()},[u,j]);const{checkScrollBar:Z}=Jt(N),ce=rt(),ae=S.useMemo(()=>ce(A),[A]),de=Kt(),X=St(t),te=(q,Y=!0)=>{if(!N)return;const ve=ce(q),fe=de(N,ve,Y);X(fe)},ie=Bt(ae,H,N),pe=S.useMemo(()=>(q,Y,ve)=>{te(q),O(q),ie(),ve&&(j(),Y!==-1&&setTimeout(()=>{const fe={startOffset:Y,endOffset:Y};N==null||N.setSelectionRanges([fe]);const _e=N==null?void 0:N.render.with(J.DocBackScrollRenderController);_e==null||_e.scrollToRange({...fe,collapsed:!0})},50),Z())},[N]);en(k,t,n,ae,m,p,pe),gt(k,t),Zt(t,p),Wn(t,A,N),qn(k,l,ae),Gt(k,N),Xt(),vt(k,t,m,T,f,()=>{k&&te(A)}),S.useEffect(()=>{if(N){const q=N.input$.pipe(V.throttleTime(100)).subscribe(Y=>{var fe,_e;const ve=((_e=(fe=Y.data.body)==null?void 0:fe.dataStream)!=null?_e:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");te(ve,!1),O(ve),ie()});return()=>{q.unsubscribe()}}},[N]),S.useEffect(()=>{const q=I.onCommandExecuted(Y=>{Y.id===D.SetCellEditVisibleOperation.id&&(M(!1),d(!1),T(!1),f())});return()=>{q.dispose()}},[m]),S.useLayoutEffect(()=>{let q;if(P.current){q=R.register({autofocus:!0,editorUnitId:F,isSingle:!0,initialSnapshot:{id:F,body:{dataStream:`\r
13
- `},documentStyle:{}}},P.current);const Y=R.getEditor(F);L(Y)}return()=>{q==null||q.dispose()}},[]),Vt(A,"",b,de,X,N);const z=()=>{setTimeout(()=>{h(),j(),T(!0)},30)},G=q=>{const Y=he(q,m).join(C.matchToken.COMMA);te(Y),ie(),O(Y),M(!1),d(!1),setTimeout(()=>{T(!0),N==null||N.setSelectionRanges([{startOffset:Y.length,endOffset:Y.length}]),j()},30)},ne=()=>{M(!1),d(!1),setTimeout(()=>{T(!0),j()},30)},se=()=>{w||(j(),setTimeout(()=>{M(!0),d(!0),T(!1)},30))};return _.jsxs("div",{className:ue.sheetRangeSelector,ref:y,children:[_.jsxs("div",{className:Wt(ue.sheetRangeSelectorTextWrap,{[ue.sheetRangeSelectorActive]:b&&!w,[ue.sheetRangeSelectorError]:w}),children:[_.jsx("div",{className:ue.sheetRangeSelectorText,ref:P,onMouseUp:z}),_.jsx(oe.Tooltip,{title:g.t("rangeSelector.buttonTooltip"),placement:"bottom",children:_.jsx(jt,{className:ue.sheetRangeSelectorIcon,onClick:se})}),o!==void 0?_.jsx("div",{className:ue.sheetRangeSelectorErrorWrap,children:o}):null,s!==void 0&&!A?_.jsx("div",{className:ue.sheetRangeSelectorPlaceholder,children:s}):null]}),E&&_.jsx(tr,{editorId:F,handleConfirm:G,handleClose:ne,unitId:t,subUnitId:n,initValue:B,visible:E,isOnlyOneRange:p,isSupportAcrossSheet:m})]})}function tr(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(J.IEditorService),u=c.useDependency(ge.IDescriptionService),p=c.useDependency(C.LexerTreeBuilder),R=c.useDependency(K.IRenderManagerService).getRenderById(i),g=R==null?void 0:R.with(exports.RefSelectionsRenderService),[I,v]=S.useState(()=>{if(l){const w=s[0];return w?he([w],d):[""]}return he(s,d)}),[y,E]=S.useState(()=>I.length-1),M=zt(),b=S.useMemo(()=>I.join(C.matchToken.COMMA),[I]),T=rt(),F=S.useMemo(()=>T(b),[b]),N=S.useMemo(()=>Yt(u,M,F).refSelections,[F]),L=()=>{v([]),setTimeout(()=>{n()},30)},P=(w,U)=>{U?g==null||g.setSkipLastEnabled(!1):g==null||g.setSkipLastEnabled(!0),v(H=>{const j=[...H];return j[w]=U,j})},k=w=>{g==null||g.setSkipLastEnabled(!1),v(U=>{if(U.length===1)return U;const H=[];return U.forEach((j,Z)=>{w!==Z&&H.push(j)}),H})},A=()=>{g==null||g.setSkipLastEnabled(!0),v(w=>(w.push(""),E(w.length-1),[...w]))},O=S.useCallback(w=>{var H;g==null||g.setSkipLastEnabled(!1);const U=w.split(C.matchToken.COMMA).filter(j=>!!j);v(l?[(H=U[0])!=null?H:""]:U)},[y,l]),B=St(i);return en(y>=0,i,a,F,d,l,O),gt(y>=0,i),Zt(i,l),vt(y>=0,i,d,V.noop,V.noop,()=>B(N)),S.useEffect(()=>{B(N)},[N]),S.useEffect(()=>{(I.length===0||I.length===1&&!I[0])&&(g==null||g.setSkipLastEnabled(!0))},[I]),S.useEffect(()=>{const w=h.focusStyle$.pipe(V.filter(U=>!!U&&c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY!==U)).subscribe(U=>{U!==e&&L()});return()=>{w.unsubscribe()}},[h,e]),_.jsx(oe.Dialog,{width:"328px",visible:o,title:f.t("rangeSelector.title"),draggable:!0,closeIcon:_.jsx(nt,{}),footer:_.jsxs("footer",{children:[_.jsx(oe.Button,{onClick:L,children:f.t("rangeSelector.cancel")}),_.jsx(oe.Button,{style:{marginLeft:10},onClick:()=>t(I.filter(w=>{const U=p.sequenceNodesBuilder(w);return U&&U.length===1&&typeof U[0]!="string"&&U[0].nodeType===C.sequenceNodeType.REFERENCE}).map(w=>C.deserializeRangeWithSheet(w)).map(w=>({...w,range:pt(w.range)}))),type:"primary",children:f.t("rangeSelector.confirm")})]}),onClose:L,children:_.jsxs("div",{className:ue.sheetRangeSelectorDialog,children:[I.map((w,U)=>_.jsxs("div",{className:ue.sheetRangeSelectorDialogItem,children:[_.jsx(oe.Input,{affixWrapperStyle:{width:"100%"},placeholder:f.t("rangeSelector.placeHolder"),onFocus:()=>E(U),value:w,onChange:H=>P(U,H)},`input_${U}`),I.length>1&&!l&&_.jsx(kt,{className:ue.sheetRangeSelectorDialogItemDelete,onClick:()=>k(U)})]},U)),!l&&_.jsx("div",{children:_.jsxs(oe.Button,{type:"link",size:"small",onClick:A,children:[_.jsx($t,{}),_.jsx("span",{children:f.t("rangeSelector.addAnotherRange")})]})})]})})}function nr(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 _t(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 rr=(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])},or="univer-formula-help-function",sr="univer-formula-help-function-title",ir="univer-formula-help-function-title-icons",cr="univer-formula-help-function-title-icon",ar="univer-formula-help-function-content",lr="univer-formula-help-function-content-inner",ur="univer-formula-help-function-content-params",dr="univer-formula-help-function-content-params-title",hr="univer-formula-help-function-content-params-detail",fr="univer-formula-help-function-active",mr="univer-formula-help-decorator",Sr="univer-formula-help-param",gr="univer-formula-help-param-prefix",pr="univer-formula-help-param-item",vr="univer-formula-help-param-active",ee={formulaHelpFunction:or,formulaHelpFunctionTitle:sr,formulaHelpFunctionTitleIcons:ir,formulaHelpFunctionTitleIcon:cr,formulaHelpFunctionContent:ar,formulaHelpFunctionContentInner:lr,formulaHelpFunctionContentParams:ur,formulaHelpFunctionContentParamsTitle:dr,formulaHelpFunctionContentParamsDetail:hr,formulaHelpFunctionActive:fr,formulaHelpDecorator:mr,formulaHelpParam:Sr,formulaHelpParamPrefix:gr,formulaHelpParamItem:pr,formulaHelpParamActive:vr},yt=()=>{};function _r(r){const{functionInfo:e,paramIndex:t,editorId:n,onParamsSwitch:o=yt,onClose:s=yt}=r,i=c.useDependency(J.IEditorService),a=c.useDependency(x.ISidebarService),l=S.useMemo(()=>!!e&&t>=0,[e,t]),[d,f]=S.useState(!0),[h,u]=S.useState([0,0]),p=c.useDependency(c.LocaleService),m=p.t("formula.prompt.required"),R=p.t("formula.prompt.optional");rr(g),S.useEffect(()=>{const v=a.scrollEvent$.pipe(V.throttleTime(100)).subscribe(g);return()=>{v.unsubscribe()}},[]),S.useEffect(()=>{const v=i.getEditor(n);if(!v)return;const y=v.getBoundingClientRect(),{left:E,top:M,height:b}=y;u([E,M+b])},[e,t,n]);function g(){const v=i.getEditor(n);if(!v)return;const y=v.getBoundingClientRect(),{left:E,top:M,height:b}=y;return u([E,M+b]),y}function I(v){o&&o(v)}return _.jsx(oe.Popup,{visible:l,offset:h,children:e?_.jsxs("div",{className:ee.formulaHelpFunction,children:[_.jsxs("div",{className:ee.formulaHelpFunctionTitle,children:[_.jsx(Cr,{prefix:e.functionName,value:e.functionParameter,active:t,onClick:I}),_.jsxs("div",{className:ee.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:ee.formulaHelpFunctionTitleIcon,style:{transform:d?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>f(!d),children:_.jsx(mt,{})}),_.jsx("div",{className:ee.formulaHelpFunctionTitleIcon,onClick:s,children:_.jsx(nt,{})})]})]}),_.jsx("div",{className:ee.formulaHelpFunctionContent,style:{height:d?"unset":0,padding:d?"revert-layer":0},children:_.jsxs("div",{className:ee.formulaHelpFunctionContentInner,children:[_.jsx(st,{title:p.t("formula.prompt.helpExample"),value:`${e.functionName}(${e.functionParameter.map(v=>v.example).join(",")})`}),_.jsx(st,{title:p.t("formula.prompt.helpAbstract"),value:e.description}),e&&e.functionParameter&&e.functionParameter.map((v,y)=>_.jsx(st,{className:t===y?ee.formulaHelpFunctionActive:"",title:v.name,value:`${v.require?m:R} ${v.detail}`},y))]})})]}):_.jsx(_.Fragment,{})})}const st=r=>_.jsxs("div",{className:ee.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`${ee.formulaHelpFunctionContentParamsTitle} ${r.className}`,children:r.title}),_.jsx("div",{className:ee.formulaHelpFunctionContentParamsDetail,children:r.value})]}),Cr=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return _.jsxs("div",{className:ee.formulaHelpParam,children:[_.jsxs("span",{className:ee.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>_.jsxs("span",{className:ee.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?ee.formulaHelpFunctionActive:ee.formulaHelpParamActive,onClick:()=>o(i),children:_t(s)}),i===t.length-1?"":","]},i)),")"]})},Me=r=>{const e=S.useRef();return e.current=r,e},Rr=(r,e,t)=>{const n=c.useDependency(ge.IDescriptionService),o=c.useDependency(C.LexerTreeBuilder),[s,i]=S.useState(),[a,l]=S.useState(-1),[d,f]=S.useState(!0),h=Me(d),u=S.useRef(e);u.current=e;const p=()=>{i(void 0),l(-1),f(!1)};return S.useEffect(()=>{if(t&&r){const m=t.selectionChange$.pipe(V.debounceTime(50)).subscribe(g=>{if(g.textRanges.length===1){const[I]=g.textRanges;if(I.collapsed&&h.current){const v=o.getFunctionAndParameter(u.current,I.startOffset-1);if(v){const{functionName:y,paramIndex:E}=v,M=n.getFunctionInfo(y);i(M),l(E);return}}}i(void 0),l(-1)}),R=t.selectionChange$.pipe(V.filter(g=>g.isEditing),V.filter(g=>g.textRanges.length===1),V.map(g=>g.textRanges[0].startOffset),V.distinctUntilChanged()).subscribe(()=>{f(!0)});return()=>{m.unsubscribe(),R.unsubscribe()}}},[t,r]),S.useEffect(()=>{r||p()},[r]),{functionInfo:s,paramIndex:a,reset:p}},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},Ir=(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}),f=()=>{s([]),a(""),l.current=-1};return S.useEffect(()=>{if(t&&r){const u=t.input$.pipe(V.debounceTime(300)).subscribe(()=>{const p=t.getSelectionRanges();if(p.length===1){const m=d.current.nodes,R=p[0];if(R.collapsed){const g=Ve(m,R.startOffset-1,!1);l.current=g;const I=m[g];if(I&&typeof I!="string"&&I.nodeType===C.sequenceNodeType.FUNCTION){l.current=g;const v=I.token,y=n.getSearchListByNameFirstLetter(v);s(y),a(v);return}}}l.current=-1,a(""),s(m=>m!=null&&m.length?[]:m)});return()=>{u.unsubscribe()}}},[t,r]),S.useEffect(()=>{r||f()},[r]),{searchList:o,searchText:i,handlerFormulaReplace:u=>{const p=[...d.current.nodes];if(l.current!==-1){const m=p.splice(l.current+1),R=p.pop()||"";let g=(typeof R=="string"?R.length:R.token.length)-u.length;return p.push(u),m[0]!==C.matchToken.OPEN_BRACKET&&(p.push(C.matchToken.OPEN_BRACKET),g--),{text:Se([...p,...m]),offset:g}}},reset:f}},Er=r=>r.reduce((e,t)=>typeof t=="string"?e+t.length:e+t.token.length,0),yr=(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}},Ct=[C.compareToken.EQUALS,C.compareToken.GREATER_THAN,C.compareToken.GREATER_THAN_OR_EQUAL,C.compareToken.LESS_THAN,C.compareToken.LESS_THAN_OR_EQUAL,C.compareToken.NOT_EQUAL,C.operatorToken.CONCATENATE,C.operatorToken.DIVIDED,C.operatorToken.MINUS,C.operatorToken.MULTIPLY,C.operatorToken.PLUS,C.operatorToken.POWER,C.matchToken.COMMA],Tt=[...Ct,C.matchToken.COLON,C.matchToken.OPEN_BRACKET],Tr=[...Ct,C.matchToken.CLOSE_BRACKET],it=r=>typeof r=="string"?r:r.token,br=(r,e,t)=>{const o=c.useDependency(K.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService),i=S.useRef(!1),a=Me(e),l=S.useMemo(()=>yr(!1,300),[]),d=h=>{s&&s.setSkipLastEnabled(h),i.current=h},f=()=>i.current;return S.useEffect(()=>{if(t&&s){const h=t.input$.subscribe(p=>{const m=p.content;m.length===1&&Tt.includes(m)?(d(!0),l.setValue(!0),l.reset()):(d(!1),l.setValue(!1))}),u=t.selectionChange$.pipe(V.debounceTime(100)).subscribe(p=>{if(l.getValue())return;const m=p.textRanges;if(!m.length)return;if(m.length!==1){d(!1);return}const R=m[0];if(!R.collapsed){d(!1);return}const g=a.current;if(!g.length){d(!0);return}const I=R.startOffset-1;if(I===0){const T=Ve(g,1,!1),F=g[T]||"",N=it(F);if(Ct.includes(N)){d(!0);return}}const v=Ve(g,I,!1),y=g[v];if(!y){d(!1);return}const E=g[v+1]||"",M=it(E),b=it(y);Tt.includes(b)&&(!E||Tr.includes(M))?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}},Nr=()=>{},Mr=(r,e,t,n,o,s,i=Nr)=>{const a=c.useDependency(K.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=Me(n),{getIsNeedAddSelection:f}=br(e,n,s),h=l.getUnit(e),u=E=>{var M,b;return(b=(M=h==null?void 0:h.getSheetBySheetId(E))==null?void 0:M.getName())!=null?b:""},p=S.useMemo(()=>u(t),[t]),m=c.useObservable(h==null?void 0:h.activeSheet$),R=Me({activeSheet:m,sheetName:p}),g=a.getRenderById(e),I=g==null?void 0:g.with(exports.RefSelectionsRenderService),v=S.useRef(!1),y=S.useRef();S.useEffect(()=>{if(I&&r){let E=!0;const M=T=>{var k,A,O,B,w,U;if(E||v.current){E=!1;return}const F=s==null?void 0:s.getSelectionRanges();if((F==null?void 0:F.length)!==1)return;const L=F[0].startOffset-1,P=[...d.current];if(f())if(L!==0){const H=Ve(P,L,!1);if(H===-1&&P.length)return;const j=T[T.length-1],Z=P.splice(H+1),ce=(k=j.rangeWithCoord.sheetId)!=null?k:t,ae={range:j.rangeWithCoord,unitId:(A=j.rangeWithCoord.unitId)!=null?A:e,sheetName:u(ce)},X=he([ae],o&&ce!==t);P.push({token:X[0],nodeType:C.sequenceNodeType.REFERENCE});const te=[...P,...Z],ie=Se(te);i(ie,Er(P),!0)}else{const H=T[T.length-1],j=(O=H.rangeWithCoord.sheetId)!=null?O:t,Z={range:H.rangeWithCoord,unitId:(B=H.rangeWithCoord.unitId)!=null?B:e,sheetName:u(j)},ae=he([Z],o&&j!==t);P.unshift({token:ae[0],nodeType:C.sequenceNodeType.REFERENCE});const de=Se(P);i(de,ae[0].length,!0)}else{let H=0;const j=P.map(X=>{var te,ie,pe;if(typeof X=="string")return X;if(X.nodeType===C.sequenceNodeType.REFERENCE){const z=C.deserializeRangeWithSheet(X.token);if(z.sheetName||(z.sheetName=p),o&&((te=R.current.activeSheet)==null?void 0:te.getName())!==z.sheetName)return X.token;const G=T[H];if(H++,!G)return"";const ne=(ie=G.rangeWithCoord.sheetId)!=null?ie:t,se={range:G.rangeWithCoord,unitId:(pe=G.rangeWithCoord.unitId)!=null?pe:e,sheetName:u(ne)};return he([se],o)[0]}return X.token}).join(""),Z=[];for(let X=H;X<=T.length-1;X++){const te=T[X],ie=(w=te.rangeWithCoord.sheetId)!=null?w:t,pe={range:te.rangeWithCoord,unitId:(U=te.rangeWithCoord.unitId)!=null?U:e,sheetName:u(ie)},G=he([pe],o&&ie!==t);Z.push(G[0])}const ce=P[P.length-1],ae=ce&&(typeof ce=="string"?!1:ce.nodeType===C.sequenceNodeType.REFERENCE),de=`${j}${Z.length&&ae?",":""}${Z.join(",")}`;i(de,de.length,!0)}},b=I.selectionMoveEnd$.subscribe(T=>{if(M(T),v.current=!1,y.current){const{result:F,offset:N}=y.current;i(F,N||-1,!0),y.current=void 0}});return()=>{b.unsubscribe()}}},[I,s,o,r]),S.useEffect(()=>{if(r&&I&&s){const E=new c.DisposableCollection,M=(F,N)=>{let L=0,P=0,k=!1;const{sheetName:A}=R.current,O=d.current.map(w=>{var U;if(typeof w=="string")return k||(P+=w.length),w;if(w.nodeType===C.sequenceNodeType.REFERENCE){const H=C.deserializeRangeWithSheet(w.token);if(H.unitId||(H.unitId=e),H.sheetName||(H.sheetName=A),o&&((U=R.current.activeSheet)==null?void 0:U.getName())!==H.sheetName)return k||(P+=w.token.length),w;if(L===N){k=!0;const j={...w,token:F};return o&&H.sheetName!==A?j.token=C.serializeRangeWithSheet(H.sheetName,C.deserializeRangeWithSheet(F).range):j.token=F,P+=j.token.length,L++,j}return k||(P+=w.token.length),L++,w}return k||(P+=w.token.length),w}),B=Se(O);i(B,-1,!1),y.current={result:B,offset:P}},b=()=>{E.dispose(),I.getSelectionControls().forEach((N,L)=>{E.add(V.merge(N.selectionMoving$,N.selectionScaling$).pipe(Ue.map(P=>C.serializeRange(P)),Ue.distinctUntilChanged()).subscribe(P=>{v.current=!0,M(P,L)}))})},T=V.merge(s.input$,I.selectionMoveEnd$).pipe(Ue.debounceTime(50)).subscribe(()=>{b()});return()=>{T.unsubscribe(),E.dispose()}}},[r,I,s])},xr=(r,e,t)=>{const n=c.useDependency(C.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(C.operatorToken.EQUALS),`${t}`)}},[t,e])},Fr="univer-sheet-embedding-formula-editor-active",Or="univer-sheet-embedding-formula-editor-wrap",Ar="univer-sheet-embedding-formula-editor-text",Dr="univer-sheet-embedding-formula-editor-error-wrap",Pr="univer-sheet-embedding-formula-editor-error",Ne={sheetEmbeddingFormulaEditorActive:Fr,sheetEmbeddingFormulaEditorWrap:Or,sheetEmbeddingFormulaEditorText:Ar,sheetEmbeddingFormulaEditorErrorWrap:Dr,sheetEmbeddingFormulaEditorError:Pr},Lr="univer-formula-search-function",wr="univer-formula-search-function-item",kr="univer-formula-search-function-item-name",Ur="univer-formula-search-function-item-name-light",$r="univer-formula-search-function-item-desc",jr="univer-formula-search-function-item-active",Ce={formulaSearchFunction:Lr,formulaSearchFunctionItem:wr,formulaSearchFunctionItemName:kr,formulaSearchFunctionItemNameLight:Ur,formulaSearchFunctionItemDesc:$r,formulaSearchFunctionItemActive:jr},Hr=()=>{},Wr=S.forwardRef(Br);function Br(r,e){const{searchText:t,searchList:n,onSelect:o,editorId:s,onClose:i=Hr}=r,a=c.useDependency(J.IEditorService),l=c.useDependency(x.IShortcutService),d=c.useDependency(c.ICommandService),f=S.useMemo(()=>!!n.length,[n]),h=S.useRef(),[u,p]=S.useState(0),[m,R]=S.useState([0,0]),g=S.useRef(!1),I=Me({searchList:n,active:u}),v=a.getEditor(s);S.useEffect(()=>{const T=a.getEditor(s),F=T==null?void 0:T.getBoundingClientRect();if(F==null)return;const{left:N,top:L,height:P}=F;R([N,L+P]),p(0)},[t,n]);function y(T){g.current&&p(T)}function E(){g.current&&p(-1)}S.useEffect(()=>{if(!n.length)return;const T=`sheet.formula-embedding-editor.search_function.${s}`,F=new c.DisposableCollection,N=L=>{const{searchList:P,active:k}=I.current;switch(L){case x.KeyCode.ARROW_UP:{p(A=>{const O=Math.max(0,A-1);return M(O),O});break}case x.KeyCode.ARROW_DOWN:{p(A=>{const O=Math.min(P.length-1,A+1);return M(O),O});break}case x.KeyCode.TAB:case x.KeyCode.ENTER:{const A=P[k];o(A.name);break}case x.KeyCode.ESC:{o("");break}}};return F.add(d.registerCommand({id:T,type:c.CommandType.OPERATION,handler(L,P){const{keyCode:k}=P;N(k)}})),[x.KeyCode.ARROW_UP,x.KeyCode.ARROW_DOWN,x.KeyCode.ENTER,x.KeyCode.ESC,x.KeyCode.TAB].map(L=>({id:T,binding:L,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keyCode:L}})).forEach(L=>{F.add(l.registerShortcut(L))}),()=>{F.dispose()}},[n]);function M(T){var U;const F=(U=h.current)==null?void 0:U.querySelectorAll(`.${Ce.formulaSearchFunctionItem}`)[T];if(!F)return;const N=F.parentNode;if(!N)return;const P=N.getBoundingClientRect().top,k=N.offsetHeight,A=F.getBoundingClientRect(),O=A.top,B=A.height;if(O>=0&&O>P&&O-P+B<=k)return;const w=F.offsetTop-(k-B)/2;N.scrollTo({top:w,behavior:"smooth"})}const b=S.useMemo(()=>{let T="";return()=>{clearTimeout(T),g.current=!0,T=setTimeout(()=>{g.current=!1},300)}},[]);return n.length>0&&_.jsx(oe.Popup,{visible:f,offset:m,children:_.jsx("ul",{className:Ce.formulaSearchFunction,ref:T=>{h.current=T,e&&(e.current=T)},children:n.map((T,F)=>_.jsxs("li",{className:u===F?`${Ce.formulaSearchFunctionItem} ${Ce.formulaSearchFunctionItemActive}`:Ce.formulaSearchFunctionItem,onMouseEnter:()=>y(F),onMouseLeave:E,onMouseMove:b,onClick:()=>{o(T.name),v&&v.focus()},children:[_.jsxs("span",{className:Ce.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Ce.formulaSearchFunctionItemNameLight,children:T.name.substring(0,t.length)}),_.jsx("span",{children:T.name.slice(t.length)})]}),_.jsx("span",{className:Ce.formulaSearchFunctionItemDesc,children:T.desc})]},F))})})}const bt=r=>r.startsWith(C.operatorToken.EQUALS)?r.slice(1):"",ct=()=>{};function rn(r){const{errorText:e,initValue:t,unitId:n,subUnitId:o,isFocus:s=!0,isSupportAcrossSheet:i=!1,onFocus:a=ct,onBlur:l=ct,onChange:d,onVerify:f,actions:h}=r,u=c.useDependency(J.IEditorService),p=S.useRef(null),[m,R]=S.useState(()=>t.startsWith(C.operatorToken.EQUALS)?t:"");h&&(h.handleOutClick=(z,G)=>{p.current&&!p.current.contains(z.target)&&G()});const g=S.useMemo(()=>bt(m),[m]),I=S.useRef(null),[v,y]=S.useState(),[E,M]=S.useState(s),b=S.useRef(null),T=S.useMemo(()=>c.createInternalEditorID(`${D.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),F=S.useMemo(()=>e!==void 0,[e]),N=rt(),L=S.useMemo(()=>N(g),[g]),P=Bt(L,z=>{d(`=${z}`)},v),k=Kt("="),A=St(n),O=(z,G=!0)=>{if(!v)return;const ne=N(z),se=k(v,ne,G);A(se)};xr(E,f,m);const B=qt(v),w=Qt(E);S.useLayoutEffect(()=>{if(s){const z=setTimeout(()=>{M(s),s&&B()},30);return()=>{clearTimeout(z)}}else w(),M(s)},[s,B]);const{checkScrollBar:U}=Jt(v);gt(E,n),Gt(E,v),Mr(E,n,o,L,i,v,(z,G,ne)=>{const se=`=${z}`;P(),R(se),O(z),ne&&(B(),G!==-1&&setTimeout(()=>{const q={startOffset:G+1,endOffset:G+1};v==null||v.setSelectionRanges([q]);const Y=v==null?void 0:v.render.with(J.DocBackScrollRenderController);Y==null||Y.scrollToRange({...q,collapsed:!0})},50),U())}),Xt(),vt(E,n,i,M,l,ct);const{searchList:j,searchText:Z,handlerFormulaReplace:ce,reset:ae}=Ir(E,L,v),{functionInfo:de,paramIndex:X,reset:te}=Rr(E,m,v);S.useEffect(()=>{if(v){const z=v.input$.subscribe(G=>{var se,q;const ne=((q=(se=G.data.body)==null?void 0:se.dataStream)!=null?q:"").replaceAll(/\n|\r/g,"");P(),R(ne),O(bt(ne),!1)});return()=>{z.unsubscribe()}}},[v]),Vt(g,"=",E,k,A,v),S.useLayoutEffect(()=>{let z;if(b.current){z=u.register({autofocus:!0,editorUnitId:T,isSingle:!0,initialSnapshot:{id:T,body:{dataStream:`${t}\r
14
- `},documentStyle:{}}},b.current);const G=u.getEditor(T);y(G)}return()=>{z==null||z.dispose()}},[]);const ie=z=>{const G=ce(z);if(G){R(`=${G.text}`);const ne=v==null?void 0:v.getSelectionRanges();if(ne&&ne.length===1){const se=ne[0];if(se.collapsed){const q=G.offset;setTimeout(()=>{v==null||v.setSelectionRanges([{startOffset:se.startOffset-q,endOffset:se.endOffset-q}])},30)}}ae(),B(),O(G.text)}},pe=()=>{setTimeout(()=>{M(!0),a(),B()},30)};return _.jsxs("div",{className:Ne.sheetEmbeddingFormulaEditor,children:[_.jsxs("div",{className:Wt(Ne.sheetEmbeddingFormulaEditorWrap,{[Ne.sheetEmbeddingFormulaEditorActive]:E,[Ne.sheetEmbeddingFormulaEditorError]:F}),ref:p,children:[_.jsx("div",{className:Ne.sheetEmbeddingFormulaEditorText,ref:b,onMouseUp:pe}),e!==void 0?_.jsx("div",{className:Ne.sheetEmbeddingFormulaEditorErrorWrap,children:e}):null]}),_.jsx(_r,{editorId:T,paramIndex:X,functionInfo:de,onClose:()=>{te(),B()}}),_.jsx(Wr,{searchText:Z,editorId:T,searchList:j,onSelect:ie,ref:I})]})}const Vr="sheets-formula-ui.base.config",qr={};function Kr(r){return r.getContextValue(c.FOCUSING_DOC)&&r.getContextValue(c.FOCUSING_UNIVER_EDITOR)&&r.getContextValue(c.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)}function on(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"&&C.ERROR_TYPE_SET.has(r.v)?r.v:null}var zr=Object.defineProperty,Yr=Object.getOwnPropertyDescriptor,Gr=(r,e,t,n)=>{for(var o=n>1?void 0:n?Yr(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&&zr(e,t,o),o},De=(r,e)=>(t,n)=>e(t,n,r);const ke="SHEET_FORMULA_ALERT",Zr={[C.ErrorType.DIV_BY_ZERO]:"divByZero",[C.ErrorType.NAME]:"name",[C.ErrorType.VALUE]:"value",[C.ErrorType.NUM]:"num",[C.ErrorType.NA]:"na",[C.ErrorType.CYCLE]:"cycle",[C.ErrorType.REF]:"ref",[C.ErrorType.SPILL]:"spill",[C.ErrorType.CALC]:"calc",[C.ErrorType.ERROR]:"error",[C.ErrorType.CONNECT]:"connect",[C.ErrorType.NULL]:"null"};let ft=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$.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=on(l,!!d);if(!f)return;const h=this._cellAlertManagerService.currentAlert.get(ke),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:D.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:ke});return}}this._cellAlertManagerService.removeAlert(ke)}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(r=>{r&&this._cellAlertManagerService.removeAlert(ke)}))}};ft=Gr([De(1,c.Inject(D.HoverManagerService)),De(2,c.Inject(D.CellAlertManagerService)),De(3,c.Inject(c.LocaleService)),De(4,c.Inject(C.FormulaDataModel)),De(5,x.IZenZoneService)],ft);var Xr=Object.defineProperty,Qr=Object.getOwnPropertyDescriptor,Jr=(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&&Xr(e,t,o),o},Nt=(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:D.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===D.DATA_TYPE.FORMULA,applyFunctions:{[D.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=to(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 p=((l=r[h])==null?void 0:l.f)||"",m=((d=r[h])==null?void 0:d.si)||"",R=c.isFormulaString(p);if(c.isFormulaId(m))u.si=m,u.f=null,u.v=null,u.p=null,u.t=null,t===c.Direction.DOWN||t===c.Direction.RIGHT?i.push(u):i.unshift(u);else if(R){let I=a.get(h);if(I)u.si=I,u.f=null,u.v=null,u.p=null,u.t=null;else{I=c.Tools.generateRandomId(6),a.set(h,I);const{offsetX:v,offsetY:y}=eo(s,t),E=this._lexerTreeBuilder.moveFormulaRefOffset(p,v,y);u.si=I,u.f=E,u.v=null,u.p=null,u.t=null}t===c.Direction.DOWN||t===c.Direction.RIGHT?i.push(u):i.unshift(u)}}}return i}};qe=Jr([Nt(0,D.IAutoFillService),Nt(1,c.Inject(C.LexerTreeBuilder))],qe);function eo(r,e){let t=0,n=0;switch(e){case c.Direction.UP:n=-r;break;case c.Direction.RIGHT:t=r;break;case c.Direction.DOWN:n=r;break;case c.Direction.LEFT:t=-r;break}return{offsetX:t,offsetY:n}}function to(r){let e=0;for(const t in r)r[t].forEach(n=>{e+=n.data.length});return e}var no=Object.defineProperty,ro=Object.getOwnPropertyDescriptor,oo=(r,e,t,n)=>{for(var o=n>1?void 0:n?ro(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&&no(e,t,o),o},Pe=(r,e)=>(t,n)=>e(t,n,r);const so="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:D.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:so,priority:10,onPasteCells:(r,e,t,n)=>this._onPasteCells(r,e,t,n,!1)}}_onPasteCells(r,e,t,n,o){var h;if([D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,D.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||D.COPY_TYPE.COPY,copyRange:r==null?void 0:r.range,pasteType:n.pasteType};return this._injector.invoke(u=>io(i,a,l,d,u,f,this._lexerTreeBuilder,this._formulaDataModel,o,r))}};Ke=oo([Pe(0,c.IUniverInstanceService),Pe(1,c.Inject(C.LexerTreeBuilder)),Pe(2,D.ISheetClipboardService),Pe(3,c.Inject(c.Injector)),Pe(4,c.Inject(C.FormulaDataModel))],Ke);function io(r,e,t,n,o,s,i,a,l=!1,d){const f=[],h=[],u=co(r,e,t,n,s,i,a,d),p={unitId:r,subUnitId:e,cellValue:u.getData()};f.push({id:$.SetRangeValuesMutation.id,params:p});const m=$.SetRangeValuesUndoMutationFactory(o,p);return h.push({id:$.SetRangeValuesMutation.id,params:m}),{undos:h,redos:f}}function co(r,e,t,n,o,s,i,a){return a?o.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?lo(r,e,t,n,i,a):o.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMULA?uo(r,e,t,n,s,i,a):ho(r,e,t,n,s,i,a):ao(r,e,t,n,i)}function ao(r,e,t,n,o){var a,l;const s=new c.ObjectMatrix,i=(l=(a=o.getFormulaData())==null?void 0:a[r])==null?void 0:l[e];return n.forValue((d,f,h)=>{var R;const u=t.rows[d],p=t.cols[f],m={};c.isFormulaString(h.v)?(m.v=null,m.f=`${h.v}`,m.si=null,m.p=null,s.setValue(u,p,m)):(R=i==null?void 0:i[u])!=null&&R[p]&&(m.v=h.v,m.f=null,m.si=null,m.p=null,s.setValue(u,p,m))}),s}function lo(r,e,t,n,o,s){var d,f,h,u;const i=new c.ObjectMatrix,a=(f=(d=o.getArrayFormulaCellData())==null?void 0:d[s.unitId])==null?void 0:f[s.subUnitId],l=(u=(h=o.getFormulaData())==null?void 0:h[r])==null?void 0:u[e];return n.forValue((p,m,R)=>{var M,b;const g=s.range.rows[p%s.range.rows.length],I=s.range.cols[m%s.range.cols.length],v=t.rows[p],y=t.cols[m],E={};if(c.isFormulaString(R.f)||c.isFormulaId(R.si))E.v=R.v,E.f=null,E.si=null,E.p=null,i.setValue(v,y,E);else if((M=a==null?void 0:a[g])!=null&&M[I]){const T=a[g][I];E.v=T.v,E.f=null,E.si=null,E.p=null,i.setValue(v,y,E)}else if((b=l==null?void 0:l[v])!=null&&b[y]){if(E.v=R.v,E.f=null,E.si=null,E.p=null,R.p){const T=sn(R);T&&(E.v=T)}i.setValue(v,y,E)}}),i}function uo(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],p=t.cols[f],m={};if(c.isFormulaId(h.si)){if(i.unitId!==r||i.subUnitId!==e){const R=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],I=t.rows[d]-i.range.rows[d%i.range.rows.length],v=o.moveFormulaRefOffset(R||"",g,I);m.si=null,m.f=v}else m.si=h.si,m.f=null;m.v=null,m.p=null,a.setValue(u,p,m)}else if(c.isFormulaString(h.f)){const R=`${d%i.range.rows.length}_${f%i.range.cols.length}`;let g=l.get(R);if(g)m.si=g,m.f=null;else{g=c.Tools.generateRandomId(6),l.set(R,g);const I=t.cols[f]-i.range.cols[f%i.range.cols.length],v=t.rows[d]-i.range.rows[d%i.range.rows.length],y=o.moveFormulaRefOffset(h.f||"",I,v);m.si=g,m.f=y}m.v=null,m.p=null,a.setValue(u,p,m)}else{if(m.v=h.v,m.f=null,m.si=null,m.p=null,h.p){const R=sn(h);R&&(m.v=R)}a.setValue(u,p,m)}}),a}function ho(r,e,t,n,o,s,i){var f,h;const a=new c.ObjectMatrix,l=new Map,d=(h=(f=s.getFormulaData())==null?void 0:f[r])==null?void 0:h[e];return n.forValue((u,p,m)=>{var v;const R=t.rows[u],g=t.cols[p],I={};if(c.isFormulaId(m.si)){if(i.unitId!==r||i.subUnitId!==e){const y=s.getFormulaStringByCell(i.range.rows[u%i.range.rows.length],i.range.cols[p%i.range.cols.length],i.subUnitId,i.unitId),E=t.cols[p]-i.range.cols[p%i.range.cols.length],M=t.rows[u]-i.range.rows[u%i.range.rows.length],b=o.moveFormulaRefOffset(y||"",E,M);I.si=null,I.f=b}else I.si=m.si,I.f=null;I.v=null,I.p=null,a.setValue(R,g,I)}else if(c.isFormulaString(m.f)){const y=`${u%i.range.rows.length}_${p%i.range.cols.length}`;let E=l.get(y);if(E)I.si=E,I.f=null;else{E=c.Tools.generateRandomId(6),l.set(y,E);const M=t.cols[p]-i.range.cols[p%i.range.cols.length],b=t.rows[u]-i.range.rows[u%i.range.rows.length],T=o.moveFormulaRefOffset(m.f||"",M,b);I.si=E,I.f=T}I.v=null,I.p=null,a.setValue(R,g,I)}else(v=d==null?void 0:d[R])!=null&&v[g]&&(I.v=m.v,I.f=null,I.si=null,I.p=m.p,a.setValue(R,g,I))}),a}function sn(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 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},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();W(this,"_previousShape");W(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 m,R,g,I;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=(R=(m=f[i])==null?void 0:m[a])==null?void 0:R[o])==null?void 0:g[s])==null)return h?{...e,...h}:n(e);const p=(I=d==null?void 0:d[i])==null?void 0:I[a];return p!=null&&(h=this._displayArrayFormulaRangeShape(p,o,s,i,a,l,h)),h?{...e,...h}:n(e)}})))}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{(e.id===C.SetFormulaCalculationResultMutation.id||e.id===C.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){return new c.ObjectMatrix(e).forValue((l,d,f)=>{if(f==null)return!0;const{startRow:h,startColumn:u,endRow:p,endColumn:m}=f;if(l===t&&d===n)return this._createArrayFormulaRangeShape(f,o),!1;if(t>=h&&t<=p&&n>=u&&n<=m){const R=i.getCell(h,u);if((R==null?void 0:R.v)===C.ErrorType.SPILL)return;const g=this._formulaDataModel.getFormulaDataItem(l,d,s,o);return g==null||g.f==null?!0:(a==null&&(a={f:g.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=D.attachSelectionWithCoord(a,o),{rowHeaderWidth:d,columnHeaderHeight:f}=o,h=new D.SelectionControl(s,D.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=So([ye(1,c.Inject($.SheetInterceptorService)),ye(2,c.Inject(C.FormulaDataModel)),ye(3,c.Inject(c.ThemeService)),ye(4,K.IRenderManagerService),ye(5,c.Inject(D.SheetSkeletonManagerService)),ye(6,c.ICommandService),ye(7,c.ILogService)],ze);var go=Object.defineProperty,po=Object.getOwnPropertyDescriptor,vo=(r,e,t,n)=>{for(var o=n>1?void 0:n?po(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&&go(e,t,o),o},Mt=(r,e)=>(t,n)=>e(t,n,r);const _o={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 on(t,!!s)?o({...t,markers:{...t==null?void 0:t.markers,..._o}}):o(t)},priority:10}))}};Ye=vo([Mt(0,c.Inject($.SheetInterceptorService)),Mt(1,c.Inject(C.FormulaDataModel))],Ye);function Co(){const r=c.useDependency(ge.TriggerCalculationController),e=c.useDependency(c.ICommandService),t=c.useObservable(r.progress$),n=S.useCallback(()=>{e.executeCommand(C.SetFormulaCalculationStopMutation.id)},[e]),o=S.useCallback(()=>{r.clearProgress()},[r]);return _.jsx(x.ProgressBar,{progress:t,onTerminate:n,onClearProgress:o})}const Ro=(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])},Io="univer-formula-help-function",Eo="univer-formula-help-function-title",yo="univer-formula-help-function-title-icons",To="univer-formula-help-function-title-icon",bo="univer-formula-help-function-content",No="univer-formula-help-function-content-inner",Mo="univer-formula-help-function-content-params",xo="univer-formula-help-function-content-params-title",Fo="univer-formula-help-function-content-params-detail",Oo="univer-formula-help-function-active",Ao="univer-formula-help-decorator",Do="univer-formula-help-param",Po="univer-formula-help-param-prefix",Lo="univer-formula-help-param-item",wo="univer-formula-help-param-active",Q={formulaHelpFunction:Io,formulaHelpFunctionTitle:Eo,formulaHelpFunctionTitleIcons:yo,formulaHelpFunctionTitleIcon:To,formulaHelpFunctionContent:bo,formulaHelpFunctionContentInner:No,formulaHelpFunctionContentParams:Mo,formulaHelpFunctionContentParamsTitle:xo,formulaHelpFunctionContentParamsDetail:Fo,formulaHelpFunctionActive:Oo,formulaHelpDecorator:Ao,formulaHelpParam:Do,formulaHelpParamPrefix:Po,formulaHelpParamItem:Lo,formulaHelpParamActive:wo};function ko(){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]),[f,h]=S.useState({left:0,top:0}),[u,p]=S.useState(null),m=c.useDependency(xe),R=c.useDependency(c.LocaleService),g=R.t("formula.prompt.required"),I=R.t("formula.prompt.optional"),v=c.useDependency(c.IUniverInstanceService),y=c.useDependency(J.IEditorService),E=c.useDependency(x.ISidebarService),M=c.useInjector();Ro(b),S.useEffect(()=>{const L=m.help$.subscribe(k=>{const{visible:A,paramIndex:O,functionInfo:B}=k;if(!A){e(A);return}const w=T();if(w==null)return;const{left:U,top:H,height:j}=w;B.description===""&&B.functionParameter.length===0||(d([U,H+j]),a(O),p(B),h({left:U,top:H}),e(A))}),P=E.scrollEvent$.pipe(V.throttleTime(100)).subscribe(b);return()=>{L==null||L.unsubscribe(),P.unsubscribe()}},[]);function b(){if(!o)return;const L=T();if(L==null)return;const{left:P,top:k,height:A}=L;d([P,k+A])}function T(){const L=v.getCurrentUniverDocInstance();if(!L)return;const P=L.getUnitId();if(!y.isEditor(P))return;const k=y.getEditor(P);return k==null?void 0:k.getBoundingClientRect()}function F(L){a(L)}function N(){s(!o),M.get(x.ILayoutService).focus()}return _.jsx(_.Fragment,{children:o?_.jsx(oe.Popup,{visible:r,offset:l,children:u?_.jsxs("div",{className:Q.formulaHelpFunction,children:[_.jsxs("div",{className:Q.formulaHelpFunctionTitle,children:[_.jsx(Uo,{prefix:u.functionName,value:u.functionParameter,active:i,onClick:F}),_.jsxs("div",{className:Q.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:Q.formulaHelpFunctionTitleIcon,style:{transform:t?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>n(!t),children:_.jsx(mt,{})}),_.jsx("div",{className:Q.formulaHelpFunctionTitleIcon,onClick:N,children:_.jsx(nt,{})})]})]}),_.jsx("div",{className:Q.formulaHelpFunctionContent,style:{height:t?"unset":0,padding:t?"revert-layer":0},children:_.jsxs("div",{className:Q.formulaHelpFunctionContentInner,children:[_.jsx(at,{title:R.t("formula.prompt.helpExample"),value:`${u.functionName}(${u.functionParameter.map(L=>L.example).join(",")})`}),_.jsx(at,{title:R.t("formula.prompt.helpAbstract"),value:u.description}),u&&u.functionParameter&&u.functionParameter.map((L,P)=>_.jsx(at,{className:i===P?Q.formulaHelpFunctionActive:"",title:L.name,value:`${L.require?g:I} ${L.detail}`},P))]})})]}):_.jsx(_.Fragment,{})}):r?_.jsx("div",{className:Q.formulaHelpDecorator,onClick:()=>s(!o),style:{left:f.left-24,top:f.top},children:_.jsx(Ut,{})}):_.jsx(_.Fragment,{})})}const at=r=>_.jsxs("div",{className:Q.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`${Q.formulaHelpFunctionContentParamsTitle} ${r.className}`,children:r.title}),_.jsx("div",{className:Q.formulaHelpFunctionContentParamsDetail,children:r.value})]}),Uo=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return _.jsxs("div",{className:Q.formulaHelpParam,children:[_.jsxs("span",{className:Q.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>_.jsxs("span",{className:Q.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?Q.formulaHelpFunctionActive:Q.formulaHelpParamActive,onClick:()=>o(i),children:_t(s)}),i===t.length-1?"":","]},i)),")"]})},$o="univer-formula-search-function",jo="univer-formula-search-function-item",Ho="univer-formula-search-function-item-name",Wo="univer-formula-search-function-item-name-light",Bo="univer-formula-search-function-item-desc",Vo="univer-formula-search-function-item-active",Re={formulaSearchFunction:$o,formulaSearchFunctionItem:jo,formulaSearchFunctionItemName:Ho,formulaSearchFunctionItemNameLight:Wo,formulaSearchFunctionItemDesc:Bo,formulaSearchFunctionItemActive:Vo};function qo(){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(""),f=S.useRef(null),h=c.useDependency(xe),u=c.useDependency(c.IUniverInstanceService),p=c.useDependency(J.IEditorService);S.useEffect(()=>{let v=[],y=0;const E=h.search$.subscribe(T=>{const{visible:F,searchText:N,searchList:L}=T;if(!F){e(F);return}const P=m();if(P==null)return;const{left:k,top:A,height:O}=P;d(N),a(L),v=L,s([k,A+O]),e(F),n(0),y=0}),M=h.navigate$.subscribe(T=>{const{direction:F}=T;if(F===c.Direction.UP){let N=y-1;N=N<0?v.length-1:N,n(N),y=N}else if(F===c.Direction.DOWN){let N=y+1;N=N>=v.length?0:N,n(N),y=N}I(y)}),b=h.accept$.subscribe(T=>{const F=v[y].name;h.acceptFormulaName(F)});return()=>{E==null||E.unsubscribe(),M==null||M.unsubscribe(),b==null||b.unsubscribe()}},[]);function m(){const y=u.getCurrentUniverDocInstance().getUnitId();if(!p.isEditor(y))return;const E=p.getEditor(y);return E==null?void 0:E.getBoundingClientRect()}function R(v){n(v)}function g(){n(-1)}function I(v){var k;const y=(k=f.current)==null?void 0:k.querySelectorAll(`.${Re.formulaSearchFunctionItem}`)[v];if(!y)return;const E=y.parentNode;if(!E)return;const b=E.getBoundingClientRect().top,T=E.offsetHeight,F=y.getBoundingClientRect(),N=F.top,L=F.height;if(N>=0&&N>b&&N-b+L<=T)return;const P=y.offsetTop-(T-L)/2;E.scrollTo({top:P,behavior:"smooth"})}return i.length>0&&_.jsx(oe.Popup,{visible:r,offset:o,children:_.jsx("ul",{className:Re.formulaSearchFunction,ref:f,children:i.map((v,y)=>_.jsxs("li",{className:t===y?`${Re.formulaSearchFunctionItem} ${Re.formulaSearchFunctionItemActive}`:Re.formulaSearchFunctionItem,onMouseEnter:()=>R(y),onMouseLeave:g,onClick:()=>h.acceptFormulaName(v.name),children:[_.jsxs("span",{className:Re.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Re.formulaSearchFunctionItemNameLight,children:v.name.substring(0,l.length)}),_.jsx("span",{children:v.name.slice(l.length)})]}),_.jsx("span",{className:Re.formulaSearchFunctionItemDesc,children:v.desc})]},y))})})}function Ko(){return _.jsxs(_.Fragment,{children:[_.jsx(qo,{}),_.jsx(ko,{})]})}const zo="univer-formula-more-functions",Yo="univer-formula-more-functions-operation",xt={formulaMoreFunctions:zo,formulaMoreFunctionsOperation:Yo};function cn(r){const{prefix:e,value:t}=r;return _.jsxs("div",{children:[_.jsxs("span",{children:[e,"("]}),t&&t.map((n,o)=>_.jsxs("span",{children:[_.jsx("span",{children:_t(n)}),o===t.length-1?"":","]},o)),")"]})}const Go="univer-formula-function-params",Zo="univer-formula-function-params-title",Xo="univer-formula-function-params-detail",lt={formulaFunctionParams:Go,formulaFunctionParamsTitle:Zo,formulaFunctionParamsDetail:Xo};function we(r){const{className:e,value:t,title:n}=r;return _.jsxs("div",{className:lt.formulaFunctionParams,children:[_.jsx("div",{className:`${lt.formulaFunctionParamsTitle} ${e}`,children:n}),_.jsx("div",{className:lt.formulaFunctionParamsDetail,children:t})]})}const Qo="univer-formula-input-params-list",Jo="univer-formula-input-params-list-item-name",es="univer-formula-input-params-list-item-selector",Le={formulaInputParamsList:Qo,formulaInputParamsListItemName:Jo,formulaInputParamsListItemSelector:es};function ts(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 _.jsxs("div",{className:Le.formulaInputParams,children:[_.jsx("div",{className:Le.formulaInputParamsList,children:n.map((a,l)=>_.jsxs("div",{children:[_.jsx("div",{className:Le.formulaInputParamsListItemName,children:a.name}),_.jsx("div",{className:Le.formulaInputParamsListItemSelector})]},l))}),_.jsx("div",{className:Le.formulaInputParamsInfo,children:_.jsx(we,{title:s===-1?_.jsx(cn,{prefix:e.functionName,value:n}):n[s].name,value:s===-1?e.description:n[s].detail})})]})}const ns="univer-formula-select-function-select",rs="univer-formula-select-function-result",os="univer-formula-select-function-result-item",ss="univer-formula-select-function-result-item-name-light",is="univer-formula-select-function-result-item-selected",cs="univer-formula-select-function-result-item-active",as="univer-formula-select-function-content",me={formulaSelectFunctionSelect:ns,formulaSelectFunctionResult:rs,formulaSelectFunctionResultItem:os,formulaSelectFunctionResultItemNameLight:ss,formulaSelectFunctionResultItemSelected:is,formulaSelectFunctionResultItemActive:cs,formulaSelectFunctionContent:as};function ls(r){const{onChange:e}=r,t="-1",[n,o]=S.useState(""),[s,i]=S.useState([]),[a,l]=S.useState(0),[d,f]=S.useState(t),[h,u]=S.useState(0),[p,m]=S.useState(null),R=c.useDependency(ge.IDescriptionService),g=c.useDependency(c.LocaleService),I=c.useDependency(x.ISidebarService),v=c.useObservable(I.sidebarOptions$),y=nr(C.FunctionType,g);y.unshift({label:g.t("formula.moreFunctions.allFunctions"),value:t});const E=g.t("formula.prompt.required"),M=g.t("formula.prompt.optional");S.useEffect(()=>{F(t)},[]),S.useEffect(()=>{T(0)},[s]),S.useEffect(()=>{v!=null&&v.visible&&(o(""),i([]),l(0),f(t),u(0),m(null),F(t))},[v]);const b=A=>{if(n.trim()==="")return A;const O=new RegExp(`(${n.toLocaleUpperCase()})`);return A.split(O).filter(Boolean).map((w,U)=>w.match(O)?_.jsx("span",{className:me.formulaSelectFunctionResultItemNameLight,children:w},U):w)},T=A=>{if(s.length===0){m(null);return}u(A);const O=R.getFunctionInfo(s[A].name);if(!O){m(null);return}m(O),e(O)};function F(A){f(A);const O=R.getSearchListByType(+A);i(O)}function N(A){o(A);const O=R.getSearchListByName(A);i(O)}function L(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 P=A=>{l(A)},k=()=>{l(-1)};return _.jsxs("div",{children:[_.jsxs("div",{className:me.formulaSelectFunctionSelect,children:[_.jsx(oe.Select,{value:d,options:y,onChange:F}),_.jsx(oe.Input,{placeholder:g.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:L,value:n,onChange:N,size:"large",allowClear:!0})]}),_.jsx("ul",{className:me.formulaSelectFunctionResult,onKeyDown:L,tabIndex:-1,children:s.map(({name:A},O)=>_.jsxs("li",{className:a===O?`${me.formulaSelectFunctionResultItem} ${me.formulaSelectFunctionResultItemActive}`:me.formulaSelectFunctionResultItem,onMouseEnter:()=>P(O),onMouseLeave:k,onClick:()=>T(O),children:[h===O&&_.jsx(wt,{className:me.formulaSelectFunctionResultItemSelected}),_.jsx("span",{className:me.formulaSelectFunctionResultItemName,children:b(A)})]},O))}),p&&_.jsxs("div",{className:me.formulaSelectFunctionContent,children:[_.jsx(we,{title:p.functionName,value:p.description}),_.jsx(we,{title:g.t("formula.moreFunctions.syntax"),value:_.jsx(cn,{prefix:p.functionName,value:p.functionParameter})}),_.jsx(we,{title:g.t("formula.prompt.helpExample"),value:`${p.functionName}(${p.functionParameter.map(A=>A.example).join(",")})`}),p.functionParameter&&p.functionParameter.map((A,O)=>_.jsx(we,{title:A.name,value:`${A.require?E:M} ${A.detail}`},O))]})]})}function us(){const r=D.useActiveWorkbook(),[e,t]=S.useState(!0),[n,o]=S.useState(!1),[s,i]=S.useState(null),a=c.useDependency(c.LocaleService),l=c.useDependency(J.IEditorService);function d(){t(!e),o(!n)}function f(){l.setFormula(`=${s==null?void 0:s.functionName}(`)}return _.jsxs("div",{className:xt.formulaMoreFunctions,children:[e&&_.jsx(ls,{onChange:i}),n&&_.jsx(ts,{functionInfo:s,onChange:()=>{}}),_.jsxs("div",{className:xt.formulaMoreFunctionsOperation,children:[n&&_.jsx(oe.Button,{type:"primary",size:"small",onClick:d,children:a.t("formula.moreFunctions.next")}),n&&_.jsx(oe.Button,{size:"small",onClick:d,children:a.t("formula.moreFunctions.prev")}),e&&!!r&&_.jsx(oe.Button,{type:"primary",size:"small",onClick:f,children:a.t("formula.moreFunctions.confirm")})]})]})}function ds(r){return{id:Qe.id,icon:"FunctionSingle",tooltip:"formula.insert.tooltip",type:x.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$:x.getMenuHiddenObservable(r,c.UniverInstanceType.UNIVER_SHEET),disabled$:D.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],worksheetTypes:[$.WorksheetEditPermission,$.WorksheetSetCellValuePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint]})}}function hs(r){return{id:Je.id,title:"formula.insert.more",type:x.MenuItemType.BUTTON}}function fs(r){return r.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(V.switchMap(n=>n&&r.get(x.IClipboardInterfaceService)?new V.Observable(s=>s.next(!r.get(x.IClipboardInterfaceService).supportClipboard)):V.of(!0)))}function ms(r){return{id:Xe.id,type:x.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:fs(r).pipe(V.combineLatestWith(D.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint],worksheetTypes:[$.WorksheetSetCellValuePermission,$.WorksheetEditPermission]})),V.map(([e,t])=>e||t))}}const Ss={[x.RibbonStartGroup.FORMULAS_INSERT]:{[Qe.id]:{order:1,menuItemFactory:ds,[Je.id]:{order:1,menuItemFactory:hs}}},[D.PASTE_SPECIAL_MENU_ID]:{[Xe.id]:{order:4,menuItemFactory:ms}}},an="meta_key_ctrl_And_Shift",ot=[x.KeyCode.ARROW_DOWN,x.KeyCode.ARROW_UP,x.KeyCode.ARROW_LEFT,x.KeyCode.ARROW_RIGHT],gs=[...ot,x.KeyCode.ENTER,x.KeyCode.TAB,x.KeyCode.ESC];function ps(){const r=[];for(const e of gs)r.push({id:Ie.id,binding:e,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e}});return r}function vs(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|x.MetaKeys.SHIFT,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,metaKey:x.MetaKeys.SHIFT}});return r}function _s(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|x.MetaKeys.CTRL_COMMAND,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,metaKey:x.MetaKeys.CTRL_COMMAND}});return r}function Cs(){const r=[];for(const e of ot)r.push({id:Ie.id,binding:e|x.MetaKeys.SHIFT|x.MetaKeys.CTRL_COMMAND,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,metaKey:an}});return r}const Rs={id:et.id,binding:x.KeyCode.F4,preconditions:r=>D.whenFormulaEditorActivated(r)};function Is(){const r=[];for(const e of[x.KeyCode.ENTER,x.KeyCode.TAB,x.KeyCode.ARROW_DOWN,x.KeyCode.ARROW_UP])r.push({id:Ie.id,binding:e,preconditions:t=>Kr(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,isSingleEditor:!0}});return r}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},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(Ss)}_registerCommands(){[Xe,Qe,Je,Be,He,Ie,et].forEach(r=>this.disposeWithMe(this._commandService.registerCommand(r)))}_registerShortcuts(){[...ps(),...vs(),..._s(),...Cs(),...Is(),Rs].forEach(r=>{this.disposeWithMe(this._shortcutService.registerShortcut(r))})}_registerComponents(){this.disposeWithMe(this._uiPartsService.registerComponent(x.BuiltInUIPart.CONTENT,()=>c.connectInjector(Ko,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent(D.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(Co,this._injector))),this._componentManager.register(At,us)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[ze]))}};Ge=Ts([Te(0,c.Inject(c.Injector)),Te(1,x.IMenuManagerService),Te(2,c.ICommandService),Te(3,x.IShortcutService),Te(4,x.IUIPartsService),Te(5,K.IRenderManagerService),Te(6,c.Inject(x.ComponentManager))],Ge);var bs=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,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&&bs(e,t,o),o},re=(r,e)=>(t,n)=>e(t,n,r);const xs=[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,p,m,R){super();W(this,"_listenInputCache",new Set);W(this,"_formulaRefColors",[]);W(this,"_previousSequenceNodes");W(this,"_previousRangesCount",0);W(this,"_previousInsertRefStringIndex");W(this,"_currentInsertRefStringIndex",-1);W(this,"_arrowMoveActionState",0);W(this,"_isSelectionMovingRefSelections",[]);W(this,"_stringColor","");W(this,"_numberColor","");W(this,"_insertSelections",[]);W(this,"_inputPanelState",0);W(this,"_userCursorMove",!1);W(this,"_previousEditorUnitId");W(this,"_existsSequenceNode",!1);W(this,"_currentlyWorkingRefRenderer",null);W(this,"_selectionsChangeDisposables");W(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=p,this._editorService=m,this._layoutService=R,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(V.filter(e=>!D.isRangeSelector(e.unitId)&&!D.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=[x.KeyCode.ARROW_DOWN,x.KeyCode.ARROW_UP,x.KeyCode.ARROW_LEFT,x.KeyCode.ARROW_RIGHT,x.KeyCode.CTRL,x.KeyCode.SHIFT];this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(V.filter(t=>{const n=(t==null?void 0:t.getUnitId())||"";return!D.isRangeSelector(n)&&!D.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(J.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!==x.KeyCode.F4&&(this._userCursorMove=!1))})),this._listenInputCache.add(n)})}_closeRangePromptWhenEditorInvisible(){this.disposeWithMe(this._editorBridgeService.afterVisible$.pipe(V.distinctUntilKeyChanged("visible")).subscribe(e=>{e.visible||this._closeRangePrompt()})),this.disposeWithMe(this._contextService.subscribeContextValue$(c.FORMULA_EDITOR_ACTIVATED).pipe(V.distinctUntilChanged()).subscribe(e=>{e||this._closeRangePrompt()}))}_initialChangeEditor(){this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(V.filter(e=>{const t=(e==null?void 0:e.getUnitId())||"";return!D.isRangeSelector(t)&&!D.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())||"";D.isRangeSelector(t)||D.isEmbeddingFormulaEditor(t)||t===c.DOCS_ZEN_EDITOR_UNIT_ID_KEY||(this._insertSelections=[],this._refSelectionsService.clear(),e&&this._editorService.isSheetEditor(e)&&this._updateEditorModel(`\r
15
- `,[]),this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue($.DISABLE_NORMAL_SELECTIONS,!1),this._contextService.setContextValue(x.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._quitSelectingMode(),this._resetTemp(),this._hideFunctionPanel())}_initSelectionsEndListener(){const e=new c.DisposableCollection;this.disposeWithMe(this._refSelectionsService.selectionMoveEnd$.subscribe(t=>{var s;if(e.dispose(),t.length===0)return;const n=((s=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:s.getUnitId())||"";if(D.isRangeSelector(n)||D.isEmbeddingFormulaEditor(n))return;this._allSelectionRenderServices.map(i=>i.getSelectionControls()).flat().forEach(i=>{i.disableHelperSelection(),e.add(V.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(D.isRangeSelector(l)||D.isEmbeddingFormulaEditor(l)){e.dispose(),this._formulaPromptService.disableLockedSelectionChange();return}this._onSelectionControlChange(a,i)})),e.add(V.merge(i.selectionMoved$,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,!C.matchRefDrawToken(o)&&this._focusIsOnlyRange(e.length)&&(this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex,C.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,C.matchToken.OPEN_BRACKET);for(let m=s+2,R=o.length;m<R;m++){const g=o[m];if(typeof g=="string")continue;const I={...g};I.startIndex+=h,I.endIndex+=h,o[m]=I}let p=l.endIndex+1;u&&(p+=1),this._syncToEditor(o,p,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===C.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&&C.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:C.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]:xs}_contextSwitch(){const e=this._getCurrentBodyDataStreamAndOffset();if(e&&c.isFormulaString(e.dataStream)){this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!0),this._contextService.setContextValue($.DISABLE_NORMAL_SELECTIONS,!0),this._contextService.setContextValue(x.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($.DISABLE_NORMAL_SELECTIONS,!1),this._contextService.setContextValue(x.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(this._refSelectionsService.clear(),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:p,token:m}=f;let R="";if(p===C.sequenceNodeType.REFERENCE){if(o.has(m))R=o.get(m);else{const g=s%this._formulaRefColors.length;R=this._formulaRefColors[g],o.set(m,R),s++}n.push({refIndex:l,themeColor:R,token:m})}else p===C.sequenceNodeType.NUMBER?R=this._numberColor:p===C.sequenceNodeType.STRING?R=this._stringColor:p===C.sequenceNodeType.ARRAY&&(R=this._stringColor);R&&R.length>0&&t.push({st:h+1-i,ed:u+2-i,ts:{cl:{rgb:R}}})}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,p=t.length;u<p;u++){const m=t[u],{themeColor:R,token:g,refIndex:I}=m,v=C.deserializeRangeWithSheet(g),{unitId:y,sheetName:E,range:M}=v,b=$.setEndForRange(M,d.getRowCount(),d.getColumnCount());if(y!=null&&y.length>0&&n!==y)continue;const T=this._getSheetIdByName(n,E.trim());if(!a&&T!==i||a&&E.length!==0&&T!==o||this._exceedCurrentRange(b,d.getRowCount(),d.getColumnCount()))continue;const F=this._getPrimary(b,R,I);if(F){f=F;continue}const N=$.getPrimaryForRange(b,d);!c.Rectangle.equals(N,b)&&b.startRow===b.endRow&&b.startColumn===b.endColumn&&(b.startRow=N.startRow,b.endRow=N.endRow,b.startColumn=N.startColumn,b.endColumn=N.endColumn),h.push({range:b,primary:N,style:$e(this._themeService,R,I.toString())})}f&&h.push(f),h.length&&this._refSelectionsService.addSelections(n,o,h)}_getPrimary(e,t,n){var h;const o=(h=this._insertSelections.find(u=>{const{startRow:p,startColumn:m,endRow:R,endColumn:g}=u.range;return p===e.startRow&&m===e.startColumn&&R===e.endRow&&g===e.endColumn||p===e.startRow&&m===e.startColumn&&e.startRow===e.endRow&&e.startColumn===e.endColumn}))==null?void 0:h.primary;if(o==null)return;const{isMerged:s,isMergedMainCell:i,startRow:a,endRow:l,startColumn:d,endColumn:f}=o;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,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(C.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(D.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:p}=l;const{startAbsoluteRefType:m,endAbsoluteRefType:R,rangeType:g}=l;if(d){const{isMerged:I,isMergedMainCell:v,startRow:y,endRow:E,startColumn:M,endColumn:b}=d;(I||v)&&y===f&&M===u&&E===h&&b===p&&(f=y,u=M,h=y,p=M)}return C.serializeRangeToRefString({sheetName:n,unitId:t,range:{startRow:f,endRow:h,startColumn:u,endColumn:p,rangeType:g,startAbsoluteRefType:m,endAbsoluteRefType:R}})}_syncToEditor(e,t,n,o=!0,s=!0){let i=C.generateStringWithSequence(e);const{textRuns:a,refSelections:l}=this._buildTextRuns(e);this._isSelectionMovingRefSelections=l,this._allSelectionRenderServices.forEach(R=>this._updateRefSelectionStyle(R,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=`${C.compareToken.EQUALS}${i}`,u=0);const{collapsed:p,style:m}=d;o?(this._commandService.executeCommand(J.ReplaceContentCommand.id,{unitId:n,body:{dataStream:h,textRuns:a},textRanges:[{startOffset:t+1-u,endOffset:t+1-u,collapsed:p,style:m}],segmentId:null,options:{fromSelection:s}}),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:m}],!0,{fromSelection:s})):(this._updateEditorModel(`${h}\r
16
- `,a),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:m}],!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(D.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 n=this._generateRefString(e);this._formulaPromptService.setSequenceNodes(t),this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,n),this._syncToEditor(t,this._previousInsertRefStringIndex+n.length);const o=this._selectionRenderService.getSelectionDataWithStyle();this._insertSelections=[],o.forEach(s=>{const i=$.convertSelectionDataToRange(s);this._insertSelections.push(i)})}_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,p=C.deserializeRangeWithSheet(u),{unitId:m,sheetName:R,range:g}=p;if(!m&&m.length>0&&o!==m)continue;const I=this._getSheetIdByName(o,R.trim());if(I&&I!==s)continue;const v=n.find(y=>{const{startRow:E,startColumn:M,endRow:b,endColumn:T,rangeType:F}=y.getRange();return F===c.RANGE_TYPE.COLUMN&&M===g.startColumn&&T===g.endColumn||F===c.RANGE_TYPE.ROW&&E===g.startRow&&b===g.endRow||E===g.startRow&&M===g.startColumn&&b===g.endRow&&T===g.endColumn||E===g.startRow&&M===g.startColumn&&g.startRow===g.endRow&&g.startColumn===g.endColumn});if(v){const y=$e(this._themeService,h,f.toString());v.updateStyle(y),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:y,isMergedMainCell:E,startRow:M,endRow:b,startColumn:T,endColumn:F}=d;(y||E)&&M===s&&T===a&&b===i&&F===l&&(s=M,a=T,i=M,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 y=h.token;u=C.getAbsoluteRefTypeWitString(y),u.endAbsoluteRefType==null&&(u.endAbsoluteRefType=u.startAbsoluteRefType)}const p=n==null?void 0:n.worksheet.getUnitId(),m=n==null?void 0:n.worksheet.getSheetId(),R=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:m,unitId:p},primary:d,style:null});this._formulaPromptService.updateSequenceRef(f,R);const g=this._formulaPromptService.getSequenceNodes(),I=g[f];typeof I!="string"&&(this._syncToEditor(g,I.endIndex+1),t.updateRange(e,this._selectionRenderService.attachPrimaryWithCoord(d)))}_refreshFormulaAndCellEditor(e){var t;for(const n of e){const o=D.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:K.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:K.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:K.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressArrowKey(e){const{keycode:t,metaKey:n}=e;let o=c.Direction.DOWN;t===x.KeyCode.ARROW_DOWN?o=c.Direction.DOWN:t===x.KeyCode.ARROW_UP?o=c.Direction.UP:t===x.KeyCode.ARROW_LEFT?o=c.Direction.LEFT:t===x.KeyCode.ARROW_RIGHT&&(o=c.Direction.RIGHT),n===x.MetaKeys.CTRL_COMMAND?this._commandService.executeCommand(D.MoveSelectionCommand.id,{direction:o,jumpOver:D.JumpOver.moveGap}):n===x.MetaKeys.SHIFT?this._commandService.executeCommand(D.ExpandSelectionCommand.id,{direction:o}):n===an?this._commandService.executeCommand(D.ExpandSelectionCommand.id,{direction:o,jumpOver:D.JumpOver.moveGap}):this._commandService.executeCommand(D.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(!(D.isRangeSelector(o)||D.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===x.KeyCode.ENTER){this._pressEnter(s);return}if(i===x.KeyCode.TAB){this._pressTab(s);return}if(i===x.KeyCode.ESC){this._pressEsc(s);return}if(this._formulaPromptService.isSearching()){if(i===x.KeyCode.ARROW_DOWN){this._formulaPromptService.navigate({direction:c.Direction.DOWN});return}if(i===x.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:K.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.addSelections([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===x.KeyCode.ARROW_DOWN?t=c.Direction.DOWN:e===x.KeyCode.ARROW_UP?t=c.Direction.UP:e===x.KeyCode.ARROW_RIGHT&&(t=c.Direction.RIGHT),this._commandService.executeCommand(J.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)!==C.compareToken.EQUALS)return;const{unitId:o}=this._getCurrentUnitIdAndSheetId();this._editorBridgeService.isVisible().visible===!1&&this._editorBridgeService.changeVisible({visible:!0,eventType:K.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!==C.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(C.matchToken.COLON)>-1)if(!this._userCursorMove)d=this._changeRangeRef(a);else{const h=a.split(C.matchToken.COLON),u=h[0],p=h[1];n-s.startIndex<=u.length?d=this._changeSingleRef(u)+C.matchToken.COLON+p:d=u+C.matchToken.COLON+this._changeSingleRef(p)}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=C.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=C.serializeRange(t),n}_changeSingleRef(e){const t=C.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=C.serializeRange(t),o}_getEditorObject(){const e=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),t=this._editorService.getEditor(e);return t==null?void 0:t.render}_isFormulaEditorActivated(){return this._editorBridgeService.isVisible().visible===!0||this._contextService.getContextValue(c.FORMULA_EDITOR_ACTIVATED)}_isSheetOrFormulaEditor(e){return e.isSheetEditor()||e.isFormulaEditor()}};Ze=Ms([re(0,c.ICommandService),re(1,c.IContextService),re(2,c.Inject(D.IEditorBridgeService)),re(3,c.Inject(xe)),re(4,c.Inject(C.LexerTreeBuilder)),re(5,K.IRenderManagerService),re(6,c.Inject(c.ThemeService)),re(7,c.Inject($.SheetsSelectionsService)),re(8,$.IRefSelectionsService),re(9,c.IUniverInstanceService),re(10,c.Inject(ge.IDescriptionService)),re(11,c.Inject(je.DocSelectionManagerService)),re(12,x.IContextMenuService),re(13,J.IEditorService),re(14,x.ILayoutService)],Ze);var ln=Object.defineProperty,Fs=Object.getOwnPropertyDescriptor,Os=(r,e,t)=>e in r?ln(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,As=(r,e,t,n)=>{for(var o=n>1?void 0:n?Fs(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&&ln(e,t,o),o},ut=(r,e)=>(t,n)=>e(t,n,r),un=(r,e,t)=>Os(r,typeof e!="symbol"?e+"":e,t);exports.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(e=qr,t,n,o){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=o;const{menu:s,...i}=this._config;s&&this._configService.setConfig("menu",s,{merge:!0}),this._configService.setConfig(Vr,i)}onStarting(){const e=this._injector;[[xe,{useClass:dt}],[Ge],[qe],[Ke],[ze],[Ye],[Ze]].forEach(n=>e.add(n))}onRendered(){[[exports.RefSelectionsRenderService],[ft]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[Ge],[Ke],[Ye]]);const e=this._injector.get(x.ComponentManager);e.register(D.RANGE_SELECTOR_COMPONENT_KEY,nn),e.register(D.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,rn)}onSteady(){this._injector.get(qe),this._injector.get(Ze)}};un(exports.UniverSheetsFormulaUIPlugin,"pluginName",Ot);un(exports.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=As([c.DependentOn(C.UniverFormulaEnginePlugin,ge.UniverSheetsFormulaPlugin),ut(1,c.Inject(c.Injector)),ut(2,K.IRenderManagerService),ut(3,c.IConfigService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=Ft;exports.FormulaEditor=rn;exports.HelpFunctionOperation=He;exports.InsertFunctionOperation=Qe;exports.MoreFunctionsOperation=Je;exports.RangeSelector=nn;exports.ReferenceAbsoluteOperation=et;exports.SearchFunctionOperation=Be;exports.SelectEditorFormulaOperation=Ie;exports.SheetOnlyPasteFormulaCommand=Xe;
9
+ */var yt;function In(){if(yt)return Oe;yt=1;var r=g,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 Oe.Fragment=t,Oe.jsx=i,Oe.jsxs=i,Oe}var Tt;function En(){return Tt||(Tt=1,ot.exports=In()),ot.exports}var _=En(),le=function(){return le=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},le.apply(this,arguments)},yn=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=g.forwardRef(function(r,e){var t=r.icon,n=r.id,o=r.className,s=r.extend,i=yn(r,["icon","id","className","extend"]),a="univerjs-icon univerjs-icon-".concat(n," ").concat(o||"").trim(),l=g.useRef("_".concat(Nn()));return wt(t,"".concat(n),{defIds:t.defIds,idSuffix:l.current},le({ref:e,className:a},i),s)});function wt(r,e,t,n,o){return g.createElement(r.tag,le(le({key:e},Tn(r,t,o)),n),(bn(r,t).children||[]).map(function(s,i){return wt(s,"".concat(e,"-").concat(r.tag,"-").concat(i),t,void 0,o)}))}function Tn(r,e,t){var n=le({},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 bn(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)?le(le({},r),{children:r.children.map(function(o){return typeof o.attrs.id=="string"&&n&&n.indexOf(o.attrs.id)>-1?le(le({},o),{attrs:le(le({},o.attrs),{id:o.attrs.id+e.idSuffix})}):o})}):r}function Nn(){return Math.random().toString(36).substring(2,8)}Ee.displayName="UniverIcon";var xn={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"}}]},kt=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"check-mark-single",ref:e,icon:xn}))});kt.displayName="CheckMarkSingle";var Mn={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=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"close-single",ref:e,icon:Mn}))});tt.displayName="CloseSingle";var Fn={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"}}]},Ut=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"delete-single",ref:e,icon:Fn}))});Ut.displayName="DeleteSingle";var On={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"}}]},$t=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"details-single",ref:e,icon:On}))});$t.displayName="DetailsSingle";var An={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"}}]},jt=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"increase-single",ref:e,icon:An}))});jt.displayName="IncreaseSingle";var Dn={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"}}]},St=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"more-single",ref:e,icon:Dn}))});St.displayName="MoreSingle";var Pn={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"}}]},Ht=g.forwardRef(function(r,e){return g.createElement(Ee,Object.assign({},r,{id:"select-range-single",ref:e,icon:Pn}))});Ht.displayName="SelectRangeSingle";function Wt(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=Wt(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Bt(){for(var r,e,t=0,n="",o=arguments.length;t<o;t++)(r=arguments[t])&&(e=Wt(r))&&(n&&(n+=" "),n+=e);return n}var Ln=Object.defineProperty,wn=Object.getOwnPropertyDescriptor,kn=(r,e,t,n)=>{for(var o=n>1?void 0:n?wn(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&&Ln(e,t,o),o},Ae=(r,e)=>(t,n)=>e(t,n,r);exports.RefSelectionsRenderService=class extends D.BaseSelectionRenderService{constructor(t,n,o,s,i,a){super(n,o,s,i);W(this,"_workbookSelections");W(this,"_eventDisposables");this._context=t,this._refSelectionsService=a,this._workbookSelections=this._refSelectionsService.getWorkbookSelections(this._context.unitId),this._initSelectionChangeListener(),this._initSkeletonChangeListener(),this._initUserActionSyncListener(),this._setSelectionStyle(Un(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._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)=>{const h=this._sheetSkeletonManagerService.getCurrent().skeleton,{row:u}=D.getCoordByOffset(d.offsetX,d.offsetY,a,h);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.ROW)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.ROW,this._getActiveViewport(d),K.ScrollTimerType.Y),d.button!==2&&f.stopPropagation())})),l.add(o==null?void 0:o.onPointerDown$.subscribeEvent((d,f)=>{const h=this._sheetSkeletonManagerService.getCurrent().skeleton,{column:u}=D.getCoordByOffset(d.offsetX,d.offsetY,a,h);D.checkInHeaderRanges(this._workbookSelections.getCurrentSelections(),u,c.RANGE_TYPE.COLUMN)||(this._onPointerDown(d,(s.zIndex||1)+1,c.RANGE_TYPE.COLUMN,this._getActiveViewport(d),K.ScrollTimerType.X),d.button!==2&&f.stopPropagation())})),l.add(i==null?void 0:i.onPointerDown$.subscribeEvent((d,f)=>{this._reset();const h=this._sheetSkeletonManagerService.getCurrent().skeleton,u=D.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:D.genNormalSelectionStyle(this._themeService),s=this._scene;return t.style=o,this.newSelectionControl(s,n,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)}_initSelectionChangeListener(){this.disposeWithMe(this._workbookSelections.selectionSet$.subscribe(t=>{if(this._reset(),!!this._skeleton)for(const o of t)this._addSelectionControlByModelData(o)}))}_initSkeletonChangeListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(t=>{if(!t)return;const{skeleton:n}=t,{scene:o}=this._context,s=o.getViewport(K.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(K.Vector2.FromArray([t.offsetX,t.offsetY]))}_getSheetObject(){return D.getSheetObject(this._context.unit,this._context)}_onPointerDown(t,n=0,o=c.RANGE_TYPE.NORMAL,s,i=K.ScrollTimerType.ALL){var P;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(K.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(!h)return;const u=l.getCoordRelativeToViewport(K.Vector2.FromArray([d,f])),{x:S,y:v}=u;this._startViewportPosX=S,this._startViewportPosY=v;const C=l.getScrollXYInfoByViewport(u),{scaleX:p,scaleY:E}=l.getAncestorScale(),m=this._skeleton.getCellByOffset(S,v,p,E,C);if(!m)return;switch(o){case c.RANGE_TYPE.NORMAL:break;case c.RANGE_TYPE.ROW:m.startColumn=0,m.endColumn=this._skeleton.getColumnCount()-1;break;case c.RANGE_TYPE.COLUMN:m.startRow=0,m.endRow=this._skeleton.getRowCount()-1;break;case c.RANGE_TYPE.ALL:m.startRow=0,m.startColumn=0,m.endRow=this._skeleton.getRowCount()-1,m.endColumn=this._skeleton.getColumnCount()-1}const I={range:m,primary:m,style:null};I.range.rangeType=o;const y=D.attachSelectionWithCoord(I,this._skeleton);this._startRangeWhenPointerDown={...y.rangeWithCoord};const x={...y.rangeWithCoord,rangeType:o};let b=this.getActiveSelectionControl();const T=this.getSelectionControls();for(const k of T){if(t.button===2&&k.model.isInclude(x)){b=k;return}if(k.model.isEqual(x)){b=k;break}}this._checkClearPreviousControls(t);const F=b==null?void 0:b.model.currentCell,N=t.shiftKey&&F,L=this._remainLastEnabled&&!t.ctrlKey&&!t.shiftKey&&!this._skipLastEnabled&&!this._singleSelectionEnabled;N&&F?this._makeSelectionByTwoCells(F,x,a,o,b):L&&b?b.updateRangeBySelectionWithCoord(y):b=this.newSelectionControl(l,a,I);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(),(P=l.getTransformer())==null||P.clearSelectedObjects(),this._setupPointerMoveListener(h,b,o,i,S,v),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 D.SelectionControl(t,s,this._themeService,{highlightHeader:this._highlightHeader,enableAutoFill:!1,rowHeaderWidth:i,columnHeaderHeight:a}),d=D.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=kn([Ae(1,c.Inject(c.Injector)),Ae(2,c.Inject(c.ThemeService)),Ae(3,M.IShortcutService),Ae(4,c.Inject(D.SheetSkeletonManagerService)),Ae(5,$.IRefSelectionsService)],exports.RefSelectionsRenderService);function Un(r){const e=D.genNormalSelectionStyle(r);return e.widgets={tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},e}const $n=(r,e,t)=>{const o=c.useDependency(K.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService);g.useEffect(()=>{if(t&&s){const i=t.input$.subscribe(a=>{a.content===R.matchToken.COMMA?s.setSkipLastEnabled(!0):s.setSkipLastEnabled(!1)});return()=>{i.unsubscribe()}}},[t,s]),g.useEffect(()=>{s&&(e.endsWith(R.matchToken.COMMA)||s.setSkipLastEnabled(!1))},[e,s])},Se=r=>r.map(e=>typeof e=="string"?e:e.token).join(""),Vt=(r,e,t)=>{const n=g.useRef(!1);return g.useEffect(()=>{if(t){const s=t.input$.subscribe(()=>{n.current=!0});return()=>{s.unsubscribe()}}},[t]),g.useEffect(()=>{if(n.current&&r){n.current=!1;const s=Se(r);e(s)}},[r]),()=>n.current=!0},nt=()=>{const r=c.useDependency(R.LexerTreeBuilder);return t=>r.sequenceNodesBuilder(t)||[]},qt=(r,e,t,n,o,s)=>{const i=nt(),a=g.useRef(!0);g.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])},Kt=r=>g.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 gt(r){const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency(c.ThemeService),n=c.useDependency($.IRefSelectionsService),s=c.useDependency(K.IRenderManagerService).getRenderById(r),i=s==null?void 0:s.with(exports.RefSelectionsRenderService),a=s==null?void 0:s.with(D.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(),v=m=>{var I;return(I=f==null?void 0:f.getSheetBySheetName(m))==null?void 0:I.getSheetId()};if(!((E=a==null?void 0:a.getWorksheetSkeleton(S))==null?void 0:E.skeleton))return;for(let m=0,I=d.length;m<I;m++){const y=d[m],{themeColor:x,token:b,refIndex:T}=y,F=R.deserializeRangeWithSheet(b),{unitId:N,sheetName:L,range:P}=F;if(N&&r!==N)continue;const k=v(L);if(k&&k!==S)continue;const A=$.setEndForRange(P,h.getRowCount(),h.getColumnCount());u.push({range:A,primary:null,style:$e(t,x,T.toString())})}((i==null?void 0:i.getSelectionControls())||[]).length===u.length?i==null||i.resetSelectionsByModelData(u):n.setSelections(u)}}function zt(r=""){const e=c.useDependency(ge.IDescriptionService),t=Yt(),n=g.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}=Gt(e,t,i);n&&h.forEach(p=>{p.ed=p.ed+n,p.st=p.st+n}),f.textRuns=h;const S=i.reduce((p,E)=>typeof E=="string"?`${p}${E}`:`${p}${E.token}`,"");f.dataStream=`${r}${S}\r
12
+ `;let v;if(a){v=s.getSelectionRanges();const p=f.dataStream.length-2+n;v.forEach(E=>{E.startOffset=Math.max(0,Math.min(E.startOffset,p)),E.endOffset=Math.max(0,Math.min(E.endOffset,p))})}const C={...l,body:f};return s.setDocumentData(C,v),u}}}function Yt(){const e=c.useDependency(c.ThemeService).getCurrentTheme();return g.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 Gt(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 m=i[i.length-1],I=m?m.ed:0,y=I+u.length;i.push({st:I,ed:y});continue}if(r.hasDefinedNameDescription(u.token.trim()))continue;const{startIndex:S,endIndex:v,nodeType:C,token:p}=u;let E="";if(C===R.sequenceNodeType.REFERENCE){if(l.has(p))E=l.get(p);else{const m=d%n.length;E=n[m],l.set(p,E),d++}a.push({refIndex:f,themeColor:E,token:p})}else C===R.sequenceNodeType.NUMBER?E=o:(C===R.sequenceNodeType.STRING||C===R.sequenceNodeType.ARRAY)&&(E=s);E&&E.length>0&&i.push({st:S,ed:v+1,ts:{cl:{rgb:E}}})}return{textRuns:i,refSelections:a}}const Zt=(r,e)=>{const t=c.useDependency(c.ICommandService),n=c.useDependency(M.IShortcutService);g.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 M.KeyCode.ARROW_LEFT:{const u=Math.max(h.startOffset-1,0);e.setSelectionRanges([{startOffset:u,endOffset:u}]);break}case M.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)}})),[M.KeyCode.ARROW_LEFT,M.KeyCode.ARROW_RIGHT,M.KeyCode.ARROW_DOWN,M.KeyCode.ARROW_UP].map(l=>({id:s,binding:l,preconditions:()=>!0,priority:900,staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keyCode:l}})).forEach(l=>{i.add(n.registerShortcut(l))}),()=>{i.dispose()}},[e,r])},Xt=(r,e)=>{const n=c.useDependency(K.IRenderManagerService).getRenderById(r),o=n==null?void 0:n.with(exports.RefSelectionsRenderService);g.useEffect(()=>{o&&(e?o==null||o.setRemainLastEnabled(!1):o==null||o.setRemainLastEnabled(!0))},[e,o])},pt=(r,e)=>{const t=c.useDependency(K.IRenderManagerService),n=c.useDependency(c.IContextService),o=c.useDependency(M.IContextMenuService),s=c.useDependency($.IRefSelectionsService),i=t.getRenderById(e),a=i==null?void 0:i.with(exports.RefSelectionsRenderService);g.useLayoutEffect(()=>{if(r){const l=a==null?void 0:a.enableSelectionChanging();return n.setContextValue($.DISABLE_NORMAL_SELECTIONS,!0),n.setContextValue(c.EDITOR_ACTIVATED,!0),()=>{n.setContextValue(c.EDITOR_ACTIVATED,!1),n.setContextValue($.DISABLE_NORMAL_SELECTIONS,!1),l==null||l.dispose()}}},[r]),g.useLayoutEffect(()=>{if(r)return()=>{s.clear()}},[r]),g.useEffect(()=>{if(r)return o.disable(),()=>{o.enable()}},[r]),g.useEffect(()=>{r&&(a==null||a.setSkipLastEnabled(!1))},[r])},Qt=()=>{g.useEffect(()=>()=>{},[])},Jt=r=>{const e=c.useDependency(c.IUniverInstanceService),t=c.useDependency($.SheetsSelectionsService);return g.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])},en=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=g.useMemo(()=>c.debounce(()=>{var v;if(!r)return;const o=r.render.with(je.DocSkeletonManagerService).getSkeleton(),{scene:s,mainComponent:i}=r.render,a=s.getViewport(J.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 K.ScrollBar(a,{barSize:8,enableVertical:!1}):a==null||a.resetCanvasSizeAndUpdateScroll():(h=null,a==null||a.scrollToBarPos({x:0,y:0}),(v=a==null?void 0:a.getScrollBar())==null||v.dispose())},30),[r]);return g.useEffect(()=>{if(r){const n=setTimeout(()=>{e(),t()},500);return()=>{clearTimeout(n)}}},[r]),g.useEffect(()=>{if(r){const n=r.input$.subscribe(()=>{t()});return()=>{n.unsubscribe()}}},[r]),{resize:e,checkScrollBar:t}},ft=r=>typeof r=="string"?r===R.matchToken.COMMA:!1,jn=r=>{if(typeof r=="object")return r.nodeType===R.sequenceNodeType.REFERENCE},Hn=r=>r.filter(e=>ft(e)||jn(e)),vt=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!==""?R.serializeRangeWithSheet(t.sheetName,t.range):R.serializeRange(t.range)):r.map(t=>R.serializeRange(t.range)),tn=(r,e,t,n,o,s,i)=>{const a=c.useDependency(K.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=g.useRef(!1),f=a.getRenderById(e),h=f==null?void 0:f.with(exports.RefSelectionsRenderService),u=g.useRef([]),S=g.useMemo(()=>{const C=Hn(n),p=u.current;return C.length===p.length?(p.splice(0),p.push(...C),p):C},[n]);u.current=S;const v=g.useRef();g.useEffect(()=>{if(r&&h){let C=!0;const p=(I,y)=>{var A;if(C||d.current){C=!1;return}const x=[...I],b=l.getUnit(e),T=((A=b==null?void 0:b.getActiveSheet())==null?void 0:A.getName())||"",F=S.map((O,B)=>{if(typeof O=="string"){if(!S[B-1])return null;const U=S[B+1];return ft(O)&&(ft(U)||B===S.length-1)?null:O}else if(O.nodeType===R.sequenceNodeType.REFERENCE){const w=R.deserializeRangeWithSheet(O.token);w.unitId=w.unitId===""?e:w.unitId,w.sheetName=w.sheetName===""?T:w.sheetName;const{unitId:U,sheetName:H}=w;if(s&&(U!==e||T!==H))return null;if(U===e&&T===H){const j=x.shift();if(j&&bt(l,e,j.rangeWithCoord.sheetId||"")===H){const Z={...O};return vt(j.rangeWithCoord),o?Z.token=R.serializeRangeWithSheet(T,j.rangeWithCoord):Z.token=R.serializeRange(j.rangeWithCoord),Z}}return O}return null}).filter(O=>!!O),N=he(x.map(O=>{var B,w,U;return{range:O.rangeWithCoord,unitId:(B=O.rangeWithCoord.unitId)!=null?B:"",sheetName:bt(l,(w=O.rangeWithCoord.unitId)!=null?w:"",(U=O.rangeWithCoord.sheetId)!=null?U:"")}}),o).join(R.matchToken.COMMA),L=Se(F),P=`${L}${L&&N?R.matchToken.COMMA:""}${N}`,k=d.current;i(P,k?-1:P.length,y)},E=h.selectionMoveEnd$.subscribe(I=>{if(p(I,!0),d.current=!1,v.current){const{result:y,offset:x}=v.current;i(y,x,!0),v.current=void 0}}),m=h.selectionMoving$.pipe(Ue.throttleTime(50)).subscribe(I=>{p(I,!1)});return()=>{E.unsubscribe(),m.unsubscribe()}}},[r,S,h,o,s,i]),g.useEffect(()=>{if(r&&h){const C=new c.DisposableCollection,p=(I,y)=>{var k;let x=0,b=0,T=!1;const F=l.getUnit(e),N=((k=F==null?void 0:F.getActiveSheet())==null?void 0:k.getName())||"",L=S.map(A=>{if(typeof A=="string")return T||(b+=A.length),A;if(A.nodeType===R.sequenceNodeType.REFERENCE){const O=R.deserializeRangeWithSheet(I);if(O.unitId=O.unitId===""?e:O.unitId,O.sheetName=O.sheetName===""?N:O.sheetName,x===y){T=!0;const B={...A,token:I};return o?B.token=R.serializeRangeWithSheet(O.sheetName,O.range):B.token=R.serializeRange(O.range),x++,b+=B.token.length,B}return x++,T||(b+=A.token.length),A}return A}),P=Se(L);v.current={result:P,offset:b},i(P,-1,!1)};let E=0;const m=h.selectionMoveEnd$.subscribe(()=>{E=setTimeout(()=>{C.dispose(),h.getSelectionControls().forEach((y,x)=>{C.add(V.merge(y.selectionMoving$,y.selectionScaling$).pipe(V.map(b=>R.serializeRange(b)),V.distinctUntilChanged()).subscribe(b=>{d.current=!0,p(b,x)}))})},30)});return()=>{m.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(J.IEditorService),d=c.useDependency(K.IRenderManagerService).getRenderById(e),f=d==null?void 0:d.with(exports.RefSelectionsRenderService);g.useEffect(()=>{if(r&&f)if(t){const h=i.onCommandExecuted(u=>{if(u.id===$.SetWorksheetActiveOperation.id){const S=f.getSelectionControls().length;for(let v=1;v<=S;v++)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])},nn=r=>!r.some(t=>{if(typeof t=="string"){if(t!==R.matchToken.COMMA)return!0}else if(t.nodeType!==R.sequenceNodeType.REFERENCE)return!0;return!1}),Wn=(r,e,t)=>{const n=g.useRef(!0);g.useEffect(()=>{if(r){const o=setTimeout(()=>{n.current=!1},500);return()=>{clearTimeout(o)}}},[r]),g.useEffect(()=>{if(!n.current&&e){const o=nn(t);e(o,Se(t))}},[t,e])},Bn="univer-sheet-range-selector-text-wrap",Vn="univer-sheet-range-selector-placeholder",qn="univer-sheet-range-selector-error",Kn="univer-sheet-range-selector-error-wrap",zn="univer-sheet-range-selector-text",Yn="univer-sheet-range-selector-active",Gn="univer-sheet-range-selector-icon",Zn="univer-sheet-range-selector-dialog-item",Xn="univer-sheet-range-selector-dialog-item-delete",ue={sheetRangeSelectorTextWrap:Bn,sheetRangeSelectorPlaceholder:Vn,sheetRangeSelectorError:qn,sheetRangeSelectorErrorWrap:Kn,sheetRangeSelectorText:zn,sheetRangeSelectorActive:Yn,sheetRangeSelectorIcon:Gn,sheetRangeSelectorDialogItem:Zn,sheetRangeSelectorDialogItemDelete:Xn},De=()=>{};function rn(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:v=!1}=r,C=c.useDependency(J.IEditorService),p=c.useDependency(c.LocaleService),E=c.useDependency(c.ICommandService),m=c.useDependency(R.LexerTreeBuilder),I=g.useRef(null),[y,x]=g.useState(!1),[b,T]=g.useState(u),F=g.useMemo(()=>c.createInternalEditorID(`${D.RANGE_SELECTOR_SYMBOLS}-${c.generateRandomId(4)}`),[]),[N,L]=g.useState(),P=g.useRef(null),k=g.useMemo(()=>!y&&b,[y,b]),[A,O]=g.useState(()=>typeof e=="string"?e:he(e,v).join(R.matchToken.COMMA));i&&(i.handleOutClick=(q,Y)=>{I.current&&!y&&!I.current.contains(q.target)&&Y()});const B=g.useMemo(()=>A.split(R.matchToken.COMMA).filter(q=>!!q).map(q=>R.deserializeRangeWithSheet(q)),[A]),w=g.useMemo(()=>o!==void 0,[o]),U=Jt(!y&&b),H=g.useMemo(()=>q=>{const Y=m.sequenceNodesBuilder(q);if(Y){if(nn(Y)){const fe=Y.map(be=>{if(typeof be=="string")return be;if(be.nodeType===R.sequenceNodeType.REFERENCE){const It={...be},Fe=R.deserializeRangeWithSheet(be.token);return Fe.range=vt(Fe.range),v||(Fe.sheetName="",Fe.unitId=""),It.token=he([Fe],v)[0],It}return be}),_e=Se(fe);a(_e)}}else O("")},[v]),j=Kt(N);g.useLayoutEffect(()=>{if(u){const q=setTimeout(()=>{T(u),u&&j()},30);return()=>{clearTimeout(q)}}else U(),T(u),N==null||N.blur()},[u,j]);const{checkScrollBar:Z}=en(N),ce=nt(),ae=g.useMemo(()=>ce(A),[A]),de=zt(),X=gt(t),te=(q,Y=!0)=>{if(!N)return;const ve=ce(q),fe=de(N,ve,Y);X(fe)},ie=Vt(ae,H,N),pe=g.useMemo(()=>(q,Y,ve)=>{te(q),O(q),ie(),ve&&(j(),Y!==-1&&setTimeout(()=>{const fe={startOffset:Y,endOffset:Y};N==null||N.setSelectionRanges([fe]);const _e=N==null?void 0:N.render.with(J.DocBackScrollRenderController);_e==null||_e.scrollToRange({...fe,collapsed:!0})},50),Z())},[N]);tn(k,t,n,ae,v,S,pe),pt(k,t),Xt(t,S),$n(t,A,N),Wn(k,l,ae),Zt(k,N),Qt(),_t(k,t,v,T,f,()=>{k&&te(A)}),g.useEffect(()=>{if(N){const q=N.input$.pipe(V.throttleTime(100)).subscribe(Y=>{var fe,_e;const ve=((_e=(fe=Y.data.body)==null?void 0:fe.dataStream)!=null?_e:"").replaceAll(/\n|\r/g,"").replaceAll(/,{2,}/g,",").replaceAll(/(^,)/g,"");te(ve,!1),O(ve),ie()});return()=>{q.unsubscribe()}}},[N]),g.useEffect(()=>{const q=E.onCommandExecuted(Y=>{Y.id===D.SetCellEditVisibleOperation.id&&(x(!1),d(!1),T(!1),f())});return()=>{q.dispose()}},[v]),g.useLayoutEffect(()=>{let q;if(P.current){q=C.register({autofocus:!0,editorUnitId:F,isSingle:!0,initialSnapshot:{id:F,body:{dataStream:`\r
13
+ `},documentStyle:{}}},P.current);const Y=C.getEditor(F);L(Y)}return()=>{q==null||q.dispose()}},[]),qt(A,"",b,de,X,N);const z=()=>{setTimeout(()=>{h(),j(),T(!0)},30)},G=q=>{const Y=he(q,v).join(R.matchToken.COMMA);te(Y),ie(),O(Y),x(!1),d(!1),setTimeout(()=>{T(!0),N==null||N.setSelectionRanges([{startOffset:Y.length,endOffset:Y.length}]),j()},30)},ne=()=>{x(!1),d(!1),setTimeout(()=>{T(!0),j()},30)},se=()=>{w||(j(),setTimeout(()=>{x(!0),d(!0),T(!1)},30))};return _.jsxs("div",{className:ue.sheetRangeSelector,ref:I,children:[_.jsxs("div",{className:Bt(ue.sheetRangeSelectorTextWrap,{[ue.sheetRangeSelectorActive]:b&&!w,[ue.sheetRangeSelectorError]:w}),children:[_.jsx("div",{className:ue.sheetRangeSelectorText,ref:P,onMouseUp:z}),_.jsx(oe.Tooltip,{title:p.t("rangeSelector.buttonTooltip"),placement:"bottom",children:_.jsx(Ht,{className:ue.sheetRangeSelectorIcon,onClick:se})}),o!==void 0?_.jsx("div",{className:ue.sheetRangeSelectorErrorWrap,children:o}):null,s!==void 0&&!A?_.jsx("div",{className:ue.sheetRangeSelectorPlaceholder,children:s}):null]}),y&&_.jsx(Qn,{editorId:F,handleConfirm:G,handleClose:ne,unitId:t,subUnitId:n,initValue:B,visible:y,isOnlyOneRange:S,isSupportAcrossSheet:v})]})}function Qn(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(J.IEditorService),u=c.useDependency(ge.IDescriptionService),S=c.useDependency(R.LexerTreeBuilder),C=c.useDependency(K.IRenderManagerService).getRenderById(i),p=C==null?void 0:C.with(exports.RefSelectionsRenderService),[E,m]=g.useState(()=>{if(l){const w=s[0];return w?he([w],d):[""]}return he(s,d)}),[I,y]=g.useState(()=>E.length-1),x=Yt(),b=g.useMemo(()=>E.join(R.matchToken.COMMA),[E]),T=nt(),F=g.useMemo(()=>T(b),[b]),N=g.useMemo(()=>Gt(u,x,F).refSelections,[F]),L=()=>{m([]),setTimeout(()=>{n()},30)},P=(w,U)=>{U?p==null||p.setSkipLastEnabled(!1):p==null||p.setSkipLastEnabled(!0),m(H=>{const j=[...H];return j[w]=U,j})},k=w=>{p==null||p.setSkipLastEnabled(!1),m(U=>{if(U.length===1)return U;const H=[];return U.forEach((j,Z)=>{w!==Z&&H.push(j)}),H})},A=()=>{p==null||p.setSkipLastEnabled(!0),m(w=>(w.push(""),y(w.length-1),[...w]))},O=g.useCallback(w=>{var H;p==null||p.setSkipLastEnabled(!1);const U=w.split(R.matchToken.COMMA).filter(j=>!!j);m(l?[(H=U[0])!=null?H:""]:U)},[I,l]),B=gt(i);return tn(I>=0,i,a,F,d,l,O),pt(I>=0,i),Xt(i,l),_t(I>=0,i,d,V.noop,V.noop,()=>B(N)),g.useEffect(()=>{B(N)},[N]),g.useEffect(()=>{(E.length===0||E.length===1&&!E[0])&&(p==null||p.setSkipLastEnabled(!0))},[E]),g.useEffect(()=>{const w=h.focusStyle$.pipe(V.filter(U=>!!U&&c.DOCS_NORMAL_EDITOR_UNIT_ID_KEY!==U)).subscribe(U=>{U!==e&&L()});return()=>{w.unsubscribe()}},[h,e]),_.jsx(oe.Dialog,{width:"328px",visible:o,title:f.t("rangeSelector.title"),draggable:!0,closeIcon:_.jsx(tt,{}),footer:_.jsxs("footer",{children:[_.jsx(oe.Button,{onClick:L,children:f.t("rangeSelector.cancel")}),_.jsx(oe.Button,{style:{marginLeft:10},onClick:()=>t(E.filter(w=>{const U=S.sequenceNodesBuilder(w);return U&&U.length===1&&typeof U[0]!="string"&&U[0].nodeType===R.sequenceNodeType.REFERENCE}).map(w=>R.deserializeRangeWithSheet(w)).map(w=>({...w,range:vt(w.range)}))),type:"primary",children:f.t("rangeSelector.confirm")})]}),onClose:L,children:_.jsxs("div",{className:ue.sheetRangeSelectorDialog,children:[E.map((w,U)=>_.jsxs("div",{className:ue.sheetRangeSelectorDialogItem,children:[_.jsx(oe.Input,{affixWrapperStyle:{width:"100%"},placeholder:f.t("rangeSelector.placeHolder"),onFocus:()=>y(U),value:w,onChange:H=>P(U,H)},`input_${U}`),E.length>1&&!l&&_.jsx(Ut,{className:ue.sheetRangeSelectorDialogItemDelete,onClick:()=>k(U)})]},U)),!l&&_.jsx("div",{children:_.jsxs(oe.Button,{type:"link",size:"small",onClick:A,children:[_.jsx(jt,{}),_.jsx("span",{children:f.t("rangeSelector.addAnotherRange")})]})})]})})}function Jn(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 er=(r,e=100)=>{g.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])},tr="univer-formula-help-function",nr="univer-formula-help-function-title",rr="univer-formula-help-function-title-icons",or="univer-formula-help-function-title-icon",sr="univer-formula-help-function-content",ir="univer-formula-help-function-content-inner",cr="univer-formula-help-function-content-params",ar="univer-formula-help-function-content-params-title",lr="univer-formula-help-function-content-params-detail",ur="univer-formula-help-function-active",dr="univer-formula-help-decorator",hr="univer-formula-help-param",fr="univer-formula-help-param-prefix",mr="univer-formula-help-param-item",Sr="univer-formula-help-param-active",ee={formulaHelpFunction:tr,formulaHelpFunctionTitle:nr,formulaHelpFunctionTitleIcons:rr,formulaHelpFunctionTitleIcon:or,formulaHelpFunctionContent:sr,formulaHelpFunctionContentInner:ir,formulaHelpFunctionContentParams:cr,formulaHelpFunctionContentParamsTitle:ar,formulaHelpFunctionContentParamsDetail:lr,formulaHelpFunctionActive:ur,formulaHelpDecorator:dr,formulaHelpParam:hr,formulaHelpParamPrefix:fr,formulaHelpParamItem:mr,formulaHelpParamActive:Sr},Nt=()=>{};function gr(r){const{functionInfo:e,paramIndex:t,editorId:n,onParamsSwitch:o=Nt,onClose:s=Nt}=r,i=c.useDependency(J.IEditorService),a=c.useDependency(M.ISidebarService),l=g.useMemo(()=>!!e&&t>=0,[e,t]),[d,f]=g.useState(!0),[h,u]=g.useState([0,0]),S=c.useDependency(c.LocaleService),v=S.t("formula.prompt.required"),C=S.t("formula.prompt.optional");er(p),g.useEffect(()=>{const m=a.scrollEvent$.pipe(V.throttleTime(100)).subscribe(p);return()=>{m.unsubscribe()}},[]),g.useEffect(()=>{const m=i.getEditor(n);if(!m)return;const I=m.getBoundingClientRect(),{left:y,top:x,height:b}=I;u([y,x+b])},[e,t,n]);function p(){const m=i.getEditor(n);if(!m)return;const I=m.getBoundingClientRect(),{left:y,top:x,height:b}=I;return u([y,x+b]),I}function E(m){o&&o(m)}return _.jsx(oe.Popup,{visible:l,offset:h,children:e?_.jsxs("div",{className:ee.formulaHelpFunction,children:[_.jsxs("div",{className:ee.formulaHelpFunctionTitle,children:[_.jsx(pr,{prefix:e.functionName,value:e.functionParameter,active:t,onClick:E}),_.jsxs("div",{className:ee.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:ee.formulaHelpFunctionTitleIcon,style:{transform:d?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>f(!d),children:_.jsx(St,{})}),_.jsx("div",{className:ee.formulaHelpFunctionTitleIcon,onClick:s,children:_.jsx(tt,{})})]})]}),_.jsx("div",{className:ee.formulaHelpFunctionContent,style:{height:d?"unset":0,padding:d?"revert-layer":0},children:_.jsxs("div",{className:ee.formulaHelpFunctionContentInner,children:[_.jsx(st,{title:S.t("formula.prompt.helpExample"),value:`${e.functionName}(${e.functionParameter.map(m=>m.example).join(",")})`}),_.jsx(st,{title:S.t("formula.prompt.helpAbstract"),value:e.description}),e&&e.functionParameter&&e.functionParameter.map((m,I)=>_.jsx(st,{className:t===I?ee.formulaHelpFunctionActive:"",title:m.name,value:`${m.require?v:C} ${m.detail}`},I))]})})]}):_.jsx(_.Fragment,{})})}const st=r=>_.jsxs("div",{className:ee.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`
14
+ ${ee.formulaHelpFunctionContentParamsTitle}
15
+ ${r.className}
16
+ `,children:r.title}),_.jsx("div",{className:ee.formulaHelpFunctionContentParamsDetail,children:r.value})]}),pr=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return _.jsxs("div",{className:ee.formulaHelpParam,children:[_.jsxs("span",{className:ee.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>_.jsxs("span",{className:ee.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?ee.formulaHelpFunctionActive:ee.formulaHelpParamActive,onClick:()=>o(i),children:Ct(s)}),i===t.length-1?"":","]},i)),")"]})},xe=r=>{const e=g.useRef();return e.current=r,e},vr=(r,e,t)=>{const n=c.useDependency(ge.IDescriptionService),o=c.useDependency(R.LexerTreeBuilder),[s,i]=g.useState(),[a,l]=g.useState(-1),[d,f]=g.useState(!0),h=xe(d),u=g.useRef(e);u.current=e;const S=()=>{i(void 0),l(-1),f(!1)};return g.useEffect(()=>{if(t&&r){const v=t.selectionChange$.pipe(V.debounceTime(50)).subscribe(p=>{if(p.textRanges.length===1){const[E]=p.textRanges;if(E.collapsed&&h.current){const m=o.getFunctionAndParameter(u.current,E.startOffset-1);if(m){const{functionName:I,paramIndex:y}=m,x=n.getFunctionInfo(I);i(x),l(y);return}}}i(void 0),l(-1)}),C=t.selectionChange$.pipe(V.filter(p=>p.isEditing),V.filter(p=>p.textRanges.length===1),V.map(p=>p.textRanges[0].startOffset),V.distinctUntilChanged()).subscribe(()=>{f(!0)});return()=>{v.unsubscribe(),C.unsubscribe()}}},[t,r]),g.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},_r=(r,e=[],t)=>{const n=c.useDependency(ge.IDescriptionService),[o,s]=g.useState([]),[i,a]=g.useState(""),l=g.useRef(-1),d=xe({nodes:e}),f=()=>{s([]),a(""),l.current=-1};return g.useEffect(()=>{if(t&&r){const u=t.input$.pipe(V.debounceTime(300)).subscribe(()=>{const S=t.getSelectionRanges();if(S.length===1){const v=d.current.nodes,C=S[0];if(C.collapsed){const p=Ve(v,C.startOffset-1,!1);l.current=p;const E=v[p];if(E&&typeof E!="string"&&E.nodeType===R.sequenceNodeType.FUNCTION){l.current=p;const m=E.token,I=n.getSearchListByNameFirstLetter(m);s(I),a(m);return}}}l.current=-1,a(""),s(v=>v!=null&&v.length?[]:v)});return()=>{u.unsubscribe()}}},[t,r]),g.useEffect(()=>{r||f()},[r]),{searchList:o,searchText:i,handlerFormulaReplace:u=>{const S=[...d.current.nodes];if(l.current!==-1){const v=S.splice(l.current+1),C=S.pop()||"";let p=(typeof C=="string"?C.length:C.token.length)-u.length;return S.push(u),v[0]!==R.matchToken.OPEN_BRACKET&&(S.push(R.matchToken.OPEN_BRACKET),p--),{text:Se([...S,...v]),offset:p}}},reset:f}},Cr=r=>r.reduce((e,t)=>typeof t=="string"?e+t.length:e+t.token.length,0),Rr=(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=[R.compareToken.EQUALS,R.compareToken.GREATER_THAN,R.compareToken.GREATER_THAN_OR_EQUAL,R.compareToken.LESS_THAN,R.compareToken.LESS_THAN_OR_EQUAL,R.compareToken.NOT_EQUAL,R.operatorToken.CONCATENATE,R.operatorToken.DIVIDED,R.operatorToken.MINUS,R.operatorToken.MULTIPLY,R.operatorToken.PLUS,R.operatorToken.POWER,R.matchToken.COMMA],xt=[...Rt,R.matchToken.COLON,R.matchToken.OPEN_BRACKET],Ir=[...Rt,R.matchToken.CLOSE_BRACKET],it=r=>typeof r=="string"?r:r.token,Er=(r,e,t)=>{const o=c.useDependency(K.IRenderManagerService).getRenderById(r),s=o==null?void 0:o.with(exports.RefSelectionsRenderService),i=g.useRef(!1),a=xe(e),l=g.useMemo(()=>Rr(!1,300),[]),d=h=>{s&&s.setSkipLastEnabled(h),i.current=h},f=()=>i.current;return g.useEffect(()=>{if(t&&s){const h=t.input$.subscribe(S=>{const v=S.content;v.length===1&&xt.includes(v)?(d(!0),l.setValue(!0),l.reset()):(d(!1),l.setValue(!1))}),u=t.selectionChange$.pipe(V.debounceTime(100)).subscribe(S=>{if(l.getValue())return;const v=S.textRanges;if(!v.length)return;if(v.length!==1){d(!1);return}const C=v[0];if(!C.collapsed){d(!1);return}const p=a.current;if(!p.length){d(!0);return}const E=C.startOffset-1;if(E===0){const T=Ve(p,1,!1),F=p[T]||"",N=it(F);if(Rt.includes(N)){d(!0);return}}const m=Ve(p,E,!1),I=p[m];if(!I){d(!1);return}const y=p[m+1]||"",x=it(y),b=it(I);xt.includes(b)&&(!y||Ir.includes(x))?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}},yr=()=>{},Tr=(r,e,t,n,o,s,i=yr)=>{const a=c.useDependency(K.IRenderManagerService),l=c.useDependency(c.IUniverInstanceService),d=xe(n),{getIsNeedAddSelection:f}=Er(e,n,s),h=l.getUnit(e),u=y=>{var x,b;return(b=(x=h==null?void 0:h.getSheetBySheetId(y))==null?void 0:x.getName())!=null?b:""},S=g.useMemo(()=>u(t),[t]),v=c.useObservable(h==null?void 0:h.activeSheet$),C=xe({activeSheet:v,sheetName:S}),p=a.getRenderById(e),E=p==null?void 0:p.with(exports.RefSelectionsRenderService),m=g.useRef(!1),I=g.useRef();g.useEffect(()=>{if(E&&r){let y=!0;const x=T=>{var k,A,O,B,w,U;if(y||m.current){y=!1;return}const F=s==null?void 0:s.getSelectionRanges();if((F==null?void 0:F.length)!==1)return;const L=F[0].startOffset-1,P=[...d.current];if(f())if(L!==0){const H=Ve(P,L,!1);if(H===-1&&P.length)return;const j=T[T.length-1],Z=P.splice(H+1),ce=(k=j.rangeWithCoord.sheetId)!=null?k:t,ae={range:j.rangeWithCoord,unitId:(A=j.rangeWithCoord.unitId)!=null?A:e,sheetName:u(ce)},X=he([ae],o&&ce!==t);P.push({token:X[0],nodeType:R.sequenceNodeType.REFERENCE});const te=[...P,...Z],ie=Se(te);i(ie,Cr(P),!0)}else{const H=T[T.length-1],j=(O=H.rangeWithCoord.sheetId)!=null?O:t,Z={range:H.rangeWithCoord,unitId:(B=H.rangeWithCoord.unitId)!=null?B:e,sheetName:u(j)},ae=he([Z],o&&j!==t);P.unshift({token:ae[0],nodeType:R.sequenceNodeType.REFERENCE});const de=Se(P);i(de,ae[0].length,!0)}else{let H=0;const j=P.map(X=>{var te,ie,pe;if(typeof X=="string")return X;if(X.nodeType===R.sequenceNodeType.REFERENCE){const z=R.deserializeRangeWithSheet(X.token);if(z.sheetName||(z.sheetName=S),o&&((te=C.current.activeSheet)==null?void 0:te.getName())!==z.sheetName)return X.token;const G=T[H];if(H++,!G)return"";const ne=(ie=G.rangeWithCoord.sheetId)!=null?ie:t,se={range:G.rangeWithCoord,unitId:(pe=G.rangeWithCoord.unitId)!=null?pe:e,sheetName:u(ne)};return he([se],o)[0]}return X.token}).join(""),Z=[];for(let X=H;X<=T.length-1;X++){const te=T[X],ie=(w=te.rangeWithCoord.sheetId)!=null?w:t,pe={range:te.rangeWithCoord,unitId:(U=te.rangeWithCoord.unitId)!=null?U:e,sheetName:u(ie)},G=he([pe],o&&ie!==t);Z.push(G[0])}const ce=P[P.length-1],ae=ce&&(typeof ce=="string"?!1:ce.nodeType===R.sequenceNodeType.REFERENCE),de=`${j}${Z.length&&ae?",":""}${Z.join(",")}`;i(de,de.length,!0)}},b=E.selectionMoveEnd$.subscribe(T=>{if(x(T),m.current=!1,I.current){const{result:F,offset:N}=I.current;i(F,N||-1,!0),I.current=void 0}});return()=>{b.unsubscribe()}}},[E,s,o,r]),g.useEffect(()=>{if(r&&E&&s){const y=new c.DisposableCollection,x=(F,N)=>{let L=0,P=0,k=!1;const{sheetName:A}=C.current,O=d.current.map(w=>{var U;if(typeof w=="string")return k||(P+=w.length),w;if(w.nodeType===R.sequenceNodeType.REFERENCE){const H=R.deserializeRangeWithSheet(w.token);if(H.unitId||(H.unitId=e),H.sheetName||(H.sheetName=A),o&&((U=C.current.activeSheet)==null?void 0:U.getName())!==H.sheetName)return k||(P+=w.token.length),w;if(L===N){k=!0;const j={...w,token:F};return o&&H.sheetName!==A?j.token=R.serializeRangeWithSheet(H.sheetName,R.deserializeRangeWithSheet(F).range):j.token=F,P+=j.token.length,L++,j}return k||(P+=w.token.length),L++,w}return k||(P+=w.token.length),w}),B=Se(O);i(B,-1,!1),I.current={result:B,offset:P}},b=()=>{y.dispose(),E.getSelectionControls().forEach((N,L)=>{y.add(V.merge(N.selectionMoving$,N.selectionScaling$).pipe(Ue.map(P=>R.serializeRange(P)),Ue.distinctUntilChanged()).subscribe(P=>{m.current=!0,x(P,L)}))})},T=V.merge(s.input$,E.selectionMoveEnd$).pipe(Ue.debounceTime(50)).subscribe(()=>{b()});return()=>{T.unsubscribe(),y.dispose()}}},[r,E,s])},br=(r,e,t)=>{const n=c.useDependency(R.LexerTreeBuilder),o=g.useRef(!0);g.useEffect(()=>{if(r){const s=setTimeout(()=>{o.current=!1},500);return()=>{clearTimeout(s)}}},[r]),g.useEffect(()=>{if(!o.current&&e){const s=n.checkIfAddBracket(t);e(s===0&&t.startsWith(R.operatorToken.EQUALS),`${t}`)}},[t,e])},Nr="univer-sheet-embedding-formula-editor-active",xr="univer-sheet-embedding-formula-editor-wrap",Mr="univer-sheet-embedding-formula-editor-text",Fr="univer-sheet-embedding-formula-editor-error-wrap",Or="univer-sheet-embedding-formula-editor-error",Ne={sheetEmbeddingFormulaEditorActive:Nr,sheetEmbeddingFormulaEditorWrap:xr,sheetEmbeddingFormulaEditorText:Mr,sheetEmbeddingFormulaEditorErrorWrap:Fr,sheetEmbeddingFormulaEditorError:Or},Ar="univer-formula-search-function",Dr="univer-formula-search-function-item",Pr="univer-formula-search-function-item-name",Lr="univer-formula-search-function-item-name-light",wr="univer-formula-search-function-item-desc",kr="univer-formula-search-function-item-active",Ce={formulaSearchFunction:Ar,formulaSearchFunctionItem:Dr,formulaSearchFunctionItemName:Pr,formulaSearchFunctionItemNameLight:Lr,formulaSearchFunctionItemDesc:wr,formulaSearchFunctionItemActive:kr},Ur=()=>{},$r=g.forwardRef(jr);function jr(r,e){const{searchText:t,searchList:n,onSelect:o,editorId:s,onClose:i=Ur}=r,a=c.useDependency(J.IEditorService),l=c.useDependency(M.IShortcutService),d=c.useDependency(c.ICommandService),f=g.useMemo(()=>!!n.length,[n]),h=g.useRef(),[u,S]=g.useState(0),[v,C]=g.useState([0,0]),p=g.useRef(!1),E=xe({searchList:n,active:u}),m=a.getEditor(s);g.useEffect(()=>{const T=a.getEditor(s),F=T==null?void 0:T.getBoundingClientRect();if(F==null)return;const{left:N,top:L,height:P}=F;C([N,L+P]),S(0)},[t,n]);function I(T){p.current&&S(T)}function y(){p.current&&S(-1)}g.useEffect(()=>{if(!n.length)return;const T=`sheet.formula-embedding-editor.search_function.${s}`,F=new c.DisposableCollection,N=L=>{const{searchList:P,active:k}=E.current;switch(L){case M.KeyCode.ARROW_UP:{S(A=>{const O=Math.max(0,A-1);return x(O),O});break}case M.KeyCode.ARROW_DOWN:{S(A=>{const O=Math.min(P.length-1,A+1);return x(O),O});break}case M.KeyCode.TAB:case M.KeyCode.ENTER:{const A=P[k];o(A.name);break}case M.KeyCode.ESC:{o("");break}}};return F.add(d.registerCommand({id:T,type:c.CommandType.OPERATION,handler(L,P){const{keyCode:k}=P;N(k)}})),[M.KeyCode.ARROW_UP,M.KeyCode.ARROW_DOWN,M.KeyCode.ENTER,M.KeyCode.ESC,M.KeyCode.TAB].map(L=>({id:T,binding:L,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keyCode:L}})).forEach(L=>{F.add(l.registerShortcut(L))}),()=>{F.dispose()}},[n]);function x(T){var U;const F=(U=h.current)==null?void 0:U.querySelectorAll(`.${Ce.formulaSearchFunctionItem}`)[T];if(!F)return;const N=F.parentNode;if(!N)return;const P=N.getBoundingClientRect().top,k=N.offsetHeight,A=F.getBoundingClientRect(),O=A.top,B=A.height;if(O>=0&&O>P&&O-P+B<=k)return;const w=F.offsetTop-(k-B)/2;N.scrollTo({top:w,behavior:"smooth"})}const b=g.useMemo(()=>{let T="";return()=>{clearTimeout(T),p.current=!0,T=setTimeout(()=>{p.current=!1},300)}},[]);return n.length>0&&_.jsx(oe.Popup,{visible:f,offset:v,children:_.jsx("ul",{className:Ce.formulaSearchFunction,ref:T=>{h.current=T,e&&(e.current=T)},children:n.map((T,F)=>_.jsxs("li",{className:u===F?`
17
+ ${Ce.formulaSearchFunctionItem}
18
+ ${Ce.formulaSearchFunctionItemActive}
19
+ `:Ce.formulaSearchFunctionItem,onMouseEnter:()=>I(F),onMouseLeave:y,onMouseMove:b,onClick:()=>{o(T.name),m&&m.focus()},children:[_.jsxs("span",{className:Ce.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Ce.formulaSearchFunctionItemNameLight,children:T.name.substring(0,t.length)}),_.jsx("span",{children:T.name.slice(t.length)})]}),_.jsx("span",{className:Ce.formulaSearchFunctionItemDesc,children:T.desc})]},F))})})}const Mt=r=>r.startsWith(R.operatorToken.EQUALS)?r.slice(1):"",ct=()=>{};function on(r){const{errorText:e,initValue:t,unitId:n,subUnitId:o,isFocus:s=!0,isSupportAcrossSheet:i=!1,onFocus:a=ct,onBlur:l=ct,onChange:d,onVerify:f,actions:h}=r,u=c.useDependency(J.IEditorService),S=g.useRef(null),[v,C]=g.useState(()=>t.startsWith(R.operatorToken.EQUALS)?t:"");h&&(h.handleOutClick=(z,G)=>{S.current&&!S.current.contains(z.target)&&G()});const p=g.useMemo(()=>Mt(v),[v]),E=g.useRef(null),[m,I]=g.useState(),[y,x]=g.useState(s),b=g.useRef(null),T=g.useMemo(()=>c.createInternalEditorID(`${D.EMBEDDING_FORMULA_EDITOR}-${c.generateRandomId(4)}`),[]),F=g.useMemo(()=>e!==void 0,[e]),N=nt(),L=g.useMemo(()=>N(p),[p]),P=Vt(L,z=>{d(`=${z}`)},m),k=zt("="),A=gt(n),O=(z,G=!0)=>{if(!m)return;const ne=N(z),se=k(m,ne,G);A(se)};br(y,f,v);const B=Kt(m),w=Jt(y);g.useLayoutEffect(()=>{if(s){const z=setTimeout(()=>{x(s),s&&B()},30);return()=>{clearTimeout(z)}}else w(),x(s)},[s,B]);const{checkScrollBar:U}=en(m);pt(y,n),Zt(y,m),Tr(y,n,o,L,i,m,(z,G,ne)=>{const se=`=${z}`;P(),C(se),O(z),ne&&(B(),G!==-1&&setTimeout(()=>{const q={startOffset:G+1,endOffset:G+1};m==null||m.setSelectionRanges([q]);const Y=m==null?void 0:m.render.with(J.DocBackScrollRenderController);Y==null||Y.scrollToRange({...q,collapsed:!0})},50),U())}),Qt(),_t(y,n,i,x,l,ct);const{searchList:j,searchText:Z,handlerFormulaReplace:ce,reset:ae}=_r(y,L,m),{functionInfo:de,paramIndex:X,reset:te}=vr(y,v,m);g.useEffect(()=>{if(m){const z=m.input$.subscribe(G=>{var se,q;const ne=((q=(se=G.data.body)==null?void 0:se.dataStream)!=null?q:"").replaceAll(/\n|\r/g,"");P(),C(ne),O(Mt(ne),!1)});return()=>{z.unsubscribe()}}},[m]),qt(p,"=",y,k,A,m),g.useLayoutEffect(()=>{let z;if(b.current){z=u.register({autofocus:!0,editorUnitId:T,isSingle:!0,initialSnapshot:{id:T,body:{dataStream:`${t}\r
20
+ `},documentStyle:{}}},b.current);const G=u.getEditor(T);I(G)}return()=>{z==null||z.dispose()}},[]);const ie=z=>{const G=ce(z);if(G){C(`=${G.text}`);const ne=m==null?void 0:m.getSelectionRanges();if(ne&&ne.length===1){const se=ne[0];if(se.collapsed){const q=G.offset;setTimeout(()=>{m==null||m.setSelectionRanges([{startOffset:se.startOffset-q,endOffset:se.endOffset-q}])},30)}}ae(),B(),O(G.text)}},pe=()=>{setTimeout(()=>{x(!0),a(),B()},30)};return _.jsxs("div",{className:Ne.sheetEmbeddingFormulaEditor,children:[_.jsxs("div",{className:Bt(Ne.sheetEmbeddingFormulaEditorWrap,{[Ne.sheetEmbeddingFormulaEditorActive]:y,[Ne.sheetEmbeddingFormulaEditorError]:F}),ref:S,children:[_.jsx("div",{className:Ne.sheetEmbeddingFormulaEditorText,ref:b,onMouseUp:pe}),e!==void 0?_.jsx("div",{className:Ne.sheetEmbeddingFormulaEditorErrorWrap,children:e}):null]}),_.jsx(gr,{editorId:T,paramIndex:X,functionInfo:de,onClose:()=>{te(),B()}}),_.jsx($r,{searchText:Z,editorId:T,searchList:j,onSelect:ie,ref:E})]})}const Hr="sheets-formula-ui.base.config",Wr={};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 sn(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"&&R.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 at="SHEET_FORMULA_ALERT",zr={[R.ErrorType.DIV_BY_ZERO]:"divByZero",[R.ErrorType.NAME]:"name",[R.ErrorType.VALUE]:"value",[R.ErrorType.NUM]:"num",[R.ErrorType.NA]:"na",[R.ErrorType.CYCLE]:"cycle",[R.ErrorType.REF]:"ref",[R.ErrorType.SPILL]:"spill",[R.ErrorType.CALC]:"calc",[R.ErrorType.ERROR]:"error",[R.ErrorType.CONNECT]:"connect",[R.ErrorType.NULL]:"null"};let mt=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(V.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=sn(l,!!d);if(!f){this._hideAlert();return}const h=this._cellAlertManagerService.currentAlert.get(at),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:D.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:at});return}}this._hideAlert()}))}_initZenService(){this.disposeWithMe(this._zenZoneService.visible$.subscribe(r=>{r&&this._hideAlert()}))}_hideAlert(){this._cellAlertManagerService.removeAlert(at)}};mt=Kr([Pe(1,c.Inject(D.HoverManagerService)),Pe(2,c.Inject(D.CellAlertManagerService)),Pe(3,c.Inject(c.LocaleService)),Pe(4,c.Inject(R.FormulaDataModel)),Pe(5,M.IZenZoneService)],mt);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},Ft=(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:D.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===D.DATA_TYPE.FORMULA,applyFunctions:{[D.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)||"",v=((d=r[h])==null?void 0:d.si)||"",C=c.isFormulaString(S);if(c.isFormulaId(v))u.si=v,u.f=null,u.v=null,u.p=null,u.t=null,t===c.Direction.DOWN||t===c.Direction.RIGHT?i.push(u):i.unshift(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:m,offsetY:I}=Xr(s,t),y=this._lexerTreeBuilder.moveFormulaRefOffset(S,m,I);u.si=E,u.f=y,u.v=null,u.p=null,u.t=null}t===c.Direction.DOWN||t===c.Direction.RIGHT?i.push(u):i.unshift(u)}}}return i}};qe=Zr([Ft(0,D.IAutoFillService),Ft(1,c.Inject(R.LexerTreeBuilder))],qe);function Xr(r,e){let t=0,n=0;switch(e){case c.Direction.UP:n=-r;break;case c.Direction.RIGHT:t=r;break;case c.Direction.DOWN:n=r;break;case c.Direction.LEFT:t=-r;break}return{offsetX:t,offsetY:n}}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:D.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([D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,D.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||D.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(R.LexerTreeBuilder)),Le(2,D.ISheetClipboardService),Le(3,c.Inject(c.Injector)),Le(4,c.Inject(R.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 v=$.SetRangeValuesUndoMutationFactory(o,S);return h.push({id:$.SetRangeValuesMutation.id,params:v}),{undos:h,redos:f}}function oo(r,e,t,n,o,s,i,a){return a?o.pasteType===D.PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE?io(r,e,t,n,i,a):o.pasteType===D.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 I,y;const v=s.range.rows[h%s.range.rows.length],C=s.range.cols[u%s.range.cols.length],p=t.rows[h],E=t.cols[u],m={};if(c.isFormulaString(S.f)||c.isFormulaId(S.si))m.v=S.v,m.f=null,m.si=null,m.p=null,i.setValue(p,E,m);else if((I=a==null?void 0:a[v])!=null&&I[C]){const x=a[v][C];m.v=x.v,m.f=null,m.si=null,m.p=null,i.setValue(p,E,m)}else if((y=l==null?void 0:l[p])!=null&&y[E]){if(m.v=S.v,m.f=null,m.si=null,m.p=null,S.p){const x=cn(S);x&&(m.v=x)}i.setValue(p,E,m)}}),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],v={};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),p=t.cols[f]-i.range.cols[f%i.range.cols.length],E=t.rows[d]-i.range.rows[d%i.range.rows.length],m=o.moveFormulaRefOffset(C||"",p,E);v.si=null,v.f=m}else v.si=h.si,v.f=null;v.v=null,v.p=null,a.setValue(u,S,v)}else if(c.isFormulaString(h.f)){const C=`${d%i.range.rows.length}_${f%i.range.cols.length}`;let p=l.get(C);if(p)v.si=p,v.f=null;else{p=c.Tools.generateRandomId(6),l.set(C,p);const E=t.cols[f]-i.range.cols[f%i.range.cols.length],m=t.rows[d]-i.range.rows[d%i.range.rows.length],I=o.moveFormulaRefOffset(h.f||"",E,m);v.si=p,v.f=I}v.v=null,v.p=null,a.setValue(u,S,v)}else{if(v.v=h.v,v.f=null,v.si=null,v.p=null,h.p){const C=cn(h);C&&(v.v=C)}a.setValue(u,S,v)}}),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 p;const S=t.rows[f],v=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),m=t.cols[h]-i.range.cols[h%i.range.cols.length],I=t.rows[f]-i.range.rows[f%i.range.rows.length],y=o.moveFormulaRefOffset(E||"",m,I);C.si=null,C.f=y}else C.si=u.si,C.f=null;C.v=null,C.p=null,a.setValue(S,v,C)}else if(c.isFormulaString(u.f)){const E=`${f%i.range.rows.length}_${h%i.range.cols.length}`;let m=l.get(E);if(m)C.si=m,C.f=null;else{m=c.Tools.generateRandomId(6),l.set(E,m);const I=t.cols[h]-i.range.cols[h%i.range.cols.length],y=t.rows[f]-i.range.rows[f%i.range.rows.length],x=o.moveFormulaRefOffset(u.f||"",I,y);C.si=m,C.f=x}C.v=null,C.p=null,a.setValue(S,v,C)}else(p=d==null?void 0:d[S])!=null&&p[v]&&(C.v=u.v,C.f=null,C.si=null,C.p=u.p,a.setValue(S,v,C))}),a}function cn(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();W(this,"_previousShape");W(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 v,C,p,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!==""&&((p=(C=(v=f[i])==null?void 0:v[a])==null?void 0:C[o])==null?void 0:p[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===R.SetFormulaCalculationResultMutation.id||e.id===R.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 p;if(h==null)return!0;const{startRow:u,startColumn:S,endRow:v,endColumn:C}=h;if(d===t&&f===n)return this._createArrayFormulaRangeShape(h,o),!1;if(t>=u&&t<=v&&n>=S&&n<=C){const E=i.getCell(u,S);if((E==null?void 0:E.v)===R.ErrorType.SPILL)return;const m=(p=l==null?void 0:l[d])==null?void 0:p[f];return m==null||m.f==null?!0:(a==null&&(a={f:m.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=D.attachSelectionWithCoord(a,o),{rowHeaderWidth:d,columnHeaderHeight:f}=o,h=new D.SelectionControl(s,D.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(R.FormulaDataModel)),ye(3,c.Inject(c.ThemeService)),ye(4,K.IRenderManagerService),ye(5,c.Inject(D.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},Ot=(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 sn(t,!!s)?o({...t,markers:{...t==null?void 0:t.markers,...go}}):o(t)},priority:10}))}};Ye=So([Ot(0,c.Inject($.SheetInterceptorService)),Ot(1,c.Inject(R.FormulaDataModel))],Ye);function po(){const r=c.useDependency(ge.TriggerCalculationController),e=c.useDependency(c.ICommandService),t=c.useObservable(r.progress$),n=g.useCallback(()=>{e.executeCommand(R.SetFormulaCalculationStopMutation.id)},[e]),o=g.useCallback(()=>{r.clearProgress()},[r]);return _.jsx(M.ProgressBar,{progress:t,onTerminate:n,onClearProgress:o})}const vo=(r,e=100)=>{g.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",Q={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]=g.useState(!1),[t,n]=g.useState(!0),[o,s]=g.useState(!0),[i,a]=g.useState(0),[l,d]=g.useState([0,0]),[f,h]=g.useState({left:0,top:0}),[u,S]=g.useState(null),v=c.useDependency(Me),C=c.useDependency(c.LocaleService),p=C.t("formula.prompt.required"),E=C.t("formula.prompt.optional"),m=c.useDependency(c.IUniverInstanceService),I=c.useDependency(J.IEditorService),y=c.useDependency(M.ISidebarService),x=c.useInjector();vo(b),g.useEffect(()=>{const L=v.help$.subscribe(k=>{const{visible:A,paramIndex:O,functionInfo:B}=k;if(!A){e(A);return}const w=T();if(w==null)return;const{left:U,top:H,height:j}=w;B.description===""&&B.functionParameter.length===0||(d([U,H+j]),a(O),S(B),h({left:U,top:H}),e(A))}),P=y.scrollEvent$.pipe(V.throttleTime(100)).subscribe(b);return()=>{L==null||L.unsubscribe(),P.unsubscribe()}},[]);function b(){if(!o)return;const L=T();if(L==null)return;const{left:P,top:k,height:A}=L;d([P,k+A])}function T(){const L=m.getCurrentUniverDocInstance();if(!L)return;const P=L.getUnitId();if(!I.isEditor(P))return;const k=I.getEditor(P);return k==null?void 0:k.getBoundingClientRect()}function F(L){a(L)}function N(){s(!o),x.get(M.ILayoutService).focus()}return _.jsx(_.Fragment,{children:o?_.jsx(oe.Popup,{visible:r,offset:l,children:u?_.jsxs("div",{className:Q.formulaHelpFunction,children:[_.jsxs("div",{className:Q.formulaHelpFunctionTitle,children:[_.jsx(Lo,{prefix:u.functionName,value:u.functionParameter,active:i,onClick:F}),_.jsxs("div",{className:Q.formulaHelpFunctionTitleIcons,children:[_.jsx("div",{className:Q.formulaHelpFunctionTitleIcon,style:{transform:t?"rotateZ(-90deg)":"rotateZ(90deg)"},onClick:()=>n(!t),children:_.jsx(St,{})}),_.jsx("div",{className:Q.formulaHelpFunctionTitleIcon,onClick:N,children:_.jsx(tt,{})})]})]}),_.jsx("div",{className:Q.formulaHelpFunctionContent,style:{height:t?"unset":0,padding:t?"revert-layer":0},children:_.jsxs("div",{className:Q.formulaHelpFunctionContentInner,children:[_.jsx(lt,{title:C.t("formula.prompt.helpExample"),value:`${u.functionName}(${u.functionParameter.map(L=>L.example).join(",")})`}),_.jsx(lt,{title:C.t("formula.prompt.helpAbstract"),value:u.description}),u&&u.functionParameter&&u.functionParameter.map((L,P)=>_.jsx(lt,{className:i===P?Q.formulaHelpFunctionActive:"",title:L.name,value:`${L.require?p:E} ${L.detail}`},P))]})})]}):_.jsx(_.Fragment,{})}):r?_.jsx("div",{className:Q.formulaHelpDecorator,onClick:()=>s(!o),style:{left:f.left-24,top:f.top},children:_.jsx($t,{})}):_.jsx(_.Fragment,{})})}const lt=r=>_.jsxs("div",{className:Q.formulaHelpFunctionContentParams,children:[_.jsx("div",{className:`
21
+ ${Q.formulaHelpFunctionContentParamsTitle}
22
+ ${r.className}
23
+ `,children:r.title}),_.jsx("div",{className:Q.formulaHelpFunctionContentParamsDetail,children:r.value})]}),Lo=r=>{const{prefix:e,value:t,active:n,onClick:o}=r;return _.jsxs("div",{className:Q.formulaHelpParam,children:[_.jsxs("span",{className:Q.formulaHelpParamPrefix,children:[e,"("]}),t&&t.map((s,i)=>_.jsxs("span",{className:Q.formulaHelpParamItem,children:[_.jsx("span",{className:n===i?Q.formulaHelpFunctionActive:Q.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]=g.useState(!1),[t,n]=g.useState(0),[o,s]=g.useState([0,0]),[i,a]=g.useState([]),[l,d]=g.useState(""),f=g.useRef(null),h=c.useDependency(Me),u=c.useDependency(c.IUniverInstanceService),S=c.useDependency(J.IEditorService);g.useEffect(()=>{let m=[],I=0;const y=h.search$.subscribe(T=>{const{visible:F,searchText:N,searchList:L}=T;if(!F){e(F);return}const P=v();if(P==null)return;const{left:k,top:A,height:O}=P;d(N),a(L),m=L,s([k,A+O]),e(F),n(0),I=0}),x=h.navigate$.subscribe(T=>{const{direction:F}=T;if(F===c.Direction.UP){let N=I-1;N=N<0?m.length-1:N,n(N),I=N}else if(F===c.Direction.DOWN){let N=I+1;N=N>=m.length?0:N,n(N),I=N}E(I)}),b=h.accept$.subscribe(T=>{const F=m[I].name;h.acceptFormulaName(F)});return()=>{y==null||y.unsubscribe(),x==null||x.unsubscribe(),b==null||b.unsubscribe()}},[]);function v(){const I=u.getCurrentUniverDocInstance().getUnitId();if(!S.isEditor(I))return;const y=S.getEditor(I);return y==null?void 0:y.getBoundingClientRect()}function C(m){n(m)}function p(){n(-1)}function E(m){var k;const I=(k=f.current)==null?void 0:k.querySelectorAll(`.${Re.formulaSearchFunctionItem}`)[m];if(!I)return;const y=I.parentNode;if(!y)return;const b=y.getBoundingClientRect().top,T=y.offsetHeight,F=I.getBoundingClientRect(),N=F.top,L=F.height;if(N>=0&&N>b&&N-b+L<=T)return;const P=I.offsetTop-(T-L)/2;y.scrollTo({top:P,behavior:"smooth"})}return i.length>0&&_.jsx(oe.Popup,{visible:r,offset:o,children:_.jsx("ul",{className:Re.formulaSearchFunction,ref:f,children:i.map((m,I)=>_.jsxs("li",{className:t===I?`
24
+ ${Re.formulaSearchFunctionItem}
25
+ ${Re.formulaSearchFunctionItemActive}
26
+ `:Re.formulaSearchFunctionItem,onMouseEnter:()=>C(I),onMouseLeave:p,onClick:()=>h.acceptFormulaName(m.name),children:[_.jsxs("span",{className:Re.formulaSearchFunctionItemName,children:[_.jsx("span",{className:Re.formulaSearchFunctionItemNameLight,children:m.name.substring(0,l.length)}),_.jsx("span",{children:m.name.slice(l.length)})]}),_.jsx("span",{className:Re.formulaSearchFunctionItemDesc,children:m.desc})]},I))})})}function Bo(){return _.jsxs(_.Fragment,{children:[_.jsx(Wo,{}),_.jsx(Po,{})]})}const Vo="univer-formula-more-functions",qo="univer-formula-more-functions-operation",At={formulaMoreFunctions:Vo,formulaMoreFunctionsOperation:qo};function an(r){const{prefix:e,value:t}=r;return _.jsxs("div",{children:[_.jsxs("span",{children:[e,"("]}),t&&t.map((n,o)=>_.jsxs("span",{children:[_.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",ut={formulaFunctionParams:Ko,formulaFunctionParamsTitle:zo,formulaFunctionParamsDetail:Yo};function ke(r){const{className:e,value:t,title:n}=r;return _.jsxs("div",{className:ut.formulaFunctionParams,children:[_.jsx("div",{className:`
27
+ ${ut.formulaFunctionParamsTitle}
28
+ ${e}
29
+ `,children:n}),_.jsx("div",{className:ut.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;g.useState([]);const[n,o]=g.useState(e.functionParameter),[s,i]=g.useState(-1);return _.jsxs("div",{className:we.formulaInputParams,children:[_.jsx("div",{className:we.formulaInputParamsList,children:n.map((a,l)=>_.jsxs("div",{children:[_.jsx("div",{className:we.formulaInputParamsListItemName,children:a.name}),_.jsx("div",{className:we.formulaInputParamsListItemSelector})]},l))}),_.jsx("div",{className:we.formulaInputParamsInfo,children:_.jsx(ke,{title:s===-1?_.jsx(an,{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",me={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]=g.useState(""),[s,i]=g.useState([]),[a,l]=g.useState(0),[d,f]=g.useState(t),[h,u]=g.useState(0),[S,v]=g.useState(null),C=c.useDependency(ge.IDescriptionService),p=c.useDependency(c.LocaleService),E=c.useDependency(M.ISidebarService),m=c.useObservable(E.sidebarOptions$),I=Jn(R.FunctionType,p);I.unshift({label:p.t("formula.moreFunctions.allFunctions"),value:t});const y=p.t("formula.prompt.required"),x=p.t("formula.prompt.optional");g.useEffect(()=>{F(t)},[]),g.useEffect(()=>{T(0)},[s]),g.useEffect(()=>{m!=null&&m.visible&&(o(""),i([]),l(0),f(t),u(0),v(null),F(t))},[m]);const b=A=>{if(n.trim()==="")return A;const O=new RegExp(`(${n.toLocaleUpperCase()})`);return A.split(O).filter(Boolean).map((w,U)=>w.match(O)?_.jsx("span",{className:me.formulaSelectFunctionResultItemNameLight,children:w},U):w)},T=A=>{if(s.length===0){v(null);return}u(A);const O=C.getFunctionInfo(s[A].name);if(!O){v(null);return}v(O),e(O)};function F(A){f(A);const O=C.getSearchListByType(+A);i(O)}function N(A){o(A);const O=C.getSearchListByName(A);i(O)}function L(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 P=A=>{l(A)},k=()=>{l(-1)};return _.jsxs("div",{children:[_.jsxs("div",{className:me.formulaSelectFunctionSelect,children:[_.jsx(oe.Select,{value:d,options:I,onChange:F}),_.jsx(oe.Input,{placeholder:p.t("formula.moreFunctions.searchFunctionPlaceholder"),onKeyDown:L,value:n,onChange:N,size:"large",allowClear:!0})]}),_.jsx("ul",{className:me.formulaSelectFunctionResult,onKeyDown:L,tabIndex:-1,children:s.map(({name:A},O)=>_.jsxs("li",{className:a===O?`
30
+ ${me.formulaSelectFunctionResultItem}
31
+ ${me.formulaSelectFunctionResultItemActive}
32
+ `:me.formulaSelectFunctionResultItem,onMouseEnter:()=>P(O),onMouseLeave:k,onClick:()=>T(O),children:[h===O&&_.jsx(kt,{className:me.formulaSelectFunctionResultItemSelected}),_.jsx("span",{className:me.formulaSelectFunctionResultItemName,children:b(A)})]},O))}),S&&_.jsxs("div",{className:me.formulaSelectFunctionContent,children:[_.jsx(ke,{title:S.functionName,value:S.description}),_.jsx(ke,{title:p.t("formula.moreFunctions.syntax"),value:_.jsx(an,{prefix:S.functionName,value:S.functionParameter})}),_.jsx(ke,{title:p.t("formula.prompt.helpExample"),value:`${S.functionName}(${S.functionParameter.map(A=>A.example).join(",")})`}),S.functionParameter&&S.functionParameter.map((A,O)=>_.jsx(ke,{title:A.name,value:`${A.require?y:x} ${A.detail}`},O))]})]})}function cs(){const r=D.useActiveWorkbook(),[e,t]=g.useState(!0),[n,o]=g.useState(!1),[s,i]=g.useState(null),a=c.useDependency(c.LocaleService),l=c.useDependency(J.IEditorService);function d(){t(!e),o(!n)}function f(){l.setFormula(`=${s==null?void 0:s.functionName}(`)}return _.jsxs("div",{className:At.formulaMoreFunctions,children:[e&&_.jsx(is,{onChange:i}),n&&_.jsx(Qo,{functionInfo:s,onChange:()=>{}}),_.jsxs("div",{className:At.formulaMoreFunctionsOperation,children:[n&&_.jsx(oe.Button,{type:"primary",size:"small",onClick:d,children:a.t("formula.moreFunctions.next")}),n&&_.jsx(oe.Button,{size:"small",onClick:d,children:a.t("formula.moreFunctions.prev")}),e&&!!r&&_.jsx(oe.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:M.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$:M.getMenuHiddenObservable(r,c.UniverInstanceType.UNIVER_SHEET),disabled$:D.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],worksheetTypes:[$.WorksheetEditPermission,$.WorksheetSetCellValuePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint]})}}function ls(r){return{id:Je.id,title:"formula.insert.more",type:M.MenuItemType.BUTTON}}function us(r){return r.get(c.IUniverInstanceService).getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_SHEET).pipe(V.switchMap(n=>n&&r.get(M.IClipboardInterfaceService)?new V.Observable(s=>s.next(!r.get(M.IClipboardInterfaceService).supportClipboard)):V.of(!0)))}function ds(r){return{id:Xe.id,type:M.MenuItemType.BUTTON,title:"formula.operation.pasteFormula",disabled$:us(r).pipe(V.combineLatestWith(D.getCurrentRangeDisable$(r,{workbookTypes:[$.WorkbookEditablePermission],rangeTypes:[$.RangeProtectionPermissionEditPoint],worksheetTypes:[$.WorksheetSetCellValuePermission,$.WorksheetEditPermission]})),V.map(([e,t])=>e||t))}}const hs={[M.RibbonStartGroup.FORMULAS_INSERT]:{[Qe.id]:{order:1,menuItemFactory:as,[Je.id]:{order:1,menuItemFactory:ls}}},[D.PASTE_SPECIAL_MENU_ID]:{[Xe.id]:{order:4,menuItemFactory:ds}}},ln="meta_key_ctrl_And_Shift",rt=[M.KeyCode.ARROW_DOWN,M.KeyCode.ARROW_UP,M.KeyCode.ARROW_LEFT,M.KeyCode.ARROW_RIGHT],fs=[...rt,M.KeyCode.ENTER,M.KeyCode.TAB,M.KeyCode.ESC];function ms(){const r=[];for(const e of fs)r.push({id:Ie.id,binding:e,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e}});return r}function Ss(){const r=[];for(const e of rt)r.push({id:Ie.id,binding:e|M.MetaKeys.SHIFT,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,metaKey:M.MetaKeys.SHIFT}});return r}function gs(){const r=[];for(const e of rt)r.push({id:Ie.id,binding:e|M.MetaKeys.CTRL_COMMAND,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,metaKey:M.MetaKeys.CTRL_COMMAND}});return r}function ps(){const r=[];for(const e of rt)r.push({id:Ie.id,binding:e|M.MetaKeys.SHIFT|M.MetaKeys.CTRL_COMMAND,preconditions:t=>D.whenFormulaEditorActivated(t),staticParameters:{eventType:K.DeviceInputEventType.Keyboard,keycode:e,metaKey:ln}});return r}const vs={id:et.id,binding:M.KeyCode.F4,preconditions:r=>D.whenFormulaEditorActivated(r)};function _s(){const r=[];for(const e of[M.KeyCode.ENTER,M.KeyCode.TAB,M.KeyCode.ARROW_DOWN,M.KeyCode.ARROW_UP])r.push({id:Ie.id,binding:e,preconditions:t=>Br(t),staticParameters:{eventType:K.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(M.BuiltInUIPart.CONTENT,()=>c.connectInjector(Bo,this._injector))),this.disposeWithMe(this._uiPartsService.registerComponent(D.SheetsUIPart.FORMULA_AUX,()=>c.connectInjector(po,this._injector))),this._componentManager.register(Lt,cs)}_registerRenderModules(){this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,[ze]))}};Ge=Is([Te(0,c.Inject(c.Injector)),Te(1,M.IMenuManagerService),Te(2,c.ICommandService),Te(3,M.IShortcutService),Te(4,M.IUIPartsService),Te(5,K.IRenderManagerService),Te(6,c.Inject(M.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},re=(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,v,C){super();W(this,"_listenInputCache",new Set);W(this,"_formulaRefColors",[]);W(this,"_previousSequenceNodes");W(this,"_previousRangesCount",0);W(this,"_previousInsertRefStringIndex");W(this,"_currentInsertRefStringIndex",-1);W(this,"_arrowMoveActionState",0);W(this,"_isSelectionMovingRefSelections",[]);W(this,"_stringColor","");W(this,"_numberColor","");W(this,"_insertSelections",[]);W(this,"_inputPanelState",0);W(this,"_userCursorMove",!1);W(this,"_previousEditorUnitId");W(this,"_existsSequenceNode",!1);W(this,"_currentlyWorkingRefRenderer",null);W(this,"_selectionsChangeDisposables");W(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=v,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(V.filter(e=>!D.isRangeSelector(e.unitId)&&!D.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=[M.KeyCode.ARROW_DOWN,M.KeyCode.ARROW_UP,M.KeyCode.ARROW_LEFT,M.KeyCode.ARROW_RIGHT,M.KeyCode.CTRL,M.KeyCode.SHIFT];this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(V.filter(t=>{const n=(t==null?void 0:t.getUnitId())||"";return!D.isRangeSelector(n)&&!D.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(J.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!==M.KeyCode.F4&&(this._userCursorMove=!1))})),this._listenInputCache.add(n)})}_closeRangePromptWhenEditorInvisible(){this.disposeWithMe(this._editorBridgeService.afterVisible$.pipe(V.distinctUntilKeyChanged("visible")).subscribe(e=>{e.visible||this._closeRangePrompt()})),this.disposeWithMe(this._contextService.subscribeContextValue$(c.FORMULA_EDITOR_ACTIVATED).pipe(V.distinctUntilChanged()).subscribe(e=>{e||this._closeRangePrompt()}))}_initialChangeEditor(){this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(c.UniverInstanceType.UNIVER_DOC).pipe(V.filter(e=>{const t=(e==null?void 0:e.getUnitId())||"";return!D.isRangeSelector(t)&&!D.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())||"";D.isRangeSelector(t)||D.isEmbeddingFormulaEditor(t)||t===c.DOCS_ZEN_EDITOR_UNIT_ID_KEY||(this._insertSelections=[],this._refSelectionsService.clear(),e&&this._editorService.isSheetEditor(e)&&this._updateEditorModel(`\r
33
+ `,[]),this._contextService.setContextValue(c.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue($.DISABLE_NORMAL_SELECTIONS,!1),this._contextService.setContextValue(M.UNI_DISABLE_CHANGING_FOCUS_KEY,!1),this._quitSelectingMode(),this._resetTemp(),this._hideFunctionPanel())}_initSelectionsEndListener(){const e=new c.DisposableCollection;this.disposeWithMe(this._refSelectionsService.selectionMoveEnd$.subscribe(t=>{var s;if(e.dispose(),t.length===0)return;const n=((s=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_DOC))==null?void 0:s.getUnitId())||"";if(D.isRangeSelector(n)||D.isEmbeddingFormulaEditor(n))return;this._allSelectionRenderServices.map(i=>i.getSelectionControls()).flat().forEach(i=>{i.disableHelperSelection(),e.add(V.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(D.isRangeSelector(l)||D.isEmbeddingFormulaEditor(l)){e.dispose(),this._formulaPromptService.disableLockedSelectionChange();return}this._onSelectionControlChange(a,i)})),e.add(V.merge(i.selectionMoved$,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,!R.matchRefDrawToken(o)&&this._focusIsOnlyRange(e.length)&&(this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex,R.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,R.matchToken.OPEN_BRACKET);for(let v=s+2,C=o.length;v<C;v++){const p=o[v];if(typeof p=="string")continue;const E={...p};E.startIndex+=h,E.endIndex+=h,o[v]=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===R.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&&R.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:R.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($.DISABLE_NORMAL_SELECTIONS,!0),this._contextService.setContextValue(M.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($.DISABLE_NORMAL_SELECTIONS,!1),this._contextService.setContextValue(M.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(this._refSelectionsService.clear(),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:v}=f;let C="";if(S===R.sequenceNodeType.REFERENCE){if(o.has(v))C=o.get(v);else{const p=s%this._formulaRefColors.length;C=this._formulaRefColors[p],o.set(v,C),s++}n.push({refIndex:l,themeColor:C,token:v})}else S===R.sequenceNodeType.NUMBER?C=this._numberColor:S===R.sequenceNodeType.STRING?C=this._stringColor:S===R.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 v=t[u],{themeColor:C,token:p,refIndex:E}=v,m=R.deserializeRangeWithSheet(p),{unitId:I,sheetName:y,range:x}=m,b=$.setEndForRange(x,d.getRowCount(),d.getColumnCount());if(I!=null&&I.length>0&&n!==I)continue;const T=this._getSheetIdByName(n,y.trim());if(!a&&T!==i||a&&y.length!==0&&T!==o||this._exceedCurrentRange(b,d.getRowCount(),d.getColumnCount()))continue;const F=this._getPrimary(b,C,E);if(F){f=F,h.push(f);continue}const N=$.getPrimaryForRange(b,d);!c.Rectangle.equals(N,b)&&b.startRow===b.endRow&&b.startColumn===b.endColumn&&(b.startRow=N.startRow,b.endRow=N.endRow,b.startColumn=N.startColumn,b.endColumn=N.endColumn),h.push({range:b,primary:N,style:$e(this._themeService,C,E.toString())})}h.length&&this._refSelectionsService.addSelections(n,o,h)}_getPrimary(e,t,n){const o=this._insertSelections.find(h=>{const{startRow:u,startColumn:S,endRow:v,endColumn:C}=h.range;return u===e.startRow&&S===e.startColumn&&v===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(R.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(D.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:v,endAbsoluteRefType:C,rangeType:p}=l;if(d){const{isMerged:E,isMergedMainCell:m,startRow:I,endRow:y,startColumn:x,endColumn:b}=d;(E||m)&&I===f&&x===u&&y===h&&b===S&&(f=I,u=x,h=I,S=x)}return R.serializeRangeToRefString({sheetName:n,unitId:t,range:{startRow:f,endRow:h,startColumn:u,endColumn:S,rangeType:p,startAbsoluteRefType:v,endAbsoluteRefType:C}})}_syncToEditor(e,t,n,o=!0,s=!0){let i=R.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=`${R.compareToken.EQUALS}${i}`,u=0);const{collapsed:S,style:v}=d;o?(this._commandService.executeCommand(J.ReplaceContentCommand.id,{unitId:n,body:{dataStream:h,textRuns:a},textRanges:[{startOffset:t+1-u,endOffset:t+1-u,collapsed:S,style:v}],segmentId:null,options:{fromSelection:s}}),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:v}],!0,{fromSelection:s})):(this._updateEditorModel(`${h}\r
34
+ `,a),this._docSelectionManagerService.replaceTextRanges([{startOffset:t+1-u,endOffset:t+1-u,style:v}],!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(D.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 n=this._generateRefString(e);this._formulaPromptService.setSequenceNodes(t),this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex,n),this._syncToEditor(t,this._previousInsertRefStringIndex+n.length);const o=this._selectionRenderService.getSelectionDataWithStyle()||[];this._insertSelections=[];const s=o[o.length-1];if(s){const i=$.convertSelectionDataToRange(s);this._insertSelections.push(i)}}_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=R.deserializeRangeWithSheet(u),{unitId:v,sheetName:C,range:p}=S;if(!v&&v.length>0&&o!==v)continue;const E=this._getSheetIdByName(o,C.trim());if(E&&E!==s)continue;const m=n.find(I=>{const{startRow:y,startColumn:x,endRow:b,endColumn:T,rangeType:F}=I.getRange();return F===c.RANGE_TYPE.COLUMN&&x===p.startColumn&&T===p.endColumn||F===c.RANGE_TYPE.ROW&&y===p.startRow&&b===p.endRow||y===p.startRow&&x===p.startColumn&&b===p.endRow&&T===p.endColumn||y===p.startRow&&x===p.startColumn&&p.startRow===p.endRow&&p.startColumn===p.endColumn});if(m){const I=$e(this._themeService,h,f.toString());m.updateStyle(I),i.add(m)}}}_onSelectionControlChange(e,t){var m;const{skeleton:n}=this._getCurrentUnitIdAndSheetId();if(!n)return;this._formulaPromptService.enableLockedSelectionChange();const o=(m=t.currentStyle)==null?void 0:m.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:I,isMergedMainCell:y,startRow:x,endRow:b,startColumn:T,endColumn:F}=d;(I||y)&&x===s&&T===a&&b===i&&F===l&&(s=x,a=T,i=x,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 I=h.token;u=R.getAbsoluteRefTypeWitString(I),u.endAbsoluteRefType==null&&(u.endAbsoluteRefType=u.startAbsoluteRefType)}const S=n==null?void 0:n.worksheet.getUnitId(),v=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:v,unitId:S},primary:d,style:null});this._formulaPromptService.updateSequenceRef(f,C);const p=this._formulaPromptService.getSequenceNodes(),E=p[f];typeof E!="string"&&(this._syncToEditor(p,E.endIndex+1),t.updateRange(e,this._selectionRenderService.attachPrimaryWithCoord(d)))}_refreshFormulaAndCellEditor(e){var t;for(const n of e){const o=D.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:K.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:K.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:K.DeviceInputEventType.Keyboard,keycode:t,unitId:""})}_pressArrowKey(e){const{keycode:t,metaKey:n}=e;let o=c.Direction.DOWN;t===M.KeyCode.ARROW_DOWN?o=c.Direction.DOWN:t===M.KeyCode.ARROW_UP?o=c.Direction.UP:t===M.KeyCode.ARROW_LEFT?o=c.Direction.LEFT:t===M.KeyCode.ARROW_RIGHT&&(o=c.Direction.RIGHT),n===M.MetaKeys.CTRL_COMMAND?this._commandService.executeCommand(D.MoveSelectionCommand.id,{direction:o,jumpOver:D.JumpOver.moveGap}):n===M.MetaKeys.SHIFT?this._commandService.executeCommand(D.ExpandSelectionCommand.id,{direction:o}):n===ln?this._commandService.executeCommand(D.ExpandSelectionCommand.id,{direction:o,jumpOver:D.JumpOver.moveGap}):this._commandService.executeCommand(D.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(!(D.isRangeSelector(o)||D.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===M.KeyCode.ENTER){this._pressEnter(s);return}if(i===M.KeyCode.TAB){this._pressTab(s);return}if(i===M.KeyCode.ESC){this._pressEsc(s);return}if(this._formulaPromptService.isSearching()){if(i===M.KeyCode.ARROW_DOWN){this._formulaPromptService.navigate({direction:c.Direction.DOWN});return}if(i===M.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:K.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.addSelections([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===M.KeyCode.ARROW_DOWN?t=c.Direction.DOWN:e===M.KeyCode.ARROW_UP?t=c.Direction.UP:e===M.KeyCode.ARROW_RIGHT&&(t=c.Direction.RIGHT),this._commandService.executeCommand(J.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)!==R.compareToken.EQUALS)return;const{unitId:o}=this._getCurrentUnitIdAndSheetId();this._editorBridgeService.isVisible().visible===!1&&this._editorBridgeService.changeVisible({visible:!0,eventType:K.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!==R.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(R.matchToken.COLON)>-1)if(!this._userCursorMove)d=this._changeRangeRef(a);else{const h=a.split(R.matchToken.COLON),u=h[0],S=h[1];n-s.startIndex<=u.length?d=this._changeSingleRef(u)+R.matchToken.COLON+S:d=u+R.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=R.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=R.serializeRange(t),n}_changeSingleRef(e){const t=R.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=R.serializeRange(t),o}_getEditorObject(){const e=this._univerInstanceService.getCurrentUniverDocInstance().getUnitId(),t=this._editorService.getEditor(e);return t==null?void 0:t.render}_isFormulaEditorActivated(){return this._editorBridgeService.isVisible().visible===!0||this._contextService.getContextValue(c.FORMULA_EDITOR_ACTIVATED)}_isSheetOrFormulaEditor(e){return e.isSheetEditor()||e.isFormulaEditor()}};Ze=Ts([re(0,c.ICommandService),re(1,c.IContextService),re(2,c.Inject(D.IEditorBridgeService)),re(3,c.Inject(Me)),re(4,c.Inject(R.LexerTreeBuilder)),re(5,K.IRenderManagerService),re(6,c.Inject(c.ThemeService)),re(7,c.Inject($.SheetsSelectionsService)),re(8,$.IRefSelectionsService),re(9,c.IUniverInstanceService),re(10,c.Inject(ge.IDescriptionService)),re(11,c.Inject(je.DocSelectionManagerService)),re(12,M.IContextMenuService),re(13,J.IEditorService),re(14,M.ILayoutService)],Ze);var un=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,xs=(r,e,t)=>e in r?un(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&&un(e,t,o),o},dt=(r,e)=>(t,n)=>e(t,n,r),dn=(r,e,t)=>xs(r,typeof e!="symbol"?e+"":e,t);exports.UniverSheetsFormulaUIPlugin=class extends c.Plugin{constructor(e=Wr,t,n,o){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=o;const{menu:s,...i}=this._config;s&&this._configService.setConfig("menu",s,{merge:!0}),this._configService.setConfig(Hr,i)}onStarting(){const e=this._injector;[[Me,{useClass:ht}],[Ge],[qe],[Ke],[ze],[Ye],[Ze]].forEach(n=>e.add(n))}onRendered(){[[exports.RefSelectionsRenderService],[mt]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(c.UniverInstanceType.UNIVER_SHEET,t))}),c.touchDependencies(this._injector,[[Ge],[Ke],[Ye]]);const e=this._injector.get(M.ComponentManager);e.register(D.RANGE_SELECTOR_COMPONENT_KEY,rn),e.register(D.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,on)}onSteady(){this._injector.get(qe),this._injector.get(Ze)}};dn(exports.UniverSheetsFormulaUIPlugin,"pluginName",Pt);dn(exports.UniverSheetsFormulaUIPlugin,"type",c.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=Ms([c.DependentOn(R.UniverFormulaEnginePlugin,ge.UniverSheetsFormulaPlugin),dt(1,c.Inject(c.Injector)),dt(2,K.IRenderManagerService),dt(3,c.IConfigService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=Dt;exports.FormulaEditor=on;exports.HelpFunctionOperation=He;exports.InsertFunctionOperation=Qe;exports.MoreFunctionsOperation=Je;exports.RangeSelector=rn;exports.ReferenceAbsoluteOperation=et;exports.SearchFunctionOperation=Be;exports.SelectEditorFormulaOperation=Ie;exports.SheetOnlyPasteFormulaCommand=Xe;