@univerjs/sheets-formula-ui 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -2,4 +2,4 @@
2
2
  `,d=Math.max(c.length-2,0);e.setSelectionRanges([{startOffset:d,endOffset:d}])}else e.setSelectionRanges(i)}})};function kr(e){var r,o;const n=e.get(a.IUniverInstanceService).getCurrentUniverDocInstance();return n!=null&&n.getBody()?{dataStream:(o=(r=n.getBody())==null?void 0:r.dataStream)!=null?o:"",offset:0}:void 0}var me=(e=>(e[e.NOT_SELECT=0]="NOT_SELECT",e[e.NEED_ADD=1]="NEED_ADD",e[e.CAN_EDIT=2]="CAN_EDIT",e[e.EDIT_OTHER_SHEET_REFERENCE=3]="EDIT_OTHER_SHEET_REFERENCE",e[e.EDIT_OTHER_WORKBOOK_REFERENCE=4]="EDIT_OTHER_WORKBOOK_REFERENCE",e))(me||{});function wr(e){var k;const{editorId:t,isFocus:n,disableOnClick:s,unitId:r,subUnitId:o}=e,i=l.useDependency(B.IRenderManagerService),c=l.useDependency(a.IUniverInstanceService),d=i.getRenderById(r),h=i.getRenderById(t),m=h==null?void 0:h.with(Q.DocSelectionRenderService),p=l.useDependency(Dt.DocSelectionManagerService),f=l.useDependency(a.Injector),[g,u]=I.useState(0),v=l.useDependency(b.LexerTreeBuilder),C=I.useRef(!0),_=d==null?void 0:d.with(exports.RefSelectionsRenderService),R=Me(g),y=c.getUnit(r,a.UniverInstanceType.UNIVER_SHEET),O=y==null?void 0:y.getSheetBySheetId(o),S=l.useEvent(U=>{_&&_.setSkipLastEnabled(U===1||U===3||U===4),R.current=U,u(U)}),x=l.useEvent(()=>{var re,se,ie;const U=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!U)return;const $=U.getActiveSheet(),A=m==null?void 0:m.getActiveTextRange(),L=A!=null&&A.collapsed?A.startOffset:-1,w=kr(f);if(!w)return;const M=(re=w==null?void 0:w.dataStream)==null?void 0:re.slice(0,-2),P=((se=v.sequenceNodesBuilder(M))!=null?se:[]).map(z=>typeof z=="object"?z.nodeType===b.sequenceNodeType.REFERENCE?{...z,range:b.deserializeRangeWithSheetWithCache(z.token)}:{...z,range:void 0}:z),T=M[L-1],D=M[L],j=P.find(z=>typeof z=="object"&&z.nodeType===b.sequenceNodeType.REFERENCE&&L===z.endIndex+2),W=T&&b.matchRefDrawToken(T)&&(!D||b.isFormulaLexerToken(D)&&D!==b.matchToken.OPEN_BRACKET),H=!!j;if((M==null?void 0:M.substring(0,1))==="="&&(W||H))if(H){if(C.current)return;const{sheetName:z,unitId:X}=j.range,Oe=(ie=c.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:ie.getUnitId();X&&X!==Oe?S(4):!z&&$.getSheetId()===(O==null?void 0:O.getSheetId())||z===$.getName()?S(2):S(3)}else C.current=!1,S(1);else S(0)});return I.useEffect(()=>{const U=p.textSelection$.pipe(q.filter($=>$.unitId===t)).subscribe(()=>{x()});return()=>U.unsubscribe()},[x,p.textSelection$,t]),I.useEffect(()=>{n||(S(0),C.current=!0)},[n,S]),I.useEffect(()=>{var $;if(!s)return;const U=($=h==null?void 0:h.mainComponent)==null?void 0:$.onPointerDown$.subscribeEvent(()=>{S(0),C.current=!0});return()=>U==null?void 0:U.unsubscribe()},[s,(k=h==null?void 0:h.mainComponent)==null?void 0:k.onPointerDown$,S]),I.useEffect(()=>{if(!n)return;const U=y==null?void 0:y.activeSheet$.subscribe(()=>{x()}),$=c.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>{x()});return()=>{U==null||U.unsubscribe(),$==null||$.unsubscribe()}},[x,n,y==null?void 0:y.activeSheet$,c.getCurrentTypeOfUnit$]),{isSelecting:g,isSelectingRef:R}}const Ar=()=>{const e=l.useDependency(b.LexerTreeBuilder);return I.useCallback(n=>e.sequenceNodesBuilder(n)||[],[e])};function Fr(e,t,n){const s=new a.ColorKit(t).setAlpha(.05).toRgbString();return{id:n,strokeWidth:1,stroke:t,fill:s,widgets:{tl:!0,tc:!0,tr:!0,ml:!0,mr:!0,bl:!0,bc:!0,br:!0},widgetSize:6,widgetStrokeWidth:1,widgetStroke:e.getColorFromTheme("white")}}function Zt(e){var y,O,S;const{unitId:t,subUnitId:n,currentWorkbook:s,refSelections:r,editor:o,refSelectionsService:i,refSelectionsRenderService:c,sheetSkeletonManagerService:d,themeService:h,univerInstanceService:m}=e,p=s.getUnitId(),f=m.getUnit(t,a.UniverInstanceType.UNIVER_SHEET),g=f==null?void 0:f.getActiveSheet(),u=[];if(!f||!g){i.setSelections(u);return}const v=g.getSheetId(),C=x=>{var k;return(k=f==null?void 0:f.getSheetBySheetName(x))==null?void 0:k.getSheetId()};if(!((y=d==null?void 0:d.getWorksheetSkeleton(v))==null?void 0:y.skeleton))return;const R=[];for(let x=0,k=r.length;x<k;x++){const U=r[x],{themeColor:$,token:A,refIndex:L,endIndex:w}=U,M=b.deserializeRangeWithSheet(A),{unitId:P,sheetName:T,range:D}=M,j=C(T);if(!j&&T||p!==t&&P!==p||P&&P!==p||j&&j!==v||!j&&v!==n)continue;const W=F.setEndForRange(D,g.getRowCount(),g.getColumnCount());W.unitId=t,W.sheetId=v,u.push({range:W,primary:null,style:Fr(h,$,L.toString())}),R.push(w)}if(o){const x=(S=(O=o.getSelectionRanges())==null?void 0:O[0])==null?void 0:S.startOffset,k=R.findIndex(U=>U+2===x);k!==-1?c==null||c.setActiveSelectionIndex(k):c==null||c.resetActiveSelectionIndex()}return u}function Pr(e,t){const n=l.useDependency(a.IUniverInstanceService),s=l.useDependency(a.ThemeService),r=l.useDependency(F.IRefSelectionsService),o=l.useDependency(B.IRenderManagerService),i=l.useObservable(I.useMemo(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[n])),c=i?o.getRenderById(i.getUnitId()):null,d=c==null?void 0:c.with(exports.RefSelectionsRenderService),h=c==null?void 0:c.with(N.SheetSkeletonManagerService),m=l.useEvent((p,f)=>{const g=n.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_SHEET);if(!g||d!=null&&d.selectionMoving)return;const u=Zt({unitId:e,subUnitId:t,currentWorkbook:g,refSelections:p,editor:f,refSelectionsService:r,refSelectionsRenderService:d,sheetSkeletonManagerService:h,themeService:s,univerInstanceService:n});if(!u)return;((d==null?void 0:d.getSelectionControls())||[]).length===u.length?d==null||d.resetSelectionsByModelData(u):r.setSelections(u)});return I.useEffect(()=>()=>{d==null||d.resetActiveSelectionIndex()},[d]),m}function Xt(e=""){const t=l.useDependency(pe.IDescriptionService),n=Lr(),s=l.useDependency(a.ICommandService),r=I.useMemo(()=>e.length,[e]);return l.useEvent((i,c,d=!0,h)=>{const m=i.getDocumentData(),p=i.getEditorId();if(!m)return[];const f=m.body;if(!f)return[];const g=f.dataStream.slice(0,f.dataStream.length-2),u={dataStream:"",...m.body};if(!g.startsWith(e))return[];if(c==null||c.length===0)return u.textRuns=[],s.syncExecuteCommand(Q.ReplaceTextRunsCommand.id,{unitId:p,body:a.getBodySlice(u,0,u.dataStream.length-2)}),[];{const{textRuns:v,refSelections:C}=Ur(t,n,c);r&&v.forEach(y=>{y.ed=y.ed+r,y.st=y.st+r}),u.textRuns=[{st:0,ed:1,ts:{fs:11}},...v];const _=c.reduce((y,O)=>typeof O=="string"?`${y}${O}`:`${y}${O.token}`,"");u.dataStream=`${e}${_}\r
3
3
  `;let R;if(d){R=i.getSelectionRanges();const y=u.dataStream.length-2+r;R.forEach(O=>{O.startOffset=Math.max(0,Math.min(O.startOffset,y)),O.endOffset=Math.max(0,Math.min(O.endOffset,y))})}return s.syncExecuteCommand(Q.ReplaceTextRunsCommand.id,{unitId:p,body:a.getBodySlice(u,0,u.dataStream.length-2),textRanges:h!=null?h:R}),C}})}function Lr(){const e=l.useDependency(a.ThemeService),t=e.getCurrentTheme();return I.useMemo(()=>{const s=[e.getColorFromTheme("loop-color.1"),e.getColorFromTheme("loop-color.2"),e.getColorFromTheme("loop-color.3"),e.getColorFromTheme("loop-color.4"),e.getColorFromTheme("loop-color.5"),e.getColorFromTheme("loop-color.6"),e.getColorFromTheme("loop-color.7"),e.getColorFromTheme("loop-color.8"),e.getColorFromTheme("loop-color.9"),e.getColorFromTheme("loop-color.10"),e.getColorFromTheme("loop-color.11"),e.getColorFromTheme("loop-color.12")].map(c=>e.isValidThemeColor(c)?e.getColorFromTheme(c):c),r=e.getColorFromTheme("blue.700"),o=e.getColorFromTheme("jiqing.800"),i=e.getColorFromTheme("black");return{formulaRefColors:s,numberColor:r,stringColor:o,plainTextColor:i}},[t])}function Ur(e,t,n){const{formulaRefColors:s,numberColor:r,stringColor:o,plainTextColor:i}=t,c=[],d=[],h=new Map;let m=0;for(let p=0,f=n.length;p<f;p++){const g=n[p];if(typeof g=="string"){const y=c[c.length-1],O=y?y.ed:0,S=O+g.length;c.push({st:O,ed:S,ts:{cl:{rgb:i},fs:11}});continue}if(e.hasDefinedNameDescription(g.token.trim())){c.push({st:g.startIndex,ed:g.endIndex+1,ts:{cl:{rgb:i},fs:11}});continue}const{startIndex:u,endIndex:v,nodeType:C,token:_}=g;let R="";if(C===b.sequenceNodeType.REFERENCE){if(h.has(_))R=h.get(_);else{const y=m%s.length;R=s[y],h.set(_,R),m++}d.push({refIndex:p,themeColor:R,token:_,startIndex:g.startIndex,endIndex:g.endIndex,index:d.length})}else C===b.sequenceNodeType.NUMBER?R=r:(C===b.sequenceNodeType.STRING||C===b.sequenceNodeType.ARRAY)&&(R=o);R&&R.length>0?c.push({st:u,ed:v+1,ts:{cl:{rgb:R},fs:11}}):c.push({st:u,ed:v+1,ts:{cl:{rgb:i},fs:11}})}return{textRuns:c,refSelections:d}}const $r=(e,t,n,s)=>{const r=l.useDependency(a.ICommandService),o=l.useDependency(l.IShortcutService),i=I.useRef(t);i.current=t;const c=I.useRef(s);c.current=s,I.useEffect(()=>{if(!n||!e)return;const h=`sheet.formula-embedding-editor.${n.getEditorId()}`,m=new a.DisposableCollection,p=(u,v)=>{if(c.current){c.current(u,v);return}let C=a.Direction.LEFT;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),v===l.MetaKeys.SHIFT?r.executeCommand(Q.MoveSelectionOperation.id,{direction:C}):r.executeCommand(Q.MoveCursorOperation.id,{direction:C})},f=(u,v)=>{let C=a.Direction.DOWN;u===l.KeyCode.ARROW_DOWN?C=a.Direction.DOWN:u===l.KeyCode.ARROW_UP?C=a.Direction.UP:u===l.KeyCode.ARROW_LEFT?C=a.Direction.LEFT:u===l.KeyCode.ARROW_RIGHT&&(C=a.Direction.RIGHT),i.current?v===l.MetaKeys.CTRL_COMMAND?r.executeCommand(N.MoveSelectionCommand.id,{direction:C,jumpOver:N.JumpOver.moveGap,extra:"formula-editor",fromCurrentSelection:i.current===me.NEED_ADD||i.current===me.EDIT_OTHER_SHEET_REFERENCE}):v===l.MetaKeys.SHIFT?r.executeCommand(N.ExpandSelectionCommand.id,{direction:C,extra:"formula-editor"}):v===(l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT)?r.executeCommand(N.ExpandSelectionCommand.id,{direction:C,jumpOver:N.JumpOver.moveGap,extra:"formula-editor"}):r.executeCommand(N.MoveSelectionCommand.id,{direction:C,extra:"formula-editor",fromCurrentSelection:i.current===me.NEED_ADD||i.current===me.EDIT_OTHER_SHEET_REFERENCE}):p(u,v)};return m.add(r.registerCommand({id:h,type:a.CommandType.OPERATION,handler(u,v){const{keyCode:C,metaKey:_}=v;f(C,_)}})),[{keyCode:l.KeyCode.ARROW_DOWN},{keyCode:l.KeyCode.ARROW_LEFT},{keyCode:l.KeyCode.ARROW_RIGHT},{keyCode:l.KeyCode.ARROW_UP},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND},{keyCode:l.KeyCode.ARROW_DOWN,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_LEFT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_RIGHT,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT},{keyCode:l.KeyCode.ARROW_UP,metaKey:l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT}].map(({keyCode:u,metaKey:v})=>({id:h,binding:v?u|v:u,preconditions:()=>!0,priority:900,staticParameters:{eventType:B.DeviceInputEventType.Keyboard,keyCode:u,metaKey:v}})).forEach(u=>{m.add(o.registerShortcut(u))}),()=>{m.dispose()}},[r,n,e,o])},jr=(e,t,n,s,r=!0)=>{var g;const o=l.useDependency(B.IRenderManagerService),i=l.useDependency(a.IContextService),c=l.useDependency(l.IContextMenuService),d=l.useDependency(F.IRefSelectionsService),h=l.useDependency(a.IUniverInstanceService),m=l.useObservable(I.useMemo(()=>h.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[h])),p=o.getRenderById((g=m==null?void 0:m.getUnitId())!=null?g:""),f=p==null?void 0:p.with(exports.RefSelectionsRenderService);I.useLayoutEffect(()=>{if(e)return i.setContextValue(a.EDITOR_ACTIVATED,!0),r&&c.disable(),()=>{const u=h.getCurrentUnitOfType(a.UniverInstanceType.UNIVER_DOC);(u==null?void 0:u.getUnitId())===s&&i.setContextValue(a.EDITOR_ACTIVATED,!1),r&&c.enable(),d.clear()}},[i,e,d,r,s]),I.useLayoutEffect(()=>{if(e&&t){const u=f==null?void 0:f.enableSelectionChanging();return i.setContextValue(F.REF_SELECTIONS_ENABLED,!0),()=>{i.setContextValue(F.REF_SELECTIONS_ENABLED,!1),u==null||u.dispose()}}},[i,e,f,t]),I.useEffect(()=>{e&&(f==null||f.setSkipLastEnabled(!1))},[e,f])},Wr=(e,t,n)=>{const s=l.useDependency(a.IUniverInstanceService),r=l.useDependency(F.SheetsSelectionsService);return I.useCallback(()=>{if(e){const i=[...r.getWorkbookSelections(t).getSelectionsOfWorksheet(n)],c=s.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),d=c==null?void 0:c.getActiveSheet();(c==null?void 0:c.getUnitId())!==t&&s.setCurrentUnitForType(t),d&&d.getSheetId()===n&&r.setSelections(i)}},[e,r,n,t,s])},Vr=e=>e.reduce((t,n)=>typeof n=="string"?t+n.length:t+n.token.length,0),ut=e=>e.map(t=>typeof t=="string"?t:t.token).join(""),Ke=(e,t=!1,n="",s=!1)=>!t&&!s?e.map(r=>b.serializeRange(r.range)):e.map(r=>s?b.serializeRangeToRefString(r):r.sheetName!==""&&r.sheetName!==n?b.serializeRangeWithSheet(r.sheetName,r.range):b.serializeRange(r.range)),Hr=e=>{var m,p,f;const{editor:t,lexerTreeBuilder:n}=e,s=t==null?void 0:t.getSelectionRanges();if((s==null?void 0:s.length)!==1)return;const o=s[0].startOffset-1,i=((p=(m=t==null?void 0:t.getDocumentData().body)==null?void 0:m.dataStream)!=null?p:`\r
4
4
  `).slice(0,-2),c=(f=n.sequenceNodesBuilder(i.slice(1)))!=null?f:[],d=ft(c,o,!1),h=zt(c,d);return{nodeIndex:d,updatingRefIndex:h,sequenceNodes:c,offset:o}},Br=(()=>{}),Kr=(e,t,n,s,r,o,i,c,d,h=Br)=>{var L;const m=l.useDependency(B.IRenderManagerService),p=l.useDependency(a.IUniverInstanceService),f=l.useDependency(a.ICommandService),g=l.useDependency(Dt.DocSelectionManagerService),u=l.useDependency(a.ThemeService),v=l.useDependency(b.LexerTreeBuilder),C=p.getUnit(s),_=l.useEvent((w,M)=>{var P,T,D;return(D=(T=(P=p.getUnit(w))==null?void 0:P.getSheetBySheetId(M))==null?void 0:T.getName())!=null?D:""}),R=I.useMemo(()=>_(s,r),[_,r,s]),y=l.useObservable(C==null?void 0:C.activeSheet$),O=Me({activeSheet:y,sheetName:R}),S=l.useObservable(I.useMemo(()=>p.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),[p])),x=m.getRenderById((L=S==null?void 0:S.getUnitId())!=null?L:""),k=x==null?void 0:x.with(exports.RefSelectionsRenderService),U=x==null?void 0:x.with(N.SheetSkeletonManagerService),$=l.useDependency(F.IRefSelectionsService),A=l.useEvent((w,M,P)=>{var re,se,ie,z,X,Oe,Ne,Ue,fe,$e;const T=Hr({editor:d,lexerTreeBuilder:v});if(!T)return;const{nodeIndex:D,updatingRefIndex:j,sequenceNodes:W,offset:H}=T;if(n.current===me.NEED_ADD)if(H!==0){if(D===-1&&W.length)return;const Y=w[w.length-1],J=W.splice(D+1),ce=(re=Y.sheetId)!=null?re:r,ee={range:Y,unitId:(se=Y.unitId)!=null?se:S.getUnitId(),sheetName:_((ie=Y.unitId)!=null?ie:S.getUnitId(),ce)},oe=ce!==r,ae=(S==null?void 0:S.getUnitId())!==s,de=Ke([ee],i&&(oe||ae),R,ae);W.push({token:de[0],nodeType:b.sequenceNodeType.REFERENCE});const _e=[...W,...J],Re=ut(_e);h(Re,Vr(W),M)}else{const Y=w[w.length-1],J=(z=Y.sheetId)!=null?z:r,ce={range:Y,unitId:(X=Y.unitId)!=null?X:S.getUnitId(),sheetName:_((Oe=Y.unitId)!=null?Oe:S.getUnitId(),J)},ee=J!==r,oe=(S==null?void 0:S.getUnitId())!==s,ae=Ke([ce],i&&(ee||oe),R,oe);W.unshift({token:ae[0],nodeType:b.sequenceNodeType.REFERENCE});const de=ut(W);h(de,ae[0].length,M)}else if(n.current===me.EDIT_OTHER_SHEET_REFERENCE||n.current===me.EDIT_OTHER_WORKBOOK_REFERENCE){const Y=w.pop();if(!Y)return;const J=W[D];if(typeof J=="object"&&J.nodeType===b.sequenceNodeType.REFERENCE){const ce=J.token;(S==null?void 0:S.getUnitId())!==s?J.token=b.serializeRangeWithSpreadsheet((Ne=S==null?void 0:S.getUnitId())!=null?Ne:"",R,Y):J.token=R===(y==null?void 0:y.getName())?b.serializeRange(Y):b.serializeRangeWithSheet(y.getName(),Y);const oe=H+(J.token.length-ce.length);h(b.generateStringWithSequence(W),oe,M)}}else{const Y=[...w];if(!P&&j!==-1){const G=Y.pop();G&&Y.splice(j,0,G)}let J=0;const ce=W.map(G=>{var he,Se,De,Ie;if(typeof G=="string")return G;if(G.nodeType===b.sequenceNodeType.REFERENCE){const le=b.deserializeRangeWithSheet(G.token);if(le.sheetName||(le.sheetName=R),(le.unitId||s)!==(S==null?void 0:S.getUnitId())||i&&((he=O.current.activeSheet)==null?void 0:he.getName())!==le.sheetName)return G.token;const te=Y[J];if(J++,!te)return"";const we=(Se=te.sheetId)!=null?Se:r,st={range:te,unitId:(De=te.unitId)!=null?De:S.getUnitId(),sheetName:_((Ie=te.unitId)!=null?Ie:S.getUnitId(),we)},je=(S==null?void 0:S.getUnitId())!==s;return Ke([st],i&&(we!==r||je),R,je)[0]}return G.token});let ee="",oe;ce.forEach((G,he)=>{ee+=G,he===D&&(oe=ee.length)});const ae=[];for(let G=J;G<=w.length-1;G++){const he=w[G],Se=(Ue=he.sheetId)!=null?Ue:r,De={range:he,unitId:(fe=he.unitId)!=null?fe:S.getUnitId(),sheetName:_(($e=he.unitId)!=null?$e:S.getUnitId(),Se)},Ie=(S==null?void 0:S.getUnitId())!==s,te=Ke([De],i&&(Se!==r||Ie),R,Ie);ae.push(te[0])}const de=W[W.length-1],_e=de&&(typeof de=="string"?!1:de.nodeType===b.sequenceNodeType.REFERENCE),Re=`${ee}${ae.length&&_e?",":""}${ae.join(",")}`;h(Re,!ae.length&&oe?oe:Re.length,M)}});I.useEffect(()=>{if(k&&e){let w=!0,M=0;const P=(D,j)=>{if(w){w=!1,M=D.length;return}const W=D.length>M;j&&(M=D.length),A(D.map(H=>H.rangeWithCoord),j,W)},T=new a.DisposableCollection;return T.add(k.selectionMoving$.subscribe(D=>{P(D,!1)})),T.add(k.selectionMoveEnd$.subscribe(D=>{P(D,!0)})),()=>{T.dispose()}}},[e,A,k]),I.useEffect(()=>{if(t&&k&&d){const w=new a.DisposableCollection,M=()=>{w.dispose(),k.getSelectionControls().forEach((D,j)=>{w.add(D.selectionScaling$.subscribe(W=>{const H=k.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),re=H[j];W.sheetId=re.sheetId,W.unitId=re.unitId,H[j]=W,A(H,!1)})),w.add(D.selectionMoving$.subscribe(W=>{const H=k.getSelectionDataWithStyle().map(se=>se.rangeWithCoord),re=H[j];W.sheetId=re.sheetId,W.unitId=re.unitId,H[j]=W,A(H,!0)}))})},P=q.merge(d.input$,$.selectionSet$,k.selectionMoveEnd$).pipe(on.debounceTime(50)).subscribe(()=>{M()});return()=>{P.unsubscribe(),w.dispose()}}},[d,t,A,k,$.selectionSet$]),k==null||k.getSelectionDataWithStyle(),I.useEffect(()=>{if(c){const w=f.onCommandExecuted(M=>{var T;if(M.id!==F.SetSelectionsOperation.id)return;const P=M.params;if(P.extra==="formula-editor"&&P.selections.length){const D=P.selections[P.selections.length-1];if(D){const j=n.current===me.NEED_ADD,W=((T=k==null?void 0:k.getSelectionDataWithStyle())!=null?T:[]).map(H=>H.rangeWithCoord);j?W.push(D.range):W[W.length-1]=D.range,A(W,!0)}}});return()=>{w.dispose()}}},[f,d,n,v,c,A,k]),I.useEffect(()=>{if(!d)return;const w=g.textSelection$.subscribe(M=>{M.unitId===d.getEditorId()&&Zt({unitId:s,subUnitId:r,refSelections:o.current,editor:d,refSelectionsService:$,refSelectionsRenderService:k,sheetSkeletonManagerService:U,themeService:u,univerInstanceService:p,currentWorkbook:S})});return()=>w.unsubscribe()},[g.textSelection$,d,o,k,$,U,r,u,s,p])},qr=(e,t,n,s,r,o)=>{const i=l.useDependency(a.ICommandService),c=l.useDependency(Q.IEditorService),h=l.useDependency(B.IRenderManagerService).getRenderById(t),m=l.useDependency(a.IUniverInstanceService),p=h==null?void 0:h.with(exports.RefSelectionsRenderService);I.useEffect(()=>{if(e&&p)if(n){const f=()=>{const v=p.getSelectionControls().length;for(let C=1;C<=v;C++)p.clearLastSelection();return setTimeout(()=>{o()},30)},g=i.onCommandExecuted(v=>{v.id===F.SetWorksheetActiveOperation.id&&f()}),u=m.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(v=>{f()});return()=>{g.dispose(),u.unsubscribe()}}else{const f=i.beforeCommandExecuted(g=>{if(g.id===F.SetWorksheetActiveOperation.id){s(!1),r(),o();const u=c.getEditor(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);u==null||u.focus()}});return()=>{f.dispose()}}},[e,p])},Yr=(e,t,n)=>{const s=l.useDependency(b.LexerTreeBuilder),r=I.useRef(!0);I.useEffect(()=>{if(e){const o=setTimeout(()=>{r.current=!1},500);return()=>{clearTimeout(o)}}},[e]),I.useEffect(()=>{if(!r.current&&t){const o=s.checkIfAddBracket(n);t(o===0&&n.startsWith(b.operatorToken.EQUALS),`${n}`)}},[n,t])},zr=(e,t=[],n)=>{const s=l.useDependency(pe.IDescriptionService),[r,o]=I.useState([]),[i,c]=I.useState(""),d=I.useRef(-1),h=Me({nodes:t}),m=()=>{o([]),c(""),d.current=-1};return I.useEffect(()=>{if(n&&e){const f=n.input$.pipe(q.debounceTime(300)).subscribe(()=>{const g=n.getSelectionRanges();if(g.length===1){const u=h.current.nodes,v=g[0];if(v.collapsed){const C=ft(u,v.startOffset-1,!1);d.current=C;const _=u[C];if(_&&typeof _!="string"&&_.nodeType===b.sequenceNodeType.FUNCTION){d.current=C;const R=_.token,y=s.getSearchListByNameFirstLetter(R);o(y),c(R);return}}}d.current=-1,c(""),o(u=>u!=null&&u.length?[]:u)});return()=>{f.unsubscribe()}}},[n,e]),I.useEffect(()=>{e||m()},[e]),{searchList:r,searchText:i,handlerFormulaReplace:(f,g)=>{const u=[...h.current.nodes];if(d.current!==-1){const v=u.splice(d.current+1),C=u.pop()||"";let _=(typeof C=="string"?C.length:C.token.length)-f.length;return u.push(f),v[0]!==b.matchToken.OPEN_BRACKET&&g!==b.FunctionType.DefinedName&&(u.push(b.matchToken.OPEN_BRACKET),_--),{text:ut([...u,...v]),offset:_}}},reset:m}},Gr=()=>{},Zr=I.forwardRef(Xr);function Xr(e,t){const{isFocus:n,sequenceNodes:s,onSelect:r,editor:o,onClose:i=Gr}=e,c=o.getEditorId(),d=l.useDependency(l.IShortcutService),h=l.useDependency(a.ICommandService),{searchList:m,searchText:p,handlerFormulaReplace:f,reset:g}=zr(n,s,o),u=I.useMemo(()=>!!m.length,[m]),v=I.useRef(void 0),[C,_]=I.useState(0),R=I.useRef(!1),[y]=Gt(c,u,[p,m]),O=Me({searchList:m,active:C}),S=(A,L)=>{const w=f(A,L);w&&(g(),r(w))};function x(A){R.current&&_(A)}function k(){R.current&&_(-1)}I.useEffect(()=>{if(!m.length)return;const A=`sheet.formula-embedding-editor.search_function.${c}`,L=new a.DisposableCollection,w=M=>{const{searchList:P,active:T}=O.current;switch(M){case l.KeyCode.ARROW_UP:{_(D=>{const j=Math.max(0,D-1);return U(j),j});break}case l.KeyCode.ARROW_DOWN:{_(D=>{const j=Math.min(P.length-1,D+1);return U(j),j});break}case l.KeyCode.TAB:case l.KeyCode.ENTER:{const D=P[T];S(D.name,D.functionType);break}case l.KeyCode.ESC:{g(),i();break}}};return L.add(h.registerCommand({id:A,type:a.CommandType.OPERATION,handler(M,P){const{keyCode:T}=P;w(T)}})),[l.KeyCode.ARROW_UP,l.KeyCode.ARROW_DOWN,l.KeyCode.ENTER,l.KeyCode.ESC,l.KeyCode.TAB].map(M=>({id:A,binding:M,preconditions:()=>!0,priority:1e3,staticParameters:{eventType:B.DeviceInputEventType.Keyboard,keyCode:M}})).forEach(M=>{L.add(d.registerShortcut(M))}),()=>{L.dispose()}},[m]);function U(A){const L=v.current;if(!L)return;const w=L.children[A];if(!w)return;const P=L.getBoundingClientRect().top,T=L.offsetHeight,D=w.getBoundingClientRect(),j=D.top,W=D.height;if(j>=0&&j>P&&j-P+W<=T)return;const H=w.offsetTop-(T-W)/2;L.scrollTo({top:H,behavior:"smooth"})}const $=I.useMemo(()=>{let A="";return()=>{clearTimeout(A),R.current=!0,A=setTimeout(()=>{R.current=!1},300)}},[]);return m.length>0&&u&&E.jsx(l.RectPopup,{portal:!0,anchorRect$:y,direction:"vertical",children:E.jsx("ul",{ref:A=>{v.current=A,t&&(t.current=A)},"data-u-comp":"sheets-formula-editor",className:V.clsx("univer-m-0 univer-box-border univer-max-h-[400px] univer-w-[250px] univer-list-none univer-overflow-y-auto univer-rounded-lg univer-bg-white univer-p-2 univer-leading-5 univer-shadow-md univer-outline-none dark:!univer-bg-gray-900",V.borderClassName,V.scrollbarClassName),children:m.map((A,L)=>E.jsxs("li",{className:V.clsx("univer-box-border univer-cursor-pointer univer-rounded univer-px-2 univer-py-1 univer-text-gray-900 univer-transition-colors dark:!univer-text-white",{"univer-bg-gray-200 dark:!univer-bg-gray-600":C===L}),onMouseEnter:()=>x(L),onMouseLeave:k,onMouseMove:$,onClick:()=>{S(A.name,A.functionType),o&&o.focus()},children:[E.jsxs("span",{className:"univer-block univer-truncate univer-text-xs",children:[E.jsx("span",{className:"univer-text-red-500",children:A.name.substring(0,p.length)}),E.jsx("span",{children:A.name.slice(p.length)})]}),E.jsx("span",{className:"univer-block univer-text-xs univer-text-gray-400",children:A.desc})]},A.name))})})}const Qr=e=>e.startsWith(b.operatorToken.EQUALS)?e.slice(1):"",Ot=()=>{},Qt=I.forwardRef((e,t)=>{var St,vt,Ct,_t;const{errorText:n,initValue:s,unitId:r,subUnitId:o,isFocus:i=!0,isSupportAcrossSheet:c=!1,onFocus:d=Ot,onBlur:h=Ot,onChange:m,onVerify:p,className:f,editorId:g,moveCursor:u=!0,onFormulaSelectingChange:v,keyboardEventConfig:C,onMoveInEditor:_,resetSelectionOnBlur:R=!0,autoScrollbar:y=!0,isSingle:O=!0,disableSelectionOnClick:S=!1,autofocus:x=!0,disableContextMenu:k,style:U}=e,$=l.useDependency(Q.IEditorService),A=I.useRef(null),L=l.useEvent(m);I.useImperativeHandle(t,()=>({isClickOutSide:Z=>A.current?!A.current.contains(Z.target):!1}));const w=l.useEvent(v),M=I.useRef(null),P=I.useRef(void 0),T=P.current,[D,j]=I.useState(i),W=I.useRef(null),H=I.useMemo(()=>g!=null?g:a.createInternalEditorID(`${N.EMBEDDING_FORMULA_EDITOR}-${a.generateRandomId(4)}`),[]),re=I.useMemo(()=>n!==void 0,[n]),se=l.useDependency(a.IUniverInstanceService),ie=se.getUnit(H);l.useObservable(ie==null?void 0:ie.change$);const z=Ar(),X=a.BuildTextUtils.transform.getPlainText((vt=(St=ie==null?void 0:ie.getBody())==null?void 0:St.dataStream)!=null?vt:""),Oe=Me(X),Ne=I.useMemo(()=>Qr(X),[X]),Ue=I.useMemo(()=>z(Ne),[Ne,z]),{isSelecting:fe,isSelectingRef:$e}=wr({unitId:r,subUnitId:o,editorId:H,isFocus:D,disableOnClick:S}),Y=I.useRef(""),ce=l.useDependency(B.IRenderManagerService).getRenderById(H),ee=ce==null?void 0:ce.with(Q.DocSelectionRenderService),oe=ee==null?void 0:ee.isFocusing,ae=I.useMemo(()=>se.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[se]),de=l.useObservable(ae),_e=(de==null?void 0:de.getUnitId())===H,Re=I.useRef([]),G=fe,Se=(_t=(Ct=l.useDependency(a.IConfigService).getConfig(Lt))==null?void 0:Ct.functionScreenTips)!=null?_t:!0;l.useUpdateEffect(()=>{L(X)},[X,L]);const De=Xt("="),Ie=Pr(r,o),le=l.useEvent((Z,ne=!0,ve,ge)=>{if(!P.current)return;Y.current=Z;const We=Z[0]==="="?Z.slice(1):"",Ce=z(We),en=Ce.reduce((Ee,He)=>typeof He=="object"?`${Ee}${He.token}`:`${Ee}${He}`,""),Ve=De(P.current,en===We?Ce:[],ne,ge);if(Re.current=Ve,ve){const Ee=ge!=null?ge:T==null?void 0:T.getSelectionRanges();if((Ee==null?void 0:Ee.length)!==1)return;const tn=Ee[0].startOffset-1,nn=ft(Ce,tn,!1),Rt=zt(Ce,nn);if(Rt>=0){const It=Ve.splice(Rt,1)[0];It&&Ve.push(It)}Ie(D?Ve:[],P.current)}});I.useEffect(()=>{D&&le(X,!1,!0)},[D]),I.useEffect(()=>{if(D){if(Y.current===X)return;le(X,!1,!0)}},[X]),Yr(D,p,X);const te=Dr(T),we=Wr(D,r,o);I.useEffect(()=>{var Z;w(fe,(Z=ee==null?void 0:ee.isFocusing)!=null?Z:!0)},[w,fe]),Q.useKeyboardEvent(D,C,T),I.useLayoutEffect(()=>{let Z;if(W.current){Z=$.register({autofocus:x,editorUnitId:H,initialSnapshot:{id:H,body:{dataStream:`${s}\r
5
- `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},W.current);const ne=$.getEditor(H);P.current=ne,le(s,!1,!0)}return()=>{Z==null||Z.dispose()}},[]),I.useLayoutEffect(()=>{i?(j(i),te()):(R&&(T==null||T.blur(),we()),j(i))},[i,T,te,we,R]);const{checkScrollBar:st}=Q.useResize(T,O,y);jr(D,!!(fe&&_e),r,H,k),$r(!!(D&&oe&&u),G,T,_);const je=l.useEvent((Z,ne,ve)=>{if(!oe)return;const ge=ne!==-1?[{startOffset:ne+1,endOffset:ne+1,collapsed:!0}]:void 0;le(`=${Z}`,!0,ve,ge),ve&&(te(),ne!==-1&&setTimeout(()=>{const We={startOffset:ne+1,endOffset:ne+1},Ce=T==null?void 0:T.render.with(Q.DocBackScrollRenderController);Ce==null||Ce.scrollToRange({...We,collapsed:!0})},50),st())});Kr(D&&!!(fe&&_e),D,$e,r,o,Re,c,!!G,T,je),qr(D&&!!(fe&&_e),r,c,j,h,()=>{le(Oe.current,!1,!0)});const mt=Z=>{if(Z){const ne=T==null?void 0:T.getSelectionRanges();if(ne&&ne.length===1){const ve=ne[0];if(ve.collapsed){const ge=Z.offset;setTimeout(()=>{T==null||T.setSelectionRanges([{startOffset:ve.startOffset-ge,endOffset:ve.endOffset-ge}])},30)}}te(),le(`=${Z.text}`)}},pt=()=>{j(!0),d(),te()};return E.jsxs("div",{className:f,children:[E.jsx("div",{ref:A,className:V.clsx("univer-relative univer-box-border univer-flex univer-h-full univer-w-full univer-items-center univer-justify-around univer-gap-2 univer-rounded-none univer-p-0 univer-ring-1",{"univer-ring-primary-500":D,"univer-ring-red-500":re}),children:E.jsx("div",{ref:W,className:"univer-relative univer-h-full univer-w-full",onMouseUp:pt})}),n!==void 0&&E.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),Se&&T&&Ne!==""&&E.jsx(Nr,{editor:T,isFocus:D,formulaText:X,onClose:()=>te()}),Se&&!!T&&E.jsx(Zr,{isFocus:D,sequenceNodes:Ue,onSelect:mt,ref:M,editor:T})]})});function Jr(e,t,n,s){const r=l.useDependency(b.LexerTreeBuilder),o=Xt(""),i=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[c,d]=I.useState([]),h=l.useDependency(N.IMarkSelectionService),m=I.useRef(""),p=l.useDependency(a.IUniverInstanceService);return I.useEffect(()=>{if(!e)return;const f=e.getDocumentDataModel().getPlainText();if(m.current===f)return;m.current=f;const g=r.sequenceNodesBuilder(f);d(g!=null?g:[])},[i,e,r]),I.useEffect(()=>{var u,v;if(!e)return;if(!t){const C=e.getDocumentData();e.setDocumentData({...C,body:{...C.body,dataStream:(v=(u=C.body)==null?void 0:u.dataStream)!=null?v:"",textRuns:[]}});return}const f=o(e,c,!1),g=new a.DisposableCollection;return f.forEach(C=>{const _=b.deserializeRangeWithSheet(C.token),R=p.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),y=R==null?void 0:R.getActiveSheet();if(!_.sheetName&&s!==(y==null?void 0:y.getSheetId())||_.sheetName&&(y==null?void 0:y.getName())!==_.sheetName)return;const O=new a.ColorKit(C.themeColor).toRgb(),S=h.addShape({range:_.range,style:{stroke:C.themeColor,fill:`rgba(${O.r}, ${O.g}, ${O.b}, 0.1)`,strokeDash:12},primary:null});S&&g.add(()=>h.removeShape(S))}),()=>{g.dispose()}},[e,t,o,h,c]),{sequenceNodes:c}}function es(e){const t=l.useDependency(F.SheetsSelectionsService),{supportAcrossSheet:n=!1,keepSheetReference:s=!1,unitId:r,subUnitId:o,onChange:i}=e,d=l.useDependency(a.IUniverInstanceService).getUnit(r,a.UniverInstanceType.UNIVER_SHEET),h=l.useEvent(i),m=l.useEvent((p,f)=>{const g=d==null?void 0:d.getActiveSheet();if(!g||!n&&g.getSheetId()!==o||!(p!=null&&p.length))return;const u=s?g.getName():g.getSheetId()===o?"":g.getName(),v=p.map(C=>({range:C.range,unitId:r,sheetName:u}));h(v,f)});I.useEffect(()=>{const p=new a.DisposableCollection;return p.add(t.selectionMoveStart$.subscribe(f=>{m(f,!0)})),p.add(t.selectionMoving$.subscribe(f=>{m(f,!1)})),p.add(t.selectionMoveEnd$.subscribe(f=>{m(f,!1)})),()=>{p.dispose()}},[m,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const Nt=e=>!e.some(n=>{if(typeof n=="string"){if(n!==b.matchToken.COMMA)return!0}else if(n.nodeType!==b.sequenceNodeType.REFERENCE)return!0;return!1}),ts=e=>{if(e.endColumn<e.startColumn){const t=e.endColumn;e.endColumn=e.startColumn,e.startColumn=t}if(e.endRow<e.startRow){const t=e.endRow;e.endRow=e.startRow,e.startRow=t}return e};function ns(e){const{visible:t,initialValue:n,unitId:s,subUnitId:r,maxRangeCount:o=1/0,supportAcrossSheet:i,keepSheetReference:c,onConfirm:d,onClose:h,onShowBySelection:m}=e,p=l.useDependency(a.LocaleService),f=l.useDependency(b.LexerTreeBuilder),[g,u]=I.useState([]),[v,C]=I.useState(0),_=I.useRef(null);I.useEffect(()=>{if(t&&n.length){const S=n.map(x=>x.sheetName?b.serializeRangeWithSheet(x.sheetName,x.range):b.serializeRange(x.range));u(S),C(S.length-1)}else u([""]),C(0)},[t]);const R=(S,x)=>{const k=[...g];k[S]=x,u(k)},y=()=>{u([...g,""]),C(g.length)},O=S=>{g.splice(S,1),u([...g])};return es({unitId:s,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(S,x)=>{if(!t&&m!=null&&m(S))return;const k=new Set(g),U=S.map(L=>L.sheetName?b.serializeRangeWithSheet(L.sheetName,L.range):b.serializeRange(L.range)),$=U.filter(L=>!k.has(L));if(!$.length)return;const A=[...g];if(U.length>1){x||A.splice(v,1),A.push(...$);const L=A.slice(0,o);u(L),C(L.length-1),requestAnimationFrame(()=>{var w;(w=_.current)==null||w.scrollTo({top:_.current.scrollHeight})})}else{A.splice(v,1,...$);const L=A.slice(0,o);u(L),C(v+$.length-1)}}}),E.jsx(V.Dialog,{width:"328px",open:t,title:p.t("rangeSelector.title"),draggable:!0,mask:!1,maskClosable:!1,footer:E.jsxs("footer",{className:"univer-flex univer-gap-2",children:[E.jsx(V.Button,{onClick:h,children:p.t("rangeSelector.cancel")}),E.jsx(V.Button,{variant:"primary",onClick:()=>{d(g.filter(S=>{const x=f.sequenceNodesBuilder(S);return x&&x.length===1&&typeof x[0]!="string"&&x[0].nodeType===b.sequenceNodeType.REFERENCE}).map(S=>b.deserializeRangeWithSheet(S)).map(S=>({...S,range:ts(S.range)})))},children:p.t("rangeSelector.confirm")})]}),onClose:h,children:E.jsxs("div",{ref:_,className:V.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",V.scrollbarClassName),children:[g.map((S,x)=>E.jsxs("div",{className:"univer-mb-2 univer-flex univer-items-center univer-gap-4",children:[E.jsx(V.Input,{className:V.clsx("univer-w-full",{"univer-border-primary-600":v===x}),placeholder:p.t("rangeSelector.placeHolder"),onFocus:()=>C(x),value:S,onChange:k=>R(x,k)}),g.length>1&&E.jsx(Bt,{className:"univer-cursor-pointer",onClick:()=>O(x)})]},x)),g.length<o&&E.jsx("div",{children:E.jsxs(V.Button,{variant:"link",onClick:y,children:[E.jsx(Kt,{}),E.jsx("span",{children:p.t("rangeSelector.addAnotherRange")})]})})]})})}function rs(e){return e.split(b.matchToken.COMMA).filter(t=>!!t).map(t=>b.deserializeRangeWithSheet(t))}function ss(e){return e.map(t=>t.sheetName?b.serializeRangeWithSheet(t.sheetName,t.range):b.serializeRange(t.range)).join(b.matchToken.COMMA)}function gt(e){const[t,n]=I.useState(null),{onVerify:s,selectorRef:r,unitId:o,subUnitId:i,maxRangeCount:c,supportAcrossSheet:d,keepSheetReference:h,autoFocus:m,onChange:p,onRangeSelectorDialogVisibleChange:f,onClickOutside:g,onFocusChange:u,forceShowDialogWhenSelectionChanged:v,hideEditor:C,resetRange:_}=e,[R,y]=I.useState(m!=null?m:!1),[O,S]=I.useState(!1),[x,k]=I.useState([]),U=l.useDependency(a.LocaleService),$=l.useDependency(Q.IEditorService),{sequenceNodes:A}=Jr(t,R,o,i),L=Me(A),w=l.useDependency(a.ICommandService),M=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),$.blur()}),P=l.useEvent(()=>{var T;M(),k(rs((T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:"")),S(!0)});return I.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){$.focus(t.getEditorId())},blur:M,verify:()=>Nt(L.current),showDialog:T=>{M(),k(T),S(!0)},hideDialog:()=>{k([]),S(!1)},getValue:()=>{var T;return(T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:""}})},[M,t,$,r,L]),I.useEffect(()=>{var T;s==null||s(Nt(A),(T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:"")},[A]),I.useEffect(()=>{f==null||f(O)},[O]),I.useEffect(()=>{if(O&&_)return()=>{const T={unitId:o,subUnitId:i,selections:_};w.executeCommand(F.SetSelectionsOperation.id,T)}},[O]),E.jsxs(E.Fragment,{children:[C?null:E.jsx(Q.RichTextEditor,{isSingle:!0,...e,onFocusChange:(T,D)=>{y(T),u==null||u(T,D)},editorRef:n,onClickOutside:()=>{y(!1),M(),g==null||g()},icon:E.jsx(V.Tooltip,{title:U.t("rangeSelector.buttonTooltip"),placement:"bottom",children:E.jsx(Yt,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:P})})}),E.jsx(ns,{initialValue:x,unitId:o,subUnitId:i,visible:O,maxRangeCount:c,onConfirm:T=>{const D=ss(T),j=a.RichTextBuilder.newEmptyData();j.body.dataStream=D,t==null||t.replaceText(D,!1),p==null||p(j,D),S(!1),k([]),requestAnimationFrame(()=>{M()})},onClose:()=>{S(!1),k([])},supportAcrossSheet:d,keepSheetReference:h,onShowBySelection:T=>R||v?(k(T),S(!0),!1):!0})]})}const os=()=>{var s,r;const e=l.useDependency(ht),t=l.useObservable(e.currentSelector$),n=I.useRef(null);return I.useEffect(()=>{var o,i;if(t)return(i=n.current)==null||i.showDialog((o=t.initialValue)!=null?o:[]),()=>{var c;(c=n.current)==null||c.hideDialog()}},[t]),E.jsx(gt,{unitId:(s=t==null?void 0:t.unitId)!=null?s:"",subUnitId:(r=t==null?void 0:t.subUnitId)!=null?r:"",hideEditor:!0,selectorRef:n,onChange:(o,i)=>{var c;t==null||t.callback((c=i==null?void 0:i.split(",").map(d=>b.deserializeRangeWithSheet(d)))!=null?c:[])}})};var is=Object.defineProperty,cs=Object.getOwnPropertyDescriptor,as=(e,t,n)=>t in e?is(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ls=(e,t,n,s)=>{for(var r=s>1?void 0:s?cs(t,n):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(r=i(r)||r);return r},qe=(e,t)=>(n,s)=>t(n,s,e),Jt=(e,t,n)=>as(e,typeof t!="symbol"?t+"":t,n);exports.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=bt,n,s,r,o){super(),this._config=t,this._injector=n,this._renderManagerService=s,this._configService=r,this._uiPartsService=o;const{menu:i,...c}=a.merge(bt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(Lt,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[tt,{useClass:at}],[ht],[Xe],[Ye],[ze],[Ge],[Ze],[exports.FormulaReorderController],[Qe]]),this._initUIPart()}onReady(){[[exports.RefSelectionsRenderService]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))})}onRendered(){[[lt]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))}),a.touchDependencies(this._injector,[[Xe],[ze],[Ze],[Qe]])}onSteady(){this._injector.get(Ye),this._injector.get(exports.FormulaReorderController)}_initUIPart(){const t=this._injector.get(l.ComponentManager);this.disposeWithMe(t.register(N.RANGE_SELECTOR_COMPONENT_KEY,gt)),this.disposeWithMe(t.register(N.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Qt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(os,this._injector)))}};Jt(exports.UniverSheetsFormulaUIPlugin,"pluginName",At);Jt(exports.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=ls([a.DependentOn(b.UniverFormulaEnginePlugin,pe.UniverSheetsFormulaPlugin),qe(1,a.Inject(a.Injector)),qe(2,B.IRenderManagerService),qe(3,a.IConfigService),qe(4,l.IUIPartsService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=kt;exports.FormulaEditor=Qt;exports.GlobalRangeSelectorService=ht;exports.HelpFunctionOperation=wt;exports.InsertFunctionOperation=ue;exports.MoreFunctionsOperation=nt;exports.RangeSelector=gt;exports.ReferenceAbsoluteOperation=dt;exports.SearchFunctionOperation=Pt;exports.SelectEditorFormulaOperation=Te;exports.SheetCopyFormulaOnlyCommand=Je;exports.SheetOnlyPasteFormulaCommand=et;
5
+ `,textRuns:[],customBlocks:[],customDecorations:[],customRanges:[]},documentStyle:{}}},W.current);const ne=$.getEditor(H);P.current=ne,le(s,!1,!0)}return()=>{Z==null||Z.dispose()}},[]),I.useLayoutEffect(()=>{i?(j(i),te()):(R&&(T==null||T.blur(),we()),j(i))},[i,T,te,we,R]);const{checkScrollBar:st}=Q.useResize(T,O,y);jr(D,!!(fe&&_e),r,H,k),$r(!!(D&&oe&&u),G,T,_);const je=l.useEvent((Z,ne,ve)=>{if(!oe)return;const ge=ne!==-1?[{startOffset:ne+1,endOffset:ne+1,collapsed:!0}]:void 0;le(`=${Z}`,!0,ve,ge),ve&&(te(),ne!==-1&&setTimeout(()=>{const We={startOffset:ne+1,endOffset:ne+1},Ce=T==null?void 0:T.render.with(Q.DocBackScrollRenderController);Ce==null||Ce.scrollToRange({...We,collapsed:!0})},50),st())});Kr(D&&!!(fe&&_e),D,$e,r,o,Re,c,!!G,T,je),qr(D&&!!(fe&&_e),r,c,j,h,()=>{le(Oe.current,!1,!0)});const mt=Z=>{if(Z){const ne=T==null?void 0:T.getSelectionRanges();if(ne&&ne.length===1){const ve=ne[0];if(ve.collapsed){const ge=Z.offset;setTimeout(()=>{T==null||T.setSelectionRanges([{startOffset:ve.startOffset-ge,endOffset:ve.endOffset-ge}])},30)}}te(),le(`=${Z.text}`)}},pt=()=>{j(!0),d(),te()};return E.jsxs("div",{className:f,children:[E.jsx("div",{ref:A,className:V.clsx("univer-relative univer-box-border univer-flex univer-h-full univer-w-full univer-items-center univer-justify-around univer-gap-2 univer-rounded-none univer-p-0 univer-ring-1",{"univer-ring-primary-500":D,"univer-ring-red-500":re}),children:E.jsx("div",{ref:W,className:"univer-relative univer-h-full univer-w-full",onMouseUp:pt})}),n!==void 0&&E.jsx("div",{className:"univer-my-1 univer-text-xs univer-text-red-500",children:n}),Se&&T&&Ne!==""&&E.jsx(Nr,{editor:T,isFocus:D,formulaText:X,onClose:()=>te()}),Se&&!!T&&E.jsx(Zr,{isFocus:D,sequenceNodes:Ue,onSelect:mt,ref:M,editor:T})]})});function Jr(e,t,n,s){const r=l.useDependency(b.LexerTreeBuilder),o=Xt(""),i=l.useObservable(e==null?void 0:e.getDocumentDataModel().change$),[c,d]=I.useState([]),h=l.useDependency(N.IMarkSelectionService),m=I.useRef(""),p=l.useDependency(a.IUniverInstanceService);return I.useEffect(()=>{if(!e)return;const f=e.getDocumentDataModel().getPlainText();if(m.current===f)return;m.current=f;const g=r.sequenceNodesBuilder(f);d(g!=null?g:[])},[i,e,r]),I.useEffect(()=>{var u,v;if(!e)return;if(!t){const C=e.getDocumentData();e.setDocumentData({...C,body:{...C.body,dataStream:(v=(u=C.body)==null?void 0:u.dataStream)!=null?v:"",textRuns:[]}});return}const f=o(e,c,!1),g=new a.DisposableCollection;return f.forEach(C=>{const _=b.deserializeRangeWithSheet(C.token),R=p.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),y=R==null?void 0:R.getActiveSheet();if(!_.sheetName&&s!==(y==null?void 0:y.getSheetId())||_.sheetName&&(y==null?void 0:y.getName())!==_.sheetName)return;const O=new a.ColorKit(C.themeColor).toRgb(),S=h.addShape({range:_.range,style:{stroke:C.themeColor,fill:`rgba(${O.r}, ${O.g}, ${O.b}, 0.1)`,strokeDash:12},primary:null});S&&g.add(()=>h.removeShape(S))}),()=>{g.dispose()}},[e,t,o,h,c]),{sequenceNodes:c}}function es(e){const t=l.useDependency(F.SheetsSelectionsService),{supportAcrossSheet:n=!1,keepSheetReference:s=!1,unitId:r,subUnitId:o,onChange:i}=e,d=l.useDependency(a.IUniverInstanceService).getUnit(r,a.UniverInstanceType.UNIVER_SHEET),h=l.useEvent(i),m=l.useEvent((p,f)=>{const g=d==null?void 0:d.getActiveSheet();if(!g||!n&&g.getSheetId()!==o||!(p!=null&&p.length))return;const u=s?g.getName():g.getSheetId()===o?"":g.getName(),v=p.map(C=>({range:C.range,unitId:r,sheetName:u}));h(v,f)});I.useEffect(()=>{const p=new a.DisposableCollection;return p.add(t.selectionMoveStart$.subscribe(f=>{m(f,!0)})),p.add(t.selectionMoving$.subscribe(f=>{m(f,!1)})),p.add(t.selectionMoveEnd$.subscribe(f=>{m(f,!1)})),()=>{p.dispose()}},[m,t.selectionMoveEnd$,t.selectionMoveStart$,t.selectionMoving$])}const Nt=e=>!e.some(n=>{if(typeof n=="string"){if(n!==b.matchToken.COMMA)return!0}else if(n.nodeType!==b.sequenceNodeType.REFERENCE)return!0;return!1}),ts=e=>{if(e.endColumn<e.startColumn){const t=e.endColumn;e.endColumn=e.startColumn,e.startColumn=t}if(e.endRow<e.startRow){const t=e.endRow;e.endRow=e.startRow,e.startRow=t}return e};function ns(e){const{visible:t,initialValue:n,unitId:s,subUnitId:r,maxRangeCount:o=1/0,supportAcrossSheet:i,keepSheetReference:c,onConfirm:d,onClose:h,onShowBySelection:m}=e,p=l.useDependency(a.LocaleService),f=l.useDependency(b.LexerTreeBuilder),[g,u]=I.useState([]),[v,C]=I.useState(0),_=I.useRef(null);I.useEffect(()=>{if(t&&n.length){const S=n.map(x=>x.sheetName?b.serializeRangeWithSheet(x.sheetName,x.range):b.serializeRange(x.range));u(S),C(S.length-1)}else u([""]),C(0)},[t]);const R=(S,x)=>{const k=[...g];k[S]=x,u(k)},y=()=>{u([...g,""]),C(g.length)},O=S=>{g.splice(S,1),u([...g])};return es({unitId:s,subUnitId:r,supportAcrossSheet:i,keepSheetReference:c,onChange:(S,x)=>{if(!t&&m!=null&&m(S))return;const k=new Set(g),U=S.map(L=>L.sheetName?b.serializeRangeWithSheet(L.sheetName,L.range):b.serializeRange(L.range)),$=U.filter(L=>!k.has(L));if(!$.length)return;const A=[...g];if(U.length>1){x||A.splice(v,1),A.push(...$);const L=A.slice(0,o);u(L),C(L.length-1),requestAnimationFrame(()=>{var w;(w=_.current)==null||w.scrollTo({top:_.current.scrollHeight})})}else{A.splice(v,1,...$);const L=A.slice(0,o);u(L),C(v+$.length-1)}}}),E.jsx(V.Dialog,{width:"328px",open:t,title:p.t("rangeSelector.title"),draggable:!0,mask:!1,maskClosable:!1,footer:E.jsxs("footer",{className:"univer-flex univer-gap-2",children:[E.jsx(V.Button,{onClick:h,children:p.t("rangeSelector.cancel")}),E.jsx(V.Button,{variant:"primary",onClick:()=>{d(g.filter(S=>{const x=f.sequenceNodesBuilder(S);return x&&x.length===1&&typeof x[0]!="string"&&x[0].nodeType===b.sequenceNodeType.REFERENCE}).map(S=>b.deserializeRangeWithSheet(S)).map(S=>({...S,range:ts(S.range)})))},children:p.t("rangeSelector.confirm")})]}),onClose:h,children:E.jsxs("div",{ref:_,className:V.clsx("-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6",V.scrollbarClassName),children:[g.map((S,x)=>E.jsxs("div",{className:"univer-mb-2 univer-flex univer-items-center univer-gap-4",children:[E.jsx(V.Input,{className:V.clsx("univer-w-full",{"univer-border-primary-600":v===x}),placeholder:p.t("rangeSelector.placeHolder"),onFocus:()=>C(x),value:S,onChange:k=>R(x,k)}),g.length>1&&E.jsx(Bt,{className:"univer-cursor-pointer",onClick:()=>O(x)})]},x)),g.length<o&&E.jsx("div",{children:E.jsxs(V.Button,{variant:"link",onClick:y,children:[E.jsx(Kt,{}),E.jsx("span",{children:p.t("rangeSelector.addAnotherRange")})]})})]})})}function rs(e){return e.split(b.matchToken.COMMA).filter(t=>!!t).map(t=>b.deserializeRangeWithSheet(t))}function ss(e){return e.map(t=>t.sheetName?b.serializeRangeWithSheet(t.sheetName,t.range):b.serializeRange(t.range)).join(b.matchToken.COMMA)}function gt(e){const[t,n]=I.useState(null),{onVerify:s,selectorRef:r,unitId:o,subUnitId:i,maxRangeCount:c,supportAcrossSheet:d,keepSheetReference:h,autoFocus:m,onChange:p,onRangeSelectorDialogVisibleChange:f,onClickOutside:g,onFocusChange:u,forceShowDialogWhenSelectionChanged:v,hideEditor:C,resetRange:_}=e,[R,y]=I.useState(m!=null?m:!1),[O,S]=I.useState(!1),[x,k]=I.useState([]),U=l.useDependency(a.LocaleService),$=l.useDependency(Q.IEditorService),{sequenceNodes:A}=Jr(t,R,o,i),L=Me(A),w=l.useDependency(a.ICommandService),M=l.useEvent(()=>{t==null||t.setSelectionRanges([]),t==null||t.blur(),$.blur()}),P=l.useEvent(()=>{var T;M(),k(rs((T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:"")),S(!0)});return I.useEffect(()=>{r&&(r.current={get editor(){return t},focus(){$.focus(t.getEditorId())},blur:M,verify:()=>Nt(L.current),showDialog:T=>{M(),k(T),S(!0)},hideDialog:()=>{k([]),S(!1)},getValue:()=>{var T;return(T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:""}})},[M,t,$,r,L]),I.useEffect(()=>{var T;s==null||s(Nt(A),(T=t==null?void 0:t.getDocumentDataModel().getPlainText())!=null?T:"")},[A]),I.useEffect(()=>{f==null||f(O)},[O]),I.useEffect(()=>{if(O&&_)return()=>{const T={unitId:o,subUnitId:i,selections:_};w.executeCommand(F.SetSelectionsOperation.id,T)}},[O]),E.jsxs(E.Fragment,{children:[C?null:E.jsx(Q.RichTextEditor,{isSingle:!0,...e,onFocusChange:(T,D)=>{y(T),u==null||u(T,D)},editorRef:n,onClickOutside:()=>{y(!1),M(),g==null||g()},icon:E.jsx(V.Tooltip,{title:U.t("rangeSelector.buttonTooltip"),placement:"bottom",children:E.jsx(Yt,{className:"univer-cursor-pointer dark:!univer-text-gray-300",onClick:P})})}),E.jsx(ns,{initialValue:x,unitId:o,subUnitId:i,visible:O,maxRangeCount:c,onConfirm:T=>{const D=ss(T),j=a.RichTextBuilder.newEmptyData();j.body.dataStream=D,t==null||t.replaceText(D,!1),p==null||p(j,D),S(!1),k([]),requestAnimationFrame(()=>{M()})},onClose:()=>{S(!1),k([])},supportAcrossSheet:d,keepSheetReference:h,onShowBySelection:T=>R||v?(k(T),S(!0),!1):!0})]})}const os=()=>{var s,r;const e=l.useDependency(ht),t=l.useObservable(e.currentSelector$),n=I.useRef(null);return I.useEffect(()=>{var o,i;if(t)return(i=n.current)==null||i.showDialog((o=t.initialValue)!=null?o:[]),()=>{var c;(c=n.current)==null||c.hideDialog()}},[t]),E.jsx(gt,{unitId:(s=t==null?void 0:t.unitId)!=null?s:"",subUnitId:(r=t==null?void 0:t.subUnitId)!=null?r:"",hideEditor:!0,selectorRef:n,onChange:(o,i)=>{var c;t==null||t.callback((c=i==null?void 0:i.split(",").map(d=>b.deserializeRangeWithSheet(d)))!=null?c:[])}})};var is=Object.defineProperty,cs=Object.getOwnPropertyDescriptor,as=(e,t,n)=>t in e?is(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ls=(e,t,n,s)=>{for(var r=s>1?void 0:s?cs(t,n):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(r=i(r)||r);return r},qe=(e,t)=>(n,s)=>t(n,s,e),Jt=(e,t,n)=>as(e,typeof t!="symbol"?t+"":t,n);exports.UniverSheetsFormulaUIPlugin=class extends a.Plugin{constructor(t=bt,n,s,r,o){super(),this._config=t,this._injector=n,this._renderManagerService=s,this._configService=r,this._uiPartsService=o;const{menu:i,...c}=a.merge(bt,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig(Lt,c,{merge:!0})}onStarting(){a.registerDependencies(this._injector,[[tt,{useClass:at}],[ht],[Xe],[Ye],[ze],[Ge],[Ze],[exports.FormulaReorderController],[Qe]]),this._initUIPart()}onReady(){[[exports.RefSelectionsRenderService]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))})}onRendered(){[[lt]].forEach(t=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(a.UniverInstanceType.UNIVER_SHEET,t))}),a.touchDependencies(this._injector,[[Xe],[ze],[Ze],[Qe]])}onSteady(){this._injector.get(Ye),this._injector.get(exports.FormulaReorderController)}_initUIPart(){const t=this._injector.get(l.ComponentManager);this.disposeWithMe(t.register(N.RANGE_SELECTOR_COMPONENT_KEY,gt)),this.disposeWithMe(t.register(N.EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,Qt)),this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.GLOBAL,()=>l.connectInjector(os,this._injector)))}};Jt(exports.UniverSheetsFormulaUIPlugin,"pluginName",At);Jt(exports.UniverSheetsFormulaUIPlugin,"type",a.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFormulaUIPlugin=ls([a.DependentOn(pe.UniverSheetsFormulaPlugin),qe(1,a.Inject(a.Injector)),qe(2,B.IRenderManagerService),qe(3,a.IConfigService),qe(4,l.IUIPartsService)],exports.UniverSheetsFormulaUIPlugin);exports.FORMULA_PROMPT_ACTIVATED=kt;exports.FormulaEditor=Qt;exports.GlobalRangeSelectorService=ht;exports.HelpFunctionOperation=wt;exports.InsertFunctionOperation=ue;exports.MoreFunctionsOperation=nt;exports.RangeSelector=gt;exports.ReferenceAbsoluteOperation=dt;exports.SearchFunctionOperation=Pt;exports.SelectEditorFormulaOperation=Te;exports.SheetCopyFormulaOnlyCommand=Je;exports.SheetOnlyPasteFormulaCommand=et;