@univerjs/find-replace 0.20.1 → 0.21.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.
Files changed (41) hide show
  1. package/lib/cjs/index.js +1322 -1
  2. package/lib/cjs/locale/ca-ES.js +52 -1
  3. package/lib/cjs/locale/en-US.js +67 -1
  4. package/lib/cjs/locale/es-ES.js +52 -1
  5. package/lib/cjs/locale/fa-IR.js +52 -1
  6. package/lib/cjs/locale/fr-FR.js +52 -1
  7. package/lib/cjs/locale/ja-JP.js +52 -1
  8. package/lib/cjs/locale/ko-KR.js +52 -1
  9. package/lib/cjs/locale/ru-RU.js +52 -1
  10. package/lib/cjs/locale/sk-SK.js +52 -1
  11. package/lib/cjs/locale/vi-VN.js +52 -1
  12. package/lib/cjs/locale/zh-CN.js +52 -1
  13. package/lib/cjs/locale/zh-TW.js +52 -1
  14. package/lib/es/index.js +1291 -1
  15. package/lib/es/locale/ca-ES.js +51 -1
  16. package/lib/es/locale/en-US.js +66 -1
  17. package/lib/es/locale/es-ES.js +51 -1
  18. package/lib/es/locale/fa-IR.js +51 -1
  19. package/lib/es/locale/fr-FR.js +51 -1
  20. package/lib/es/locale/ja-JP.js +51 -1
  21. package/lib/es/locale/ko-KR.js +51 -1
  22. package/lib/es/locale/ru-RU.js +51 -1
  23. package/lib/es/locale/sk-SK.js +51 -1
  24. package/lib/es/locale/vi-VN.js +51 -1
  25. package/lib/es/locale/zh-CN.js +51 -1
  26. package/lib/es/locale/zh-TW.js +51 -1
  27. package/lib/index.js +1291 -1
  28. package/lib/locale/ca-ES.js +51 -1
  29. package/lib/locale/en-US.js +66 -1
  30. package/lib/locale/es-ES.js +51 -1
  31. package/lib/locale/fa-IR.js +51 -1
  32. package/lib/locale/fr-FR.js +51 -1
  33. package/lib/locale/ja-JP.js +51 -1
  34. package/lib/locale/ko-KR.js +51 -1
  35. package/lib/locale/ru-RU.js +51 -1
  36. package/lib/locale/sk-SK.js +51 -1
  37. package/lib/locale/vi-VN.js +51 -1
  38. package/lib/locale/zh-CN.js +51 -1
  39. package/lib/locale/zh-TW.js +51 -1
  40. package/lib/umd/index.js +1 -1
  41. package/package.json +8 -8
package/lib/index.js CHANGED
@@ -1 +1,1291 @@
1
- import{CommandType as e,Disposable as t,DisposableCollection as n,EDITOR_ACTIVATED as r,FOCUSING_SHEET as i,ICommandService as a,IConfigService as o,IConfirmService as s,IContextService as c,IUniverInstanceService as l,Inject as u,Injector as d,LocaleService as f,Plugin as p,RxDisposable as ee,UniverInstanceType as te,createIdentifier as ne,merge as re,toDisposable as m}from"@univerjs/core";import{Button as ie,Checkbox as ae,FormDualColumnLayout as oe,FormLayout as h,Input as se,MessageType as g,Pager as ce,Select as _}from"@univerjs/design";import{ComponentManager as v,IDialogService as le,ILayoutService as y,IMenuManagerService as ue,IMessageService as de,IShortcutService as fe,KeyCode as b,MenuItemType as pe,MetaKeys as x,RibbonDataGroup as me,getMenuHiddenObservable as he,useDebounceFn as ge,useDependency as S,useObservable as C}from"@univerjs/ui";import{RENDER_RAW_FORMULA_KEY as _e}from"@univerjs/engine-render";import{BehaviorSubject as w,Subject as T,combineLatest as ve,debounceTime as ye,fromEvent as be,map as xe,takeUntil as Se,throttleTime as Ce}from"rxjs";import{SearchIcon as we}from"@univerjs/icons";import{forwardRef as Te,useCallback as E,useEffect as D,useImperativeHandle as Ee,useMemo as O,useRef as De,useState as Oe}from"react";import{Fragment as k,jsx as A,jsxs as j}from"react/jsx-runtime";const ke=`FIND_REPLACE_INPUT_FOCUS`,Ae=`FIND_REPLACE_DIALOG_FOCUS`,je=`FIND_REPLACE_REPLACE_REVEALED`;function M(e){"@babel/helpers - typeof";return M=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},M(e)}function Me(e,t){if(M(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(M(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ne(e){var t=Me(e,`string`);return M(t)==`symbol`?t:t+``}function N(e,t,n){return(t=Ne(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function P(e,t){return function(n,r){t(n,r,e)}}function F(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Pe=class extends t{};const I=ne(`find-replace.service`);function Fe(e){return e.findString!==void 0||e.inputtingFindString!==void 0||e.findDirection!==void 0||e.matchesTheWholeCell!==void 0||e.caseSensitive!==void 0||e.findScope!==void 0||e.findBy!==void 0}let L=class extends t{get searched(){return this._findModels.length>0}constructor(e,t,n,r){super(),this._state=e,this._providers=t,this._univerInstanceService=n,this._commandService=r,N(this,`currentMatch$`,new w(null)),N(this,`replaceables$`,new w([])),N(this,`_findModels`,[]),N(this,`_matchingModel`,null),N(this,`_matches`,[]),N(this,`_currentSearchingDisposables`,null),this.disposeWithMe(this._state.stateUpdates$.pipe(Ce(200,void 0,{leading:!0,trailing:!0})).subscribe(async e=>{let t=this._state.state;Fe(e)&&(t.findString!==``&&!t.replaceRevealed?(await this._startSearching(),this._state.changeState({findCompleted:!0})):e.replaceRevealed!==!0&&this._stopSearching())}))}dispose(){super.dispose(),this._stopSearching(),this.currentMatch$.complete(),this.replaceables$.complete(),this._state.changeState({...V(),revealed:!1})}async start(){if(!this._state.findString)return{results:[]};let e=await this._startSearching();return this._state.changeState({findCompleted:!0}),e}focusSelection(){var e;(e=this._matchingModel)==null||e.focusSelection()}async _startSearching(){if(!this._state.findString)return{results:[]};let e=Array.from(this._providers),t=this._findModels=(await Promise.all(e.map(e=>e.find({findString:this._state.findString,findDirection:this._state.findDirection,findScope:this._state.findScope,findBy:this._state.findBy,replaceRevealed:this._state.replaceRevealed,caseSensitive:this._state.caseSensitive,matchesTheWholeCell:this._state.matchesTheWholeCell})))).flat();this._subscribeToModelsChanges(t);let n=this._matches=t.map(e=>e.getMatches()).flat();return this.replaceables$.next(n.filter(e=>e.replaceable)),n.length?(this._moveToInitialMatch(t),this._state.changeState({matchesCount:n.length}),{results:n}):(this._state.changeState({matchesCount:0,matchesPosition:0}),{results:[]})}_stopSearching(){var e;this._providers.forEach(e=>e.terminate()),this._findModels=[],this._matches=[],this._matchingModel=null,(e=this._currentSearchingDisposables)==null||e.dispose(),this._currentSearchingDisposables=null,this.currentMatch$.next(null),this.replaceables$.next([]),this._state.changeState({findCompleted:!1,matchesCount:0,matchesPosition:0})}_subscribeToModelsChanges(e){let t=this._currentSearchingDisposables=new n,r=ve(e.map(e=>e.matchesUpdate$)).pipe(ye(220)).subscribe(([...e])=>{let t=this._matches=e.flat();t.length?(this._moveToInitialMatch(this._findModels,!0),this._state.changeState({matchesCount:t.length}),this.replaceables$.next(t.filter(e=>e.replaceable))):(this._state.changeState({matchesCount:0,matchesPosition:0}),this.replaceables$.next([]))});e.forEach(e=>t.add(m(e.activelyChangingMatch$.subscribe(e=>{let t=this._matches.findIndex(t=>t===e);this._state.changeState({matchesPosition:t+1})})))),t.add(m(r))}async replace(){return this._matchingModel?this._matchingModel.replace(this._state.replaceString):!1}async replaceAll(){let e=await Promise.all(this._findModels.map(e=>e.replaceAll(this._state.replaceString))).then(e=>e.reduce((e,t)=>(e.success+=t.success,e.failure+=t.failure,e),{success:0,failure:0}));return e.failure===0&&this._stopSearching(),e}getCurrentMatch(){return this._state.matchesPosition>0?this._matches[this._state.matchesPosition-1]:null}_markMatch(e){let t=this._matches.findIndex(t=>t===e);this.currentMatch$.next(e),this._state.changeState({matchesPosition:t+1})}moveToNextMatch(){if(!this._matchingModel)return;let e=this._findModels.length===1,t=this._matchingModel.moveToNextMatch({loop:e});if(t)return this._markMatch(t),t;{let e=this._findModels.findIndex(e=>e===this._matchingModel);return this._moveToNextUnitMatch(e)}}_moveToNextUnitMatch(e){let t=this._findModels.length;for(let n=(e+1)%t;n!==e;){let e=this._findModels[n],r=e.moveToNextMatch({ignoreSelection:!0});if(r)return this._matchingModel=e,this._markMatch(r),r;n=(n+1)%t}if(this._matchingModel){let e=this._matchingModel.moveToNextMatch({ignoreSelection:!0});return e&&this._markMatch(e),e}}moveToPreviousMatch(){if(!this._matchingModel)return;let e=this._findModels.length===1,t=this._matchingModel.moveToPreviousMatch({loop:e});if(t){let e=this._matches.findIndex(e=>e===t);return this.currentMatch$.next(t),this._state.changeState({matchesPosition:e+1}),t}else{let e=this._findModels.length,t=this._findModels.findIndex(e=>e===this._matchingModel);for(let n=(t-1+e)%e;n!==t;){let t=this._findModels[n],r=t.moveToPreviousMatch({ignoreSelection:!0});if(r)return this._matchingModel=t,this._markMatch(r),r;n=(n-1)%e}let n=this._matchingModel.moveToPreviousMatch({ignoreSelection:!0});return n&&this._markMatch(n),n}}_moveToInitialMatch(e,t=!1){var n;let r=(n=this._univerInstanceService.getFocusedUnit())==null?void 0:n.getUnitId();if(!r)return-1;let i=e.findIndex(e=>e.unitId===r);if(i!==-1){this._matchingModel=e[i];let n=this._matchingModel.moveToNextMatch({stayIfOnMatch:!0,noFocus:t});if(n)return this._markMatch(n),i}return this._moveToNextUnitMatch(i),0}};L=F([P(2,l),P(3,a)],L);let R=function(e){return e.ROW=`row`,e.COLUMN=`column`,e}({}),z=function(e){return e.VALUE=`value`,e.FORMULA=`formula`,e}({}),B=function(e){return e.SUBUNIT=`subunit`,e.UNIT=`unit`,e}({});function V(){return{caseSensitive:!1,findBy:z.VALUE,findCompleted:!1,findDirection:R.ROW,findScope:B.SUBUNIT,findString:``,inputtingFindString:``,matchesCount:0,matchesPosition:0,matchesTheWholeCell:!1,replaceRevealed:!1,replaceString:``,revealed:!0}}var Ie=class{constructor(){N(this,`_stateUpdates$`,new T),N(this,`stateUpdates$`,this._stateUpdates$.asObservable()),N(this,`_state$`,new w(V())),N(this,`state$`,this._state$.asObservable()),N(this,`_findString`,``),N(this,`_inputtingFindString`,``),N(this,`_replaceString`,``),N(this,`_revealed`,!1),N(this,`_replaceRevealed`,!1),N(this,`_matchesPosition`,0),N(this,`_matchesCount`,0),N(this,`_caseSensitive`,!0),N(this,`_matchesTheWholeCell`,!1),N(this,`_findDirection`,R.ROW),N(this,`_findScope`,B.SUBUNIT),N(this,`_findBy`,z.VALUE),N(this,`_findCompleted`,!1)}get state(){return this._state$.getValue()}get inputtingFindString(){return this._inputtingFindString}get findString(){return this._findString}get revealed(){return this._revealed}get replaceRevealed(){return this._replaceRevealed}get matchesPosition(){return this._matchesPosition}get matchesCount(){return this._matchesCount}get replaceString(){return this._replaceString}get caseSensitive(){return this._caseSensitive}get matchesTheWholeCell(){return this._matchesTheWholeCell}get findDirection(){return this._findDirection}get findScope(){return this._findScope}get findBy(){return this._findBy}get findCompleted(){return this._findCompleted}changeState(e){let t=!1,n={};e.findString!==void 0&&e.findString!==this._findString&&(this._findString=e.findString,n.findString=this._findString,t=!0),e.revealed!==void 0&&e.revealed!==this._revealed&&(this._revealed=e.revealed,n.revealed=e.revealed,t=!0),e.replaceRevealed!==void 0&&e.replaceRevealed!==this._replaceRevealed&&(this._replaceRevealed=e.replaceRevealed,n.replaceRevealed=e.replaceRevealed,t=!0),e.replaceString!==void 0&&e.replaceString!==this._replaceString&&(this._replaceString=e.replaceString,n.replaceString=e.replaceString,t=!0),e.matchesCount!==void 0&&e.matchesCount!==this._matchesCount&&(this._matchesCount=e.matchesCount,n.matchesCount=e.matchesCount,t=!0),e.matchesPosition!==void 0&&e.matchesPosition!==this._matchesPosition&&(this._matchesPosition=e.matchesPosition,n.matchesPosition=e.matchesPosition,t=!0),e.findBy!==void 0&&e.findBy!==this._findBy&&(this._findBy=e.findBy,n.findBy=e.findBy,t=!0),e.findScope!==void 0&&e.findScope!==this._findScope&&(this._findScope=e.findScope,n.findScope=e.findScope,t=!0),e.findDirection!==void 0&&e.findDirection!==this._findDirection&&(this._findDirection=e.findDirection,n.findDirection=e.findDirection,t=!0),e.caseSensitive!==void 0&&e.caseSensitive!==this._caseSensitive&&(this._caseSensitive=e.caseSensitive,n.caseSensitive=e.caseSensitive,t=!0),e.matchesTheWholeCell!==void 0&&e.matchesTheWholeCell!==this._matchesTheWholeCell&&(this._matchesTheWholeCell=e.matchesTheWholeCell,n.matchesTheWholeCell=e.matchesTheWholeCell,t=!0),e.inputtingFindString!==void 0&&e.inputtingFindString!==this._inputtingFindString&&(this._inputtingFindString=e.inputtingFindString,n.inputtingFindString=e.inputtingFindString,t=!0),e.findCompleted!==void 0&&e.findCompleted!==this._findCompleted&&(this._findCompleted=e.findCompleted,n.findCompleted=e.findCompleted,t=!0),t&&(this._state$.next({caseSensitive:this._caseSensitive,findBy:this._findBy,findCompleted:this._findCompleted,findDirection:this._findDirection,findScope:this._findScope,findString:this._findString,inputtingFindString:this._inputtingFindString,matchesCount:this._matchesCount,matchesPosition:this._matchesPosition,matchesTheWholeCell:this._matchesTheWholeCell,replaceRevealed:this._replaceRevealed,revealed:this._revealed}),this._stateUpdates$.next(n))}};let H=class extends t{get stateUpdates$(){return this._state.stateUpdates$}get state$(){return this._state.state$}get revealed(){return this._state.revealed}get replaceRevealed(){return this._state.replaceRevealed}constructor(e,t){super(),this._injector=e,this._contextService=t,N(this,`_providers`,new Set),N(this,`_state`,new Ie),N(this,`_model`,void 0),N(this,`_currentMatch$`,new w(null)),N(this,`currentMatch$`,this._currentMatch$.asObservable()),N(this,`_replaceables$`,new w([])),N(this,`replaceables$`,this._replaceables$.asObservable()),N(this,`_focusSignal$`,new T),N(this,`focusSignal$`,this._focusSignal$.asObservable())}dispose(){super.dispose(),this._currentMatch$.next(null),this._currentMatch$.complete(),this._replaceables$.next([]),this._replaceables$.complete(),this._focusSignal$.complete()}getProviders(){return this._providers}getCurrentMatch(){var e;return(e=this._model)==null?void 0:e.getCurrentMatch()}getFindString(){return this._state.findString}changeFindString(e){this._state.changeState({findString:e})}focusFindInput(){this._focusSignal$.next()}changeInputtingFindString(e){e?this._state.changeState({inputtingFindString:e}):this._state.changeState({inputtingFindString:``,findString:``})}changeReplaceString(e){this._state.changeState({replaceString:e})}changeMatchesTheWholeCell(e){this._state.changeState({matchesTheWholeCell:e})}changeCaseSensitive(e){this._state.changeState({caseSensitive:e})}changeFindBy(e){this._state.changeState({findBy:e}),this._toggleDisplayRawFormula(e===z.FORMULA)}changeFindScope(e){this._state.changeState({findScope:e})}changeFindDirection(e){this._state.changeState({findDirection:e})}moveToNextMatch(){this._model&&(this._state.replaceRevealed&&!this._model.searched?(this._state.changeState({findString:this._state.inputtingFindString}),this._model.start()):this._model.moveToNextMatch(),this._focusSignal$.next())}moveToPreviousMatch(){this._model&&(this._state.replaceRevealed&&!this._model.searched?(this._state.changeState({findString:this._state.inputtingFindString}),this._model.start()):this._model.moveToPreviousMatch(),this._focusSignal$.next())}async replace(){return this._model?this._model.replace():!1}async replaceAll(){if(!this._model)throw Error(`[FindReplaceService] replaceAll: model is not initialized!`);return this._model.replaceAll()}revealReplace(){this._state.changeState({replaceRevealed:!0,inputtingFindString:this._state.findString}),this._toggleRevealReplace(!0)}focusSelection(){var e;(e=this._model)==null||e.focusSelection()}start(e=!1){if(this._providers.size===0)return!1;this._model=this._injector.createInstance(L,this._state,this._providers),this._model.currentMatch$.subscribe(e=>this._currentMatch$.next(e)),this._model.replaceables$.subscribe(e=>this._replaceables$.next(e));let t=V();return e&&(t.replaceRevealed=!0),this._state.changeState(t),this._toggleRevealReplace(e),!0}find(){var e;(e=this._model)==null||e.start()}terminate(){var e;(e=this._model)==null||e.dispose(),this._model=null,this._toggleDisplayRawFormula(!1),this._toggleRevealReplace(!1)}registerFindReplaceProvider(e){return this._providers.add(e),m(()=>this._providers.delete(e))}_toggleRevealReplace(e){this._contextService.setContextValue(je,e)}_toggleDisplayRawFormula(e){this._contextService.setContextValue(_e,e)}};H=F([P(0,u(d)),P(1,c)],H);const U={id:`ui.command.replace-current-match`,type:e.COMMAND,handler:e=>e.get(I).replace()},W={id:`ui.command.replace-all-matches`,type:e.COMMAND,handler:async e=>{let t=e.get(s),n=e.get(f),r=e.get(de);if(!await t.confirm({id:`CONFIRM_REPLACE_ALL`,title:{title:n.t(`find-replace.replace.confirm.title`)},cancelText:n.t(`button.cancel`),confirmText:n.t(`button.confirm`)}))return!1;let{success:i,failure:a}=await e.get(I).replaceAll();return a>0?(i===0?r.show({type:g.Error,content:n.t(`find-replace.replace.all-failure`)}):r.show({type:g.Warning,content:n.t(`find-replace.replace.partial-success`,`${i}`,`${a}`)}),!1):(r.show({type:g.Success,content:n.t(`find-replace.replace.all-success`,`${i}`)}),!0)}},G={id:`ui.operation.open-find-dialog`,type:e.OPERATION,handler:e=>{let t=e.get(I);return t.revealed?t.focusFindInput():t.start(),!0}},K={id:`ui.operation.open-replace-dialog`,type:e.OPERATION,handler:e=>{let t=e.get(I);return t.revealed?t.replaceRevealed?t.focusFindInput():t.revealReplace():t.start(!0),!0}},q={type:e.OPERATION,id:`ui.operation.go-to-next-match`,handler:e=>(e.get(I).moveToNextMatch(),!0)},J={type:e.OPERATION,id:`ui.operation.go-to-previous-match`,handler:e=>(e.get(I).moveToPreviousMatch(),!0)},Le={type:e.OPERATION,id:`ui.operation.focus-selection`,handler:e=>(e.get(I).focusSelection(),!0)};function Re(e){let t=e.get(c);return{id:G.id,icon:`SearchIcon`,tooltip:`find-replace.toolbar`,type:pe.BUTTON,hidden$:he(e,te.UNIVER_SHEET),disabled$:ve([t.subscribeContextValue$(r),t.subscribeContextValue$(i)]).pipe(xe(([e,t])=>e||!t))}}const ze={[me.ORGANIZATION]:{[G.id]:{order:2,menuItemFactory:Re}}};function Be(e){let{findCompleted:t,localeService:n,matchesCount:r,matchesPosition:i,initialFindString:a,findReplaceService:o,onChange:s,...c}=e,[l,u]=Oe(a),d=t&&r===0?n.t(`find-replace.dialog.no-result`):r===0?` `:void 0;function f(e){i===r&&e===1?o.moveToNextMatch():i===1&&e===r||e<i?o.moveToPreviousMatch():o.moveToNextMatch()}return A(`div`,{className:`univer-relative univer-flex univer-items-center univer-gap-2`,onDrag:e=>e.stopPropagation(),children:A(se,{"data-u-comp":`search-input`,autoFocus:!0,placeholder:n.t(`find-replace.dialog.find-placeholder`),value:l,onChange:e=>{u(e),s==null||s(e)},slot:A(ce,{loop:!0,text:d,value:i,total:r,onChange:f}),...c})})}function Ve(e,t){let n=E(()=>{var e;(e=document.querySelector(`.univer-find-input input`))==null||e.focus()},[]),r=E(()=>{let e=document.querySelectorAll(`[data-u-comp=find-replace-dialog] [data-u-comp=search-input]`);return Array.from(e).some(e=>e===document.activeElement)},[]);return Ee(t,()=>({focus:n,selectHasFocus:r})),D(()=>{let t=e.focusSignal$.subscribe(()=>n());return()=>t.unsubscribe()},[e,n]),{focus:n,selectHasFocus:r}}const He=Te(function(e,t){let n=S(f),r=S(I),i=S(a),{findCompleted:o,findString:s,matchesCount:c,matchesPosition:l}=C(r.state$,void 0,!0),u=E(()=>{i.executeCommand(K.id)},[i]),d=ge(e=>r.changeFindString(e),500);return Ve(r,t),j(k,{children:[A(Be,{findCompleted:o,matchesCount:c,matchesPosition:l,findReplaceService:r,localeService:n,initialFindString:s,onChange:d}),A(`div`,{className:`univer-mt-4 univer-text-center`,children:A(`a`,{className:`hover:univer-text-primary-500/80 univer-cursor-pointer univer-text-sm univer-text-primary-500 univer-transition-colors`,onClick:u,children:n.t(`find-replace.dialog.advanced-finding`)})})]})}),Ue=Te(function(e,t){let n=S(I),r=S(f),i=S(a),o=S(de),s=C(n.currentMatch$,void 0,!0),c=C(n.replaceables$,void 0,!0),{matchesCount:l,matchesPosition:u,findString:d,inputtingFindString:p,replaceString:ee,caseSensitive:te,matchesTheWholeCell:ne,findDirection:re,findScope:m,findBy:ce,findCompleted:v}=C(n.state$,void 0,!0),le=p.length===0,y=l===0||!(s!=null&&s.replaceable),ue=c.length===0,fe=E(e=>n.changeInputtingFindString(e),[n]),b=E(e=>n.changeReplaceString(e),[n]),{focus:pe}=Ve(n,t),x=E(()=>{d===p?n.moveToNextMatch():(n.changeFindString(p),n.find())},[d,p,n]),me=E(()=>i.executeCommand(U.id),[i]),he=E(async()=>{await i.executeCommand(W.id),pe()},[i]),ge=E(e=>{n.changeFindDirection(e)},[n]),_e=E(e=>{n.changeFindScope(e)},[n]),w=E(e=>{n.changeFindBy(e)},[n]),T=Ge(r),ve=Ke(r),ye=qe(r);return D(()=>{v&&l===0&&o.show({content:r.t(`find-replace.dialog.no-match`),type:g.Warning,duration:5e3})},[v,l,o,r]),j(`div`,{children:[A(h,{label:r.t(`find-replace.dialog.find`),children:A(Be,{findCompleted:v,className:`univer-find-input`,matchesCount:l,matchesPosition:u,findReplaceService:n,localeService:r,initialFindString:p,onChange:fe})}),A(h,{label:r.t(`find-replace.dialog.replace`),children:A(se,{placeholder:r.t(`find-replace.dialog.replace-placeholder`),value:ee,onChange:e=>b(e)})}),A(h,{label:r.t(`find-replace.dialog.find-direction.title`),children:A(_,{value:re,options:ve,onChange:ge})}),A(oe,{children:j(k,{children:[A(h,{label:r.t(`find-replace.dialog.find-scope.title`),children:A(_,{value:m,options:T,onChange:_e})}),A(h,{label:r.t(`find-replace.dialog.find-by.title`),children:A(_,{value:ce,options:ye,onChange:w})})]})}),A(oe,{children:j(k,{children:[A(h,{children:A(ae,{checked:te,onChange:e=>{n.changeCaseSensitive(e)},children:r.t(`find-replace.dialog.case-sensitive`)})}),A(h,{children:A(ae,{checked:ne,onChange:e=>{n.changeMatchesTheWholeCell(e)},children:r.t(`find-replace.dialog.match-the-whole-cell`)})})]})}),j(`div`,{className:`univer-mt-6 univer-flex univer-justify-between`,children:[A(ie,{variant:`primary`,onClick:x,disabled:le,children:r.t(`find-replace.dialog.find`)}),j(`span`,{className:`univer-inline-flex univer-gap-2`,children:[A(ie,{disabled:y,onClick:me,children:r.t(`find-replace.dialog.replace`)}),A(ie,{disabled:ue,onClick:he,children:r.t(`find-replace.dialog.replace-all`)})]})]})]})});function We(){let e=S(I),t=S(y),n=S(c),r=C(e.state$,void 0,!0),i=De(null);D(()=>{let e;return i.current&&(e=t.registerContainerElement(i.current)),()=>e==null?void 0:e.dispose()},[t]);let a=De(null),o=E(e=>n.setContextValue(Ae,e),[n]),s=E(e=>n.setContextValue(ke,e),[n]);return D(()=>{var e;let t=be(document,`focusin`).subscribe(e=>{var t;e.target&&(t=i.current)!=null&&t.contains(e.target)?o(!0):o(!1),!a.current||!a.current.selectHasFocus()?s(!1):s(!0)});return(e=a.current)==null||e.focus(),o(!0),s(!0),()=>{t.unsubscribe(),o(!1)}},[o,s]),A(`div`,{ref:i,"data-u-comp":`find-replace-dialog`,children:r.replaceRevealed?A(Ue,{ref:a}):A(He,{ref:a})})}function Ge(e){return O(()=>[{label:e.t(`find-replace.dialog.find-scope.current-sheet`),value:B.SUBUNIT},{label:e.t(`find-replace.dialog.find-scope.workbook`),value:B.UNIT}],[e.getCurrentLocale()])}function Ke(e){return O(()=>[{label:e.t(`find-replace.dialog.find-direction.row`),value:R.ROW},{label:e.t(`find-replace.dialog.find-direction.column`),value:R.COLUMN}],[e.getCurrentLocale()])}function qe(e){return O(()=>[{label:e.t(`find-replace.dialog.find-by.value`),value:z.VALUE},{label:e.t(`find-replace.dialog.find-by.formula`),value:z.FORMULA}],[e.getCurrentLocale()])}function Y(e){return e.getContextValue(Ae)}function Je(e){return e.getContextValue(je)}function Ye(e){return e.getContextValue(ke)}const X=`7_find-replace-shortcuts`;function Z(e){return e.getContextValue(i)}function Xe(e){return!e.getContextValue(r)}const Ze={id:G.id,description:`find-replace.shortcut.open-find-dialog`,binding:b.F|x.CTRL_COMMAND,group:X,preconditions(e){return!Y(e)&&Z(e)&&Xe(e)}},Qe={id:G.id,description:`find-replace.shortcut.open-find-dialog`,binding:b.F|x.CTRL_COMMAND,mac:b.F|x.MAC_CTRL,preconditions(e){return!Y(e)&&Z(e)&&Xe(e)}},$e={id:K.id,description:`find-replace.shortcut.open-replace-dialog`,binding:b.H|x.CTRL_COMMAND,mac:b.H|x.MAC_CTRL,group:X,preconditions(e){return Z(e)&&Xe(e)&&(!Y(e)||!Je(e))}},et={id:q.id,description:`find-replace.shortcut.go-to-next-match`,binding:b.ENTER,group:X,priority:1e3,preconditions(e){return Ye(e)&&Y(e)}},tt={id:J.id,description:`find-replace.shortcut.go-to-previous-match`,binding:b.ENTER|x.SHIFT,group:X,priority:1e3,preconditions(e){return Ye(e)&&Y(e)}},nt={id:Le.id,description:`find-replace.shortcut.focus-selection`,binding:b.ESC,group:X,priority:1e3,preconditions(e){return Y(e)}},rt=`DESKTOP_FIND_REPLACE_DIALOG`;let Q=class extends ee{constructor(e,t,n,r,i,a,o,s,c){super(),this._univerInstanceService=e,this._menuManagerService=t,this._shortcutService=n,this._commandService=r,this._findReplaceService=i,this._dialogService=a,this._layoutService=o,this._localeService=s,this._componentManager=c,N(this,`_closingListenerDisposable`,void 0),this._initCommands(),this._initUI(),this._initShortcuts()}dispose(){var e;super.dispose(),(e=this._closingListenerDisposable)==null||e.dispose(),this._closingListenerDisposable=null}_initCommands(){[G,K,q,J,W,U,Le].forEach(e=>{this.disposeWithMe(this._commandService.registerCommand(e))})}_initShortcuts(){[$e,Ze,Qe,tt,et,nt].forEach(e=>this.disposeWithMe(this._shortcutService.registerShortcut(e)))}_initUI(){[[`FindReplaceDialog`,We],[`SearchIcon`,we]].forEach(([e,t])=>{this.disposeWithMe(this._componentManager.register(e,t))}),this._menuManagerService.mergeMenu(ze),this._findReplaceService.stateUpdates$.pipe(Se(this.dispose$)).subscribe(e=>{e.revealed===!0&&this._openPanel()})}_openPanel(){this._dialogService.open({id:rt,draggable:!0,width:350,title:{title:this._localeService.t(`find-replace.dialog.title`)},children:{label:`FindReplaceDialog`},destroyOnClose:!0,mask:!1,maskClosable:!1,defaultPosition:it(),preservePositionOnDestroy:!0,onClose:()=>this.closePanel()}),this._closingListenerDisposable=m(this._univerInstanceService.focused$.pipe(Se(this.dispose$)).subscribe(e=>{(!e||!this._univerInstanceService.getUniverSheetInstance(e))&&this.closePanel()}))}closePanel(){this._closingListenerDisposable&&(this._closingListenerDisposable.dispose(),this._closingListenerDisposable=null,this._dialogService.close(rt),this._findReplaceService.terminate(),queueMicrotask(()=>this._layoutService.focus()))}};Q=F([P(0,l),P(1,ue),P(2,fe),P(3,a),P(4,I),P(5,le),P(6,y),P(7,u(f)),P(8,u(v))],Q);function it(){let{innerWidth:e}=window;return{x:e-350-20,y:64}}var at=`@univerjs/find-replace`,ot=`0.20.1`;const st=`find-replace.config`;Symbol(st);const ct={};let $=class extends p{constructor(e=ct,t,n){super(),this._config=e,this._injector=t,this._configService=n;let{...r}=re({},ct,this._config);this._configService.setConfig(st,r)}onStarting(){[[Q],[I,{useClass:H}]].forEach(e=>this._injector.add(e))}onRendered(){this._injector.get(Q)}};N($,`pluginName`,`UNIVER_FIND_REPLACE_PLUGIN`),N($,`packageName`,at),N($,`version`,ot),$=F([P(1,u(d)),P(2,o)],$);export{z as FindBy,R as FindDirection,Pe as FindModel,Q as FindReplaceController,L as FindReplaceModel,Ie as FindReplaceState,B as FindScope,q as GoToNextMatchOperation,J as GoToPreviousMatchOperation,I as IFindReplaceService,G as OpenFindDialogOperation,K as OpenReplaceDialogOperation,W as ReplaceAllMatchesCommand,U as ReplaceCurrentMatchCommand,$ as UniverFindReplacePlugin,V as createInitFindReplaceState};
1
+ import { CommandType, Disposable, DisposableCollection, EDITOR_ACTIVATED, FOCUSING_SHEET, ICommandService, IConfigService, IConfirmService, IContextService, IUniverInstanceService, Inject, Injector, LocaleService, Plugin, RxDisposable, UniverInstanceType, createIdentifier, merge, toDisposable } from "@univerjs/core";
2
+ import { Button, Checkbox, FormDualColumnLayout, FormLayout, Input, MessageType, Pager, Select } from "@univerjs/design";
3
+ import { ComponentManager, IDialogService, ILayoutService, IMenuManagerService, IMessageService, IShortcutService, KeyCode, MenuItemType, MetaKeys, RibbonDataGroup, getMenuHiddenObservable, useDebounceFn, useDependency, useObservable } from "@univerjs/ui";
4
+ import { RENDER_RAW_FORMULA_KEY } from "@univerjs/engine-render";
5
+ import { BehaviorSubject, Subject, combineLatest, debounceTime, fromEvent, map, takeUntil, throttleTime } from "rxjs";
6
+ import { SearchIcon } from "@univerjs/icons";
7
+ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+
10
+ //#region src/services/context-keys.ts
11
+ /**
12
+ * Copyright 2023-present DreamNum Co., Ltd.
13
+ *
14
+ * Licensed under the Apache License, Version 2.0 (the "License");
15
+ * you may not use this file except in compliance with the License.
16
+ * You may obtain a copy of the License at
17
+ *
18
+ * http://www.apache.org/licenses/LICENSE-2.0
19
+ *
20
+ * Unless required by applicable law or agreed to in writing, software
21
+ * distributed under the License is distributed on an "AS IS" BASIS,
22
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ * See the License for the specific language governing permissions and
24
+ * limitations under the License.
25
+ */
26
+ const FIND_REPLACE_INPUT_FOCUS = "FIND_REPLACE_INPUT_FOCUS";
27
+ /**
28
+ * If find replace panel is focused.
29
+ */
30
+ const FIND_REPLACE_DIALOG_FOCUS = "FIND_REPLACE_DIALOG_FOCUS";
31
+ /**
32
+ * If the find replace feature is activated and the replace is revealed.
33
+ */
34
+ const FIND_REPLACE_REPLACE_REVEALED = "FIND_REPLACE_REPLACE_REVEALED";
35
+
36
+ //#endregion
37
+ //#region \0@oxc-project+runtime@0.124.0/helpers/typeof.js
38
+ function _typeof(o) {
39
+ "@babel/helpers - typeof";
40
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
41
+ return typeof o;
42
+ } : function(o) {
43
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
44
+ }, _typeof(o);
45
+ }
46
+
47
+ //#endregion
48
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPrimitive.js
49
+ function toPrimitive(t, r) {
50
+ if ("object" != _typeof(t) || !t) return t;
51
+ var e = t[Symbol.toPrimitive];
52
+ if (void 0 !== e) {
53
+ var i = e.call(t, r || "default");
54
+ if ("object" != _typeof(i)) return i;
55
+ throw new TypeError("@@toPrimitive must return a primitive value.");
56
+ }
57
+ return ("string" === r ? String : Number)(t);
58
+ }
59
+
60
+ //#endregion
61
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPropertyKey.js
62
+ function toPropertyKey(t) {
63
+ var i = toPrimitive(t, "string");
64
+ return "symbol" == _typeof(i) ? i : i + "";
65
+ }
66
+
67
+ //#endregion
68
+ //#region \0@oxc-project+runtime@0.124.0/helpers/defineProperty.js
69
+ function _defineProperty(e, r, t) {
70
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
71
+ value: t,
72
+ enumerable: !0,
73
+ configurable: !0,
74
+ writable: !0
75
+ }) : e[r] = t, e;
76
+ }
77
+
78
+ //#endregion
79
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
80
+ function __decorateParam(paramIndex, decorator) {
81
+ return function(target, key) {
82
+ decorator(target, key, paramIndex);
83
+ };
84
+ }
85
+
86
+ //#endregion
87
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
88
+ function __decorate(decorators, target, key, desc) {
89
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
90
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
91
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
92
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
93
+ }
94
+
95
+ //#endregion
96
+ //#region src/services/find-replace.service.ts
97
+ var FindModel = class extends Disposable {};
98
+ const IFindReplaceService = createIdentifier("find-replace.service");
99
+ /**
100
+ *
101
+ * @param statusUpdate
102
+ */
103
+ function shouldStateUpdateTriggerResearch(statusUpdate) {
104
+ if (typeof statusUpdate.findString !== "undefined") return true;
105
+ if (typeof statusUpdate.inputtingFindString !== "undefined") return true;
106
+ if (typeof statusUpdate.findDirection !== "undefined") return true;
107
+ if (typeof statusUpdate.matchesTheWholeCell !== "undefined") return true;
108
+ if (typeof statusUpdate.caseSensitive !== "undefined") return true;
109
+ if (typeof statusUpdate.findScope !== "undefined") return true;
110
+ if (typeof statusUpdate.findBy !== "undefined") return true;
111
+ return false;
112
+ }
113
+ let FindReplaceModel = class FindReplaceModel extends Disposable {
114
+ get searched() {
115
+ return this._findModels.length > 0;
116
+ }
117
+ constructor(_state, _providers, _univerInstanceService, _commandService) {
118
+ super();
119
+ this._state = _state;
120
+ this._providers = _providers;
121
+ this._univerInstanceService = _univerInstanceService;
122
+ this._commandService = _commandService;
123
+ _defineProperty(this, "currentMatch$", new BehaviorSubject(null));
124
+ _defineProperty(this, "replaceables$", new BehaviorSubject([]));
125
+ _defineProperty(this, "_findModels", []);
126
+ _defineProperty(this, "_matchingModel", null);
127
+ _defineProperty(this, "_matches", []);
128
+ _defineProperty(this, "_currentSearchingDisposables", null);
129
+ this.disposeWithMe(this._state.stateUpdates$.pipe(throttleTime(200, void 0, {
130
+ leading: true,
131
+ trailing: true
132
+ })).subscribe(async (stateUpdate) => {
133
+ const state = this._state.state;
134
+ if (shouldStateUpdateTriggerResearch(stateUpdate)) {
135
+ if (state.findString !== "" && !state.replaceRevealed) {
136
+ await this._startSearching();
137
+ this._state.changeState({ findCompleted: true });
138
+ } else if (stateUpdate.replaceRevealed !== true) this._stopSearching();
139
+ }
140
+ }));
141
+ }
142
+ dispose() {
143
+ super.dispose();
144
+ this._stopSearching();
145
+ this.currentMatch$.complete();
146
+ this.replaceables$.complete();
147
+ this._state.changeState({
148
+ ...createInitFindReplaceState(),
149
+ revealed: false
150
+ });
151
+ }
152
+ async start() {
153
+ if (!this._state.findString) return { results: [] };
154
+ const complete = await this._startSearching();
155
+ this._state.changeState({ findCompleted: true });
156
+ return complete;
157
+ }
158
+ focusSelection() {
159
+ var _this$_matchingModel;
160
+ (_this$_matchingModel = this._matchingModel) === null || _this$_matchingModel === void 0 || _this$_matchingModel.focusSelection();
161
+ }
162
+ /** Call this method to start a `searching`. */
163
+ async _startSearching() {
164
+ if (!this._state.findString) return { results: [] };
165
+ const providers = Array.from(this._providers);
166
+ const findModels = this._findModels = (await Promise.all(providers.map((provider) => provider.find({
167
+ findString: this._state.findString,
168
+ findDirection: this._state.findDirection,
169
+ findScope: this._state.findScope,
170
+ findBy: this._state.findBy,
171
+ replaceRevealed: this._state.replaceRevealed,
172
+ caseSensitive: this._state.caseSensitive,
173
+ matchesTheWholeCell: this._state.matchesTheWholeCell
174
+ })))).flat();
175
+ this._subscribeToModelsChanges(findModels);
176
+ const newMatches = this._matches = findModels.map((c) => c.getMatches()).flat();
177
+ this.replaceables$.next(newMatches.filter((m) => m.replaceable));
178
+ if (!newMatches.length) {
179
+ this._state.changeState({
180
+ matchesCount: 0,
181
+ matchesPosition: 0
182
+ });
183
+ return { results: [] };
184
+ }
185
+ this._moveToInitialMatch(findModels);
186
+ this._state.changeState({ matchesCount: newMatches.length });
187
+ return { results: newMatches };
188
+ }
189
+ /** Terminate the current searching session, when searching string is empty. */
190
+ _stopSearching() {
191
+ var _this$_currentSearchi;
192
+ this._providers.forEach((provider) => provider.terminate());
193
+ this._findModels = [];
194
+ this._matches = [];
195
+ this._matchingModel = null;
196
+ (_this$_currentSearchi = this._currentSearchingDisposables) === null || _this$_currentSearchi === void 0 || _this$_currentSearchi.dispose();
197
+ this._currentSearchingDisposables = null;
198
+ this.currentMatch$.next(null);
199
+ this.replaceables$.next([]);
200
+ this._state.changeState({
201
+ findCompleted: false,
202
+ matchesCount: 0,
203
+ matchesPosition: 0
204
+ });
205
+ }
206
+ _subscribeToModelsChanges(models) {
207
+ const disposables = this._currentSearchingDisposables = new DisposableCollection();
208
+ const matchesUpdateSubscription = combineLatest(models.map((model) => model.matchesUpdate$)).pipe(debounceTime(220)).subscribe(([ ...allMatches]) => {
209
+ const newMatches = this._matches = allMatches.flat();
210
+ if (newMatches.length) {
211
+ this._moveToInitialMatch(this._findModels, true);
212
+ this._state.changeState({ matchesCount: newMatches.length });
213
+ this.replaceables$.next(newMatches.filter((m) => m.replaceable));
214
+ } else {
215
+ this._state.changeState({
216
+ matchesCount: 0,
217
+ matchesPosition: 0
218
+ });
219
+ this.replaceables$.next([]);
220
+ }
221
+ });
222
+ models.forEach((model) => disposables.add(toDisposable(model.activelyChangingMatch$.subscribe((match) => {
223
+ const index = this._matches.findIndex((m) => m === match);
224
+ this._state.changeState({ matchesPosition: index + 1 });
225
+ }))));
226
+ disposables.add(toDisposable(matchesUpdateSubscription));
227
+ }
228
+ async replace() {
229
+ if (!this._matchingModel) return false;
230
+ return this._matchingModel.replace(this._state.replaceString);
231
+ }
232
+ async replaceAll() {
233
+ const result = await Promise.all(this._findModels.map((m) => m.replaceAll(this._state.replaceString))).then((results) => results.reduce((acc, cur) => {
234
+ acc.success += cur.success;
235
+ acc.failure += cur.failure;
236
+ return acc;
237
+ }, {
238
+ success: 0,
239
+ failure: 0
240
+ }));
241
+ if (result.failure === 0) this._stopSearching();
242
+ return result;
243
+ }
244
+ getCurrentMatch() {
245
+ return this._state.matchesPosition > 0 ? this._matches[this._state.matchesPosition - 1] : null;
246
+ }
247
+ _markMatch(match) {
248
+ const index = this._matches.findIndex((value) => value === match);
249
+ this.currentMatch$.next(match);
250
+ this._state.changeState({ matchesPosition: index + 1 });
251
+ }
252
+ moveToNextMatch() {
253
+ if (!this._matchingModel) return;
254
+ const loopInCurrentUnit = this._findModels.length === 1;
255
+ const nextMatch = this._matchingModel.moveToNextMatch({ loop: loopInCurrentUnit });
256
+ if (nextMatch) {
257
+ this._markMatch(nextMatch);
258
+ return nextMatch;
259
+ } else {
260
+ const currentModelIndex = this._findModels.findIndex((m) => m === this._matchingModel);
261
+ return this._moveToNextUnitMatch(currentModelIndex);
262
+ }
263
+ }
264
+ _moveToNextUnitMatch(startingIndex) {
265
+ const l = this._findModels.length;
266
+ for (let i = (startingIndex + 1) % l; i !== startingIndex;) {
267
+ const nextPositionModel = this._findModels[i];
268
+ const nextMatch = nextPositionModel.moveToNextMatch({ ignoreSelection: true });
269
+ if (nextMatch) {
270
+ this._matchingModel = nextPositionModel;
271
+ this._markMatch(nextMatch);
272
+ return nextMatch;
273
+ }
274
+ i = (i + 1) % l;
275
+ }
276
+ if (this._matchingModel) {
277
+ const nextMatch = this._matchingModel.moveToNextMatch({ ignoreSelection: true });
278
+ if (nextMatch) this._markMatch(nextMatch);
279
+ return nextMatch;
280
+ }
281
+ }
282
+ moveToPreviousMatch() {
283
+ if (!this._matchingModel) return;
284
+ const loopInCurrentUnit = this._findModels.length === 1;
285
+ const nextMatch = this._matchingModel.moveToPreviousMatch({ loop: loopInCurrentUnit });
286
+ if (nextMatch) {
287
+ const index = this._matches.findIndex((value) => value === nextMatch);
288
+ this.currentMatch$.next(nextMatch);
289
+ this._state.changeState({ matchesPosition: index + 1 });
290
+ return nextMatch;
291
+ } else {
292
+ const l = this._findModels.length;
293
+ const currentModelIndex = this._findModels.findIndex((m) => m === this._matchingModel);
294
+ for (let i = (currentModelIndex - 1 + l) % l; i !== currentModelIndex;) {
295
+ const nextPositionModel = this._findModels[i];
296
+ const nextMatch = nextPositionModel.moveToPreviousMatch({ ignoreSelection: true });
297
+ if (nextMatch) {
298
+ this._matchingModel = nextPositionModel;
299
+ this._markMatch(nextMatch);
300
+ return nextMatch;
301
+ }
302
+ i = (i - 1) % l;
303
+ }
304
+ const nextMatch = this._matchingModel.moveToPreviousMatch({ ignoreSelection: true });
305
+ if (nextMatch) this._markMatch(nextMatch);
306
+ return nextMatch;
307
+ }
308
+ }
309
+ _moveToInitialMatch(findModels, noFocus = false) {
310
+ var _this$_univerInstance;
311
+ const focusedUnitId = (_this$_univerInstance = this._univerInstanceService.getFocusedUnit()) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getUnitId();
312
+ if (!focusedUnitId) return -1;
313
+ const i = findModels.findIndex((model) => model.unitId === focusedUnitId);
314
+ if (i !== -1) {
315
+ this._matchingModel = findModels[i];
316
+ const nextMatch = this._matchingModel.moveToNextMatch({
317
+ stayIfOnMatch: true,
318
+ noFocus
319
+ });
320
+ if (nextMatch) {
321
+ this._markMatch(nextMatch);
322
+ return i;
323
+ }
324
+ }
325
+ this._moveToNextUnitMatch(i);
326
+ return 0;
327
+ }
328
+ };
329
+ FindReplaceModel = __decorate([__decorateParam(2, IUniverInstanceService), __decorateParam(3, ICommandService)], FindReplaceModel);
330
+ let FindDirection = /* @__PURE__ */ function(FindDirection) {
331
+ /** Default. */
332
+ FindDirection["ROW"] = "row";
333
+ FindDirection["COLUMN"] = "column";
334
+ return FindDirection;
335
+ }({});
336
+ let FindBy = /* @__PURE__ */ function(FindBy) {
337
+ FindBy["VALUE"] = "value";
338
+ FindBy["FORMULA"] = "formula";
339
+ return FindBy;
340
+ }({});
341
+ let FindScope = /* @__PURE__ */ function(FindScope) {
342
+ /** Default. */
343
+ FindScope["SUBUNIT"] = "subunit";
344
+ /** Find the scope in the current unit. */
345
+ FindScope["UNIT"] = "unit";
346
+ return FindScope;
347
+ }({});
348
+ function createInitFindReplaceState() {
349
+ return {
350
+ caseSensitive: false,
351
+ findBy: FindBy.VALUE,
352
+ findCompleted: false,
353
+ findDirection: FindDirection.ROW,
354
+ findScope: FindScope.SUBUNIT,
355
+ findString: "",
356
+ inputtingFindString: "",
357
+ matchesCount: 0,
358
+ matchesPosition: 0,
359
+ matchesTheWholeCell: false,
360
+ replaceRevealed: false,
361
+ replaceString: "",
362
+ revealed: true
363
+ };
364
+ }
365
+ /**
366
+ * This class stores find replace options state. These state are stored
367
+ * here instead of the React component so we can change state from
368
+ * operations.
369
+ */
370
+ var FindReplaceState = class {
371
+ constructor() {
372
+ _defineProperty(this, "_stateUpdates$", new Subject());
373
+ _defineProperty(this, "stateUpdates$", this._stateUpdates$.asObservable());
374
+ _defineProperty(this, "_state$", new BehaviorSubject(createInitFindReplaceState()));
375
+ _defineProperty(this, "state$", this._state$.asObservable());
376
+ _defineProperty(this, "_findString", "");
377
+ _defineProperty(this, "_inputtingFindString", "");
378
+ _defineProperty(this, "_replaceString", "");
379
+ _defineProperty(this, "_revealed", false);
380
+ _defineProperty(this, "_replaceRevealed", false);
381
+ _defineProperty(this, "_matchesPosition", 0);
382
+ _defineProperty(this, "_matchesCount", 0);
383
+ _defineProperty(this, "_caseSensitive", true);
384
+ _defineProperty(this, "_matchesTheWholeCell", false);
385
+ _defineProperty(this, "_findDirection", FindDirection.ROW);
386
+ _defineProperty(this, "_findScope", FindScope.SUBUNIT);
387
+ _defineProperty(this, "_findBy", FindBy.VALUE);
388
+ _defineProperty(this, "_findCompleted", false);
389
+ }
390
+ get state() {
391
+ return this._state$.getValue();
392
+ }
393
+ get inputtingFindString() {
394
+ return this._inputtingFindString;
395
+ }
396
+ get findString() {
397
+ return this._findString;
398
+ }
399
+ get revealed() {
400
+ return this._revealed;
401
+ }
402
+ get replaceRevealed() {
403
+ return this._replaceRevealed;
404
+ }
405
+ get matchesPosition() {
406
+ return this._matchesPosition;
407
+ }
408
+ get matchesCount() {
409
+ return this._matchesCount;
410
+ }
411
+ get replaceString() {
412
+ return this._replaceString;
413
+ }
414
+ get caseSensitive() {
415
+ return this._caseSensitive;
416
+ }
417
+ get matchesTheWholeCell() {
418
+ return this._matchesTheWholeCell;
419
+ }
420
+ get findDirection() {
421
+ return this._findDirection;
422
+ }
423
+ get findScope() {
424
+ return this._findScope;
425
+ }
426
+ get findBy() {
427
+ return this._findBy;
428
+ }
429
+ get findCompleted() {
430
+ return this._findCompleted;
431
+ }
432
+ changeState(changes) {
433
+ let changed = false;
434
+ const changedState = {};
435
+ if (typeof changes.findString !== "undefined" && changes.findString !== this._findString) {
436
+ this._findString = changes.findString;
437
+ changedState.findString = this._findString;
438
+ changed = true;
439
+ }
440
+ if (typeof changes.revealed !== "undefined" && changes.revealed !== this._revealed) {
441
+ this._revealed = changes.revealed;
442
+ changedState.revealed = changes.revealed;
443
+ changed = true;
444
+ }
445
+ if (typeof changes.replaceRevealed !== "undefined" && changes.replaceRevealed !== this._replaceRevealed) {
446
+ this._replaceRevealed = changes.replaceRevealed;
447
+ changedState.replaceRevealed = changes.replaceRevealed;
448
+ changed = true;
449
+ }
450
+ if (typeof changes.replaceString !== "undefined" && changes.replaceString !== this._replaceString) {
451
+ this._replaceString = changes.replaceString;
452
+ changedState.replaceString = changes.replaceString;
453
+ changed = true;
454
+ }
455
+ if (typeof changes.matchesCount !== "undefined" && changes.matchesCount !== this._matchesCount) {
456
+ this._matchesCount = changes.matchesCount;
457
+ changedState.matchesCount = changes.matchesCount;
458
+ changed = true;
459
+ }
460
+ if (typeof changes.matchesPosition !== "undefined" && changes.matchesPosition !== this._matchesPosition) {
461
+ this._matchesPosition = changes.matchesPosition;
462
+ changedState.matchesPosition = changes.matchesPosition;
463
+ changed = true;
464
+ }
465
+ if (typeof changes.findBy !== "undefined" && changes.findBy !== this._findBy) {
466
+ this._findBy = changes.findBy;
467
+ changedState.findBy = changes.findBy;
468
+ changed = true;
469
+ }
470
+ if (typeof changes.findScope !== "undefined" && changes.findScope !== this._findScope) {
471
+ this._findScope = changes.findScope;
472
+ changedState.findScope = changes.findScope;
473
+ changed = true;
474
+ }
475
+ if (typeof changes.findDirection !== "undefined" && changes.findDirection !== this._findDirection) {
476
+ this._findDirection = changes.findDirection;
477
+ changedState.findDirection = changes.findDirection;
478
+ changed = true;
479
+ }
480
+ if (typeof changes.caseSensitive !== "undefined" && changes.caseSensitive !== this._caseSensitive) {
481
+ this._caseSensitive = changes.caseSensitive;
482
+ changedState.caseSensitive = changes.caseSensitive;
483
+ changed = true;
484
+ }
485
+ if (typeof changes.matchesTheWholeCell !== "undefined" && changes.matchesTheWholeCell !== this._matchesTheWholeCell) {
486
+ this._matchesTheWholeCell = changes.matchesTheWholeCell;
487
+ changedState.matchesTheWholeCell = changes.matchesTheWholeCell;
488
+ changed = true;
489
+ }
490
+ if (typeof changes.inputtingFindString !== "undefined" && changes.inputtingFindString !== this._inputtingFindString) {
491
+ this._inputtingFindString = changes.inputtingFindString;
492
+ changedState.inputtingFindString = changes.inputtingFindString;
493
+ changed = true;
494
+ }
495
+ if (typeof changes.findCompleted !== "undefined" && changes.findCompleted !== this._findCompleted) {
496
+ this._findCompleted = changes.findCompleted;
497
+ changedState.findCompleted = changes.findCompleted;
498
+ changed = true;
499
+ }
500
+ if (changed) {
501
+ this._state$.next({
502
+ caseSensitive: this._caseSensitive,
503
+ findBy: this._findBy,
504
+ findCompleted: this._findCompleted,
505
+ findDirection: this._findDirection,
506
+ findScope: this._findScope,
507
+ findString: this._findString,
508
+ inputtingFindString: this._inputtingFindString,
509
+ matchesCount: this._matchesCount,
510
+ matchesPosition: this._matchesPosition,
511
+ matchesTheWholeCell: this._matchesTheWholeCell,
512
+ replaceRevealed: this._replaceRevealed,
513
+ revealed: this._revealed
514
+ });
515
+ this._stateUpdates$.next(changedState);
516
+ }
517
+ }
518
+ };
519
+ let FindReplaceService = class FindReplaceService extends Disposable {
520
+ get stateUpdates$() {
521
+ return this._state.stateUpdates$;
522
+ }
523
+ get state$() {
524
+ return this._state.state$;
525
+ }
526
+ get revealed() {
527
+ return this._state.revealed;
528
+ }
529
+ get replaceRevealed() {
530
+ return this._state.replaceRevealed;
531
+ }
532
+ constructor(_injector, _contextService) {
533
+ super();
534
+ this._injector = _injector;
535
+ this._contextService = _contextService;
536
+ _defineProperty(this, "_providers", /* @__PURE__ */ new Set());
537
+ _defineProperty(this, "_state", new FindReplaceState());
538
+ _defineProperty(this, "_model", void 0);
539
+ _defineProperty(this, "_currentMatch$", new BehaviorSubject(null));
540
+ _defineProperty(this, "currentMatch$", this._currentMatch$.asObservable());
541
+ _defineProperty(this, "_replaceables$", new BehaviorSubject([]));
542
+ _defineProperty(this, "replaceables$", this._replaceables$.asObservable());
543
+ _defineProperty(this, "_focusSignal$", new Subject());
544
+ _defineProperty(this, "focusSignal$", this._focusSignal$.asObservable());
545
+ }
546
+ dispose() {
547
+ super.dispose();
548
+ this._currentMatch$.next(null);
549
+ this._currentMatch$.complete();
550
+ this._replaceables$.next([]);
551
+ this._replaceables$.complete();
552
+ this._focusSignal$.complete();
553
+ }
554
+ getProviders() {
555
+ return this._providers;
556
+ }
557
+ getCurrentMatch() {
558
+ var _this$_model;
559
+ return (_this$_model = this._model) === null || _this$_model === void 0 ? void 0 : _this$_model.getCurrentMatch();
560
+ }
561
+ getFindString() {
562
+ return this._state.findString;
563
+ }
564
+ changeFindString(findString) {
565
+ this._state.changeState({ findString });
566
+ }
567
+ focusFindInput() {
568
+ this._focusSignal$.next();
569
+ }
570
+ changeInputtingFindString(value) {
571
+ if (value) this._state.changeState({ inputtingFindString: value });
572
+ else this._state.changeState({
573
+ inputtingFindString: "",
574
+ findString: ""
575
+ });
576
+ }
577
+ changeReplaceString(replaceString) {
578
+ this._state.changeState({ replaceString });
579
+ }
580
+ changeMatchesTheWholeCell(matchesTheWholeCell) {
581
+ this._state.changeState({ matchesTheWholeCell });
582
+ }
583
+ changeCaseSensitive(caseSensitive) {
584
+ this._state.changeState({ caseSensitive });
585
+ }
586
+ changeFindBy(findBy) {
587
+ this._state.changeState({ findBy });
588
+ this._toggleDisplayRawFormula(findBy === FindBy.FORMULA);
589
+ }
590
+ changeFindScope(scope) {
591
+ this._state.changeState({ findScope: scope });
592
+ }
593
+ changeFindDirection(direction) {
594
+ this._state.changeState({ findDirection: direction });
595
+ }
596
+ moveToNextMatch() {
597
+ if (!this._model) return;
598
+ if (this._state.replaceRevealed && !this._model.searched) {
599
+ this._state.changeState({ findString: this._state.inputtingFindString });
600
+ this._model.start();
601
+ } else this._model.moveToNextMatch();
602
+ this._focusSignal$.next();
603
+ }
604
+ moveToPreviousMatch() {
605
+ if (!this._model) return;
606
+ if (this._state.replaceRevealed && !this._model.searched) {
607
+ this._state.changeState({ findString: this._state.inputtingFindString });
608
+ this._model.start();
609
+ } else this._model.moveToPreviousMatch();
610
+ this._focusSignal$.next();
611
+ }
612
+ async replace() {
613
+ if (!this._model) return false;
614
+ return this._model.replace();
615
+ }
616
+ async replaceAll() {
617
+ if (!this._model) throw new Error("[FindReplaceService] replaceAll: model is not initialized!");
618
+ return this._model.replaceAll();
619
+ }
620
+ revealReplace() {
621
+ this._state.changeState({
622
+ replaceRevealed: true,
623
+ inputtingFindString: this._state.findString
624
+ });
625
+ this._toggleRevealReplace(true);
626
+ }
627
+ focusSelection() {
628
+ var _this$_model2;
629
+ (_this$_model2 = this._model) === null || _this$_model2 === void 0 || _this$_model2.focusSelection();
630
+ }
631
+ start(revealReplace = false) {
632
+ if (this._providers.size === 0) return false;
633
+ this._model = this._injector.createInstance(FindReplaceModel, this._state, this._providers);
634
+ this._model.currentMatch$.subscribe((match) => this._currentMatch$.next(match));
635
+ this._model.replaceables$.subscribe((replaceables) => this._replaceables$.next(replaceables));
636
+ const newState = createInitFindReplaceState();
637
+ if (revealReplace) newState.replaceRevealed = true;
638
+ this._state.changeState(newState);
639
+ this._toggleRevealReplace(revealReplace);
640
+ return true;
641
+ }
642
+ find() {
643
+ var _this$_model3;
644
+ (_this$_model3 = this._model) === null || _this$_model3 === void 0 || _this$_model3.start();
645
+ }
646
+ terminate() {
647
+ var _this$_model4;
648
+ (_this$_model4 = this._model) === null || _this$_model4 === void 0 || _this$_model4.dispose();
649
+ this._model = null;
650
+ this._toggleDisplayRawFormula(false);
651
+ this._toggleRevealReplace(false);
652
+ }
653
+ registerFindReplaceProvider(provider) {
654
+ this._providers.add(provider);
655
+ return toDisposable(() => this._providers.delete(provider));
656
+ }
657
+ _toggleRevealReplace(revealReplace) {
658
+ this._contextService.setContextValue(FIND_REPLACE_REPLACE_REVEALED, revealReplace);
659
+ }
660
+ _toggleDisplayRawFormula(force) {
661
+ this._contextService.setContextValue(RENDER_RAW_FORMULA_KEY, force);
662
+ }
663
+ };
664
+ FindReplaceService = __decorate([__decorateParam(0, Inject(Injector)), __decorateParam(1, IContextService)], FindReplaceService);
665
+
666
+ //#endregion
667
+ //#region src/commands/commands/replace.command.ts
668
+ const ReplaceCurrentMatchCommand = {
669
+ id: "ui.command.replace-current-match",
670
+ type: CommandType.COMMAND,
671
+ handler: (accessor) => {
672
+ return accessor.get(IFindReplaceService).replace();
673
+ }
674
+ };
675
+ const CONFIRM_REPLACE_ALL_ID = "CONFIRM_REPLACE_ALL";
676
+ const ReplaceAllMatchesCommand = {
677
+ id: "ui.command.replace-all-matches",
678
+ type: CommandType.COMMAND,
679
+ handler: async (accessor) => {
680
+ const confirmService = accessor.get(IConfirmService);
681
+ const localeService = accessor.get(LocaleService);
682
+ const messageService = accessor.get(IMessageService);
683
+ if (!await confirmService.confirm({
684
+ id: CONFIRM_REPLACE_ALL_ID,
685
+ title: { title: localeService.t("find-replace.replace.confirm.title") },
686
+ cancelText: localeService.t("button.cancel"),
687
+ confirmText: localeService.t("button.confirm")
688
+ })) return false;
689
+ const { success, failure } = await accessor.get(IFindReplaceService).replaceAll();
690
+ if (failure > 0) {
691
+ if (success === 0) messageService.show({
692
+ type: MessageType.Error,
693
+ content: localeService.t("find-replace.replace.all-failure")
694
+ });
695
+ else messageService.show({
696
+ type: MessageType.Warning,
697
+ content: localeService.t("find-replace.replace.partial-success", `${success}`, `${failure}`)
698
+ });
699
+ return false;
700
+ }
701
+ messageService.show({
702
+ type: MessageType.Success,
703
+ content: localeService.t("find-replace.replace.all-success", `${success}`)
704
+ });
705
+ return true;
706
+ }
707
+ };
708
+
709
+ //#endregion
710
+ //#region src/commands/operations/find-replace.operation.ts
711
+ const OpenFindDialogOperation = {
712
+ id: "ui.operation.open-find-dialog",
713
+ type: CommandType.OPERATION,
714
+ handler: (accessor) => {
715
+ const findReplaceService = accessor.get(IFindReplaceService);
716
+ if (!findReplaceService.revealed) findReplaceService.start();
717
+ else findReplaceService.focusFindInput();
718
+ return true;
719
+ }
720
+ };
721
+ const OpenReplaceDialogOperation = {
722
+ id: "ui.operation.open-replace-dialog",
723
+ type: CommandType.OPERATION,
724
+ handler: (accessor) => {
725
+ const findReplaceService = accessor.get(IFindReplaceService);
726
+ if (!findReplaceService.revealed) findReplaceService.start(true);
727
+ else if (!findReplaceService.replaceRevealed) findReplaceService.revealReplace();
728
+ else findReplaceService.focusFindInput();
729
+ return true;
730
+ }
731
+ };
732
+ const GoToNextMatchOperation = {
733
+ type: CommandType.OPERATION,
734
+ id: "ui.operation.go-to-next-match",
735
+ handler: (accessor) => {
736
+ accessor.get(IFindReplaceService).moveToNextMatch();
737
+ return true;
738
+ }
739
+ };
740
+ const GoToPreviousMatchOperation = {
741
+ type: CommandType.OPERATION,
742
+ id: "ui.operation.go-to-previous-match",
743
+ handler: (accessor) => {
744
+ accessor.get(IFindReplaceService).moveToPreviousMatch();
745
+ return true;
746
+ }
747
+ };
748
+ const FocusSelectionOperation = {
749
+ type: CommandType.OPERATION,
750
+ id: "ui.operation.focus-selection",
751
+ handler: (accessor) => {
752
+ accessor.get(IFindReplaceService).focusSelection();
753
+ return true;
754
+ }
755
+ };
756
+
757
+ //#endregion
758
+ //#region src/menu/find-replace.menu.ts
759
+ function FindReplaceMenuItemFactory(accessor) {
760
+ const contextService = accessor.get(IContextService);
761
+ return {
762
+ id: OpenFindDialogOperation.id,
763
+ icon: "SearchIcon",
764
+ tooltip: "find-replace.toolbar",
765
+ type: MenuItemType.BUTTON,
766
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
767
+ disabled$: combineLatest([contextService.subscribeContextValue$(EDITOR_ACTIVATED), contextService.subscribeContextValue$(FOCUSING_SHEET)]).pipe(map(([editorActivated, focusingSheet]) => editorActivated || !focusingSheet))
768
+ };
769
+ }
770
+
771
+ //#endregion
772
+ //#region src/menu/schema.ts
773
+ const menuSchema = { [RibbonDataGroup.ORGANIZATION]: { [OpenFindDialogOperation.id]: {
774
+ order: 2,
775
+ menuItemFactory: FindReplaceMenuItemFactory
776
+ } } };
777
+
778
+ //#endregion
779
+ //#region src/views/dialog/SearchInput.tsx
780
+ function SearchInput(props) {
781
+ const { findCompleted: findComplete, localeService, matchesCount, matchesPosition, initialFindString, findReplaceService, onChange, ...rest } = props;
782
+ const [value, setValue] = useState(initialFindString);
783
+ const text = findComplete && matchesCount === 0 ? localeService.t("find-replace.dialog.no-result") : matchesCount === 0 ? " " : void 0;
784
+ function handleChangePosition(newIndex) {
785
+ if (matchesPosition === matchesCount && newIndex === 1) findReplaceService.moveToNextMatch();
786
+ else if (matchesPosition === 1 && newIndex === matchesCount) findReplaceService.moveToPreviousMatch();
787
+ else if (newIndex < matchesPosition) findReplaceService.moveToPreviousMatch();
788
+ else findReplaceService.moveToNextMatch();
789
+ }
790
+ return /* @__PURE__ */ jsx("div", {
791
+ className: "univer-relative univer-flex univer-items-center univer-gap-2",
792
+ onDrag: (e) => e.stopPropagation(),
793
+ children: /* @__PURE__ */ jsx(Input, {
794
+ "data-u-comp": "search-input",
795
+ autoFocus: true,
796
+ placeholder: localeService.t("find-replace.dialog.find-placeholder"),
797
+ value,
798
+ onChange: (value) => {
799
+ setValue(value);
800
+ onChange === null || onChange === void 0 || onChange(value);
801
+ },
802
+ slot: /* @__PURE__ */ jsx(Pager, {
803
+ loop: true,
804
+ text,
805
+ value: matchesPosition,
806
+ total: matchesCount,
807
+ onChange: handleChangePosition
808
+ }),
809
+ ...rest
810
+ })
811
+ });
812
+ }
813
+
814
+ //#endregion
815
+ //#region src/views/dialog/FindReplaceDialog.tsx
816
+ function useFindInputFocus(findReplaceService, ref) {
817
+ const focus = useCallback(() => {
818
+ var _document$querySelect;
819
+ (_document$querySelect = document.querySelector(".univer-find-input input")) === null || _document$querySelect === void 0 || _document$querySelect.focus();
820
+ }, []);
821
+ const selectHasFocus = useCallback(() => {
822
+ const allInputs = document.querySelectorAll("[data-u-comp=find-replace-dialog] [data-u-comp=search-input]");
823
+ return Array.from(allInputs).some((input) => input === document.activeElement);
824
+ }, []);
825
+ useImperativeHandle(ref, () => ({
826
+ focus,
827
+ selectHasFocus
828
+ }));
829
+ useEffect(() => {
830
+ const subscription = findReplaceService.focusSignal$.subscribe(() => focus());
831
+ return () => subscription.unsubscribe();
832
+ }, [findReplaceService, focus]);
833
+ return {
834
+ focus,
835
+ selectHasFocus
836
+ };
837
+ }
838
+ const FindDialog = forwardRef(function FindDialogImpl(_props, ref) {
839
+ const localeService = useDependency(LocaleService);
840
+ const findReplaceService = useDependency(IFindReplaceService);
841
+ const commandService = useDependency(ICommandService);
842
+ const { findCompleted, findString, matchesCount, matchesPosition } = useObservable(findReplaceService.state$, void 0, true);
843
+ const revealReplace = useCallback(() => {
844
+ commandService.executeCommand(OpenReplaceDialogOperation.id);
845
+ }, [commandService]);
846
+ const onFindStringChange = useDebounceFn((findString) => {
847
+ return findReplaceService.changeFindString(findString);
848
+ }, 500);
849
+ useFindInputFocus(findReplaceService, ref);
850
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(SearchInput, {
851
+ findCompleted,
852
+ matchesCount,
853
+ matchesPosition,
854
+ findReplaceService,
855
+ localeService,
856
+ initialFindString: findString,
857
+ onChange: onFindStringChange
858
+ }), /* @__PURE__ */ jsx("div", {
859
+ className: "univer-mt-4 univer-text-center",
860
+ children: /* @__PURE__ */ jsx("a", {
861
+ className: "hover:univer-text-primary-500/80 univer-cursor-pointer univer-text-sm univer-text-primary-500 univer-transition-colors",
862
+ onClick: revealReplace,
863
+ children: localeService.t("find-replace.dialog.advanced-finding")
864
+ })
865
+ })] });
866
+ });
867
+ const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref) {
868
+ const findReplaceService = useDependency(IFindReplaceService);
869
+ const localeService = useDependency(LocaleService);
870
+ const commandService = useDependency(ICommandService);
871
+ const messageService = useDependency(IMessageService);
872
+ const currentMatch = useObservable(findReplaceService.currentMatch$, void 0, true);
873
+ const replaceables = useObservable(findReplaceService.replaceables$, void 0, true);
874
+ const { matchesCount, matchesPosition, findString, inputtingFindString, replaceString, caseSensitive, matchesTheWholeCell, findDirection, findScope, findBy, findCompleted } = useObservable(findReplaceService.state$, void 0, true);
875
+ const findDisabled = inputtingFindString.length === 0;
876
+ const replaceDisabled = matchesCount === 0 || !(currentMatch === null || currentMatch === void 0 ? void 0 : currentMatch.replaceable);
877
+ const replaceAllDisabled = replaceables.length === 0;
878
+ const onFindStringChange = useCallback((newValue) => findReplaceService.changeInputtingFindString(newValue), [findReplaceService]);
879
+ const onReplaceStringChange = useCallback((replaceString) => findReplaceService.changeReplaceString(replaceString), [findReplaceService]);
880
+ const { focus } = useFindInputFocus(findReplaceService, ref);
881
+ const onClickFindButton = useCallback(() => {
882
+ if (findString === inputtingFindString) findReplaceService.moveToNextMatch();
883
+ else {
884
+ findReplaceService.changeFindString(inputtingFindString);
885
+ findReplaceService.find();
886
+ }
887
+ }, [
888
+ findString,
889
+ inputtingFindString,
890
+ findReplaceService
891
+ ]);
892
+ const onClickReplaceButton = useCallback(() => commandService.executeCommand(ReplaceCurrentMatchCommand.id), [commandService]);
893
+ const onClickReplaceAllButton = useCallback(async () => {
894
+ await commandService.executeCommand(ReplaceAllMatchesCommand.id);
895
+ focus();
896
+ }, [commandService]);
897
+ const onChangeFindDirection = useCallback((findDirection) => {
898
+ findReplaceService.changeFindDirection(findDirection);
899
+ }, [findReplaceService]);
900
+ const onChangeFindScope = useCallback((findScope) => {
901
+ findReplaceService.changeFindScope(findScope);
902
+ }, [findReplaceService]);
903
+ const onChangeFindBy = useCallback((findBy) => {
904
+ findReplaceService.changeFindBy(findBy);
905
+ }, [findReplaceService]);
906
+ const findScopeOptions = useFindScopeOptions(localeService);
907
+ const findDirectionOptions = useFindDirectionOptions(localeService);
908
+ const findByOptions = useFindByOptions(localeService);
909
+ useEffect(() => {
910
+ if (findCompleted && matchesCount === 0) messageService.show({
911
+ content: localeService.t("find-replace.dialog.no-match"),
912
+ type: MessageType.Warning,
913
+ duration: 5e3
914
+ });
915
+ }, [
916
+ findCompleted,
917
+ matchesCount,
918
+ messageService,
919
+ localeService
920
+ ]);
921
+ return /* @__PURE__ */ jsxs("div", { children: [
922
+ /* @__PURE__ */ jsx(FormLayout, {
923
+ label: localeService.t("find-replace.dialog.find"),
924
+ children: /* @__PURE__ */ jsx(SearchInput, {
925
+ findCompleted,
926
+ className: "univer-find-input",
927
+ matchesCount,
928
+ matchesPosition,
929
+ findReplaceService,
930
+ localeService,
931
+ initialFindString: inputtingFindString,
932
+ onChange: onFindStringChange
933
+ })
934
+ }),
935
+ /* @__PURE__ */ jsx(FormLayout, {
936
+ label: localeService.t("find-replace.dialog.replace"),
937
+ children: /* @__PURE__ */ jsx(Input, {
938
+ placeholder: localeService.t("find-replace.dialog.replace-placeholder"),
939
+ value: replaceString,
940
+ onChange: (value) => onReplaceStringChange(value)
941
+ })
942
+ }),
943
+ /* @__PURE__ */ jsx(FormLayout, {
944
+ label: localeService.t("find-replace.dialog.find-direction.title"),
945
+ children: /* @__PURE__ */ jsx(Select, {
946
+ value: findDirection,
947
+ options: findDirectionOptions,
948
+ onChange: onChangeFindDirection
949
+ })
950
+ }),
951
+ /* @__PURE__ */ jsx(FormDualColumnLayout, { children: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(FormLayout, {
952
+ label: localeService.t("find-replace.dialog.find-scope.title"),
953
+ children: /* @__PURE__ */ jsx(Select, {
954
+ value: findScope,
955
+ options: findScopeOptions,
956
+ onChange: onChangeFindScope
957
+ })
958
+ }), /* @__PURE__ */ jsx(FormLayout, {
959
+ label: localeService.t("find-replace.dialog.find-by.title"),
960
+ children: /* @__PURE__ */ jsx(Select, {
961
+ value: findBy,
962
+ options: findByOptions,
963
+ onChange: onChangeFindBy
964
+ })
965
+ })] }) }),
966
+ /* @__PURE__ */ jsx(FormDualColumnLayout, { children: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(FormLayout, { children: /* @__PURE__ */ jsx(Checkbox, {
967
+ checked: caseSensitive,
968
+ onChange: (checked) => {
969
+ findReplaceService.changeCaseSensitive(checked);
970
+ },
971
+ children: localeService.t("find-replace.dialog.case-sensitive")
972
+ }) }), /* @__PURE__ */ jsx(FormLayout, { children: /* @__PURE__ */ jsx(Checkbox, {
973
+ checked: matchesTheWholeCell,
974
+ onChange: (checked) => {
975
+ findReplaceService.changeMatchesTheWholeCell(checked);
976
+ },
977
+ children: localeService.t("find-replace.dialog.match-the-whole-cell")
978
+ }) })] }) }),
979
+ /* @__PURE__ */ jsxs("div", {
980
+ className: "univer-mt-6 univer-flex univer-justify-between",
981
+ children: [/* @__PURE__ */ jsx(Button, {
982
+ variant: "primary",
983
+ onClick: onClickFindButton,
984
+ disabled: findDisabled,
985
+ children: localeService.t("find-replace.dialog.find")
986
+ }), /* @__PURE__ */ jsxs("span", {
987
+ className: "univer-inline-flex univer-gap-2",
988
+ children: [/* @__PURE__ */ jsx(Button, {
989
+ disabled: replaceDisabled,
990
+ onClick: onClickReplaceButton,
991
+ children: localeService.t("find-replace.dialog.replace")
992
+ }), /* @__PURE__ */ jsx(Button, {
993
+ disabled: replaceAllDisabled,
994
+ onClick: onClickReplaceAllButton,
995
+ children: localeService.t("find-replace.dialog.replace-all")
996
+ })]
997
+ })]
998
+ })
999
+ ] });
1000
+ });
1001
+ function FindReplaceDialog() {
1002
+ const findReplaceService = useDependency(IFindReplaceService);
1003
+ const layoutService = useDependency(ILayoutService);
1004
+ const contextService = useDependency(IContextService);
1005
+ const state = useObservable(findReplaceService.state$, void 0, true);
1006
+ const dialogContainerRef = useRef(null);
1007
+ useEffect(() => {
1008
+ let disposable;
1009
+ if (dialogContainerRef.current) disposable = layoutService.registerContainerElement(dialogContainerRef.current);
1010
+ return () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
1011
+ }, [layoutService]);
1012
+ const focusRef = useRef(null);
1013
+ const setDialogContainerFocus = useCallback((focused) => contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, focused), [contextService]);
1014
+ const setDialogInputFocus = useCallback((focused) => contextService.setContextValue(FIND_REPLACE_INPUT_FOCUS, focused), [contextService]);
1015
+ useEffect(() => {
1016
+ var _focusRef$current;
1017
+ const focusSubscription = fromEvent(document, "focusin").subscribe((event) => {
1018
+ var _dialogContainerRef$c;
1019
+ if (event.target && ((_dialogContainerRef$c = dialogContainerRef.current) === null || _dialogContainerRef$c === void 0 ? void 0 : _dialogContainerRef$c.contains(event.target))) setDialogContainerFocus(true);
1020
+ else setDialogContainerFocus(false);
1021
+ if (!focusRef.current || !focusRef.current.selectHasFocus()) setDialogInputFocus(false);
1022
+ else setDialogInputFocus(true);
1023
+ });
1024
+ (_focusRef$current = focusRef.current) === null || _focusRef$current === void 0 || _focusRef$current.focus();
1025
+ setDialogContainerFocus(true);
1026
+ setDialogInputFocus(true);
1027
+ return () => {
1028
+ focusSubscription.unsubscribe();
1029
+ setDialogContainerFocus(false);
1030
+ };
1031
+ }, [setDialogContainerFocus, setDialogInputFocus]);
1032
+ return /* @__PURE__ */ jsx("div", {
1033
+ ref: dialogContainerRef,
1034
+ "data-u-comp": "find-replace-dialog",
1035
+ children: !state.replaceRevealed ? /* @__PURE__ */ jsx(FindDialog, { ref: focusRef }) : /* @__PURE__ */ jsx(ReplaceDialog, { ref: focusRef })
1036
+ });
1037
+ }
1038
+ function useFindScopeOptions(localeService) {
1039
+ return useMemo(() => {
1040
+ return [{
1041
+ label: localeService.t("find-replace.dialog.find-scope.current-sheet"),
1042
+ value: FindScope.SUBUNIT
1043
+ }, {
1044
+ label: localeService.t("find-replace.dialog.find-scope.workbook"),
1045
+ value: FindScope.UNIT
1046
+ }];
1047
+ }, [localeService.getCurrentLocale()]);
1048
+ }
1049
+ function useFindDirectionOptions(localeService) {
1050
+ return useMemo(() => {
1051
+ return [{
1052
+ label: localeService.t("find-replace.dialog.find-direction.row"),
1053
+ value: FindDirection.ROW
1054
+ }, {
1055
+ label: localeService.t("find-replace.dialog.find-direction.column"),
1056
+ value: FindDirection.COLUMN
1057
+ }];
1058
+ }, [localeService.getCurrentLocale()]);
1059
+ }
1060
+ function useFindByOptions(localeService) {
1061
+ return useMemo(() => {
1062
+ return [{
1063
+ label: localeService.t("find-replace.dialog.find-by.value"),
1064
+ value: FindBy.VALUE
1065
+ }, {
1066
+ label: localeService.t("find-replace.dialog.find-by.formula"),
1067
+ value: FindBy.FORMULA
1068
+ }];
1069
+ }, [localeService.getCurrentLocale()]);
1070
+ }
1071
+
1072
+ //#endregion
1073
+ //#region src/controllers/find-replace.shortcut.ts
1074
+ function whenFindReplaceDialogFocused(contextService) {
1075
+ return contextService.getContextValue(FIND_REPLACE_DIALOG_FOCUS);
1076
+ }
1077
+ function whenReplaceRevealed(contextService) {
1078
+ return contextService.getContextValue(FIND_REPLACE_REPLACE_REVEALED);
1079
+ }
1080
+ function whenFindReplaceInputFocused(contextService) {
1081
+ return contextService.getContextValue(FIND_REPLACE_INPUT_FOCUS);
1082
+ }
1083
+ const FIND_REPLACE_SHORTCUT_GROUP = "7_find-replace-shortcuts";
1084
+ function whenSheetFocused(contextService) {
1085
+ return contextService.getContextValue(FOCUSING_SHEET);
1086
+ }
1087
+ function whenEditorNotActivated(contextService) {
1088
+ return !contextService.getContextValue(EDITOR_ACTIVATED);
1089
+ }
1090
+ const OpenFindDialogShortcutItem = {
1091
+ id: OpenFindDialogOperation.id,
1092
+ description: "find-replace.shortcut.open-find-dialog",
1093
+ binding: KeyCode.F | MetaKeys.CTRL_COMMAND,
1094
+ group: FIND_REPLACE_SHORTCUT_GROUP,
1095
+ preconditions(contextService) {
1096
+ return !whenFindReplaceDialogFocused(contextService) && whenSheetFocused(contextService) && whenEditorNotActivated(contextService);
1097
+ }
1098
+ };
1099
+ const MacOpenFindDialogShortcutItem = {
1100
+ id: OpenFindDialogOperation.id,
1101
+ description: "find-replace.shortcut.open-find-dialog",
1102
+ binding: KeyCode.F | MetaKeys.CTRL_COMMAND,
1103
+ mac: KeyCode.F | MetaKeys.MAC_CTRL,
1104
+ preconditions(contextService) {
1105
+ return !whenFindReplaceDialogFocused(contextService) && whenSheetFocused(contextService) && whenEditorNotActivated(contextService);
1106
+ }
1107
+ };
1108
+ const OpenReplaceDialogShortcutItem = {
1109
+ id: OpenReplaceDialogOperation.id,
1110
+ description: "find-replace.shortcut.open-replace-dialog",
1111
+ binding: KeyCode.H | MetaKeys.CTRL_COMMAND,
1112
+ mac: KeyCode.H | MetaKeys.MAC_CTRL,
1113
+ group: FIND_REPLACE_SHORTCUT_GROUP,
1114
+ preconditions(contextService) {
1115
+ return whenSheetFocused(contextService) && whenEditorNotActivated(contextService) && (!whenFindReplaceDialogFocused(contextService) || !whenReplaceRevealed(contextService));
1116
+ }
1117
+ };
1118
+ const GoToNextFindMatchShortcutItem = {
1119
+ id: GoToNextMatchOperation.id,
1120
+ description: "find-replace.shortcut.go-to-next-match",
1121
+ binding: KeyCode.ENTER,
1122
+ group: FIND_REPLACE_SHORTCUT_GROUP,
1123
+ priority: 1e3,
1124
+ preconditions(contextService) {
1125
+ return whenFindReplaceInputFocused(contextService) && whenFindReplaceDialogFocused(contextService);
1126
+ }
1127
+ };
1128
+ const GoToPreviousFindMatchShortcutItem = {
1129
+ id: GoToPreviousMatchOperation.id,
1130
+ description: "find-replace.shortcut.go-to-previous-match",
1131
+ binding: KeyCode.ENTER | MetaKeys.SHIFT,
1132
+ group: FIND_REPLACE_SHORTCUT_GROUP,
1133
+ priority: 1e3,
1134
+ preconditions(contextService) {
1135
+ return whenFindReplaceInputFocused(contextService) && whenFindReplaceDialogFocused(contextService);
1136
+ }
1137
+ };
1138
+ const FocusSelectionShortcutItem = {
1139
+ id: FocusSelectionOperation.id,
1140
+ description: "find-replace.shortcut.focus-selection",
1141
+ binding: KeyCode.ESC,
1142
+ group: FIND_REPLACE_SHORTCUT_GROUP,
1143
+ priority: 1e3,
1144
+ preconditions(contextService) {
1145
+ return whenFindReplaceDialogFocused(contextService);
1146
+ }
1147
+ };
1148
+
1149
+ //#endregion
1150
+ //#region src/controllers/find-replace.controller.ts
1151
+ const FIND_REPLACE_DIALOG_ID = "DESKTOP_FIND_REPLACE_DIALOG";
1152
+ const FIND_REPLACE_PANEL_WIDTH = 350;
1153
+ const FIND_REPLACE_PANEL_RIGHT_PADDING = 20;
1154
+ const FIND_REPLACE_PANEL_TOP_PADDING = 64;
1155
+ let FindReplaceController = class FindReplaceController extends RxDisposable {
1156
+ constructor(_univerInstanceService, _menuManagerService, _shortcutService, _commandService, _findReplaceService, _dialogService, _layoutService, _localeService, _componentManager) {
1157
+ super();
1158
+ this._univerInstanceService = _univerInstanceService;
1159
+ this._menuManagerService = _menuManagerService;
1160
+ this._shortcutService = _shortcutService;
1161
+ this._commandService = _commandService;
1162
+ this._findReplaceService = _findReplaceService;
1163
+ this._dialogService = _dialogService;
1164
+ this._layoutService = _layoutService;
1165
+ this._localeService = _localeService;
1166
+ this._componentManager = _componentManager;
1167
+ _defineProperty(this, "_closingListenerDisposable", void 0);
1168
+ this._initCommands();
1169
+ this._initUI();
1170
+ this._initShortcuts();
1171
+ }
1172
+ dispose() {
1173
+ var _this$_closingListene;
1174
+ super.dispose();
1175
+ (_this$_closingListene = this._closingListenerDisposable) === null || _this$_closingListene === void 0 || _this$_closingListene.dispose();
1176
+ this._closingListenerDisposable = null;
1177
+ }
1178
+ _initCommands() {
1179
+ [
1180
+ OpenFindDialogOperation,
1181
+ OpenReplaceDialogOperation,
1182
+ GoToNextMatchOperation,
1183
+ GoToPreviousMatchOperation,
1184
+ ReplaceAllMatchesCommand,
1185
+ ReplaceCurrentMatchCommand,
1186
+ FocusSelectionOperation
1187
+ ].forEach((c) => {
1188
+ this.disposeWithMe(this._commandService.registerCommand(c));
1189
+ });
1190
+ }
1191
+ _initShortcuts() {
1192
+ [
1193
+ OpenReplaceDialogShortcutItem,
1194
+ OpenFindDialogShortcutItem,
1195
+ MacOpenFindDialogShortcutItem,
1196
+ GoToPreviousFindMatchShortcutItem,
1197
+ GoToNextFindMatchShortcutItem,
1198
+ FocusSelectionShortcutItem
1199
+ ].forEach((s) => this.disposeWithMe(this._shortcutService.registerShortcut(s)));
1200
+ }
1201
+ _initUI() {
1202
+ [["FindReplaceDialog", FindReplaceDialog], ["SearchIcon", SearchIcon]].forEach(([key, comp]) => {
1203
+ this.disposeWithMe(this._componentManager.register(key, comp));
1204
+ });
1205
+ this._menuManagerService.mergeMenu(menuSchema);
1206
+ this._findReplaceService.stateUpdates$.pipe(takeUntil(this.dispose$)).subscribe((newState) => {
1207
+ if (newState.revealed === true) this._openPanel();
1208
+ });
1209
+ }
1210
+ _openPanel() {
1211
+ this._dialogService.open({
1212
+ id: FIND_REPLACE_DIALOG_ID,
1213
+ draggable: true,
1214
+ width: FIND_REPLACE_PANEL_WIDTH,
1215
+ title: { title: this._localeService.t("find-replace.dialog.title") },
1216
+ children: { label: "FindReplaceDialog" },
1217
+ destroyOnClose: true,
1218
+ mask: false,
1219
+ maskClosable: false,
1220
+ defaultPosition: getFindReplaceDialogDefaultPosition(),
1221
+ preservePositionOnDestroy: true,
1222
+ onClose: () => this.closePanel()
1223
+ });
1224
+ this._closingListenerDisposable = toDisposable(this._univerInstanceService.focused$.pipe(takeUntil(this.dispose$)).subscribe((focused) => {
1225
+ if (!focused || !this._univerInstanceService.getUniverSheetInstance(focused)) this.closePanel();
1226
+ }));
1227
+ }
1228
+ closePanel() {
1229
+ if (!this._closingListenerDisposable) return;
1230
+ this._closingListenerDisposable.dispose();
1231
+ this._closingListenerDisposable = null;
1232
+ this._dialogService.close(FIND_REPLACE_DIALOG_ID);
1233
+ this._findReplaceService.terminate();
1234
+ queueMicrotask(() => this._layoutService.focus());
1235
+ }
1236
+ };
1237
+ FindReplaceController = __decorate([
1238
+ __decorateParam(0, IUniverInstanceService),
1239
+ __decorateParam(1, IMenuManagerService),
1240
+ __decorateParam(2, IShortcutService),
1241
+ __decorateParam(3, ICommandService),
1242
+ __decorateParam(4, IFindReplaceService),
1243
+ __decorateParam(5, IDialogService),
1244
+ __decorateParam(6, ILayoutService),
1245
+ __decorateParam(7, Inject(LocaleService)),
1246
+ __decorateParam(8, Inject(ComponentManager))
1247
+ ], FindReplaceController);
1248
+ function getFindReplaceDialogDefaultPosition() {
1249
+ const { innerWidth } = window;
1250
+ return {
1251
+ x: innerWidth - FIND_REPLACE_PANEL_WIDTH - FIND_REPLACE_PANEL_RIGHT_PADDING,
1252
+ y: FIND_REPLACE_PANEL_TOP_PADDING
1253
+ };
1254
+ }
1255
+
1256
+ //#endregion
1257
+ //#region package.json
1258
+ var name = "@univerjs/find-replace";
1259
+ var version = "0.21.0";
1260
+
1261
+ //#endregion
1262
+ //#region src/config/config.ts
1263
+ const FIND_REPLACE_PLUGIN_CONFIG_KEY = "find-replace.config";
1264
+ const configSymbol = Symbol(FIND_REPLACE_PLUGIN_CONFIG_KEY);
1265
+ const defaultPluginConfig = {};
1266
+
1267
+ //#endregion
1268
+ //#region src/plugin.ts
1269
+ let UniverFindReplacePlugin = class UniverFindReplacePlugin extends Plugin {
1270
+ constructor(_config = defaultPluginConfig, _injector, _configService) {
1271
+ super();
1272
+ this._config = _config;
1273
+ this._injector = _injector;
1274
+ this._configService = _configService;
1275
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
1276
+ this._configService.setConfig(FIND_REPLACE_PLUGIN_CONFIG_KEY, rest);
1277
+ }
1278
+ onStarting() {
1279
+ [[FindReplaceController], [IFindReplaceService, { useClass: FindReplaceService }]].forEach((d) => this._injector.add(d));
1280
+ }
1281
+ onRendered() {
1282
+ this._injector.get(FindReplaceController);
1283
+ }
1284
+ };
1285
+ _defineProperty(UniverFindReplacePlugin, "pluginName", "UNIVER_FIND_REPLACE_PLUGIN");
1286
+ _defineProperty(UniverFindReplacePlugin, "packageName", name);
1287
+ _defineProperty(UniverFindReplacePlugin, "version", version);
1288
+ UniverFindReplacePlugin = __decorate([__decorateParam(1, Inject(Injector)), __decorateParam(2, IConfigService)], UniverFindReplacePlugin);
1289
+
1290
+ //#endregion
1291
+ export { FindBy, FindDirection, FindModel, FindReplaceController, FindReplaceModel, FindReplaceState, FindScope, GoToNextMatchOperation, GoToPreviousMatchOperation, IFindReplaceService, OpenFindDialogOperation, OpenReplaceDialogOperation, ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand, UniverFindReplacePlugin, createInitFindReplaceState };