@univerjs/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,939 @@
1
- import{CommandType as e,DataValidationOperator as t,Disposable as n,ICommandService as r,IConfigService as i,ILogService as a,IResourceManagerService as o,IUndoRedoService as s,IUniverInstanceService as c,Inject as l,Injector as u,LocaleService as d,Plugin as f,Tools as p,UniverInstanceType as m,merge as h,toDisposable as g}from"@univerjs/core";import{BehaviorSubject as _,Subject as v,debounceTime as y}from"rxjs";function b(e){return{type:e.type,operator:e.operator,formula1:e.formula1,formula2:e.formula2,allowBlank:e.allowBlank}}function x(e){return{error:e.error,errorStyle:e.errorStyle,errorTitle:e.errorTitle,imeMode:e.imeMode,prompt:e.prompt,promptTitle:e.promptTitle,showDropDown:e.showDropDown,showErrorMessage:e.showErrorMessage,showInputMessage:e.showInputMessage,renderMode:e.renderMode,bizInfo:e.bizInfo}}let S=function(e){return e[e.SETTING=0]=`SETTING`,e[e.RANGE=1]=`RANGE`,e[e.OPTIONS=2]=`OPTIONS`,e[e.ALL=3]=`ALL`,e}({});function C(e){"@babel/helpers - typeof";return C=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},C(e)}function w(e,t){if(C(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(C(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function T(e){var t=w(e,`string`);return C(t)==`symbol`?t:t+``}function E(e,t,n){return(t=T(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function D(e,t){return function(n,r){t(n,r,e)}}function O(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 k=class extends n{constructor(e){super(),this._logService=e,E(this,`_model`,new Map),E(this,`_ruleChange$`,new v),E(this,`ruleChange$`,this._ruleChange$.asObservable()),E(this,`ruleChangeDebounce$`,this.ruleChange$.pipe(y(20))),this.disposeWithMe({dispose:()=>{this._ruleChange$.complete()}})}_ensureMap(e,t){this._model.has(e)||this._model.set(e,new Map);let n=this._model.get(e);if(n.has(t))return n.get(t);let r={map:new Map,list:[]};return n.set(t,r),r}_addSubUnitRule(e,t,n){let{map:r,list:i}=e,a=(Array.isArray(t)?t:[t]).filter(e=>!r.has(e.uid));typeof n==`number`&&n<i.length?i.splice(n,0,...a):i.push(...a),a.forEach(e=>{r.set(e.uid,e)})}_removeSubUnitRule(e,t){let{map:n,list:r}=e,i=r.findIndex(e=>e.uid===t);i>-1&&(r.splice(i,1),n.delete(t))}_updateSubUnitRule(e,t,n){let{map:r,list:i}=e,a=r.get(t),o=i.findIndex(e=>t===e.uid);if(!a)throw Error(`Data validation rule is not found, ruleId: ${t}.`);let s={...a};switch(n.type){case S.RANGE:s.ranges=n.payload;break;case S.SETTING:Object.assign(s,b(n.payload));break;case S.OPTIONS:Object.assign(s,x(n.payload));break;case S.ALL:Object.assign(s,n.payload);break;default:break}return i[o]=s,r.set(t,s),s}_addRuleSideEffect(e,t,n,r){if(!this._ensureMap(e,t).map.get(n.uid))return{rule:n,type:`add`,unitId:e,subUnitId:t,source:r}}addRule(e,t,n,r,i){try{let a=this._ensureMap(e,t),o=(Array.isArray(n)?n:[n]).map(n=>this._addRuleSideEffect(e,t,n,r));this._addSubUnitRule(a,n,i),o.forEach(e=>{e&&this._ruleChange$.next(e)})}catch(e){this._logService.error(e)}}updateRule(e,t,n,r,i){try{let a=this._ensureMap(e,t),o=p.deepClone(a.map.get(n));if(!o)throw Error(`Data validation rule is not found, ruleId: ${n}.`);let s=this._updateSubUnitRule(a,n,r);this._ruleChange$.next({rule:s,type:`update`,unitId:e,subUnitId:t,source:i,updatePayload:r,oldRule:o})}catch(e){this._logService.error(e)}}removeRule(e,t,n,r){try{let i=this._ensureMap(e,t),a=i.map.get(n);a&&(this._removeSubUnitRule(i,n),this._ruleChange$.next({rule:a,type:`remove`,unitId:e,subUnitId:t,source:r}))}catch(e){this._logService.error(e)}}getRuleById(e,t,n){return this._ensureMap(e,t).map.get(n)}getRuleIndex(e,t,n){return this._ensureMap(e,t).list.findIndex(e=>e.uid===n)}getRules(e,t){return[...this._ensureMap(e,t).list]}getUnitRules(e){let t=this._model.get(e);if(!t)return[];let n=[];return t.forEach((e,t)=>{n.push([t,e.list])}),n}deleteUnitRules(e){this._model.delete(e)}getSubUnitIds(e){var t,n;return Array.from((t=(n=this._model.get(e))==null?void 0:n.keys())==null?[]:t)}getAll(){return Array.from(this._model.keys()).map(e=>[e,this.getUnitRules(e)])}};k=O([D(0,a)],k);const A={type:e.MUTATION,id:`data-validation.mutation.addRule`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,rule:i,index:a,source:o=`command`}=t;return e.get(k).addRule(n,r,i,o,a),!0}},j={type:e.MUTATION,id:`data-validation.mutation.removeRule`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,ruleId:i,source:a=`command`}=t,o=e.get(k);return Array.isArray(i)?i.forEach(e=>{o.removeRule(n,r,e,a)}):o.removeRule(n,r,i,a),!0}},M={type:e.MUTATION,id:`data-validation.mutation.updateRule`,handler(e,t){if(!t)return!1;let{unitId:n,subUnitId:r,ruleId:i,payload:a,source:o=`command`}=t;return e.get(k).updateRule(n,r,i,a,o),!0}};let N=class extends n{constructor(e,t,n){super(),this._resourceManagerService=e,this._univerInstanceService=t,this._dataValidationModel=n,this._initSnapshot()}_initSnapshot(){let e=e=>{let t=this._dataValidationModel.getUnitRules(e),n={};return t?(t.forEach(([e,t])=>{n[e]=t}),JSON.stringify(n)):``},t=e=>{if(!e)return{};try{return JSON.parse(e)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({pluginName:`SHEET_DATA_VALIDATION_PLUGIN`,businesses:[m.UNIVER_SHEET],toJson:t=>e(t),parseJson:e=>t(e),onUnLoad:e=>{this._dataValidationModel.deleteUnitRules(e)},onLoad:(e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(t=>{this._dataValidationModel.addRule(e,n,t,`patched`)})})}}))}};N=O([D(0,o),D(1,c),D(2,l(k))],N);var P=`@univerjs/data-validation`,F=`0.20.1`;let I=function(e){return e.SHEET=`sheet`,e}({});var L=class{constructor(){E(this,`_validatorByScopes`,new Map),E(this,`_validatorMap`,new Map),E(this,`_validatorsChange$`,new _(void 0)),E(this,`validatorsChange$`,this._validatorsChange$.asObservable())}_addValidatorToScope(e,t){this._validatorByScopes.has(t)||this._validatorByScopes.set(t,[]);let n=this._validatorByScopes.get(t);if(n.findIndex(t=>t.id===e.id)>-1)throw Error(`Validator item with the same id ${e.id} has already been added!`);n.push(e)}_removeValidatorFromScope(e,t){let n=this._validatorByScopes.get(t);if(!n)return;let r=n.findIndex(t=>t.id===e.id);r>-1&&n.splice(r,1)}register(e){return this._validatorMap.set(e.id,e),Array.isArray(e.scopes)?e.scopes.forEach(t=>{this._addValidatorToScope(e,t)}):this._addValidatorToScope(e,e.scopes),this._validatorsChange$.next(),g(()=>{this._validatorMap.delete(e.id),Array.isArray(e.scopes)?e.scopes.forEach(t=>{this._removeValidatorFromScope(e,t)}):this._removeValidatorFromScope(e,e.scopes),this._validatorsChange$.next()})}getValidatorItem(e){return this._validatorMap.get(e)}getValidatorsByScope(e){return this._validatorByScopes.get(e)}};const R={type:e.COMMAND,id:`data-validation.command.addRule`,async handler(e,t){if(e.get(a).error("[Deprecated]: `AddDataValidationCommand` is deprecated, please use `AddSheetDataValidationCommand` in `@univerjs/sheets-data-validation` instead!"),!t)return!1;let{rule:n,unitId:i,subUnitId:o}=t,c=e.get(r),l=e.get(s),u={...t,rule:{...t.rule,ranges:[t.rule.range]}},d=[{id:A.id,params:u}],f=[{id:j.id,params:{unitId:i,subUnitId:o,ruleId:n.uid}}];return l.pushUndoRedo({unitID:i,redoMutations:d,undoMutations:f}),await c.executeCommand(A.id,u),!0}},z={type:e.COMMAND,id:`data-validation.command.removeRule`,handler(e,t){if(e.get(a).error("[Deprecated]: `RemoveDataValidationCommand` is deprecated, please use `RemoveSheetDataValidationCommand` in `@univerjs/sheets-data-validation` instead!"),!t)return!1;let{unitId:n,subUnitId:i,ruleId:o}=t,c=e.get(r),l=e.get(s),u=e.get(k),d=[{id:j.id,params:t}],f=[{id:A.id,params:{unitId:n,subUnitId:i,rule:{...u.getRuleById(n,i,o)},index:u.getRuleIndex(n,i,o)}}];return l.pushUndoRedo({undoMutations:f,redoMutations:d,unitID:t.unitId}),c.executeCommand(j.id,t),!0}},B={type:e.COMMAND,id:`data-validation.command.updateDataValidationSetting`,handler(e,t){if(e.get(a).warn("[Deprecated]: `UpdateDataValidationOptionsCommand` is deprecated, please use `UpdateSheetDataValidationOptionsCommand` in `@univerjs/sheets-data-validation` instead!"),!t)return!1;let n=e.get(r),i=e.get(s),o=e.get(k),{unitId:c,subUnitId:l,ruleId:u,options:d}=t,f=o.getRuleById(c,l,u);if(!f)return!1;let p={unitId:c,subUnitId:l,ruleId:u,payload:{type:S.OPTIONS,payload:d}},m=[{id:M.id,params:p}],h={unitId:c,subUnitId:l,ruleId:u,payload:{type:S.OPTIONS,payload:x(f)}},g=[{id:M.id,params:h}];return i.pushUndoRedo({unitID:c,redoMutations:m,undoMutations:g}),n.executeCommand(M.id,p),!0}},V={type:e.COMMAND,id:`data-validation.command.updateDataValidationOptions`,handler(e,t){if(e.get(a).error("[Deprecated]: `UpdateDataValidationSettingCommand` is deprecated, please use `UpdateSheetDataValidationSettingCommand` in `@univerjs/sheets-data-validation` instead!"),!t)return!1;let n=e.get(r),i=e.get(s),o=e.get(k),c=e.get(L),{unitId:l,subUnitId:u,ruleId:d,setting:f}=t,p=c.getValidatorItem(f.type);if(!p)return!1;let m=o.getRuleById(l,u,d);if(!m)return!1;let h={...m,...f};if(!p.validatorFormula(h,l,u).success)return!1;let g={unitId:l,subUnitId:u,ruleId:d,payload:{type:S.SETTING,payload:{...f,...p.normalizeFormula(h,l,u)}}},_=[{id:M.id,params:g}],v={unitId:l,subUnitId:u,ruleId:d,payload:{type:S.SETTING,payload:b(m)}},y=[{id:M.id,params:v}];return i.pushUndoRedo({unitID:l,redoMutations:_,undoMutations:y}),n.executeCommand(M.id,g),!0}},H={type:e.COMMAND,id:`data-validation.command.removeAll`,handler(e,t){if(e.get(a).error("[Deprecated]: `RemoveAllDataValidationCommand` is deprecated, please use `RemoveSheetAllDataValidationCommand` in `@univerjs/sheets-data-validation` instead!"),!t)return!1;let{unitId:n,subUnitId:i}=t,o=e.get(r),c=e.get(k),l=e.get(s),u=[...c.getRules(n,i)],d={unitId:n,subUnitId:i,ruleId:u.map(e=>e.uid)},f=[{id:j.id,params:d}],p=[{id:A.id,params:{unitId:n,subUnitId:i,rule:u}}];return l.pushUndoRedo({redoMutations:f,undoMutations:p,unitID:n}),o.executeCommand(j.id,d),!0}},U=`data-validation.config`;Symbol(U);const W={};let G=class extends f{constructor(e=W,t,n,r){super(),this._config=e,this._injector=t,this._commandService=n,this._configService=r;let{...i}=h({},W,this._config);this._configService.setConfig(U,i)}onStarting(){[[k],[L],[N]].forEach(e=>this._injector.add(e)),[R,H,B,V,z,A,M,j].forEach(e=>{this._commandService.registerCommand(e)})}onReady(){this._injector.get(N)}};E(G,`pluginName`,`UNIVER_DATA_VALIDATION_PLUGIN`),E(G,`packageName`,P),E(G,`version`,F),E(G,`type`,m.UNIVER_SHEET),G=O([D(1,l(u)),D(2,r),D(3,i)],G),t.BETWEEN,t.EQUAL,t.GREATER_THAN,t.GREATER_THAN_OR_EQUAL,t.LESS_THAN,t.LESS_THAN_OR_EQUAL,t.NOT_BETWEEN,t.NOT_EQUAL;const K={[t.BETWEEN]:`dataValidation.ruleName.between`,[t.EQUAL]:`dataValidation.ruleName.equal`,[t.GREATER_THAN]:`dataValidation.ruleName.greaterThan`,[t.GREATER_THAN_OR_EQUAL]:`dataValidation.ruleName.greaterThanOrEqual`,[t.LESS_THAN]:`dataValidation.ruleName.lessThan`,[t.LESS_THAN_OR_EQUAL]:`dataValidation.ruleName.lessThanOrEqual`,[t.NOT_BETWEEN]:`dataValidation.ruleName.notBetween`,[t.NOT_EQUAL]:`dataValidation.ruleName.notEqual`,NONE:`dataValidation.ruleName.legal`},q={[t.BETWEEN]:`dataValidation.errorMsg.between`,[t.EQUAL]:`dataValidation.errorMsg.equal`,[t.GREATER_THAN]:`dataValidation.errorMsg.greaterThan`,[t.GREATER_THAN_OR_EQUAL]:`dataValidation.errorMsg.greaterThanOrEqual`,[t.LESS_THAN]:`dataValidation.errorMsg.lessThan`,[t.LESS_THAN_OR_EQUAL]:`dataValidation.errorMsg.lessThanOrEqual`,[t.NOT_BETWEEN]:`dataValidation.errorMsg.notBetween`,[t.NOT_EQUAL]:`dataValidation.errorMsg.notEqual`,NONE:`dataValidation.errorMsg.legal`},J={[t.BETWEEN]:`dataValidation.textLength.errorMsg.between`,[t.EQUAL]:`dataValidation.textLength.errorMsg.equal`,[t.GREATER_THAN]:`dataValidation.textLength.errorMsg.greaterThan`,[t.GREATER_THAN_OR_EQUAL]:`dataValidation.textLength.errorMsg.greaterThanOrEqual`,[t.LESS_THAN]:`dataValidation.textLength.errorMsg.lessThan`,[t.LESS_THAN_OR_EQUAL]:`dataValidation.textLength.errorMsg.lessThanOrEqual`,[t.NOT_BETWEEN]:`dataValidation.textLength.errorMsg.notBetween`,[t.NOT_EQUAL]:`dataValidation.textLength.errorMsg.notEqual`},Y=[t.BETWEEN,t.NOT_BETWEEN],X=`{FORMULA1}`,Z=`{FORMULA2}`,Q=`{TYPE}`,ee={[t.BETWEEN]:`dataValidation.operators.between`,[t.EQUAL]:`dataValidation.operators.equal`,[t.GREATER_THAN]:`dataValidation.operators.greaterThan`,[t.GREATER_THAN_OR_EQUAL]:`dataValidation.operators.greaterThanOrEqual`,[t.LESS_THAN]:`dataValidation.operators.lessThan`,[t.LESS_THAN_OR_EQUAL]:`dataValidation.operators.lessThanOrEqual`,[t.NOT_BETWEEN]:`dataValidation.operators.notBetween`,[t.NOT_EQUAL]:`dataValidation.operators.notEqual`};let te=function(e){return e.DATE=`date`,e.TIME=`time`,e.DATETIME=`datetime`,e.LIST=`list`,e.MULTIPLE_LIST=`multipleList`,e.COLOR=`color`,e.CASCADE=`cascade`,e}({}),$=class{constructor(e,t){this.localeService=e,this.injector=t,E(this,`offsetFormulaByRange`,!0),E(this,`formulaInput`,void 0),E(this,`canvasRender`,null),E(this,`dropdownType`,void 0),E(this,`optionsInput`,void 0),E(this,`skipDefaultFontRender`,void 0)}get operatorNames(){return this.operators.map(e=>this.localeService.t(ee[e]))}get titleStr(){return this.localeService.t(this.title)}generateRuleName(e){var t,n;if(!e.operator)return this.localeService.t(K.NONE).replace(Q,this.titleStr);let r=this.localeService.t(K[e.operator]).replace(X,(t=e.formula1)==null?``:t).replace(Z,(n=e.formula2)==null?``:n);return`${this.titleStr} ${r}`}generateRuleErrorMessage(e,t){var n,r;return e.operator?`${this.localeService.t(q[e.operator]).replace(X,(n=e.formula1)==null?``:n).replace(Z,(r=e.formula2)==null?``:r)}`:this.localeService.t(q.NONE).replace(Q,this.titleStr)}getExtraStyle(e,t,n,r,i){}getRuleFinalError(e,t){return e.showErrorMessage&&e.error?e.error:this.generateRuleErrorMessage(e,t)}isEmptyCellValue(e){return e===``||e==null}normalizeFormula(e,t,n){return{formula1:e.formula1,formula2:e.formula2}}async isValidType(e,t,n){return!0}transform(e,t,n){return e}async validatorIsEqual(e,t,n){let{formula1:r}=t,{value:i}=e;return Number.isNaN(r)?!0:i===r}async validatorIsNotEqual(e,t,n){let{formula1:r}=t;return Number.isNaN(r)?!0:e.value!==r}async validatorIsBetween(e,t,n){let{formula1:r,formula2:i}=t;if(Number.isNaN(r)||Number.isNaN(i))return!0;let a=Math.min(r,i),o=Math.max(r,i);return e.value>=a&&e.value<=o}async validatorIsNotBetween(e,t,n){let{formula1:r,formula2:i}=t;if(Number.isNaN(r)||Number.isNaN(i))return!0;let a=Math.min(r,i),o=Math.max(r,i);return e.value<a||e.value>o}async validatorIsGreaterThan(e,t,n){let{formula1:r}=t;return Number.isNaN(r)?!0:e.value>r}async validatorIsGreaterThanOrEqual(e,t,n){let{formula1:r}=t;return Number.isNaN(r)?!0:e.value>=r}async validatorIsLessThan(e,t,n){let{formula1:r}=t;return Number.isNaN(r)?!0:e.value<r}async validatorIsLessThanOrEqual(e,t,n){let{formula1:r}=t;return Number.isNaN(r)?!0:e.value<=r}async validator(e,n){let{value:r,unitId:i,subUnitId:a}=e,o=this.isEmptyCellValue(r),{allowBlank:s=!0,operator:c}=n;if(o)return s;let l=await this.parseFormula(n,i,a,e.row,e.column);if(!l.isFormulaValid||!await this.isValidType(e,l,n))return!1;if(!c)return!0;let u=this.transform(e,l,n);switch(c){case t.BETWEEN:return this.validatorIsBetween(u,l,n);case t.EQUAL:return this.validatorIsEqual(u,l,n);case t.GREATER_THAN:return this.validatorIsGreaterThan(u,l,n);case t.GREATER_THAN_OR_EQUAL:return this.validatorIsGreaterThanOrEqual(u,l,n);case t.LESS_THAN:return this.validatorIsLessThan(u,l,n);case t.LESS_THAN_OR_EQUAL:return this.validatorIsLessThanOrEqual(u,l,n);case t.NOT_BETWEEN:return this.validatorIsNotBetween(u,l,n);case t.NOT_EQUAL:return this.validatorIsNotEqual(u,l,n);default:throw Error(`Unknown operator.`)}}};$=O([D(0,l(d)),D(1,l(u))],$);export{A as AddDataValidationMutation,$ as BaseDataValidator,k as DataValidationModel,N as DataValidationResourceController,te as DataValidatorDropdownType,I as DataValidatorRegistryScope,L as DataValidatorRegistryService,X as FORMULA1,Z as FORMULA2,j as RemoveDataValidationMutation,Y as TWO_FORMULA_OPERATOR_COUNT,Q as TYPE,J as TextLengthErrorTitleMap,G as UniverDataValidationPlugin,M as UpdateDataValidationMutation,S as UpdateRuleType,x as getRuleOptions,b as getRuleSetting};
1
+ import { CommandType, DataValidationOperator, Disposable, ICommandService, IConfigService, ILogService, IResourceManagerService, IUndoRedoService, IUniverInstanceService, Inject, Injector, LocaleService, Plugin, Tools, UniverInstanceType, merge, toDisposable } from "@univerjs/core";
2
+ import { BehaviorSubject, Subject, debounceTime } from "rxjs";
3
+
4
+ //#region src/common/util.ts
5
+ function getRuleSetting(rule) {
6
+ return {
7
+ type: rule.type,
8
+ operator: rule.operator,
9
+ formula1: rule.formula1,
10
+ formula2: rule.formula2,
11
+ allowBlank: rule.allowBlank
12
+ };
13
+ }
14
+ function getRuleOptions(rule) {
15
+ return {
16
+ error: rule.error,
17
+ errorStyle: rule.errorStyle,
18
+ errorTitle: rule.errorTitle,
19
+ imeMode: rule.imeMode,
20
+ prompt: rule.prompt,
21
+ promptTitle: rule.promptTitle,
22
+ showDropDown: rule.showDropDown,
23
+ showErrorMessage: rule.showErrorMessage,
24
+ showInputMessage: rule.showInputMessage,
25
+ renderMode: rule.renderMode,
26
+ bizInfo: rule.bizInfo
27
+ };
28
+ }
29
+
30
+ //#endregion
31
+ //#region src/types/enum/update-rule-type.ts
32
+ /**
33
+ * Copyright 2023-present DreamNum Co., Ltd.
34
+ *
35
+ * Licensed under the Apache License, Version 2.0 (the "License");
36
+ * you may not use this file except in compliance with the License.
37
+ * You may obtain a copy of the License at
38
+ *
39
+ * http://www.apache.org/licenses/LICENSE-2.0
40
+ *
41
+ * Unless required by applicable law or agreed to in writing, software
42
+ * distributed under the License is distributed on an "AS IS" BASIS,
43
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44
+ * See the License for the specific language governing permissions and
45
+ * limitations under the License.
46
+ */
47
+ let UpdateRuleType = /* @__PURE__ */ function(UpdateRuleType) {
48
+ UpdateRuleType[UpdateRuleType["SETTING"] = 0] = "SETTING";
49
+ UpdateRuleType[UpdateRuleType["RANGE"] = 1] = "RANGE";
50
+ UpdateRuleType[UpdateRuleType["OPTIONS"] = 2] = "OPTIONS";
51
+ UpdateRuleType[UpdateRuleType["ALL"] = 3] = "ALL";
52
+ return UpdateRuleType;
53
+ }({});
54
+
55
+ //#endregion
56
+ //#region \0@oxc-project+runtime@0.124.0/helpers/typeof.js
57
+ function _typeof(o) {
58
+ "@babel/helpers - typeof";
59
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
60
+ return typeof o;
61
+ } : function(o) {
62
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
63
+ }, _typeof(o);
64
+ }
65
+
66
+ //#endregion
67
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPrimitive.js
68
+ function toPrimitive(t, r) {
69
+ if ("object" != _typeof(t) || !t) return t;
70
+ var e = t[Symbol.toPrimitive];
71
+ if (void 0 !== e) {
72
+ var i = e.call(t, r || "default");
73
+ if ("object" != _typeof(i)) return i;
74
+ throw new TypeError("@@toPrimitive must return a primitive value.");
75
+ }
76
+ return ("string" === r ? String : Number)(t);
77
+ }
78
+
79
+ //#endregion
80
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPropertyKey.js
81
+ function toPropertyKey(t) {
82
+ var i = toPrimitive(t, "string");
83
+ return "symbol" == _typeof(i) ? i : i + "";
84
+ }
85
+
86
+ //#endregion
87
+ //#region \0@oxc-project+runtime@0.124.0/helpers/defineProperty.js
88
+ function _defineProperty(e, r, t) {
89
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
90
+ value: t,
91
+ enumerable: !0,
92
+ configurable: !0,
93
+ writable: !0
94
+ }) : e[r] = t, e;
95
+ }
96
+
97
+ //#endregion
98
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
99
+ function __decorateParam(paramIndex, decorator) {
100
+ return function(target, key) {
101
+ decorator(target, key, paramIndex);
102
+ };
103
+ }
104
+
105
+ //#endregion
106
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
107
+ function __decorate(decorators, target, key, desc) {
108
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
109
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
110
+ 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;
111
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
112
+ }
113
+
114
+ //#endregion
115
+ //#region src/models/data-validation-model.ts
116
+ let DataValidationModel = class DataValidationModel extends Disposable {
117
+ constructor(_logService) {
118
+ super();
119
+ this._logService = _logService;
120
+ _defineProperty(this, "_model", /* @__PURE__ */ new Map());
121
+ _defineProperty(this, "_ruleChange$", new Subject());
122
+ _defineProperty(this, "ruleChange$", this._ruleChange$.asObservable());
123
+ _defineProperty(this, "ruleChangeDebounce$", this.ruleChange$.pipe(debounceTime(20)));
124
+ this.disposeWithMe({ dispose: () => {
125
+ this._ruleChange$.complete();
126
+ } });
127
+ }
128
+ _ensureMap(unitId, subUnitId) {
129
+ if (!this._model.has(unitId)) this._model.set(unitId, /* @__PURE__ */ new Map());
130
+ const unitMap = this._model.get(unitId);
131
+ if (unitMap.has(subUnitId)) return unitMap.get(subUnitId);
132
+ const map = {
133
+ map: /* @__PURE__ */ new Map(),
134
+ list: []
135
+ };
136
+ unitMap.set(subUnitId, map);
137
+ return map;
138
+ }
139
+ _addSubUnitRule(subUnit, rule, index) {
140
+ const { map: dataValidationMap, list: dataValidations } = subUnit;
141
+ const rules = (Array.isArray(rule) ? rule : [rule]).filter((item) => !dataValidationMap.has(item.uid));
142
+ if (typeof index === "number" && index < dataValidations.length) dataValidations.splice(index, 0, ...rules);
143
+ else dataValidations.push(...rules);
144
+ rules.forEach((item) => {
145
+ dataValidationMap.set(item.uid, item);
146
+ });
147
+ }
148
+ _removeSubUnitRule(subUnit, ruleId) {
149
+ const { map: dataValidationMap, list: dataValidations } = subUnit;
150
+ const index = dataValidations.findIndex((item) => item.uid === ruleId);
151
+ if (index > -1) {
152
+ dataValidations.splice(index, 1);
153
+ dataValidationMap.delete(ruleId);
154
+ }
155
+ }
156
+ _updateSubUnitRule(subUnit, ruleId, payload) {
157
+ const { map: dataValidationMap, list: dataValidations } = subUnit;
158
+ const oldRule = dataValidationMap.get(ruleId);
159
+ const index = dataValidations.findIndex((rule) => ruleId === rule.uid);
160
+ if (!oldRule) throw new Error(`Data validation rule is not found, ruleId: ${ruleId}.`);
161
+ const rule = { ...oldRule };
162
+ switch (payload.type) {
163
+ case UpdateRuleType.RANGE:
164
+ rule.ranges = payload.payload;
165
+ break;
166
+ case UpdateRuleType.SETTING:
167
+ Object.assign(rule, getRuleSetting(payload.payload));
168
+ break;
169
+ case UpdateRuleType.OPTIONS:
170
+ Object.assign(rule, getRuleOptions(payload.payload));
171
+ break;
172
+ case UpdateRuleType.ALL:
173
+ Object.assign(rule, payload.payload);
174
+ break;
175
+ default: break;
176
+ }
177
+ dataValidations[index] = rule;
178
+ dataValidationMap.set(ruleId, rule);
179
+ return rule;
180
+ }
181
+ _addRuleSideEffect(unitId, subUnitId, rule, source) {
182
+ if (this._ensureMap(unitId, subUnitId).map.get(rule.uid)) return;
183
+ return {
184
+ rule,
185
+ type: "add",
186
+ unitId,
187
+ subUnitId,
188
+ source
189
+ };
190
+ }
191
+ addRule(unitId, subUnitId, rule, source, index) {
192
+ try {
193
+ const subUnitMap = this._ensureMap(unitId, subUnitId);
194
+ const effects = (Array.isArray(rule) ? rule : [rule]).map((item) => this._addRuleSideEffect(unitId, subUnitId, item, source));
195
+ this._addSubUnitRule(subUnitMap, rule, index);
196
+ effects.forEach((effect) => {
197
+ if (effect) this._ruleChange$.next(effect);
198
+ });
199
+ } catch (error) {
200
+ this._logService.error(error);
201
+ }
202
+ }
203
+ updateRule(unitId, subUnitId, ruleId, payload, source) {
204
+ try {
205
+ const subUnitMap = this._ensureMap(unitId, subUnitId);
206
+ const oldRule = Tools.deepClone(subUnitMap.map.get(ruleId));
207
+ if (!oldRule) throw new Error(`Data validation rule is not found, ruleId: ${ruleId}.`);
208
+ const rule = this._updateSubUnitRule(subUnitMap, ruleId, payload);
209
+ this._ruleChange$.next({
210
+ rule,
211
+ type: "update",
212
+ unitId,
213
+ subUnitId,
214
+ source,
215
+ updatePayload: payload,
216
+ oldRule
217
+ });
218
+ } catch (error) {
219
+ this._logService.error(error);
220
+ }
221
+ }
222
+ removeRule(unitId, subUnitId, ruleId, source) {
223
+ try {
224
+ const map = this._ensureMap(unitId, subUnitId);
225
+ const oldRule = map.map.get(ruleId);
226
+ if (oldRule) {
227
+ this._removeSubUnitRule(map, ruleId);
228
+ this._ruleChange$.next({
229
+ rule: oldRule,
230
+ type: "remove",
231
+ unitId,
232
+ subUnitId,
233
+ source
234
+ });
235
+ }
236
+ } catch (error) {
237
+ this._logService.error(error);
238
+ }
239
+ }
240
+ getRuleById(unitId, subUnitId, ruleId) {
241
+ return this._ensureMap(unitId, subUnitId).map.get(ruleId);
242
+ }
243
+ getRuleIndex(unitId, subUnitId, ruleId) {
244
+ return this._ensureMap(unitId, subUnitId).list.findIndex((rule) => rule.uid === ruleId);
245
+ }
246
+ getRules(unitId, subUnitId) {
247
+ return [...this._ensureMap(unitId, subUnitId).list];
248
+ }
249
+ getUnitRules(unitId) {
250
+ const unitMap = this._model.get(unitId);
251
+ if (!unitMap) return [];
252
+ const res = [];
253
+ unitMap.forEach((manager, subUnitId) => {
254
+ res.push([subUnitId, manager.list]);
255
+ });
256
+ return res;
257
+ }
258
+ deleteUnitRules(unitId) {
259
+ this._model.delete(unitId);
260
+ }
261
+ getSubUnitIds(unitId) {
262
+ var _this$_model$get$keys, _this$_model$get;
263
+ return Array.from((_this$_model$get$keys = (_this$_model$get = this._model.get(unitId)) === null || _this$_model$get === void 0 ? void 0 : _this$_model$get.keys()) !== null && _this$_model$get$keys !== void 0 ? _this$_model$get$keys : []);
264
+ }
265
+ getAll() {
266
+ return Array.from(this._model.keys()).map((unitId) => [unitId, this.getUnitRules(unitId)]);
267
+ }
268
+ };
269
+ DataValidationModel = __decorate([__decorateParam(0, ILogService)], DataValidationModel);
270
+
271
+ //#endregion
272
+ //#region src/commands/mutations/data-validation.mutation.ts
273
+ const AddDataValidationMutation = {
274
+ type: CommandType.MUTATION,
275
+ id: "data-validation.mutation.addRule",
276
+ handler(accessor, params) {
277
+ if (!params) return false;
278
+ const { unitId, subUnitId, rule, index, source = "command" } = params;
279
+ accessor.get(DataValidationModel).addRule(unitId, subUnitId, rule, source, index);
280
+ return true;
281
+ }
282
+ };
283
+ const RemoveDataValidationMutation = {
284
+ type: CommandType.MUTATION,
285
+ id: "data-validation.mutation.removeRule",
286
+ handler(accessor, params) {
287
+ if (!params) return false;
288
+ const { unitId, subUnitId, ruleId, source = "command" } = params;
289
+ const dataValidationModel = accessor.get(DataValidationModel);
290
+ if (Array.isArray(ruleId)) ruleId.forEach((item) => {
291
+ dataValidationModel.removeRule(unitId, subUnitId, item, source);
292
+ });
293
+ else dataValidationModel.removeRule(unitId, subUnitId, ruleId, source);
294
+ return true;
295
+ }
296
+ };
297
+ const UpdateDataValidationMutation = {
298
+ type: CommandType.MUTATION,
299
+ id: "data-validation.mutation.updateRule",
300
+ handler(accessor, params) {
301
+ if (!params) return false;
302
+ const { unitId, subUnitId, ruleId, payload, source = "command" } = params;
303
+ accessor.get(DataValidationModel).updateRule(unitId, subUnitId, ruleId, payload, source);
304
+ return true;
305
+ }
306
+ };
307
+
308
+ //#endregion
309
+ //#region src/controllers/dv-resource.controller.ts
310
+ const DATA_VALIDATION_PLUGIN_NAME = "SHEET_DATA_VALIDATION_PLUGIN";
311
+ let DataValidationResourceController = class DataValidationResourceController extends Disposable {
312
+ constructor(_resourceManagerService, _univerInstanceService, _dataValidationModel) {
313
+ super();
314
+ this._resourceManagerService = _resourceManagerService;
315
+ this._univerInstanceService = _univerInstanceService;
316
+ this._dataValidationModel = _dataValidationModel;
317
+ this._initSnapshot();
318
+ }
319
+ _initSnapshot() {
320
+ const toJson = (unitID) => {
321
+ const map = this._dataValidationModel.getUnitRules(unitID);
322
+ const resultMap = {};
323
+ if (map) {
324
+ map.forEach(([key, v]) => {
325
+ resultMap[key] = v;
326
+ });
327
+ return JSON.stringify(resultMap);
328
+ }
329
+ return "";
330
+ };
331
+ const parseJson = (json) => {
332
+ if (!json) return {};
333
+ try {
334
+ return JSON.parse(json);
335
+ } catch (err) {
336
+ return {};
337
+ }
338
+ };
339
+ this.disposeWithMe(this._resourceManagerService.registerPluginResource({
340
+ pluginName: DATA_VALIDATION_PLUGIN_NAME,
341
+ businesses: [UniverInstanceType.UNIVER_SHEET],
342
+ toJson: (unitID) => toJson(unitID),
343
+ parseJson: (json) => parseJson(json),
344
+ onUnLoad: (unitID) => {
345
+ this._dataValidationModel.deleteUnitRules(unitID);
346
+ },
347
+ onLoad: (unitID, value) => {
348
+ Object.keys(value).forEach((subunitId) => {
349
+ value[subunitId].forEach((rule) => {
350
+ this._dataValidationModel.addRule(unitID, subunitId, rule, "patched");
351
+ });
352
+ });
353
+ }
354
+ }));
355
+ }
356
+ };
357
+ DataValidationResourceController = __decorate([
358
+ __decorateParam(0, IResourceManagerService),
359
+ __decorateParam(1, IUniverInstanceService),
360
+ __decorateParam(2, Inject(DataValidationModel))
361
+ ], DataValidationResourceController);
362
+
363
+ //#endregion
364
+ //#region package.json
365
+ var name = "@univerjs/data-validation";
366
+ var version = "0.21.0";
367
+
368
+ //#endregion
369
+ //#region src/services/data-validator-registry.service.ts
370
+ let DataValidatorRegistryScope = /* @__PURE__ */ function(DataValidatorRegistryScope) {
371
+ DataValidatorRegistryScope["SHEET"] = "sheet";
372
+ return DataValidatorRegistryScope;
373
+ }({});
374
+ /**
375
+ * Register data validator
376
+ */
377
+ var DataValidatorRegistryService = class {
378
+ constructor() {
379
+ _defineProperty(this, "_validatorByScopes", /* @__PURE__ */ new Map());
380
+ _defineProperty(this, "_validatorMap", /* @__PURE__ */ new Map());
381
+ _defineProperty(this, "_validatorsChange$", new BehaviorSubject(void 0));
382
+ _defineProperty(this, "validatorsChange$", this._validatorsChange$.asObservable());
383
+ }
384
+ _addValidatorToScope(validator, scope) {
385
+ if (!this._validatorByScopes.has(scope)) this._validatorByScopes.set(scope, []);
386
+ const validators = this._validatorByScopes.get(scope);
387
+ if (validators.findIndex((m) => m.id === validator.id) > -1) throw new Error(`Validator item with the same id ${validator.id} has already been added!`);
388
+ validators.push(validator);
389
+ }
390
+ _removeValidatorFromScope(validator, scope) {
391
+ const validators = this._validatorByScopes.get(scope);
392
+ if (!validators) return;
393
+ const index = validators.findIndex((v) => v.id === validator.id);
394
+ if (index > -1) validators.splice(index, 1);
395
+ }
396
+ register(validator) {
397
+ this._validatorMap.set(validator.id, validator);
398
+ if (Array.isArray(validator.scopes)) validator.scopes.forEach((scope) => {
399
+ this._addValidatorToScope(validator, scope);
400
+ });
401
+ else this._addValidatorToScope(validator, validator.scopes);
402
+ this._validatorsChange$.next();
403
+ return toDisposable(() => {
404
+ this._validatorMap.delete(validator.id);
405
+ if (Array.isArray(validator.scopes)) validator.scopes.forEach((scope) => {
406
+ this._removeValidatorFromScope(validator, scope);
407
+ });
408
+ else this._removeValidatorFromScope(validator, validator.scopes);
409
+ this._validatorsChange$.next();
410
+ });
411
+ }
412
+ getValidatorItem(id) {
413
+ return this._validatorMap.get(id);
414
+ }
415
+ getValidatorsByScope(scope) {
416
+ return this._validatorByScopes.get(scope);
417
+ }
418
+ };
419
+
420
+ //#endregion
421
+ //#region src/commands/commands/data-validation.command.ts
422
+ /**
423
+ * @deprecated `AddDataValidationCommand` is deprecated, please use `AddSheetDataValidationCommand` in `@univerjs/sheets-data-validation` instead!
424
+ */
425
+ const AddDataValidationCommand = {
426
+ type: CommandType.COMMAND,
427
+ id: "data-validation.command.addRule",
428
+ async handler(accessor, params) {
429
+ accessor.get(ILogService).error("[Deprecated]: `AddDataValidationCommand` is deprecated, please use `AddSheetDataValidationCommand` in `@univerjs/sheets-data-validation` instead!");
430
+ if (!params) return false;
431
+ const { rule, unitId, subUnitId } = params;
432
+ const commandService = accessor.get(ICommandService);
433
+ const undoRedoService = accessor.get(IUndoRedoService);
434
+ const mutationParams = {
435
+ ...params,
436
+ rule: {
437
+ ...params.rule,
438
+ ranges: [params.rule.range]
439
+ }
440
+ };
441
+ const redoMutations = [{
442
+ id: AddDataValidationMutation.id,
443
+ params: mutationParams
444
+ }];
445
+ const undoMutations = [{
446
+ id: RemoveDataValidationMutation.id,
447
+ params: {
448
+ unitId,
449
+ subUnitId,
450
+ ruleId: rule.uid
451
+ }
452
+ }];
453
+ undoRedoService.pushUndoRedo({
454
+ unitID: unitId,
455
+ redoMutations,
456
+ undoMutations
457
+ });
458
+ await commandService.executeCommand(AddDataValidationMutation.id, mutationParams);
459
+ return true;
460
+ }
461
+ };
462
+ /**
463
+ * @deprecated `RemoveDataValidationCommand` is deprecated, please use `RemoveSheetDataValidationCommand` in `@univerjs/sheets-data-validation` instead!
464
+ */
465
+ const RemoveDataValidationCommand = {
466
+ type: CommandType.COMMAND,
467
+ id: "data-validation.command.removeRule",
468
+ handler(accessor, params) {
469
+ accessor.get(ILogService).error("[Deprecated]: `RemoveDataValidationCommand` is deprecated, please use `RemoveSheetDataValidationCommand` in `@univerjs/sheets-data-validation` instead!");
470
+ if (!params) return false;
471
+ const { unitId, subUnitId, ruleId } = params;
472
+ const commandService = accessor.get(ICommandService);
473
+ const undoRedoService = accessor.get(IUndoRedoService);
474
+ const dataValidationModel = accessor.get(DataValidationModel);
475
+ const redoMutations = [{
476
+ id: RemoveDataValidationMutation.id,
477
+ params
478
+ }];
479
+ const undoMutations = [{
480
+ id: AddDataValidationMutation.id,
481
+ params: {
482
+ unitId,
483
+ subUnitId,
484
+ rule: { ...dataValidationModel.getRuleById(unitId, subUnitId, ruleId) },
485
+ index: dataValidationModel.getRuleIndex(unitId, subUnitId, ruleId)
486
+ }
487
+ }];
488
+ undoRedoService.pushUndoRedo({
489
+ undoMutations,
490
+ redoMutations,
491
+ unitID: params.unitId
492
+ });
493
+ commandService.executeCommand(RemoveDataValidationMutation.id, params);
494
+ return true;
495
+ }
496
+ };
497
+ /**
498
+ * @deprecated `UpdateDataValidationOptionsCommand` is deprecated, please use `UpdateSheetDataValidationOptionsCommand` in `@univerjs/sheets-data-validation` instead!
499
+ */
500
+ const UpdateDataValidationOptionsCommand = {
501
+ type: CommandType.COMMAND,
502
+ id: "data-validation.command.updateDataValidationSetting",
503
+ handler(accessor, params) {
504
+ accessor.get(ILogService).warn("[Deprecated]: `UpdateDataValidationOptionsCommand` is deprecated, please use `UpdateSheetDataValidationOptionsCommand` in `@univerjs/sheets-data-validation` instead!");
505
+ if (!params) return false;
506
+ const commandService = accessor.get(ICommandService);
507
+ const redoUndoService = accessor.get(IUndoRedoService);
508
+ const dataValidationModel = accessor.get(DataValidationModel);
509
+ const { unitId, subUnitId, ruleId, options } = params;
510
+ const rule = dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
511
+ if (!rule) return false;
512
+ const mutationParams = {
513
+ unitId,
514
+ subUnitId,
515
+ ruleId,
516
+ payload: {
517
+ type: UpdateRuleType.OPTIONS,
518
+ payload: options
519
+ }
520
+ };
521
+ const redoMutations = [{
522
+ id: UpdateDataValidationMutation.id,
523
+ params: mutationParams
524
+ }];
525
+ const undoMutationParams = {
526
+ unitId,
527
+ subUnitId,
528
+ ruleId,
529
+ payload: {
530
+ type: UpdateRuleType.OPTIONS,
531
+ payload: getRuleOptions(rule)
532
+ }
533
+ };
534
+ const undoMutations = [{
535
+ id: UpdateDataValidationMutation.id,
536
+ params: undoMutationParams
537
+ }];
538
+ redoUndoService.pushUndoRedo({
539
+ unitID: unitId,
540
+ redoMutations,
541
+ undoMutations
542
+ });
543
+ commandService.executeCommand(UpdateDataValidationMutation.id, mutationParams);
544
+ return true;
545
+ }
546
+ };
547
+ /**
548
+ * @deprecated `UpdateDataValidationSettingCommand` is deprecated, please use `UpdateSheetDataValidationSettingCommand` in `@univerjs/sheets-data-validation` instead!
549
+ */
550
+ const UpdateDataValidationSettingCommand = {
551
+ type: CommandType.COMMAND,
552
+ id: "data-validation.command.updateDataValidationOptions",
553
+ handler(accessor, params) {
554
+ accessor.get(ILogService).error("[Deprecated]: `UpdateDataValidationSettingCommand` is deprecated, please use `UpdateSheetDataValidationSettingCommand` in `@univerjs/sheets-data-validation` instead!");
555
+ if (!params) return false;
556
+ const commandService = accessor.get(ICommandService);
557
+ const redoUndoService = accessor.get(IUndoRedoService);
558
+ const dataValidationModel = accessor.get(DataValidationModel);
559
+ const dataValidatorRegistryService = accessor.get(DataValidatorRegistryService);
560
+ const { unitId, subUnitId, ruleId, setting } = params;
561
+ const validator = dataValidatorRegistryService.getValidatorItem(setting.type);
562
+ if (!validator) return false;
563
+ const rule = dataValidationModel.getRuleById(unitId, subUnitId, ruleId);
564
+ if (!rule) return false;
565
+ const newRule = {
566
+ ...rule,
567
+ ...setting
568
+ };
569
+ if (!validator.validatorFormula(newRule, unitId, subUnitId).success) return false;
570
+ const mutationParams = {
571
+ unitId,
572
+ subUnitId,
573
+ ruleId,
574
+ payload: {
575
+ type: UpdateRuleType.SETTING,
576
+ payload: {
577
+ ...setting,
578
+ ...validator.normalizeFormula(newRule, unitId, subUnitId)
579
+ }
580
+ }
581
+ };
582
+ const redoMutations = [{
583
+ id: UpdateDataValidationMutation.id,
584
+ params: mutationParams
585
+ }];
586
+ const undoMutationParams = {
587
+ unitId,
588
+ subUnitId,
589
+ ruleId,
590
+ payload: {
591
+ type: UpdateRuleType.SETTING,
592
+ payload: getRuleSetting(rule)
593
+ }
594
+ };
595
+ const undoMutations = [{
596
+ id: UpdateDataValidationMutation.id,
597
+ params: undoMutationParams
598
+ }];
599
+ redoUndoService.pushUndoRedo({
600
+ unitID: unitId,
601
+ redoMutations,
602
+ undoMutations
603
+ });
604
+ commandService.executeCommand(UpdateDataValidationMutation.id, mutationParams);
605
+ return true;
606
+ }
607
+ };
608
+ /**
609
+ * @deprecated `RemoveAllDataValidationCommand` is deprecated, please use `RemoveSheetAllDataValidationCommand` in `@univerjs/sheets-data-validation` instead!
610
+ */
611
+ const RemoveAllDataValidationCommand = {
612
+ type: CommandType.COMMAND,
613
+ id: "data-validation.command.removeAll",
614
+ handler(accessor, params) {
615
+ accessor.get(ILogService).error("[Deprecated]: `RemoveAllDataValidationCommand` is deprecated, please use `RemoveSheetAllDataValidationCommand` in `@univerjs/sheets-data-validation` instead!");
616
+ if (!params) return false;
617
+ const { unitId, subUnitId } = params;
618
+ const commandService = accessor.get(ICommandService);
619
+ const dataValidationModel = accessor.get(DataValidationModel);
620
+ const undoRedoService = accessor.get(IUndoRedoService);
621
+ const currentRules = [...dataValidationModel.getRules(unitId, subUnitId)];
622
+ const redoParams = {
623
+ unitId,
624
+ subUnitId,
625
+ ruleId: currentRules.map((rule) => rule.uid)
626
+ };
627
+ const redoMutations = [{
628
+ id: RemoveDataValidationMutation.id,
629
+ params: redoParams
630
+ }];
631
+ const undoMutations = [{
632
+ id: AddDataValidationMutation.id,
633
+ params: {
634
+ unitId,
635
+ subUnitId,
636
+ rule: currentRules
637
+ }
638
+ }];
639
+ undoRedoService.pushUndoRedo({
640
+ redoMutations,
641
+ undoMutations,
642
+ unitID: unitId
643
+ });
644
+ commandService.executeCommand(RemoveDataValidationMutation.id, redoParams);
645
+ return true;
646
+ }
647
+ };
648
+
649
+ //#endregion
650
+ //#region src/config/config.ts
651
+ /**
652
+ * Copyright 2023-present DreamNum Co., Ltd.
653
+ *
654
+ * Licensed under the Apache License, Version 2.0 (the "License");
655
+ * you may not use this file except in compliance with the License.
656
+ * You may obtain a copy of the License at
657
+ *
658
+ * http://www.apache.org/licenses/LICENSE-2.0
659
+ *
660
+ * Unless required by applicable law or agreed to in writing, software
661
+ * distributed under the License is distributed on an "AS IS" BASIS,
662
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
663
+ * See the License for the specific language governing permissions and
664
+ * limitations under the License.
665
+ */
666
+ const DATA_VALIDATION_PLUGIN_CONFIG_KEY = "data-validation.config";
667
+ const configSymbol = Symbol(DATA_VALIDATION_PLUGIN_CONFIG_KEY);
668
+ const defaultPluginConfig = {};
669
+
670
+ //#endregion
671
+ //#region src/plugin.ts
672
+ let UniverDataValidationPlugin = class UniverDataValidationPlugin extends Plugin {
673
+ constructor(_config = defaultPluginConfig, _injector, _commandService, _configService) {
674
+ super();
675
+ this._config = _config;
676
+ this._injector = _injector;
677
+ this._commandService = _commandService;
678
+ this._configService = _configService;
679
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
680
+ this._configService.setConfig(DATA_VALIDATION_PLUGIN_CONFIG_KEY, rest);
681
+ }
682
+ onStarting() {
683
+ [
684
+ [DataValidationModel],
685
+ [DataValidatorRegistryService],
686
+ [DataValidationResourceController]
687
+ ].forEach((d) => this._injector.add(d));
688
+ [
689
+ AddDataValidationCommand,
690
+ RemoveAllDataValidationCommand,
691
+ UpdateDataValidationOptionsCommand,
692
+ UpdateDataValidationSettingCommand,
693
+ RemoveDataValidationCommand,
694
+ AddDataValidationMutation,
695
+ UpdateDataValidationMutation,
696
+ RemoveDataValidationMutation
697
+ ].forEach((command) => {
698
+ this._commandService.registerCommand(command);
699
+ });
700
+ }
701
+ onReady() {
702
+ this._injector.get(DataValidationResourceController);
703
+ }
704
+ };
705
+ _defineProperty(UniverDataValidationPlugin, "pluginName", "UNIVER_DATA_VALIDATION_PLUGIN");
706
+ _defineProperty(UniverDataValidationPlugin, "packageName", name);
707
+ _defineProperty(UniverDataValidationPlugin, "version", version);
708
+ _defineProperty(UniverDataValidationPlugin, "type", UniverInstanceType.UNIVER_SHEET);
709
+ UniverDataValidationPlugin = __decorate([
710
+ __decorateParam(1, Inject(Injector)),
711
+ __decorateParam(2, ICommandService),
712
+ __decorateParam(3, IConfigService)
713
+ ], UniverDataValidationPlugin);
714
+
715
+ //#endregion
716
+ //#region src/types/const/operator-text-map.ts
717
+ /**
718
+ * Copyright 2023-present DreamNum Co., Ltd.
719
+ *
720
+ * Licensed under the Apache License, Version 2.0 (the "License");
721
+ * you may not use this file except in compliance with the License.
722
+ * You may obtain a copy of the License at
723
+ *
724
+ * http://www.apache.org/licenses/LICENSE-2.0
725
+ *
726
+ * Unless required by applicable law or agreed to in writing, software
727
+ * distributed under the License is distributed on an "AS IS" BASIS,
728
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
729
+ * See the License for the specific language governing permissions and
730
+ * limitations under the License.
731
+ */
732
+ const OperatorTextMap = {
733
+ [DataValidationOperator.BETWEEN]: "dataValidation.operators.between",
734
+ [DataValidationOperator.EQUAL]: "dataValidation.operators.equal",
735
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.operators.greaterThan",
736
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.operators.greaterThanOrEqual",
737
+ [DataValidationOperator.LESS_THAN]: "dataValidation.operators.lessThan",
738
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.operators.lessThanOrEqual",
739
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.operators.notBetween",
740
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.operators.notEqual"
741
+ };
742
+ const OperatorTitleMap = {
743
+ [DataValidationOperator.BETWEEN]: "dataValidation.ruleName.between",
744
+ [DataValidationOperator.EQUAL]: "dataValidation.ruleName.equal",
745
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.ruleName.greaterThan",
746
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.ruleName.greaterThanOrEqual",
747
+ [DataValidationOperator.LESS_THAN]: "dataValidation.ruleName.lessThan",
748
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.ruleName.lessThanOrEqual",
749
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.ruleName.notBetween",
750
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.ruleName.notEqual",
751
+ NONE: "dataValidation.ruleName.legal"
752
+ };
753
+ const OperatorErrorTitleMap = {
754
+ [DataValidationOperator.BETWEEN]: "dataValidation.errorMsg.between",
755
+ [DataValidationOperator.EQUAL]: "dataValidation.errorMsg.equal",
756
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.errorMsg.greaterThan",
757
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.errorMsg.greaterThanOrEqual",
758
+ [DataValidationOperator.LESS_THAN]: "dataValidation.errorMsg.lessThan",
759
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.errorMsg.lessThanOrEqual",
760
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.errorMsg.notBetween",
761
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.errorMsg.notEqual",
762
+ NONE: "dataValidation.errorMsg.legal"
763
+ };
764
+ const TextLengthErrorTitleMap = {
765
+ [DataValidationOperator.BETWEEN]: "dataValidation.textLength.errorMsg.between",
766
+ [DataValidationOperator.EQUAL]: "dataValidation.textLength.errorMsg.equal",
767
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.textLength.errorMsg.greaterThan",
768
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.textLength.errorMsg.greaterThanOrEqual",
769
+ [DataValidationOperator.LESS_THAN]: "dataValidation.textLength.errorMsg.lessThan",
770
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.textLength.errorMsg.lessThanOrEqual",
771
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.textLength.errorMsg.notBetween",
772
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.textLength.errorMsg.notEqual"
773
+ };
774
+
775
+ //#endregion
776
+ //#region src/types/const/two-formula-operators.ts
777
+ /**
778
+ * Copyright 2023-present DreamNum Co., Ltd.
779
+ *
780
+ * Licensed under the Apache License, Version 2.0 (the "License");
781
+ * you may not use this file except in compliance with the License.
782
+ * You may obtain a copy of the License at
783
+ *
784
+ * http://www.apache.org/licenses/LICENSE-2.0
785
+ *
786
+ * Unless required by applicable law or agreed to in writing, software
787
+ * distributed under the License is distributed on an "AS IS" BASIS,
788
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
789
+ * See the License for the specific language governing permissions and
790
+ * limitations under the License.
791
+ */
792
+ const TWO_FORMULA_OPERATOR_COUNT = [DataValidationOperator.BETWEEN, DataValidationOperator.NOT_BETWEEN];
793
+
794
+ //#endregion
795
+ //#region src/validators/base-data-validator.ts
796
+ const FORMULA1 = "{FORMULA1}";
797
+ const FORMULA2 = "{FORMULA2}";
798
+ const TYPE = "{TYPE}";
799
+ const operatorNameMap = {
800
+ [DataValidationOperator.BETWEEN]: "dataValidation.operators.between",
801
+ [DataValidationOperator.EQUAL]: "dataValidation.operators.equal",
802
+ [DataValidationOperator.GREATER_THAN]: "dataValidation.operators.greaterThan",
803
+ [DataValidationOperator.GREATER_THAN_OR_EQUAL]: "dataValidation.operators.greaterThanOrEqual",
804
+ [DataValidationOperator.LESS_THAN]: "dataValidation.operators.lessThan",
805
+ [DataValidationOperator.LESS_THAN_OR_EQUAL]: "dataValidation.operators.lessThanOrEqual",
806
+ [DataValidationOperator.NOT_BETWEEN]: "dataValidation.operators.notBetween",
807
+ [DataValidationOperator.NOT_EQUAL]: "dataValidation.operators.notEqual"
808
+ };
809
+ let DataValidatorDropdownType = /* @__PURE__ */ function(DataValidatorDropdownType) {
810
+ DataValidatorDropdownType["DATE"] = "date";
811
+ DataValidatorDropdownType["TIME"] = "time";
812
+ DataValidatorDropdownType["DATETIME"] = "datetime";
813
+ DataValidatorDropdownType["LIST"] = "list";
814
+ DataValidatorDropdownType["MULTIPLE_LIST"] = "multipleList";
815
+ DataValidatorDropdownType["COLOR"] = "color";
816
+ DataValidatorDropdownType["CASCADE"] = "cascade";
817
+ return DataValidatorDropdownType;
818
+ }({});
819
+ let BaseDataValidator = class BaseDataValidator {
820
+ constructor(localeService, injector) {
821
+ this.localeService = localeService;
822
+ this.injector = injector;
823
+ _defineProperty(this, "offsetFormulaByRange", true);
824
+ _defineProperty(this, "formulaInput", void 0);
825
+ _defineProperty(this, "canvasRender", null);
826
+ _defineProperty(this, "dropdownType", void 0);
827
+ _defineProperty(this, "optionsInput", void 0);
828
+ _defineProperty(this, "skipDefaultFontRender", void 0);
829
+ }
830
+ get operatorNames() {
831
+ return this.operators.map((operator) => this.localeService.t(operatorNameMap[operator]));
832
+ }
833
+ get titleStr() {
834
+ return this.localeService.t(this.title);
835
+ }
836
+ generateRuleName(rule) {
837
+ var _rule$formula, _rule$formula2;
838
+ if (!rule.operator) return this.localeService.t(OperatorTitleMap.NONE).replace(TYPE, this.titleStr);
839
+ const ruleName = this.localeService.t(OperatorTitleMap[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 : "");
840
+ return `${this.titleStr} ${ruleName}`;
841
+ }
842
+ generateRuleErrorMessage(rule, position) {
843
+ var _rule$formula3, _rule$formula4;
844
+ if (!rule.operator) return this.localeService.t(OperatorErrorTitleMap.NONE).replace(TYPE, this.titleStr);
845
+ return `${this.localeService.t(OperatorErrorTitleMap[rule.operator]).replace(FORMULA1, (_rule$formula3 = rule.formula1) !== null && _rule$formula3 !== void 0 ? _rule$formula3 : "").replace(FORMULA2, (_rule$formula4 = rule.formula2) !== null && _rule$formula4 !== void 0 ? _rule$formula4 : "")}`;
846
+ }
847
+ getExtraStyle(rule, value, ctx, row, column) {}
848
+ getRuleFinalError(rule, position) {
849
+ if (rule.showErrorMessage && rule.error) return rule.error;
850
+ return this.generateRuleErrorMessage(rule, position);
851
+ }
852
+ isEmptyCellValue(cellValue) {
853
+ if (cellValue === "" || cellValue === void 0 || cellValue === null) return true;
854
+ return false;
855
+ }
856
+ normalizeFormula(rule, unitId, subUnitId) {
857
+ return {
858
+ formula1: rule.formula1,
859
+ formula2: rule.formula2
860
+ };
861
+ }
862
+ async isValidType(cellInfo, formula, rule) {
863
+ return true;
864
+ }
865
+ transform(cellInfo, formula, rule) {
866
+ return cellInfo;
867
+ }
868
+ async validatorIsEqual(cellInfo, formula, rule) {
869
+ const { formula1 } = formula;
870
+ const { value: cellValue } = cellInfo;
871
+ if (Number.isNaN(formula1)) return true;
872
+ return cellValue === formula1;
873
+ }
874
+ async validatorIsNotEqual(cellInfo, formula, _rule) {
875
+ const { formula1 } = formula;
876
+ if (Number.isNaN(formula1)) return true;
877
+ return cellInfo.value !== formula1;
878
+ }
879
+ async validatorIsBetween(cellInfo, formula, _rule) {
880
+ const { formula1, formula2 } = formula;
881
+ if (Number.isNaN(formula1) || Number.isNaN(formula2)) return true;
882
+ const start = Math.min(formula1, formula2);
883
+ const end = Math.max(formula1, formula2);
884
+ return cellInfo.value >= start && cellInfo.value <= end;
885
+ }
886
+ async validatorIsNotBetween(cellInfo, formula, _rule) {
887
+ const { formula1, formula2 } = formula;
888
+ if (Number.isNaN(formula1) || Number.isNaN(formula2)) return true;
889
+ const start = Math.min(formula1, formula2);
890
+ const end = Math.max(formula1, formula2);
891
+ return cellInfo.value < start || cellInfo.value > end;
892
+ }
893
+ async validatorIsGreaterThan(cellInfo, formula, _rule) {
894
+ const { formula1 } = formula;
895
+ if (Number.isNaN(formula1)) return true;
896
+ return cellInfo.value > formula1;
897
+ }
898
+ async validatorIsGreaterThanOrEqual(cellInfo, formula, _rule) {
899
+ const { formula1 } = formula;
900
+ if (Number.isNaN(formula1)) return true;
901
+ return cellInfo.value >= formula1;
902
+ }
903
+ async validatorIsLessThan(cellInfo, formula, _rule) {
904
+ const { formula1 } = formula;
905
+ if (Number.isNaN(formula1)) return true;
906
+ return cellInfo.value < formula1;
907
+ }
908
+ async validatorIsLessThanOrEqual(cellInfo, formula, _rule) {
909
+ const { formula1 } = formula;
910
+ if (Number.isNaN(formula1)) return true;
911
+ return cellInfo.value <= formula1;
912
+ }
913
+ async validator(cellInfo, rule) {
914
+ const { value: cellValue, unitId, subUnitId } = cellInfo;
915
+ const isEmpty = this.isEmptyCellValue(cellValue);
916
+ const { allowBlank = true, operator } = rule;
917
+ if (isEmpty) return allowBlank;
918
+ const formulaInfo = await this.parseFormula(rule, unitId, subUnitId, cellInfo.row, cellInfo.column);
919
+ if (!formulaInfo.isFormulaValid) return false;
920
+ if (!await this.isValidType(cellInfo, formulaInfo, rule)) return false;
921
+ if (!operator) return true;
922
+ const transformedCell = this.transform(cellInfo, formulaInfo, rule);
923
+ switch (operator) {
924
+ case DataValidationOperator.BETWEEN: return this.validatorIsBetween(transformedCell, formulaInfo, rule);
925
+ case DataValidationOperator.EQUAL: return this.validatorIsEqual(transformedCell, formulaInfo, rule);
926
+ case DataValidationOperator.GREATER_THAN: return this.validatorIsGreaterThan(transformedCell, formulaInfo, rule);
927
+ case DataValidationOperator.GREATER_THAN_OR_EQUAL: return this.validatorIsGreaterThanOrEqual(transformedCell, formulaInfo, rule);
928
+ case DataValidationOperator.LESS_THAN: return this.validatorIsLessThan(transformedCell, formulaInfo, rule);
929
+ case DataValidationOperator.LESS_THAN_OR_EQUAL: return this.validatorIsLessThanOrEqual(transformedCell, formulaInfo, rule);
930
+ case DataValidationOperator.NOT_BETWEEN: return this.validatorIsNotBetween(transformedCell, formulaInfo, rule);
931
+ case DataValidationOperator.NOT_EQUAL: return this.validatorIsNotEqual(transformedCell, formulaInfo, rule);
932
+ default: throw new Error("Unknown operator.");
933
+ }
934
+ }
935
+ };
936
+ BaseDataValidator = __decorate([__decorateParam(0, Inject(LocaleService)), __decorateParam(1, Inject(Injector))], BaseDataValidator);
937
+
938
+ //#endregion
939
+ export { AddDataValidationMutation, BaseDataValidator, DataValidationModel, DataValidationResourceController, DataValidatorDropdownType, DataValidatorRegistryScope, DataValidatorRegistryService, FORMULA1, FORMULA2, RemoveDataValidationMutation, TWO_FORMULA_OPERATOR_COUNT, TYPE, TextLengthErrorTitleMap, UniverDataValidationPlugin, UpdateDataValidationMutation, UpdateRuleType, getRuleOptions, getRuleSetting };