@univerjs/sheets-data-validation 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/es/index.js CHANGED
@@ -1 +1,3258 @@
1
- import{CellValueType as e,CommandType as t,DataValidationOperator as n,DataValidationRenderMode as r,DataValidationStatus as i,DataValidationType as a,DependentOn as o,Disposable as s,ICommandService as c,IConfigService as l,IPermissionService as u,IUndoRedoService as d,IUniverInstanceService as f,Inject as p,Injector as m,LifecycleService as h,LifecycleStages as g,ObjectMatrix as ee,Plugin as te,RBush as ne,Range as _,Rectangle as v,RxDisposable as re,Tools as y,UniverInstanceType as b,WrapStrategy as ie,bufferDebounceTime as ae,dateKit as oe,debounce as se,generateRandomId as ce,getIntersectRange as le,getOriginCellValue as ue,isFormulaString as x,isRangesEqual as de,merge as fe,numfmt as S,sequenceExecute as pe,toDisposable as me}from"@univerjs/core";import{AddDataValidationMutation as C,BaseDataValidator as w,DataValidationModel as T,DataValidatorRegistryService as E,RemoveDataValidationMutation as D,TextLengthErrorTitleMap as he,UniverDataValidationPlugin as ge,UpdateDataValidationMutation as O,UpdateRuleType as k,getRuleOptions as _e,getRuleSetting as ve}from"@univerjs/data-validation";import{ERROR_TYPE_SET as ye,LexerTreeBuilder as A,OtherFormulaBizType as be,RegisterOtherFormulaService as xe,deserializeRangeWithSheet as Se,deserializeRangeWithSheetWithCache as Ce,isReferenceString as we,operatorToken as Te,sequenceNodeType as Ee}from"@univerjs/engine-formula";import{ClearSelectionAllCommand as De,CopySheetCommand as Oe,RefRangeService as ke,RemoveSheetCommand as Ae,RemoveSheetMutation as je,SetRangeValuesMutation as j,SetRangeValuesUndoMutationFactory as Me,SheetInterceptorService as Ne,SheetsSelectionsService as Pe,WorksheetViewPermission as Fe,getSheetCommandTarget as Ie,handleCommonDefaultRangeChangeWithEffectRefCommands as Le}from"@univerjs/sheets";import{Subject as Re,bufferWhen as ze,filter as Be}from"rxjs";import{UnitAction as Ve}from"@univerjs/protocol";import{FormulaRefRangeService as He,UniverSheetsFormulaPlugin as Ue}from"@univerjs/sheets-formula";function M(e){"@babel/helpers - typeof";return M=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},M(e)}function We(e,t){if(M(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(M(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ge(e){var t=We(e,`string`);return M(t)==`symbol`?t:t+``}function N(e,t,n){return(t=Ge(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function P(e,t){return function(n,r){t(n,r,e)}}function F(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let I=class extends s{constructor(e,t,n){super(),this._commandService=e,this._univerInstanceService=t,this._sheetDataValidationModel=n,N(this,`_cacheMatrix`,new Map),N(this,`_dirtyRanges$`,new Re),N(this,`dirtyRanges$`,this._dirtyRanges$.asObservable()),this._initDirtyRanges(),this._initSheetRemove()}_initDirtyRanges(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{if(e.id===j.id&&!(t!=null&&t.onlyLocal)){let{cellValue:t,unitId:n,subUnitId:r}=e.params;if(t){let e=new ee(t).getDataRange();if(e.endRow===-1)return;let i=this._sheetDataValidationModel.getRules(n,r).map(e=>e.ranges).flat().map(t=>le(t,e)).filter(Boolean);i.length&&this.markRangeDirty(n,r,i,!0)}}}))}_initSheetRemove(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===je.id){var t;let{unitId:n,subUnitId:r}=e.params;(t=this._cacheMatrix.get(n))==null||t.delete(r)}})),this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(e=>{e.type===b.UNIVER_SHEET&&this._cacheMatrix.delete(e.getUnitId())}))}_ensureCache(e,t){let n=this._cacheMatrix.get(e);n||(n=new Map,this._cacheMatrix.set(e,n));let r=n.get(t);return r||(r=new ee,n.set(t,r)),r}ensureCache(e,t){return this._ensureCache(e,t)}addRule(e,t,n){this.markRangeDirty(e,t,n.ranges)}removeRule(e,t,n){this._deleteRange(e,t,n.ranges)}markRangeDirty(e,t,n,r){let i=this._ensureCache(e,t);n.forEach(e=>{_.foreach(e,(e,t)=>{i.getValue(e,t)!==void 0&&i.setValue(e,t,void 0)})}),this._dirtyRanges$.next({unitId:e,subUnitId:t,ranges:n,isSetRange:r})}_deleteRange(e,t,n){let r=this._ensureCache(e,t);n.forEach(e=>{_.foreach(e,(e,t)=>{r.realDeleteValue(e,t)})}),this._dirtyRanges$.next({unitId:e,subUnitId:t,ranges:n})}getValue(e,t,n,r){return this._ensureCache(e,t).getValue(n,r)}};I=F([P(0,p(c)),P(1,p(f)),P(2,p(T))],I);function L(e){var t;return e==null||(t=e[0])==null||(t=t[0])==null?void 0:t.v}function R(e){var t;return e==null||(t=e[0])==null?void 0:t[0]}function z(e){return!ye.has(e)}function B(e,t){var n;let r=t.getValidatorItem(e);return(n=r==null?void 0:r.offsetFormulaByRange)==null?!1:n}let V=class extends s{constructor(e,t,n,r,i){super(),this._instanceSrv=e,this._registerOtherFormulaService=t,this._dataValidationModel=n,this._dataValidationCacheService=r,this._validatorRegistryService=i,N(this,`_ruleFormulaMap`,new Map),N(this,`_ruleFormulaMap2`,new Map),this._initFormulaResultHandler(),this._initDirtyRanges()}dispose(){super.dispose(),this._ruleFormulaMap.clear(),this._ruleFormulaMap2.clear()}_initFormulaResultHandler(){this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe(e=>{for(let t in e){let n=e[t];if(this._instanceSrv.getUnitType(t)===b.UNIVER_SHEET)for(let e in n){let r=n[e],{ruleFormulaMap:i}=this._ensureMaps(t,e);r.forEach(n=>{var r,a;let o=i.get((r=n.extra)==null?void 0:r.ruleId),s=this._dataValidationModel.getRuleById(t,e,(a=n.extra)==null?void 0:a.ruleId);s&&o&&this._dataValidationCacheService.markRangeDirty(t,e,s.ranges)})}}}))}_ensureMaps(e,t){let n=this._ruleFormulaMap.get(e),r=this._ruleFormulaMap2.get(e);n||(n=new Map,this._ruleFormulaMap.set(e,n)),r||(r=new Map,this._ruleFormulaMap2.set(e,r));let i=n.get(t);i||(i=new Map,n.set(t,i));let a=r.get(t);return a||(a=new Map,r.set(t,a)),{ruleFormulaMap:i,ruleFormulaMap2:a}}_registerFormula(e,t,n,r,i){return this._registerOtherFormulaService.registerFormulaWithRange(e,t,r,i,{ruleId:n},be.DATA_VALIDATION_CUSTOM,n)}_handleDirtyRanges(e,t,n){this._dataValidationModel.getRules(e,t).forEach(r=>{let i=r.ranges;v.doAnyRangesIntersect(i,n)&&this.makeRuleDirty(e,t,r.uid)})}_initDirtyRanges(){this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.subscribe(e=>{e.isSetRange&&this._handleDirtyRanges(e.unitId,e.subUnitId,e.ranges)}))}deleteByRuleId(e,t,n){let{ruleFormulaMap:r,ruleFormulaMap2:i}=this._ensureMaps(e,t),a=this._dataValidationModel.getRuleById(e,t,n),o=r.get(n);if(!a||!o)return;let s=r.get(n);s&&(r.delete(n),this._registerOtherFormulaService.deleteFormula(e,t,[s.formulaId]));let c=i.get(n);c&&(i.delete(n),this._registerOtherFormulaService.deleteFormula(e,t,[c.formulaId]))}_addFormulaByRange(e,t,n,r,i,a){let{ruleFormulaMap:o,ruleFormulaMap2:s}=this._ensureMaps(e,t),c=a[0].startRow,l=a[0].startColumn;if(r&&x(r)){let i=this._registerFormula(e,t,n,r,a);o.set(n,{formula:r,originCol:l,originRow:c,formulaId:i})}if(i&&x(i)){let r=this._registerFormula(e,t,n,i,a);s.set(n,{formula:i,originCol:l,originRow:c,formulaId:r})}}addRule(e,t,n){if(B(n.type,this._validatorRegistryService)){let{ranges:r,formula1:i,formula2:a,uid:o}=n;this._addFormulaByRange(e,t,o,i,a,r)}}async getCellFormulaValue(e,t,n,r,i){var a;let{ruleFormulaMap:o}=this._ensureMaps(e,t),s=o.get(n);if(!s)return Promise.resolve(void 0);let c=await this._registerOtherFormulaService.getFormulaValue(e,t,s.formulaId),{originRow:l,originCol:u}=s,d=r-l,f=i-u;return R(c==null||(a=c.result)==null||(a=a[d])==null?void 0:a[f])}async getCellFormula2Value(e,t,n,r,i){var a;let{ruleFormulaMap2:o}=this._ensureMaps(e,t),s=o.get(n);if(!s)return Promise.resolve(void 0);let c=await this._registerOtherFormulaService.getFormulaValue(e,t,s.formulaId),{originRow:l,originCol:u}=s,d=r-l,f=i-u;return R(c==null||(a=c.result)==null||(a=a[d])==null?void 0:a[f])}getCellFormulaValueSync(e,t,n,r,i){var a;let{ruleFormulaMap:o}=this._ensureMaps(e,t),s=o.get(n);if(!s)return;let c=this._registerOtherFormulaService.getFormulaValueSync(e,t,s.formulaId),{originRow:l,originCol:u}=s,d=r-l,f=i-u;return R(c==null||(a=c.result)==null||(a=a[d])==null?void 0:a[f])}getCellFormula2ValueSync(e,t,n,r,i){var a;let{ruleFormulaMap2:o}=this._ensureMaps(e,t),s=o.get(n);if(!s)return;let c=this._registerOtherFormulaService.getFormulaValueSync(e,t,s.formulaId),{originRow:l,originCol:u}=s,d=r-l,f=i-u;return R(c==null||(a=c.result)==null||(a=a[d])==null?void 0:a[f])}getRuleFormulaInfo(e,t,n){let{ruleFormulaMap:r}=this._ensureMaps(e,t);return r.get(n)}makeRuleDirty(e,t,n){var r,i;let a=(r=this._ruleFormulaMap.get(e))==null||(r=r.get(t))==null?void 0:r.get(n),o=(i=this._ruleFormulaMap2.get(e))==null||(i=i.get(t))==null?void 0:i.get(n);a&&this._registerOtherFormulaService.markFormulaDirty(e,t,a.formulaId),o&&this._registerOtherFormulaService.markFormulaDirty(e,t,o.formulaId)}};V=F([P(0,f),P(1,p(xe)),P(2,p(T)),P(3,p(I)),P(4,p(E))],V);function H(e){return ue(e)}function Ke(e){var t;return String((t=H(e))==null?``:t)}function qe(e){return e.filter(Boolean).join(`,`)}function U(e){return e.split(`,`).filter(Boolean)}function Je(e){let t=H(e);return t==null?``:t.toString()}function W(e,t,n){let{formula1:r,formula2:i}=t,a=t.ranges[0].startRow,o=t.ranges[0].startColumn,s=n.row-a,c=n.col-o;return{transformedFormula1:x(r)?e.moveFormulaRefOffset(r,c,s,!0):r,transformedFormula2:x(i)?e.moveFormulaRefOffset(i,c,s,!0):i}}let G=class extends s{constructor(e,t){super(),this._injector=e,this._dataValidationModel=t,N(this,`_cache`,new Map),this._initRuleChangeListener()}_initRuleChangeListener(){this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{(e.type===`remove`||e.type===`update`)&&this.markRuleDirty(e.unitId,e.subUnitId,e.rule.uid)}))}getOrCompute(e,t,n){let r=this.getCache(e,t,n.uid);if(r)return r;let i=this._injector.get(K).getRuleFormulaResultSync(e,t,n.uid);return this.computeAndCache(e,t,n,i)}_ensureCache(e,t){let n=this._cache.get(e);n||(n=new Map,this._cache.set(e,n));let r=n.get(t);return r||(r=new Map,n.set(t,r)),r}getCache(e,t,n){var r;return(r=this._cache.get(e))==null||(r=r.get(t))==null?void 0:r.get(n)}setCache(e,t,n,r){this._ensureCache(e,t).set(n,r)}markRuleDirty(e,t,n){var r;(r=this._cache.get(e))==null||(r=r.get(t))==null||r.delete(n)}clear(){this._cache.clear()}computeAndCache(e,t,n,r){var i;let{formula1:a=``,formula2:o=``}=n,s=x(a)?this._getRuleFormulaResultSet(r==null||(i=r[0])==null||(i=i.result)==null||(i=i[0])==null?void 0:i[0]):U(a),c=o.split(`,`),l=s.map((e,t)=>({label:e,color:c[t]||``})),u={};for(let e of l)e.color&&(u[e.label]=e.color);let d={list:s,listWithColor:l,colorMap:u,set:new Set(s)};return this.setCache(e,t,n.uid,d),d}_getRuleFormulaResultSet(e){if(!e)return[];let t=new Set;for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i)for(let e=0,r=i.length;e<r;e++){let r=i[e],a=H(r);if(a!=null){var n;if(typeof a!=`string`&&typeof(r==null?void 0:r.s)==`object`&&!((n=r.s)==null||(n=n.n)==null)&&n.pattern){t.add(S.format(r.s.n.pattern,a,{throws:!1}));continue}let e=typeof a==`string`?a:String(a);z(e)&&t.add(e)}}}return[...t]}};G=F([P(0,p(m)),P(1,p(T))],G);let K=class extends s{constructor(e,t,n,r,i,a){super(),this._instanceService=e,this._registerOtherFormulaService=t,this._dataValidationCacheService=n,this._dataValidationModel=r,this._validatorRegistryService=i,this._listCacheService=a,N(this,`_formulaRuleMap`,new Map),this._initFormulaResultHandler()}_initFormulaResultHandler(){this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe(e=>{for(let t in e){let n=e[t];if(this._instanceService.getUnitType(t)===b.UNIVER_SHEET)for(let e in n){let r=n[e],i=this._ensureRuleFormulaMap(t,e);r.forEach(n=>{var r;let a=(r=n.extra)==null?void 0:r.ruleId;if(a&&i.get(a)){let n=this._dataValidationModel.getRuleById(t,e,a);n&&(this._listCacheService.markRuleDirty(t,e,a),this._dataValidationCacheService.markRangeDirty(t,e,n.ranges))}})}}}))}_ensureRuleFormulaMap(e,t){let n=this._formulaRuleMap.get(e);n||(n=new Map,this._formulaRuleMap.set(e,n));let r=n.get(t);return r||(r=new Map,n.set(t,r)),r}_registerSingleFormula(e,t,n,r){return this._registerOtherFormulaService.registerFormulaWithRange(e,t,n,[{startColumn:0,endColumn:0,startRow:0,endRow:0}],{ruleId:r},be.DATA_VALIDATION,r)}addRule(e,t,n){if(!B(n.type,this._validatorRegistryService)&&n.type!==a.CHECKBOX){let{formula1:r,formula2:i,uid:a}=n,o=x(r),s=x(i);if(!o&&!s)return;let c=this._ensureRuleFormulaMap(e,t),l=[void 0,void 0];o&&(l[0]={id:this._registerSingleFormula(e,t,r,a),text:r}),s&&(l[1]={id:this._registerSingleFormula(e,t,i,a),text:i}),c.set(a,l)}}removeRule(e,t,n){let r=this._ensureRuleFormulaMap(e,t).get(n);if(!r)return;let[i,a]=r,o=[i==null?void 0:i.id,a==null?void 0:a.id].filter(Boolean);o.length&&this._registerOtherFormulaService.deleteFormula(e,t,o)}getRuleFormulaResult(e,t,n){let r=this._ensureRuleFormulaMap(e,t).get(n);if(!r)return Promise.resolve(null);let i=async n=>n&&this._registerOtherFormulaService.getFormulaValue(e,t,n.id);return Promise.all([i(r[0]),i(r[1])])}getRuleFormulaResultSync(e,t,n){let r=this._ensureRuleFormulaMap(e,t).get(n);if(r)return r.map(n=>{if(n)return this._registerOtherFormulaService.getFormulaValueSync(e,t,n.id)})}getRuleFormulaInfo(e,t,n){return this._ensureRuleFormulaMap(e,t).get(n)}};K=F([P(0,f),P(1,p(xe)),P(2,p(I)),P(3,p(T)),P(4,p(E)),P(5,p(G))],K);var Ye=class e{constructor(e,t,n,r,i=!1){this._unitId=t,this._subUnitId=n,this._univerInstanceService=r,this._disableTree=i,N(this,`_map`,void 0),N(this,`_tree`,new ne),N(this,`_dirty`,!0),N(this,`_buildTree`,()=>{if(!this._dirty||this._disableTree)return;this._tree.clear();let e=[];this._map.forEach((t,n)=>{t.forEach(t=>{e.push({minX:t.startRow,maxX:t.endRow,minY:t.startColumn,maxY:t.endColumn,ruleId:n})})}),this._tree.load(e),this._dirty=!1}),N(this,`_debonceBuildTree`,se(this._buildTree,0)),this._map=e,this._buildTree()}get _worksheet(){var e;return(e=this._univerInstanceService.getUnit(this._unitId,b.UNIVER_SHEET))==null?void 0:e.getSheetBySheetId(this._subUnitId)}_addRule(e,t){if(!this._worksheet)return;let n=v.mergeRanges(t.map(e=>_.transformRange(e,this._worksheet)));this._map.forEach((e,t)=>{let r=v.subtractMulti(e,n);r.length===0?this._map.delete(t):this._map.set(t,r)}),this._dirty=!0,this._map.set(e,n),this._debonceBuildTree()}addRule(e){this._addRule(e.uid,e.ranges)}removeRange(e){if(!this._worksheet)return;let t=e.map(e=>_.transformRange(e,this._worksheet));this._map.forEach((e,n)=>{let r=v.subtractMulti(e,t);r.length===0?this._map.delete(n):this._map.set(n,r)}),this._dirty=!0,this._debonceBuildTree()}_removeRule(e){this._map.delete(e),this._dirty=!0,this._debonceBuildTree()}removeRule(e){this._removeRule(e.uid)}updateRange(e,t){this._removeRule(e),this._addRule(e,t)}addRangeRules(e){e.forEach(({id:e,ranges:t})=>{if(!t.length)return;let n=this._map.get(e);n?(this._map.set(e,v.mergeRanges([...n,...t])),n=this._map.get(e)):(n=t,this._map.set(e,n)),this._map.forEach((n,r)=>{if(r===e)return;let i=v.subtractMulti(n,t);i.length===0?this._map.delete(r):this._map.set(r,i)})}),this._dirty=!0,this._debonceBuildTree()}diff(e){let t=[],n=0;return e.forEach((e,r)=>{var i;let a=(i=this._map.get(e.uid))==null?[]:i,o=e.ranges;a.length!==0&&(a.length!==o.length||a.some((e,t)=>!v.equals(e,o[t])))&&t.push({type:`update`,ruleId:e.uid,oldRanges:o,newRanges:v.sort(a),rule:e}),a.length===0&&(t.push({type:`delete`,rule:e,index:r-n}),n++)}),t}diffWithAddition(e,t){let n=[],r=0;return e.forEach((e,t)=>{var i;let a=(i=this._map.get(e.uid))==null?[]:i,o=e.ranges;a.length!==0&&(a.length!==o.length||a.some((e,t)=>!v.equals(e,o[t])))&&n.push({type:`update`,ruleId:e.uid,oldRanges:o,newRanges:v.sort(a),rule:e}),a.length===0&&(n.push({type:`delete`,rule:e,index:t-r}),r++)}),Array.from(t).forEach(e=>{var t;let r=(t=this._map.get(e.uid))==null?[]:t;n.push({type:`add`,rule:{...e,ranges:v.sort(r)}})}),n}clone(){return new e(new Map(y.deepClone(Array.from(this._map.entries()))),this._unitId,this._subUnitId,this._univerInstanceService,!0)}getValue(e,t){this._dirty&&this._buildTree();let n=this._tree.search({minX:e,maxX:e,minY:t,maxY:t});return n.length>0?n[0].ruleId:void 0}};let q=class extends s{constructor(e,t,n,r,i,a,o){super(),this._dataValidationModel=e,this._univerInstanceService=t,this._dataValidatorRegistryService=n,this._dataValidationCacheService=r,this._dataValidationFormulaService=i,this._dataValidationCustomFormulaService=a,this._commandService=o,N(this,`_ruleMatrixMap`,new Map),N(this,`_validStatusChange$`,new Re),N(this,`_ruleChange$`,new Re),N(this,`ruleChange$`,this._ruleChange$.asObservable()),N(this,`validStatusChange$`,this._validStatusChange$.asObservable()),this._initRuleUpdateListener(),this.disposeWithMe(()=>{this._ruleChange$.complete(),this._validStatusChange$.complete()}),this._initUniverInstanceListener()}_initUniverInstanceListener(){this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(e=>{this._ruleMatrixMap.delete(e.getUnitId())})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===je.id){let{unitId:t,subUnitId:n}=e.params,r=this._ruleMatrixMap.get(t);r&&r.delete(n)}}))}_initRuleUpdateListener(){let e=this._dataValidationModel.getAll();for(let[t,n]of e)for(let[e,r]of n)for(let n of r)this._addRule(t,e,n),this._ruleChange$.next({type:`add`,unitId:t,subUnitId:e,rule:n,source:`patched`});this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{switch(e.type){case`add`:this._addRule(e.unitId,e.subUnitId,e.rule);break;case`update`:this._updateRule(e.unitId,e.subUnitId,e.rule.uid,e.oldRule,e.updatePayload);break;case`remove`:this._removeRule(e.unitId,e.subUnitId,e.rule);break}this._ruleChange$.next(e)}))}_ensureRuleMatrix(e,t){let n=this._ruleMatrixMap.get(e);n||(n=new Map,this._ruleMatrixMap.set(e,n));let r=n.get(t);return r||(r=new Ye(new Map,e,t,this._univerInstanceService),n.set(t,r)),r}_addRuleSideEffect(e,t,n){this._ensureRuleMatrix(e,t).addRule(n),this._dataValidationCacheService.addRule(e,t,n),this._dataValidationFormulaService.addRule(e,t,n),this._dataValidationCustomFormulaService.addRule(e,t,n)}_addRule(e,t,n){(Array.isArray(n)?n:[n]).forEach(n=>{this._addRuleSideEffect(e,t,n)})}_updateRule(e,t,n,r,i){let a=this._ensureRuleMatrix(e,t),o={...r,...i.payload};i.type===k.RANGE?a.updateRange(n,i.payload):i.type===k.ALL&&a.updateRange(n,i.payload.ranges),this._dataValidationCacheService.removeRule(e,t,r),this._dataValidationCacheService.addRule(e,t,o),this._dataValidationFormulaService.removeRule(e,t,r.uid),this._dataValidationFormulaService.addRule(e,t,o),this._dataValidationCustomFormulaService.deleteByRuleId(e,t,n),this._dataValidationCustomFormulaService.addRule(e,t,o)}_removeRule(e,t,n){this._ensureRuleMatrix(e,t).removeRule(n),this._dataValidationCacheService.removeRule(e,t,n),this._dataValidationCustomFormulaService.deleteByRuleId(e,t,n.uid)}getValidator(e){return this._dataValidatorRegistryService.getValidatorItem(e)}getRuleIdByLocation(e,t,n,r){return this._ensureRuleMatrix(e,t).getValue(n,r)}getRuleByLocation(e,t,n,r){let i=this.getRuleIdByLocation(e,t,n,r);if(i)return this._dataValidationModel.getRuleById(e,t,i)}validator(e,t,n){let{col:r,row:a,unitId:o,subUnitId:s,worksheet:c}=t,l=(t,i)=>{n&&n(t,i),i&&this._validStatusChange$.next({unitId:o,subUnitId:s,ruleId:e.uid,status:t,row:a,col:r})},u=c.getCellValueOnly(a,r),d=this.getValidator(e.type),f=c.getCellRaw(a,r),p=H(f);if(d){let n=this._dataValidationCacheService.ensureCache(o,s),c=n.getValue(a,r);return c==null?(n.setValue(a,r,i.VALIDATING),d.validator({value:p,unitId:o,subUnitId:s,row:a,column:r,worksheet:t.worksheet,workbook:t.workbook,interceptValue:H(u),t:f==null?void 0:f.t},e).then(e=>{let t=e?i.VALID:i.INVALID,o=n.getValue(a,r);t===i.VALID?n.realDeleteValue(a,r):n.setValue(a,r,t),l(t,c!==o)}),i.VALIDATING):(l(c==null?i.VALID:c,!1),c==null?i.VALID:c)}else return l(i.VALID,!1),i.VALID}getRuleObjectMatrix(e,t){return this._ensureRuleMatrix(e,t)}getRuleById(e,t,n){return this._dataValidationModel.getRuleById(e,t,n)}getRuleIndex(e,t,n){return this._dataValidationModel.getRuleIndex(e,t,n)}getRules(e,t){return[...this._dataValidationModel.getRules(e,t)]}getUnitRules(e){return this._dataValidationModel.getUnitRules(e)}deleteUnitRules(e){return this._dataValidationModel.deleteUnitRules(e)}getSubUnitIds(e){return this._dataValidationModel.getSubUnitIds(e)}getAll(){return this._dataValidationModel.getAll()}};q=F([P(0,p(T)),P(1,f),P(2,p(E)),P(3,p(I)),P(4,p(K)),P(5,p(V)),P(6,c)],q);const Xe=1,Ze=0;function Qe(e,t){return y.isBlank(e)?t.t(`dataValidation.validFail.value`):x(e)?t.t(`dataValidation.validFail.primitive`):``}const J=e=>y.isDefine(e)&&String(e).toLowerCase()===`true`?`1`:String(e).toLowerCase()===`false`?`0`:e;var $e=class extends w{constructor(...e){super(...e),N(this,`id`,a.CHECKBOX),N(this,`title`,`dataValidation.checkbox.title`),N(this,`operators`,[]),N(this,`scopes`,[`sheet`]),N(this,`order`,41),N(this,`offsetFormulaByRange`,!1),N(this,`_formulaService`,this.injector.get(K)),N(this,`skipDefaultFontRender`,(e,t,n)=>{let{unitId:r,subUnitId:i}=n,{formula1:a,formula2:o}=this.parseFormulaSync(e,r,i),s=`${t==null?``:t}`;return!s||s===`${a}`||s===`${o}`})}validatorFormula(e,t,n){let{formula1:r,formula2:i}=e,a=r===i;if(y.isBlank(r)&&y.isBlank(i))return{success:!0};if(a)return{success:!1,formula1:this.localeService.t(`dataValidation.validFail.checkboxEqual`),formula2:this.localeService.t(`dataValidation.validFail.checkboxEqual`)};let o=Qe(r,this.localeService),s=Qe(i,this.localeService);return{success:!o&&!s,formula1:o,formula2:s}}async parseFormula(e,t,n){var r,i;let{formula1:a=1,formula2:o=0}=e,s=await this._formulaService.getRuleFormulaResult(t,n,e.uid),c=x(a)?L(s==null||(r=s[0])==null||(r=r.result)==null?void 0:r[0][0]):a,l=x(o)?L(s==null||(i=s[1])==null||(i=i.result)==null?void 0:i[0][0]):o,u=z(String(c))&&z(String(l));return{formula1:J(c),formula2:J(l),originFormula1:c,originFormula2:l,isFormulaValid:u}}getExtraStyle(e,t){return{tb:ie.CLIP}}parseFormulaSync(e,t,n){var r,i;let{formula1:a=1,formula2:o=0}=e,s=this._formulaService.getRuleFormulaResultSync(t,n,e.uid),c=x(a)?L(s==null||(r=s[0])==null||(r=r.result)==null?void 0:r[0][0]):a,l=x(o)?L(s==null||(i=s[1])==null||(i=i.result)==null?void 0:i[0][0]):o,u=z(String(c))&&z(String(l));return{formula1:J(c),formula2:J(l),originFormula1:c,originFormula2:l,isFormulaValid:u}}async isValidType(e,t,n){let{value:r,unitId:i,subUnitId:a}=e,{formula1:o,formula2:s,originFormula1:c,originFormula2:l}=await this.parseFormula(n,i,a);return!y.isDefine(o)||!y.isDefine(s)?!0:y.isDefine(r)&&(String(r)===String(o)||String(r)===String(s)||String(r)===String(c==null?``:c)||String(r)===String(l==null?``:l))}generateRuleErrorMessage(e){return this.localeService.t(`dataValidation.checkbox.error`)}generateRuleName(e){return this.titleStr}};const et={[n.BETWEEN]:`dataValidation.date.operators.between`,[n.EQUAL]:`dataValidation.date.operators.equal`,[n.GREATER_THAN]:`dataValidation.date.operators.greaterThan`,[n.GREATER_THAN_OR_EQUAL]:`dataValidation.date.operators.greaterThanOrEqual`,[n.LESS_THAN]:`dataValidation.date.operators.lessThan`,[n.LESS_THAN_OR_EQUAL]:`dataValidation.date.operators.lessThanOrEqual`,[n.NOT_BETWEEN]:`dataValidation.date.operators.notBetween`,[n.NOT_EQUAL]:`dataValidation.date.operators.notEqual`};n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL;const tt={[n.BETWEEN]:`dataValidation.date.ruleName.between`,[n.EQUAL]:`dataValidation.date.ruleName.equal`,[n.GREATER_THAN]:`dataValidation.date.ruleName.greaterThan`,[n.GREATER_THAN_OR_EQUAL]:`dataValidation.date.ruleName.greaterThanOrEqual`,[n.LESS_THAN]:`dataValidation.date.ruleName.lessThan`,[n.LESS_THAN_OR_EQUAL]:`dataValidation.date.ruleName.lessThanOrEqual`,[n.NOT_BETWEEN]:`dataValidation.date.ruleName.notBetween`,[n.NOT_EQUAL]:`dataValidation.date.ruleName.notEqual`,NONE:`dataValidation.date.ruleName.legal`},nt={[n.BETWEEN]:`dataValidation.date.errorMsg.between`,[n.EQUAL]:`dataValidation.date.errorMsg.equal`,[n.GREATER_THAN]:`dataValidation.date.errorMsg.greaterThan`,[n.GREATER_THAN_OR_EQUAL]:`dataValidation.date.errorMsg.greaterThanOrEqual`,[n.LESS_THAN]:`dataValidation.date.errorMsg.lessThan`,[n.LESS_THAN_OR_EQUAL]:`dataValidation.date.errorMsg.lessThanOrEqual`,[n.NOT_BETWEEN]:`dataValidation.date.errorMsg.notBetween`,[n.NOT_EQUAL]:`dataValidation.date.errorMsg.notEqual`,NONE:`dataValidation.date.errorMsg.legal`},rt=[n.BETWEEN,n.NOT_BETWEEN],Y=`{FORMULA1}`,X=`{FORMULA2}`,it=e=>{var t,n;if(e==null||typeof e==`boolean`)return;if(typeof e==`number`||!Number.isNaN(+e))return+e;let r=(t=S.parseDate(e))==null?void 0:t.v;return y.isDefine(r)?r:(n=S.parseDate(oe(e).format(`YYYY-MM-DD HH:mm:ss`)))==null?void 0:n.v};var at=class extends w{constructor(...e){super(...e),N(this,`id`,a.DATE),N(this,`title`,`dataValidation.date.title`),N(this,`order`,40),N(this,`operators`,[n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL]),N(this,`scopes`,[`sheet`]),N(this,`_customFormulaService`,this.injector.get(V)),N(this,`_lexerTreeBuilder`,this.injector.get(A))}async parseFormula(e,t,n,r,i){let a=await this._customFormulaService.getCellFormulaValue(t,n,e.uid,r,i),o=await this._customFormulaService.getCellFormula2Value(t,n,e.uid,r,i),{formula1:s,formula2:c}=e,l=z(String(a==null?void 0:a.v))&&z(String(o==null?void 0:o.v));return{formula1:it(x(s)?a==null?void 0:a.v:s),formula2:it(x(c)?o==null?void 0:o.v:c),isFormulaValid:l}}async isValidType(e){let{interceptValue:t,value:n}=e;return typeof n==`number`&&typeof t==`string`||typeof t==`string`?!!S.parseDate(t):!1}_validatorSingleFormula(e){return!y.isBlank(e)&&(x(e)||!Number.isNaN(+e)||!!(e&&S.parseDate(e)))}validatorFormula(e,t,n){let r=e.operator;if(!r)return{success:!0};let i=this._validatorSingleFormula(e.formula1),a=this.localeService.t(`dataValidation.validFail.date`);if(rt.includes(r)){let t=this._validatorSingleFormula(e.formula2);return{success:i&&t,formula1:i?void 0:a,formula2:t?void 0:a}}return{success:i,formula1:i?void 0:a}}normalizeFormula(e,t,n){let{formula1:r,formula2:i,bizInfo:a}=e,o=e=>{if(!e)return e;let t;if(!Number.isNaN(+e))t=S.dateFromSerial(+e);else{var n;let r=(n=S.parseDate(e))==null?void 0:n.v;if(r==null)return``;t=S.dateFromSerial(r)}return oe(`${t[0]}/${t[1]}/${t[2]} ${t[3]}:${t[4]}:${t[5]}`).format(a!=null&&a.showTime?`YYYY-MM-DD HH:mm:ss`:`YYYY-MM-DD`)};return{formula1:x(r)?r:o(`${r}`),formula2:x(i)?i:o(`${i}`)}}transform(e,t,n){let{value:r}=e;return{...e,value:it(r)}}get operatorNames(){return this.operators.map(e=>this.localeService.t(et[e]))}generateRuleName(e){var t,n;if(!e.operator)return this.localeService.t(tt.NONE);let r=this.localeService.t(tt[e.operator]).replace(Y,(t=e.formula1)==null?``:t).replace(X,(n=e.formula2)==null?``:n);return`${this.titleStr} ${r}`}generateRuleErrorMessage(e,t){if(!e.operator)return this.titleStr;let{transformedFormula1:n,transformedFormula2:r}=W(this._lexerTreeBuilder,e,t);return`${this.localeService.t(nt[e.operator]).replace(Y,n==null?``:n).replace(X,r==null?``:r)}`}};n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL,n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL;const ot={[n.BETWEEN]:`dataValidation.errorMsg.between`,[n.EQUAL]:`dataValidation.errorMsg.equal`,[n.GREATER_THAN]:`dataValidation.errorMsg.greaterThan`,[n.GREATER_THAN_OR_EQUAL]:`dataValidation.errorMsg.greaterThanOrEqual`,[n.LESS_THAN]:`dataValidation.errorMsg.lessThan`,[n.LESS_THAN_OR_EQUAL]:`dataValidation.errorMsg.lessThanOrEqual`,[n.NOT_BETWEEN]:`dataValidation.errorMsg.notBetween`,[n.NOT_EQUAL]:`dataValidation.errorMsg.notEqual`,NONE:`dataValidation.errorMsg.legal`};function Z(e){return+e}var st=class extends w{constructor(...e){super(...e),N(this,`_customFormulaService`,this.injector.get(V)),N(this,`id`,a.DECIMAL),N(this,`_lexerTreeBuilder`,this.injector.get(A)),N(this,`title`,`dataValidation.decimal.title`),N(this,`order`,20),N(this,`operators`,[n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL]),N(this,`scopes`,[`sheet`])}_isFormulaOrNumber(e){return!y.isBlank(e)&&(x(e)||!Number.isNaN(+e))}async isValidType(e,t,n){let{value:r}=e;return!Number.isNaN(Z(r))}transform(e,t,n){let{value:r}=e;return{...e,value:Z(r)}}_parseNumber(e){return e==null?NaN:+e}async parseFormula(e,t,n,r,i){let a=await this._customFormulaService.getCellFormulaValue(t,n,e.uid,r,i),o=await this._customFormulaService.getCellFormula2Value(t,n,e.uid,r,i),{formula1:s,formula2:c}=e,l=z(String(a==null?void 0:a.v))&&z(String(o==null?void 0:o.v));return{formula1:this._parseNumber(x(s)?a==null?void 0:a.v:s),formula2:this._parseNumber(x(c)?o==null?void 0:o.v:c),isFormulaValid:l}}validatorFormula(e,t,n){let r=e.operator;if(!r)return{success:!0};let i=y.isDefine(e.formula1)&&this._isFormulaOrNumber(e.formula1),a=y.isDefine(e.formula2)&&this._isFormulaOrNumber(e.formula2),o=rt.includes(r),s=this.localeService.t(`dataValidation.validFail.number`);return o?{success:i&&a,formula1:i?void 0:s,formula2:a?void 0:s}:{success:i,formula1:i?``:s}}generateRuleErrorMessage(e,t){if(!e.operator)return this.localeService.t(ot.NONE).replace(`{TYPE}`,this.titleStr);let{transformedFormula1:n,transformedFormula2:r}=W(this._lexerTreeBuilder,e,t);return`${this.localeService.t(ot[e.operator]).replace(Y,n==null?``:n).replace(X,r==null?``:r)}`}};function ct(e){if(!e)return[];let t=new Set;for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i)for(let e=0,r=i.length;e<r;e++){let r=i[e],a=H(r);if(a!=null){var n;if(typeof a!=`string`&&typeof(r==null?void 0:r.s)==`object`&&!((n=r.s)==null||(n=n.n)==null)&&n.pattern){t.add(S.format(r.s.n.pattern,a,{throws:!1}));continue}let e=typeof a==`string`?a:String(a);z(e)&&t.add(e)}}}return[...t]}const lt=[`if`,`indirect`,`choose`,`offset`];function ut(e,t){if(!x(e)||we(e.slice(1)))return!0;let n=t.sequenceNodesBuilder(e);return n&&n.some(e=>typeof e==`object`&&e.nodeType===Ee.FUNCTION&&lt.indexOf(e.token.toLowerCase())>-1)}function dt(e,t){let{formula1:n=``,ranges:r}=e;if(we(n.slice(1))){let e=Se(n.slice(1));if((!e.sheetName||e.sheetName===t)&&r.some(t=>v.intersects(t,e.range)))return!0}return!1}var ft=class extends w{constructor(...e){super(...e),N(this,`formulaService`,this.injector.get(K)),N(this,`_lexer`,this.injector.get(A)),N(this,`_univerInstanceService`,this.injector.get(f)),N(this,`_listCacheService`,this.injector.get(G)),N(this,`order`,50),N(this,`offsetFormulaByRange`,!1),N(this,`id`,a.LIST),N(this,`title`,`dataValidation.list.title`),N(this,`operators`,[]),N(this,`scopes`,[`sheet`]),N(this,`skipDefaultFontRender`,e=>e.renderMode!==r.TEXT)}validatorFormula(e,t,n){var r,i;let a=!y.isBlank(e.formula1),o=ut((r=e.formula1)==null?``:r,this._lexer),s=(i=this._univerInstanceService.getUnit(t,b.UNIVER_SHEET))==null||(i=i.getSheetBySheetId(n))==null?void 0:i.getName(),c=dt(e,s==null?``:s);return{success:!!(a&&o&&!c),formula1:a?o?c?this.localeService.t(`dataValidation.validFail.listIntersects`):void 0:this.localeService.t(`dataValidation.validFail.listInvalid`):this.localeService.t(`dataValidation.validFail.list`)}}getExtraStyle(e,t,{style:n}){var i;let o=(i=n.tb===ie.OVERFLOW?ie.CLIP:n.tb)==null?ie.WRAP:i;if(e.type===a.LIST&&(e.renderMode===r.ARROW||e.renderMode===r.TEXT)){let n=this.getListWithColorMap(e)[`${t==null?``:t}`];if(n)return{bg:{rgb:n},tb:o}}return{tb:o}}parseCellValue(e){return U(e.toString())}async parseFormula(e,t,n){var r;let i=await this.formulaService.getRuleFormulaResult(t,n,e.uid),a=L(i==null||(r=i[0])==null||(r=r.result)==null?void 0:r[0][0]);return{formula1:void 0,formula2:void 0,isFormulaValid:z(String(a))}}async isValidType(e,t,n){let{value:r,unitId:i,subUnitId:a}=e,{formula1:o=``}=n,s=x(o)?this._listCacheService.getOrCompute(i,a,n).list:U(o);return this.parseCellValue(r).every(e=>s.includes(e))}generateRuleName(){return this.localeService.t(`dataValidation.list.name`)}generateRuleErrorMessage(){return this.localeService.t(`dataValidation.list.error`)}_getUnitAndSubUnit(e,t){var n,r;let i=(n=e?this._univerInstanceService.getUniverSheetInstance(e):void 0)==null?this._univerInstanceService.getCurrentUnitForType(b.UNIVER_SHEET):n;if(!i)return null;let a=(r=t?i.getSheetBySheetId(t):void 0)==null?i.getActiveSheet():r;return a?{unitId:i.getUnitId(),subUnitId:a.getSheetId()}:null}getList(e,t,n){let r=this._getUnitAndSubUnit(t,n);if(!r)return[];let{unitId:i,subUnitId:a}=r;return this._listCacheService.getOrCompute(i,a,e).list}async getListAsync(e,t,n){var r;let{formula1:i=``}=e,a=this._getUnitAndSubUnit(t,n);if(!a)return[];let{unitId:o,subUnitId:s}=a,c=await this.formulaService.getRuleFormulaResult(o,s,e.uid);return x(i)?ct(c==null||(r=c[0])==null||(r=r.result)==null?void 0:r[0][0]):U(i)}getListWithColor(e,t,n){let r=this._getUnitAndSubUnit(t,n);if(!r)return[];let{unitId:i,subUnitId:a}=r;return this._listCacheService.getOrCompute(i,a,e).listWithColor}getListWithColorMap(e,t,n){let r=this._getUnitAndSubUnit(t,n);if(!r)return{};let{unitId:i,subUnitId:a}=r;return this._listCacheService.getOrCompute(i,a,e).colorMap}},pt=class extends w{constructor(...e){super(...e),N(this,`id`,a.TEXT_LENGTH),N(this,`title`,`dataValidation.textLength.title`),N(this,`_lexerTreeBuilder`,this.injector.get(A)),N(this,`order`,30),N(this,`operators`,[n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL]),N(this,`scopes`,[`sheet`]),N(this,`_customFormulaService`,this.injector.get(V))}_isFormulaOrInt(e){return!y.isBlank(e)&&(x(e)||!Number.isNaN(+e)&&Number.isInteger(+e))}validatorFormula(e,t,n){let r=e.operator;if(!r)return{success:!1};let i=y.isDefine(e.formula1)&&this._isFormulaOrInt(e.formula1),a=y.isDefine(e.formula2)&&this._isFormulaOrInt(e.formula2),o=rt.includes(r),s=this.localeService.t(`dataValidation.validFail.number`);return o?{success:i&&a,formula1:i?void 0:s,formula2:a?void 0:s}:{success:i,formula1:s}}_parseNumber(e){return e==null?NaN:+e}async parseFormula(e,t,n,r,i){let a=await this._customFormulaService.getCellFormulaValue(t,n,e.uid,r,i),o=await this._customFormulaService.getCellFormula2Value(t,n,e.uid,r,i),{formula1:s,formula2:c}=e,l=z(String(a==null?void 0:a.v))&&z(String(o==null?void 0:o.v));return{formula1:this._parseNumber(x(s)?a==null?void 0:a.v:s),formula2:this._parseNumber(x(c)?o==null?void 0:o.v:c),isFormulaValid:l}}transform(e,t,n){return{...e,value:e.value.toString().length}}async isValidType(e,t,n){let{value:r}=e;return typeof r==`string`||typeof r==`number`}generateRuleErrorMessage(e,t){if(!e.operator)return this.titleStr;let{transformedFormula1:n,transformedFormula2:r}=W(this._lexerTreeBuilder,e,t);return`${this.localeService.t(he[e.operator]).replace(Y,n==null?``:n).replace(X,r==null?``:r)}`}};function mt(e){var t,n;return e?e.p?!((t=(n=e.p.body)==null?void 0:n.dataStream)==null?``:t).slice(0,-2).trim():y.isBlank(e.v):!0}function ht(e,t,n,r,i=`command`,o=!0){let s=r.get(A),c=r.get(E),l=[],u=[],d=r.get(q),p=Ie(r.get(f),{unitId:e,subUnitId:t});if(!p)return{redoMutations:l,undoMutations:u};let{worksheet:m}=p,h=new ee,g=!1;function te(e,t){o&&e.forEach(e=>{_.foreach(e,(e,n)=>{let r=m.getCellRaw(e,n),i=Ke(r);(mt(r)||i===t)&&!(r!=null&&r.p)&&(g=!0,h.setValue(e,n,{v:t,p:null}))})})}if(n.forEach(n=>{switch(n.type){case`delete`:l.push({id:D.id,params:{unitId:e,subUnitId:t,ruleId:n.rule.uid,source:i}}),u.unshift({id:C.id,params:{unitId:e,subUnitId:t,rule:n.rule,index:n.index,source:i}});break;case`update`:{if(B(n.rule.type,c)){let r=n.oldRanges[0].startRow,a=n.oldRanges[0].startColumn,o=n.newRanges[0].startRow,c=n.newRanges[0].startColumn,d=o-r,f=c-a,p=x(n.rule.formula1)?s.moveFormulaRefOffset(n.rule.formula1,f,d):n.rule.formula1,m=x(n.rule.formula2)?s.moveFormulaRefOffset(n.rule.formula2,f,d):n.rule.formula2;p!==n.rule.formula1||m!==n.rule.formula2||!de(n.newRanges,n.oldRanges)?(l.push({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.ruleId,payload:{type:k.ALL,payload:{formula1:p,formula2:m,ranges:n.newRanges}}}}),u.unshift({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.ruleId,payload:{type:k.ALL,payload:{formula1:n.rule.formula1,formula2:n.rule.formula2,ranges:n.oldRanges}}}})):(l.push({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.ruleId,payload:{type:k.RANGE,payload:n.newRanges},source:i}}),u.unshift({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.ruleId,payload:{type:k.RANGE,payload:n.oldRanges},source:i}}))}else l.push({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.ruleId,payload:{type:k.RANGE,payload:n.newRanges},source:i}}),u.unshift({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.ruleId,payload:{type:k.RANGE,payload:n.oldRanges},source:i}});let r=d.getRuleById(e,t,n.ruleId);if(r&&r.type===a.CHECKBOX){let i=d.getValidator(a.CHECKBOX).parseFormulaSync(r,e,t);te(n.newRanges,i.formula2)}break}case`add`:if(l.push({id:C.id,params:{unitId:e,subUnitId:t,rule:n.rule,source:i}}),u.unshift({id:D.id,params:{unitId:e,subUnitId:t,ruleId:n.rule.uid,source:i}}),n.rule.type===a.CHECKBOX){let r=d.getValidator(a.CHECKBOX).parseFormulaSync(n.rule,e,t);te(n.rule.ranges,r.originFormula2)}break;default:break}}),g){let n={id:j.id,params:{unitId:e,subUnitId:t,cellValue:h.getData()}},i={id:j.id,params:Me(r,n.params)};l.push(n),u.push(i)}return{redoMutations:l,undoMutations:u}}const gt={type:t.COMMAND,id:`sheet.command.updateDataValidationRuleRange`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,ranges:i,ruleId:a}=t,o=e.get(q),s=e.get(c),l=e.get(d);if(!o.getRuleById(n,r,a))return!1;let u=o.getRuleObjectMatrix(n,r).clone();u.updateRange(a,i);let{redoMutations:f,undoMutations:p}=ht(n,r,u.diff(o.getRules(n,r)),e);return l.pushUndoRedo({undoMutations:p,redoMutations:f,unitID:n}),pe(f,s),!0}},_t={type:t.COMMAND,id:`sheet.command.addDataValidation`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,rule:i}=t,a=e.get(q),o=e.get(c),s=e.get(d),l=a.getRuleObjectMatrix(n,r).clone();l.addRule(i);let u=l.diff(a.getRules(n,r)),f=a.getValidator(i.type),p={unitId:n,subUnitId:r,rule:{...i,...f==null?void 0:f.normalizeFormula(i,n,r)}},{redoMutations:m,undoMutations:h}=ht(n,r,u,e);return m.push({id:C.id,params:p}),h.unshift({id:D.id,params:{unitId:n,subUnitId:r,ruleId:i.uid}}),s.pushUndoRedo({unitID:n,redoMutations:m,undoMutations:h}),pe(m,o),!0}},vt={type:t.COMMAND,id:`sheets.command.update-data-validation-setting`,handler(e,t){if(!t)return!1;let n=e.get(c),r=e.get(d),i=e.get(q),o=e.get(E),{unitId:s,subUnitId:l,ruleId:u,setting:p}=t,m=o.getValidatorItem(p.type);if(!m)return!1;let h=i.getRuleById(s,l,u);if(!h)return!1;let g={...h,...p};if(!m.validatorFormula(g,s,l).success)return!1;let te={unitId:s,subUnitId:l,ruleId:u,payload:{type:k.SETTING,payload:{...p,...m.normalizeFormula(g,s,l)}}},ne=[{id:O.id,params:te}],v={unitId:s,subUnitId:l,ruleId:u,payload:{type:k.SETTING,payload:ve(h)}},re=[{id:O.id,params:v}];if(p.type===a.CHECKBOX){let t=h.ranges,n=Ie(e.get(f),{unitId:s,subUnitId:l});if(n){let r=new ee,{worksheet:i}=n,{formula2:a=0,formula1:o=1}=h,{formula2:c=0,formula1:u=1}=p,d=!1;if(t.forEach(e=>{_.foreach(e,(e,t)=>{let n=i.getCellRaw(e,t),s=Ke(n);(mt(n)||s===String(a))&&!(n!=null&&n.p)?(r.setValue(e,t,{v:c,p:null}),d=!0):s===String(o)&&!(n!=null&&n.p)&&(r.setValue(e,t,{v:u,p:null}),d=!0)})}),d){let t={id:j.id,params:{unitId:s,subUnitId:l,cellValue:r.getData()}},n={id:j.id,params:Me(e,t.params)};ne.push(t),re.push(n)}}}return pe(ne,n).result?(r.pushUndoRedo({unitID:s,redoMutations:ne,undoMutations:re}),!0):!1}},yt={type:t.COMMAND,id:`sheets.command.update-data-validation-options`,handler(e,t){if(!t)return!1;let n=e.get(c),r=e.get(d),i=e.get(q),{unitId:a,subUnitId:o,ruleId:s,options:l}=t,u=i.getRuleById(a,o,s);if(!u)return!1;let f={unitId:a,subUnitId:o,ruleId:s,payload:{type:k.OPTIONS,payload:l}},p=[{id:O.id,params:f}],m={unitId:a,subUnitId:o,ruleId:s,payload:{type:k.OPTIONS,payload:_e(u)}},h=[{id:O.id,params:m}];return r.pushUndoRedo({unitID:a,redoMutations:p,undoMutations:h}),n.executeCommand(O.id,f),!0}},bt={type:t.COMMAND,id:`sheets.command.clear-range-data-validation`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,ranges:i}=t,a=e.get(c),o=Ie(e.get(f),{unitId:n,subUnitId:r}),s=e.get(q);if(!o)return!1;let l=e.get(d),u=s.getRuleObjectMatrix(n,r).clone();u.removeRange(i);let{redoMutations:p,undoMutations:m}=ht(n,r,u.diff(s.getRules(n,r)),e);return l.pushUndoRedo({unitID:n,redoMutations:p,undoMutations:m}),pe(p,a).result}},xt={type:t.COMMAND,id:`sheet.command.remove-all-data-validation`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r}=t,i=e.get(c),a=e.get(q),o=e.get(d),s=[...a.getRules(n,r)],l={unitId:n,subUnitId:r,ruleId:s.map(e=>e.uid)},u=[{id:D.id,params:l}],f=[{id:C.id,params:{unitId:n,subUnitId:r,rule:s}}];return o.pushUndoRedo({redoMutations:u,undoMutations:f,unitID:n}),i.executeCommand(D.id,l),!0}},St=(e,t)=>{let n=e.get(q),{unitId:r,subUnitId:i,ruleId:a,source:o}=t;if(Array.isArray(a)){let e=a.map(e=>n.getRuleById(r,i,e)).filter(Boolean);return[{id:C.id,params:{unitId:r,subUnitId:i,rule:e,source:o}}]}return[{id:C.id,params:{unitId:r,subUnitId:i,rule:{...n.getRuleById(r,i,a)},index:n.getRuleIndex(r,i,a)}}]},Ct={type:t.COMMAND,id:`sheet.command.remove-data-validation-rule`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,ruleId:i}=t,a=e.get(c),o=e.get(d),s=e.get(q),l=[{id:D.id,params:t}],u=[{id:C.id,params:{unitId:n,subUnitId:r,rule:{...s.getRuleById(n,r,i)},index:s.getRuleIndex(n,r,i)}}];return o.pushUndoRedo({undoMutations:u,redoMutations:l,unitID:t.unitId}),a.executeCommand(D.id,t),!0}},wt=`SHEET_DATA_VALIDATION_PLUGIN`;let Tt=class extends s{constructor(e,t,n){super(),this._univerInstanceService=e,this._permissionService=t,this._lexerTreeBuilder=n}getFormulaRefCheck(e){let t=this._lexerTreeBuilder.sequenceNodesBuilder(e);if(!t)return!0;for(let e=0;e<t.length;e++){let r=t[e];if(typeof r==`string`)continue;let{token:i}=r,a=Ce(i),o=this._univerInstanceService.getCurrentUnitForType(b.UNIVER_SHEET),s=o.getActiveSheet(),c=o.getUnitId();if(a.sheetName){if(s=o.getSheetBySheetName(a.sheetName),!s)return!1;let e=s==null?void 0:s.getSheetId();if(!this._permissionService.getPermissionPoint(new Fe(c,e).id))return!1}if(!s)return!1;let{startRow:l,endRow:u,startColumn:d,endColumn:f}=a.range;for(let e=l;e<=u;e++)for(let t=d;t<=f;t++){var n;let r=(n=s.getCell(e,t))==null||(n=n.selectionProtection)==null?void 0:n[0];if((r==null?void 0:r[Ve.View])===!1)return!1}}return!0}};Tt=F([P(0,f),P(1,u),P(2,p(A))],Tt);var Et=`@univerjs/sheets-data-validation`,Dt=`0.20.1`;const Ot=`sheets-data-validation.config`;Symbol(Ot);const kt={};let At=class extends s{constructor(e,t,n){super(),this._dataValidationModel=e,this._formulaRefRangeService=t,this._validatorRegistryService=n,N(this,`_disposableMap`,new Map),N(this,`registerRule`,(e,t,n)=>{B(n.type,this._validatorRegistryService)&&this.register(e,t,n)}),this._initRefRange()}_getIdWithUnitId(e,t,n){return`${e}_${t}_${n}`}register(e,t,n){let r=n.ranges,i=n.formula1,a=n.formula2,o=this._formulaRefRangeService.registerRangeFormula(e,t,r,[i==null?``:i,a==null?``:a],o=>{if(o.length===0)return{undos:[{id:C.id,params:{unitId:e,subUnitId:t,rule:n,source:`patched`}}],redos:[{id:D.id,params:{unitId:e,subUnitId:t,ruleId:n.uid,source:`patched`}}]};let s=[],c=[],l=o[0];s.push({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.uid,payload:{type:k.ALL,payload:{ranges:l.ranges,formula1:l.formulas[0],formula2:l.formulas[1]}},source:`patched`}}),c.push({id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.uid,payload:{type:k.ALL,payload:{ranges:r,formula1:i,formula2:a}},source:`patched`}});for(let r=1;r<o.length;r++){let i=o[r],a=ce();s.push({id:C.id,params:{unitId:e,subUnitId:t,rule:{...n,uid:a,formula1:i.formulas[0],formula2:i.formulas[1],ranges:i.ranges},source:`patched`}}),c.push({id:D.id,params:{unitId:e,subUnitId:t,ruleId:a,source:`patched`}})}return{undos:c,redos:s}}),s=this._getIdWithUnitId(e,t,n.uid);this._disposableMap.set(s,o)}_initRefRange(){let e=this._dataValidationModel.getAll();for(let[t,n]of e)for(let[e,r]of n)for(let n of r)this.registerRule(t,e,n);this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{let{unitId:t,subUnitId:n,rule:r}=e;switch(e.type){case`add`:{let t=e.rule;this.registerRule(e.unitId,e.subUnitId,t);break}case`remove`:{let e=this._disposableMap.get(this._getIdWithUnitId(t,n,r.uid));e&&e.dispose();break}case`update`:{let r=e.rule,i=this._disposableMap.get(this._getIdWithUnitId(t,n,r.uid));i&&i.dispose(),this.registerRule(e.unitId,e.subUnitId,r);break}}})),this.disposeWithMe(me(()=>{this._disposableMap.forEach(e=>{e.dispose()}),this._disposableMap.clear()}))}};At=F([P(0,p(q)),P(1,p(He)),P(2,p(E))],At);let jt=class extends s{constructor(e,t,n,r,i,a){super(),this._dataValidationModel=e,this._injector=t,this._refRangeService=n,this._dataValidationFormulaService=r,this._formulaRefRangeService=i,this._validatorRegistryService=a,N(this,`_disposableMap`,new Map),N(this,`registerRule`,(e,t,n)=>{B(n.type,this._validatorRegistryService)||(this.register(e,t,n),this.registerFormula(e,t,n))}),this._initRefRange()}_getIdWithUnitId(e,t,n){return`${e}_${t}_${n}`}registerFormula(e,t,n){var r;let i=n.uid,a=this._getIdWithUnitId(e,t,i),o=(r=this._disposableMap.get(a))==null?new Set:r,s=(r,a)=>{let o=this._dataValidationModel.getRuleById(e,t,i);if(!o)return{redos:[],undos:[]};let s=o[r];if(!s||s===a)return{redos:[],undos:[]};let c={unitId:e,subUnitId:t,ruleId:n.uid,payload:{type:k.SETTING,payload:{type:o.type,formula1:o.formula1,formula2:o.formula2,[r]:a}},source:`patched`},l={unitId:e,subUnitId:t,ruleId:n.uid,payload:{type:k.SETTING,payload:{type:o.type,formula1:o.formula1,formula2:o.formula2}},source:`patched`};return{redos:[{id:O.id,params:c}],undos:[{id:O.id,params:l}]}},c=this._dataValidationFormulaService.getRuleFormulaInfo(e,t,i);if(c){let[n,r]=c;if(n){let r=this._formulaRefRangeService.registerFormula(e,t,n.text,e=>s(`formula1`,e));o.add(()=>r.dispose())}if(r){let n=this._formulaRefRangeService.registerFormula(e,t,r.text,e=>s(`formula2`,e));o.add(()=>n.dispose())}}}register(e,t,n){var r;let i=r=>{let i=[...n.ranges],a=i.map(e=>Le(e,r)).filter(e=>!!e).flat();if(de(a,i))return{redos:[],undos:[]};if(a.length){let r={unitId:e,subUnitId:t,ruleId:n.uid,payload:{type:k.RANGE,payload:a},source:`patched`};return{redos:[{id:O.id,params:r}],undos:[{id:O.id,params:{unitId:e,subUnitId:t,ruleId:n.uid,payload:{type:k.RANGE,payload:i},source:`patched`}}]}}else{let r={unitId:e,subUnitId:t,ruleId:n.uid};return{redos:[{id:D.id,params:r}],undos:St(this._injector,r)}}},a=[];n.ranges.forEach(n=>{let r=this._refRangeService.registerRefRange(n,i,e,t);a.push(()=>r.dispose())});let o=this._getIdWithUnitId(e,t,n.uid),s=(r=this._disposableMap.get(o))==null?new Set:r;s.add(()=>a.forEach(e=>e())),this._disposableMap.set(o,s)}_initRefRange(){let e=this._dataValidationModel.getAll();for(let[t,n]of e)for(let[e,r]of n)for(let n of r)this.registerRule(t,e,n);this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{let{unitId:t,subUnitId:n,rule:r}=e;switch(e.type){case`add`:{let t=e.rule;this.registerRule(e.unitId,e.subUnitId,t);break}case`remove`:{let e=this._disposableMap.get(this._getIdWithUnitId(t,n,r.uid));e&&e.forEach(e=>e());break}case`update`:{let r=e.rule,i=this._disposableMap.get(this._getIdWithUnitId(t,n,r.uid));i&&i.forEach(e=>e()),this.registerRule(e.unitId,e.subUnitId,r);break}}})),this.disposeWithMe(me(()=>{this._disposableMap.forEach(e=>{e.forEach(e=>e())}),this._disposableMap.clear()}))}};jt=F([P(0,p(q)),P(1,p(m)),P(2,p(ke)),P(3,p(K)),P(4,p(He)),P(5,p(E))],jt);let Mt=class extends s{constructor(e,t,n){super(),this._sheetInterceptorService=e,this._univerInstanceService=t,this._sheetDataValidationModel=n,this._initSheetChange()}_initSheetChange(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:e=>{if(e.id===Ae.id){var t;let n=e.params,r=n.unitId||this._univerInstanceService.getCurrentUnitForType(b.UNIVER_SHEET).getUnitId(),i=this._univerInstanceService.getUniverSheetInstance(r);if(!i)return{redos:[],undos:[]};let a=n.subUnitId||((t=i.getActiveSheet())==null?void 0:t.getSheetId());if(!a)return{redos:[],undos:[]};let o=this._sheetDataValidationModel.getRules(r,a);if(o.length===0)return{redos:[],undos:[]};let s={unitId:r,subUnitId:a,ruleId:o.map(e=>e.uid),source:`patched`},c={unitId:r,subUnitId:a,rule:[...o],source:`patched`};return{redos:[{id:D.id,params:s}],undos:[{id:C.id,params:c}]}}else if(e.id===Oe.id){let{unitId:t,subUnitId:n,targetSubUnitId:r}=e.params;if(!t||!n||!r)return{redos:[],undos:[]};let i=this._sheetDataValidationModel.getRules(t,n);if(i.length===0)return{redos:[],undos:[]};let a=i.map(e=>({...e,uid:ce(6)}));return{redos:[{id:C.id,params:{unitId:t,subUnitId:r,rule:a,source:`patched`}}],undos:[{id:D.id,params:{unitId:t,subUnitId:r,ruleId:a.map(e=>e.uid),source:`patched`}}]}}return{redos:[],undos:[]}}}))}};Mt=F([P(0,p(Ne)),P(1,p(f)),P(2,p(q))],Mt);var Nt=class extends w{constructor(...e){super(...e),N(this,`id`,a.ANY),N(this,`title`,`dataValidation.any.title`),N(this,`operators`,[]),N(this,`scopes`,[`sheet`]),N(this,`order`,0),N(this,`offsetFormulaByRange`,!1)}async parseFormula(e,t,n){return{formula1:e.formula1,formula2:e.formula2,isFormulaValid:!0}}validatorFormula(e,t,n){return{success:!0}}async isValidType(e,t,n){return!0}generateRuleErrorMessage(e){return this.localeService.t(`dataValidation.any.error`)}},Pt=class extends w{constructor(...e){super(...e),N(this,`id`,a.CUSTOM),N(this,`title`,`dataValidation.custom.title`),N(this,`operators`,[]),N(this,`scopes`,[`sheet`]),N(this,`order`,60),N(this,`_customFormulaService`,this.injector.get(V)),N(this,`_lexerTreeBuilder`,this.injector.get(A))}validatorFormula(e,t,n){var r;let i=x(e.formula1),a=(r=e.formula1)==null?``:r,o=this._lexerTreeBuilder.checkIfAddBracket(a)===0&&a.startsWith(Te.EQUALS);return{success:i&&o,formula1:i&&o?``:this.localeService.t(`dataValidation.validFail.formula`)}}async parseFormula(e,t,n){return{formula1:void 0,formula2:void 0,isFormulaValid:!0}}async isValidType(t,n,r){let{column:i,row:a,unitId:o,subUnitId:s}=t,c=await this._customFormulaService.getCellFormulaValue(o,s,r.uid,a,i),l=c==null?void 0:c.v;return z(String(l))&&y.isDefine(l)&&l!==``?c.t===e.BOOLEAN?!!l:typeof l==`boolean`?l:typeof l==`number`?!!l:typeof l==`string`?z(l):!!l:!1}generateRuleErrorMessage(e){return this.localeService.t(`dataValidation.custom.error`)}generateRuleName(e){var t;return this.localeService.t(`dataValidation.custom.ruleName`).replace(`{FORMULA1}`,(t=e.formula1)==null?``:t)}},Ft=class extends ft{constructor(...e){super(...e),N(this,`id`,a.LIST_MULTIPLE),N(this,`title`,`dataValidation.listMultiple.title`),N(this,`offsetFormulaByRange`,!1),N(this,`skipDefaultFontRender`,()=>!0)}},It=class extends w{constructor(...e){super(...e),N(this,`_customFormulaService`,this.injector.get(V)),N(this,`_lexerTreeBuilder`,this.injector.get(A)),N(this,`id`,a.WHOLE),N(this,`title`,`dataValidation.whole.title`),N(this,`order`,10),N(this,`operators`,[n.BETWEEN,n.EQUAL,n.GREATER_THAN,n.GREATER_THAN_OR_EQUAL,n.LESS_THAN,n.LESS_THAN_OR_EQUAL,n.NOT_BETWEEN,n.NOT_EQUAL]),N(this,`scopes`,[`sheet`])}_isFormulaOrInt(e){return!y.isBlank(e)&&(x(e)||!Number.isNaN(+e)&&Number.isInteger(+e))}async isValidType(e,t,n){let{value:r}=e,i=Z(r);return!Number.isNaN(i)&&Number.isInteger(i)}transform(e,t,n){let{value:r}=e;return{...e,value:Z(r)}}_parseNumber(e){return e==null?NaN:+e}async parseFormula(e,t,n,r,i){let a=await this._customFormulaService.getCellFormulaValue(t,n,e.uid,r,i),o=await this._customFormulaService.getCellFormula2Value(t,n,e.uid,r,i),{formula1:s,formula2:c}=e,l=x(s)?a==null?void 0:a.v:s,u=x(c)?o==null?void 0:o.v:c,d=z(`${l}`)&&z(`${u}`);return{formula1:this._parseNumber(l),formula2:this._parseNumber(u),isFormulaValid:d}}validatorFormula(e,t,n){let r=e.operator;if(!r)return{success:!0};let i=y.isDefine(e.formula1)&&this._isFormulaOrInt(e.formula1),a=y.isDefine(e.formula2)&&this._isFormulaOrInt(e.formula2),o=rt.includes(r),s=this.localeService.t(`dataValidation.validFail.number`);return o?{success:i&&a,formula1:i?void 0:s,formula2:a?void 0:s}:{success:i,formula1:s}}generateRuleErrorMessage(e,t){if(!e.operator)return this.localeService.t(ot.NONE).replace(`{TYPE}`,this.titleStr);let{transformedFormula1:n,transformedFormula2:r}=W(this._lexerTreeBuilder,e,t);return`${this.localeService.t(ot[e.operator]).replace(Y,n==null?``:n).replace(X,r==null?``:r)}`}};let Lt=class extends re{constructor(e,t,n,r,i,a){super(),this._univerInstanceService=e,this._dataValidatorRegistryService=t,this._injector=n,this._selectionManagerService=r,this._sheetInterceptorService=i,this._sheetDataValidationModel=a,this._init()}_init(){this._registerValidators(),this._initCommandInterceptor()}_registerValidators(){[Nt,st,It,pt,at,$e,ft,Ft,Pt].forEach(e=>{let t=this._injector.createInstance(e);this.disposeWithMe(this._dataValidatorRegistryService.register(t)),this.disposeWithMe(me(()=>this._injector.delete(e)))})}_initCommandInterceptor(){this._sheetInterceptorService.interceptCommand({getMutations:e=>{if(e.id===De.id){var t;let e=this._univerInstanceService.getCurrentUnitForType(b.UNIVER_SHEET),n=e.getUnitId(),r=e.getActiveSheet();if(!r)throw Error(`No active sheet found`);let i=r.getSheetId(),a=(t=this._selectionManagerService.getCurrentSelections())==null?void 0:t.map(e=>e.range),o=this._sheetDataValidationModel.getRuleObjectMatrix(n,i).clone();a&&o.removeRange(a);let{redoMutations:s,undoMutations:c}=ht(n,i,o.diff(this._sheetDataValidationModel.getRules(n,i)),this._injector,`patched`);return{undos:c,redos:s}}return{undos:[],redos:[]}}})}};Lt=F([P(0,f),P(1,p(E)),P(2,p(m)),P(3,p(Pe)),P(4,p(Ne)),P(5,p(q))],Lt);let Q=class extends s{constructor(e,t,n,r){super(),this._univerInstanceService=e,this._sheetDataValidationModel=t,this._dataValidationCacheService=n,this._lifecycleService=r,this._initRecalculate()}_initRecalculate(){let e=e=>{if(e.length===0)return;let t=this._univerInstanceService.getCurrentUnitForType(b.UNIVER_SHEET),n=t==null?void 0:t.getActiveSheet(),r={};e.flat().forEach(e=>{r[e.unitId]||(r[e.unitId]={}),r[e.unitId][e.subUnitId]||(r[e.unitId][e.subUnitId]=[]);let t=this._univerInstanceService.getUnit(e.unitId,b.UNIVER_SHEET),n=t==null?void 0:t.getSheetBySheetId(e.subUnitId);n&&r[e.unitId][e.subUnitId].push(...e.ranges.map(e=>_.transformRange(e,n)))}),Object.entries(r).forEach(([e,r])=>{Object.entries(r).forEach(([r,i])=>{(t==null?void 0:t.getUnitId())===e&&(n==null?void 0:n.getSheetId())===r?this.validatorRanges(e,r,i):requestIdleCallback(()=>{this.validatorRanges(e,r,i)})})})};this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(ze(()=>this._lifecycleService.lifecycle$.pipe(Be(e=>e===g.Rendered)))).subscribe(e)),this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(Be(()=>this._lifecycleService.stage>=g.Rendered),ae(20)).subscribe(e))}async _validatorByCell(e,t,n,r){let a=e.getUnitId(),o=t.getSheetId();if(!y.isDefine(n)||!y.isDefine(r))throw Error(`row or col is not defined, row: ${n}, col: ${r}`);let s=n,c=r,l=t.getMergedCell(n,r);l&&(s=l.startRow,c=l.startColumn);let u=this._sheetDataValidationModel.getRuleByLocation(a,o,s,c);return u?new Promise(n=>{this._sheetDataValidationModel.validator(u,{unitId:a,subUnitId:o,row:s,col:c,worksheet:t,workbook:e},e=>{n(e)})}):i.VALID}async validatorCell(e,t,n,r){let i=this._univerInstanceService.getUnit(e,b.UNIVER_SHEET);if(!i)throw Error(`cannot find current workbook, unitId: ${e}`);let a=i.getSheetBySheetId(t);if(!a)throw Error(`cannot find current worksheet, sheetId: ${t}`);return this._validatorByCell(i,a,n,r)}async validatorRanges(e,t,n){if(!n.length)return Promise.resolve([]);let r=this._univerInstanceService.getUnit(e,b.UNIVER_SHEET);if(!r)throw Error(`cannot find current workbook, unitId: ${e}`);let a=r.getSheetBySheetId(t);if(!a)throw Error(`cannot find current worksheet, sheetId: ${t}`);let o=this._sheetDataValidationModel.getRules(e,t).map(e=>e.ranges).flat(),s=n.map(e=>o.map(t=>le(e,t))).flat().filter(Boolean),c=[],l=await Promise.all(s.map((e,t)=>{let n=[];for(let i=e.startRow;i<=e.endRow;i++)for(let o=e.startColumn;o<=e.endColumn;o++){n.push(this._validatorByCell(r,a,i,o));let e=a.getMergedCell(i,o);e&&c.push({resultRowIndex:t,resultColIndex:n.length-1,row:e.startRow,col:e.startColumn})}return Promise.all(n)}));return c.length&&c.forEach(({resultRowIndex:n,resultColIndex:r,row:a,col:o})=>{if(l[n][r]===i.VALIDATING){var s;l[n][r]=(s=this._dataValidationCacheService.getValue(e,t,a,o))==null?i.VALID:s}}),l}async validatorWorksheet(e,t){let n=this._univerInstanceService.getUnit(e,b.UNIVER_SHEET);if(!n)throw Error(`cannot find current workbook, unitId: ${e}`);let r=n.getSheetBySheetId(t);if(!r)throw Error(`cannot find current worksheet, sheetId: ${t}`);let i=this._sheetDataValidationModel.getRules(e,t);return await Promise.all(i.map(e=>Promise.all(e.ranges.map(e=>{let t=[];return _.foreach(e,(e,i)=>{t.push(this._validatorByCell(n,r,e,i))}),Promise.all(t)})))),this._dataValidationCacheService.ensureCache(e,t)}async validatorWorkbook(e){let t=this._sheetDataValidationModel.getSubUnitIds(e),n=await Promise.all(t.map(t=>this.validatorWorksheet(e,t))),r={};return n.forEach((e,n)=>{r[t[n]]=e}),r}getDataValidations(e,t,n){let r=this._sheetDataValidationModel.getRuleObjectMatrix(e,t),i=new Set;return n.forEach(e=>{_.foreach(e,(e,t)=>{let n=r.getValue(e,t);n&&i.add(n)})}),Array.from(i).map(n=>this._sheetDataValidationModel.getRuleById(e,t,n)).filter(Boolean)}getDataValidation(e,t,n){return this.getDataValidations(e,t,n)[0]}};Q=F([P(0,f),P(1,p(q)),P(2,p(I)),P(3,p(h))],Q);let $=class extends te{constructor(e=kt,t,n,r){super(),this._config=e,this._injector=t,this._commandService=n,this._configService=r;let{...i}=fe({},kt,this._config);this._configService.setConfig(Ot,i)}onStarting(){[[I],[G],[K],[V],[Q],[q],[Lt],[Tt],[Mt],[jt],[At]].forEach(e=>{this._injector.add(e)}),[_t,gt,vt,yt,Ct,xt,bt].forEach(e=>{this._commandService.registerCommand(e)}),this._injector.get(I),this._injector.get(Q),this._injector.get(Lt),this._injector.get(At),this._injector.get(jt)}onReady(){this._injector.get(Mt)}onRendered(){this._injector.get(Tt)}};N($,`pluginName`,wt),N($,`packageName`,Et),N($,`version`,Dt),N($,`type`,b.UNIVER_SHEET),$=F([o(Ue,ge),P(1,p(m)),P(2,c),P(3,l)],$);function Rt(e){let t=e.get(Pe).getCurrentSelections().map(e=>e.range);return{uid:ce(6),type:a.DECIMAL,operator:n.EQUAL,formula1:`100`,ranges:t==null?[{startColumn:0,endColumn:0,startRow:0,endRow:0}]:t}}const zt=`data-validation.custom-formula-input`,Bt=`data-validation.formula-input`,Vt=`data-validation.list-formula-input`,Ht=`data-validation.checkbox-formula-input`;export{_t as AddSheetDataValidationCommand,Bt as BASE_FORMULA_INPUT_NAME,Xe as CHECKBOX_FORMULA_1,Ze as CHECKBOX_FORMULA_2,Ht as CHECKBOX_FORMULA_INPUT_NAME,zt as CUSTOM_FORMULA_INPUT_NAME,$e as CheckboxValidator,bt as ClearRangeDataValidationCommand,wt as DATA_VALIDATION_PLUGIN_NAME,I as DataValidationCacheService,V as DataValidationCustomFormulaService,Tt as DataValidationFormulaController,K as DataValidationFormulaService,G as DataValidationListCacheService,at as DateValidator,Vt as LIST_FORMULA_INPUT_NAME,Ft as ListMultipleValidator,ft as ListValidator,xt as RemoveSheetAllDataValidationCommand,Ct as RemoveSheetDataValidationCommand,q as SheetDataValidationModel,Q as SheetsDataValidationValidatorService,$ as UniverSheetsDataValidationPlugin,yt as UpdateSheetDataValidationOptionsCommand,gt as UpdateSheetDataValidationRangeCommand,vt as UpdateSheetDataValidationSettingCommand,Rt as createDefaultNewRule,U as deserializeListOptions,Z as getCellValueNumber,H as getCellValueOrigin,Je as getDataValidationCellValue,ht as getDataValidationDiffMutations,R as getFormulaCellData,L as getFormulaResult,W as getTransformedFormula,z as isLegalFormulaResult,qe as serializeListOptions,J as transformCheckboxValue};
1
+ import { CellValueType, CommandType, DataValidationOperator, DataValidationRenderMode, DataValidationStatus, DataValidationType, DependentOn, Disposable, ICommandService, IConfigService, IPermissionService, IUndoRedoService, IUniverInstanceService, Inject, Injector, LifecycleService, LifecycleStages, ObjectMatrix, Plugin, RBush, Range, Rectangle, RxDisposable, Tools, UniverInstanceType, WrapStrategy, bufferDebounceTime, dateKit, debounce, generateRandomId, getIntersectRange, getOriginCellValue, isFormulaString, isRangesEqual, merge, numfmt, sequenceExecute, toDisposable } from "@univerjs/core";
2
+ import { AddDataValidationMutation, BaseDataValidator, DataValidationModel, DataValidatorRegistryService, RemoveDataValidationMutation, TextLengthErrorTitleMap, UniverDataValidationPlugin, UpdateDataValidationMutation, UpdateRuleType, getRuleOptions, getRuleSetting } from "@univerjs/data-validation";
3
+ import { ERROR_TYPE_SET, LexerTreeBuilder, OtherFormulaBizType, RegisterOtherFormulaService, deserializeRangeWithSheet, deserializeRangeWithSheetWithCache, isReferenceString, operatorToken, sequenceNodeType } from "@univerjs/engine-formula";
4
+ import { ClearSelectionAllCommand, CopySheetCommand, RefRangeService, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService, SheetsSelectionsService, WorksheetViewPermission, getSheetCommandTarget, handleCommonDefaultRangeChangeWithEffectRefCommands } from "@univerjs/sheets";
5
+ import { Subject, bufferWhen, filter } from "rxjs";
6
+ import { UnitAction } from "@univerjs/protocol";
7
+ import { FormulaRefRangeService, UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
8
+
9
+ //#region \0@oxc-project+runtime@0.124.0/helpers/typeof.js
10
+ function _typeof(o) {
11
+ "@babel/helpers - typeof";
12
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
13
+ return typeof o;
14
+ } : function(o) {
15
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
16
+ }, _typeof(o);
17
+ }
18
+
19
+ //#endregion
20
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPrimitive.js
21
+ function toPrimitive(t, r) {
22
+ if ("object" != _typeof(t) || !t) return t;
23
+ var e = t[Symbol.toPrimitive];
24
+ if (void 0 !== e) {
25
+ var i = e.call(t, r || "default");
26
+ if ("object" != _typeof(i)) return i;
27
+ throw new TypeError("@@toPrimitive must return a primitive value.");
28
+ }
29
+ return ("string" === r ? String : Number)(t);
30
+ }
31
+
32
+ //#endregion
33
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPropertyKey.js
34
+ function toPropertyKey(t) {
35
+ var i = toPrimitive(t, "string");
36
+ return "symbol" == _typeof(i) ? i : i + "";
37
+ }
38
+
39
+ //#endregion
40
+ //#region \0@oxc-project+runtime@0.124.0/helpers/defineProperty.js
41
+ function _defineProperty(e, r, t) {
42
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
43
+ value: t,
44
+ enumerable: !0,
45
+ configurable: !0,
46
+ writable: !0
47
+ }) : e[r] = t, e;
48
+ }
49
+
50
+ //#endregion
51
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
52
+ function __decorateParam(paramIndex, decorator) {
53
+ return function(target, key) {
54
+ decorator(target, key, paramIndex);
55
+ };
56
+ }
57
+
58
+ //#endregion
59
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
60
+ function __decorate(decorators, target, key, desc) {
61
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
62
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
63
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
64
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
65
+ }
66
+
67
+ //#endregion
68
+ //#region src/services/dv-cache.service.ts
69
+ let DataValidationCacheService = class DataValidationCacheService extends Disposable {
70
+ constructor(_commandService, _univerInstanceService, _sheetDataValidationModel) {
71
+ super();
72
+ this._commandService = _commandService;
73
+ this._univerInstanceService = _univerInstanceService;
74
+ this._sheetDataValidationModel = _sheetDataValidationModel;
75
+ _defineProperty(this, "_cacheMatrix", /* @__PURE__ */ new Map());
76
+ _defineProperty(this, "_dirtyRanges$", new Subject());
77
+ _defineProperty(this, "dirtyRanges$", this._dirtyRanges$.asObservable());
78
+ this._initDirtyRanges();
79
+ this._initSheetRemove();
80
+ }
81
+ _initDirtyRanges() {
82
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
83
+ if (commandInfo.id === SetRangeValuesMutation.id && !(options === null || options === void 0 ? void 0 : options.onlyLocal)) {
84
+ const { cellValue, unitId, subUnitId } = commandInfo.params;
85
+ if (cellValue) {
86
+ const range = new ObjectMatrix(cellValue).getDataRange();
87
+ if (range.endRow === -1) return;
88
+ const intersectsRanges = this._sheetDataValidationModel.getRules(unitId, subUnitId).map((rule) => rule.ranges).flat().map((ruleRange) => getIntersectRange(ruleRange, range)).filter(Boolean);
89
+ if (intersectsRanges.length) this.markRangeDirty(unitId, subUnitId, intersectsRanges, true);
90
+ }
91
+ }
92
+ }));
93
+ }
94
+ _initSheetRemove() {
95
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {
96
+ if (commandInfo.id === RemoveSheetMutation.id) {
97
+ var _this$_cacheMatrix$ge;
98
+ const { unitId, subUnitId } = commandInfo.params;
99
+ (_this$_cacheMatrix$ge = this._cacheMatrix.get(unitId)) === null || _this$_cacheMatrix$ge === void 0 || _this$_cacheMatrix$ge.delete(subUnitId);
100
+ }
101
+ }));
102
+ this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe((univerInstance) => {
103
+ if (univerInstance.type === UniverInstanceType.UNIVER_SHEET) this._cacheMatrix.delete(univerInstance.getUnitId());
104
+ }));
105
+ }
106
+ _ensureCache(unitId, subUnitId) {
107
+ let unitMap = this._cacheMatrix.get(unitId);
108
+ if (!unitMap) {
109
+ unitMap = /* @__PURE__ */ new Map();
110
+ this._cacheMatrix.set(unitId, unitMap);
111
+ }
112
+ let cacheMatrix = unitMap.get(subUnitId);
113
+ if (!cacheMatrix) {
114
+ cacheMatrix = new ObjectMatrix();
115
+ unitMap.set(subUnitId, cacheMatrix);
116
+ }
117
+ return cacheMatrix;
118
+ }
119
+ ensureCache(unitId, subUnitId) {
120
+ return this._ensureCache(unitId, subUnitId);
121
+ }
122
+ addRule(unitId, subUnitId, rule) {
123
+ this.markRangeDirty(unitId, subUnitId, rule.ranges);
124
+ }
125
+ removeRule(unitId, subUnitId, rule) {
126
+ this._deleteRange(unitId, subUnitId, rule.ranges);
127
+ }
128
+ markRangeDirty(unitId, subUnitId, ranges, isSetRange) {
129
+ const cache = this._ensureCache(unitId, subUnitId);
130
+ ranges.forEach((range) => {
131
+ Range.foreach(range, (row, col) => {
132
+ if (cache.getValue(row, col) !== void 0) cache.setValue(row, col, void 0);
133
+ });
134
+ });
135
+ this._dirtyRanges$.next({
136
+ unitId,
137
+ subUnitId,
138
+ ranges,
139
+ isSetRange
140
+ });
141
+ }
142
+ _deleteRange(unitId, subUnitId, ranges) {
143
+ const cache = this._ensureCache(unitId, subUnitId);
144
+ ranges.forEach((range) => {
145
+ Range.foreach(range, (row, col) => {
146
+ cache.realDeleteValue(row, col);
147
+ });
148
+ });
149
+ this._dirtyRanges$.next({
150
+ unitId,
151
+ subUnitId,
152
+ ranges
153
+ });
154
+ }
155
+ getValue(unitId, subUnitId, row, col) {
156
+ return this._ensureCache(unitId, subUnitId).getValue(row, col);
157
+ }
158
+ };
159
+ DataValidationCacheService = __decorate([
160
+ __decorateParam(0, Inject(ICommandService)),
161
+ __decorateParam(1, Inject(IUniverInstanceService)),
162
+ __decorateParam(2, Inject(DataValidationModel))
163
+ ], DataValidationCacheService);
164
+
165
+ //#endregion
166
+ //#region src/utils/formula.ts
167
+ function getFormulaResult(result) {
168
+ var _result$;
169
+ return result === null || result === void 0 || (_result$ = result[0]) === null || _result$ === void 0 || (_result$ = _result$[0]) === null || _result$ === void 0 ? void 0 : _result$.v;
170
+ }
171
+ function getFormulaCellData(result) {
172
+ var _result$2;
173
+ return result === null || result === void 0 || (_result$2 = result[0]) === null || _result$2 === void 0 ? void 0 : _result$2[0];
174
+ }
175
+ function isLegalFormulaResult(res) {
176
+ return !ERROR_TYPE_SET.has(res);
177
+ }
178
+ /**
179
+ * Judge if the data-validation's formula need to be offseted by ranges
180
+ */
181
+ function shouldOffsetFormulaByRange(type, validatorRegistryService) {
182
+ var _validator$offsetForm;
183
+ const validator = validatorRegistryService.getValidatorItem(type);
184
+ return (_validator$offsetForm = validator === null || validator === void 0 ? void 0 : validator.offsetFormulaByRange) !== null && _validator$offsetForm !== void 0 ? _validator$offsetForm : false;
185
+ }
186
+
187
+ //#endregion
188
+ //#region src/services/dv-custom-formula.service.ts
189
+ let DataValidationCustomFormulaService = class DataValidationCustomFormulaService extends Disposable {
190
+ constructor(_instanceSrv, _registerOtherFormulaService, _dataValidationModel, _dataValidationCacheService, _validatorRegistryService) {
191
+ super();
192
+ this._instanceSrv = _instanceSrv;
193
+ this._registerOtherFormulaService = _registerOtherFormulaService;
194
+ this._dataValidationModel = _dataValidationModel;
195
+ this._dataValidationCacheService = _dataValidationCacheService;
196
+ this._validatorRegistryService = _validatorRegistryService;
197
+ _defineProperty(this, "_ruleFormulaMap", /* @__PURE__ */ new Map());
198
+ _defineProperty(this, "_ruleFormulaMap2", /* @__PURE__ */ new Map());
199
+ this._initFormulaResultHandler();
200
+ this._initDirtyRanges();
201
+ }
202
+ dispose() {
203
+ super.dispose();
204
+ this._ruleFormulaMap.clear();
205
+ this._ruleFormulaMap2.clear();
206
+ }
207
+ _initFormulaResultHandler() {
208
+ this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe((resultMap) => {
209
+ for (const unitId in resultMap) {
210
+ const unitMap = resultMap[unitId];
211
+ if (this._instanceSrv.getUnitType(unitId) !== UniverInstanceType.UNIVER_SHEET) continue;
212
+ for (const subUnitId in unitMap) {
213
+ const results = unitMap[subUnitId];
214
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
215
+ results.forEach((result) => {
216
+ var _result$extra, _result$extra2;
217
+ const ruleInfo = ruleFormulaMap.get((_result$extra = result.extra) === null || _result$extra === void 0 ? void 0 : _result$extra.ruleId);
218
+ const rule = this._dataValidationModel.getRuleById(unitId, subUnitId, (_result$extra2 = result.extra) === null || _result$extra2 === void 0 ? void 0 : _result$extra2.ruleId);
219
+ if (rule && ruleInfo) this._dataValidationCacheService.markRangeDirty(unitId, subUnitId, rule.ranges);
220
+ });
221
+ }
222
+ }
223
+ }));
224
+ }
225
+ _ensureMaps(unitId, subUnitId) {
226
+ let ruleFormulaUnitMap = this._ruleFormulaMap.get(unitId);
227
+ let ruleFormulaUnitMap2 = this._ruleFormulaMap2.get(unitId);
228
+ if (!ruleFormulaUnitMap) {
229
+ ruleFormulaUnitMap = /* @__PURE__ */ new Map();
230
+ this._ruleFormulaMap.set(unitId, ruleFormulaUnitMap);
231
+ }
232
+ if (!ruleFormulaUnitMap2) {
233
+ ruleFormulaUnitMap2 = /* @__PURE__ */ new Map();
234
+ this._ruleFormulaMap2.set(unitId, ruleFormulaUnitMap2);
235
+ }
236
+ let ruleFormulaMap = ruleFormulaUnitMap.get(subUnitId);
237
+ if (!ruleFormulaMap) {
238
+ ruleFormulaMap = /* @__PURE__ */ new Map();
239
+ ruleFormulaUnitMap.set(subUnitId, ruleFormulaMap);
240
+ }
241
+ let ruleFormulaMap2 = ruleFormulaUnitMap2.get(subUnitId);
242
+ if (!ruleFormulaMap2) {
243
+ ruleFormulaMap2 = /* @__PURE__ */ new Map();
244
+ ruleFormulaUnitMap2.set(subUnitId, ruleFormulaMap2);
245
+ }
246
+ return {
247
+ ruleFormulaMap,
248
+ ruleFormulaMap2
249
+ };
250
+ }
251
+ _registerFormula(unitId, subUnitId, ruleId, formulaString, ranges) {
252
+ return this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formulaString, ranges, { ruleId }, OtherFormulaBizType.DATA_VALIDATION_CUSTOM, ruleId);
253
+ }
254
+ _handleDirtyRanges(unitId, subUnitId, ranges) {
255
+ this._dataValidationModel.getRules(unitId, subUnitId).forEach((rule) => {
256
+ const ruleRanges = rule.ranges;
257
+ if (Rectangle.doAnyRangesIntersect(ruleRanges, ranges)) this.makeRuleDirty(unitId, subUnitId, rule.uid);
258
+ });
259
+ }
260
+ _initDirtyRanges() {
261
+ this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.subscribe((data) => {
262
+ if (data.isSetRange) this._handleDirtyRanges(data.unitId, data.subUnitId, data.ranges);
263
+ }));
264
+ }
265
+ deleteByRuleId(unitId, subUnitId, ruleId) {
266
+ const { ruleFormulaMap, ruleFormulaMap2 } = this._ensureMaps(unitId, subUnitId);
267
+ const rule = this._dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
268
+ const formulaInfo = ruleFormulaMap.get(ruleId);
269
+ if (!rule || !formulaInfo) return;
270
+ const current = ruleFormulaMap.get(ruleId);
271
+ if (current) {
272
+ ruleFormulaMap.delete(ruleId);
273
+ this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, [current.formulaId]);
274
+ }
275
+ const current2 = ruleFormulaMap2.get(ruleId);
276
+ if (current2) {
277
+ ruleFormulaMap2.delete(ruleId);
278
+ this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, [current2.formulaId]);
279
+ }
280
+ }
281
+ _addFormulaByRange(unitId, subUnitId, ruleId, formula, formula2, ranges) {
282
+ const { ruleFormulaMap, ruleFormulaMap2 } = this._ensureMaps(unitId, subUnitId);
283
+ const originRow = ranges[0].startRow;
284
+ const originCol = ranges[0].startColumn;
285
+ if (formula && isFormulaString(formula)) {
286
+ const formulaId = this._registerFormula(unitId, subUnitId, ruleId, formula, ranges);
287
+ ruleFormulaMap.set(ruleId, {
288
+ formula,
289
+ originCol,
290
+ originRow,
291
+ formulaId
292
+ });
293
+ }
294
+ if (formula2 && isFormulaString(formula2)) {
295
+ const formulaId2 = this._registerFormula(unitId, subUnitId, ruleId, formula2, ranges);
296
+ ruleFormulaMap2.set(ruleId, {
297
+ formula: formula2,
298
+ originCol,
299
+ originRow,
300
+ formulaId: formulaId2
301
+ });
302
+ }
303
+ }
304
+ addRule(unitId, subUnitId, rule) {
305
+ if (shouldOffsetFormulaByRange(rule.type, this._validatorRegistryService)) {
306
+ const { ranges, formula1, formula2, uid: ruleId } = rule;
307
+ this._addFormulaByRange(unitId, subUnitId, ruleId, formula1, formula2, ranges);
308
+ }
309
+ }
310
+ async getCellFormulaValue(unitId, subUnitId, ruleId, row, column) {
311
+ var _result$result;
312
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
313
+ const current = ruleFormulaMap.get(ruleId);
314
+ if (!current) return Promise.resolve(void 0);
315
+ const result = await this._registerOtherFormulaService.getFormulaValue(unitId, subUnitId, current.formulaId);
316
+ const { originRow, originCol } = current;
317
+ const offsetRow = row - originRow;
318
+ const offsetCol = column - originCol;
319
+ return getFormulaCellData(result === null || result === void 0 || (_result$result = result.result) === null || _result$result === void 0 || (_result$result = _result$result[offsetRow]) === null || _result$result === void 0 ? void 0 : _result$result[offsetCol]);
320
+ }
321
+ async getCellFormula2Value(unitId, subUnitId, ruleId, row, column) {
322
+ var _result$result2;
323
+ const { ruleFormulaMap2 } = this._ensureMaps(unitId, subUnitId);
324
+ const current = ruleFormulaMap2.get(ruleId);
325
+ if (!current) return Promise.resolve(void 0);
326
+ const result = await this._registerOtherFormulaService.getFormulaValue(unitId, subUnitId, current.formulaId);
327
+ const { originRow, originCol } = current;
328
+ const offsetRow = row - originRow;
329
+ const offsetCol = column - originCol;
330
+ return getFormulaCellData(result === null || result === void 0 || (_result$result2 = result.result) === null || _result$result2 === void 0 || (_result$result2 = _result$result2[offsetRow]) === null || _result$result2 === void 0 ? void 0 : _result$result2[offsetCol]);
331
+ }
332
+ getCellFormulaValueSync(unitId, subUnitId, ruleId, row, column) {
333
+ var _result$result3;
334
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
335
+ const current = ruleFormulaMap.get(ruleId);
336
+ if (!current) return;
337
+ const result = this._registerOtherFormulaService.getFormulaValueSync(unitId, subUnitId, current.formulaId);
338
+ const { originRow, originCol } = current;
339
+ const offsetRow = row - originRow;
340
+ const offsetCol = column - originCol;
341
+ return getFormulaCellData(result === null || result === void 0 || (_result$result3 = result.result) === null || _result$result3 === void 0 || (_result$result3 = _result$result3[offsetRow]) === null || _result$result3 === void 0 ? void 0 : _result$result3[offsetCol]);
342
+ }
343
+ getCellFormula2ValueSync(unitId, subUnitId, ruleId, row, column) {
344
+ var _result$result4;
345
+ const { ruleFormulaMap2 } = this._ensureMaps(unitId, subUnitId);
346
+ const current = ruleFormulaMap2.get(ruleId);
347
+ if (!current) return;
348
+ const result = this._registerOtherFormulaService.getFormulaValueSync(unitId, subUnitId, current.formulaId);
349
+ const { originRow, originCol } = current;
350
+ const offsetRow = row - originRow;
351
+ const offsetCol = column - originCol;
352
+ return getFormulaCellData(result === null || result === void 0 || (_result$result4 = result.result) === null || _result$result4 === void 0 || (_result$result4 = _result$result4[offsetRow]) === null || _result$result4 === void 0 ? void 0 : _result$result4[offsetCol]);
353
+ }
354
+ getRuleFormulaInfo(unitId, subUnitId, ruleId) {
355
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
356
+ return ruleFormulaMap.get(ruleId);
357
+ }
358
+ makeRuleDirty(unitId, subUnitId, ruleId) {
359
+ var _this$_ruleFormulaMap, _this$_ruleFormulaMap2;
360
+ const formula1 = (_this$_ruleFormulaMap = this._ruleFormulaMap.get(unitId)) === null || _this$_ruleFormulaMap === void 0 || (_this$_ruleFormulaMap = _this$_ruleFormulaMap.get(subUnitId)) === null || _this$_ruleFormulaMap === void 0 ? void 0 : _this$_ruleFormulaMap.get(ruleId);
361
+ const formula2 = (_this$_ruleFormulaMap2 = this._ruleFormulaMap2.get(unitId)) === null || _this$_ruleFormulaMap2 === void 0 || (_this$_ruleFormulaMap2 = _this$_ruleFormulaMap2.get(subUnitId)) === null || _this$_ruleFormulaMap2 === void 0 ? void 0 : _this$_ruleFormulaMap2.get(ruleId);
362
+ if (formula1) this._registerOtherFormulaService.markFormulaDirty(unitId, subUnitId, formula1.formulaId);
363
+ if (formula2) this._registerOtherFormulaService.markFormulaDirty(unitId, subUnitId, formula2.formulaId);
364
+ }
365
+ };
366
+ DataValidationCustomFormulaService = __decorate([
367
+ __decorateParam(0, IUniverInstanceService),
368
+ __decorateParam(1, Inject(RegisterOtherFormulaService)),
369
+ __decorateParam(2, Inject(DataValidationModel)),
370
+ __decorateParam(3, Inject(DataValidationCacheService)),
371
+ __decorateParam(4, Inject(DataValidatorRegistryService))
372
+ ], DataValidationCustomFormulaService);
373
+
374
+ //#endregion
375
+ //#region src/utils/get-cell-data-origin.ts
376
+ function getCellValueOrigin(cell) {
377
+ return getOriginCellValue(cell);
378
+ }
379
+ function getStringCellValue(cell) {
380
+ var _getCellValueOrigin;
381
+ return String((_getCellValueOrigin = getCellValueOrigin(cell)) !== null && _getCellValueOrigin !== void 0 ? _getCellValueOrigin : "");
382
+ }
383
+
384
+ //#endregion
385
+ //#region src/validators/util.ts
386
+ function serializeListOptions(options) {
387
+ return options.filter(Boolean).join(",");
388
+ }
389
+ function deserializeListOptions(optionsStr) {
390
+ return optionsStr.split(",").filter(Boolean);
391
+ }
392
+ function getDataValidationCellValue(cellData) {
393
+ const cellValue = getCellValueOrigin(cellData);
394
+ if (cellValue === void 0 || cellValue === null) return "";
395
+ return cellValue.toString();
396
+ }
397
+ function getTransformedFormula(lexerTreeBuilder, rule, position) {
398
+ const { formula1, formula2 } = rule;
399
+ const originStartRow = rule.ranges[0].startRow;
400
+ const originStartColumn = rule.ranges[0].startColumn;
401
+ const offsetRow = position.row - originStartRow;
402
+ const offsetColumn = position.col - originStartColumn;
403
+ return {
404
+ transformedFormula1: isFormulaString(formula1) ? lexerTreeBuilder.moveFormulaRefOffset(formula1, offsetColumn, offsetRow, true) : formula1,
405
+ transformedFormula2: isFormulaString(formula2) ? lexerTreeBuilder.moveFormulaRefOffset(formula2, offsetColumn, offsetRow, true) : formula2
406
+ };
407
+ }
408
+
409
+ //#endregion
410
+ //#region src/services/dv-list-cache.service.ts
411
+ let DataValidationListCacheService = class DataValidationListCacheService extends Disposable {
412
+ constructor(_injector, _dataValidationModel) {
413
+ super();
414
+ this._injector = _injector;
415
+ this._dataValidationModel = _dataValidationModel;
416
+ _defineProperty(this, "_cache", /* @__PURE__ */ new Map());
417
+ this._initRuleChangeListener();
418
+ }
419
+ _initRuleChangeListener() {
420
+ this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe((change) => {
421
+ if (change.type === "remove" || change.type === "update") this.markRuleDirty(change.unitId, change.subUnitId, change.rule.uid);
422
+ }));
423
+ }
424
+ /**
425
+ * Get cached list data or compute and cache it if not exists.
426
+ */
427
+ getOrCompute(unitId, subUnitId, rule) {
428
+ const cached = this.getCache(unitId, subUnitId, rule.uid);
429
+ if (cached) return cached;
430
+ const results = this._injector.get(DataValidationFormulaService).getRuleFormulaResultSync(unitId, subUnitId, rule.uid);
431
+ return this.computeAndCache(unitId, subUnitId, rule, results);
432
+ }
433
+ _ensureCache(unitId, subUnitId) {
434
+ let unitMap = this._cache.get(unitId);
435
+ if (!unitMap) {
436
+ unitMap = /* @__PURE__ */ new Map();
437
+ this._cache.set(unitId, unitMap);
438
+ }
439
+ let subUnitMap = unitMap.get(subUnitId);
440
+ if (!subUnitMap) {
441
+ subUnitMap = /* @__PURE__ */ new Map();
442
+ unitMap.set(subUnitId, subUnitMap);
443
+ }
444
+ return subUnitMap;
445
+ }
446
+ /**
447
+ * Get cached list data for a rule. Returns undefined if not cached.
448
+ */
449
+ getCache(unitId, subUnitId, ruleId) {
450
+ var _this$_cache$get;
451
+ return (_this$_cache$get = this._cache.get(unitId)) === null || _this$_cache$get === void 0 || (_this$_cache$get = _this$_cache$get.get(subUnitId)) === null || _this$_cache$get === void 0 ? void 0 : _this$_cache$get.get(ruleId);
452
+ }
453
+ /**
454
+ * Set cache for a rule.
455
+ */
456
+ setCache(unitId, subUnitId, ruleId, item) {
457
+ this._ensureCache(unitId, subUnitId).set(ruleId, item);
458
+ }
459
+ /**
460
+ * Mark a rule's cache as dirty (invalidate it).
461
+ * Called when formula results change.
462
+ */
463
+ markRuleDirty(unitId, subUnitId, ruleId) {
464
+ var _this$_cache$get2;
465
+ (_this$_cache$get2 = this._cache.get(unitId)) === null || _this$_cache$get2 === void 0 || (_this$_cache$get2 = _this$_cache$get2.get(subUnitId)) === null || _this$_cache$get2 === void 0 || _this$_cache$get2.delete(ruleId);
466
+ }
467
+ /**
468
+ * Clear all caches.
469
+ */
470
+ clear() {
471
+ this._cache.clear();
472
+ }
473
+ /**
474
+ * Compute list data from formula result and cache it.
475
+ */
476
+ computeAndCache(unitId, subUnitId, rule, formulaResult) {
477
+ var _formulaResult$;
478
+ const { formula1 = "", formula2 = "" } = rule;
479
+ const list = isFormulaString(formula1) ? this._getRuleFormulaResultSet(formulaResult === null || formulaResult === void 0 || (_formulaResult$ = formulaResult[0]) === null || _formulaResult$ === void 0 || (_formulaResult$ = _formulaResult$.result) === null || _formulaResult$ === void 0 || (_formulaResult$ = _formulaResult$[0]) === null || _formulaResult$ === void 0 ? void 0 : _formulaResult$[0]) : deserializeListOptions(formula1);
480
+ const colorList = formula2.split(",");
481
+ const listWithColor = list.map((label, i) => ({
482
+ label,
483
+ color: colorList[i] || ""
484
+ }));
485
+ const colorMap = {};
486
+ for (const item of listWithColor) if (item.color) colorMap[item.label] = item.color;
487
+ const cacheItem = {
488
+ list,
489
+ listWithColor,
490
+ colorMap,
491
+ set: new Set(list)
492
+ };
493
+ this.setCache(unitId, subUnitId, rule.uid, cacheItem);
494
+ return cacheItem;
495
+ }
496
+ /**
497
+ * Extract string list from formula result cells.
498
+ */
499
+ _getRuleFormulaResultSet(result) {
500
+ if (!result) return [];
501
+ const resultSet = /* @__PURE__ */ new Set();
502
+ for (let i = 0, rowLen = result.length; i < rowLen; i++) {
503
+ const row = result[i];
504
+ if (!row) continue;
505
+ for (let j = 0, colLen = row.length; j < colLen; j++) {
506
+ const cell = row[j];
507
+ const value = getCellValueOrigin(cell);
508
+ if (value !== null && value !== void 0) {
509
+ var _cell$s;
510
+ if (typeof value !== "string" && typeof (cell === null || cell === void 0 ? void 0 : cell.s) === "object" && ((_cell$s = cell.s) === null || _cell$s === void 0 || (_cell$s = _cell$s.n) === null || _cell$s === void 0 ? void 0 : _cell$s.pattern)) {
511
+ resultSet.add(numfmt.format(cell.s.n.pattern, value, { throws: false }));
512
+ continue;
513
+ }
514
+ const valueStr = typeof value === "string" ? value : String(value);
515
+ if (isLegalFormulaResult(valueStr)) resultSet.add(valueStr);
516
+ }
517
+ }
518
+ }
519
+ return [...resultSet];
520
+ }
521
+ };
522
+ DataValidationListCacheService = __decorate([__decorateParam(0, Inject(Injector)), __decorateParam(1, Inject(DataValidationModel))], DataValidationListCacheService);
523
+
524
+ //#endregion
525
+ //#region src/services/dv-formula.service.ts
526
+ let DataValidationFormulaService = class DataValidationFormulaService extends Disposable {
527
+ constructor(_instanceService, _registerOtherFormulaService, _dataValidationCacheService, _dataValidationModel, _validatorRegistryService, _listCacheService) {
528
+ super();
529
+ this._instanceService = _instanceService;
530
+ this._registerOtherFormulaService = _registerOtherFormulaService;
531
+ this._dataValidationCacheService = _dataValidationCacheService;
532
+ this._dataValidationModel = _dataValidationModel;
533
+ this._validatorRegistryService = _validatorRegistryService;
534
+ this._listCacheService = _listCacheService;
535
+ _defineProperty(this, "_formulaRuleMap", /* @__PURE__ */ new Map());
536
+ this._initFormulaResultHandler();
537
+ }
538
+ _initFormulaResultHandler() {
539
+ this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe((resultMap) => {
540
+ for (const unitId in resultMap) {
541
+ const unitMap = resultMap[unitId];
542
+ if (this._instanceService.getUnitType(unitId) !== UniverInstanceType.UNIVER_SHEET) continue;
543
+ for (const subUnitId in unitMap) {
544
+ const results = unitMap[subUnitId];
545
+ const formulaMap = this._ensureRuleFormulaMap(unitId, subUnitId);
546
+ results.forEach((result) => {
547
+ var _result$extra;
548
+ const ruleId = (_result$extra = result.extra) === null || _result$extra === void 0 ? void 0 : _result$extra.ruleId;
549
+ if (ruleId && formulaMap.get(ruleId)) {
550
+ const rule = this._dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
551
+ if (rule) {
552
+ this._listCacheService.markRuleDirty(unitId, subUnitId, ruleId);
553
+ this._dataValidationCacheService.markRangeDirty(unitId, subUnitId, rule.ranges);
554
+ }
555
+ }
556
+ });
557
+ }
558
+ }
559
+ }));
560
+ }
561
+ _ensureRuleFormulaMap(unitId, subUnitId) {
562
+ let unitMap = this._formulaRuleMap.get(unitId);
563
+ if (!unitMap) {
564
+ unitMap = /* @__PURE__ */ new Map();
565
+ this._formulaRuleMap.set(unitId, unitMap);
566
+ }
567
+ let subUnitMap = unitMap.get(subUnitId);
568
+ if (!subUnitMap) {
569
+ subUnitMap = /* @__PURE__ */ new Map();
570
+ unitMap.set(subUnitId, subUnitMap);
571
+ }
572
+ return subUnitMap;
573
+ }
574
+ _registerSingleFormula(unitId, subUnitId, formula, ruleId) {
575
+ return this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formula, [{
576
+ startColumn: 0,
577
+ endColumn: 0,
578
+ startRow: 0,
579
+ endRow: 0
580
+ }], { ruleId }, OtherFormulaBizType.DATA_VALIDATION, ruleId);
581
+ }
582
+ addRule(unitId, subUnitId, rule) {
583
+ if (!shouldOffsetFormulaByRange(rule.type, this._validatorRegistryService) && rule.type !== DataValidationType.CHECKBOX) {
584
+ const { formula1, formula2, uid: ruleId } = rule;
585
+ const isFormula1Legal = isFormulaString(formula1);
586
+ const isFormula2Legal = isFormulaString(formula2);
587
+ if (!isFormula1Legal && !isFormula2Legal) return;
588
+ const formulaRuleMap = this._ensureRuleFormulaMap(unitId, subUnitId);
589
+ const item = [void 0, void 0];
590
+ if (isFormula1Legal) item[0] = {
591
+ id: this._registerSingleFormula(unitId, subUnitId, formula1, ruleId),
592
+ text: formula1
593
+ };
594
+ if (isFormula2Legal) item[1] = {
595
+ id: this._registerSingleFormula(unitId, subUnitId, formula2, ruleId),
596
+ text: formula2
597
+ };
598
+ formulaRuleMap.set(ruleId, item);
599
+ }
600
+ }
601
+ removeRule(unitId, subUnitId, ruleId) {
602
+ const item = this._ensureRuleFormulaMap(unitId, subUnitId).get(ruleId);
603
+ if (!item) return;
604
+ const [formula1, formula2] = item;
605
+ const idList = [formula1 === null || formula1 === void 0 ? void 0 : formula1.id, formula2 === null || formula2 === void 0 ? void 0 : formula2.id].filter(Boolean);
606
+ idList.length && this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, idList);
607
+ }
608
+ getRuleFormulaResult(unitId, subUnitId, ruleId) {
609
+ const formulaInfo = this._ensureRuleFormulaMap(unitId, subUnitId).get(ruleId);
610
+ if (!formulaInfo) return Promise.resolve(null);
611
+ const getResult = async (info) => info && this._registerOtherFormulaService.getFormulaValue(unitId, subUnitId, info.id);
612
+ return Promise.all([getResult(formulaInfo[0]), getResult(formulaInfo[1])]);
613
+ }
614
+ getRuleFormulaResultSync(unitId, subUnitId, ruleId) {
615
+ const formulaInfo = this._ensureRuleFormulaMap(unitId, subUnitId).get(ruleId);
616
+ if (!formulaInfo) return;
617
+ return formulaInfo.map((i) => {
618
+ if (i) return this._registerOtherFormulaService.getFormulaValueSync(unitId, subUnitId, i.id);
619
+ });
620
+ }
621
+ getRuleFormulaInfo(unitId, subUnitId, ruleId) {
622
+ return this._ensureRuleFormulaMap(unitId, subUnitId).get(ruleId);
623
+ }
624
+ };
625
+ DataValidationFormulaService = __decorate([
626
+ __decorateParam(0, IUniverInstanceService),
627
+ __decorateParam(1, Inject(RegisterOtherFormulaService)),
628
+ __decorateParam(2, Inject(DataValidationCacheService)),
629
+ __decorateParam(3, Inject(DataValidationModel)),
630
+ __decorateParam(4, Inject(DataValidatorRegistryService)),
631
+ __decorateParam(5, Inject(DataValidationListCacheService))
632
+ ], DataValidationFormulaService);
633
+
634
+ //#endregion
635
+ //#region src/models/rule-matrix.ts
636
+ var RuleMatrix = class RuleMatrix {
637
+ constructor(value, _unitId, _subUnitId, _univerInstanceService, _disableTree = false) {
638
+ this._unitId = _unitId;
639
+ this._subUnitId = _subUnitId;
640
+ this._univerInstanceService = _univerInstanceService;
641
+ this._disableTree = _disableTree;
642
+ _defineProperty(this, "_map", void 0);
643
+ _defineProperty(this, "_tree", new RBush());
644
+ _defineProperty(this, "_dirty", true);
645
+ _defineProperty(this, "_buildTree", () => {
646
+ if (!this._dirty || this._disableTree) return;
647
+ this._tree.clear();
648
+ const items = [];
649
+ this._map.forEach((ranges, ruleId) => {
650
+ ranges.forEach((range) => {
651
+ items.push({
652
+ minX: range.startRow,
653
+ maxX: range.endRow,
654
+ minY: range.startColumn,
655
+ maxY: range.endColumn,
656
+ ruleId
657
+ });
658
+ });
659
+ });
660
+ this._tree.load(items);
661
+ this._dirty = false;
662
+ });
663
+ _defineProperty(this, "_debonceBuildTree", debounce(this._buildTree, 0));
664
+ this._map = value;
665
+ this._buildTree();
666
+ }
667
+ get _worksheet() {
668
+ var _this$_univerInstance;
669
+ return (_this$_univerInstance = this._univerInstanceService.getUnit(this._unitId, UniverInstanceType.UNIVER_SHEET)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getSheetBySheetId(this._subUnitId);
670
+ }
671
+ _addRule(ruleId, _ranges) {
672
+ if (!this._worksheet) return;
673
+ const ranges = Rectangle.mergeRanges(_ranges.map((range) => Range.transformRange(range, this._worksheet)));
674
+ this._map.forEach((value, key) => {
675
+ const newRanges = Rectangle.subtractMulti(value, ranges);
676
+ if (newRanges.length === 0) this._map.delete(key);
677
+ else this._map.set(key, newRanges);
678
+ });
679
+ this._dirty = true;
680
+ this._map.set(ruleId, ranges);
681
+ this._debonceBuildTree();
682
+ }
683
+ addRule(rule) {
684
+ this._addRule(rule.uid, rule.ranges);
685
+ }
686
+ removeRange(_ranges) {
687
+ if (!this._worksheet) return;
688
+ const ranges = _ranges.map((range) => Range.transformRange(range, this._worksheet));
689
+ this._map.forEach((value, key) => {
690
+ const newRanges = Rectangle.subtractMulti(value, ranges);
691
+ if (newRanges.length === 0) this._map.delete(key);
692
+ else this._map.set(key, newRanges);
693
+ });
694
+ this._dirty = true;
695
+ this._debonceBuildTree();
696
+ }
697
+ _removeRule(ruleId) {
698
+ this._map.delete(ruleId);
699
+ this._dirty = true;
700
+ this._debonceBuildTree();
701
+ }
702
+ removeRule(rule) {
703
+ this._removeRule(rule.uid);
704
+ }
705
+ updateRange(ruleId, _newRanges) {
706
+ this._removeRule(ruleId);
707
+ this._addRule(ruleId, _newRanges);
708
+ }
709
+ addRangeRules(rules) {
710
+ rules.forEach(({ id: ruleId, ranges }) => {
711
+ if (!ranges.length) return;
712
+ let current = this._map.get(ruleId);
713
+ if (!current) {
714
+ current = ranges;
715
+ this._map.set(ruleId, current);
716
+ } else {
717
+ this._map.set(ruleId, Rectangle.mergeRanges([...current, ...ranges]));
718
+ current = this._map.get(ruleId);
719
+ }
720
+ this._map.forEach((value, key) => {
721
+ if (key === ruleId) return;
722
+ const newRanges = Rectangle.subtractMulti(value, ranges);
723
+ if (newRanges.length === 0) this._map.delete(key);
724
+ else this._map.set(key, newRanges);
725
+ });
726
+ });
727
+ this._dirty = true;
728
+ this._debonceBuildTree();
729
+ }
730
+ diff(rules) {
731
+ const mutations = [];
732
+ let deleteIndex = 0;
733
+ rules.forEach((rule, index) => {
734
+ var _this$_map$get;
735
+ const newRanges = (_this$_map$get = this._map.get(rule.uid)) !== null && _this$_map$get !== void 0 ? _this$_map$get : [];
736
+ const oldRanges = rule.ranges;
737
+ if (newRanges.length !== 0 && (newRanges.length !== oldRanges.length || newRanges.some((range, i) => !Rectangle.equals(range, oldRanges[i])))) mutations.push({
738
+ type: "update",
739
+ ruleId: rule.uid,
740
+ oldRanges,
741
+ newRanges: Rectangle.sort(newRanges),
742
+ rule
743
+ });
744
+ if (newRanges.length === 0) {
745
+ mutations.push({
746
+ type: "delete",
747
+ rule,
748
+ index: index - deleteIndex
749
+ });
750
+ deleteIndex++;
751
+ }
752
+ });
753
+ return mutations;
754
+ }
755
+ diffWithAddition(rules, additionRules) {
756
+ const mutations = [];
757
+ let deleteIndex = 0;
758
+ rules.forEach((rule, index) => {
759
+ var _this$_map$get2;
760
+ const newRanges = (_this$_map$get2 = this._map.get(rule.uid)) !== null && _this$_map$get2 !== void 0 ? _this$_map$get2 : [];
761
+ const oldRanges = rule.ranges;
762
+ if (newRanges.length !== 0 && (newRanges.length !== oldRanges.length || newRanges.some((range, i) => !Rectangle.equals(range, oldRanges[i])))) mutations.push({
763
+ type: "update",
764
+ ruleId: rule.uid,
765
+ oldRanges,
766
+ newRanges: Rectangle.sort(newRanges),
767
+ rule
768
+ });
769
+ if (newRanges.length === 0) {
770
+ mutations.push({
771
+ type: "delete",
772
+ rule,
773
+ index: index - deleteIndex
774
+ });
775
+ deleteIndex++;
776
+ }
777
+ });
778
+ Array.from(additionRules).forEach((rule) => {
779
+ var _this$_map$get3;
780
+ const newRanges = (_this$_map$get3 = this._map.get(rule.uid)) !== null && _this$_map$get3 !== void 0 ? _this$_map$get3 : [];
781
+ mutations.push({
782
+ type: "add",
783
+ rule: {
784
+ ...rule,
785
+ ranges: Rectangle.sort(newRanges)
786
+ }
787
+ });
788
+ });
789
+ return mutations;
790
+ }
791
+ clone() {
792
+ return new RuleMatrix(new Map(Tools.deepClone(Array.from(this._map.entries()))), this._unitId, this._subUnitId, this._univerInstanceService, true);
793
+ }
794
+ getValue(row, col) {
795
+ if (this._dirty) this._buildTree();
796
+ const result = this._tree.search({
797
+ minX: row,
798
+ maxX: row,
799
+ minY: col,
800
+ maxY: col
801
+ });
802
+ return result.length > 0 ? result[0].ruleId : void 0;
803
+ }
804
+ };
805
+
806
+ //#endregion
807
+ //#region src/models/sheet-data-validation-model.ts
808
+ let SheetDataValidationModel = class SheetDataValidationModel extends Disposable {
809
+ constructor(_dataValidationModel, _univerInstanceService, _dataValidatorRegistryService, _dataValidationCacheService, _dataValidationFormulaService, _dataValidationCustomFormulaService, _commandService) {
810
+ super();
811
+ this._dataValidationModel = _dataValidationModel;
812
+ this._univerInstanceService = _univerInstanceService;
813
+ this._dataValidatorRegistryService = _dataValidatorRegistryService;
814
+ this._dataValidationCacheService = _dataValidationCacheService;
815
+ this._dataValidationFormulaService = _dataValidationFormulaService;
816
+ this._dataValidationCustomFormulaService = _dataValidationCustomFormulaService;
817
+ this._commandService = _commandService;
818
+ _defineProperty(this, "_ruleMatrixMap", /* @__PURE__ */ new Map());
819
+ _defineProperty(this, "_validStatusChange$", new Subject());
820
+ _defineProperty(this, "_ruleChange$", new Subject());
821
+ _defineProperty(this, "ruleChange$", this._ruleChange$.asObservable());
822
+ _defineProperty(this, "validStatusChange$", this._validStatusChange$.asObservable());
823
+ this._initRuleUpdateListener();
824
+ this.disposeWithMe(() => {
825
+ this._ruleChange$.complete();
826
+ this._validStatusChange$.complete();
827
+ });
828
+ this._initUniverInstanceListener();
829
+ }
830
+ _initUniverInstanceListener() {
831
+ this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe((unit) => {
832
+ this._ruleMatrixMap.delete(unit.getUnitId());
833
+ }));
834
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
835
+ if (command.id === RemoveSheetMutation.id) {
836
+ const { unitId, subUnitId } = command.params;
837
+ const subUnitMap = this._ruleMatrixMap.get(unitId);
838
+ if (subUnitMap) subUnitMap.delete(subUnitId);
839
+ }
840
+ }));
841
+ }
842
+ _initRuleUpdateListener() {
843
+ const allRules = this._dataValidationModel.getAll();
844
+ for (const [unitId, subUnitMap] of allRules) for (const [subUnitId, rules] of subUnitMap) for (const rule of rules) {
845
+ this._addRule(unitId, subUnitId, rule);
846
+ this._ruleChange$.next({
847
+ type: "add",
848
+ unitId,
849
+ subUnitId,
850
+ rule,
851
+ source: "patched"
852
+ });
853
+ }
854
+ this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe((ruleChange) => {
855
+ switch (ruleChange.type) {
856
+ case "add":
857
+ this._addRule(ruleChange.unitId, ruleChange.subUnitId, ruleChange.rule);
858
+ break;
859
+ case "update":
860
+ this._updateRule(ruleChange.unitId, ruleChange.subUnitId, ruleChange.rule.uid, ruleChange.oldRule, ruleChange.updatePayload);
861
+ break;
862
+ case "remove":
863
+ this._removeRule(ruleChange.unitId, ruleChange.subUnitId, ruleChange.rule);
864
+ break;
865
+ }
866
+ this._ruleChange$.next(ruleChange);
867
+ }));
868
+ }
869
+ _ensureRuleMatrix(unitId, subUnitId) {
870
+ let unitMap = this._ruleMatrixMap.get(unitId);
871
+ if (!unitMap) {
872
+ unitMap = /* @__PURE__ */ new Map();
873
+ this._ruleMatrixMap.set(unitId, unitMap);
874
+ }
875
+ let matrix = unitMap.get(subUnitId);
876
+ if (!matrix) {
877
+ matrix = new RuleMatrix(/* @__PURE__ */ new Map(), unitId, subUnitId, this._univerInstanceService);
878
+ unitMap.set(subUnitId, matrix);
879
+ }
880
+ return matrix;
881
+ }
882
+ _addRuleSideEffect(unitId, subUnitId, rule) {
883
+ this._ensureRuleMatrix(unitId, subUnitId).addRule(rule);
884
+ this._dataValidationCacheService.addRule(unitId, subUnitId, rule);
885
+ this._dataValidationFormulaService.addRule(unitId, subUnitId, rule);
886
+ this._dataValidationCustomFormulaService.addRule(unitId, subUnitId, rule);
887
+ }
888
+ _addRule(unitId, subUnitId, rule) {
889
+ (Array.isArray(rule) ? rule : [rule]).forEach((item) => {
890
+ this._addRuleSideEffect(unitId, subUnitId, item);
891
+ });
892
+ }
893
+ _updateRule(unitId, subUnitId, ruleId, oldRule, payload) {
894
+ const ruleMatrix = this._ensureRuleMatrix(unitId, subUnitId);
895
+ const newRule = {
896
+ ...oldRule,
897
+ ...payload.payload
898
+ };
899
+ if (payload.type === UpdateRuleType.RANGE) ruleMatrix.updateRange(ruleId, payload.payload);
900
+ else if (payload.type === UpdateRuleType.ALL) ruleMatrix.updateRange(ruleId, payload.payload.ranges);
901
+ this._dataValidationCacheService.removeRule(unitId, subUnitId, oldRule);
902
+ this._dataValidationCacheService.addRule(unitId, subUnitId, newRule);
903
+ this._dataValidationFormulaService.removeRule(unitId, subUnitId, oldRule.uid);
904
+ this._dataValidationFormulaService.addRule(unitId, subUnitId, newRule);
905
+ this._dataValidationCustomFormulaService.deleteByRuleId(unitId, subUnitId, ruleId);
906
+ this._dataValidationCustomFormulaService.addRule(unitId, subUnitId, newRule);
907
+ }
908
+ _removeRule(unitId, subUnitId, oldRule) {
909
+ this._ensureRuleMatrix(unitId, subUnitId).removeRule(oldRule);
910
+ this._dataValidationCacheService.removeRule(unitId, subUnitId, oldRule);
911
+ this._dataValidationCustomFormulaService.deleteByRuleId(unitId, subUnitId, oldRule.uid);
912
+ }
913
+ getValidator(type) {
914
+ return this._dataValidatorRegistryService.getValidatorItem(type);
915
+ }
916
+ getRuleIdByLocation(unitId, subUnitId, row, col) {
917
+ return this._ensureRuleMatrix(unitId, subUnitId).getValue(row, col);
918
+ }
919
+ getRuleByLocation(unitId, subUnitId, row, col) {
920
+ const ruleId = this.getRuleIdByLocation(unitId, subUnitId, row, col);
921
+ if (!ruleId) return;
922
+ return this._dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
923
+ }
924
+ validator(rule, pos, _onCompete) {
925
+ const { col, row, unitId, subUnitId, worksheet } = pos;
926
+ const onCompete = (status, changed) => {
927
+ if (_onCompete) _onCompete(status, changed);
928
+ if (changed) this._validStatusChange$.next({
929
+ unitId,
930
+ subUnitId,
931
+ ruleId: rule.uid,
932
+ status,
933
+ row,
934
+ col
935
+ });
936
+ };
937
+ const cell = worksheet.getCellValueOnly(row, col);
938
+ const validator = this.getValidator(rule.type);
939
+ const cellRaw = worksheet.getCellRaw(row, col);
940
+ const cellValue = getCellValueOrigin(cellRaw);
941
+ if (validator) {
942
+ const cache = this._dataValidationCacheService.ensureCache(unitId, subUnitId);
943
+ const current = cache.getValue(row, col);
944
+ if (current === null || current === void 0) {
945
+ cache.setValue(row, col, DataValidationStatus.VALIDATING);
946
+ validator.validator({
947
+ value: cellValue,
948
+ unitId,
949
+ subUnitId,
950
+ row,
951
+ column: col,
952
+ worksheet: pos.worksheet,
953
+ workbook: pos.workbook,
954
+ interceptValue: getCellValueOrigin(cell),
955
+ t: cellRaw === null || cellRaw === void 0 ? void 0 : cellRaw.t
956
+ }, rule).then((status) => {
957
+ const realStatus = status ? DataValidationStatus.VALID : DataValidationStatus.INVALID;
958
+ const now = cache.getValue(row, col);
959
+ if (realStatus === DataValidationStatus.VALID) cache.realDeleteValue(row, col);
960
+ else cache.setValue(row, col, realStatus);
961
+ onCompete(realStatus, current !== now);
962
+ });
963
+ return DataValidationStatus.VALIDATING;
964
+ }
965
+ onCompete(current !== null && current !== void 0 ? current : DataValidationStatus.VALID, false);
966
+ return current !== null && current !== void 0 ? current : DataValidationStatus.VALID;
967
+ } else {
968
+ onCompete(DataValidationStatus.VALID, false);
969
+ return DataValidationStatus.VALID;
970
+ }
971
+ }
972
+ getRuleObjectMatrix(unitId, subUnitId) {
973
+ return this._ensureRuleMatrix(unitId, subUnitId);
974
+ }
975
+ getRuleById(unitId, subUnitId, ruleId) {
976
+ return this._dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
977
+ }
978
+ getRuleIndex(unitId, subUnitId, ruleId) {
979
+ return this._dataValidationModel.getRuleIndex(unitId, subUnitId, ruleId);
980
+ }
981
+ getRules(unitId, subUnitId) {
982
+ return [...this._dataValidationModel.getRules(unitId, subUnitId)];
983
+ }
984
+ getUnitRules(unitId) {
985
+ return this._dataValidationModel.getUnitRules(unitId);
986
+ }
987
+ deleteUnitRules(unitId) {
988
+ return this._dataValidationModel.deleteUnitRules(unitId);
989
+ }
990
+ getSubUnitIds(unitId) {
991
+ return this._dataValidationModel.getSubUnitIds(unitId);
992
+ }
993
+ getAll() {
994
+ return this._dataValidationModel.getAll();
995
+ }
996
+ };
997
+ SheetDataValidationModel = __decorate([
998
+ __decorateParam(0, Inject(DataValidationModel)),
999
+ __decorateParam(1, IUniverInstanceService),
1000
+ __decorateParam(2, Inject(DataValidatorRegistryService)),
1001
+ __decorateParam(3, Inject(DataValidationCacheService)),
1002
+ __decorateParam(4, Inject(DataValidationFormulaService)),
1003
+ __decorateParam(5, Inject(DataValidationCustomFormulaService)),
1004
+ __decorateParam(6, ICommandService)
1005
+ ], SheetDataValidationModel);
1006
+
1007
+ //#endregion
1008
+ //#region src/validators/checkbox-validator.ts
1009
+ const CHECKBOX_FORMULA_1 = 1;
1010
+ const CHECKBOX_FORMULA_2 = 0;
1011
+ function getFailMessage(formula, localeService) {
1012
+ if (Tools.isBlank(formula)) return localeService.t("dataValidation.validFail.value");
1013
+ if (isFormulaString(formula)) return localeService.t("dataValidation.validFail.primitive");
1014
+ return "";
1015
+ }
1016
+ const transformCheckboxValue = (value) => Tools.isDefine(value) && String(value).toLowerCase() === "true" ? "1" : String(value).toLowerCase() === "false" ? "0" : value;
1017
+ var CheckboxValidator = class extends BaseDataValidator {
1018
+ constructor(..._args) {
1019
+ super(..._args);
1020
+ _defineProperty(this, "id", DataValidationType.CHECKBOX);
1021
+ _defineProperty(this, "title", "dataValidation.checkbox.title");
1022
+ _defineProperty(this, "operators", []);
1023
+ _defineProperty(this, "scopes", ["sheet"]);
1024
+ _defineProperty(this, "order", 41);
1025
+ _defineProperty(this, "offsetFormulaByRange", false);
1026
+ _defineProperty(this, "_formulaService", this.injector.get(DataValidationFormulaService));
1027
+ _defineProperty(this, "skipDefaultFontRender", (rule, cellValue, pos) => {
1028
+ const { unitId, subUnitId } = pos;
1029
+ const { formula1, formula2 } = this.parseFormulaSync(rule, unitId, subUnitId);
1030
+ const valueStr = `${cellValue !== null && cellValue !== void 0 ? cellValue : ""}`;
1031
+ return !valueStr || valueStr === `${formula1}` || valueStr === `${formula2}`;
1032
+ });
1033
+ }
1034
+ validatorFormula(rule, unitId, subUnitId) {
1035
+ const { formula1, formula2 } = rule;
1036
+ const isEqual = formula1 === formula2;
1037
+ if (Tools.isBlank(formula1) && Tools.isBlank(formula2)) return { success: true };
1038
+ if (isEqual) return {
1039
+ success: false,
1040
+ formula1: this.localeService.t("dataValidation.validFail.checkboxEqual"),
1041
+ formula2: this.localeService.t("dataValidation.validFail.checkboxEqual")
1042
+ };
1043
+ const error1 = getFailMessage(formula1, this.localeService);
1044
+ const error2 = getFailMessage(formula2, this.localeService);
1045
+ return {
1046
+ success: !error1 && !error2,
1047
+ formula1: error1,
1048
+ formula2: error2
1049
+ };
1050
+ }
1051
+ async parseFormula(rule, unitId, subUnitId) {
1052
+ var _results$, _results$2;
1053
+ const { formula1 = 1, formula2 = 0 } = rule;
1054
+ const results = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
1055
+ const originFormula1 = isFormulaString(formula1) ? getFormulaResult(results === null || results === void 0 || (_results$ = results[0]) === null || _results$ === void 0 || (_results$ = _results$.result) === null || _results$ === void 0 ? void 0 : _results$[0][0]) : formula1;
1056
+ const originFormula2 = isFormulaString(formula2) ? getFormulaResult(results === null || results === void 0 || (_results$2 = results[1]) === null || _results$2 === void 0 || (_results$2 = _results$2.result) === null || _results$2 === void 0 ? void 0 : _results$2[0][0]) : formula2;
1057
+ const isFormulaValid = isLegalFormulaResult(String(originFormula1)) && isLegalFormulaResult(String(originFormula2));
1058
+ return {
1059
+ formula1: transformCheckboxValue(originFormula1),
1060
+ formula2: transformCheckboxValue(originFormula2),
1061
+ originFormula1,
1062
+ originFormula2,
1063
+ isFormulaValid
1064
+ };
1065
+ }
1066
+ getExtraStyle(rule, value) {
1067
+ return { tb: WrapStrategy.CLIP };
1068
+ }
1069
+ parseFormulaSync(rule, unitId, subUnitId) {
1070
+ var _results$3, _results$4;
1071
+ const { formula1 = 1, formula2 = 0 } = rule;
1072
+ const results = this._formulaService.getRuleFormulaResultSync(unitId, subUnitId, rule.uid);
1073
+ const originFormula1 = isFormulaString(formula1) ? getFormulaResult(results === null || results === void 0 || (_results$3 = results[0]) === null || _results$3 === void 0 || (_results$3 = _results$3.result) === null || _results$3 === void 0 ? void 0 : _results$3[0][0]) : formula1;
1074
+ const originFormula2 = isFormulaString(formula2) ? getFormulaResult(results === null || results === void 0 || (_results$4 = results[1]) === null || _results$4 === void 0 || (_results$4 = _results$4.result) === null || _results$4 === void 0 ? void 0 : _results$4[0][0]) : formula2;
1075
+ const isFormulaValid = isLegalFormulaResult(String(originFormula1)) && isLegalFormulaResult(String(originFormula2));
1076
+ return {
1077
+ formula1: transformCheckboxValue(originFormula1),
1078
+ formula2: transformCheckboxValue(originFormula2),
1079
+ originFormula1,
1080
+ originFormula2,
1081
+ isFormulaValid
1082
+ };
1083
+ }
1084
+ async isValidType(cellInfo, formula, rule) {
1085
+ const { value, unitId, subUnitId } = cellInfo;
1086
+ const { formula1, formula2, originFormula1, originFormula2 } = await this.parseFormula(rule, unitId, subUnitId);
1087
+ if (!Tools.isDefine(formula1) || !Tools.isDefine(formula2)) return true;
1088
+ return Tools.isDefine(value) && (String(value) === String(formula1) || String(value) === String(formula2) || String(value) === String(originFormula1 !== null && originFormula1 !== void 0 ? originFormula1 : "") || String(value) === String(originFormula2 !== null && originFormula2 !== void 0 ? originFormula2 : ""));
1089
+ }
1090
+ generateRuleErrorMessage(rule) {
1091
+ return this.localeService.t("dataValidation.checkbox.error");
1092
+ }
1093
+ generateRuleName(rule) {
1094
+ return this.titleStr;
1095
+ }
1096
+ };
1097
+
1098
+ //#endregion
1099
+ //#region src/common/date-text-map.ts
1100
+ /**
1101
+ * Copyright 2023-present DreamNum Co., Ltd.
1102
+ *
1103
+ * Licensed under the Apache License, Version 2.0 (the "License");
1104
+ * you may not use this file except in compliance with the License.
1105
+ * You may obtain a copy of the License at
1106
+ *
1107
+ * http://www.apache.org/licenses/LICENSE-2.0
1108
+ *
1109
+ * Unless required by applicable law or agreed to in writing, software
1110
+ * distributed under the License is distributed on an "AS IS" BASIS,
1111
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
+ * See the License for the specific language governing permissions and
1113
+ * limitations under the License.
1114
+ */
1115
+ const DateOperatorNameMap = {
1116
+ [DataValidationOperator.BETWEEN]: "dataValidation.date.operators.between",
1117
+ [DataValidationOperator.EQUAL]: "dataValidation.date.operators.equal",
1118
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.date.operators.greaterThan",
1119
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.date.operators.greaterThanOrEqual",
1120
+ [DataValidationOperator.LESS_THAN]: "dataValidation.date.operators.lessThan",
1121
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.date.operators.lessThanOrEqual",
1122
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.date.operators.notBetween",
1123
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.date.operators.notEqual"
1124
+ };
1125
+ const DateOperatorTextMap = {
1126
+ [DataValidationOperator.BETWEEN]: "dataValidation.date.operators.between",
1127
+ [DataValidationOperator.EQUAL]: "dataValidation.date.operators.equal",
1128
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.date.operators.greaterThan",
1129
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.date.operators.greaterThanOrEqual",
1130
+ [DataValidationOperator.LESS_THAN]: "dataValidation.date.operators.lessThan",
1131
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.date.operators.lessThanOrEqual",
1132
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.date.operators.notBetween",
1133
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.date.operators.notEqual"
1134
+ };
1135
+ const DateOperatorTitleMap = {
1136
+ [DataValidationOperator.BETWEEN]: "dataValidation.date.ruleName.between",
1137
+ [DataValidationOperator.EQUAL]: "dataValidation.date.ruleName.equal",
1138
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.date.ruleName.greaterThan",
1139
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.date.ruleName.greaterThanOrEqual",
1140
+ [DataValidationOperator.LESS_THAN]: "dataValidation.date.ruleName.lessThan",
1141
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.date.ruleName.lessThanOrEqual",
1142
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.date.ruleName.notBetween",
1143
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.date.ruleName.notEqual",
1144
+ NONE: "dataValidation.date.ruleName.legal"
1145
+ };
1146
+ const DateOperatorErrorTitleMap = {
1147
+ [DataValidationOperator.BETWEEN]: "dataValidation.date.errorMsg.between",
1148
+ [DataValidationOperator.EQUAL]: "dataValidation.date.errorMsg.equal",
1149
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.date.errorMsg.greaterThan",
1150
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.date.errorMsg.greaterThanOrEqual",
1151
+ [DataValidationOperator.LESS_THAN]: "dataValidation.date.errorMsg.lessThan",
1152
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.date.errorMsg.lessThanOrEqual",
1153
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.date.errorMsg.notBetween",
1154
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.date.errorMsg.notEqual",
1155
+ NONE: "dataValidation.date.errorMsg.legal"
1156
+ };
1157
+
1158
+ //#endregion
1159
+ //#region src/types/const/two-formula-operators.ts
1160
+ /**
1161
+ * Copyright 2023-present DreamNum Co., Ltd.
1162
+ *
1163
+ * Licensed under the Apache License, Version 2.0 (the "License");
1164
+ * you may not use this file except in compliance with the License.
1165
+ * You may obtain a copy of the License at
1166
+ *
1167
+ * http://www.apache.org/licenses/LICENSE-2.0
1168
+ *
1169
+ * Unless required by applicable law or agreed to in writing, software
1170
+ * distributed under the License is distributed on an "AS IS" BASIS,
1171
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1172
+ * See the License for the specific language governing permissions and
1173
+ * limitations under the License.
1174
+ */
1175
+ const TWO_FORMULA_OPERATOR_COUNT = [DataValidationOperator.BETWEEN, DataValidationOperator.NOT_BETWEEN];
1176
+
1177
+ //#endregion
1178
+ //#region src/validators/const.ts
1179
+ /**
1180
+ * Copyright 2023-present DreamNum Co., Ltd.
1181
+ *
1182
+ * Licensed under the Apache License, Version 2.0 (the "License");
1183
+ * you may not use this file except in compliance with the License.
1184
+ * You may obtain a copy of the License at
1185
+ *
1186
+ * http://www.apache.org/licenses/LICENSE-2.0
1187
+ *
1188
+ * Unless required by applicable law or agreed to in writing, software
1189
+ * distributed under the License is distributed on an "AS IS" BASIS,
1190
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1191
+ * See the License for the specific language governing permissions and
1192
+ * limitations under the License.
1193
+ */
1194
+ const FORMULA1 = "{FORMULA1}";
1195
+ const FORMULA2 = "{FORMULA2}";
1196
+
1197
+ //#endregion
1198
+ //#region src/validators/date-validator.ts
1199
+ const transformDate2SerialNumber = (value) => {
1200
+ var _numfmt$parseDate, _numfmt$parseDate2;
1201
+ if (value === void 0 || value === null || typeof value === "boolean") return;
1202
+ if (typeof value === "number" || !Number.isNaN(+value)) return +value;
1203
+ const v = (_numfmt$parseDate = numfmt.parseDate(value)) === null || _numfmt$parseDate === void 0 ? void 0 : _numfmt$parseDate.v;
1204
+ if (Tools.isDefine(v)) return v;
1205
+ return (_numfmt$parseDate2 = numfmt.parseDate(dateKit(value).format("YYYY-MM-DD HH:mm:ss"))) === null || _numfmt$parseDate2 === void 0 ? void 0 : _numfmt$parseDate2.v;
1206
+ };
1207
+ var DateValidator = class extends BaseDataValidator {
1208
+ constructor(..._args) {
1209
+ super(..._args);
1210
+ _defineProperty(this, "id", DataValidationType.DATE);
1211
+ _defineProperty(this, "title", "dataValidation.date.title");
1212
+ _defineProperty(this, "order", 40);
1213
+ _defineProperty(this, "operators", [
1214
+ DataValidationOperator.BETWEEN,
1215
+ DataValidationOperator.EQUAL,
1216
+ DataValidationOperator.GREATER_THAN,
1217
+ DataValidationOperator.GREATER_THAN_OR_EQUAL,
1218
+ DataValidationOperator.LESS_THAN,
1219
+ DataValidationOperator.LESS_THAN_OR_EQUAL,
1220
+ DataValidationOperator.NOT_BETWEEN,
1221
+ DataValidationOperator.NOT_EQUAL
1222
+ ]);
1223
+ _defineProperty(this, "scopes", ["sheet"]);
1224
+ _defineProperty(this, "_customFormulaService", this.injector.get(DataValidationCustomFormulaService));
1225
+ _defineProperty(this, "_lexerTreeBuilder", this.injector.get(LexerTreeBuilder));
1226
+ }
1227
+ async parseFormula(rule, unitId, subUnitId, row, column) {
1228
+ const formulaResult1 = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, rule.uid, row, column);
1229
+ const formulaResult2 = await this._customFormulaService.getCellFormula2Value(unitId, subUnitId, rule.uid, row, column);
1230
+ const { formula1, formula2 } = rule;
1231
+ const isFormulaValid = isLegalFormulaResult(String(formulaResult1 === null || formulaResult1 === void 0 ? void 0 : formulaResult1.v)) && isLegalFormulaResult(String(formulaResult2 === null || formulaResult2 === void 0 ? void 0 : formulaResult2.v));
1232
+ return {
1233
+ formula1: transformDate2SerialNumber(isFormulaString(formula1) ? formulaResult1 === null || formulaResult1 === void 0 ? void 0 : formulaResult1.v : formula1),
1234
+ formula2: transformDate2SerialNumber(isFormulaString(formula2) ? formulaResult2 === null || formulaResult2 === void 0 ? void 0 : formulaResult2.v : formula2),
1235
+ isFormulaValid
1236
+ };
1237
+ }
1238
+ async isValidType(info) {
1239
+ const { interceptValue, value } = info;
1240
+ if (typeof value === "number" && typeof interceptValue === "string") return Boolean(numfmt.parseDate(interceptValue));
1241
+ if (typeof interceptValue === "string") return Boolean(numfmt.parseDate(interceptValue));
1242
+ return false;
1243
+ }
1244
+ _validatorSingleFormula(formula) {
1245
+ return !Tools.isBlank(formula) && (isFormulaString(formula) || !Number.isNaN(+formula) || Boolean(formula && numfmt.parseDate(formula)));
1246
+ }
1247
+ validatorFormula(rule, unitId, subUnitId) {
1248
+ const operator = rule.operator;
1249
+ if (!operator) return { success: true };
1250
+ const formula1Success = this._validatorSingleFormula(rule.formula1);
1251
+ const errorMsg = this.localeService.t("dataValidation.validFail.date");
1252
+ if (TWO_FORMULA_OPERATOR_COUNT.includes(operator)) {
1253
+ const formula2Success = this._validatorSingleFormula(rule.formula2);
1254
+ return {
1255
+ success: formula1Success && formula2Success,
1256
+ formula1: formula1Success ? void 0 : errorMsg,
1257
+ formula2: formula2Success ? void 0 : errorMsg
1258
+ };
1259
+ }
1260
+ return {
1261
+ success: formula1Success,
1262
+ formula1: formula1Success ? void 0 : errorMsg
1263
+ };
1264
+ }
1265
+ normalizeFormula(rule, _unitId, _subUnitId) {
1266
+ const { formula1, formula2, bizInfo } = rule;
1267
+ const normlizeSingleFormula = (formula) => {
1268
+ if (!formula) return formula;
1269
+ let date;
1270
+ if (!Number.isNaN(+formula)) date = numfmt.dateFromSerial(+formula);
1271
+ else {
1272
+ var _numfmt$parseDate3;
1273
+ const res = (_numfmt$parseDate3 = numfmt.parseDate(formula)) === null || _numfmt$parseDate3 === void 0 ? void 0 : _numfmt$parseDate3.v;
1274
+ if (res === void 0 || res === null) return "";
1275
+ date = numfmt.dateFromSerial(res);
1276
+ }
1277
+ return dateKit(`${date[0]}/${date[1]}/${date[2]} ${date[3]}:${date[4]}:${date[5]}`).format((bizInfo === null || bizInfo === void 0 ? void 0 : bizInfo.showTime) ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD");
1278
+ };
1279
+ return {
1280
+ formula1: isFormulaString(formula1) ? formula1 : normlizeSingleFormula(`${formula1}`),
1281
+ formula2: isFormulaString(formula2) ? formula2 : normlizeSingleFormula(`${formula2}`)
1282
+ };
1283
+ }
1284
+ transform(cellInfo, _formula, _rule) {
1285
+ const { value } = cellInfo;
1286
+ return {
1287
+ ...cellInfo,
1288
+ value: transformDate2SerialNumber(value)
1289
+ };
1290
+ }
1291
+ get operatorNames() {
1292
+ return this.operators.map((operator) => this.localeService.t(DateOperatorNameMap[operator]));
1293
+ }
1294
+ generateRuleName(rule) {
1295
+ var _rule$formula, _rule$formula2;
1296
+ if (!rule.operator) return this.localeService.t(DateOperatorTitleMap.NONE);
1297
+ const ruleName = this.localeService.t(DateOperatorTitleMap[rule.operator]).replace(FORMULA1, (_rule$formula = rule.formula1) !== null && _rule$formula !== void 0 ? _rule$formula : "").replace(FORMULA2, (_rule$formula2 = rule.formula2) !== null && _rule$formula2 !== void 0 ? _rule$formula2 : "");
1298
+ return `${this.titleStr} ${ruleName}`;
1299
+ }
1300
+ generateRuleErrorMessage(rule, pos) {
1301
+ if (!rule.operator) return this.titleStr;
1302
+ const { transformedFormula1, transformedFormula2 } = getTransformedFormula(this._lexerTreeBuilder, rule, pos);
1303
+ return `${this.localeService.t(DateOperatorErrorTitleMap[rule.operator]).replace(FORMULA1, transformedFormula1 !== null && transformedFormula1 !== void 0 ? transformedFormula1 : "").replace(FORMULA2, transformedFormula2 !== null && transformedFormula2 !== void 0 ? transformedFormula2 : "")}`;
1304
+ }
1305
+ };
1306
+
1307
+ //#endregion
1308
+ //#region src/types/const/operator-text-map.ts
1309
+ /**
1310
+ * Copyright 2023-present DreamNum Co., Ltd.
1311
+ *
1312
+ * Licensed under the Apache License, Version 2.0 (the "License");
1313
+ * you may not use this file except in compliance with the License.
1314
+ * You may obtain a copy of the License at
1315
+ *
1316
+ * http://www.apache.org/licenses/LICENSE-2.0
1317
+ *
1318
+ * Unless required by applicable law or agreed to in writing, software
1319
+ * distributed under the License is distributed on an "AS IS" BASIS,
1320
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1321
+ * See the License for the specific language governing permissions and
1322
+ * limitations under the License.
1323
+ */
1324
+ const OperatorTextMap = {
1325
+ [DataValidationOperator.BETWEEN]: "dataValidation.operators.between",
1326
+ [DataValidationOperator.EQUAL]: "dataValidation.operators.equal",
1327
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.operators.greaterThan",
1328
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.operators.greaterThanOrEqual",
1329
+ [DataValidationOperator.LESS_THAN]: "dataValidation.operators.lessThan",
1330
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.operators.lessThanOrEqual",
1331
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.operators.notBetween",
1332
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.operators.notEqual"
1333
+ };
1334
+ const OperatorTitleMap = {
1335
+ [DataValidationOperator.BETWEEN]: "dataValidation.ruleName.between",
1336
+ [DataValidationOperator.EQUAL]: "dataValidation.ruleName.equal",
1337
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.ruleName.greaterThan",
1338
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.ruleName.greaterThanOrEqual",
1339
+ [DataValidationOperator.LESS_THAN]: "dataValidation.ruleName.lessThan",
1340
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.ruleName.lessThanOrEqual",
1341
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.ruleName.notBetween",
1342
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.ruleName.notEqual"
1343
+ };
1344
+ const OperatorErrorTitleMap = {
1345
+ [DataValidationOperator.BETWEEN]: "dataValidation.errorMsg.between",
1346
+ [DataValidationOperator.EQUAL]: "dataValidation.errorMsg.equal",
1347
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.errorMsg.greaterThan",
1348
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.errorMsg.greaterThanOrEqual",
1349
+ [DataValidationOperator.LESS_THAN]: "dataValidation.errorMsg.lessThan",
1350
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.errorMsg.lessThanOrEqual",
1351
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.errorMsg.notBetween",
1352
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.errorMsg.notEqual",
1353
+ NONE: "dataValidation.errorMsg.legal"
1354
+ };
1355
+
1356
+ //#endregion
1357
+ //#region src/validators/decimal-validator.ts
1358
+ function getCellValueNumber(cellValue) {
1359
+ return +cellValue;
1360
+ }
1361
+ var DecimalValidator = class extends BaseDataValidator {
1362
+ constructor(..._args) {
1363
+ super(..._args);
1364
+ _defineProperty(this, "_customFormulaService", this.injector.get(DataValidationCustomFormulaService));
1365
+ _defineProperty(this, "id", DataValidationType.DECIMAL);
1366
+ _defineProperty(this, "_lexerTreeBuilder", this.injector.get(LexerTreeBuilder));
1367
+ _defineProperty(this, "title", "dataValidation.decimal.title");
1368
+ _defineProperty(this, "order", 20);
1369
+ _defineProperty(this, "operators", [
1370
+ DataValidationOperator.BETWEEN,
1371
+ DataValidationOperator.EQUAL,
1372
+ DataValidationOperator.GREATER_THAN,
1373
+ DataValidationOperator.GREATER_THAN_OR_EQUAL,
1374
+ DataValidationOperator.LESS_THAN,
1375
+ DataValidationOperator.LESS_THAN_OR_EQUAL,
1376
+ DataValidationOperator.NOT_BETWEEN,
1377
+ DataValidationOperator.NOT_EQUAL
1378
+ ]);
1379
+ _defineProperty(this, "scopes", ["sheet"]);
1380
+ }
1381
+ _isFormulaOrNumber(formula) {
1382
+ return !Tools.isBlank(formula) && (isFormulaString(formula) || !Number.isNaN(+formula));
1383
+ }
1384
+ async isValidType(cellInfo, formula, rule) {
1385
+ const { value: cellValue } = cellInfo;
1386
+ return !Number.isNaN(getCellValueNumber(cellValue));
1387
+ }
1388
+ transform(cellInfo, formula, rule) {
1389
+ const { value: cellValue } = cellInfo;
1390
+ return {
1391
+ ...cellInfo,
1392
+ value: getCellValueNumber(cellValue)
1393
+ };
1394
+ }
1395
+ _parseNumber(formula) {
1396
+ if (formula === void 0 || formula === null) return NaN;
1397
+ return +formula;
1398
+ }
1399
+ async parseFormula(rule, unitId, subUnitId, row, column) {
1400
+ const formulaResult1 = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, rule.uid, row, column);
1401
+ const formulaResult2 = await this._customFormulaService.getCellFormula2Value(unitId, subUnitId, rule.uid, row, column);
1402
+ const { formula1, formula2 } = rule;
1403
+ const isFormulaValid = isLegalFormulaResult(String(formulaResult1 === null || formulaResult1 === void 0 ? void 0 : formulaResult1.v)) && isLegalFormulaResult(String(formulaResult2 === null || formulaResult2 === void 0 ? void 0 : formulaResult2.v));
1404
+ return {
1405
+ formula1: this._parseNumber(isFormulaString(formula1) ? formulaResult1 === null || formulaResult1 === void 0 ? void 0 : formulaResult1.v : formula1),
1406
+ formula2: this._parseNumber(isFormulaString(formula2) ? formulaResult2 === null || formulaResult2 === void 0 ? void 0 : formulaResult2.v : formula2),
1407
+ isFormulaValid
1408
+ };
1409
+ }
1410
+ validatorFormula(rule, unitId, subUnitId) {
1411
+ const operator = rule.operator;
1412
+ if (!operator) return { success: true };
1413
+ const formula1Success = Tools.isDefine(rule.formula1) && this._isFormulaOrNumber(rule.formula1);
1414
+ const formula2Success = Tools.isDefine(rule.formula2) && this._isFormulaOrNumber(rule.formula2);
1415
+ const isTwoFormula = TWO_FORMULA_OPERATOR_COUNT.includes(operator);
1416
+ const errorMsg = this.localeService.t("dataValidation.validFail.number");
1417
+ if (isTwoFormula) return {
1418
+ success: formula1Success && formula2Success,
1419
+ formula1: formula1Success ? void 0 : errorMsg,
1420
+ formula2: formula2Success ? void 0 : errorMsg
1421
+ };
1422
+ return {
1423
+ success: formula1Success,
1424
+ formula1: formula1Success ? "" : errorMsg
1425
+ };
1426
+ }
1427
+ generateRuleErrorMessage(rule, position) {
1428
+ if (!rule.operator) return this.localeService.t(OperatorErrorTitleMap.NONE).replace("{TYPE}", this.titleStr);
1429
+ const { transformedFormula1, transformedFormula2 } = getTransformedFormula(this._lexerTreeBuilder, rule, position);
1430
+ return `${this.localeService.t(OperatorErrorTitleMap[rule.operator]).replace(FORMULA1, transformedFormula1 !== null && transformedFormula1 !== void 0 ? transformedFormula1 : "").replace(FORMULA2, transformedFormula2 !== null && transformedFormula2 !== void 0 ? transformedFormula2 : "")}`;
1431
+ }
1432
+ };
1433
+
1434
+ //#endregion
1435
+ //#region src/validators/list-validator.ts
1436
+ function getRuleFormulaResultSet(result) {
1437
+ if (!result) return [];
1438
+ const resultSet = /* @__PURE__ */ new Set();
1439
+ for (let i = 0, rowLen = result.length; i < rowLen; i++) {
1440
+ const row = result[i];
1441
+ if (!row) continue;
1442
+ for (let j = 0, colLen = row.length; j < colLen; j++) {
1443
+ const cell = row[j];
1444
+ const value = getCellValueOrigin(cell);
1445
+ if (value !== null && value !== void 0) {
1446
+ var _cell$s;
1447
+ if (typeof value !== "string" && typeof (cell === null || cell === void 0 ? void 0 : cell.s) === "object" && ((_cell$s = cell.s) === null || _cell$s === void 0 || (_cell$s = _cell$s.n) === null || _cell$s === void 0 ? void 0 : _cell$s.pattern)) {
1448
+ resultSet.add(numfmt.format(cell.s.n.pattern, value, { throws: false }));
1449
+ continue;
1450
+ }
1451
+ const valueStr = typeof value === "string" ? value : String(value);
1452
+ if (isLegalFormulaResult(valueStr)) resultSet.add(valueStr);
1453
+ }
1454
+ }
1455
+ }
1456
+ return [...resultSet];
1457
+ }
1458
+ const supportedFormula = [
1459
+ "if",
1460
+ "indirect",
1461
+ "choose",
1462
+ "offset"
1463
+ ];
1464
+ function isValidListFormula(formula, lexer) {
1465
+ if (!isFormulaString(formula)) return true;
1466
+ if (isReferenceString(formula.slice(1))) return true;
1467
+ const nodes = lexer.sequenceNodesBuilder(formula);
1468
+ return nodes && nodes.some((node) => typeof node === "object" && node.nodeType === sequenceNodeType.FUNCTION && supportedFormula.indexOf(node.token.toLowerCase()) > -1);
1469
+ }
1470
+ function isRuleIntersects(rule, sheetName) {
1471
+ const { formula1 = "", ranges } = rule;
1472
+ if (isReferenceString(formula1.slice(1))) {
1473
+ const refRange = deserializeRangeWithSheet(formula1.slice(1));
1474
+ if ((!refRange.sheetName || refRange.sheetName === sheetName) && ranges.some((range) => Rectangle.intersects(range, refRange.range))) return true;
1475
+ }
1476
+ return false;
1477
+ }
1478
+ var ListValidator = class extends BaseDataValidator {
1479
+ constructor(..._args) {
1480
+ super(..._args);
1481
+ _defineProperty(this, "formulaService", this.injector.get(DataValidationFormulaService));
1482
+ _defineProperty(this, "_lexer", this.injector.get(LexerTreeBuilder));
1483
+ _defineProperty(this, "_univerInstanceService", this.injector.get(IUniverInstanceService));
1484
+ _defineProperty(this, "_listCacheService", this.injector.get(DataValidationListCacheService));
1485
+ _defineProperty(this, "order", 50);
1486
+ _defineProperty(this, "offsetFormulaByRange", false);
1487
+ _defineProperty(this, "id", DataValidationType.LIST);
1488
+ _defineProperty(this, "title", "dataValidation.list.title");
1489
+ _defineProperty(this, "operators", []);
1490
+ _defineProperty(this, "scopes", ["sheet"]);
1491
+ _defineProperty(this, "skipDefaultFontRender", (rule) => {
1492
+ return rule.renderMode !== DataValidationRenderMode.TEXT;
1493
+ });
1494
+ }
1495
+ validatorFormula(rule, unitId, subUnitId) {
1496
+ var _rule$formula, _this$_univerInstance;
1497
+ const success = !Tools.isBlank(rule.formula1);
1498
+ const valid = isValidListFormula((_rule$formula = rule.formula1) !== null && _rule$formula !== void 0 ? _rule$formula : "", this._lexer);
1499
+ const sheetName = (_this$_univerInstance = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET)) === null || _this$_univerInstance === void 0 || (_this$_univerInstance = _this$_univerInstance.getSheetBySheetId(subUnitId)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getName();
1500
+ const isIntersects = isRuleIntersects(rule, sheetName !== null && sheetName !== void 0 ? sheetName : "");
1501
+ return {
1502
+ success: Boolean(success && valid && !isIntersects),
1503
+ formula1: success ? valid ? !isIntersects ? void 0 : this.localeService.t("dataValidation.validFail.listIntersects") : this.localeService.t("dataValidation.validFail.listInvalid") : this.localeService.t("dataValidation.validFail.list")
1504
+ };
1505
+ }
1506
+ getExtraStyle(rule, value, { style: defaultStyle }) {
1507
+ var _ref;
1508
+ const tb = (_ref = defaultStyle.tb !== WrapStrategy.OVERFLOW ? defaultStyle.tb : WrapStrategy.CLIP) !== null && _ref !== void 0 ? _ref : WrapStrategy.WRAP;
1509
+ if (rule.type === DataValidationType.LIST && (rule.renderMode === DataValidationRenderMode.ARROW || rule.renderMode === DataValidationRenderMode.TEXT)) {
1510
+ const color = this.getListWithColorMap(rule)[`${value !== null && value !== void 0 ? value : ""}`];
1511
+ if (color) return {
1512
+ bg: { rgb: color },
1513
+ tb
1514
+ };
1515
+ }
1516
+ return { tb };
1517
+ }
1518
+ parseCellValue(cellValue) {
1519
+ return deserializeListOptions(cellValue.toString());
1520
+ }
1521
+ async parseFormula(rule, unitId, subUnitId) {
1522
+ var _results$;
1523
+ const results = await this.formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
1524
+ const formulaResult1 = getFormulaResult(results === null || results === void 0 || (_results$ = results[0]) === null || _results$ === void 0 || (_results$ = _results$.result) === null || _results$ === void 0 ? void 0 : _results$[0][0]);
1525
+ return {
1526
+ formula1: void 0,
1527
+ formula2: void 0,
1528
+ isFormulaValid: isLegalFormulaResult(String(formulaResult1))
1529
+ };
1530
+ }
1531
+ async isValidType(cellInfo, formula, rule) {
1532
+ const { value, unitId, subUnitId } = cellInfo;
1533
+ const { formula1 = "" } = rule;
1534
+ const formula1Result = isFormulaString(formula1) ? this._listCacheService.getOrCompute(unitId, subUnitId, rule).list : deserializeListOptions(formula1);
1535
+ return this.parseCellValue(value).every((i) => formula1Result.includes(i));
1536
+ }
1537
+ generateRuleName() {
1538
+ return this.localeService.t("dataValidation.list.name");
1539
+ }
1540
+ generateRuleErrorMessage() {
1541
+ return this.localeService.t("dataValidation.list.error");
1542
+ }
1543
+ _getUnitAndSubUnit(currentUnitId, currentSubUnitId) {
1544
+ var _ref2, _ref3;
1545
+ const workbook = (_ref2 = currentUnitId ? this._univerInstanceService.getUniverSheetInstance(currentUnitId) : void 0) !== null && _ref2 !== void 0 ? _ref2 : this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET);
1546
+ if (!workbook) return null;
1547
+ const worksheet = (_ref3 = currentSubUnitId ? workbook.getSheetBySheetId(currentSubUnitId) : void 0) !== null && _ref3 !== void 0 ? _ref3 : workbook.getActiveSheet();
1548
+ if (!worksheet) return null;
1549
+ return {
1550
+ unitId: workbook.getUnitId(),
1551
+ subUnitId: worksheet.getSheetId()
1552
+ };
1553
+ }
1554
+ getList(rule, currentUnitId, currentSubUnitId) {
1555
+ const location = this._getUnitAndSubUnit(currentUnitId, currentSubUnitId);
1556
+ if (!location) return [];
1557
+ const { unitId, subUnitId } = location;
1558
+ return this._listCacheService.getOrCompute(unitId, subUnitId, rule).list;
1559
+ }
1560
+ async getListAsync(rule, currentUnitId, currentSubUnitId) {
1561
+ var _results$2;
1562
+ const { formula1 = "" } = rule;
1563
+ const location = this._getUnitAndSubUnit(currentUnitId, currentSubUnitId);
1564
+ if (!location) return [];
1565
+ const { unitId, subUnitId } = location;
1566
+ const results = await this.formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
1567
+ return isFormulaString(formula1) ? getRuleFormulaResultSet(results === null || results === void 0 || (_results$2 = results[0]) === null || _results$2 === void 0 || (_results$2 = _results$2.result) === null || _results$2 === void 0 ? void 0 : _results$2[0][0]) : deserializeListOptions(formula1);
1568
+ }
1569
+ getListWithColor(rule, currentUnitId, currentSubUnitId) {
1570
+ const location = this._getUnitAndSubUnit(currentUnitId, currentSubUnitId);
1571
+ if (!location) return [];
1572
+ const { unitId, subUnitId } = location;
1573
+ return this._listCacheService.getOrCompute(unitId, subUnitId, rule).listWithColor;
1574
+ }
1575
+ getListWithColorMap(rule, currentUnitId, currentSubUnitId) {
1576
+ const location = this._getUnitAndSubUnit(currentUnitId, currentSubUnitId);
1577
+ if (!location) return {};
1578
+ const { unitId, subUnitId } = location;
1579
+ return this._listCacheService.getOrCompute(unitId, subUnitId, rule).colorMap;
1580
+ }
1581
+ };
1582
+
1583
+ //#endregion
1584
+ //#region src/validators/text-length-validator.ts
1585
+ var TextLengthValidator = class extends BaseDataValidator {
1586
+ constructor(..._args) {
1587
+ super(..._args);
1588
+ _defineProperty(this, "id", DataValidationType.TEXT_LENGTH);
1589
+ _defineProperty(this, "title", "dataValidation.textLength.title");
1590
+ _defineProperty(this, "_lexerTreeBuilder", this.injector.get(LexerTreeBuilder));
1591
+ _defineProperty(this, "order", 30);
1592
+ _defineProperty(this, "operators", [
1593
+ DataValidationOperator.BETWEEN,
1594
+ DataValidationOperator.EQUAL,
1595
+ DataValidationOperator.GREATER_THAN,
1596
+ DataValidationOperator.GREATER_THAN_OR_EQUAL,
1597
+ DataValidationOperator.LESS_THAN,
1598
+ DataValidationOperator.LESS_THAN_OR_EQUAL,
1599
+ DataValidationOperator.NOT_BETWEEN,
1600
+ DataValidationOperator.NOT_EQUAL
1601
+ ]);
1602
+ _defineProperty(this, "scopes", ["sheet"]);
1603
+ _defineProperty(this, "_customFormulaService", this.injector.get(DataValidationCustomFormulaService));
1604
+ }
1605
+ _isFormulaOrInt(formula) {
1606
+ return !Tools.isBlank(formula) && (isFormulaString(formula) || !Number.isNaN(+formula) && Number.isInteger(+formula));
1607
+ }
1608
+ validatorFormula(rule, _unitId, _subUnitId) {
1609
+ const operator = rule.operator;
1610
+ if (!operator) return { success: false };
1611
+ const formula1Success = Tools.isDefine(rule.formula1) && this._isFormulaOrInt(rule.formula1);
1612
+ const formula2Success = Tools.isDefine(rule.formula2) && this._isFormulaOrInt(rule.formula2);
1613
+ const isTwoFormula = TWO_FORMULA_OPERATOR_COUNT.includes(operator);
1614
+ const errorMsg = this.localeService.t("dataValidation.validFail.number");
1615
+ if (isTwoFormula) return {
1616
+ success: formula1Success && formula2Success,
1617
+ formula1: formula1Success ? void 0 : errorMsg,
1618
+ formula2: formula2Success ? void 0 : errorMsg
1619
+ };
1620
+ return {
1621
+ success: formula1Success,
1622
+ formula1: errorMsg
1623
+ };
1624
+ }
1625
+ _parseNumber(formula) {
1626
+ if (formula === void 0 || formula === null) return NaN;
1627
+ return +formula;
1628
+ }
1629
+ async parseFormula(rule, unitId, subUnitId, row, column) {
1630
+ const formulaResult1 = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, rule.uid, row, column);
1631
+ const formulaResult2 = await this._customFormulaService.getCellFormula2Value(unitId, subUnitId, rule.uid, row, column);
1632
+ const { formula1, formula2 } = rule;
1633
+ const isFormulaValid = isLegalFormulaResult(String(formulaResult1 === null || formulaResult1 === void 0 ? void 0 : formulaResult1.v)) && isLegalFormulaResult(String(formulaResult2 === null || formulaResult2 === void 0 ? void 0 : formulaResult2.v));
1634
+ return {
1635
+ formula1: this._parseNumber(isFormulaString(formula1) ? formulaResult1 === null || formulaResult1 === void 0 ? void 0 : formulaResult1.v : formula1),
1636
+ formula2: this._parseNumber(isFormulaString(formula2) ? formulaResult2 === null || formulaResult2 === void 0 ? void 0 : formulaResult2.v : formula2),
1637
+ isFormulaValid
1638
+ };
1639
+ }
1640
+ transform(cellInfo, _formula, _rule) {
1641
+ return {
1642
+ ...cellInfo,
1643
+ value: cellInfo.value.toString().length
1644
+ };
1645
+ }
1646
+ async isValidType(cellInfo, _formula, _rule) {
1647
+ const { value: cellValue } = cellInfo;
1648
+ return typeof cellValue === "string" || typeof cellValue === "number";
1649
+ }
1650
+ generateRuleErrorMessage(rule, pos) {
1651
+ if (!rule.operator) return this.titleStr;
1652
+ const { transformedFormula1, transformedFormula2 } = getTransformedFormula(this._lexerTreeBuilder, rule, pos);
1653
+ return `${this.localeService.t(TextLengthErrorTitleMap[rule.operator]).replace(FORMULA1, transformedFormula1 !== null && transformedFormula1 !== void 0 ? transformedFormula1 : "").replace(FORMULA2, transformedFormula2 !== null && transformedFormula2 !== void 0 ? transformedFormula2 : "")}`;
1654
+ }
1655
+ };
1656
+
1657
+ //#endregion
1658
+ //#region src/commands/commands/data-validation.command.ts
1659
+ function isBlankCell(cellData) {
1660
+ var _cellData$p$body$data, _cellData$p$body;
1661
+ if (!cellData) return true;
1662
+ if (!cellData.p) return Tools.isBlank(cellData.v);
1663
+ return !((_cellData$p$body$data = (_cellData$p$body = cellData.p.body) === null || _cellData$p$body === void 0 ? void 0 : _cellData$p$body.dataStream) !== null && _cellData$p$body$data !== void 0 ? _cellData$p$body$data : "").slice(0, -2).trim();
1664
+ }
1665
+ function getDataValidationDiffMutations(unitId, subUnitId, diffs, accessor, source = "command", fillDefaultValue = true) {
1666
+ const lexerTreeBuilder = accessor.get(LexerTreeBuilder);
1667
+ const validatorRegistryService = accessor.get(DataValidatorRegistryService);
1668
+ const redoMutations = [];
1669
+ const undoMutations = [];
1670
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
1671
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), {
1672
+ unitId,
1673
+ subUnitId
1674
+ });
1675
+ if (!target) return {
1676
+ redoMutations,
1677
+ undoMutations
1678
+ };
1679
+ const { worksheet } = target;
1680
+ const redoMatrix = new ObjectMatrix();
1681
+ let setRangeValue = false;
1682
+ function setRangesDefaultValue(ranges, defaultValue) {
1683
+ if (!fillDefaultValue) return;
1684
+ ranges.forEach((range) => {
1685
+ Range.foreach(range, (row, column) => {
1686
+ const cellData = worksheet.getCellRaw(row, column);
1687
+ const value = getStringCellValue(cellData);
1688
+ if ((isBlankCell(cellData) || value === defaultValue) && !(cellData === null || cellData === void 0 ? void 0 : cellData.p)) {
1689
+ setRangeValue = true;
1690
+ redoMatrix.setValue(row, column, {
1691
+ v: defaultValue,
1692
+ p: null
1693
+ });
1694
+ }
1695
+ });
1696
+ });
1697
+ }
1698
+ diffs.forEach((diff) => {
1699
+ switch (diff.type) {
1700
+ case "delete":
1701
+ redoMutations.push({
1702
+ id: RemoveDataValidationMutation.id,
1703
+ params: {
1704
+ unitId,
1705
+ subUnitId,
1706
+ ruleId: diff.rule.uid,
1707
+ source
1708
+ }
1709
+ });
1710
+ undoMutations.unshift({
1711
+ id: AddDataValidationMutation.id,
1712
+ params: {
1713
+ unitId,
1714
+ subUnitId,
1715
+ rule: diff.rule,
1716
+ index: diff.index,
1717
+ source
1718
+ }
1719
+ });
1720
+ break;
1721
+ case "update": {
1722
+ if (shouldOffsetFormulaByRange(diff.rule.type, validatorRegistryService)) {
1723
+ const originRow = diff.oldRanges[0].startRow;
1724
+ const originColumn = diff.oldRanges[0].startColumn;
1725
+ const newRow = diff.newRanges[0].startRow;
1726
+ const newColumn = diff.newRanges[0].startColumn;
1727
+ const rowDiff = newRow - originRow;
1728
+ const columnDiff = newColumn - originColumn;
1729
+ const newFormula = isFormulaString(diff.rule.formula1) ? lexerTreeBuilder.moveFormulaRefOffset(diff.rule.formula1, columnDiff, rowDiff) : diff.rule.formula1;
1730
+ const newFormula2 = isFormulaString(diff.rule.formula2) ? lexerTreeBuilder.moveFormulaRefOffset(diff.rule.formula2, columnDiff, rowDiff) : diff.rule.formula2;
1731
+ if (newFormula !== diff.rule.formula1 || newFormula2 !== diff.rule.formula2 || !isRangesEqual(diff.newRanges, diff.oldRanges)) {
1732
+ redoMutations.push({
1733
+ id: UpdateDataValidationMutation.id,
1734
+ params: {
1735
+ unitId,
1736
+ subUnitId,
1737
+ ruleId: diff.ruleId,
1738
+ payload: {
1739
+ type: UpdateRuleType.ALL,
1740
+ payload: {
1741
+ formula1: newFormula,
1742
+ formula2: newFormula2,
1743
+ ranges: diff.newRanges
1744
+ }
1745
+ }
1746
+ }
1747
+ });
1748
+ undoMutations.unshift({
1749
+ id: UpdateDataValidationMutation.id,
1750
+ params: {
1751
+ unitId,
1752
+ subUnitId,
1753
+ ruleId: diff.ruleId,
1754
+ payload: {
1755
+ type: UpdateRuleType.ALL,
1756
+ payload: {
1757
+ formula1: diff.rule.formula1,
1758
+ formula2: diff.rule.formula2,
1759
+ ranges: diff.oldRanges
1760
+ }
1761
+ }
1762
+ }
1763
+ });
1764
+ } else {
1765
+ redoMutations.push({
1766
+ id: UpdateDataValidationMutation.id,
1767
+ params: {
1768
+ unitId,
1769
+ subUnitId,
1770
+ ruleId: diff.ruleId,
1771
+ payload: {
1772
+ type: UpdateRuleType.RANGE,
1773
+ payload: diff.newRanges
1774
+ },
1775
+ source
1776
+ }
1777
+ });
1778
+ undoMutations.unshift({
1779
+ id: UpdateDataValidationMutation.id,
1780
+ params: {
1781
+ unitId,
1782
+ subUnitId,
1783
+ ruleId: diff.ruleId,
1784
+ payload: {
1785
+ type: UpdateRuleType.RANGE,
1786
+ payload: diff.oldRanges
1787
+ },
1788
+ source
1789
+ }
1790
+ });
1791
+ }
1792
+ } else {
1793
+ redoMutations.push({
1794
+ id: UpdateDataValidationMutation.id,
1795
+ params: {
1796
+ unitId,
1797
+ subUnitId,
1798
+ ruleId: diff.ruleId,
1799
+ payload: {
1800
+ type: UpdateRuleType.RANGE,
1801
+ payload: diff.newRanges
1802
+ },
1803
+ source
1804
+ }
1805
+ });
1806
+ undoMutations.unshift({
1807
+ id: UpdateDataValidationMutation.id,
1808
+ params: {
1809
+ unitId,
1810
+ subUnitId,
1811
+ ruleId: diff.ruleId,
1812
+ payload: {
1813
+ type: UpdateRuleType.RANGE,
1814
+ payload: diff.oldRanges
1815
+ },
1816
+ source
1817
+ }
1818
+ });
1819
+ }
1820
+ const rule = sheetDataValidationModel.getRuleById(unitId, subUnitId, diff.ruleId);
1821
+ if (rule && rule.type === DataValidationType.CHECKBOX) {
1822
+ const formula = sheetDataValidationModel.getValidator(DataValidationType.CHECKBOX).parseFormulaSync(rule, unitId, subUnitId);
1823
+ setRangesDefaultValue(diff.newRanges, formula.formula2);
1824
+ }
1825
+ break;
1826
+ }
1827
+ case "add":
1828
+ redoMutations.push({
1829
+ id: AddDataValidationMutation.id,
1830
+ params: {
1831
+ unitId,
1832
+ subUnitId,
1833
+ rule: diff.rule,
1834
+ source
1835
+ }
1836
+ });
1837
+ undoMutations.unshift({
1838
+ id: RemoveDataValidationMutation.id,
1839
+ params: {
1840
+ unitId,
1841
+ subUnitId,
1842
+ ruleId: diff.rule.uid,
1843
+ source
1844
+ }
1845
+ });
1846
+ if (diff.rule.type === DataValidationType.CHECKBOX) {
1847
+ const formula = sheetDataValidationModel.getValidator(DataValidationType.CHECKBOX).parseFormulaSync(diff.rule, unitId, subUnitId);
1848
+ setRangesDefaultValue(diff.rule.ranges, formula.originFormula2);
1849
+ }
1850
+ break;
1851
+ default: break;
1852
+ }
1853
+ });
1854
+ if (setRangeValue) {
1855
+ const redoSetRangeValues = {
1856
+ id: SetRangeValuesMutation.id,
1857
+ params: {
1858
+ unitId,
1859
+ subUnitId,
1860
+ cellValue: redoMatrix.getData()
1861
+ }
1862
+ };
1863
+ const undoSetRangeValues = {
1864
+ id: SetRangeValuesMutation.id,
1865
+ params: SetRangeValuesUndoMutationFactory(accessor, redoSetRangeValues.params)
1866
+ };
1867
+ redoMutations.push(redoSetRangeValues);
1868
+ undoMutations.push(undoSetRangeValues);
1869
+ }
1870
+ return {
1871
+ redoMutations,
1872
+ undoMutations
1873
+ };
1874
+ }
1875
+ const UpdateSheetDataValidationRangeCommand = {
1876
+ type: CommandType.COMMAND,
1877
+ id: "sheet.command.updateDataValidationRuleRange",
1878
+ handler(accessor, params) {
1879
+ if (!params) return false;
1880
+ const { unitId, subUnitId, ranges, ruleId } = params;
1881
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
1882
+ const commandService = accessor.get(ICommandService);
1883
+ const undoRedoService = accessor.get(IUndoRedoService);
1884
+ if (!sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId)) return false;
1885
+ const matrix = sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId).clone();
1886
+ matrix.updateRange(ruleId, ranges);
1887
+ const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, matrix.diff(sheetDataValidationModel.getRules(unitId, subUnitId)), accessor);
1888
+ undoRedoService.pushUndoRedo({
1889
+ undoMutations,
1890
+ redoMutations,
1891
+ unitID: unitId
1892
+ });
1893
+ sequenceExecute(redoMutations, commandService);
1894
+ return true;
1895
+ }
1896
+ };
1897
+ const AddSheetDataValidationCommand = {
1898
+ type: CommandType.COMMAND,
1899
+ id: "sheet.command.addDataValidation",
1900
+ handler(accessor, params) {
1901
+ if (!params) return false;
1902
+ const { unitId, subUnitId, rule } = params;
1903
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
1904
+ const commandService = accessor.get(ICommandService);
1905
+ const undoRedoService = accessor.get(IUndoRedoService);
1906
+ const matrix = sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId).clone();
1907
+ matrix.addRule(rule);
1908
+ const diffs = matrix.diff(sheetDataValidationModel.getRules(unitId, subUnitId));
1909
+ const validator = sheetDataValidationModel.getValidator(rule.type);
1910
+ const mutationParams = {
1911
+ unitId,
1912
+ subUnitId,
1913
+ rule: {
1914
+ ...rule,
1915
+ ...validator === null || validator === void 0 ? void 0 : validator.normalizeFormula(rule, unitId, subUnitId)
1916
+ }
1917
+ };
1918
+ const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, diffs, accessor);
1919
+ redoMutations.push({
1920
+ id: AddDataValidationMutation.id,
1921
+ params: mutationParams
1922
+ });
1923
+ undoMutations.unshift({
1924
+ id: RemoveDataValidationMutation.id,
1925
+ params: {
1926
+ unitId,
1927
+ subUnitId,
1928
+ ruleId: rule.uid
1929
+ }
1930
+ });
1931
+ undoRedoService.pushUndoRedo({
1932
+ unitID: unitId,
1933
+ redoMutations,
1934
+ undoMutations
1935
+ });
1936
+ sequenceExecute(redoMutations, commandService);
1937
+ return true;
1938
+ }
1939
+ };
1940
+ const UpdateSheetDataValidationSettingCommand = {
1941
+ type: CommandType.COMMAND,
1942
+ id: "sheets.command.update-data-validation-setting",
1943
+ handler(accessor, params) {
1944
+ if (!params) return false;
1945
+ const commandService = accessor.get(ICommandService);
1946
+ const redoUndoService = accessor.get(IUndoRedoService);
1947
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
1948
+ const dataValidatorRegistryService = accessor.get(DataValidatorRegistryService);
1949
+ const { unitId, subUnitId, ruleId, setting } = params;
1950
+ const validator = dataValidatorRegistryService.getValidatorItem(setting.type);
1951
+ if (!validator) return false;
1952
+ const rule = sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId);
1953
+ if (!rule) return false;
1954
+ const newRule = {
1955
+ ...rule,
1956
+ ...setting
1957
+ };
1958
+ if (!validator.validatorFormula(newRule, unitId, subUnitId).success) return false;
1959
+ const mutationParams = {
1960
+ unitId,
1961
+ subUnitId,
1962
+ ruleId,
1963
+ payload: {
1964
+ type: UpdateRuleType.SETTING,
1965
+ payload: {
1966
+ ...setting,
1967
+ ...validator.normalizeFormula(newRule, unitId, subUnitId)
1968
+ }
1969
+ }
1970
+ };
1971
+ const redoMutations = [{
1972
+ id: UpdateDataValidationMutation.id,
1973
+ params: mutationParams
1974
+ }];
1975
+ const undoMutationParams = {
1976
+ unitId,
1977
+ subUnitId,
1978
+ ruleId,
1979
+ payload: {
1980
+ type: UpdateRuleType.SETTING,
1981
+ payload: getRuleSetting(rule)
1982
+ }
1983
+ };
1984
+ const undoMutations = [{
1985
+ id: UpdateDataValidationMutation.id,
1986
+ params: undoMutationParams
1987
+ }];
1988
+ if (setting.type === DataValidationType.CHECKBOX) {
1989
+ const ranges = rule.ranges;
1990
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), {
1991
+ unitId,
1992
+ subUnitId
1993
+ });
1994
+ if (target) {
1995
+ const redoMatrix = new ObjectMatrix();
1996
+ const { worksheet } = target;
1997
+ const { formula2: oldFormula2 = 0, formula1: oldFormula1 = 1 } = rule;
1998
+ const { formula2 = 0, formula1 = 1 } = setting;
1999
+ let setted = false;
2000
+ ranges.forEach((range) => {
2001
+ Range.foreach(range, (row, column) => {
2002
+ const cellData = worksheet.getCellRaw(row, column);
2003
+ const value = getStringCellValue(cellData);
2004
+ if ((isBlankCell(cellData) || value === String(oldFormula2)) && !(cellData === null || cellData === void 0 ? void 0 : cellData.p)) {
2005
+ redoMatrix.setValue(row, column, {
2006
+ v: formula2,
2007
+ p: null
2008
+ });
2009
+ setted = true;
2010
+ } else if (value === String(oldFormula1) && !(cellData === null || cellData === void 0 ? void 0 : cellData.p)) {
2011
+ redoMatrix.setValue(row, column, {
2012
+ v: formula1,
2013
+ p: null
2014
+ });
2015
+ setted = true;
2016
+ }
2017
+ });
2018
+ });
2019
+ if (setted) {
2020
+ const redoSetRangeValues = {
2021
+ id: SetRangeValuesMutation.id,
2022
+ params: {
2023
+ unitId,
2024
+ subUnitId,
2025
+ cellValue: redoMatrix.getData()
2026
+ }
2027
+ };
2028
+ const undoSetRangeValues = {
2029
+ id: SetRangeValuesMutation.id,
2030
+ params: SetRangeValuesUndoMutationFactory(accessor, redoSetRangeValues.params)
2031
+ };
2032
+ redoMutations.push(redoSetRangeValues);
2033
+ undoMutations.push(undoSetRangeValues);
2034
+ }
2035
+ }
2036
+ }
2037
+ if (sequenceExecute(redoMutations, commandService).result) {
2038
+ redoUndoService.pushUndoRedo({
2039
+ unitID: unitId,
2040
+ redoMutations,
2041
+ undoMutations
2042
+ });
2043
+ return true;
2044
+ }
2045
+ return false;
2046
+ }
2047
+ };
2048
+ const UpdateSheetDataValidationOptionsCommand = {
2049
+ type: CommandType.COMMAND,
2050
+ id: "sheets.command.update-data-validation-options",
2051
+ handler(accessor, params) {
2052
+ if (!params) return false;
2053
+ const commandService = accessor.get(ICommandService);
2054
+ const redoUndoService = accessor.get(IUndoRedoService);
2055
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
2056
+ const { unitId, subUnitId, ruleId, options } = params;
2057
+ const rule = sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId);
2058
+ if (!rule) return false;
2059
+ const mutationParams = {
2060
+ unitId,
2061
+ subUnitId,
2062
+ ruleId,
2063
+ payload: {
2064
+ type: UpdateRuleType.OPTIONS,
2065
+ payload: options
2066
+ }
2067
+ };
2068
+ const redoMutations = [{
2069
+ id: UpdateDataValidationMutation.id,
2070
+ params: mutationParams
2071
+ }];
2072
+ const undoMutationParams = {
2073
+ unitId,
2074
+ subUnitId,
2075
+ ruleId,
2076
+ payload: {
2077
+ type: UpdateRuleType.OPTIONS,
2078
+ payload: getRuleOptions(rule)
2079
+ }
2080
+ };
2081
+ const undoMutations = [{
2082
+ id: UpdateDataValidationMutation.id,
2083
+ params: undoMutationParams
2084
+ }];
2085
+ redoUndoService.pushUndoRedo({
2086
+ unitID: unitId,
2087
+ redoMutations,
2088
+ undoMutations
2089
+ });
2090
+ commandService.executeCommand(UpdateDataValidationMutation.id, mutationParams);
2091
+ return true;
2092
+ }
2093
+ };
2094
+ const ClearRangeDataValidationCommand = {
2095
+ type: CommandType.COMMAND,
2096
+ id: "sheets.command.clear-range-data-validation",
2097
+ handler(accessor, params) {
2098
+ if (!params) return false;
2099
+ const { unitId, subUnitId, ranges } = params;
2100
+ const commandService = accessor.get(ICommandService);
2101
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), {
2102
+ unitId,
2103
+ subUnitId
2104
+ });
2105
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
2106
+ if (!target) return false;
2107
+ const undoRedoService = accessor.get(IUndoRedoService);
2108
+ const matrix = sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId).clone();
2109
+ matrix.removeRange(ranges);
2110
+ const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, matrix.diff(sheetDataValidationModel.getRules(unitId, subUnitId)), accessor);
2111
+ undoRedoService.pushUndoRedo({
2112
+ unitID: unitId,
2113
+ redoMutations,
2114
+ undoMutations
2115
+ });
2116
+ return sequenceExecute(redoMutations, commandService).result;
2117
+ }
2118
+ };
2119
+ const RemoveSheetAllDataValidationCommand = {
2120
+ type: CommandType.COMMAND,
2121
+ id: "sheet.command.remove-all-data-validation",
2122
+ handler(accessor, params) {
2123
+ if (!params) return false;
2124
+ const { unitId, subUnitId } = params;
2125
+ const commandService = accessor.get(ICommandService);
2126
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
2127
+ const undoRedoService = accessor.get(IUndoRedoService);
2128
+ const currentRules = [...sheetDataValidationModel.getRules(unitId, subUnitId)];
2129
+ const redoParams = {
2130
+ unitId,
2131
+ subUnitId,
2132
+ ruleId: currentRules.map((rule) => rule.uid)
2133
+ };
2134
+ const redoMutations = [{
2135
+ id: RemoveDataValidationMutation.id,
2136
+ params: redoParams
2137
+ }];
2138
+ const undoMutations = [{
2139
+ id: AddDataValidationMutation.id,
2140
+ params: {
2141
+ unitId,
2142
+ subUnitId,
2143
+ rule: currentRules
2144
+ }
2145
+ }];
2146
+ undoRedoService.pushUndoRedo({
2147
+ redoMutations,
2148
+ undoMutations,
2149
+ unitID: unitId
2150
+ });
2151
+ commandService.executeCommand(RemoveDataValidationMutation.id, redoParams);
2152
+ return true;
2153
+ }
2154
+ };
2155
+ const removeDataValidationUndoFactory = (accessor, redoParams) => {
2156
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
2157
+ const { unitId, subUnitId, ruleId, source } = redoParams;
2158
+ if (Array.isArray(ruleId)) {
2159
+ const rules = ruleId.map((id) => sheetDataValidationModel.getRuleById(unitId, subUnitId, id)).filter(Boolean);
2160
+ return [{
2161
+ id: AddDataValidationMutation.id,
2162
+ params: {
2163
+ unitId,
2164
+ subUnitId,
2165
+ rule: rules,
2166
+ source
2167
+ }
2168
+ }];
2169
+ }
2170
+ return [{
2171
+ id: AddDataValidationMutation.id,
2172
+ params: {
2173
+ unitId,
2174
+ subUnitId,
2175
+ rule: { ...sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId) },
2176
+ index: sheetDataValidationModel.getRuleIndex(unitId, subUnitId, ruleId)
2177
+ }
2178
+ }];
2179
+ };
2180
+ const RemoveSheetDataValidationCommand = {
2181
+ type: CommandType.COMMAND,
2182
+ id: "sheet.command.remove-data-validation-rule",
2183
+ handler(accessor, params) {
2184
+ if (!params) return false;
2185
+ const { unitId, subUnitId, ruleId } = params;
2186
+ const commandService = accessor.get(ICommandService);
2187
+ const undoRedoService = accessor.get(IUndoRedoService);
2188
+ const sheetDataValidationModel = accessor.get(SheetDataValidationModel);
2189
+ const redoMutations = [{
2190
+ id: RemoveDataValidationMutation.id,
2191
+ params
2192
+ }];
2193
+ const undoMutations = [{
2194
+ id: AddDataValidationMutation.id,
2195
+ params: {
2196
+ unitId,
2197
+ subUnitId,
2198
+ rule: { ...sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId) },
2199
+ index: sheetDataValidationModel.getRuleIndex(unitId, subUnitId, ruleId)
2200
+ }
2201
+ }];
2202
+ undoRedoService.pushUndoRedo({
2203
+ undoMutations,
2204
+ redoMutations,
2205
+ unitID: params.unitId
2206
+ });
2207
+ commandService.executeCommand(RemoveDataValidationMutation.id, params);
2208
+ return true;
2209
+ }
2210
+ };
2211
+
2212
+ //#endregion
2213
+ //#region src/common/const.ts
2214
+ /**
2215
+ * Copyright 2023-present DreamNum Co., Ltd.
2216
+ *
2217
+ * Licensed under the Apache License, Version 2.0 (the "License");
2218
+ * you may not use this file except in compliance with the License.
2219
+ * You may obtain a copy of the License at
2220
+ *
2221
+ * http://www.apache.org/licenses/LICENSE-2.0
2222
+ *
2223
+ * Unless required by applicable law or agreed to in writing, software
2224
+ * distributed under the License is distributed on an "AS IS" BASIS,
2225
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2226
+ * See the License for the specific language governing permissions and
2227
+ * limitations under the License.
2228
+ */
2229
+ const DATA_VALIDATION_PLUGIN_NAME = "SHEET_DATA_VALIDATION_PLUGIN";
2230
+
2231
+ //#endregion
2232
+ //#region src/controllers/dv-formula.controller.ts
2233
+ let DataValidationFormulaController = class DataValidationFormulaController extends Disposable {
2234
+ constructor(_univerInstanceService, _permissionService, _lexerTreeBuilder) {
2235
+ super();
2236
+ this._univerInstanceService = _univerInstanceService;
2237
+ this._permissionService = _permissionService;
2238
+ this._lexerTreeBuilder = _lexerTreeBuilder;
2239
+ }
2240
+ getFormulaRefCheck(formulaString) {
2241
+ const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString);
2242
+ if (!sequenceNodes) return true;
2243
+ for (let i = 0; i < sequenceNodes.length; i++) {
2244
+ const node = sequenceNodes[i];
2245
+ if (typeof node === "string") continue;
2246
+ const { token } = node;
2247
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
2248
+ const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET);
2249
+ let targetSheet = workbook.getActiveSheet();
2250
+ const unitId = workbook.getUnitId();
2251
+ if (sequenceGrid.sheetName) {
2252
+ targetSheet = workbook.getSheetBySheetName(sequenceGrid.sheetName);
2253
+ if (!targetSheet) return false;
2254
+ const subUnitId = targetSheet === null || targetSheet === void 0 ? void 0 : targetSheet.getSheetId();
2255
+ if (!this._permissionService.getPermissionPoint(new WorksheetViewPermission(unitId, subUnitId).id)) return false;
2256
+ }
2257
+ if (!targetSheet) return false;
2258
+ const { startRow, endRow, startColumn, endColumn } = sequenceGrid.range;
2259
+ for (let i = startRow; i <= endRow; i++) for (let j = startColumn; j <= endColumn; j++) {
2260
+ var _targetSheet$getCell;
2261
+ const permission = (_targetSheet$getCell = targetSheet.getCell(i, j)) === null || _targetSheet$getCell === void 0 || (_targetSheet$getCell = _targetSheet$getCell.selectionProtection) === null || _targetSheet$getCell === void 0 ? void 0 : _targetSheet$getCell[0];
2262
+ if ((permission === null || permission === void 0 ? void 0 : permission[UnitAction.View]) === false) return false;
2263
+ }
2264
+ }
2265
+ return true;
2266
+ }
2267
+ };
2268
+ DataValidationFormulaController = __decorate([
2269
+ __decorateParam(0, IUniverInstanceService),
2270
+ __decorateParam(1, IPermissionService),
2271
+ __decorateParam(2, Inject(LexerTreeBuilder))
2272
+ ], DataValidationFormulaController);
2273
+
2274
+ //#endregion
2275
+ //#region package.json
2276
+ var name = "@univerjs/sheets-data-validation";
2277
+ var version = "0.21.0";
2278
+
2279
+ //#endregion
2280
+ //#region src/config/config.ts
2281
+ /**
2282
+ * Copyright 2023-present DreamNum Co., Ltd.
2283
+ *
2284
+ * Licensed under the Apache License, Version 2.0 (the "License");
2285
+ * you may not use this file except in compliance with the License.
2286
+ * You may obtain a copy of the License at
2287
+ *
2288
+ * http://www.apache.org/licenses/LICENSE-2.0
2289
+ *
2290
+ * Unless required by applicable law or agreed to in writing, software
2291
+ * distributed under the License is distributed on an "AS IS" BASIS,
2292
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2293
+ * See the License for the specific language governing permissions and
2294
+ * limitations under the License.
2295
+ */
2296
+ const SHEETS_DATA_VALIDATION_PLUGIN_CONFIG_KEY = "sheets-data-validation.config";
2297
+ const configSymbol = Symbol(SHEETS_DATA_VALIDATION_PLUGIN_CONFIG_KEY);
2298
+ const defaultPluginConfig = {};
2299
+
2300
+ //#endregion
2301
+ //#region src/controllers/dv-formula-ref-range.controller.ts
2302
+ let DataValidationFormulaRefRangeController = class DataValidationFormulaRefRangeController extends Disposable {
2303
+ constructor(_dataValidationModel, _formulaRefRangeService, _validatorRegistryService) {
2304
+ super();
2305
+ this._dataValidationModel = _dataValidationModel;
2306
+ this._formulaRefRangeService = _formulaRefRangeService;
2307
+ this._validatorRegistryService = _validatorRegistryService;
2308
+ _defineProperty(this, "_disposableMap", /* @__PURE__ */ new Map());
2309
+ _defineProperty(this, "registerRule", (unitId, subUnitId, rule) => {
2310
+ if (!shouldOffsetFormulaByRange(rule.type, this._validatorRegistryService)) return;
2311
+ this.register(unitId, subUnitId, rule);
2312
+ });
2313
+ this._initRefRange();
2314
+ }
2315
+ _getIdWithUnitId(unitID, subUnitId, ruleId) {
2316
+ return `${unitID}_${subUnitId}_${ruleId}`;
2317
+ }
2318
+ register(unitId, subUnitId, rule) {
2319
+ const oldRanges = rule.ranges;
2320
+ const oldFormula1 = rule.formula1;
2321
+ const oldFormula2 = rule.formula2;
2322
+ const disposable = this._formulaRefRangeService.registerRangeFormula(unitId, subUnitId, oldRanges, [oldFormula1 !== null && oldFormula1 !== void 0 ? oldFormula1 : "", oldFormula2 !== null && oldFormula2 !== void 0 ? oldFormula2 : ""], (res) => {
2323
+ if (res.length === 0) return {
2324
+ undos: [{
2325
+ id: AddDataValidationMutation.id,
2326
+ params: {
2327
+ unitId,
2328
+ subUnitId,
2329
+ rule,
2330
+ source: "patched"
2331
+ }
2332
+ }],
2333
+ redos: [{
2334
+ id: RemoveDataValidationMutation.id,
2335
+ params: {
2336
+ unitId,
2337
+ subUnitId,
2338
+ ruleId: rule.uid,
2339
+ source: "patched"
2340
+ }
2341
+ }]
2342
+ };
2343
+ const redos = [];
2344
+ const undos = [];
2345
+ const first = res[0];
2346
+ redos.push({
2347
+ id: UpdateDataValidationMutation.id,
2348
+ params: {
2349
+ unitId,
2350
+ subUnitId,
2351
+ ruleId: rule.uid,
2352
+ payload: {
2353
+ type: UpdateRuleType.ALL,
2354
+ payload: {
2355
+ ranges: first.ranges,
2356
+ formula1: first.formulas[0],
2357
+ formula2: first.formulas[1]
2358
+ }
2359
+ },
2360
+ source: "patched"
2361
+ }
2362
+ });
2363
+ undos.push({
2364
+ id: UpdateDataValidationMutation.id,
2365
+ params: {
2366
+ unitId,
2367
+ subUnitId,
2368
+ ruleId: rule.uid,
2369
+ payload: {
2370
+ type: UpdateRuleType.ALL,
2371
+ payload: {
2372
+ ranges: oldRanges,
2373
+ formula1: oldFormula1,
2374
+ formula2: oldFormula2
2375
+ }
2376
+ },
2377
+ source: "patched"
2378
+ }
2379
+ });
2380
+ for (let i = 1; i < res.length; i++) {
2381
+ const item = res[i];
2382
+ const id = generateRandomId();
2383
+ redos.push({
2384
+ id: AddDataValidationMutation.id,
2385
+ params: {
2386
+ unitId,
2387
+ subUnitId,
2388
+ rule: {
2389
+ ...rule,
2390
+ uid: id,
2391
+ formula1: item.formulas[0],
2392
+ formula2: item.formulas[1],
2393
+ ranges: item.ranges
2394
+ },
2395
+ source: "patched"
2396
+ }
2397
+ });
2398
+ undos.push({
2399
+ id: RemoveDataValidationMutation.id,
2400
+ params: {
2401
+ unitId,
2402
+ subUnitId,
2403
+ ruleId: id,
2404
+ source: "patched"
2405
+ }
2406
+ });
2407
+ }
2408
+ return {
2409
+ undos,
2410
+ redos
2411
+ };
2412
+ });
2413
+ const id = this._getIdWithUnitId(unitId, subUnitId, rule.uid);
2414
+ this._disposableMap.set(id, disposable);
2415
+ }
2416
+ _initRefRange() {
2417
+ const allRules = this._dataValidationModel.getAll();
2418
+ for (const [unitId, subUnitMap] of allRules) for (const [subUnitId, rules] of subUnitMap) for (const rule of rules) this.registerRule(unitId, subUnitId, rule);
2419
+ this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe((option) => {
2420
+ const { unitId, subUnitId, rule } = option;
2421
+ switch (option.type) {
2422
+ case "add": {
2423
+ const rule = option.rule;
2424
+ this.registerRule(option.unitId, option.subUnitId, rule);
2425
+ break;
2426
+ }
2427
+ case "remove": {
2428
+ const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule.uid));
2429
+ if (disposeSet) disposeSet.dispose();
2430
+ break;
2431
+ }
2432
+ case "update": {
2433
+ const rule = option.rule;
2434
+ const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule.uid));
2435
+ if (disposeSet) disposeSet.dispose();
2436
+ this.registerRule(option.unitId, option.subUnitId, rule);
2437
+ break;
2438
+ }
2439
+ }
2440
+ }));
2441
+ this.disposeWithMe(toDisposable(() => {
2442
+ this._disposableMap.forEach((item) => {
2443
+ item.dispose();
2444
+ });
2445
+ this._disposableMap.clear();
2446
+ }));
2447
+ }
2448
+ };
2449
+ DataValidationFormulaRefRangeController = __decorate([
2450
+ __decorateParam(0, Inject(SheetDataValidationModel)),
2451
+ __decorateParam(1, Inject(FormulaRefRangeService)),
2452
+ __decorateParam(2, Inject(DataValidatorRegistryService))
2453
+ ], DataValidationFormulaRefRangeController);
2454
+
2455
+ //#endregion
2456
+ //#region src/controllers/dv-ref-range.controller.ts
2457
+ let DataValidationRefRangeController = class DataValidationRefRangeController extends Disposable {
2458
+ constructor(_dataValidationModel, _injector, _refRangeService, _dataValidationFormulaService, _formulaRefRangeService, _validatorRegistryService) {
2459
+ super();
2460
+ this._dataValidationModel = _dataValidationModel;
2461
+ this._injector = _injector;
2462
+ this._refRangeService = _refRangeService;
2463
+ this._dataValidationFormulaService = _dataValidationFormulaService;
2464
+ this._formulaRefRangeService = _formulaRefRangeService;
2465
+ this._validatorRegistryService = _validatorRegistryService;
2466
+ _defineProperty(this, "_disposableMap", /* @__PURE__ */ new Map());
2467
+ _defineProperty(this, "registerRule", (unitId, subUnitId, rule) => {
2468
+ if (shouldOffsetFormulaByRange(rule.type, this._validatorRegistryService)) return;
2469
+ this.register(unitId, subUnitId, rule);
2470
+ this.registerFormula(unitId, subUnitId, rule);
2471
+ });
2472
+ this._initRefRange();
2473
+ }
2474
+ _getIdWithUnitId(unitID, subUnitId, ruleId) {
2475
+ return `${unitID}_${subUnitId}_${ruleId}`;
2476
+ }
2477
+ registerFormula(unitId, subUnitId, rule) {
2478
+ var _this$_disposableMap$;
2479
+ const ruleId = rule.uid;
2480
+ const id = this._getIdWithUnitId(unitId, subUnitId, ruleId);
2481
+ const disposeSet = (_this$_disposableMap$ = this._disposableMap.get(id)) !== null && _this$_disposableMap$ !== void 0 ? _this$_disposableMap$ : /* @__PURE__ */ new Set();
2482
+ const handleFormulaChange = (type, formulaString) => {
2483
+ const oldRule = this._dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
2484
+ if (!oldRule) return {
2485
+ redos: [],
2486
+ undos: []
2487
+ };
2488
+ const oldFormula = oldRule[type];
2489
+ if (!oldFormula || oldFormula === formulaString) return {
2490
+ redos: [],
2491
+ undos: []
2492
+ };
2493
+ const redoParams = {
2494
+ unitId,
2495
+ subUnitId,
2496
+ ruleId: rule.uid,
2497
+ payload: {
2498
+ type: UpdateRuleType.SETTING,
2499
+ payload: {
2500
+ type: oldRule.type,
2501
+ formula1: oldRule.formula1,
2502
+ formula2: oldRule.formula2,
2503
+ [type]: formulaString
2504
+ }
2505
+ },
2506
+ source: "patched"
2507
+ };
2508
+ const undoParams = {
2509
+ unitId,
2510
+ subUnitId,
2511
+ ruleId: rule.uid,
2512
+ payload: {
2513
+ type: UpdateRuleType.SETTING,
2514
+ payload: {
2515
+ type: oldRule.type,
2516
+ formula1: oldRule.formula1,
2517
+ formula2: oldRule.formula2
2518
+ }
2519
+ },
2520
+ source: "patched"
2521
+ };
2522
+ return {
2523
+ redos: [{
2524
+ id: UpdateDataValidationMutation.id,
2525
+ params: redoParams
2526
+ }],
2527
+ undos: [{
2528
+ id: UpdateDataValidationMutation.id,
2529
+ params: undoParams
2530
+ }]
2531
+ };
2532
+ };
2533
+ const currentFormula = this._dataValidationFormulaService.getRuleFormulaInfo(unitId, subUnitId, ruleId);
2534
+ if (currentFormula) {
2535
+ const [formula1, formula2] = currentFormula;
2536
+ if (formula1) {
2537
+ const disposable = this._formulaRefRangeService.registerFormula(unitId, subUnitId, formula1.text, (newFormulaString) => handleFormulaChange("formula1", newFormulaString));
2538
+ disposeSet.add(() => disposable.dispose());
2539
+ }
2540
+ if (formula2) {
2541
+ const disposable = this._formulaRefRangeService.registerFormula(unitId, subUnitId, formula2.text, (newFormulaString) => handleFormulaChange("formula2", newFormulaString));
2542
+ disposeSet.add(() => disposable.dispose());
2543
+ }
2544
+ }
2545
+ }
2546
+ register(unitId, subUnitId, rule) {
2547
+ var _this$_disposableMap$2;
2548
+ const handleRangeChange = (commandInfo) => {
2549
+ const oldRanges = [...rule.ranges];
2550
+ const resultRanges = oldRanges.map((range) => {
2551
+ return handleCommonDefaultRangeChangeWithEffectRefCommands(range, commandInfo);
2552
+ }).filter((range) => !!range).flat();
2553
+ if (isRangesEqual(resultRanges, oldRanges)) return {
2554
+ redos: [],
2555
+ undos: []
2556
+ };
2557
+ if (resultRanges.length) {
2558
+ const redoParams = {
2559
+ unitId,
2560
+ subUnitId,
2561
+ ruleId: rule.uid,
2562
+ payload: {
2563
+ type: UpdateRuleType.RANGE,
2564
+ payload: resultRanges
2565
+ },
2566
+ source: "patched"
2567
+ };
2568
+ return {
2569
+ redos: [{
2570
+ id: UpdateDataValidationMutation.id,
2571
+ params: redoParams
2572
+ }],
2573
+ undos: [{
2574
+ id: UpdateDataValidationMutation.id,
2575
+ params: {
2576
+ unitId,
2577
+ subUnitId,
2578
+ ruleId: rule.uid,
2579
+ payload: {
2580
+ type: UpdateRuleType.RANGE,
2581
+ payload: oldRanges
2582
+ },
2583
+ source: "patched"
2584
+ }
2585
+ }]
2586
+ };
2587
+ } else {
2588
+ const redoParams = {
2589
+ unitId,
2590
+ subUnitId,
2591
+ ruleId: rule.uid
2592
+ };
2593
+ return {
2594
+ redos: [{
2595
+ id: RemoveDataValidationMutation.id,
2596
+ params: redoParams
2597
+ }],
2598
+ undos: removeDataValidationUndoFactory(this._injector, redoParams)
2599
+ };
2600
+ }
2601
+ };
2602
+ const disposeList = [];
2603
+ rule.ranges.forEach((range) => {
2604
+ const disposable = this._refRangeService.registerRefRange(range, handleRangeChange, unitId, subUnitId);
2605
+ disposeList.push(() => disposable.dispose());
2606
+ });
2607
+ const id = this._getIdWithUnitId(unitId, subUnitId, rule.uid);
2608
+ const current = (_this$_disposableMap$2 = this._disposableMap.get(id)) !== null && _this$_disposableMap$2 !== void 0 ? _this$_disposableMap$2 : /* @__PURE__ */ new Set();
2609
+ current.add(() => disposeList.forEach((dispose) => dispose()));
2610
+ this._disposableMap.set(id, current);
2611
+ }
2612
+ _initRefRange() {
2613
+ const allRules = this._dataValidationModel.getAll();
2614
+ for (const [unitId, subUnitMap] of allRules) for (const [subUnitId, rules] of subUnitMap) for (const rule of rules) this.registerRule(unitId, subUnitId, rule);
2615
+ this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe((option) => {
2616
+ const { unitId, subUnitId, rule } = option;
2617
+ switch (option.type) {
2618
+ case "add": {
2619
+ const rule = option.rule;
2620
+ this.registerRule(option.unitId, option.subUnitId, rule);
2621
+ break;
2622
+ }
2623
+ case "remove": {
2624
+ const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule.uid));
2625
+ if (disposeSet) disposeSet.forEach((dispose) => dispose());
2626
+ break;
2627
+ }
2628
+ case "update": {
2629
+ const rule = option.rule;
2630
+ const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule.uid));
2631
+ if (disposeSet) disposeSet.forEach((dispose) => dispose());
2632
+ this.registerRule(option.unitId, option.subUnitId, rule);
2633
+ break;
2634
+ }
2635
+ }
2636
+ }));
2637
+ this.disposeWithMe(toDisposable(() => {
2638
+ this._disposableMap.forEach((item) => {
2639
+ item.forEach((dispose) => dispose());
2640
+ });
2641
+ this._disposableMap.clear();
2642
+ }));
2643
+ }
2644
+ };
2645
+ DataValidationRefRangeController = __decorate([
2646
+ __decorateParam(0, Inject(SheetDataValidationModel)),
2647
+ __decorateParam(1, Inject(Injector)),
2648
+ __decorateParam(2, Inject(RefRangeService)),
2649
+ __decorateParam(3, Inject(DataValidationFormulaService)),
2650
+ __decorateParam(4, Inject(FormulaRefRangeService)),
2651
+ __decorateParam(5, Inject(DataValidatorRegistryService))
2652
+ ], DataValidationRefRangeController);
2653
+
2654
+ //#endregion
2655
+ //#region src/controllers/dv-sheet.controller.ts
2656
+ let SheetDataValidationSheetController = class SheetDataValidationSheetController extends Disposable {
2657
+ constructor(_sheetInterceptorService, _univerInstanceService, _sheetDataValidationModel) {
2658
+ super();
2659
+ this._sheetInterceptorService = _sheetInterceptorService;
2660
+ this._univerInstanceService = _univerInstanceService;
2661
+ this._sheetDataValidationModel = _sheetDataValidationModel;
2662
+ this._initSheetChange();
2663
+ }
2664
+ _initSheetChange() {
2665
+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({ getMutations: (commandInfo) => {
2666
+ if (commandInfo.id === RemoveSheetCommand.id) {
2667
+ var _workbook$getActiveSh;
2668
+ const params = commandInfo.params;
2669
+ const unitId = params.unitId || this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET).getUnitId();
2670
+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
2671
+ if (!workbook) return {
2672
+ redos: [],
2673
+ undos: []
2674
+ };
2675
+ const subUnitId = params.subUnitId || ((_workbook$getActiveSh = workbook.getActiveSheet()) === null || _workbook$getActiveSh === void 0 ? void 0 : _workbook$getActiveSh.getSheetId());
2676
+ if (!subUnitId) return {
2677
+ redos: [],
2678
+ undos: []
2679
+ };
2680
+ const rules = this._sheetDataValidationModel.getRules(unitId, subUnitId);
2681
+ if (rules.length === 0) return {
2682
+ redos: [],
2683
+ undos: []
2684
+ };
2685
+ const redoParams = {
2686
+ unitId,
2687
+ subUnitId,
2688
+ ruleId: rules.map((i) => i.uid),
2689
+ source: "patched"
2690
+ };
2691
+ const undoParams = {
2692
+ unitId,
2693
+ subUnitId,
2694
+ rule: [...rules],
2695
+ source: "patched"
2696
+ };
2697
+ return {
2698
+ redos: [{
2699
+ id: RemoveDataValidationMutation.id,
2700
+ params: redoParams
2701
+ }],
2702
+ undos: [{
2703
+ id: AddDataValidationMutation.id,
2704
+ params: undoParams
2705
+ }]
2706
+ };
2707
+ } else if (commandInfo.id === CopySheetCommand.id) {
2708
+ const { unitId, subUnitId, targetSubUnitId } = commandInfo.params;
2709
+ if (!unitId || !subUnitId || !targetSubUnitId) return {
2710
+ redos: [],
2711
+ undos: []
2712
+ };
2713
+ const rules = this._sheetDataValidationModel.getRules(unitId, subUnitId);
2714
+ if (rules.length === 0) return {
2715
+ redos: [],
2716
+ undos: []
2717
+ };
2718
+ const newRules = rules.map((rule) => {
2719
+ return {
2720
+ ...rule,
2721
+ uid: generateRandomId(6)
2722
+ };
2723
+ });
2724
+ return {
2725
+ redos: [{
2726
+ id: AddDataValidationMutation.id,
2727
+ params: {
2728
+ unitId,
2729
+ subUnitId: targetSubUnitId,
2730
+ rule: newRules,
2731
+ source: "patched"
2732
+ }
2733
+ }],
2734
+ undos: [{
2735
+ id: RemoveDataValidationMutation.id,
2736
+ params: {
2737
+ unitId,
2738
+ subUnitId: targetSubUnitId,
2739
+ ruleId: newRules.map((r) => r.uid),
2740
+ source: "patched"
2741
+ }
2742
+ }]
2743
+ };
2744
+ }
2745
+ return {
2746
+ redos: [],
2747
+ undos: []
2748
+ };
2749
+ } }));
2750
+ }
2751
+ };
2752
+ SheetDataValidationSheetController = __decorate([
2753
+ __decorateParam(0, Inject(SheetInterceptorService)),
2754
+ __decorateParam(1, Inject(IUniverInstanceService)),
2755
+ __decorateParam(2, Inject(SheetDataValidationModel))
2756
+ ], SheetDataValidationSheetController);
2757
+
2758
+ //#endregion
2759
+ //#region src/validators/any-validator.ts
2760
+ var AnyValidator = class extends BaseDataValidator {
2761
+ constructor(..._args) {
2762
+ super(..._args);
2763
+ _defineProperty(this, "id", DataValidationType.ANY);
2764
+ _defineProperty(this, "title", "dataValidation.any.title");
2765
+ _defineProperty(this, "operators", []);
2766
+ _defineProperty(this, "scopes", ["sheet"]);
2767
+ _defineProperty(this, "order", 0);
2768
+ _defineProperty(this, "offsetFormulaByRange", false);
2769
+ }
2770
+ async parseFormula(rule, unitId, subUnitId) {
2771
+ return {
2772
+ formula1: rule.formula1,
2773
+ formula2: rule.formula2,
2774
+ isFormulaValid: true
2775
+ };
2776
+ }
2777
+ validatorFormula(rule, unitId, subUnitId) {
2778
+ return { success: true };
2779
+ }
2780
+ async isValidType(cellInfo, formula, rule) {
2781
+ return true;
2782
+ }
2783
+ generateRuleErrorMessage(rule) {
2784
+ return this.localeService.t("dataValidation.any.error");
2785
+ }
2786
+ };
2787
+
2788
+ //#endregion
2789
+ //#region src/validators/custom-validator.ts
2790
+ var CustomFormulaValidator = class extends BaseDataValidator {
2791
+ constructor(..._args) {
2792
+ super(..._args);
2793
+ _defineProperty(this, "id", DataValidationType.CUSTOM);
2794
+ _defineProperty(this, "title", "dataValidation.custom.title");
2795
+ _defineProperty(this, "operators", []);
2796
+ _defineProperty(this, "scopes", ["sheet"]);
2797
+ _defineProperty(this, "order", 60);
2798
+ _defineProperty(this, "_customFormulaService", this.injector.get(DataValidationCustomFormulaService));
2799
+ _defineProperty(this, "_lexerTreeBuilder", this.injector.get(LexerTreeBuilder));
2800
+ }
2801
+ validatorFormula(rule, unitId, subUnitId) {
2802
+ var _rule$formula;
2803
+ const success = isFormulaString(rule.formula1);
2804
+ const formulaText = (_rule$formula = rule.formula1) !== null && _rule$formula !== void 0 ? _rule$formula : "";
2805
+ const valid = this._lexerTreeBuilder.checkIfAddBracket(formulaText) === 0 && formulaText.startsWith(operatorToken.EQUALS);
2806
+ return {
2807
+ success: success && valid,
2808
+ formula1: success && valid ? "" : this.localeService.t("dataValidation.validFail.formula")
2809
+ };
2810
+ }
2811
+ async parseFormula(_rule, _unitId, _subUnitId) {
2812
+ return {
2813
+ formula1: void 0,
2814
+ formula2: void 0,
2815
+ isFormulaValid: true
2816
+ };
2817
+ }
2818
+ async isValidType(cellInfo, _formula, _rule) {
2819
+ const { column, row, unitId, subUnitId } = cellInfo;
2820
+ const cellData = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, _rule.uid, row, column);
2821
+ const formulaResult = cellData === null || cellData === void 0 ? void 0 : cellData.v;
2822
+ if (!isLegalFormulaResult(String(formulaResult))) return false;
2823
+ if (Tools.isDefine(formulaResult) && formulaResult !== "") {
2824
+ if (cellData.t === CellValueType.BOOLEAN) return Boolean(formulaResult);
2825
+ if (typeof formulaResult === "boolean") return formulaResult;
2826
+ if (typeof formulaResult === "number") return Boolean(formulaResult);
2827
+ if (typeof formulaResult === "string") return isLegalFormulaResult(formulaResult);
2828
+ return Boolean(formulaResult);
2829
+ }
2830
+ return false;
2831
+ }
2832
+ generateRuleErrorMessage(rule) {
2833
+ return this.localeService.t("dataValidation.custom.error");
2834
+ }
2835
+ generateRuleName(rule) {
2836
+ var _rule$formula2;
2837
+ return this.localeService.t("dataValidation.custom.ruleName").replace("{FORMULA1}", (_rule$formula2 = rule.formula1) !== null && _rule$formula2 !== void 0 ? _rule$formula2 : "");
2838
+ }
2839
+ };
2840
+
2841
+ //#endregion
2842
+ //#region src/validators/list-multiple-validator.ts
2843
+ /**
2844
+ * Copyright 2023-present DreamNum Co., Ltd.
2845
+ *
2846
+ * Licensed under the Apache License, Version 2.0 (the "License");
2847
+ * you may not use this file except in compliance with the License.
2848
+ * You may obtain a copy of the License at
2849
+ *
2850
+ * http://www.apache.org/licenses/LICENSE-2.0
2851
+ *
2852
+ * Unless required by applicable law or agreed to in writing, software
2853
+ * distributed under the License is distributed on an "AS IS" BASIS,
2854
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2855
+ * See the License for the specific language governing permissions and
2856
+ * limitations under the License.
2857
+ */
2858
+ var ListMultipleValidator = class extends ListValidator {
2859
+ constructor(..._args) {
2860
+ super(..._args);
2861
+ _defineProperty(this, "id", DataValidationType.LIST_MULTIPLE);
2862
+ _defineProperty(this, "title", "dataValidation.listMultiple.title");
2863
+ _defineProperty(this, "offsetFormulaByRange", false);
2864
+ _defineProperty(this, "skipDefaultFontRender", () => {
2865
+ return true;
2866
+ });
2867
+ }
2868
+ };
2869
+
2870
+ //#endregion
2871
+ //#region src/validators/whole-validator.ts
2872
+ var WholeValidator = class extends BaseDataValidator {
2873
+ constructor(..._args) {
2874
+ super(..._args);
2875
+ _defineProperty(this, "_customFormulaService", this.injector.get(DataValidationCustomFormulaService));
2876
+ _defineProperty(this, "_lexerTreeBuilder", this.injector.get(LexerTreeBuilder));
2877
+ _defineProperty(this, "id", DataValidationType.WHOLE);
2878
+ _defineProperty(this, "title", "dataValidation.whole.title");
2879
+ _defineProperty(this, "order", 10);
2880
+ _defineProperty(this, "operators", [
2881
+ DataValidationOperator.BETWEEN,
2882
+ DataValidationOperator.EQUAL,
2883
+ DataValidationOperator.GREATER_THAN,
2884
+ DataValidationOperator.GREATER_THAN_OR_EQUAL,
2885
+ DataValidationOperator.LESS_THAN,
2886
+ DataValidationOperator.LESS_THAN_OR_EQUAL,
2887
+ DataValidationOperator.NOT_BETWEEN,
2888
+ DataValidationOperator.NOT_EQUAL
2889
+ ]);
2890
+ _defineProperty(this, "scopes", ["sheet"]);
2891
+ }
2892
+ _isFormulaOrInt(formula) {
2893
+ return !Tools.isBlank(formula) && (isFormulaString(formula) || !Number.isNaN(+formula) && Number.isInteger(+formula));
2894
+ }
2895
+ async isValidType(cellInfo, _formula, _rule) {
2896
+ const { value: cellValue } = cellInfo;
2897
+ const num = getCellValueNumber(cellValue);
2898
+ return !Number.isNaN(num) && Number.isInteger(num);
2899
+ }
2900
+ transform(cellInfo, _formula, _rule) {
2901
+ const { value: cellValue } = cellInfo;
2902
+ return {
2903
+ ...cellInfo,
2904
+ value: getCellValueNumber(cellValue)
2905
+ };
2906
+ }
2907
+ _parseNumber(formula) {
2908
+ if (formula === void 0 || formula === null) return NaN;
2909
+ return +formula;
2910
+ }
2911
+ async parseFormula(rule, unitId, subUnitId, row, column) {
2912
+ const res1 = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, rule.uid, row, column);
2913
+ const res2 = await this._customFormulaService.getCellFormula2Value(unitId, subUnitId, rule.uid, row, column);
2914
+ const { formula1, formula2 } = rule;
2915
+ const formula1Result = isFormulaString(formula1) ? res1 === null || res1 === void 0 ? void 0 : res1.v : formula1;
2916
+ const formula2Result = isFormulaString(formula2) ? res2 === null || res2 === void 0 ? void 0 : res2.v : formula2;
2917
+ const isFormulaValid = isLegalFormulaResult(`${formula1Result}`) && isLegalFormulaResult(`${formula2Result}`);
2918
+ return {
2919
+ formula1: this._parseNumber(formula1Result),
2920
+ formula2: this._parseNumber(formula2Result),
2921
+ isFormulaValid
2922
+ };
2923
+ }
2924
+ validatorFormula(rule, _unitId, _subUnitId) {
2925
+ const operator = rule.operator;
2926
+ if (!operator) return { success: true };
2927
+ const formula1Success = Tools.isDefine(rule.formula1) && this._isFormulaOrInt(rule.formula1);
2928
+ const formula2Success = Tools.isDefine(rule.formula2) && this._isFormulaOrInt(rule.formula2);
2929
+ const isTwoFormula = TWO_FORMULA_OPERATOR_COUNT.includes(operator);
2930
+ const errorMsg = this.localeService.t("dataValidation.validFail.number");
2931
+ if (isTwoFormula) return {
2932
+ success: formula1Success && formula2Success,
2933
+ formula1: formula1Success ? void 0 : errorMsg,
2934
+ formula2: formula2Success ? void 0 : errorMsg
2935
+ };
2936
+ return {
2937
+ success: formula1Success,
2938
+ formula1: errorMsg
2939
+ };
2940
+ }
2941
+ generateRuleErrorMessage(rule, position) {
2942
+ if (!rule.operator) return this.localeService.t(OperatorErrorTitleMap.NONE).replace("{TYPE}", this.titleStr);
2943
+ const { transformedFormula1, transformedFormula2 } = getTransformedFormula(this._lexerTreeBuilder, rule, position);
2944
+ return `${this.localeService.t(OperatorErrorTitleMap[rule.operator]).replace(FORMULA1, transformedFormula1 !== null && transformedFormula1 !== void 0 ? transformedFormula1 : "").replace(FORMULA2, transformedFormula2 !== null && transformedFormula2 !== void 0 ? transformedFormula2 : "")}`;
2945
+ }
2946
+ };
2947
+
2948
+ //#endregion
2949
+ //#region src/controllers/dv.controller.ts
2950
+ let DataValidationController = class DataValidationController extends RxDisposable {
2951
+ constructor(_univerInstanceService, _dataValidatorRegistryService, _injector, _selectionManagerService, _sheetInterceptorService, _sheetDataValidationModel) {
2952
+ super();
2953
+ this._univerInstanceService = _univerInstanceService;
2954
+ this._dataValidatorRegistryService = _dataValidatorRegistryService;
2955
+ this._injector = _injector;
2956
+ this._selectionManagerService = _selectionManagerService;
2957
+ this._sheetInterceptorService = _sheetInterceptorService;
2958
+ this._sheetDataValidationModel = _sheetDataValidationModel;
2959
+ this._init();
2960
+ }
2961
+ _init() {
2962
+ this._registerValidators();
2963
+ this._initCommandInterceptor();
2964
+ }
2965
+ _registerValidators() {
2966
+ [
2967
+ AnyValidator,
2968
+ DecimalValidator,
2969
+ WholeValidator,
2970
+ TextLengthValidator,
2971
+ DateValidator,
2972
+ CheckboxValidator,
2973
+ ListValidator,
2974
+ ListMultipleValidator,
2975
+ CustomFormulaValidator
2976
+ ].forEach((Validator) => {
2977
+ const validator = this._injector.createInstance(Validator);
2978
+ this.disposeWithMe(this._dataValidatorRegistryService.register(validator));
2979
+ this.disposeWithMe(toDisposable(() => this._injector.delete(Validator)));
2980
+ });
2981
+ }
2982
+ _initCommandInterceptor() {
2983
+ this._sheetInterceptorService.interceptCommand({ getMutations: (commandInfo) => {
2984
+ if (commandInfo.id === ClearSelectionAllCommand.id) {
2985
+ var _this$_selectionManag;
2986
+ const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET);
2987
+ const unitId = workbook.getUnitId();
2988
+ const worksheet = workbook.getActiveSheet();
2989
+ if (!worksheet) throw new Error("No active sheet found");
2990
+ const subUnitId = worksheet.getSheetId();
2991
+ const selections = (_this$_selectionManag = this._selectionManagerService.getCurrentSelections()) === null || _this$_selectionManag === void 0 ? void 0 : _this$_selectionManag.map((s) => s.range);
2992
+ const ruleMatrix = this._sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId).clone();
2993
+ if (selections) ruleMatrix.removeRange(selections);
2994
+ const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, ruleMatrix.diff(this._sheetDataValidationModel.getRules(unitId, subUnitId)), this._injector, "patched");
2995
+ return {
2996
+ undos: undoMutations,
2997
+ redos: redoMutations
2998
+ };
2999
+ }
3000
+ return {
3001
+ undos: [],
3002
+ redos: []
3003
+ };
3004
+ } });
3005
+ }
3006
+ };
3007
+ DataValidationController = __decorate([
3008
+ __decorateParam(0, IUniverInstanceService),
3009
+ __decorateParam(1, Inject(DataValidatorRegistryService)),
3010
+ __decorateParam(2, Inject(Injector)),
3011
+ __decorateParam(3, Inject(SheetsSelectionsService)),
3012
+ __decorateParam(4, Inject(SheetInterceptorService)),
3013
+ __decorateParam(5, Inject(SheetDataValidationModel))
3014
+ ], DataValidationController);
3015
+
3016
+ //#endregion
3017
+ //#region src/services/dv-validator-service.ts
3018
+ let SheetsDataValidationValidatorService = class SheetsDataValidationValidatorService extends Disposable {
3019
+ constructor(_univerInstanceService, _sheetDataValidationModel, _dataValidationCacheService, _lifecycleService) {
3020
+ super();
3021
+ this._univerInstanceService = _univerInstanceService;
3022
+ this._sheetDataValidationModel = _sheetDataValidationModel;
3023
+ this._dataValidationCacheService = _dataValidationCacheService;
3024
+ this._lifecycleService = _lifecycleService;
3025
+ this._initRecalculate();
3026
+ }
3027
+ _initRecalculate() {
3028
+ const handleDirtyRanges = (ranges) => {
3029
+ if (ranges.length === 0) return;
3030
+ const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET);
3031
+ const worksheet = workbook === null || workbook === void 0 ? void 0 : workbook.getActiveSheet();
3032
+ const map = {};
3033
+ ranges.flat().forEach((range) => {
3034
+ if (!map[range.unitId]) map[range.unitId] = {};
3035
+ if (!map[range.unitId][range.subUnitId]) map[range.unitId][range.subUnitId] = [];
3036
+ const workbook = this._univerInstanceService.getUnit(range.unitId, UniverInstanceType.UNIVER_SHEET);
3037
+ const worksheet = workbook === null || workbook === void 0 ? void 0 : workbook.getSheetBySheetId(range.subUnitId);
3038
+ if (!worksheet) return;
3039
+ map[range.unitId][range.subUnitId].push(...range.ranges.map((range) => Range.transformRange(range, worksheet)));
3040
+ });
3041
+ Object.entries(map).forEach(([unitId, subUnitMap]) => {
3042
+ Object.entries(subUnitMap).forEach(([subUnitId, ranges]) => {
3043
+ if ((workbook === null || workbook === void 0 ? void 0 : workbook.getUnitId()) === unitId && (worksheet === null || worksheet === void 0 ? void 0 : worksheet.getSheetId()) === subUnitId) this.validatorRanges(unitId, subUnitId, ranges);
3044
+ else requestIdleCallback(() => {
3045
+ this.validatorRanges(unitId, subUnitId, ranges);
3046
+ });
3047
+ });
3048
+ });
3049
+ };
3050
+ this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(bufferWhen(() => this._lifecycleService.lifecycle$.pipe(filter((stage) => stage === LifecycleStages.Rendered)))).subscribe(handleDirtyRanges));
3051
+ this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(filter(() => this._lifecycleService.stage >= LifecycleStages.Rendered), bufferDebounceTime(20)).subscribe(handleDirtyRanges));
3052
+ }
3053
+ async _validatorByCell(workbook, worksheet, row, col) {
3054
+ const unitId = workbook.getUnitId();
3055
+ const subUnitId = worksheet.getSheetId();
3056
+ if (!Tools.isDefine(row) || !Tools.isDefine(col)) throw new Error(`row or col is not defined, row: ${row}, col: ${col}`);
3057
+ let _row = row;
3058
+ let _col = col;
3059
+ const mergedCell = worksheet.getMergedCell(row, col);
3060
+ if (mergedCell) {
3061
+ _row = mergedCell.startRow;
3062
+ _col = mergedCell.startColumn;
3063
+ }
3064
+ const rule = this._sheetDataValidationModel.getRuleByLocation(unitId, subUnitId, _row, _col);
3065
+ if (!rule) return DataValidationStatus.VALID;
3066
+ return new Promise((resolve) => {
3067
+ this._sheetDataValidationModel.validator(rule, {
3068
+ unitId,
3069
+ subUnitId,
3070
+ row: _row,
3071
+ col: _col,
3072
+ worksheet,
3073
+ workbook
3074
+ }, (status) => {
3075
+ resolve(status);
3076
+ });
3077
+ });
3078
+ }
3079
+ async validatorCell(unitId, subUnitId, row, col) {
3080
+ const workbook = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET);
3081
+ if (!workbook) throw new Error(`cannot find current workbook, unitId: ${unitId}`);
3082
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
3083
+ if (!worksheet) throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);
3084
+ return this._validatorByCell(workbook, worksheet, row, col);
3085
+ }
3086
+ async validatorRanges(unitId, subUnitId, ranges) {
3087
+ if (!ranges.length) return Promise.resolve([]);
3088
+ const workbook = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET);
3089
+ if (!workbook) throw new Error(`cannot find current workbook, unitId: ${unitId}`);
3090
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
3091
+ if (!worksheet) throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);
3092
+ const ruleRanges = this._sheetDataValidationModel.getRules(unitId, subUnitId).map((i) => i.ranges).flat();
3093
+ const intersectRanges = ranges.map((range) => ruleRanges.map((ruleRange) => getIntersectRange(range, ruleRange))).flat().filter(Boolean);
3094
+ const mergeCells = [];
3095
+ const result = await Promise.all(intersectRanges.map((range, resultRowIndex) => {
3096
+ const promises = [];
3097
+ for (let row = range.startRow; row <= range.endRow; row++) for (let col = range.startColumn; col <= range.endColumn; col++) {
3098
+ promises.push(this._validatorByCell(workbook, worksheet, row, col));
3099
+ const mergedCell = worksheet.getMergedCell(row, col);
3100
+ if (mergedCell) mergeCells.push({
3101
+ resultRowIndex,
3102
+ resultColIndex: promises.length - 1,
3103
+ row: mergedCell.startRow,
3104
+ col: mergedCell.startColumn
3105
+ });
3106
+ }
3107
+ return Promise.all(promises);
3108
+ }));
3109
+ /**
3110
+ * If this range has merged cells, the validation status of merged cells should be the same as the main cell, so we need to update the status of merged cells here after all validations are done.
3111
+ * Because during the validation process, merged cells are all marked as VALIDATING status in cache.
3112
+ */
3113
+ if (mergeCells.length) mergeCells.forEach(({ resultRowIndex, resultColIndex, row, col }) => {
3114
+ if (result[resultRowIndex][resultColIndex] === DataValidationStatus.VALIDATING) {
3115
+ var _this$_dataValidation;
3116
+ result[resultRowIndex][resultColIndex] = (_this$_dataValidation = this._dataValidationCacheService.getValue(unitId, subUnitId, row, col)) !== null && _this$_dataValidation !== void 0 ? _this$_dataValidation : DataValidationStatus.VALID;
3117
+ }
3118
+ });
3119
+ return result;
3120
+ }
3121
+ async validatorWorksheet(unitId, subUnitId) {
3122
+ const workbook = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET);
3123
+ if (!workbook) throw new Error(`cannot find current workbook, unitId: ${unitId}`);
3124
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
3125
+ if (!worksheet) throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);
3126
+ const rules = this._sheetDataValidationModel.getRules(unitId, subUnitId);
3127
+ await Promise.all(rules.map((rule) => {
3128
+ return Promise.all(rule.ranges.map((range) => {
3129
+ const promises = [];
3130
+ Range.foreach(range, (row, col) => {
3131
+ promises.push(this._validatorByCell(workbook, worksheet, row, col));
3132
+ });
3133
+ return Promise.all(promises);
3134
+ }));
3135
+ }));
3136
+ return this._dataValidationCacheService.ensureCache(unitId, subUnitId);
3137
+ }
3138
+ async validatorWorkbook(unitId) {
3139
+ const sheetIds = this._sheetDataValidationModel.getSubUnitIds(unitId);
3140
+ const results = await Promise.all(sheetIds.map((id) => this.validatorWorksheet(unitId, id)));
3141
+ const map = {};
3142
+ results.forEach((result, i) => {
3143
+ map[sheetIds[i]] = result;
3144
+ });
3145
+ return map;
3146
+ }
3147
+ getDataValidations(unitId, subUnitId, ranges) {
3148
+ const ruleMatrix = this._sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId);
3149
+ const ruleIdSet = /* @__PURE__ */ new Set();
3150
+ ranges.forEach((range) => {
3151
+ Range.foreach(range, (row, col) => {
3152
+ const ruleId = ruleMatrix.getValue(row, col);
3153
+ if (ruleId) ruleIdSet.add(ruleId);
3154
+ });
3155
+ });
3156
+ return Array.from(ruleIdSet).map((id) => this._sheetDataValidationModel.getRuleById(unitId, subUnitId, id)).filter(Boolean);
3157
+ }
3158
+ getDataValidation(unitId, subUnitId, ranges) {
3159
+ return this.getDataValidations(unitId, subUnitId, ranges)[0];
3160
+ }
3161
+ };
3162
+ SheetsDataValidationValidatorService = __decorate([
3163
+ __decorateParam(0, IUniverInstanceService),
3164
+ __decorateParam(1, Inject(SheetDataValidationModel)),
3165
+ __decorateParam(2, Inject(DataValidationCacheService)),
3166
+ __decorateParam(3, Inject(LifecycleService))
3167
+ ], SheetsDataValidationValidatorService);
3168
+
3169
+ //#endregion
3170
+ //#region src/plugin.ts
3171
+ let UniverSheetsDataValidationPlugin = class UniverSheetsDataValidationPlugin extends Plugin {
3172
+ constructor(_config = defaultPluginConfig, _injector, _commandService, _configService) {
3173
+ super();
3174
+ this._config = _config;
3175
+ this._injector = _injector;
3176
+ this._commandService = _commandService;
3177
+ this._configService = _configService;
3178
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
3179
+ this._configService.setConfig(SHEETS_DATA_VALIDATION_PLUGIN_CONFIG_KEY, rest);
3180
+ }
3181
+ onStarting() {
3182
+ [
3183
+ [DataValidationCacheService],
3184
+ [DataValidationListCacheService],
3185
+ [DataValidationFormulaService],
3186
+ [DataValidationCustomFormulaService],
3187
+ [SheetsDataValidationValidatorService],
3188
+ [SheetDataValidationModel],
3189
+ [DataValidationController],
3190
+ [DataValidationFormulaController],
3191
+ [SheetDataValidationSheetController],
3192
+ [DataValidationRefRangeController],
3193
+ [DataValidationFormulaRefRangeController]
3194
+ ].forEach((dep) => {
3195
+ this._injector.add(dep);
3196
+ });
3197
+ [
3198
+ AddSheetDataValidationCommand,
3199
+ UpdateSheetDataValidationRangeCommand,
3200
+ UpdateSheetDataValidationSettingCommand,
3201
+ UpdateSheetDataValidationOptionsCommand,
3202
+ RemoveSheetDataValidationCommand,
3203
+ RemoveSheetAllDataValidationCommand,
3204
+ ClearRangeDataValidationCommand
3205
+ ].forEach((command) => {
3206
+ this._commandService.registerCommand(command);
3207
+ });
3208
+ this._injector.get(DataValidationCacheService);
3209
+ this._injector.get(SheetsDataValidationValidatorService);
3210
+ this._injector.get(DataValidationController);
3211
+ this._injector.get(DataValidationFormulaRefRangeController);
3212
+ this._injector.get(DataValidationRefRangeController);
3213
+ }
3214
+ onReady() {
3215
+ this._injector.get(SheetDataValidationSheetController);
3216
+ }
3217
+ onRendered() {
3218
+ this._injector.get(DataValidationFormulaController);
3219
+ }
3220
+ };
3221
+ _defineProperty(UniverSheetsDataValidationPlugin, "pluginName", DATA_VALIDATION_PLUGIN_NAME);
3222
+ _defineProperty(UniverSheetsDataValidationPlugin, "packageName", name);
3223
+ _defineProperty(UniverSheetsDataValidationPlugin, "version", version);
3224
+ _defineProperty(UniverSheetsDataValidationPlugin, "type", UniverInstanceType.UNIVER_SHEET);
3225
+ UniverSheetsDataValidationPlugin = __decorate([
3226
+ DependentOn(UniverSheetsFormulaPlugin, UniverDataValidationPlugin),
3227
+ __decorateParam(1, Inject(Injector)),
3228
+ __decorateParam(2, ICommandService),
3229
+ __decorateParam(3, IConfigService)
3230
+ ], UniverSheetsDataValidationPlugin);
3231
+
3232
+ //#endregion
3233
+ //#region src/utils/create.ts
3234
+ function createDefaultNewRule(accessor) {
3235
+ const currentRanges = accessor.get(SheetsSelectionsService).getCurrentSelections().map((s) => s.range);
3236
+ return {
3237
+ uid: generateRandomId(6),
3238
+ type: DataValidationType.DECIMAL,
3239
+ operator: DataValidationOperator.EQUAL,
3240
+ formula1: "100",
3241
+ ranges: currentRanges !== null && currentRanges !== void 0 ? currentRanges : [{
3242
+ startColumn: 0,
3243
+ endColumn: 0,
3244
+ startRow: 0,
3245
+ endRow: 0
3246
+ }]
3247
+ };
3248
+ }
3249
+
3250
+ //#endregion
3251
+ //#region src/index.ts
3252
+ const CUSTOM_FORMULA_INPUT_NAME = "data-validation.custom-formula-input";
3253
+ const BASE_FORMULA_INPUT_NAME = "data-validation.formula-input";
3254
+ const LIST_FORMULA_INPUT_NAME = "data-validation.list-formula-input";
3255
+ const CHECKBOX_FORMULA_INPUT_NAME = "data-validation.checkbox-formula-input";
3256
+
3257
+ //#endregion
3258
+ export { AddSheetDataValidationCommand, BASE_FORMULA_INPUT_NAME, CHECKBOX_FORMULA_1, CHECKBOX_FORMULA_2, CHECKBOX_FORMULA_INPUT_NAME, CUSTOM_FORMULA_INPUT_NAME, CheckboxValidator, ClearRangeDataValidationCommand, DATA_VALIDATION_PLUGIN_NAME, DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaController, DataValidationFormulaService, DataValidationListCacheService, DateValidator, LIST_FORMULA_INPUT_NAME, ListMultipleValidator, ListValidator, RemoveSheetAllDataValidationCommand, RemoveSheetDataValidationCommand, SheetDataValidationModel, SheetsDataValidationValidatorService, UniverSheetsDataValidationPlugin, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand, createDefaultNewRule, deserializeListOptions, getCellValueNumber, getCellValueOrigin, getDataValidationCellValue, getDataValidationDiffMutations, getFormulaCellData, getFormulaResult, getTransformedFormula, isLegalFormulaResult, serializeListOptions, transformCheckboxValue };