@univerjs/sheets-find-replace 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "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);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),findReplace=require("@univerjs/find-replace"),sheets=require("@univerjs/sheets"),engineRender=require("@univerjs/engine-render"),sheetsUi=require("@univerjs/sheets-ui"),rxjs=require("rxjs"),_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"),_a;exports.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);exports.SheetsFindReplaceController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Steady,exports.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)],exports.SheetsFindReplaceController);const SHEETS_FIND_REPLACE_PROVIDER_NAME="sheets-find-replace-provider",FIND_REPLACE_Z_INDEX=1e4;var _a2;let SheetFindModel=(_a2=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)).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 _a5;const currentWorksheet=this._workbook.getActiveSheet();if(!currentWorksheet)return!1;const currentSelections=this._workbookSelections.getCurrentSelections();return(_a5=currentSelections==null?void 0:currentSelections.some(selection=>!isSelectionSingleCell(selection,currentWorksheet)))!=null?_a5:!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 _a5;this._highlightShapes.forEach(shape=>{var _a6;(_a6=shape.getScene())==null||_a6.makeDirty(),shape.dispose()}),this._highlightShapes=[],(_a5=this._currentHighlightShape)==null||_a5.dispose(),this._currentHighlightShape=null}_updateFindHighlight(){var _a5;this._disposeHighlights();const skeleton=(_a5=this._sheetSkeletonManagerService.getCurrent())==null?void 0:_a5.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 _a5;if((_a5=this._currentHighlightShape)==null||_a5.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 _a5;const subUnitId=match.range.subUnitId;subUnitId!==((_a5=this._workbook.getActiveSheet())==null?void 0:_a5.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 _a5,_b,_c,_d,_e;if(!this._matches.length)return null;const loop=(_a5=params==null?void 0:params.loop)!=null?_a5:!1,stayIfOnMatch=(_b=params==null?void 0:params.stayIfOnMatch)!=null?_b:!1,noFocus=(_c=params==null?void 0:params.noFocus)!=null?_c:!1,ignoreSelection=(_d=params==null?void 0:params.ignoreSelection)!=null?_d:!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 _a5,_b,_c,_d,_e;if(!this._matches.length)return null;const loop=(_a5=params==null?void 0:params.loop)!=null?_a5:!1,stayIfOnMatch=(_b=params==null?void 0:params.stayIfOnMatch)!=null?_b:!1,noFocus=(_c=params==null?void 0:params.noFocus)!=null?_c:!1,ignoreSelection=(_d=params==null?void 0:params.ignoreSelection)!=null?_d:!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 _a5;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=(_a5=this._workbook.getActiveSheet())==null?void 0:_a5.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 _a5;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=(_a5=this._workbook.getActiveSheet())==null?void 0:_a5.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 _a5;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(!!((_a5=currentContent.p)!=null&&_a5.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(_a2,"SheetFindModel"),_a2);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");var _a3;let SheetsFindReplaceProvider=(_a3=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(_a3,"SheetsFindReplaceProvider"),_a3);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 _a5,_b,_c;const rawValue=(_c=(_b=(_a5=cell==null?void 0:cell.p)==null?void 0:_a5.body)==null?void 0:_b.dataStream)!=null?_c: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";var _a4;exports.UniverSheetsFindReplacePlugin=(_a4=class extends core.Plugin{constructor(_config,_injector){super(),this._injector=_injector}onStarting(){[[exports.SheetsFindReplaceController]].forEach(d=>this._injector.add(d))}},__name(_a4,"UniverSheetsFindReplacePlugin"),_a4);__publicField2(exports.UniverSheetsFindReplacePlugin,"pluginName",NAME);__publicField2(exports.UniverSheetsFindReplacePlugin,"type",core.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFindReplacePlugin=__decorateClass([core.DependentOn(sheets.UniverSheetsPlugin,sheets.UniverSheetsPlugin,findReplace.UniverFindReplacePlugin),__decorateParam(1,core.Inject(core.Injector))],exports.UniverSheetsFindReplacePlugin);exports.SheetReplaceCommand=SheetReplaceCommand;
1
+ "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);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),findReplace=require("@univerjs/find-replace"),sheets=require("@univerjs/sheets"),engineRender=require("@univerjs/engine-render"),sheetsUi=require("@univerjs/sheets-ui"),rxjs=require("rxjs"),_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"),_a;exports.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);exports.SheetsFindReplaceController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Steady,exports.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)],exports.SheetsFindReplaceController);const SHEETS_FIND_REPLACE_PROVIDER_NAME="sheets-find-replace-provider",FIND_REPLACE_Z_INDEX=1e4;var _a2;let SheetFindModel=(_a2=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)).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 _a5;const currentWorksheet=this._workbook.getActiveSheet();if(!currentWorksheet)return!1;const currentSelections=this._workbookSelections.getCurrentSelections();return(_a5=currentSelections==null?void 0:currentSelections.some(selection=>!isSelectionSingleCell(selection,currentWorksheet)))!=null?_a5:!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 _a5;this._highlightShapes.forEach(shape=>{var _a6;(_a6=shape.getScene())==null||_a6.makeDirty(),shape.dispose()}),this._highlightShapes=[],(_a5=this._currentHighlightShape)==null||_a5.dispose(),this._currentHighlightShape=null}_updateFindHighlight(){var _a5;this._disposeHighlights();const skeleton=(_a5=this._sheetSkeletonManagerService.getCurrent())==null?void 0:_a5.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 _a5;if((_a5=this._currentHighlightShape)==null||_a5.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 _a5;const subUnitId=match.range.subUnitId;subUnitId!==((_a5=this._workbook.getActiveSheet())==null?void 0:_a5.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 _a5,_b,_c,_d,_e;if(!this._matches.length)return null;const loop=(_a5=params==null?void 0:params.loop)!=null?_a5:!1,stayIfOnMatch=(_b=params==null?void 0:params.stayIfOnMatch)!=null?_b:!1,noFocus=(_c=params==null?void 0:params.noFocus)!=null?_c:!1,ignoreSelection=(_d=params==null?void 0:params.ignoreSelection)!=null?_d:!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 _a5,_b,_c,_d,_e;if(!this._matches.length)return null;const loop=(_a5=params==null?void 0:params.loop)!=null?_a5:!1,stayIfOnMatch=(_b=params==null?void 0:params.stayIfOnMatch)!=null?_b:!1,noFocus=(_c=params==null?void 0:params.noFocus)!=null?_c:!1,ignoreSelection=(_d=params==null?void 0:params.ignoreSelection)!=null?_d:!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 _a5;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=(_a5=this._workbook.getActiveSheet())==null?void 0:_a5.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 _a5;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=(_a5=this._workbook.getActiveSheet())==null?void 0:_a5.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 _a5;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(!!((_a5=currentContent.p)!=null&&_a5.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(_a2,"SheetFindModel"),_a2);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");var _a3;let SheetsFindReplaceProvider=(_a3=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(_a3,"SheetsFindReplaceProvider"),_a3);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 _a5,_b,_c;const rawValue=(_c=(_b=(_a5=cell==null?void 0:cell.p)==null?void 0:_a5.body)==null?void 0:_b.dataStream)!=null?_c: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");const PLUGIN_CONFIG_KEY="sheets-find-replace.config",defaultPluginConfig={};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";var _a4;exports.UniverSheetsFindReplacePlugin=(_a4=class extends core.Plugin{constructor(_config=defaultPluginConfig,_injector,_configService){super(),this._config=_config,this._injector=_injector,this._configService=_configService;const{...rest}=this._config;this._configService.setConfig(PLUGIN_CONFIG_KEY,rest)}onStarting(){[[exports.SheetsFindReplaceController]].forEach(d=>this._injector.add(d))}},__name(_a4,"UniverSheetsFindReplacePlugin"),_a4);__publicField2(exports.UniverSheetsFindReplacePlugin,"pluginName",NAME);__publicField2(exports.UniverSheetsFindReplacePlugin,"type",core.UniverInstanceType.UNIVER_SHEET);exports.UniverSheetsFindReplacePlugin=__decorateClass([core.DependentOn(sheets.UniverSheetsPlugin,sheets.UniverSheetsPlugin,findReplace.UniverFindReplacePlugin),__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,core.IConfigService)],exports.UniverSheetsFindReplacePlugin);exports.SheetReplaceCommand=SheetReplaceCommand;
package/lib/es/index.js CHANGED
@@ -2,7 +2,7 @@ var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
3
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
5
- import { CommandType, IUndoRedoService, ICommandService, Rectangle, OnLifecycle, LifecycleStages, Inject, Injector, ThemeService, Disposable, EDITOR_ACTIVATED, IContextService, IUniverInstanceService, UniverInstanceType, fromCallback, ColorKit, rotate, groupBy, ObjectMatrix, Tools, replaceInDocumentBody, DependentOn, Plugin } from "@univerjs/core";
5
+ import { CommandType, IUndoRedoService, ICommandService, Rectangle, OnLifecycle, LifecycleStages, Inject, Injector, ThemeService, Disposable, EDITOR_ACTIVATED, IContextService, IUniverInstanceService, UniverInstanceType, fromCallback, ColorKit, rotate, groupBy, ObjectMatrix, Tools, replaceInDocumentBody, DependentOn, Plugin, IConfigService } from "@univerjs/core";
6
6
  import { FindReplaceController, IFindReplaceService, FindModel, FindBy, FindScope, FindDirection, UniverFindReplacePlugin } from "@univerjs/find-replace";
7
7
  import { SetRangeValuesCommand, SheetsSelectionsService, SetWorksheetActiveOperation, SetSelectionsOperation, SetWorksheetActivateCommand, UniverSheetsPlugin } from "@univerjs/sheets";
8
8
  import { Shape, Rect, IRenderManagerService, RENDER_RAW_FORMULA_KEY } from "@univerjs/engine-render";
@@ -599,6 +599,7 @@ function trimLeadingTrailingWhitespace(value) {
599
599
  return value.replace(/^ +/g, "").replace(/ +$/g, "");
600
600
  }
601
601
  __name(trimLeadingTrailingWhitespace, "trimLeadingTrailingWhitespace");
602
+ const PLUGIN_CONFIG_KEY = "sheets-find-replace.config", defaultPluginConfig = {};
602
603
  var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __defNormalProp2 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, "__defNormalProp"), __decorateClass = /* @__PURE__ */ __name((decorators, target, key, kind) => {
603
604
  for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
604
605
  (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
@@ -607,8 +608,10 @@ var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnProperty
607
608
  const NAME = "SHEET_FIND_REPLACE_PLUGIN";
608
609
  var _a4;
609
610
  let UniverSheetsFindReplacePlugin = (_a4 = class extends Plugin {
610
- constructor(_config, _injector) {
611
- super(), this._injector = _injector;
611
+ constructor(_config = defaultPluginConfig, _injector, _configService) {
612
+ super(), this._config = _config, this._injector = _injector, this._configService = _configService;
613
+ const { ...rest } = this._config;
614
+ this._configService.setConfig(PLUGIN_CONFIG_KEY, rest);
612
615
  }
613
616
  onStarting() {
614
617
  [[SheetsFindReplaceController]].forEach((d) => this._injector.add(d));
@@ -618,7 +621,8 @@ __publicField2(UniverSheetsFindReplacePlugin, "pluginName", NAME);
618
621
  __publicField2(UniverSheetsFindReplacePlugin, "type", UniverInstanceType.UNIVER_SHEET);
619
622
  UniverSheetsFindReplacePlugin = __decorateClass([
620
623
  DependentOn(UniverSheetsPlugin, UniverSheetsPlugin, UniverFindReplacePlugin),
621
- __decorateParam(1, Inject(Injector))
624
+ __decorateParam(1, Inject(Injector)),
625
+ __decorateParam(2, IConfigService)
622
626
  ], UniverSheetsFindReplacePlugin);
623
627
  export {
624
628
  SheetReplaceCommand,
@@ -0,0 +1,20 @@
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 declare const PLUGIN_CONFIG_KEY = "sheets-find-replace.config";
17
+ export declare const configSymbol: unique symbol;
18
+ export interface IUniverSheetsFindReplaceConfig {
19
+ }
20
+ export declare const defaultPluginConfig: IUniverSheetsFindReplaceConfig;
@@ -1,8 +1,11 @@
1
- import { Injector, Plugin, UniverInstanceType } from '@univerjs/core';
1
+ import { IConfigService, Injector, Plugin, UniverInstanceType } from '@univerjs/core';
2
+ import { IUniverSheetsFindReplaceConfig } from './controllers/config.schema';
2
3
  export declare class UniverSheetsFindReplacePlugin extends Plugin {
4
+ private readonly _config;
3
5
  protected readonly _injector: Injector;
6
+ private readonly _configService;
4
7
  static pluginName: string;
5
8
  static type: UniverInstanceType;
6
- constructor(_config: unknown, _injector: Injector);
9
+ constructor(_config: Partial<IUniverSheetsFindReplaceConfig> | undefined, _injector: Injector, _configService: IConfigService);
7
10
  onStarting(): void;
8
11
  }
package/lib/umd/index.js CHANGED
@@ -1 +1 @@
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)).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=>{var _a3;(_a3=shape.getScene())==null||_a3.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"})});
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)).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=>{var _a3;(_a3=shape.getScene())==null||_a3.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");const PLUGIN_CONFIG_KEY="sheets-find-replace.config",defaultPluginConfig={};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=defaultPluginConfig,_injector,_configService){super(),this._config=_config,this._injector=_injector,this._configService=_configService;const{...rest}=this._config;this._configService.setConfig(PLUGIN_CONFIG_KEY,rest)}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)),__decorateParam(2,core.IConfigService)],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.11",
3
+ "version": "0.2.13",
4
4
  "private": false,
5
5
  "description": "UniverSheet find replace plugin",
6
6
  "author": "DreamNum <developer@univer.ai>",
@@ -48,27 +48,27 @@
48
48
  ],
49
49
  "peerDependencies": {
50
50
  "rxjs": ">=7.0.0",
51
- "@univerjs/engine-render": "0.2.11",
52
- "@univerjs/core": "0.2.11",
53
- "@univerjs/find-replace": "0.2.11",
54
- "@univerjs/sheets": "0.2.11",
55
- "@univerjs/sheets-ui": "0.2.11"
51
+ "@univerjs/core": "0.2.13",
52
+ "@univerjs/find-replace": "0.2.13",
53
+ "@univerjs/engine-render": "0.2.13",
54
+ "@univerjs/sheets": "0.2.13",
55
+ "@univerjs/sheets-ui": "0.2.13"
56
56
  },
57
57
  "dependencies": {
58
- "@univerjs/protocol": "0.1.39-alpha.15"
58
+ "@univerjs/protocol": "0.1.39-alpha.15",
59
+ "@univerjs/engine-formula": "0.2.13",
60
+ "@univerjs/core": "0.2.13",
61
+ "@univerjs/engine-render": "0.2.13",
62
+ "@univerjs/sheets": "0.2.13",
63
+ "@univerjs/sheets-ui": "0.2.13",
64
+ "@univerjs/find-replace": "0.2.13"
59
65
  },
60
66
  "devDependencies": {
61
67
  "rxjs": "^7.8.1",
62
- "typescript": "^5.5.4",
63
- "vite": "^5.4.2",
68
+ "typescript": "^5.6.2",
69
+ "vite": "^5.4.4",
64
70
  "vitest": "^2.0.5",
65
- "@univerjs/core": "0.2.11",
66
- "@univerjs/engine-render": "0.2.11",
67
- "@univerjs/engine-formula": "0.2.11",
68
- "@univerjs/find-replace": "0.2.11",
69
- "@univerjs/sheets": "0.2.11",
70
- "@univerjs/shared": "0.2.11",
71
- "@univerjs/sheets-ui": "0.2.11"
71
+ "@univerjs-infra/shared": "0.2.13"
72
72
  },
73
73
  "univerSpace": {
74
74
  ".": {