"use strict";var J=Object.defineProperty;var Z=(c,e,t)=>e in c?J(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var _=(c,e,t)=>Z(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@univerjs/core"),S=require("@univerjs/find-replace"),C=require("@univerjs/sheets"),M=require("@univerjs/engine-render"),k=require("@univerjs/sheets-ui"),v=require("rxjs"),ee="sheets-find-replace.config",O={},U={id:"sheet.command.replace",type:l.CommandType.COMMAND,handler:async(c,e)=>{const t=c.get(l.IUndoRedoService),n=c.get(l.ICommandService),{unitId:i,replacements:r}=e,s=t.__tempBatchingUndoRedo(i),o=await Promise.all(r.map(h=>n.executeCommand(C.SetRangeValuesCommand.id,{unitId:i,subUnitId:h.subUnitId,value:h.value})));return s.dispose(),te(o,r)}};function te(c,e){let t=0,n=0;return c.forEach((i,r)=>{const s=e[r].count;i?t+=s:n+=s}),{success:t,failure:n}}class ne extends M.Shape{constructor(t,n){super(t,n);_(this,"_activated",!1);_(this,"_inHiddenRange",!1);_(this,"_color");n&&this.setShapeProps(n)}setShapeProps(t){this._activated=!!t.activated,typeof t.inHiddenRange<"u"&&(this._inHiddenRange=t.inHiddenRange),typeof t.color<"u"&&(this._color=t.color),this.transformByState({width:t.width,height:t.height})}_draw(t){const n=this._activated,i=`rgba(${this._color.r}, ${this._color.g}, ${this._color.b}, 0.35)`,r=`rgb(${this._color.r}, ${this._color.g}, ${this._color.b})`;M.Rect.drawWith(t,{width:this.width,height:this.height,fill:i,stroke:n?r:void 0,strokeWidth:n?2:0,evented:!1})}}function A(c,e){return c.startRow===e.startRow&&c.startColumn===e.startColumn}function D(c,e){return c.startRowe.startRow||c.startRow===e.startRow&&c.startColumn>=e.startColumn}function se(c,e){return c.startColumn>e.startColumn||c.startColumn===e.startColumn&&c.startRow>=e.startRow}function re(c,e){const{range:t}=c,{startRow:n,startColumn:i}=t,r=e.getMergedCell(n,i);return r?l.Rectangle.equals(t,r):t.endRow===t.startRow&&t.endColumn===t.startColumn}var oe=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,B=(c,e,t,n)=>{for(var i=n>1?void 0:n?ce(e,t):e,r=c.length-1,s;r>=0;r--)(s=c[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&oe(e,t,i),i},I=(c,e)=>(t,n)=>e(t,n,c);exports.SheetsFindReplaceController=class extends l.Disposable{constructor(t,n,i,r,s){super();_(this,"_provider");this._injector=t,this._findReplaceController=n,this._contextService=i,this._findReplaceService=r,this._commandService=s,this._init(),this._initCommands()}dispose(){super.dispose(),this._findReplaceController.closePanel(),this._provider.dispose()}_init(){const t=this._injector.createInstance(P);this._provider=t,this.disposeWithMe(this._findReplaceService.registerFindReplaceProvider(t)),this.disposeWithMe(this._contextService.subscribeContextValue$(l.EDITOR_ACTIVATED).pipe(v.filter(n=>!!n)).subscribe(()=>this._findReplaceController.closePanel()))}_initCommands(){[U].forEach(t=>this.disposeWithMe(this._commandService.registerCommand(t)))}};exports.SheetsFindReplaceController=B([I(0,l.Inject(l.Injector)),I(1,l.Inject(S.FindReplaceController)),I(2,l.IContextService),I(3,S.IFindReplaceService),I(4,l.ICommandService)],exports.SheetsFindReplaceController);const he="sheets-find-replace-provider",ae=1e4;let F=class extends S.FindModel{constructor(e,t,n,i,r,s,o,h){super();_(this,"_matchesUpdate$",new v.Subject);_(this,"matchesUpdate$",this._matchesUpdate$.asObservable());_(this,"_activelyChangingMatch$",new v.Subject);_(this,"activelyChangingMatch$",this._activelyChangingMatch$.asObservable());_(this,"_matchesByWorksheet",new Map);_(this,"_matches",[]);_(this,"_matchesPosition",0);_(this,"_activeHighlightIndex",-1);_(this,"_highlightShapes",[]);_(this,"_currentHighlightShape",null);_(this,"_query",null);_(this,"_workbookSelections");this._workbook=e,this._sheetSkeletonManagerService=t,this._univerInstanceService=n,this._renderManagerService=i,this._commandService=r,this._contextService=s,this._themeService=o,this._workbookSelections=h.getWorkbookSelections(this.unitId)}get _matchesCount(){return this._matches.length}get unitId(){return this._workbook.getUnitId()}get matchesCount(){return this._matchesCount}get matchesPosition(){return this._matchesPosition}get currentMatch(){return this._matchesPosition>0?this._matches[this._matchesPosition-1]:null}dispose(){super.dispose(),this._disposeHighlights(),this._toggleDisplayRawFormula(!1)}getMatches(){return this._matches}start(e){switch(this._query=e,e.findBy===S.FindBy.FORMULA?this._toggleDisplayRawFormula(!0):this._toggleDisplayRawFormula(!1),e.findScope){case S.FindScope.UNIT:this.findInWorkbook(e);break;case S.FindScope.SUBUNIT:default:this.findInActiveWorksheet(e);break}}_toggleDisplayRawFormula(e){this._contextService.setContextValue(M.RENDER_RAW_FORMULA_KEY,e)}findInWorkbook(e){const t=this._workbook.getUnitId();let n,i=!0;const r=()=>{const s=this._workbook.getSheets().filter(o=>!o.isSheetHidden()).map(o=>{const h=this._findInWorksheet(o,e,t),d=o.getSheetId(),{results:a}=h;return a.length?this._matchesByWorksheet.set(d,h.results):this._matchesByWorksheet.delete(d),h});this._matches=s.map(o=>o.results).flat(),this._updateFindHighlight(),i?(n={results:this._matches},i=!1):this._matchesUpdate$.next(this._matches)};return this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(()=>{this._updateFindHighlight(),this._updateCurrentHighlightShape(this._activeHighlightIndex)})),this.disposeWithMe(l.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(v.filter(([s,o])=>s.id===C.SetWorksheetActiveOperation.id&&!(o!=null&&o.fromFindReplace))).subscribe(()=>{const s=this._workbook.getActiveSheet();if(!s)return;const o=s.getSheetId();this._matchesByWorksheet.has(o)&&this._findNextMatchOnActiveSheetChange(s)})),this.disposeWithMe(l.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(v.filter(([s])=>s.type===l.CommandType.MUTATION&&s.params.unitId===this._workbook.getUnitId()),v.throttleTime(600,void 0,{leading:!1,trailing:!0})).subscribe(()=>r())),r(),n}_findNextMatchOnActiveSheetChange(e){let t,n,i=0;const r=this._matchesByWorksheet.get(e.getSheetId()),s=this._workbookSelections.getCurrentSelections();s!=null&&s.length?([t,i]=this._findNextMatchByRange(r,s[0].range),n=r.findIndex(o=>o===t)):(t=r[0],n=0,i=this._matches.findIndex(o=>o===t)),this._matchesPosition=i+1,this._activelyChangingMatch$.next(t),this._activeHighlightIndex=n,this._updateFindHighlight(),this._updateCurrentHighlightShape(n)}findInActiveWorksheet(e){const t=this._workbook.getUnitId(),n=()=>{var u;const h=this._workbook.getActiveSheet();if(!h)return!1;const d=this._workbookSelections.getCurrentSelections();return(u=d==null?void 0:d.some(g=>!re(g,h)))!=null?u:!1};let i,r=!0,s=!1;const o=()=>{const h=this._workbook.getActiveSheet();if(!h)return{results:[]};const d=this.currentMatch;s=n();const a=this._workbookSelections.getCurrentSelections(),u=s?this._findInSelections(h,a,e,t):this._findInWorksheet(h,e,t);return this._matches=u.results,this._matchesPosition=this._tryRestoreLastMatchesPosition(d,this._matches),r?(i=u,r=!1):this._matchesUpdate$.next(this._matches),this._updateFindHighlight(),u};return this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(()=>this._updateFindHighlight())),this.disposeWithMe(v.merge(l.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(v.filter(([h])=>{if(h.type===l.CommandType.MUTATION&&h.params.unitId===this._workbook.getUnitId())return!0;if(h.id===C.SetSelectionsOperation.id&&h.params.unitId===t){const d=n();return d===!1&&s===!1?!1:(s=d,!0)}return!1})),this._workbook.activeSheet$.pipe(v.skip(1))).pipe(v.debounceTime(200)).subscribe(()=>o())),o(),i}_findInRange(e,t,n,i,r){const s=[],o=e.getSheetId(),h=(t.findDirection===S.FindDirection.COLUMN?e.iterateByColumn:e.iterateByRow).bind(e)(n);for(const d of h){const{row:a,col:u,colSpan:g,rowSpan:m,value:p}=d;if(r!=null&&r(a,u)||!p||e.getRowFiltered(a))continue;const{hit:R,replaceable:w,isFormula:b}=le(e,a,u,t,p);if(R){const y={provider:he,unitId:i,replaceable:w,isFormula:b,range:{subUnitId:o,range:{startRow:a,startColumn:u,endColumn:u+(g!=null?g:1)-1,endRow:a+(m!=null?m:1)-1}}};s.push(y)}}return{results:s}}_findInSelections(e,t,n,i){const{findDirection:r}=n,s=r===S.FindDirection.ROW?D:N,o=new Set;return{results:t.map(d=>this._findInRange(e,n,d.range,i,(a,u)=>{const g=`${a}-${u}`;return o.has(g)?!0:(o.add(g),!1)}).results).flat().sort((d,a)=>s(d.range.range,a.range.range)?-1:1)}}_findInWorksheet(e,t,n){const i=e.getRowCount(),r=e.getColumnCount(),s={startRow:0,startColumn:0,endRow:i-1,endColumn:r-1};return this._findInRange(e,t,s,n)}_disposeHighlights(){var e;this._highlightShapes.forEach(t=>{var n;(n=t.getScene())==null||n.makeDirty(),t.dispose()}),this._highlightShapes=[],(e=this._currentHighlightShape)==null||e.dispose(),this._currentHighlightShape=null}_updateFindHighlight(){var u;this._disposeHighlights();const e=(u=this._sheetSkeletonManagerService.getCurrent())==null?void 0:u.skeleton;if(!e)return;const t=this._workbook.getUnitId(),n=this._renderManagerService.getRenderById(t);if(n==null)return;const{scene:i}=n,r=this._matches,s=this._themeService.getCurrentTheme().gold400,o=new l.ColorKit(s).toRgb(),h=this._workbook.getActiveSheet();if(!h)return;const d=h.getSheetId(),a=r.filter(g=>g.range.subUnitId===d).map((g,m)=>{const{startColumn:p,startRow:R,endColumn:w,endRow:b}=g.range.range,y=k.getCoordByCell(R,p,i,e),G=k.getCoordByCell(b,w,i,e),{startX:W,startY:H}=y,{endX:Y,endY:q}=G,T=!h.getRowRawVisible(R),E=!h.getColVisible(p),K=T||E,Q=E?2:Y-W,X=T?2:q-H,z={left:W,top:H,color:o,width:Q,height:X,evented:!1,inHiddenRange:K,zIndex:ae};return new ne(`find-highlight-${m}`,z)});i.addObjects(a),this._highlightShapes=a,i.makeDirty()}_updateCurrentHighlightShape(e){var t;if((t=this._currentHighlightShape)==null||t.setShapeProps({activated:!1}),this._currentHighlightShape=null,e!==void 0){const n=this._highlightShapes[e];if(!n)return;this._currentHighlightShape=n,n.setShapeProps({activated:!0})}}_getSheetObject(){return k.getSheetObject(this._univerInstanceService,this._renderManagerService)}_focusMatch(e){var n;const t=e.range.subUnitId;t!==((n=this._workbook.getActiveSheet())==null?void 0:n.getSheetId())&&this._commandService.executeCommand(C.SetWorksheetActivateCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:t},{fromFindReplace:!0}),this._commandService.executeCommand(k.ScrollToCellCommand.id,{range:e.range.range},{fromFindReplace:!0})}_tryRestoreLastMatchesPosition(e,t){if(!e)return 0;const{subUnitId:n}=e.range,{startColumn:i,startRow:r}=e.range.range,s=t.findIndex(o=>{if(n!==o.range.subUnitId)return!1;const{startColumn:h,startRow:d}=o.range.range;return h===i&&d===r});return s>-1?s+1:0}moveToNextMatch(e){var o,h,d,a,u;if(!this._matches.length)return null;const t=(o=e==null?void 0:e.loop)!=null?o:!1,n=(h=e==null?void 0:e.stayIfOnMatch)!=null?h:!1,i=(d=e==null?void 0:e.noFocus)!=null?d:!1,r=(a=e==null?void 0:e.ignoreSelection)!=null?a:!1,s=this._findNextMatch(t,n,r);if(s){const[g,m]=s;return this._matchesPosition=m+1,this._query.findScope===S.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(g.range.subUnitId).findIndex(p=>p===g):this._activeHighlightIndex=m,i||this._focusMatch(g),((u=this._workbook.getActiveSheet())==null?void 0:u.getSheetId())===g.range.subUnitId&&this._updateCurrentHighlightShape(this._activeHighlightIndex),g}return this._matchesPosition=0,this._updateCurrentHighlightShape(),null}moveToPreviousMatch(e){var o,h,d,a,u;if(!this._matches.length)return null;const t=(o=e==null?void 0:e.loop)!=null?o:!1,n=(h=e==null?void 0:e.stayIfOnMatch)!=null?h:!1,i=(d=e==null?void 0:e.noFocus)!=null?d:!1,r=(a=e==null?void 0:e.ignoreSelection)!=null?a:!1,s=this._findPreviousMatch(t,n,r);if(s){const[g,m]=s;return this._matchesPosition=m+1,this._query.findScope===S.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(g.range.subUnitId).findIndex(p=>p===g):this._activeHighlightIndex=m,i||this._focusMatch(g),((u=this._workbook.getActiveSheet())==null?void 0:u.getSheetId())===g.range.subUnitId&&this._updateCurrentHighlightShape(this._activeHighlightIndex),g}return this._matchesPosition=0,this._updateCurrentHighlightShape(),null}_findPreviousMatch(e=!1,t=!1,n=!1){var o;if(this.currentMatch){const h=this._matches.findIndex(g=>g===this.currentMatch);if(t)return[this.currentMatch,h];const d=h-1;if(!e&&d<0)return null;const a=this._matches.length,u=(d+a)%a;return[this._matches[u],u]}const i=this._workbookSelections.getCurrentLastSelection();if(n||!i){const h=this._matches.length-1;return[this._matches[h],h]}if(this._query.findScope!==S.FindScope.UNIT)return this._findPreviousMatchByRange(this._matches,i.range);const r=(o=this._workbook.getActiveSheet())==null?void 0:o.getSheetId();if(!r)return null;const s=this._findPreviousWorksheetThatHasAMatch(r,e);return s?this._findPreviousMatchByRange(this._matchesByWorksheet.get(s),i.range):null}_findNextMatch(e=!1,t=!1,n=!1){var o;if(this.currentMatch){const h=this._matches.findIndex(g=>g===this.currentMatch);if(t)return[this.currentMatch,h];const d=h+1,a=this._matches.length;if(!e&&d>=a)return null;const u=d%a;return[this._matches[u],u]}const i=this._workbookSelections.getCurrentLastSelection();if(n||!i)return[this._matches[0],0];if(this._query.findScope!==S.FindScope.UNIT)return this._findNextMatchByRange(this._matches,i.range,t);const r=(o=this._workbook.getActiveSheet())==null?void 0:o.getSheetId();if(!r)return null;const s=this._findNextWorksheetThatHasAMatch(r,e);return s?this._findNextMatchByRange(this._matchesByWorksheet.get(s),i.range):null}_findPreviousWorksheetThatHasAMatch(e,t=!1){const n=this._workbook.getSheetOrders(),i=n.findIndex(o=>o===e),s=(t?l.rotate(n,i+1):n.slice(0,i+1)).findLast(o=>this._matchesByWorksheet.has(o));return s!=null?s:null}_findNextWorksheetThatHasAMatch(e,t=!1){const n=this._workbook.getSheetOrders(),i=n.findIndex(o=>o===e),s=(t?l.rotate(n,i):n.slice(i)).find(o=>this._matchesByWorksheet.has(o));return s!=null?s:null}_findNextMatchByRange(e,t,n=!1){const i=this._query.findDirection===S.FindDirection.ROW;let r=e.findIndex(o=>{const h=o.range.range;if(!(i?D(t,h):N(t,h)))return!1;const a=A(t,h);return n?a:!a});r===-1&&(r=e.length-1);const s=e[r];return[s,this._matches.findIndex(o=>o===s)]}_findPreviousMatchByRange(e,t,n=!1){const i=this._query.findDirection===S.FindDirection.ROW;let r=this._matches.findLastIndex(o=>{const h=o.range.range;if(!(i?ie(t,h):se(t,h)))return!1;const a=A(t,h);return n?a:!a});r===-1&&(r=0);const s=e[r];return[s,this._matches.findIndex(o=>o===s)]}async replace(e){if(this._matchesCount===0||!this.currentMatch||!this._query||!this.currentMatch.replaceable)return!1;const t=this.currentMatch.range,n=this._workbook.getSheetBySheetId(this.currentMatch.range.subUnitId),i=this._getReplacedCellData(this.currentMatch,n,this._query.findBy===S.FindBy.FORMULA,this._query.findString,e,this._query.caseSensitive?"g":"ig"),r={unitId:this.currentMatch.unitId,subUnitId:t.subUnitId,value:{[t.range.startRow]:{[t.range.startColumn]:i}}};return this._commandService.executeCommand(C.SetRangeValuesCommand.id,r)}async replaceAll(e){if(this._matchesCount===0||!this._query)return{success:0,failure:0};const t=this._workbook.getUnitId(),{findString:n,caseSensitive:i,findBy:r}=this._query,s=r===S.FindBy.FORMULA,o=i?"g":"ig",h=[];return l.groupBy(this._matches.filter(a=>a.replaceable),a=>a.range.subUnitId).forEach((a,u)=>{const g=new l.ObjectMatrix,m=this._workbook.getSheetBySheetId(u);a.forEach(p=>{const{startColumn:R,startRow:w}=p.range.range,b=this._getReplacedCellData(p,m,s,n,e,o);b&&g.setValue(w,R,b)}),h.push({count:a.length,subUnitId:u,value:g.getMatrix()})}),h?this._commandService.executeCommand(U.id,{unitId:t,replacements:h}):{success:0,failure:0}}_getReplacedCellData(e,t,n,i,r,s){var m;const o=e.range.range,{startRow:h,startColumn:d}=o,a=t.getCellRaw(h,d);if(e.isFormula)return n?{f:a.f.replace(new RegExp($(i),s),r),v:null}:null;if(!!((m=a.p)!=null&&m.body)){const p=l.Tools.deepClone(a.p);return l.replaceInDocumentBody(p.body,i,r,this._query.caseSensitive),{p}}return{v:a.v.toString().replace(new RegExp($(i),s),r)}}};F=B([I(2,l.IUniverInstanceService),I(3,M.IRenderManagerService),I(4,l.ICommandService),I(5,l.IContextService),I(6,l.Inject(l.ThemeService)),I(7,l.Inject(C.SheetsSelectionsService))],F);function $(c){return c.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}let P=class extends l.Disposable{constructor(e,t,n){super();_(this,"_findModelsByUnitId",new Map);this._univerInstanceService=e,this._renderManagerService=t,this._injector=n}async find(e){this._terminate();const t=this._univerInstanceService.getAllUnitsForType(l.UniverInstanceType.UNIVER_SHEET),n=this._preprocessQuery(e);return t.map(r=>{const s=this._renderManagerService.getRenderById(r.getUnitId()).with(k.SheetSkeletonManagerService),o=this._injector.createInstance(F,r,s);return this._findModelsByUnitId.set(r.getUnitId(),o),o.start(n),o})}terminate(){this._terminate()}_terminate(){this._findModelsByUnitId.forEach(e=>e.dispose()),this._findModelsByUnitId.clear()}_preprocessQuery(e){let t=e.caseSensitive?e.findString:e.findString.toLowerCase();return t=t.trim(),{...e,findString:t}}};P=B([I(0,l.IUniverInstanceService),I(1,M.IRenderManagerService),I(2,l.Inject(l.Injector))],P);const f={hit:!1,replaceable:!1,isFormula:!1,rawData:null};function le(c,e,t,n,i){const{findBy:r}=n,s=r===S.FindBy.FORMULA,o=c.getCellRaw(e,t);return f.rawData=o,!(o!=null&&o.f)?(f.isFormula=!1,x(i,n)?o?(f.hit=!0,f.replaceable=!0):(f.hit=!0,f.replaceable=!1):(f.hit=!1,f.replaceable=!1),f):(f.isFormula=!0,s?x({v:o.f},n)?(f.hit=!0,f.replaceable=!0,f):(f.hit=!1,f.replaceable=!1,f):(f.replaceable=!1,x(i,n)?f.hit=!0:f.hit=!1,f))}function x(c,e){let t=de(c);return t?e.matchesTheWholeCell?(t=ue(t),e.caseSensitive?t===e.findString:t.toLowerCase()===e.findString):e.caseSensitive?t.indexOf(e.findString)>-1:t.toLowerCase().indexOf(e.findString)>-1:!1}function de(c){var t,n,i;const e=(i=(n=(t=c==null?void 0:c.p)==null?void 0:t.body)==null?void 0:n.dataStream)!=null?i:c==null?void 0:c.v;return typeof e=="number"?`${e}`:typeof e=="boolean"?e?"1":"0":e}function ue(c){return c.replace(/^ +/g,"").replace(/ +$/g,"")}var L=Object.defineProperty,ge=Object.getOwnPropertyDescriptor,fe=(c,e,t)=>e in c?L(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,_e=(c,e,t,n)=>{for(var i=n>1?void 0:n?ge(e,t):e,r=c.length-1,s;r>=0;r--)(s=c[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&L(e,t,i),i},j=(c,e)=>(t,n)=>e(t,n,c),V=(c,e,t)=>fe(c,typeof e!="symbol"?e+"":e,t);const Se="SHEET_FIND_REPLACE_PLUGIN";exports.UniverSheetsFindReplacePlugin=class extends l.Plugin{constructor(e=O,t,n){super(),this._config=e,this._injector=t,this._configService=n;const{...i}=l.merge({},O,this._config);this._configService.setConfig(ee,i)}onStarting(){[[exports.SheetsFindReplaceController]].forEach(e=>this._injector.add(e))}onSteady(){this._injector.get(exports.SheetsFindReplaceController)}};V(exports.UniverSheetsFindReplacePlugin,"pluginName",Se);V(exports.UniverSheetsFindReplacePlugin,"type",l.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFindReplacePlugin=_e([l.DependentOn(C.UniverSheetsPlugin,C.UniverSheetsPlugin,S.UniverFindReplacePlugin),j(1,l.Inject(l.Injector)),j(2,l.IConfigService)],exports.UniverSheetsFindReplacePlugin);exports.SheetReplaceCommand=U;