@univerjs/sheets-find-replace 0.1.3

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.
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { Disposable, ICommandService, IContextService, IUniverInstanceService, ThemeService } from '@univerjs/core';
17
+ import type { ICellData, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
18
+ import { IRenderManagerService } from '@univerjs/engine-render';
19
+ import type { IFindComplete, IFindMatch, IFindMoveParams, IFindQuery, IReplaceAllResult } from '@univerjs/find-replace';
20
+ import { FindModel, FindReplaceController, IFindReplaceService } from '@univerjs/find-replace';
21
+ import { SelectionManagerService } from '@univerjs/sheets';
22
+ import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
23
+ import { type IDisposable, Injector } from '@wendellhu/redi';
24
+ export declare class SheetsFindReplaceController extends Disposable implements IDisposable {
25
+ private readonly _injector;
26
+ private readonly _findReplaceController;
27
+ private readonly _contextService;
28
+ private readonly _findReplaceService;
29
+ private readonly _commandService;
30
+ private _provider;
31
+ constructor(_injector: Injector, _findReplaceController: FindReplaceController, _contextService: IContextService, _findReplaceService: IFindReplaceService, _commandService: ICommandService);
32
+ dispose(): void;
33
+ private _init;
34
+ private _initCommands;
35
+ }
36
+ declare const SHEETS_FIND_REPLACE_PROVIDER_NAME = "sheets-find-replace-provider";
37
+ export interface ISheetCellMatch extends IFindMatch {
38
+ isFormula: boolean;
39
+ provider: typeof SHEETS_FIND_REPLACE_PROVIDER_NAME;
40
+ range: {
41
+ subUnitId: string;
42
+ range: IRange;
43
+ };
44
+ }
45
+ /**
46
+ * This class executes finding in a workbook and subscribe to the content change event so when its results changes
47
+ * FindReplaceService would know that and update searching results. Also this class in responsible for
48
+ * highlighting matched cells.
49
+ */
50
+ export declare class SheetFindModel extends FindModel {
51
+ private readonly _workbook;
52
+ private readonly _univerInstanceService;
53
+ private readonly _renderManagerService;
54
+ private readonly _commandService;
55
+ private readonly _contextService;
56
+ private readonly _themeService;
57
+ private readonly _sheetSkeletonManagerService;
58
+ private readonly _selectionManagerService;
59
+ private readonly _matchesUpdate$;
60
+ readonly matchesUpdate$: import("rxjs").Observable<ISheetCellMatch[]>;
61
+ private readonly _activelyChangingMatch$;
62
+ readonly activelyChangingMatch$: import("rxjs").Observable<ISheetCellMatch>;
63
+ /** Hold matches by the worksheet they are in. Make it easier to track the next (or previous) match when searching in the whole workbook. */
64
+ private _matchesByWorksheet;
65
+ /** Hold all matches in the currently searching scope. */
66
+ private _matches;
67
+ /** Position of the current focused ISheetCellMatch, starting from 1. */
68
+ private _matchesPosition;
69
+ private _activeHighlightIndex;
70
+ private _highlightShapes;
71
+ private _currentHighlightShape;
72
+ /** This properties holds the query params during this searching session. */
73
+ private _query;
74
+ private get _matchesCount();
75
+ get unitId(): string;
76
+ get matchesCount(): number;
77
+ get matchesPosition(): number;
78
+ get currentMatch(): Nullable<ISheetCellMatch>;
79
+ constructor(_workbook: Workbook, _univerInstanceService: IUniverInstanceService, _renderManagerService: IRenderManagerService, _commandService: ICommandService, _contextService: IContextService, _themeService: ThemeService, _sheetSkeletonManagerService: SheetSkeletonManagerService, _selectionManagerService: SelectionManagerService);
80
+ dispose(): void;
81
+ getMatches(): IFindMatch[];
82
+ start(query: IFindQuery): void;
83
+ private _toggleDisplayRawFormula;
84
+ /**
85
+ * Find all matches in the current workbook no matter which worksheet is activated.
86
+ * @param query the query object
87
+ * @returns the query complete event
88
+ */
89
+ findInWorkbook(query: IFindQuery): IFindComplete;
90
+ /**
91
+ * This method is used in `findInWorkbook`. When the active sheet changes, this method helps to find the next match
92
+ * in the new worksheet.
93
+ */
94
+ private _findNextMatchOnActiveSheetChange;
95
+ /**
96
+ * Find all matches (only) in the currently activated worksheet.
97
+ * @param query the query object
98
+ * @returns the query complete event
99
+ */
100
+ findInActiveWorksheet(query: IFindQuery): IFindComplete;
101
+ private _findInRange;
102
+ private _findInSelections;
103
+ /** Find matches in a given worksheet. */
104
+ private _findInWorksheet;
105
+ private _disposeHighlights;
106
+ private _updateFindHighlight;
107
+ private _updateCurrentHighlightShape;
108
+ private _getSheetObject;
109
+ private _focusMatch;
110
+ private _tryRestoreLastMatchesPosition;
111
+ moveToNextMatch(params?: IFindMoveParams): ISheetCellMatch | null;
112
+ moveToPreviousMatch(params?: IFindMoveParams): ISheetCellMatch | null;
113
+ private _findPreviousMatch;
114
+ private _findNextMatch;
115
+ private _findPreviousWorksheetThatHasAMatch;
116
+ private _findNextWorksheetThatHasAMatch;
117
+ private _findNextMatchByRange;
118
+ private _findPreviousMatchByRange;
119
+ replace(replaceString: string): Promise<boolean>;
120
+ replaceAll(replaceString: string): Promise<IReplaceAllResult>;
121
+ private _getReplacedCellData;
122
+ }
123
+ interface IValuePassingObject {
124
+ hit: boolean;
125
+ replaceable: boolean;
126
+ isFormula: boolean;
127
+ rawData: Nullable<ICellData>;
128
+ }
129
+ /**
130
+ * This function determines if a cell's content matches what is searched for.
131
+ * @param worksheet worksheet the Worksheet to search
132
+ * @param row the row index
133
+ * @param col the column index
134
+ * @param query the parsed query object
135
+ * @returns if the cell is hit, replaceable and is a formula
136
+ */
137
+ export declare function hitCell(worksheet: Worksheet, row: number, col: number, query: IFindQuery, cellData: ICellData): IValuePassingObject;
138
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { type IRange, type Worksheet } from '@univerjs/core';
17
+ import type { ISelectionWithStyle } from '@univerjs/sheets';
18
+ export declare function isSamePosition(range1: IRange, range2: IRange): boolean;
19
+ /**
20
+ * Tell if `range2` is after (or the same as) `range1` with row direction is at priority.
21
+ * @param range1
22
+ * @param range2
23
+ * @returns
24
+ */
25
+ export declare function isBehindPositionWithRowPriority(range1: IRange, range2: IRange): boolean;
26
+ /**
27
+ * Tell if `range2` is after (or the same as) `range1` with column direction is at priority.
28
+ * @param range1
29
+ * @param range2
30
+ * @returns
31
+ */
32
+ export declare function isBehindPositionWithColumnPriority(range1: IRange, range2: IRange): boolean;
33
+ /**
34
+ * Tell if `range2` is before (or the same as) `range1` with column direction is at priority.
35
+ * @param range1
36
+ * @param range2
37
+ * @returns
38
+ */
39
+ export declare function isBeforePositionWithRowPriority(range1: IRange, range2: IRange): boolean;
40
+ export declare function isBeforePositionWithColumnPriority(range1: IRange, range2: IRange): boolean;
41
+ export declare function isSelectionSingleCell(selection: ISelectionWithStyle, worksheet: Worksheet): boolean;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export { enUS, zhCN } from './locale';
17
+ export { UniverSheetsFindReplacePlugin } from './plugin';
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ declare const _default: {
17
+ 'sheet-find-replace': {
18
+ replace: {
19
+ 'partial-failure': string;
20
+ failure: string;
21
+ };
22
+ };
23
+ };
24
+ export default _default;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export { default as enUS } from './en-US';
17
+ export { default as zhCN } from './zh-CN';
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ declare const _default: {
17
+ 'sheet-find-replace': {
18
+ replace: {
19
+ 'partial-failure': string;
20
+ failure: string;
21
+ };
22
+ };
23
+ };
24
+ export default _default;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { Plugin, PluginType } from '@univerjs/core';
17
+ import { Injector } from '@wendellhu/redi';
18
+ export interface IFindPluginConfig {
19
+ }
20
+ export declare class UniverSheetsFindReplacePlugin extends Plugin {
21
+ protected readonly _injector: Injector;
22
+ static type: PluginType;
23
+ constructor(_config: Partial<IFindPluginConfig>, _injector: Injector);
24
+ onStarting(injector: Injector): void;
25
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IRgbColor, Nullable } from '@univerjs/core';
17
+ import type { IShapeProps } from '@univerjs/engine-render';
18
+ import { Shape } from '@univerjs/engine-render';
19
+ export interface ISheetFindReplaceHighlightShapeProps extends IShapeProps {
20
+ inHiddenRange: boolean;
21
+ color: IRgbColor;
22
+ activated?: boolean;
23
+ }
24
+ export declare class SheetFindReplaceHighlightShape extends Shape<ISheetFindReplaceHighlightShapeProps> {
25
+ protected _activated: boolean;
26
+ protected _inHiddenRange: boolean;
27
+ protected _color: Nullable<IRgbColor>;
28
+ constructor(key?: string, props?: ISheetFindReplaceHighlightShapeProps);
29
+ setShapeProps(props: Partial<ISheetFindReplaceHighlightShapeProps>): void;
30
+ protected _draw(ctx: CanvasRenderingContext2D): void;
31
+ }
@@ -0,0 +1 @@
1
+ (function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@univerjs/core"),require("@wendellhu/redi"),require("@univerjs/engine-render"),require("@univerjs/find-replace"),require("@univerjs/sheets"),require("@univerjs/sheets-ui"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@wendellhu/redi","@univerjs/engine-render","@univerjs/find-replace","@univerjs/sheets","@univerjs/sheets-ui","rxjs"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.UniverSheetsFindReplace={},u.UniverCore,u["@wendellhu/redi"],u.UniverEngineRender,u.UniverFindReplace,u.UniverSheets,u.UniverSheetsUi,u.rxjs))})(this,function(u,l,m,x,S,R,k,w){"use strict";var Ie=Object.defineProperty;var Ce=(u,l,m)=>l in u?Ie(u,l,{enumerable:!0,configurable:!0,writable:!0,value:m}):u[l]=m;var _=(u,l,m)=>(Ce(u,typeof l!="symbol"?l+"":l,m),m);var T;const Q={"sheet-find-replace":{replace:{"partial-failure":"Failed to replace some cells",failure:"Failed to replace all cells"}}},X={"sheet-find-replace":{replace:{"partial-failure":"部分单元格替换失败",failure:"替换失败"}}};class Y extends x.Shape{constructor(t,i){super(t,i);_(this,"_activated",!1);_(this,"_inHiddenRange",!1);_(this,"_color");i&&this.setShapeProps(i)}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 i=this._activated,n=`rgba(${this._color.r}, ${this._color.g}, ${this._color.b}, 0.35)`,r=`rgb(${this._color.r}, ${this._color.g}, ${this._color.b})`;x.Rect.drawWith(t,{width:this.width,height:this.height,fill:n,stroke:i?r:void 0,strokeWidth:i?2:0,evented:!1})}}const A={id:"sheet.command.replace",type:l.CommandType.COMMAND,handler:async(h,e)=>{const t=h.get(l.IUndoRedoService),i=h.get(l.ICommandService),{unitId:n,replacements:r}=e,s=t.__tempBatchingUndoRedo(n),o=await Promise.all(r.map(c=>i.executeCommand(R.SetRangeValuesCommand.id,{unitId:n,subUnitId:c.subUnitId,value:c.value})));return s.dispose(),z(o,r)}};function z(h,e){let t=0,i=0;return h.forEach((n,r)=>{const s=e[r].count;n?t+=s:i+=s}),{success:t,failure:i}}function E(h,e){return h.startRow===e.startRow&&h.startColumn===e.startColumn}function D(h,e){return h.startRow<e.startRow||h.startRow===e.startRow&&h.startColumn<=e.startColumn}function j(h,e){return h.startColumn<e.startColumn||h.startColumn===e.startColumn&&h.startRow<=e.startRow}function G(h,e){return h.startRow>e.startRow||h.startRow===e.startRow&&h.startColumn>=e.startColumn}function K(h,e){return h.startColumn>e.startColumn||h.startColumn===e.startColumn&&h.startRow>=e.startRow}function J(h,e){const{range:t}=h,{startRow:i,startColumn:n}=t,r=e.getMergedCell(i,n);return r?l.Rectangle.equals(t,r):t.endRow===t.startRow&&t.endColumn===t.startColumn}var Z=Object.defineProperty,ee=Object.getOwnPropertyDescriptor,P=(h,e,t,i)=>{for(var n=i>1?void 0:i?ee(e,t):e,r=h.length-1,s;r>=0;r--)(s=h[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&Z(e,t,n),n},p=(h,e)=>(t,i)=>e(t,i,h);let U=class extends l.Disposable{constructor(e,t,i,n,r){super();_(this,"_provider");this._injector=e,this._findReplaceController=t,this._contextService=i,this._findReplaceService=n,this._commandService=r,this._init(),this._initCommands()}dispose(){super.dispose(),this._provider.dispose()}_init(){const e=this._injector.createInstance(W);this._provider=e,this.disposeWithMe(this._findReplaceService.registerFindReplaceProvider(e)),this.disposeWithMe(this._contextService.subscribeContextValue$(l.EDITOR_ACTIVATED).pipe(w.filter(t=>!!t)).subscribe(()=>this._findReplaceController.closePanel()))}_initCommands(){[A].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}};U=P([l.OnLifecycle(l.LifecycleStages.Steady,U),p(0,m.Inject(m.Injector)),p(1,m.Inject(S.FindReplaceController)),p(2,l.IContextService),p(3,S.IFindReplaceService),p(4,l.ICommandService)],U);const te="sheets-find-replace-provider",ie=1e4;let B=class extends S.FindModel{constructor(e,t,i,n,r,s,o,c){super();_(this,"_matchesUpdate$",new w.Subject);_(this,"matchesUpdate$",this._matchesUpdate$.asObservable());_(this,"_activelyChangingMatch$",new w.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._workbook=e,this._univerInstanceService=t,this._renderManagerService=i,this._commandService=n,this._contextService=r,this._themeService=s,this._sheetSkeletonManagerService=o,this._selectionManagerService=c}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(x.RENDER_RAW_FORMULA_KEY,e)}findInWorkbook(e){const t=this._workbook.getUnitId();let i,n=!0;const r=()=>{const s=this._workbook.getSheets().filter(o=>!o.isSheetHidden()).map(o=>{const c=this._findInWorksheet(o,e,t),a=o.getSheetId(),{results:d}=c;return d.length?this._matchesByWorksheet.set(a,c.results):this._matchesByWorksheet.delete(a),c});this._matches=s.map(o=>o.results).flat(),this._updateFindHighlight(),n?(i={results:this._matches},n=!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).pipe(w.filter(([s,o])=>s.id===R.SetWorksheetActiveOperation.id&&!(o!=null&&o.fromFindReplace))).subscribe(()=>{const s=this._workbook.getActiveSheet(),o=s.getSheetId();this._matchesByWorksheet.has(o)&&this._findNextMatchOnActiveSheetChange(s)})),this.disposeWithMe(l.fromCallback(this._commandService.onCommandExecuted).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(),i}_findNextMatchOnActiveSheetChange(e){let t,i,n=0;const r=this._matchesByWorksheet.get(e.getSheetId()),s=this._selectionManagerService.getSelections();s!=null&&s.length?([t,n]=this._findNextMatchByRange(r,s[0].range),i=r.findIndex(o=>o===t)):(t=r[0],i=0,n=this._matches.findIndex(o=>o===t)),this._matchesPosition=n+1,this._activelyChangingMatch$.next(t),this._activeHighlightIndex=i,this._updateFindHighlight(),this._updateCurrentHighlightShape(i)}findInActiveWorksheet(e){const t=this._workbook.getUnitId(),i=()=>{var g;const c=this._workbook.getActiveSheet(),a=this._selectionManagerService.getSelections();return(g=a==null?void 0:a.some(v=>!J(v,c)))!=null?g:!1};let n,r=!0,s=!1;const o=()=>{const c=this._workbook.getActiveSheet(),a=this.currentMatch;s=i();const d=this._selectionManagerService.getSelections(),g=s?this._findInSelections(c,d,e,t):this._findInWorksheet(c,e,t);return this._matches=g.results,this._matchesPosition=this._tryRestoreLastMatchesPosition(a,this._matches),r?(n=g,r=!1):this._matchesUpdate$.next(this._matches),this._updateFindHighlight(),g};return this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(()=>this._updateFindHighlight())),this.disposeWithMe(w.merge(l.fromCallback(this._commandService.onCommandExecuted).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 a=i();return a===!1&&s===!1?!1:(s=a,!0)}return!1})),this._workbook.activeSheet$.pipe(w.skip(1))).pipe(w.debounceTime(200)).subscribe(()=>o())),o(),n}_findInRange(e,t,i,n,r){const s=[],o=e.getSheetId(),c=(t.findDirection===S.FindDirection.COLUMN?e.iterateByColumn:e.iterateByRow).bind(e)(i);for(;;){const{done:a,value:d}=c.next();if(a)break;const{row:g,col:v,colSpan:C,rowSpan:I,value:b}=d;if(r!=null&&r(g,v))continue;const{hit:y,replaceable:M,isFormula:F}=ne(e,g,v,t,b);if(y){const O={provider:te,unitId:n,replaceable:M,isFormula:F,range:{subUnitId:o,range:{startRow:g,startColumn:v,endColumn:v+(C!=null?C:1)-1,endRow:g+(I!=null?I:1)-1}}};s.push(O)}}return{results:s}}_findInSelections(e,t,i,n){const{findDirection:r}=i,s=r===S.FindDirection.ROW?D:j,o=new Set;return{results:t.map(a=>this._findInRange(e,i,a.range,n,(d,g)=>{const v=`${d}-${g}`;return o.has(v)?!0:(o.add(v),!1)}).results).flat().sort((a,d)=>s(a.range.range,d.range.range)?-1:1)}}_findInWorksheet(e,t,i){const n=e.getRowCount(),r=e.getColumnCount(),s={startRow:0,startColumn:0,endRow:n-1,endColumn:r-1};return this._findInRange(e,t,s,i)}_disposeHighlights(){var e;this._highlightShapes.forEach(t=>{t.dispose(),t.getScene().makeDirty()}),this._highlightShapes=[],(e=this._currentHighlightShape)==null||e.dispose(),this._currentHighlightShape=null}_updateFindHighlight(){var C,I;this._disposeHighlights();const e=(C=this._sheetSkeletonManagerService.getCurrent())==null?void 0:C.skeleton;if(!e||!this._getSheetObject()||((I=this._univerInstanceService.getFocusedUniverInstance())==null?void 0:I.getUnitId())!==this._workbook.getUnitId())return;const n=this._workbook.getUnitId(),r=this._renderManagerService.getRenderById(n);if(r==null)return;const{scene:s}=r,o=this._matches,c=this._themeService.getCurrentTheme().gold400,a=new l.ColorKit(c).toRgb(),d=this._workbook.getActiveSheet(),g=d.getSheetId(),v=o.filter(b=>b.range.subUnitId===g).map((b,y)=>{const{startColumn:M,startRow:F,endColumn:O,endRow:de}=b.range.range,ue=k.getCoordByCell(F,M,s,e),ge=k.getCoordByCell(de,O,s,e),{startX:$,startY:L}=ue,{endX:fe,endY:_e}=ge,V=!d.getRowVisible(F),q=!d.getColVisible(M),Se=V||q,me=q?2:fe-$,ve=V?2:_e-L,pe={left:$,top:L,color:a,width:me,height:ve,evented:!1,inHiddenRange:Se};return new Y(`find-highlight-${y}`,pe)});s.addObjects(v,ie),this._highlightShapes=v,s.makeDirty()}_updateCurrentHighlightShape(e){var t;if((t=this._currentHighlightShape)==null||t.setShapeProps({activated:!1}),this._currentHighlightShape=null,e!==void 0){const i=this._highlightShapes[e];if(!i)return;this._currentHighlightShape=i,i.setShapeProps({activated:!0})}}_getSheetObject(){return k.getSheetObject(this._univerInstanceService,this._renderManagerService)}_focusMatch(e){const t=e.range.subUnitId;t!==this._workbook.getActiveSheet().getSheetId()&&this._commandService.syncExecuteCommand(R.SetWorksheetActivateCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:t},{fromFindReplace:!0}),this._commandService.syncExecuteCommand(k.ScrollToCellCommand.id,{range:e.range.range},{fromFindReplace:!0})}_tryRestoreLastMatchesPosition(e,t){if(!e)return 0;const{subUnitId:i}=e.range,{startColumn:n,startRow:r}=e.range.range,s=t.findIndex(o=>{if(i!==o.range.subUnitId)return!1;const{startColumn:c,startRow:a}=o.range.range;return c===n&&a===r});return s>-1?s+1:0}moveToNextMatch(e){var s,o,c;if(!this._matches.length)return null;const t=(s=e==null?void 0:e.loop)!=null?s:!1,i=(o=e==null?void 0:e.stayIfOnMatch)!=null?o:!1,n=(c=e==null?void 0:e.noFocus)!=null?c:!1,r=this._findNextMatch(t,i);if(r){const[a,d]=r;return this._matchesPosition=d+1,this._query.findScope===S.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(a.range.subUnitId).findIndex(g=>g===a):this._activeHighlightIndex=d,n||this._focusMatch(a),this._workbook.getActiveSheet().getSheetId()===a.range.subUnitId&&this._updateCurrentHighlightShape(this._activeHighlightIndex),a}return this._matchesPosition=0,this._updateCurrentHighlightShape(),null}moveToPreviousMatch(e){var s,o,c;if(!this._matches.length)return null;const t=(s=e==null?void 0:e.loop)!=null?s:!1,i=(o=e==null?void 0:e.stayIfOnMatch)!=null?o:!1,n=(c=e==null?void 0:e.noFocus)!=null?c:!1,r=this._findPreviousMatch(t,i);if(r){const[a,d]=r;return this._matchesPosition=d+1,this._query.findScope===S.FindScope.UNIT?this._activeHighlightIndex=this._matchesByWorksheet.get(a.range.subUnitId).findIndex(g=>g===a):this._activeHighlightIndex=d,n||this._focusMatch(a),this._workbook.getActiveSheet().getSheetId()===a.range.subUnitId&&this._updateCurrentHighlightShape(this._activeHighlightIndex),a}return this._matchesPosition=0,this._updateCurrentHighlightShape(),null}_findPreviousMatch(e=!1,t=!1){if(this.currentMatch){const s=this._matches.findIndex(d=>d===this.currentMatch);if(t)return[this.currentMatch,s];const o=s-1;if(!e&&o<0)return null;const c=this._matches.length,a=(o+c)%c;return[this._matches[a],a]}const i=this._selectionManagerService.getSelections();if(!(i!=null&&i.length))return[this._matches[0],0];if(this._query.findScope!==S.FindScope.UNIT)return this._findPreviousMatchByRange(this._matches,i[0].range);const n=this._workbook.getActiveSheet().getSheetId(),r=this._findPreviousWorksheetThatHasAMatch(n,e);return r?this._findPreviousMatchByRange(this._matchesByWorksheet.get(r),i[0].range):null}_findNextMatch(e=!1,t=!1){if(this.currentMatch){const s=this._matches.findIndex(d=>d===this.currentMatch);if(t)return[this.currentMatch,s];const o=s+1,c=this._matches.length;if(!e&&o>=c)return null;const a=o%c;return[this._matches[a],a]}const i=this._selectionManagerService.getSelections();if(!(i!=null&&i.length))return[this._matches[0],0];if(this._query.findScope!==S.FindScope.UNIT)return this._findNextMatchByRange(this._matches,i[0].range,t);const n=this._workbook.getActiveSheet().getSheetId(),r=this._findNextWorksheetThatHasAMatch(n,e);return r?this._findNextMatchByRange(this._matchesByWorksheet.get(r),i[0].range):null}_findPreviousWorksheetThatHasAMatch(e,t=!1){const i=this._workbook.getSheetOrders(),n=i.findIndex(o=>o===e),s=(t?l.rotate(i,n+1):i.slice(0,n+1)).findLast(o=>this._matchesByWorksheet.has(o));return s!=null?s:null}_findNextWorksheetThatHasAMatch(e,t=!1){const i=this._workbook.getSheetOrders(),n=i.findIndex(o=>o===e),s=(t?l.rotate(i,n):i.slice(n)).find(o=>this._matchesByWorksheet.has(o));return s!=null?s:null}_findNextMatchByRange(e,t,i=!1){const n=this._query.findDirection===S.FindDirection.ROW;let r=e.findIndex(o=>{const c=o.range.range;if(!(n?D(t,c):j(t,c)))return!1;const d=E(t,c);return i?d:!d});r===-1&&(r=e.length-1);const s=e[r];return[s,this._matches.findIndex(o=>o===s)]}_findPreviousMatchByRange(e,t,i=!1){const n=this._query.findDirection===S.FindDirection.ROW;let r=this._matches.findLastIndex(o=>{const c=o.range.range;if(!(n?G(t,c):K(t,c)))return!1;const d=E(t,c);return i?d:!d});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,i=this._workbook.getSheetBySheetId(this.currentMatch.range.subUnitId),n=this._getReplacedCellData(this.currentMatch,i,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]:n}}};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:i,caseSensitive:n,findBy:r}=this._query,s=r===S.FindBy.FORMULA,o=n?"g":"ig",c=[];return l.groupBy(this._matches.filter(d=>d.replaceable),d=>d.range.subUnitId).forEach((d,g)=>{const v=new l.ObjectMatrix,C=this._workbook.getSheetBySheetId(g);d.forEach(I=>{const{startColumn:b,startRow:y}=I.range.range,M=this._getReplacedCellData(I,C,s,i,e,o);M&&v.setValue(y,b,M)}),c.push({count:d.length,subUnitId:g,value:v.getMatrix()})}),c?this._commandService.executeCommand(A.id,{unitId:t,replacements:c}):{success:0,failure:0}}_getReplacedCellData(e,t,i,n,r,s){var C;const o=e.range.range,{startRow:c,startColumn:a}=o,d=t.getCellRaw(c,a);if(e.isFormula)return i?{f:d.f.replace(new RegExp(N(n),s),r),v:null}:null;if(!!((C=d.p)!=null&&C.body)){const I=l.Tools.deepClone(d.p);return l.replaceInDocumentBody(I.body,n,r),{p:I}}return{v:d.v.toString().replace(new RegExp(N(n),s),r)}}};B=P([p(1,l.IUniverInstanceService),p(2,x.IRenderManagerService),p(3,l.ICommandService),p(4,l.IContextService),p(5,m.Inject(l.ThemeService)),p(6,m.Inject(k.SheetSkeletonManagerService)),p(7,m.Inject(R.SelectionManagerService))],B);function N(h){return h.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}let W=class extends l.Disposable{constructor(e,t){super();_(this,"_findModelsByUnitId",new Map);this._univerInstanceService=e,this._injector=t}async find(e){this._terminate();const t=this._univerInstanceService.getCurrentUniverSheetInstance();if(t){const i=this._injector.createInstance(B,t);this._findModelsByUnitId.set(t.getUnitId(),i);const n=this._preprocessQuery(e);return i.start(n),[i]}return[]}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}}};W=P([p(0,l.IUniverInstanceService),p(1,m.Inject(m.Injector))],W);const f={hit:!1,replaceable:!1,isFormula:!1,rawData:null};function ne(h,e,t,i,n){const{findBy:r}=i,s=r===S.FindBy.FORMULA,o=h.getCellRaw(e,t);return f.rawData=o,!(o!=null&&o.f)?(f.isFormula=!1,H(n,i)?o?(f.hit=!0,f.replaceable=!0):(f.hit=!0,f.replaceable=!1):(f.hit=!1,f.replaceable=!1),f):(f.isFormula=!0,s?H({v:o.f},i)?(f.hit=!0,f.replaceable=!0,f):(f.hit=!1,f.replaceable=!1,f):(f.replaceable=!1,H(n,i)?f.hit=!0:f.hit=!1,f))}function H(h,e){let t=se(h);return t?e.matchesTheWholeCell?(t=re(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 se(h){var t,i,n;const e=(n=(i=(t=h==null?void 0:h.p)==null?void 0:t.body)==null?void 0:i.dataStream)!=null?n:h==null?void 0:h.v;return typeof e=="number"?`${e}`:typeof e=="boolean"?e?"1":"0":e}function re(h){return h.replace(/^ +/g,"").replace(/ +$/g,"")}var oe=Object.defineProperty,he=Object.getOwnPropertyDescriptor,ce=(h,e,t,i)=>{for(var n=i>1?void 0:i?he(e,t):e,r=h.length-1,s;r>=0;r--)(s=h[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&oe(e,t,n),n},ae=(h,e)=>(t,i)=>e(t,i,h);const le="UNIVER_SHEETS_FIND_REPLACE_PLUGIN";u.UniverSheetsFindReplacePlugin=(T=class extends l.Plugin{constructor(e,t){super(le),this._injector=t}onStarting(e){[[U]].forEach(t=>{e.add(t)})}},_(T,"type",l.PluginType.Sheet),T),u.UniverSheetsFindReplacePlugin=ce([ae(1,m.Inject(m.Injector))],u.UniverSheetsFindReplacePlugin),u.enUS=Q,u.zhCN=X,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,82 @@
1
+ {
2
+ "name": "@univerjs/sheets-find-replace",
3
+ "version": "0.1.3",
4
+ "private": false,
5
+ "description": "UniverSheet find replace plugin",
6
+ "author": "DreamNum <developer@univer.ai>",
7
+ "license": "Apache-2.0",
8
+ "funding": {
9
+ "type": "opencollective",
10
+ "url": "https://opencollective.com/univer"
11
+ },
12
+ "homepage": "https://univer.ai",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/dream-num/univer"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/dream-num/univer/issues"
19
+ },
20
+ "keywords": [],
21
+ "exports": {
22
+ ".": {
23
+ "import": "./lib/es/index.js",
24
+ "require": "./lib/cjs/index.js",
25
+ "types": "./lib/types/index.d.ts"
26
+ },
27
+ "./*": {
28
+ "import": "./lib/es/*",
29
+ "require": "./lib/cjs/*",
30
+ "types": "./lib/types/index.d.ts"
31
+ },
32
+ "./lib/*": "./lib/*"
33
+ },
34
+ "main": "./lib/cjs/index.js",
35
+ "module": "./lib/es/index.js",
36
+ "types": "./lib/types/index.d.ts",
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "directories": {
41
+ "lib": "lib"
42
+ },
43
+ "files": [
44
+ "lib"
45
+ ],
46
+ "engines": {
47
+ "node": ">=16.0.0",
48
+ "npm": ">=8.0.0"
49
+ },
50
+ "peerDependencies": {
51
+ "@wendellhu/redi": "0.13.0",
52
+ "rxjs": ">=7.0.0",
53
+ "@univerjs/engine-render": "0.1.3",
54
+ "@univerjs/core": "0.1.3",
55
+ "@univerjs/find-replace": "0.1.3",
56
+ "@univerjs/sheets": "0.1.3",
57
+ "@univerjs/sheets-ui": "0.1.3"
58
+ },
59
+ "devDependencies": {
60
+ "@wendellhu/redi": "^0.13.0",
61
+ "less": "^4.2.0",
62
+ "react": "^18.2.0",
63
+ "rxjs": "^7.8.1",
64
+ "typescript": "^5.4.2",
65
+ "vite": "^5.1.6",
66
+ "vitest": "^1.3.1",
67
+ "@univerjs/core": "0.1.3",
68
+ "@univerjs/engine-formula": "0.1.3",
69
+ "@univerjs/engine-render": "0.1.3",
70
+ "@univerjs/find-replace": "0.1.3",
71
+ "@univerjs/shared": "0.1.3",
72
+ "@univerjs/sheets-ui": "0.1.3",
73
+ "@univerjs/sheets": "0.1.3"
74
+ },
75
+ "scripts": {
76
+ "test": "vitest run",
77
+ "test:watch": "vitest",
78
+ "coverage": "vitest run --coverage",
79
+ "lint:types": "tsc --noEmit",
80
+ "build": "tsc && vite build"
81
+ }
82
+ }