@univerjs/sheets-find-replace 0.2.4 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/index.js +1 -1
- package/lib/es/index.js +433 -416
- package/lib/types/controllers/sheet-find-replace.controller.d.ts +1 -2
- package/lib/types/plugin.d.ts +2 -3
- package/lib/umd/index.js +1 -1
- package/package.json +16 -18
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { ICellData, IRange, Nullable, Workbook, Worksheet, Disposable, ICommandService, IContextService, IUniverInstanceService, ThemeService } from '@univerjs/core';
|
|
1
|
+
import { ICellData, IDisposable, IRange, Nullable, Workbook, Worksheet, Disposable, ICommandService, IContextService, Injector, IUniverInstanceService, ThemeService } from '@univerjs/core';
|
|
2
2
|
import { IRenderManagerService } from '@univerjs/engine-render';
|
|
3
3
|
import { IFindComplete, IFindMatch, IFindMoveParams, IFindQuery, IReplaceAllResult, FindModel, FindReplaceController, IFindReplaceService } from '@univerjs/find-replace';
|
|
4
4
|
import { SheetsSelectionsService } from '@univerjs/sheets';
|
|
5
5
|
import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
|
|
6
|
-
import { IDisposable, Injector } from '@wendellhu/redi';
|
|
7
6
|
|
|
8
7
|
export declare class SheetsFindReplaceController extends Disposable implements IDisposable {
|
|
9
8
|
private readonly _injector;
|
package/lib/types/plugin.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { Plugin, UniverInstanceType } from '@univerjs/core';
|
|
2
|
-
import { Injector } from '@wendellhu/redi';
|
|
1
|
+
import { Injector, Plugin, UniverInstanceType } from '@univerjs/core';
|
|
3
2
|
|
|
4
3
|
export declare class UniverSheetsFindReplacePlugin extends Plugin {
|
|
5
4
|
protected readonly _injector: Injector;
|
|
6
5
|
static pluginName: string;
|
|
7
6
|
static type: UniverInstanceType;
|
|
8
7
|
constructor(_config: unknown, _injector: Injector);
|
|
9
|
-
onStarting(
|
|
8
|
+
onStarting(): void;
|
|
10
9
|
}
|
package/lib/umd/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(_,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@univerjs/core"),require("@wendellhu/redi"),require("@univerjs/find-replace"),require("@univerjs/sheets"),require("@univerjs/engine-render"),require("@univerjs/sheets-ui"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@wendellhu/redi","@univerjs/find-replace","@univerjs/sheets","@univerjs/engine-render","@univerjs/sheets-ui","rxjs"],l):(_=typeof globalThis<"u"?globalThis:_||self,l(_.UniverSheetsFindReplace={},_.UniverCore,_["@wendellhu/redi"],_.UniverFindReplace,_.UniverSheets,_.UniverEngineRender,_.UniverSheetsUi,_.rxjs))})(this,function(_,l,p,S,R,M,y,w){"use strict";var fe=Object.defineProperty;var Se=(_,l,p)=>l in _?fe(_,l,{enumerable:!0,configurable:!0,writable:!0,value:p}):_[l]=p;var m=(_,l,p)=>Se(_,typeof l!="symbol"?l+"":l,p);class q extends M.Shape{constructor(t,n){super(t,n);m(this,"_activated",!1);m(this,"_inHiddenRange",!1);m(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})}}const U={id:"sheet.command.replace",type:l.CommandType.COMMAND,handler:async(h,e)=>{const t=h.get(l.IUndoRedoService),n=h.get(l.ICommandService),{unitId:i,replacements:r}=e,s=t.__tempBatchingUndoRedo(i),o=await Promise.all(r.map(c=>n.executeCommand(R.SetRangeValuesCommand.id,{unitId:i,subUnitId:c.subUnitId,value:c.value})));return s.dispose(),Q(o,r)}};function Q(h,e){let t=0,n=0;return h.forEach((i,r)=>{const s=e[r].count;i?t+=s:n+=s}),{success:t,failure:n}}function H(h,e){return h.startRow===e.startRow&&h.startColumn===e.startColumn}function O(h,e){return h.startRow<e.startRow||h.startRow===e.startRow&&h.startColumn<=e.startColumn}function E(h,e){return h.startColumn<e.startColumn||h.startColumn===e.startColumn&&h.startRow<=e.startRow}function X(h,e){return h.startRow>e.startRow||h.startRow===e.startRow&&h.startColumn>=e.startColumn}function Y(h,e){return h.startColumn>e.startColumn||h.startColumn===e.startColumn&&h.startRow>=e.startRow}function G(h,e){const{range:t}=h,{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 K=Object.defineProperty,z=Object.getOwnPropertyDescriptor,x=(h,e,t,n)=>{for(var i=n>1?void 0:n?z(e,t):e,r=h.length-1,s;r>=0;r--)(s=h[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&K(e,t,i),i},C=(h,e)=>(t,n)=>e(t,n,h);_.SheetsFindReplaceController=class extends l.Disposable{constructor(t,n,i,r,s){super();m(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(B);this._provider=t,this.disposeWithMe(this._findReplaceService.registerFindReplaceProvider(t)),this.disposeWithMe(this._contextService.subscribeContextValue$(l.EDITOR_ACTIVATED).pipe(w.filter(n=>!!n)).subscribe(()=>this._findReplaceController.closePanel()))}_initCommands(){[U].forEach(t=>this.disposeWithMe(this._commandService.registerCommand(t)))}},_.SheetsFindReplaceController=x([l.OnLifecycle(l.LifecycleStages.Steady,_.SheetsFindReplaceController),C(0,p.Inject(p.Injector)),C(1,p.Inject(S.FindReplaceController)),C(2,l.IContextService),C(3,S.IFindReplaceService),C(4,l.ICommandService)],_.SheetsFindReplaceController);const J="sheets-find-replace-provider",Z=1e4;let P=class extends S.FindModel{constructor(e,t,n,i,r,s,o,c){super();m(this,"_matchesUpdate$",new w.Subject);m(this,"matchesUpdate$",this._matchesUpdate$.asObservable());m(this,"_activelyChangingMatch$",new w.Subject);m(this,"activelyChangingMatch$",this._activelyChangingMatch$.asObservable());m(this,"_matchesByWorksheet",new Map);m(this,"_matches",[]);m(this,"_matchesPosition",0);m(this,"_activeHighlightIndex",-1);m(this,"_highlightShapes",[]);m(this,"_currentHighlightShape",null);m(this,"_query",null);m(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=c.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 c=this._findInWorksheet(o,e,t),d=o.getSheetId(),{results:a}=c;return a.length?this._matchesByWorksheet.set(d,c.results):this._matchesByWorksheet.delete(d),c});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.onCommandExecuted)).pipe(w.filter(([s,o])=>s.id===R.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(w.filter(([s])=>s.type===l.CommandType.MUTATION&&s.params.unitId===this._workbook.getUnitId()),w.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 c=this._workbook.getActiveSheet();if(!c)return!1;const d=this._workbookSelections.getCurrentSelections();return(u=d==null?void 0:d.some(g=>!G(g,c)))!=null?u:!1};let i,r=!0,s=!1;const o=()=>{const c=this._workbook.getActiveSheet();if(!c)return{results:[]};const d=this.currentMatch;s=n();const a=this._workbookSelections.getCurrentSelections(),u=s?this._findInSelections(c,a,e,t):this._findInWorksheet(c,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(w.merge(l.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(w.filter(([c])=>{if(c.type===l.CommandType.MUTATION&&c.params.unitId===this._workbook.getUnitId())return!0;if(c.id===R.SetSelectionsOperation.id&&c.params.unitId===t){const d=n();return d===!1&&s===!1?!1:(s=d,!0)}return!1})),this._workbook.activeSheet$.pipe(w.skip(1))).pipe(w.debounceTime(200)).subscribe(()=>o())),o(),i}_findInRange(e,t,n,i,r){const s=[],o=e.getSheetId(),c=(t.findDirection===S.FindDirection.COLUMN?e.iterateByColumn:e.iterateByRow).bind(e)(n);for(const d of c){const{row:a,col:u,colSpan:g,rowSpan:v,value:I}=d;if(r!=null&&r(a,u)||!I||e.getRowFiltered(a))continue;const{hit:b,replaceable:F,isFormula:k}=ee(e,a,u,t,I);if(b){const T={provider:J,unitId:i,replaceable:F,isFormula:k,range:{subUnitId:o,range:{startRow:a,startColumn:u,endColumn:u+(g!=null?g:1)-1,endRow:a+(v!=null?v:1)-1}}};s.push(T)}}return{results:s}}_findInSelections(e,t,n,i){const{findDirection:r}=n,s=r===S.FindDirection.ROW?O:E,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=>{t.getScene().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(),c=this._workbook.getActiveSheet();if(!c)return;const d=c.getSheetId(),a=r.filter(g=>g.range.subUnitId===d).map((g,v)=>{const{startColumn:I,startRow:b,endColumn:F,endRow:k}=g.range.range,T=y.getCoordByCell(b,I,i,e),ce=y.getCoordByCell(k,F,i,e),{startX:$,startY:j}=T,{endX:ae,endY:le}=ce,L=!c.getRowRawVisible(b),V=!c.getColVisible(I),de=L||V,ue=V?2:ae-$,ge=L?2:le-j,_e={left:$,top:j,color:o,width:ue,height:ge,evented:!1,inHiddenRange:de,zIndex:Z};return new q(`find-highlight-${v}`,_e)});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 y.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(R.SetWorksheetActivateCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:t},{fromFindReplace:!0}),this._commandService.executeCommand(y.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:c,startRow:d}=o.range.range;return c===i&&d===r});return s>-1?s+1:0}moveToNextMatch(e){var o,c,d,a,u;if(!this._matches.length)return null;const t=(o=e==null?void 0:e.loop)!=null?o:!1,n=(c=e==null?void 0:e.stayIfOnMatch)!=null?c:!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,v]=s;return this._matchesPosition=v+1,this._query.findScope===S.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(g.range.subUnitId).findIndex(I=>I===g):this._activeHighlightIndex=v,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,c,d,a,u;if(!this._matches.length)return null;const t=(o=e==null?void 0:e.loop)!=null?o:!1,n=(c=e==null?void 0:e.stayIfOnMatch)!=null?c:!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,v]=s;return this._matchesPosition=v+1,this._query.findScope===S.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(g.range.subUnitId).findIndex(I=>I===g):this._activeHighlightIndex=v,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 c=this._matches.findIndex(g=>g===this.currentMatch);if(t)return[this.currentMatch,c];const d=c-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 c=this._matches.length-1;return[this._matches[c],c]}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 c=this._matches.findIndex(g=>g===this.currentMatch);if(t)return[this.currentMatch,c];const d=c+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 c=o.range.range;if(!(i?O(t,c):E(t,c)))return!1;const a=H(t,c);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 c=o.range.range;if(!(i?X(t,c):Y(t,c)))return!1;const a=H(t,c);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(R.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",c=[];return l.groupBy(this._matches.filter(a=>a.replaceable),a=>a.range.subUnitId).forEach((a,u)=>{const g=new l.ObjectMatrix,v=this._workbook.getSheetBySheetId(u);a.forEach(I=>{const{startColumn:b,startRow:F}=I.range.range,k=this._getReplacedCellData(I,v,s,n,e,o);k&&g.setValue(F,b,k)}),c.push({count:a.length,subUnitId:u,value:g.getMatrix()})}),c?this._commandService.executeCommand(U.id,{unitId:t,replacements:c}):{success:0,failure:0}}_getReplacedCellData(e,t,n,i,r,s){var v;const o=e.range.range,{startRow:c,startColumn:d}=o,a=t.getCellRaw(c,d);if(e.isFormula)return n?{f:a.f.replace(new RegExp(A(i),s),r),v:null}:null;if(!!((v=a.p)!=null&&v.body)){const I=l.Tools.deepClone(a.p);return l.replaceInDocumentBody(I.body,i,r),{p:I}}return{v:a.v.toString().replace(new RegExp(A(i),s),r)}}};P=x([C(2,l.IUniverInstanceService),C(3,M.IRenderManagerService),C(4,l.ICommandService),C(5,l.IContextService),C(6,p.Inject(l.ThemeService)),C(7,p.Inject(R.SheetsSelectionsService))],P);function A(h){return h.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}let B=class extends l.Disposable{constructor(e,t,n){super();m(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(y.SheetSkeletonManagerService),o=this._injector.createInstance(P,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}}};B=x([C(0,l.IUniverInstanceService),C(1,M.IRenderManagerService),C(2,p.Inject(p.Injector))],B);const f={hit:!1,replaceable:!1,isFormula:!1,rawData:null};function ee(h,e,t,n,i){const{findBy:r}=n,s=r===S.FindBy.FORMULA,o=h.getCellRaw(e,t);return f.rawData=o,!(o!=null&&o.f)?(f.isFormula=!1,W(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?W({v:o.f},n)?(f.hit=!0,f.replaceable=!0,f):(f.hit=!1,f.replaceable=!1,f):(f.replaceable=!1,W(i,n)?f.hit=!0:f.hit=!1,f))}function W(h,e){let t=te(h);return t?e.matchesTheWholeCell?(t=ne(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 te(h){var t,n,i;const e=(i=(n=(t=h==null?void 0:h.p)==null?void 0:t.body)==null?void 0:n.dataStream)!=null?i:h==null?void 0:h.v;return typeof e=="number"?`${e}`:typeof e=="boolean"?e?"1":"0":e}function ne(h){return h.replace(/^ +/g,"").replace(/ +$/g,"")}var D=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,se=(h,e,t)=>e in h?D(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t,re=(h,e,t,n)=>{for(var i=n>1?void 0:n?ie(e,t):e,r=h.length-1,s;r>=0;r--)(s=h[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&D(e,t,i),i},oe=(h,e)=>(t,n)=>e(t,n,h),N=(h,e,t)=>se(h,typeof e!="symbol"?e+"":e,t);const he="SHEET_FIND_REPLACE_PLUGIN";_.UniverSheetsFindReplacePlugin=class extends l.Plugin{constructor(e,t){super(),this._injector=t}onStarting(e){[[_.SheetsFindReplaceController]].forEach(t=>e.add(t))}},N(_.UniverSheetsFindReplacePlugin,"pluginName",he),N(_.UniverSheetsFindReplacePlugin,"type",l.UniverInstanceType.UNIVER_SHEET),_.UniverSheetsFindReplacePlugin=re([l.DependentOn(R.UniverSheetsPlugin,R.UniverSheetsPlugin,S.UniverFindReplacePlugin),oe(1,p.Inject(p.Injector))],_.UniverSheetsFindReplacePlugin),_.SheetReplaceCommand=U,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("@univerjs/find-replace"),require("@univerjs/sheets"),require("@univerjs/engine-render"),require("@univerjs/sheets-ui"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/find-replace","@univerjs/sheets","@univerjs/engine-render","@univerjs/sheets-ui","rxjs"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverSheetsFindReplace={},global.UniverCore,global.UniverFindReplace,global.UniverSheets,global.UniverEngineRender,global.UniverSheetsUi,global.rxjs))})(this,function(exports2,core,findReplace,sheets,engineRender,sheetsUi,rxjs){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a,_b,_c,_d;const _SheetFindReplaceHighlightShape=class _SheetFindReplaceHighlightShape extends engineRender.Shape{constructor(key,props){super(key,props);__publicField(this,"_activated",!1);__publicField(this,"_inHiddenRange",!1);__publicField(this,"_color");props&&this.setShapeProps(props)}setShapeProps(props){this._activated=!!props.activated,typeof props.inHiddenRange<"u"&&(this._inHiddenRange=props.inHiddenRange),typeof props.color<"u"&&(this._color=props.color),this.transformByState({width:props.width,height:props.height})}_draw(ctx){const activated=this._activated,color=`rgba(${this._color.r}, ${this._color.g}, ${this._color.b}, 0.35)`,borderColor=`rgb(${this._color.r}, ${this._color.g}, ${this._color.b})`;engineRender.Rect.drawWith(ctx,{width:this.width,height:this.height,fill:color,stroke:activated?borderColor:void 0,strokeWidth:activated?2:0,evented:!1})}};__name(_SheetFindReplaceHighlightShape,"SheetFindReplaceHighlightShape");let SheetFindReplaceHighlightShape=_SheetFindReplaceHighlightShape;const SheetReplaceCommand={id:"sheet.command.replace",type:core.CommandType.COMMAND,handler:__name(async(accessor,params)=>{const undoRedoService=accessor.get(core.IUndoRedoService),commandService=accessor.get(core.ICommandService),{unitId,replacements}=params,disposeBatchingHandler=undoRedoService.__tempBatchingUndoRedo(unitId),results=await Promise.all(replacements.map(replacement=>commandService.executeCommand(sheets.SetRangeValuesCommand.id,{unitId,subUnitId:replacement.subUnitId,value:replacement.value})));return disposeBatchingHandler.dispose(),getReplaceAllResult(results,replacements)},"handler")};function getReplaceAllResult(results,replacements){let success=0,failure=0;return results.forEach((r,index)=>{const count=replacements[index].count;r?success+=count:failure+=count}),{success,failure}}__name(getReplaceAllResult,"getReplaceAllResult");function isSamePosition(range1,range2){return range1.startRow===range2.startRow&&range1.startColumn===range2.startColumn}__name(isSamePosition,"isSamePosition");function isBehindPositionWithRowPriority(range1,range2){return range1.startRow<range2.startRow||range1.startRow===range2.startRow&&range1.startColumn<=range2.startColumn}__name(isBehindPositionWithRowPriority,"isBehindPositionWithRowPriority");function isBehindPositionWithColumnPriority(range1,range2){return range1.startColumn<range2.startColumn||range1.startColumn===range2.startColumn&&range1.startRow<=range2.startRow}__name(isBehindPositionWithColumnPriority,"isBehindPositionWithColumnPriority");function isBeforePositionWithRowPriority(range1,range2){return range1.startRow>range2.startRow||range1.startRow===range2.startRow&&range1.startColumn>=range2.startColumn}__name(isBeforePositionWithRowPriority,"isBeforePositionWithRowPriority");function isBeforePositionWithColumnPriority(range1,range2){return range1.startColumn>range2.startColumn||range1.startColumn===range2.startColumn&&range1.startRow>=range2.startRow}__name(isBeforePositionWithColumnPriority,"isBeforePositionWithColumnPriority");function isSelectionSingleCell(selection,worksheet){const{range}=selection,{startRow,startColumn}=range,hasMergedCell=worksheet.getMergedCell(startRow,startColumn);return hasMergedCell?core.Rectangle.equals(range,hasMergedCell):range.endRow===range.startRow&&range.endColumn===range.startColumn}__name(isSelectionSingleCell,"isSelectionSingleCell");var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");exports2.SheetsFindReplaceController=(_a=class extends core.Disposable{constructor(_injector,_findReplaceController,_contextService,_findReplaceService,_commandService){super();__publicField(this,"_provider");this._injector=_injector,this._findReplaceController=_findReplaceController,this._contextService=_contextService,this._findReplaceService=_findReplaceService,this._commandService=_commandService,this._init(),this._initCommands()}dispose(){super.dispose(),this._findReplaceController.closePanel(),this._provider.dispose()}_init(){const provider=this._injector.createInstance(SheetsFindReplaceProvider);this._provider=provider,this.disposeWithMe(this._findReplaceService.registerFindReplaceProvider(provider)),this.disposeWithMe(this._contextService.subscribeContextValue$(core.EDITOR_ACTIVATED).pipe(rxjs.filter(v=>!!v)).subscribe(()=>this._findReplaceController.closePanel()))}_initCommands(){[SheetReplaceCommand].forEach(command=>this.disposeWithMe(this._commandService.registerCommand(command)))}},__name(_a,"SheetsFindReplaceController"),_a),exports2.SheetsFindReplaceController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Steady,exports2.SheetsFindReplaceController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,core.Inject(findReplace.FindReplaceController)),__decorateParam$1(2,core.IContextService),__decorateParam$1(3,findReplace.IFindReplaceService),__decorateParam$1(4,core.ICommandService)],exports2.SheetsFindReplaceController);const SHEETS_FIND_REPLACE_PROVIDER_NAME="sheets-find-replace-provider",FIND_REPLACE_Z_INDEX=1e4;let SheetFindModel=(_b=class extends findReplace.FindModel{constructor(_workbook,_sheetSkeletonManagerService,_univerInstanceService,_renderManagerService,_commandService,_contextService,_themeService,_selectionManagerService){super();__publicField(this,"_matchesUpdate$",new rxjs.Subject);__publicField(this,"matchesUpdate$",this._matchesUpdate$.asObservable());__publicField(this,"_activelyChangingMatch$",new rxjs.Subject);__publicField(this,"activelyChangingMatch$",this._activelyChangingMatch$.asObservable());__publicField(this,"_matchesByWorksheet",new Map);__publicField(this,"_matches",[]);__publicField(this,"_matchesPosition",0);__publicField(this,"_activeHighlightIndex",-1);__publicField(this,"_highlightShapes",[]);__publicField(this,"_currentHighlightShape",null);__publicField(this,"_query",null);__publicField(this,"_workbookSelections");this._workbook=_workbook,this._sheetSkeletonManagerService=_sheetSkeletonManagerService,this._univerInstanceService=_univerInstanceService,this._renderManagerService=_renderManagerService,this._commandService=_commandService,this._contextService=_contextService,this._themeService=_themeService,this._workbookSelections=_selectionManagerService.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(query){switch(this._query=query,query.findBy===findReplace.FindBy.FORMULA?this._toggleDisplayRawFormula(!0):this._toggleDisplayRawFormula(!1),query.findScope){case findReplace.FindScope.UNIT:this.findInWorkbook(query);break;case findReplace.FindScope.SUBUNIT:default:this.findInActiveWorksheet(query);break}}_toggleDisplayRawFormula(force){this._contextService.setContextValue(engineRender.RENDER_RAW_FORMULA_KEY,force)}findInWorkbook(query){const unitId=this._workbook.getUnitId();let complete,firstSearch=!0;const findInWorkbook=__name(()=>{const allCompletes=this._workbook.getSheets().filter(worksheet=>!worksheet.isSheetHidden()).map(worksheet=>{const complete2=this._findInWorksheet(worksheet,query,unitId),sheetId=worksheet.getSheetId(),{results}=complete2;return results.length?this._matchesByWorksheet.set(sheetId,complete2.results):this._matchesByWorksheet.delete(sheetId),complete2});this._matches=allCompletes.map(c=>c.results).flat(),this._updateFindHighlight(),firstSearch?(complete={results:this._matches},firstSearch=!1):this._matchesUpdate$.next(this._matches)},"findInWorkbook");return this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(()=>{this._updateFindHighlight(),this._updateCurrentHighlightShape(this._activeHighlightIndex)})),this.disposeWithMe(core.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService.onCommandExecuted)).pipe(rxjs.filter(([command,options])=>command.id===sheets.SetWorksheetActiveOperation.id&&!(options!=null&&options.fromFindReplace))).subscribe(()=>{const activeSheet=this._workbook.getActiveSheet();if(!activeSheet)return;const activeSheetId=activeSheet.getSheetId();this._matchesByWorksheet.has(activeSheetId)&&this._findNextMatchOnActiveSheetChange(activeSheet)})),this.disposeWithMe(core.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(rxjs.filter(([command])=>command.type===core.CommandType.MUTATION&&command.params.unitId===this._workbook.getUnitId()),rxjs.throttleTime(600,void 0,{leading:!1,trailing:!0})).subscribe(()=>findInWorkbook())),findInWorkbook(),complete}_findNextMatchOnActiveSheetChange(activeSheet){let match,index,globalIndex=0;const matchesByWorksheet=this._matchesByWorksheet.get(activeSheet.getSheetId()),selections=this._workbookSelections.getCurrentSelections();selections!=null&&selections.length?([match,globalIndex]=this._findNextMatchByRange(matchesByWorksheet,selections[0].range),index=matchesByWorksheet.findIndex(m=>m===match)):(match=matchesByWorksheet[0],index=0,globalIndex=this._matches.findIndex(m=>m===match)),this._matchesPosition=globalIndex+1,this._activelyChangingMatch$.next(match),this._activeHighlightIndex=index,this._updateFindHighlight(),this._updateCurrentHighlightShape(index)}findInActiveWorksheet(query){const unitId=this._workbook.getUnitId(),checkShouldFindInSelections=__name(()=>{var _a2;const currentWorksheet=this._workbook.getActiveSheet();if(!currentWorksheet)return!1;const currentSelections=this._workbookSelections.getCurrentSelections();return(_a2=currentSelections==null?void 0:currentSelections.some(selection=>!isSelectionSingleCell(selection,currentWorksheet)))!=null?_a2:!1},"checkShouldFindInSelections");let complete,firstSearch=!0,findBySelections=!1;const performFindInWorksheet=__name(()=>{const currentWorksheet=this._workbook.getActiveSheet();if(!currentWorksheet)return{results:[]};const lastMatch=this.currentMatch;findBySelections=checkShouldFindInSelections();const currentSelections=this._workbookSelections.getCurrentSelections(),newComplete=findBySelections?this._findInSelections(currentWorksheet,currentSelections,query,unitId):this._findInWorksheet(currentWorksheet,query,unitId);return this._matches=newComplete.results,this._matchesPosition=this._tryRestoreLastMatchesPosition(lastMatch,this._matches),firstSearch?(complete=newComplete,firstSearch=!1):this._matchesUpdate$.next(this._matches),this._updateFindHighlight(),newComplete},"performFindInWorksheet");return this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(()=>this._updateFindHighlight())),this.disposeWithMe(rxjs.merge(core.fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(rxjs.filter(([command])=>{if(command.type===core.CommandType.MUTATION&&command.params.unitId===this._workbook.getUnitId())return!0;if(command.id===sheets.SetSelectionsOperation.id&&command.params.unitId===unitId){const shouldFindBySelections=checkShouldFindInSelections();return shouldFindBySelections===!1&&findBySelections===!1?!1:(findBySelections=shouldFindBySelections,!0)}return!1})),this._workbook.activeSheet$.pipe(rxjs.skip(1))).pipe(rxjs.debounceTime(200)).subscribe(()=>performFindInWorksheet())),performFindInWorksheet(),complete}_findInRange(worksheet,query,range,unitId,dedupeFn){const results=[],subUnitId=worksheet.getSheetId(),iter=(query.findDirection===findReplace.FindDirection.COLUMN?worksheet.iterateByColumn:worksheet.iterateByRow).bind(worksheet)(range);for(const value of iter){const{row,col,colSpan,rowSpan,value:cellData}=value;if(dedupeFn!=null&&dedupeFn(row,col)||!cellData||worksheet.getRowFiltered(row))continue;const{hit,replaceable,isFormula}=hitCell(worksheet,row,col,query,cellData);if(hit){const result={provider:SHEETS_FIND_REPLACE_PROVIDER_NAME,unitId,replaceable,isFormula,range:{subUnitId,range:{startRow:row,startColumn:col,endColumn:col+(colSpan!=null?colSpan:1)-1,endRow:row+(rowSpan!=null?rowSpan:1)-1}}};results.push(result)}}return{results}}_findInSelections(worksheet,selections,query,unitId){const{findDirection}=query,sortFn=findDirection===findReplace.FindDirection.ROW?isBehindPositionWithRowPriority:isBehindPositionWithColumnPriority,dedupeSet=new Set;return{results:selections.map(selection=>this._findInRange(worksheet,query,selection.range,unitId,(row,col)=>{const key=`${row}-${col}`;return dedupeSet.has(key)?!0:(dedupeSet.add(key),!1)}).results).flat().sort((a,b)=>sortFn(a.range.range,b.range.range)?-1:1)}}_findInWorksheet(worksheet,query,unitId){const rowCount=worksheet.getRowCount(),colCount=worksheet.getColumnCount(),range={startRow:0,startColumn:0,endRow:rowCount-1,endColumn:colCount-1};return this._findInRange(worksheet,query,range,unitId)}_disposeHighlights(){var _a2;this._highlightShapes.forEach(shape=>{shape.getScene().makeDirty(),shape.dispose()}),this._highlightShapes=[],(_a2=this._currentHighlightShape)==null||_a2.dispose(),this._currentHighlightShape=null}_updateFindHighlight(){var _a2;this._disposeHighlights();const skeleton=(_a2=this._sheetSkeletonManagerService.getCurrent())==null?void 0:_a2.skeleton;if(!skeleton)return;const unitId=this._workbook.getUnitId(),currentRender=this._renderManagerService.getRenderById(unitId);if(currentRender==null)return;const{scene}=currentRender,matches=this._matches,searchBackgroundColor=this._themeService.getCurrentTheme().gold400,color=new core.ColorKit(searchBackgroundColor).toRgb(),worksheet=this._workbook.getActiveSheet();if(!worksheet)return;const activeSheetId=worksheet.getSheetId(),highlightShapes=matches.filter(match=>match.range.subUnitId===activeSheetId).map((find,index)=>{const{startColumn,startRow,endColumn,endRow}=find.range.range,startPosition=sheetsUi.getCoordByCell(startRow,startColumn,scene,skeleton),endPosition=sheetsUi.getCoordByCell(endRow,endColumn,scene,skeleton),{startX,startY}=startPosition,{endX,endY}=endPosition,rowHidden=!worksheet.getRowRawVisible(startRow),columnHidden=!worksheet.getColVisible(startColumn),inHiddenRange=rowHidden||columnHidden,width=columnHidden?2:endX-startX,height=rowHidden?2:endY-startY,props={left:startX,top:startY,color,width,height,evented:!1,inHiddenRange,zIndex:FIND_REPLACE_Z_INDEX};return new SheetFindReplaceHighlightShape(`find-highlight-${index}`,props)});scene.addObjects(highlightShapes),this._highlightShapes=highlightShapes,scene.makeDirty()}_updateCurrentHighlightShape(matchIndex){var _a2;if((_a2=this._currentHighlightShape)==null||_a2.setShapeProps({activated:!1}),this._currentHighlightShape=null,matchIndex!==void 0){const shape=this._highlightShapes[matchIndex];if(!shape)return;this._currentHighlightShape=shape,shape.setShapeProps({activated:!0})}}_getSheetObject(){return sheetsUi.getSheetObject(this._univerInstanceService,this._renderManagerService)}_focusMatch(match){var _a2;const subUnitId=match.range.subUnitId;subUnitId!==((_a2=this._workbook.getActiveSheet())==null?void 0:_a2.getSheetId())&&this._commandService.executeCommand(sheets.SetWorksheetActivateCommand.id,{unitId:this._workbook.getUnitId(),subUnitId},{fromFindReplace:!0}),this._commandService.executeCommand(sheetsUi.ScrollToCellCommand.id,{range:match.range.range},{fromFindReplace:!0})}_tryRestoreLastMatchesPosition(lastMatch,newMatches){if(!lastMatch)return 0;const{subUnitId:lastSubUnitId}=lastMatch.range,{startColumn:lastStartColumn,startRow:lastStartRow}=lastMatch.range.range,index=newMatches.findIndex(match=>{if(lastSubUnitId!==match.range.subUnitId)return!1;const{startColumn,startRow}=match.range.range;return startColumn===lastStartColumn&&startRow===lastStartRow});return index>-1?index+1:0}moveToNextMatch(params){var _a2,_b2,_c2,_d2,_e;if(!this._matches.length)return null;const loop=(_a2=params==null?void 0:params.loop)!=null?_a2:!1,stayIfOnMatch=(_b2=params==null?void 0:params.stayIfOnMatch)!=null?_b2:!1,noFocus=(_c2=params==null?void 0:params.noFocus)!=null?_c2:!1,ignoreSelection=(_d2=params==null?void 0:params.ignoreSelection)!=null?_d2:!1,matchToMove=this._findNextMatch(loop,stayIfOnMatch,ignoreSelection);if(matchToMove){const[match,index]=matchToMove;return this._matchesPosition=index+1,this._query.findScope===findReplace.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(match.range.subUnitId).findIndex(m=>m===match):this._activeHighlightIndex=index,noFocus||this._focusMatch(match),((_e=this._workbook.getActiveSheet())==null?void 0:_e.getSheetId())===match.range.subUnitId&&this._updateCurrentHighlightShape(this._activeHighlightIndex),match}return this._matchesPosition=0,this._updateCurrentHighlightShape(),null}moveToPreviousMatch(params){var _a2,_b2,_c2,_d2,_e;if(!this._matches.length)return null;const loop=(_a2=params==null?void 0:params.loop)!=null?_a2:!1,stayIfOnMatch=(_b2=params==null?void 0:params.stayIfOnMatch)!=null?_b2:!1,noFocus=(_c2=params==null?void 0:params.noFocus)!=null?_c2:!1,ignoreSelection=(_d2=params==null?void 0:params.ignoreSelection)!=null?_d2:!1,matchToMove=this._findPreviousMatch(loop,stayIfOnMatch,ignoreSelection);if(matchToMove){const[match,index]=matchToMove;return this._matchesPosition=index+1,this._query.findScope===findReplace.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(match.range.subUnitId).findIndex(m=>m===match):this._activeHighlightIndex=index,noFocus||this._focusMatch(match),((_e=this._workbook.getActiveSheet())==null?void 0:_e.getSheetId())===match.range.subUnitId&&this._updateCurrentHighlightShape(this._activeHighlightIndex),match}return this._matchesPosition=0,this._updateCurrentHighlightShape(),null}_findPreviousMatch(loop=!1,stayIfOnMatch=!1,ignoreSelection=!1){var _a2;if(this.currentMatch){const currentMatchIndex=this._matches.findIndex(match=>match===this.currentMatch);if(stayIfOnMatch)return[this.currentMatch,currentMatchIndex];const nextMatchIndex=currentMatchIndex-1;if(!loop&&nextMatchIndex<0)return null;const length=this._matches.length,modded=(nextMatchIndex+length)%length;return[this._matches[modded],modded]}const lastSelection=this._workbookSelections.getCurrentLastSelection();if(ignoreSelection||!lastSelection){const lastIndex=this._matches.length-1;return[this._matches[lastIndex],lastIndex]}if(this._query.findScope!==findReplace.FindScope.UNIT)return this._findPreviousMatchByRange(this._matches,lastSelection.range);const currentSheetId=(_a2=this._workbook.getActiveSheet())==null?void 0:_a2.getSheetId();if(!currentSheetId)return null;const worksheetThatHasMatch=this._findPreviousWorksheetThatHasAMatch(currentSheetId,loop);return worksheetThatHasMatch?this._findPreviousMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch),lastSelection.range):null}_findNextMatch(loop=!1,stayIfOnMatch=!1,ignoreSelection=!1){var _a2;if(this.currentMatch){const currentMatchIndex=this._matches.findIndex(match=>match===this.currentMatch);if(stayIfOnMatch)return[this.currentMatch,currentMatchIndex];const nextMatchIndex=currentMatchIndex+1,length=this._matches.length;if(!loop&&nextMatchIndex>=length)return null;const modded=nextMatchIndex%length;return[this._matches[modded],modded]}const last=this._workbookSelections.getCurrentLastSelection();if(ignoreSelection||!last)return[this._matches[0],0];if(this._query.findScope!==findReplace.FindScope.UNIT)return this._findNextMatchByRange(this._matches,last.range,stayIfOnMatch);const currentSheetId=(_a2=this._workbook.getActiveSheet())==null?void 0:_a2.getSheetId();if(!currentSheetId)return null;const worksheetThatHasMatch=this._findNextWorksheetThatHasAMatch(currentSheetId,loop);return worksheetThatHasMatch?this._findNextMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch),last.range):null}_findPreviousWorksheetThatHasAMatch(currentWorksheet,loop=!1){const rawWorksheetsInOrder=this._workbook.getSheetOrders(),currentSheetIndex=rawWorksheetsInOrder.findIndex(sheet=>sheet===currentWorksheet),first=(loop?core.rotate(rawWorksheetsInOrder,currentSheetIndex+1):rawWorksheetsInOrder.slice(0,currentSheetIndex+1)).findLast(worksheet=>this._matchesByWorksheet.has(worksheet));return first!=null?first:null}_findNextWorksheetThatHasAMatch(currentWorksheet,loop=!1){const rawWorksheetsInOrder=this._workbook.getSheetOrders(),currentSheetIndex=rawWorksheetsInOrder.findIndex(sheet=>sheet===currentWorksheet),first=(loop?core.rotate(rawWorksheetsInOrder,currentSheetIndex):rawWorksheetsInOrder.slice(currentSheetIndex)).find(worksheet=>this._matchesByWorksheet.has(worksheet));return first!=null?first:null}_findNextMatchByRange(matches,range,stayIfOnMatch=!1){const findByRow=this._query.findDirection===findReplace.FindDirection.ROW;let index=matches.findIndex(match2=>{const matchRange=match2.range.range;if(!(findByRow?isBehindPositionWithRowPriority(range,matchRange):isBehindPositionWithColumnPriority(range,matchRange)))return!1;const isSame=isSamePosition(range,matchRange);return stayIfOnMatch?isSame:!isSame});index===-1&&(index=matches.length-1);const match=matches[index];return[match,this._matches.findIndex(m=>m===match)]}_findPreviousMatchByRange(matches,range,stayIfOnMatch=!1){const findByRow=this._query.findDirection===findReplace.FindDirection.ROW;let index=this._matches.findLastIndex(match2=>{const matchRange=match2.range.range;if(!(findByRow?isBeforePositionWithRowPriority(range,matchRange):isBeforePositionWithColumnPriority(range,matchRange)))return!1;const isSame=isSamePosition(range,matchRange);return stayIfOnMatch?isSame:!isSame});index===-1&&(index=0);const match=matches[index];return[match,this._matches.findIndex(m=>m===match)]}async replace(replaceString){if(this._matchesCount===0||!this.currentMatch||!this._query||!this.currentMatch.replaceable)return!1;const range=this.currentMatch.range,targetWorksheet=this._workbook.getSheetBySheetId(this.currentMatch.range.subUnitId),newContent=this._getReplacedCellData(this.currentMatch,targetWorksheet,this._query.findBy===findReplace.FindBy.FORMULA,this._query.findString,replaceString,this._query.caseSensitive?"g":"ig"),params={unitId:this.currentMatch.unitId,subUnitId:range.subUnitId,value:{[range.range.startRow]:{[range.range.startColumn]:newContent}}};return this._commandService.executeCommand(sheets.SetRangeValuesCommand.id,params)}async replaceAll(replaceString){if(this._matchesCount===0||!this._query)return{success:0,failure:0};const unitId=this._workbook.getUnitId(),{findString,caseSensitive,findBy}=this._query,shouldReplaceFormula=findBy===findReplace.FindBy.FORMULA,replaceFlag=caseSensitive?"g":"ig",replacements=[];return core.groupBy(this._matches.filter(m=>m.replaceable),match=>match.range.subUnitId).forEach((matches,subUnitId)=>{const matrix=new core.ObjectMatrix,worksheet=this._workbook.getSheetBySheetId(subUnitId);matches.forEach(match=>{const{startColumn,startRow}=match.range.range,newCellData=this._getReplacedCellData(match,worksheet,shouldReplaceFormula,findString,replaceString,replaceFlag);newCellData&&matrix.setValue(startRow,startColumn,newCellData)}),replacements.push({count:matches.length,subUnitId,value:matrix.getMatrix()})}),replacements?this._commandService.executeCommand(SheetReplaceCommand.id,{unitId,replacements}):{success:0,failure:0}}_getReplacedCellData(match,worksheet,shouldReplaceFormula,findString,replaceString,replaceFlag){var _a2;const range=match.range.range,{startRow,startColumn}=range,currentContent=worksheet.getCellRaw(startRow,startColumn);if(match.isFormula)return shouldReplaceFormula?{f:currentContent.f.replace(new RegExp(escapeRegExp(findString),replaceFlag),replaceString),v:null}:null;if(!!((_a2=currentContent.p)!=null&&_a2.body)){const clonedRichText=core.Tools.deepClone(currentContent.p);return core.replaceInDocumentBody(clonedRichText.body,findString,replaceString),{p:clonedRichText}}return{v:currentContent.v.toString().replace(new RegExp(escapeRegExp(findString),replaceFlag),replaceString)}}},__name(_b,"SheetFindModel"),_b);SheetFindModel=__decorateClass$1([__decorateParam$1(2,core.IUniverInstanceService),__decorateParam$1(3,engineRender.IRenderManagerService),__decorateParam$1(4,core.ICommandService),__decorateParam$1(5,core.IContextService),__decorateParam$1(6,core.Inject(core.ThemeService)),__decorateParam$1(7,core.Inject(sheets.SheetsSelectionsService))],SheetFindModel);function escapeRegExp(text){return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}__name(escapeRegExp,"escapeRegExp");let SheetsFindReplaceProvider=(_c=class extends core.Disposable{constructor(_univerInstanceService,_renderManagerService,_injector){super();__publicField(this,"_findModelsByUnitId",new Map);this._univerInstanceService=_univerInstanceService,this._renderManagerService=_renderManagerService,this._injector=_injector}async find(query){this._terminate();const allWorkbooks=this._univerInstanceService.getAllUnitsForType(core.UniverInstanceType.UNIVER_SHEET),parsedQuery=this._preprocessQuery(query);return allWorkbooks.map(workbook=>{const skeletonManagerService=this._renderManagerService.getRenderById(workbook.getUnitId()).with(sheetsUi.SheetSkeletonManagerService),sheetFind=this._injector.createInstance(SheetFindModel,workbook,skeletonManagerService);return this._findModelsByUnitId.set(workbook.getUnitId(),sheetFind),sheetFind.start(parsedQuery),sheetFind})}terminate(){this._terminate()}_terminate(){this._findModelsByUnitId.forEach(model=>model.dispose()),this._findModelsByUnitId.clear()}_preprocessQuery(query){let findString=query.caseSensitive?query.findString:query.findString.toLowerCase();return findString=findString.trim(),{...query,findString}}},__name(_c,"SheetsFindReplaceProvider"),_c);SheetsFindReplaceProvider=__decorateClass$1([__decorateParam$1(0,core.IUniverInstanceService),__decorateParam$1(1,engineRender.IRenderManagerService),__decorateParam$1(2,core.Inject(core.Injector))],SheetsFindReplaceProvider);const VALUE_PASSING_OBJECT={hit:!1,replaceable:!1,isFormula:!1,rawData:null};function hitCell(worksheet,row,col,query,cellData){const{findBy}=query,findByFormula=findBy===findReplace.FindBy.FORMULA,rawData=worksheet.getCellRaw(row,col);return VALUE_PASSING_OBJECT.rawData=rawData,!(rawData!=null&&rawData.f)?(VALUE_PASSING_OBJECT.isFormula=!1,matchCellData(cellData,query)?rawData?(VALUE_PASSING_OBJECT.hit=!0,VALUE_PASSING_OBJECT.replaceable=!0):(VALUE_PASSING_OBJECT.hit=!0,VALUE_PASSING_OBJECT.replaceable=!1):(VALUE_PASSING_OBJECT.hit=!1,VALUE_PASSING_OBJECT.replaceable=!1),VALUE_PASSING_OBJECT):(VALUE_PASSING_OBJECT.isFormula=!0,findByFormula?matchCellData({v:rawData.f},query)?(VALUE_PASSING_OBJECT.hit=!0,VALUE_PASSING_OBJECT.replaceable=!0,VALUE_PASSING_OBJECT):(VALUE_PASSING_OBJECT.hit=!1,VALUE_PASSING_OBJECT.replaceable=!1,VALUE_PASSING_OBJECT):(VALUE_PASSING_OBJECT.replaceable=!1,matchCellData(cellData,query)?VALUE_PASSING_OBJECT.hit=!0:VALUE_PASSING_OBJECT.hit=!1,VALUE_PASSING_OBJECT))}__name(hitCell,"hitCell");function matchCellData(cellData,query){let value=extractPureValue(cellData);return value?query.matchesTheWholeCell?(value=trimLeadingTrailingWhitespace(value),query.caseSensitive?value===query.findString:value.toLowerCase()===query.findString):query.caseSensitive?value.indexOf(query.findString)>-1:value.toLowerCase().indexOf(query.findString)>-1:!1}__name(matchCellData,"matchCellData");function extractPureValue(cell){var _a2,_b2,_c2;const rawValue=(_c2=(_b2=(_a2=cell==null?void 0:cell.p)==null?void 0:_a2.body)==null?void 0:_b2.dataStream)!=null?_c2:cell==null?void 0:cell.v;return typeof rawValue=="number"?`${rawValue}`:typeof rawValue=="boolean"?rawValue?"1":"0":rawValue}__name(extractPureValue,"extractPureValue");function trimLeadingTrailingWhitespace(value){return value.replace(/^ +/g,"").replace(/ +$/g,"")}__name(trimLeadingTrailingWhitespace,"trimLeadingTrailingWhitespace");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__defNormalProp2=__name((obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,"__defNormalProp"),__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),__publicField2=__name((obj,key,value)=>__defNormalProp2(obj,typeof key!="symbol"?key+"":key,value),"__publicField");const NAME="SHEET_FIND_REPLACE_PLUGIN";exports2.UniverSheetsFindReplacePlugin=(_d=class extends core.Plugin{constructor(_config,_injector){super(),this._injector=_injector}onStarting(){[[exports2.SheetsFindReplaceController]].forEach(d=>this._injector.add(d))}},__name(_d,"UniverSheetsFindReplacePlugin"),_d),__publicField2(exports2.UniverSheetsFindReplacePlugin,"pluginName",NAME),__publicField2(exports2.UniverSheetsFindReplacePlugin,"type",core.UniverInstanceType.UNIVER_SHEET),exports2.UniverSheetsFindReplacePlugin=__decorateClass([core.DependentOn(sheets.UniverSheetsPlugin,sheets.UniverSheetsPlugin,findReplace.UniverFindReplacePlugin),__decorateParam(1,core.Inject(core.Injector))],exports2.UniverSheetsFindReplacePlugin),exports2.SheetReplaceCommand=SheetReplaceCommand,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/sheets-find-replace",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "UniverSheet find replace plugin",
|
|
6
6
|
"author": "DreamNum <developer@univer.ai>",
|
|
@@ -47,30 +47,28 @@
|
|
|
47
47
|
"lib"
|
|
48
48
|
],
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@wendellhu/redi": "0.16.0",
|
|
51
50
|
"rxjs": ">=7.0.0",
|
|
52
|
-
"@univerjs/core": "0.2.
|
|
53
|
-
"@univerjs/engine-render": "0.2.
|
|
54
|
-
"@univerjs/find-replace": "0.2.
|
|
55
|
-
"@univerjs/sheets-ui": "0.2.
|
|
56
|
-
"@univerjs/sheets": "0.2.
|
|
51
|
+
"@univerjs/core": "0.2.6",
|
|
52
|
+
"@univerjs/engine-render": "0.2.6",
|
|
53
|
+
"@univerjs/find-replace": "0.2.6",
|
|
54
|
+
"@univerjs/sheets-ui": "0.2.6",
|
|
55
|
+
"@univerjs/sheets": "0.2.6"
|
|
57
56
|
},
|
|
58
57
|
"dependencies": {
|
|
59
58
|
"@univerjs/protocol": "0.1.38-alpha.23"
|
|
60
59
|
},
|
|
61
60
|
"devDependencies": {
|
|
62
|
-
"@wendellhu/redi": "0.16.0",
|
|
63
61
|
"rxjs": "^7.8.1",
|
|
64
|
-
"typescript": "^5.5.
|
|
65
|
-
"vite": "^5.3.
|
|
66
|
-
"vitest": "^2.0.
|
|
67
|
-
"@univerjs/core": "0.2.
|
|
68
|
-
"@univerjs/engine-formula": "0.2.
|
|
69
|
-
"@univerjs/
|
|
70
|
-
"@univerjs/
|
|
71
|
-
"@univerjs/
|
|
72
|
-
"@univerjs/
|
|
73
|
-
"@univerjs/sheets": "0.2.
|
|
62
|
+
"typescript": "^5.5.4",
|
|
63
|
+
"vite": "^5.3.5",
|
|
64
|
+
"vitest": "^2.0.4",
|
|
65
|
+
"@univerjs/core": "0.2.6",
|
|
66
|
+
"@univerjs/engine-formula": "0.2.6",
|
|
67
|
+
"@univerjs/engine-render": "0.2.6",
|
|
68
|
+
"@univerjs/find-replace": "0.2.6",
|
|
69
|
+
"@univerjs/sheets": "0.2.6",
|
|
70
|
+
"@univerjs/shared": "0.2.6",
|
|
71
|
+
"@univerjs/sheets-ui": "0.2.6"
|
|
74
72
|
},
|
|
75
73
|
"univerSpace": {
|
|
76
74
|
".": {
|