New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

enum-plus

Package Overview
Dependencies
Maintainers
0
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

enum-plus - npm Package Compare versions

Comparing version 1.0.3 to 2.0.1

README.zh-CN.md

19

CHANGELOG.md

@@ -0,1 +1,20 @@

<!-- markdownlint-disable MD009 -->
# enum-plus Changelog
## 2.0.1
2025-2-2
### Features
- 🔥 Support for enum text localization
- The `Enum` method now accepts a `localize` option that can be used to localize the enum text
- You can also set the `Enum.localize` static method to localize all enums in a lower priority
- 🔥 Add `menus` method
### Breaking Changes
- 💣 All parameters after the first of the `Enum` method has been changed to an `options` object
## 1.0.3

@@ -2,0 +21,0 @@

37

es/enum-collection.d.ts

@@ -1,28 +0,6 @@

import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumOption, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem } from './types';
import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumItemOptionData, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem, EnumItemOptions, MenuItemOption } from './types';
import { EnumValuesArray } from './enum-values';
/**
* 枚举类型
*
* @example
*
* const Week = new EnumCollectionClass({
* Sunday: 0,
* Monday: 1
* } as const);
*
* const Week = new EnumCollectionClass({
* Sunday: { value: 0, label: "星期日" },
* Monday: { value: 1, label: "星期一" },
* } as const);
*
* // Usage:
*
* import('./index.ts')
*
* 更多用法请参考 `Enum` 静态方法
*
* @export
* @class EnumCollectionClass
* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* EN: Enum collection
* CN: 枚举项集合
*/

@@ -32,12 +10,13 @@ export declare class EnumCollectionClass<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> implements IEnumValues<T, K, V> {

readonly keys: K[];
constructor(init?: T);
constructor(init?: T, options?: EnumItemOptions);
key(value?: string | number): K | undefined;
label(keyOrValue?: string | number): string | undefined;
has(keyOrValue?: string | number): boolean;
options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumOption<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
options(): EnumItemOptionData<K, V>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[];
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
valuesEnum(): Record<V, {
text: string;
}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -44,0 +23,0 @@ raw(): T;

@@ -5,55 +5,33 @@ import { KEYS, VALUES } from './index';

/**
* 枚举类型
*
* @example
*
* const Week = new EnumCollectionClass({
* Sunday: 0,
* Monday: 1
* } as const);
*
* const Week = new EnumCollectionClass({
* Sunday: { value: 0, label: "星期日" },
* Monday: { value: 1, label: "星期一" },
* } as const);
*
* // Usage:
*
* import('./index.ts')
*
* 更多用法请参考 `Enum` 静态方法
*
* @export
* @class EnumCollectionClass
* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* EN: Enum collection
* CN: 枚举项集合
*/
export class EnumCollectionClass {
constructor(init = {}) {
const keys = Object.keys(init); // 定义枚举项,可以通过key直接访问,例如 Week.Monday
keys.forEach((key) => {
const { value } = parseEnumItem(init[key], key);
// @ts-ignore: 把枚举项动态扩展到this上,方便使用
constructor(init = {}, options) {
const keys = Object.keys(init);
const parsed = keys.map((key) => parseEnumItem(init[key], key, { typeInit: init, keys }));
keys.forEach((key, index) => {
const { value } = parsed[index];
// @ts-expect-error: dynamically define property
this[key] = value;
});
// @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突
// @ts-expect-error: if init contains keys, use KEYS to avoid naming conflicts
this[Object.keys(init).includes('keys') ? KEYS : 'keys'] = keys;
// 构建枚举项数据
// @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突
const values = new EnumValuesArray(init, ...keys.map((key) => {
const { value, label } = parseEnumItem(init[key], key);
return new EnumItemClass(key, value, label, init[key]);
// Build enum item data
const values = new EnumValuesArray(init, ...keys.map((key, index) => {
const { value, label } = parsed[index];
return new EnumItemClass(key, value, label, init[key], options).readonly();
}));
// @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突
// @ts-expect-error: if init contains values, use VALUES to avoid naming conflicts
this[Object.keys(init).includes('values') ? VALUES : 'values'] = values;
// 重写一些系统方法,不写在class声明上是因为会在ts中多一个Symbol的字段,在开发时没必要看到
// @ts-ignore: 重写Object.toString方法,显示类型更友好
// Override some system methods
// @ts-expect-error: Override Object.toString method for better type display
this[Symbol.toStringTag] = 'EnumCollection';
// 重写 `instanceof` 操作符规则
// @ts-ignore: 重写 instanceof 操作符,以识别枚举类型
// Override the `instanceof` operator rule
// @ts-expect-error: Override the instanceof operator
this[Symbol.hasInstance] = (instance) => {
// value故意使用==,支持数字和字符创格式的value
// intentionally use == to support both number and string format value
return this.values.some(
// eslint-disable-next-line eqeqeq
(i) => i.value == instance || i.key === instance || i.label === instance);
(i) => instance == i.value || instance === i.key);
};

@@ -74,3 +52,3 @@ Object.freeze(this);

options(config) {
// @ts-ignore: 调用values的options方法
// @ts-ignore: call the options method of values
return this.values.options(config);

@@ -81,2 +59,5 @@ }

}
menus() {
return this.values.menus();
}
filters() {

@@ -103,9 +84,8 @@ return this.values.filters();

}
function parseEnumItem(init, key) {
function parseEnumItem(init, key, options) {
var _a, _b;
let value;
let label;
if (init !== undefined) {
if (init != null) {
if (typeof init === 'number' || typeof init === 'string' || typeof init === 'symbol') {
// EnumValue类型
value = init;

@@ -115,7 +95,8 @@ label = key;

else if (typeof init === 'object') {
// Initialize using object
if (Object.prototype.toString.call(init) === '[object Object]') {
if ('value' in init /*TS assertion*/ && Object.keys(init).includes('value')) {
// {value, label}类型
if ('value' in init && Object.keys(init).includes('value')) {
// type of {value, label}
value = (_a = init.value) !== null && _a !== void 0 ? _a : key;
if ('label' in init /*TS assertion*/ && Object.keys(init).includes('label')) {
if ('label' in init && Object.keys(init).includes('label')) {
label = init.label;

@@ -127,4 +108,4 @@ }

}
else if ('label' in init /*TS assertion*/ && Object.keys(init).includes('label')) {
// {label}类型
else if ('label' in init && Object.keys(init).includes('label')) {
// typeof {label}
value = key;

@@ -134,3 +115,3 @@ label = (_b = init.label) !== null && _b !== void 0 ? _b : key;

else {
// {} 空对象
// {} empty object
value = key;

@@ -141,3 +122,3 @@ label = key;

else {
// 可能是Date、RegExp等基元类型
// Probably Date, RegExp and other primitive types
value = init;

@@ -152,8 +133,44 @@ label = key;

else {
// undefined类型
return inferFromNull(key, options);
}
return { value, label };
}
function inferFromNull(key, options) {
const { typeInit, keys } = options;
let value;
const label = key;
// If the value is empty, first check the number incrementing enumeration, otherwise use the key as the value
const index = keys.indexOf(key);
const prev = typeInit[keys[index - 1]];
// Only pure number and empty enumeration will be incremented
if (keys.some((k) => typeInit[k] != null && typeof typeInit[k] !== 'number')) {
value = key;
label = key;
}
else if (index === 0) {
value = 0;
}
else if (typeof prev === 'number') {
value = (prev + 1);
}
else {
// only nulls
let seed = 0;
let count = 0;
// find seed
for (let i = index - 1; i >= 0; i--) {
const val = typeInit[keys[i]];
count++;
if (typeof val === 'number') {
seed = val;
break;
}
else {
// only nulls
continue;
}
}
value = (seed + count);
}
return { value, label };
}
//# sourceMappingURL=enum-collection.js.map

@@ -1,20 +0,28 @@

import type { EnumItemInit, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
import type { EnumItemInit, EnumItemOptions, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
/**
* Enum item class
* @template V General type of value
* @template K General type of key
* @template T Initialize object of enum item
*/
export declare class EnumItemClass<T extends EnumItemInit<V>, K extends EnumKey<any> = string, V extends EnumValue = ValueTypeFromSingleInit<T, K>> {
/**
* 枚举项的值
*/
#private;
/** Enum item value */
readonly value: V;
/**
* 枚举项的显示名称
*/
/** Enum item label (or called display name) */
readonly label: string;
/**
* 枚举项的Key
*/
/** Enum item key */
readonly key: K;
/** Original initialization object */
readonly raw: T;
/**
* 原始初始化对象
* Instantiate an enum item
* @param key Enum item key
* @param value Enum item value
* @param label Enum item display name
* @param raw Original initialization object
* @param options Construction options
*/
readonly raw: T;
constructor(key: K, value: V, label: string, raw: T);
constructor(key: K, value: V, label: string, raw: T, options?: EnumItemOptions);
readonly(): this;
toString(): string;

@@ -21,0 +29,0 @@ toLocaleString(): string;

@@ -0,3 +1,57 @@

var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _EnumItemClass_localize, _EnumItemClass_localizedProxy;
import { Enum } from '.';
/**
* Enum item class
* @template V General type of value
* @template K General type of key
* @template T Initialize object of enum item
*/
export class EnumItemClass {
constructor(key, value, label, raw) {
/**
* Instantiate an enum item
* @param key Enum item key
* @param value Enum item value
* @param label Enum item display name
* @param raw Original initialization object
* @param options Construction options
*/
constructor(key, value, label, raw, options) {
_EnumItemClass_localize.set(this, void 0);
_EnumItemClass_localizedProxy.set(this, new Proxy(this, {
get: (target, prop) => {
const origin = target[prop];
if (prop === 'label') {
return target.toString();
}
else if (typeof origin === 'function') {
return origin.bind(target);
}
return origin;
},
// Not allowed to edit
set: () => {
return true;
},
defineProperty: () => {
return true;
},
deleteProperty: () => {
return true;
},
setPrototypeOf: () => {
return true;
},
}));
const { localize = Enum.localize } = options !== null && options !== void 0 ? options : {};
this.key = key;

@@ -7,22 +61,32 @@ this.value = value;

this.raw = raw;
// 重写一些系统方法,不写在class声明上是因为会在ts中多一个Symbol的字段,开发时没必要看到
// @ts-ignore: 重写Object.toString方法,显示类型更友好
__classPrivateFieldSet(this, _EnumItemClass_localize, (content) => {
if (typeof localize === 'function') {
return localize(content);
}
return content;
}, "f");
// Override some system methods
// @ts-ignore: Override Object.toString method to display type more friendly
this[Symbol.toStringTag] = 'EnumItem';
// @ts-ignore: 重写Object.toPrimitive方法,返回枚举值
// @ts-ignore: Override Object.toPrimitive method to return enum value
this[Symbol.toPrimitive] = (hint) => {
if (hint === 'number') {
// +value
return this.value;
// for cases like Number(value) or +value
return this.valueOf();
}
else if (hint === 'string') {
// `${value}`
return this.label;
// for cases like String(value), `${value}`
return this.toString();
}
// value + ''
return this.label;
// for cases like '' + value, value == 1
return this.valueOf();
};
Object.freeze(this);
// Object.freeze(this);
}
readonly() {
return __classPrivateFieldGet(this, _EnumItemClass_localizedProxy, "f");
}
toString() {
return this.label;
var _a;
return (_a = __classPrivateFieldGet(this, _EnumItemClass_localize, "f").call(this, this.label)) !== null && _a !== void 0 ? _a : this.label;
}

@@ -36,2 +100,3 @@ toLocaleString() {

}
_EnumItemClass_localize = new WeakMap(), _EnumItemClass_localizedProxy = new WeakMap();
//# sourceMappingURL=enum-item.js.map
import type { EnumItemClass } from './enum-item';
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumKey, EnumOption, EnumValue, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types';
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumKey, EnumItemOptionData, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types';
/**
* 枚举项集合数组
* Enum items array, mostly are simple wrappers for EnumCollectionClass
*

@@ -10,3 +10,3 @@ * @export

* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* @template T Type of the initialization data of the enum collection
*/

@@ -16,6 +16,6 @@ export declare class EnumValuesArray<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> extends Array<EnumItemClass<T[K], K, V>> implements IEnumValues<T, K, V> {

/**
* 构造函数
* Instantiate an enum items array
*
* @param {T} raw 原始初始化数据对象
* @param {...EnumItemClass<T[K], K, V>[]} items 生成后的枚举项数组
* @param {T} raw Original initialization data object
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array
* @memberof EnumValuesArray

@@ -27,8 +27,9 @@ */

has(keyOrValue?: string | number): boolean;
options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumOption<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
options(): EnumItemOptionData<K, V>[];
options(config?: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[];
options<FK = never, FV = never>(config?: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
valuesEnum(): Record<V, {
text: string;
}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -39,13 +40,13 @@ raw(): T;

/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get valueType(): V;
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get keyType(): K;
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get rawType(): T[K];
}

@@ -14,3 +14,3 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {

/**
* 枚举项集合数组
* Enum items array, mostly are simple wrappers for EnumCollectionClass
*

@@ -21,10 +21,10 @@ * @export

* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* @template T Type of the initialization data of the enum collection
*/
export class EnumValuesArray extends Array {
/**
* 构造函数
* Instantiate an enum items array
*
* @param {T} raw 原始初始化数据对象
* @param {...EnumItemClass<T[K], K, V>[]} items 生成后的枚举项数组
* @param {T} raw Original initialization data object
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array
* @memberof EnumValuesArray

@@ -42,3 +42,3 @@ */

var _a, _b;
// 先查value,再查key
// First find by value, then find by key
return (_b = ((_a = this.find((i) => i.value === keyOrValue)) !== null && _a !== void 0 ? _a : this.find((i) => i.key === keyOrValue))) === null || _b === void 0 ? void 0 : _b.label;

@@ -54,3 +54,3 @@ }

options(config = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f")) {
var _a;
var _a, _b, _c;
const { firstOption = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f").firstOption } = config;

@@ -60,7 +60,9 @@ if (firstOption) {

// 默认选项
return [{ key: '', value: '', label: '全部' }, ...this];
const value = (_a = ('firstOptionValue' in config ? config.firstOptionValue : undefined)) !== null && _a !== void 0 ? _a : '';
const label = (_b = ('firstOptionLabel' in config ? config.firstOptionLabel : undefined)) !== null && _b !== void 0 ? _b : 'All';
return [{ key: '', value, label }, ...this];
}
else {
return [
Object.assign(Object.assign({}, firstOption), { key: (_a = firstOption.key) !== null && _a !== void 0 ? _a : firstOption.value }),
Object.assign(Object.assign({}, firstOption), { key: (_c = firstOption.key) !== null && _c !== void 0 ? _c : firstOption.value }),
...this,

@@ -82,2 +84,5 @@ ];

}
menus() {
return this.map(({ value, label }) => ({ key: value, label }));
}
filters() {

@@ -88,3 +93,3 @@ return this.map(({ value, label }) => ({ text: label, value }));

if (value == null) {
// 返回整个对象
// Return the original initialization object
return __classPrivateFieldGet(this, _EnumValuesArray_raw, "f");

@@ -94,6 +99,6 @@ }

if (Object.keys(__classPrivateFieldGet(this, _EnumValuesArray_raw, "f")).includes(value)) {
// 当做key查找
// Find by key
return __classPrivateFieldGet(this, _EnumValuesArray_raw, "f")[value];
}
// 当做value查找
// Find by value
const itemByValue = this.find((i) => i.value === value);

@@ -109,18 +114,18 @@ if (itemByValue) {

/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get valueType() {
throw new Error('枚举的valueType属性仅允许用来声明ts类型,不能在运行时访问! 在ts类型中请配合`typeof`运算符使用,例如: typeof Week.valueType');
throw new Error('The valueType property of the enumeration is only allowed to be used to declare the ts type, and cannot be accessed at runtime! Please use the `typeof` operator in the ts type, for example: typeof Week.valueType');
}
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get keyType() {
throw new Error('枚举的keyType属性仅允许用来声明ts类型,不能在运行时访问! 在ts类型中请配合`typeof`运算符使用,例如: typeof Week.keyType');
throw new Error('The keyType property of the enumeration is only allowed to be used to declare the ts type, and cannot be accessed at runtime! Please use the `typeof` operator in the ts type, for example: typeof Week.keyType');
}
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get rawType() {
throw new Error('枚举的rawType属性仅允许用来声明ts类型,不能在运行时访问! 在ts类型中请配合`typeof`运算符使用,例如: typeof Week.rawType');
throw new Error('The rawType property of the enumeration is only allowed to be used to declare the ts type, and cannot be accessed at runtime! Please use the `typeof` operator in the ts type, for example: typeof Week.rawType');
}

@@ -127,0 +132,0 @@ }

@@ -1,129 +0,58 @@

import type { EnumInit, EnumKey, EnumValue, IEnum, StandardEnumInit, ValueTypeFromSingleInit } from './types';
import type { EnumInit, EnumInitOptions, EnumKey, EnumValue, IEnum, StandardEnumInit, ValueTypeFromSingleInit } from './types';
export * from './types';
/**
* 枚举values集合的访问Symbol,一般情况下使用不到
* EN: Alias of `values`. If the enum contains a field with the same name as `values`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `values` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问
*/
export declare const VALUES: unique symbol;
/**
* 枚举keys集合的访问Symbol,一般情况下使用不到
* EN: Alias of `keys`. If the enum contains a field with the same name as `keys`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `keys` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问
*/
export declare const KEYS: unique symbol;
/**
* 生成一个枚举集合,枚举值仅支持 `number` 和 `string` 两种类型。
* EN: Generate an enum collection, the enum value supports `number` and `string` types, and the enum name supports localization solutions
*
* CN: 生成一个枚举集合,枚举值支持`number`和`string`类型,枚举名称支持本地化方案
*
* @example
* // 示例1:number类型
* const Week = Enum({
* Sunday: 0,
* Monday: 1
* Sunday: { value: 0, label: 'Sunday' },
* Monday: { value: 1, label: 'Monday' }
* } as const);
*
* // 示例2:string类型
* const Week = Enum({
* Sunday: "Sunday",
* Monday: "Monday"
* } as const);
* @param init Enum item object, see usage examples for the way to pass values | 枚举项对象,传值方式参见使用示例
* @returns Enum collection | 枚举集合
*/
export declare function Enum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T): IEnum<T, K, V>;
/**
* EN: Generate an enum based on the Map object
*
* // 示例3(标准写法,推荐):扩展label显示文本
* const Week = Enum({
* Sunday: { value: 0, label: '星期日' },
* Monday: { value: 1, label: '星期一' }
* } as const);
* CN: 基于Map对象生成枚举
*
* // 示例4(推荐):省略label,value的默认值为key
* const Week = Enum({
* Sunday: { label: '星期日' }, // 等价于 { value: "Sunday", label: '星期日' }
* Monday: { label: '星期一' } // 等价于 { value: "Monday", label: '星期一' }
* } as const);
* @param init map object, see usage examples for the way to pass values | map对象,传值方式参见使用示例
* @returns Enum collection | 枚举集合
*/
export declare function Enum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T, options: EnumInitOptions<T, K, V>): IEnum<T, K, V>;
/**
* EN: Generate an enum based on an object array
*
* // 示例5:与示例2等价,value的默认值为key
* const Week = Enum({
* Sunday: undefined, // 等价于 { value: "Sunday" }
* Monday: undefined // 等价于 { value: "Sunday" }
* } as const);
* CN: 基于对象数组生成枚举
*
* @param init Enum item array | 枚举项数组
*/
export declare function Enum<T extends Record<string, any>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T[]): IEnum<StandardEnumInit<string, V>, string, V>;
/**
* EN: Generate an enum based on an object array
*
* // 示例6:扩展自定义字段
* const Week = Enum({
* Sunday: { value: 0, label: '星期日', active: true, disabled: false },
* Monday: { value: 0, label: '星期日', active: false, disabled: true }
* } as const);
* // Week.raw('Sunday').active // true
* // Week.raw('Monday').disabled // true
* CN: 基于对象数组生成枚举
*
* // Usage:
*
* // 直接作为Select的数据源
* <Select options={Week.values} />
* // 在头部增加默认选项(默认文本为'全部',value为'')
* <Select options={Week.options({ firstOption: true })} />
* // 在头部增加自定义选项
* <Select options={Week.options({ firstOption: { value: 0, label: '不限' } as const })} />
*
* // 使用AntDesignPro
* <ProFormSelect valueEnum={Week.valuesEnum()} />
*
* // 支持所有数组遍历,但不支持任何形式的修改
* Week.values.length; // 2
* Week.values.map((item) => item.value); // [0, 1],可遍历
* Week.values.forEach(item => { }); // 可遍历
* for (let item of Week.values) { } // 可遍历
* Week.values.push({ value: 2, label: '星期二' }); // ❌ 不可修改
* Week.values[0].label = "foo"; // ❌ 不可修改
*
* // 获取第一个枚举项的值
* Week.values[0].value // 0
*
* // 判断某个值是否有效?
* Week.values.some(item => item.value === 1); // true
* if(1 instance of Week) // true,更简单的用法
*
* // instanceof 判断
* 1 instance of Week // true
* "1" instance of Week // true
* "Monday" instance of Week // true
*
* // 获取某个值的显示文本
* Week.label(1); // 星期一,
* Week.label(Week.Monday); // 星期一
* Week.label('Monday'); // 星期一
*
* // 获取某个枚举项的key
* Week.key(1); // 'Monday'
* Week.key(Week.Monday); // 'Monday'
* Week.key(9); // undefined
*
* // 两个枚举合并(或者扩展某个枚举)
* const myWeek = Enum({
* ...Week.raw(),
* Friday: 5,
* Saturday: 6,
* };
*
* // 给枚举字段声明类型,【强烈建议】
* type Props = {
* week: typeof Week.valueType // 0 | 1
* weekName: typeof Week.keyType // 'Sunday' | 'Monday'
* };
* // 使用valueType类型可以更准确的限定取值范围,比使用number、string这种宽泛的数据类型更好
*
* // 😟命名冲突?
* // 如果Week的key、label、options方法与某个枚举的key重名了,则这些方法会被覆盖掉,
* // 不用担心,在 `Week.values` 下仍然可以访问到这些方法
*
* @param init 枚举项对象,传值方式参见使用示例
* @returns 枚举集合
* @param init Enum item array | 枚举项数组
* @param options Generate options | 生成选项
*/
export declare function Enum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T): IEnum<T, K, V> & Object;
/**
* 从数组构造枚举集合
* @param init 枚举项数组
* @param getValue 枚举项的value字段名,或者获取key值的函数
* @param getLabel 枚举项的label字段名,或者获取key值的函数
* @param getKey 枚举项的key字段名,或者获取key值的函数
*/
export declare function Enum<T extends Record<string, any>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T[], getValue?: keyof T | ((item: T) => V), getLabel?: keyof T | ((item: T) => string), getKey?: keyof T | ((item: T) => string)): IEnum<StandardEnumInit<string, V>, string, V>;
export declare function Enum<T extends Record<string, any>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T[], options: EnumInitOptions<T, K, V>): IEnum<StandardEnumInit<string, V>, string, V>;
export declare namespace Enum {
var localize: (<T extends string>(content: T | undefined) => string | T | undefined) | undefined;
}
import { EnumCollectionClass } from './enum-collection';
export * from './types';
/**
* 枚举values集合的访问Symbol,一般情况下使用不到
* EN: Alias of `values`. If the enum contains a field with the same name as `values`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `values` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问
*/
export const VALUES = Symbol('[values]');
/**
* 枚举keys集合的访问Symbol,一般情况下使用不到
* EN: Alias of `keys`. If the enum contains a field with the same name as `keys`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `keys` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问
*/
export const KEYS = Symbol('[keys]');
export function Enum(init, getValue = 'value', getLabel = 'label', getKey = 'key') {
export function Enum(init, options) {
if (Array.isArray(init)) {
const initMap = getInitMapFromArray(init, getValue, getLabel, getKey);
return new EnumCollectionClass(initMap);
const initMap = getInitMapFromArray(init, options);
return new EnumCollectionClass(initMap, options);
}
else {
return new EnumCollectionClass(init);
return new EnumCollectionClass(init, options);
}
}
function getInitMapFromArray(init, getValue, getLabel, getKey) {
/**
* EN: Global localization function, used to convert enum item text to localized text. Only need to be set once, effective globally, need to be set at the project entry, before running any Enum instance
*
* CN: 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效,需要在项目入口处设置,在运行任何Enum实例之前
*
* @param content Original text | 原始文本
* @returns Localized text | 本地化文本
*/
Enum.localize = undefined;
function getInitMapFromArray(init, options) {
const { getValue = 'value', getLabel = 'label', getKey = 'key', } = options !== null && options !== void 0 ? options : {};
return init.reduce((acc, item) => {

@@ -26,0 +36,0 @@ const value = typeof getValue === 'function' ? getValue(item) : item[getValue];

import type { KEYS, VALUES } from './index';
import type { EnumItemClass } from './enum-item';
/**
* 数组的类型声明
* **EN:** Enum initialization options
*
* **CN:** 枚举初始化选项
*/
export declare type EnumInitOptions<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> = {
/**
* **EN:** The name of the field in the enumeration item that stores the value, or the function to get the key value, default is `value`
*
* **CN:** 枚举项的value字段名,或者获取key值的函数,默认为 `value`
*/
getValue?: keyof T | ((item: T) => V);
/**
* **EN:** The name of the field in the enumeration item that stores the label, or the function to get the key value, default is `label`
*
* **CN:** 枚举项的label字段名,或者获取key值的函数,默认为 `label`
*/
getLabel?: keyof T | ((item: T) => string);
/**
* **EN:** The name of the field in the enumeration item that stores the key, or the function to get the key value, default is `key`
*
* **CN:** 枚举项的key字段名,或者获取key值的函数,默认为 `key`
*/
getKey?: keyof T | ((item: T) => K);
} & EnumItemOptions;
export declare type EnumItemOptions = {
/**
* **EN:** Localization function, used to convert the text of the enumeration item to localized text
*
* **CN:** 本地化函数,用于把枚举项文本转换为本地化文本
*
* @param content Original text | 原始文本
* @returns Localized text | 本地化文本
*/
localize?: <T extends string>(content: T | undefined) => T | string | undefined;
};
/**
* **EN:** Enum collection interface
*
* Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you can only use `type`
*
* **CN:** 数组的类型声明
*
* 本来可以直接使用`EnumClass`, 但是TS不允许`class`中自定义索引访问器,只能使用`type`
*/
export declare type IEnum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> = IEnumValues<T, K, V> & {
[key in K]: ValueTypeFromSingleInit<T[key], key>;
[key in K]: ValueTypeFromSingleInit<T[key], key, T[K] extends number | undefined ? number : key>;
} & (T extends {

@@ -16,4 +56,8 @@ values: unknown;

/**
* 所有枚举项的数组,可以直接作为AntDesign组件的数据源
* **EN:** All enumeration items in the array, can be used directly as the data source of the AntDesign component
*
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any modification methods
*
* **CN:** 所有枚举项的数组,可以直接作为AntDesign组件的数据源
*
* 仅支持 ReadonlyArray<T> 中的只读方法,不支持push、pop等任何修改的方法

@@ -28,4 +72,8 @@ */

/**
* 获取枚举项的key列表
* **EN:** Get the key list of the enumeration item
*
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any modification methods
*
* **CN:** 获取枚举项的key列表
*
* 常在typescript作为类型声明使用,例如: `type Props = { week: typeof Week['keys'] }`

@@ -36,52 +84,69 @@ */

/**
* 枚举项集合接口,不包含从数组集成的成员
* **EN:** Enum item collection interface, excluding members inherited from the array
*
* **CN:** 枚举项集合接口,不包含从数组集成的成员
*
* @export
* @interface IEnumValues
* @template T 枚举集合初始化数据的类型
* @template T Enum collection initialization data type | 枚举集合初始化数据的类型
*/
export interface IEnumValues<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> {
/**
* 获取某个枚举项的label显示名称
* @param value 枚举项的value或key
* @returns {string | undefined} 枚举项的label显示名称
* **EN:** Get the enumeration item by key or value
*
* **CN:** 获取某个枚举项的label显示名称
*
* @param value Enum item value or key | 枚举项的value或key
* @returns {string | undefined} Display name of the enumeration item | 枚举项的label显示名称
*/
label(keyOrValue?: string | number): string | undefined;
/**
* 获取某个枚举项对应的key
* **EN:** Get the key corresponding to a certain enumeration item
*
* **CN:** 获取某个枚举项对应的key
*/
key(value?: string | number): K | undefined;
/**
* 判断某个枚举项是否存在
* @param keyOrValue 枚举项的key或value
* **EN:** Get the value corresponding to a certain enumeration item
*
* **CN:** 判断某个枚举项是否存在
*
* @param keyOrValue Enum item key or value | 枚举项的key或value
*/
has(keyOrValue?: string | number): boolean;
/**
* 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
* **EN:** Generate an array of data sources that meet the AntDesign specification, which can be directly passed to the `options` of components such as Select, Radio, and Checkbox
*
* The data format is: `[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* 数据格式为:`[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*/
options(): EnumOption<K, V>[];
options(): EnumItemOptionData<K, V>[];
/**
* 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
* **EN:** Generate an array of data sources that meet the AntDesign specification, which can be directly passed to the `options` of components such as Select, Radio, and Checkbox
*
* @param config 自定义选项
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* @param config Custom options | 自定义选项
*/
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[];
/**
* 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
* **EN:** Generate an array of data sources that meet the AntDesign specification, which can be directly passed to the `options` of components such as Select, Radio, and Checkbox
*
* @param config 自定义选项
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* @param config Custom options | 自定义选项
*/
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumOption<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
options<FK, FV>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
/**
* 生成一个符合AntDesignPro规范的枚举集合对象。
* **EN:** Generate an object that meets the AntDesignPro specification for the enumeration set
*
* 数据结构为:
* The data structure is: `{ 0: { text: "Sunday" }, 1: { text: "Monday" } }`
*
* @example
* // 对象的`key`为枚举项的值,`value`为枚举项的label名称
* {
* 0: { text: "星期日" },
* 1: { text: "星期一" },
* };
* **CN:** 生成一个符合AntDesignPro规范的枚举集合对象。
*
* 数据结构为:`{ 0: { text: "Sunday" }, 1: { text: "Monday" } }`
*
* @see https://procomponents.ant.design/components/schema#valueenum-1

@@ -94,12 +159,10 @@ * @see https://procomponents.ant.design/components/field-set#proformselect

/**
* 生成一个filters数组,可以直接传递给AntDesign Table组件Column的filters属性,作为列的筛选项
* **EN:** Generate a data source that meets the specification of the column filter function of the AntDesign Table component
*
* 数据结构为:
* The data structure is: `[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]`
*
* @example
* [
* { value: 0, text: "星期日" },
* { value: 1, text: "星期一" },
* ]
* **CN:** 为AntDesign Table组件的列筛选功能生成符合规范的数据源
*
* 数据结构为:`[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]`
*
* @see https://ant.design/components/table-cn#components-table-demo-head

@@ -110,4 +173,17 @@ * @see https://ant.design/components/table-cn#column

/**
* 获取枚举集合的初始化对象
* @return {T} 初始化对象集合
* **EN:** Generate a data source that meets the specification of the AntDesign Menu, Dropdown and other components
*
* The data structure is: `[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]`
*
* **CN:** 为 AntDesign Menu、Dropdown 等组件生成符合规范的数据源
*
* 数据结构为:`[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]`
*/
menus(): MenuItemOption<V>[];
/**
* **EN:** Get the enumeration item by key or value
*
* **CN:** 获取枚举集合的初始化对象
*
* @return {T} Enum collection initialization object | 初始化对象集合
* @memberof IEnumValues

@@ -117,4 +193,7 @@ */

/**
* 获取某个枚举项的原始初始化对象。如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
* @param keyOrValue 枚举key或value
* **EN:** Get the original initialization object of a certain enumeration item. If custom fields are added to the enumeration item, you can use this method to get them.
*
* **CN:** 获取某个枚举项的原始初始化对象。如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
*
* @param keyOrValue Enum key or value | 枚举key或value
*/

@@ -124,4 +203,8 @@ raw(keyOrValue: V | K): T[K];

/**
* 所有枚举值的数据类型
* **EN:** The data type of all enumeration values
*
* 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* **CN:** 所有枚举值的数据类型
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用

@@ -131,15 +214,18 @@ *

*
* // 声明变量的类型
* // Declare the type of the variable | 声明变量的类型
* const week: typeof Week.valueType = Week.Monday; // 0
*
* // 声明类型字段
* // Declare type field | 声明类型字段
* type Props = {
* week: typeof Week.valueType // 0 | 1
* };
* // 使用valueType类型可以更准确的限定取值范围,比使用number、string这种宽泛的数据类型更好
*/
valueType: V;
/**
* 所有枚举key的数据类型
* **EN:** The data type of all enumeration keys
*
* 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* **CN:** 所有枚举key的数据类型
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用

@@ -149,18 +235,19 @@ *

*
* // 声明变量的类型
* // Declare the type of the variable | 声明变量的类型
* const weekName: typeof Week.keyType = "Sunday"; // "Sunday" | "Monday"
*
* // 声明类型字段
* // Declare type field | 声明类型字段
* type Props = {
* weekName: typeof Week.keyType // "Sunday" | "Monday"
* };
* // 使用keyType类型可以更准确的限定取值范围,比使用string这种宽泛的数据类型更好
*/
keyType: K;
/**
* 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
* **EN:** The type of the original initialization object of the enumeration item. If custom fields are added to the enumeration item, you can use this method to get them.
*
* **CN:** 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
*/
rawType: T[K];
}
export declare type EnumInit<K extends keyof any = string, V extends EnumValue = EnumValue> = NumberEnumInit<K> | StringEnumInit<K> | StandardEnumInit<K, V> | ValueOnlyEnumInit<K, V> | LabelOnlyEnumInit<K> | CompactEnumInit<K> | OmitEnumInit<K>;
export declare type EnumInit<K extends keyof any = string, V extends EnumValue = EnumValue> = NumberEnumInit<K> | StringEnumInit<K> | StandardEnumInit<K, V> | ValueOnlyEnumInit<K, V> | LabelOnlyEnumInit<K> | CompactEnumInit<K> | AutoIncrementedEnumInit<K>;
export declare type NumberEnumInit<K extends keyof any> = Record<K, number>;

@@ -172,3 +259,5 @@ export declare type StringEnumInit<K extends keyof any> = Record<K, string>;

export declare type CompactEnumInit<K extends keyof any> = Record<K, CompactEnumItemInit>;
export declare type OmitEnumInit<K extends keyof any> = Record<K, undefined>;
export declare type AutoIncrementedEnumInit<K extends keyof any> = Record<K, undefined>;
/** @deprecated Use `AutoIncrementedEnumInit` instead */
export declare type OmitEnumInit<K extends keyof any> = AutoIncrementedEnumInit<K>;
export declare type EnumItemInit<V extends EnumValue = EnumValue> = EnumValue | StandardEnumItemInit<V> | ValueOnlyEnumItemInit<V> | LabelOnlyEnumItemInit | CompactEnumItemInit | undefined;

@@ -186,72 +275,84 @@ export declare type StandardEnumItemInit<V extends EnumValue> = {

export declare type CompactEnumItemInit = Record<string, never>;
/**
* 由枚举项生成的作为Select组件数据源的数据结构
*/
export declare type EnumOption<K, V> = {
/**
* 选项的值
*/
/** Data structure of ant-design Select options */
export declare type EnumItemOptionData<K, V> = {
/** Option value */
value: V;
/**
* 选项的显示文本
*/
/** Option label */
label: string;
/**
* 选项的key,默认使用`value`
*/
/** Option key, default is `value` */
key: K;
};
/**
* Table列筛选项的数据结构
*/
/** Data structure of column filter items of ant-design Table */
export declare type ColumnFilterItem<V> = {
/**
* 显示文本
*/
/** Display name */
text: string;
/**
* 值
*/
/** Value */
value: V;
};
/**
* 枚举值的类型,支持number、string、symbol
*/
/** Data structure of ant-design Menu items */
export declare type MenuItemOption<V> = {
/** Key of menu item */
key: V;
/** Menu item text */
label: string;
};
/** Enum value type, support number, string, symbol */
export declare type EnumValue = keyof any;
/**
* 获取枚举初始化对象中key的类型
*/
/** Enum key collection */
export declare type EnumKey<T> = keyof T;
/**
* options方法的更多选项
*/
/** More options for the options method */
export declare type OptionsConfig = object;
export declare type BooleanFirstOptionConfig<B extends boolean> = {
export declare type BooleanFirstOptionConfig<V> = {
/**
* 在头部添加一个默认选项。
* **EN:** Add a default option at the top
* - `true`: the option uses the default value, `value` is `''`, `label` is `'All'`;
* - `false`: the default option is not added;
*
* 如果为`true`,则选项使用默认值,`value`为`''`,`label`为`'全部'`;
* 如果为`false`,则不添加默认选项;
* **CN:** 在头部添加一个默认选项
*
* - `true`:选项使用默认值,`value`为`''`,`label`为`'全部'`
* - `false`:不添加默认选项
*
* @default false
*/
firstOption?: B;
firstOption: boolean;
/**
* **EN:** Default option value, default is `''`
*
* **CN:** 默认选项的值,默认为`''`
*
* @default ''
*/
firstOptionValue?: V;
/**
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called
*
* **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法
*/
firstOptionLabel?: string;
};
export declare type ObjectFirstOptionConfig<K, V> = {
/**
* 首行选项的配置
* **EN:** Configuration of the first option
*
* **CN:** 首行选项的配置
*/
firstOption?: EnumOptionConfig<K, V>;
/**
* **EN:** Add a default option at the top
*
* **CN:** 默认选项的值,默认为`''`
*/
firstOptionValue?: never;
/**
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called
*
* **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法
*/
firstOptionLabel?: never;
};
export declare type EnumOptionConfig<K, V> = Omit<EnumOption<K, V>, 'key'> & Partial<Pick<EnumOption<K, V>, 'key'>>;
/**
* 从枚举集合或枚举项的初始化对象推断value类型
*/
/**
* 从枚举项的初始化对象推断value类型
*/
export declare type ValueTypeFromSingleInit<T, FB = string> = T extends EnumValue ? T : T extends StandardEnumItemInit<infer V> ? V : T extends ValueOnlyEnumItemInit<infer V> ? V : T extends LabelOnlyEnumItemInit ? FB : T extends CompactEnumItemInit ? FB : T extends undefined ? FB : never;
/**
* 从枚举集合初始化对象推断value类型
*/
export declare type ValueTypeFromEnumInit<T, K extends EnumKey<T> = EnumKey<T>> = T extends NumberEnumInit<K> ? number : T extends StringEnumInit<K> ? string : T extends StandardEnumInit<K, infer V> ? V : T extends ValueOnlyEnumInit<K, infer V> ? V : T extends LabelOnlyEnumInit<K> ? K : T extends CompactEnumInit<K> ? K : T extends OmitEnumInit<K> ? K : K;
export declare type EnumOptionConfig<K, V> = Omit<EnumItemOptionData<K, V>, 'key'> & Partial<Pick<EnumItemOptionData<K, V>, 'key'>>;
/** Infer the value type from the initialization object of the enumeration item */
export declare type ValueTypeFromSingleInit<T, Key = string, Fallback = Key> = T extends EnumValue ? T : T extends StandardEnumItemInit<infer V> ? V : T extends ValueOnlyEnumItemInit<infer V> ? V : T extends LabelOnlyEnumItemInit ? Key : T extends CompactEnumItemInit ? Key : T extends undefined ? Fallback : never;
/** Infer the value type from the initialization object of the enumeration collection */
export declare type ValueTypeFromEnumInit<T, K extends EnumKey<T> = EnumKey<T>> = T extends NumberEnumInit<K> ? number : T extends StringEnumInit<K> ? string : T extends StandardEnumInit<K, infer V> ? V : T extends ValueOnlyEnumInit<K, infer V> ? V : T extends LabelOnlyEnumInit<K> ? K : T extends CompactEnumInit<K> ? K : T extends AutoIncrementedEnumInit<K> ? K : K;

@@ -1,28 +0,6 @@

import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumOption, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem } from './types';
import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumItemOptionData, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem, EnumItemOptions, MenuItemOption } from './types';
import { EnumValuesArray } from './enum-values';
/**
* 枚举类型
*
* @example
*
* const Week = new EnumCollectionClass({
* Sunday: 0,
* Monday: 1
* } as const);
*
* const Week = new EnumCollectionClass({
* Sunday: { value: 0, label: "星期日" },
* Monday: { value: 1, label: "星期一" },
* } as const);
*
* // Usage:
*
* import('./index.ts')
*
* 更多用法请参考 `Enum` 静态方法
*
* @export
* @class EnumCollectionClass
* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* EN: Enum collection
* CN: 枚举项集合
*/

@@ -32,12 +10,13 @@ export declare class EnumCollectionClass<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> implements IEnumValues<T, K, V> {

readonly keys: K[];
constructor(init?: T);
constructor(init?: T, options?: EnumItemOptions);
key(value?: string | number): K | undefined;
label(keyOrValue?: string | number): string | undefined;
has(keyOrValue?: string | number): boolean;
options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumOption<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
options(): EnumItemOptionData<K, V>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[];
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
valuesEnum(): Record<V, {
text: string;
}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -44,0 +23,0 @@ raw(): T;

@@ -8,55 +8,33 @@ "use strict";

/**
* 枚举类型
*
* @example
*
* const Week = new EnumCollectionClass({
* Sunday: 0,
* Monday: 1
* } as const);
*
* const Week = new EnumCollectionClass({
* Sunday: { value: 0, label: "星期日" },
* Monday: { value: 1, label: "星期一" },
* } as const);
*
* // Usage:
*
* import('./index.ts')
*
* 更多用法请参考 `Enum` 静态方法
*
* @export
* @class EnumCollectionClass
* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* EN: Enum collection
* CN: 枚举项集合
*/
class EnumCollectionClass {
constructor(init = {}) {
const keys = Object.keys(init); // 定义枚举项,可以通过key直接访问,例如 Week.Monday
keys.forEach((key) => {
const { value } = parseEnumItem(init[key], key);
// @ts-ignore: 把枚举项动态扩展到this上,方便使用
constructor(init = {}, options) {
const keys = Object.keys(init);
const parsed = keys.map((key) => parseEnumItem(init[key], key, { typeInit: init, keys }));
keys.forEach((key, index) => {
const { value } = parsed[index];
// @ts-expect-error: dynamically define property
this[key] = value;
});
// @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突
// @ts-expect-error: if init contains keys, use KEYS to avoid naming conflicts
this[Object.keys(init).includes('keys') ? index_1.KEYS : 'keys'] = keys;
// 构建枚举项数据
// @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突
const values = new enum_values_1.EnumValuesArray(init, ...keys.map((key) => {
const { value, label } = parseEnumItem(init[key], key);
return new enum_item_1.EnumItemClass(key, value, label, init[key]);
// Build enum item data
const values = new enum_values_1.EnumValuesArray(init, ...keys.map((key, index) => {
const { value, label } = parsed[index];
return new enum_item_1.EnumItemClass(key, value, label, init[key], options).readonly();
}));
// @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突
// @ts-expect-error: if init contains values, use VALUES to avoid naming conflicts
this[Object.keys(init).includes('values') ? index_1.VALUES : 'values'] = values;
// 重写一些系统方法,不写在class声明上是因为会在ts中多一个Symbol的字段,在开发时没必要看到
// @ts-ignore: 重写Object.toString方法,显示类型更友好
// Override some system methods
// @ts-expect-error: Override Object.toString method for better type display
this[Symbol.toStringTag] = 'EnumCollection';
// 重写 `instanceof` 操作符规则
// @ts-ignore: 重写 instanceof 操作符,以识别枚举类型
// Override the `instanceof` operator rule
// @ts-expect-error: Override the instanceof operator
this[Symbol.hasInstance] = (instance) => {
// value故意使用==,支持数字和字符创格式的value
// intentionally use == to support both number and string format value
return this.values.some(
// eslint-disable-next-line eqeqeq
(i) => i.value == instance || i.key === instance || i.label === instance);
(i) => instance == i.value || instance === i.key);
};

@@ -77,3 +55,3 @@ Object.freeze(this);

options(config) {
// @ts-ignore: 调用values的options方法
// @ts-ignore: call the options method of values
return this.values.options(config);

@@ -84,2 +62,5 @@ }

}
menus() {
return this.values.menus();
}
filters() {

@@ -107,9 +88,8 @@ return this.values.filters();

exports.EnumCollectionClass = EnumCollectionClass;
function parseEnumItem(init, key) {
function parseEnumItem(init, key, options) {
var _a, _b;
let value;
let label;
if (init !== undefined) {
if (init != null) {
if (typeof init === 'number' || typeof init === 'string' || typeof init === 'symbol') {
// EnumValue类型
value = init;

@@ -119,7 +99,8 @@ label = key;

else if (typeof init === 'object') {
// Initialize using object
if (Object.prototype.toString.call(init) === '[object Object]') {
if ('value' in init /*TS assertion*/ && Object.keys(init).includes('value')) {
// {value, label}类型
if ('value' in init && Object.keys(init).includes('value')) {
// type of {value, label}
value = (_a = init.value) !== null && _a !== void 0 ? _a : key;
if ('label' in init /*TS assertion*/ && Object.keys(init).includes('label')) {
if ('label' in init && Object.keys(init).includes('label')) {
label = init.label;

@@ -131,4 +112,4 @@ }

}
else if ('label' in init /*TS assertion*/ && Object.keys(init).includes('label')) {
// {label}类型
else if ('label' in init && Object.keys(init).includes('label')) {
// typeof {label}
value = key;

@@ -138,3 +119,3 @@ label = (_b = init.label) !== null && _b !== void 0 ? _b : key;

else {
// {} 空对象
// {} empty object
value = key;

@@ -145,3 +126,3 @@ label = key;

else {
// 可能是Date、RegExp等基元类型
// Probably Date, RegExp and other primitive types
value = init;

@@ -156,8 +137,44 @@ label = key;

else {
// undefined类型
return inferFromNull(key, options);
}
return { value, label };
}
function inferFromNull(key, options) {
const { typeInit, keys } = options;
let value;
const label = key;
// If the value is empty, first check the number incrementing enumeration, otherwise use the key as the value
const index = keys.indexOf(key);
const prev = typeInit[keys[index - 1]];
// Only pure number and empty enumeration will be incremented
if (keys.some((k) => typeInit[k] != null && typeof typeInit[k] !== 'number')) {
value = key;
label = key;
}
else if (index === 0) {
value = 0;
}
else if (typeof prev === 'number') {
value = (prev + 1);
}
else {
// only nulls
let seed = 0;
let count = 0;
// find seed
for (let i = index - 1; i >= 0; i--) {
const val = typeInit[keys[i]];
count++;
if (typeof val === 'number') {
seed = val;
break;
}
else {
// only nulls
continue;
}
}
value = (seed + count);
}
return { value, label };
}
//# sourceMappingURL=enum-collection.js.map

@@ -1,20 +0,28 @@

import type { EnumItemInit, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
import type { EnumItemInit, EnumItemOptions, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
/**
* Enum item class
* @template V General type of value
* @template K General type of key
* @template T Initialize object of enum item
*/
export declare class EnumItemClass<T extends EnumItemInit<V>, K extends EnumKey<any> = string, V extends EnumValue = ValueTypeFromSingleInit<T, K>> {
/**
* 枚举项的值
*/
#private;
/** Enum item value */
readonly value: V;
/**
* 枚举项的显示名称
*/
/** Enum item label (or called display name) */
readonly label: string;
/**
* 枚举项的Key
*/
/** Enum item key */
readonly key: K;
/** Original initialization object */
readonly raw: T;
/**
* 原始初始化对象
* Instantiate an enum item
* @param key Enum item key
* @param value Enum item value
* @param label Enum item display name
* @param raw Original initialization object
* @param options Construction options
*/
readonly raw: T;
constructor(key: K, value: V, label: string, raw: T);
constructor(key: K, value: V, label: string, raw: T, options?: EnumItemOptions);
readonly(): this;
toString(): string;

@@ -21,0 +29,0 @@ toLocaleString(): string;

"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _EnumItemClass_localize, _EnumItemClass_localizedProxy;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnumItemClass = void 0;
const _1 = require(".");
/**
* Enum item class
* @template V General type of value
* @template K General type of key
* @template T Initialize object of enum item
*/
class EnumItemClass {
constructor(key, value, label, raw) {
/**
* Instantiate an enum item
* @param key Enum item key
* @param value Enum item value
* @param label Enum item display name
* @param raw Original initialization object
* @param options Construction options
*/
constructor(key, value, label, raw, options) {
_EnumItemClass_localize.set(this, void 0);
_EnumItemClass_localizedProxy.set(this, new Proxy(this, {
get: (target, prop) => {
const origin = target[prop];
if (prop === 'label') {
return target.toString();
}
else if (typeof origin === 'function') {
return origin.bind(target);
}
return origin;
},
// Not allowed to edit
set: () => {
return true;
},
defineProperty: () => {
return true;
},
deleteProperty: () => {
return true;
},
setPrototypeOf: () => {
return true;
},
}));
const { localize = _1.Enum.localize } = options !== null && options !== void 0 ? options : {};
this.key = key;

@@ -10,22 +64,32 @@ this.value = value;

this.raw = raw;
// 重写一些系统方法,不写在class声明上是因为会在ts中多一个Symbol的字段,开发时没必要看到
// @ts-ignore: 重写Object.toString方法,显示类型更友好
__classPrivateFieldSet(this, _EnumItemClass_localize, (content) => {
if (typeof localize === 'function') {
return localize(content);
}
return content;
}, "f");
// Override some system methods
// @ts-ignore: Override Object.toString method to display type more friendly
this[Symbol.toStringTag] = 'EnumItem';
// @ts-ignore: 重写Object.toPrimitive方法,返回枚举值
// @ts-ignore: Override Object.toPrimitive method to return enum value
this[Symbol.toPrimitive] = (hint) => {
if (hint === 'number') {
// +value
return this.value;
// for cases like Number(value) or +value
return this.valueOf();
}
else if (hint === 'string') {
// `${value}`
return this.label;
// for cases like String(value), `${value}`
return this.toString();
}
// value + ''
return this.label;
// for cases like '' + value, value == 1
return this.valueOf();
};
Object.freeze(this);
// Object.freeze(this);
}
readonly() {
return __classPrivateFieldGet(this, _EnumItemClass_localizedProxy, "f");
}
toString() {
return this.label;
var _a;
return (_a = __classPrivateFieldGet(this, _EnumItemClass_localize, "f").call(this, this.label)) !== null && _a !== void 0 ? _a : this.label;
}

@@ -40,2 +104,3 @@ toLocaleString() {

exports.EnumItemClass = EnumItemClass;
_EnumItemClass_localize = new WeakMap(), _EnumItemClass_localizedProxy = new WeakMap();
//# sourceMappingURL=enum-item.js.map
import type { EnumItemClass } from './enum-item';
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumKey, EnumOption, EnumValue, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types';
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumKey, EnumItemOptionData, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types';
/**
* 枚举项集合数组
* Enum items array, mostly are simple wrappers for EnumCollectionClass
*

@@ -10,3 +10,3 @@ * @export

* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* @template T Type of the initialization data of the enum collection
*/

@@ -16,6 +16,6 @@ export declare class EnumValuesArray<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> extends Array<EnumItemClass<T[K], K, V>> implements IEnumValues<T, K, V> {

/**
* 构造函数
* Instantiate an enum items array
*
* @param {T} raw 原始初始化数据对象
* @param {...EnumItemClass<T[K], K, V>[]} items 生成后的枚举项数组
* @param {T} raw Original initialization data object
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array
* @memberof EnumValuesArray

@@ -27,8 +27,9 @@ */

has(keyOrValue?: string | number): boolean;
options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumOption<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
options(): EnumItemOptionData<K, V>[];
options(config?: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[];
options<FK = never, FV = never>(config?: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
valuesEnum(): Record<V, {
text: string;
}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -39,13 +40,13 @@ raw(): T;

/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get valueType(): V;
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get keyType(): K;
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get rawType(): T[K];
}

@@ -17,3 +17,3 @@ "use strict";

/**
* 枚举项集合数组
* Enum items array, mostly are simple wrappers for EnumCollectionClass
*

@@ -24,10 +24,10 @@ * @export

* @implements {IEnumValues<T, K, V>}
* @template T 枚举集合初始化数据的类型
* @template T Type of the initialization data of the enum collection
*/
class EnumValuesArray extends Array {
/**
* 构造函数
* Instantiate an enum items array
*
* @param {T} raw 原始初始化数据对象
* @param {...EnumItemClass<T[K], K, V>[]} items 生成后的枚举项数组
* @param {T} raw Original initialization data object
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array
* @memberof EnumValuesArray

@@ -45,3 +45,3 @@ */

var _a, _b;
// 先查value,再查key
// First find by value, then find by key
return (_b = ((_a = this.find((i) => i.value === keyOrValue)) !== null && _a !== void 0 ? _a : this.find((i) => i.key === keyOrValue))) === null || _b === void 0 ? void 0 : _b.label;

@@ -57,3 +57,3 @@ }

options(config = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f")) {
var _a;
var _a, _b, _c;
const { firstOption = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f").firstOption } = config;

@@ -63,7 +63,9 @@ if (firstOption) {

// 默认选项
return [{ key: '', value: '', label: '全部' }, ...this];
const value = (_a = ('firstOptionValue' in config ? config.firstOptionValue : undefined)) !== null && _a !== void 0 ? _a : '';
const label = (_b = ('firstOptionLabel' in config ? config.firstOptionLabel : undefined)) !== null && _b !== void 0 ? _b : 'All';
return [{ key: '', value, label }, ...this];
}
else {
return [
Object.assign(Object.assign({}, firstOption), { key: (_a = firstOption.key) !== null && _a !== void 0 ? _a : firstOption.value }),
Object.assign(Object.assign({}, firstOption), { key: (_c = firstOption.key) !== null && _c !== void 0 ? _c : firstOption.value }),
...this,

@@ -85,2 +87,5 @@ ];

}
menus() {
return this.map(({ value, label }) => ({ key: value, label }));
}
filters() {

@@ -91,3 +96,3 @@ return this.map(({ value, label }) => ({ text: label, value }));

if (value == null) {
// 返回整个对象
// Return the original initialization object
return __classPrivateFieldGet(this, _EnumValuesArray_raw, "f");

@@ -97,6 +102,6 @@ }

if (Object.keys(__classPrivateFieldGet(this, _EnumValuesArray_raw, "f")).includes(value)) {
// 当做key查找
// Find by key
return __classPrivateFieldGet(this, _EnumValuesArray_raw, "f")[value];
}
// 当做value查找
// Find by value
const itemByValue = this.find((i) => i.value === value);

@@ -112,18 +117,18 @@ if (itemByValue) {

/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get valueType() {
throw new Error('枚举的valueType属性仅允许用来声明ts类型,不能在运行时访问! 在ts类型中请配合`typeof`运算符使用,例如: typeof Week.valueType');
throw new Error('The valueType property of the enumeration is only allowed to be used to declare the ts type, and cannot be accessed at runtime! Please use the `typeof` operator in the ts type, for example: typeof Week.valueType');
}
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get keyType() {
throw new Error('枚举的keyType属性仅允许用来声明ts类型,不能在运行时访问! 在ts类型中请配合`typeof`运算符使用,例如: typeof Week.keyType');
throw new Error('The keyType property of the enumeration is only allowed to be used to declare the ts type, and cannot be accessed at runtime! Please use the `typeof` operator in the ts type, for example: typeof Week.keyType');
}
/**
* @deprecated Stub方法,不支持直接调用
* @deprecated Stub method, only for typing usages, not for runtime calling
*/
get rawType() {
throw new Error('枚举的rawType属性仅允许用来声明ts类型,不能在运行时访问! 在ts类型中请配合`typeof`运算符使用,例如: typeof Week.rawType');
throw new Error('The rawType property of the enumeration is only allowed to be used to declare the ts type, and cannot be accessed at runtime! Please use the `typeof` operator in the ts type, for example: typeof Week.rawType');
}

@@ -130,0 +135,0 @@ }

@@ -1,129 +0,58 @@

import type { EnumInit, EnumKey, EnumValue, IEnum, StandardEnumInit, ValueTypeFromSingleInit } from './types';
import type { EnumInit, EnumInitOptions, EnumKey, EnumValue, IEnum, StandardEnumInit, ValueTypeFromSingleInit } from './types';
export * from './types';
/**
* 枚举values集合的访问Symbol,一般情况下使用不到
* EN: Alias of `values`. If the enum contains a field with the same name as `values`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `values` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问
*/
export declare const VALUES: unique symbol;
/**
* 枚举keys集合的访问Symbol,一般情况下使用不到
* EN: Alias of `keys`. If the enum contains a field with the same name as `keys`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `keys` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问
*/
export declare const KEYS: unique symbol;
/**
* 生成一个枚举集合,枚举值仅支持 `number` 和 `string` 两种类型。
* EN: Generate an enum collection, the enum value supports `number` and `string` types, and the enum name supports localization solutions
*
* CN: 生成一个枚举集合,枚举值支持`number`和`string`类型,枚举名称支持本地化方案
*
* @example
* // 示例1:number类型
* const Week = Enum({
* Sunday: 0,
* Monday: 1
* Sunday: { value: 0, label: 'Sunday' },
* Monday: { value: 1, label: 'Monday' }
* } as const);
*
* // 示例2:string类型
* const Week = Enum({
* Sunday: "Sunday",
* Monday: "Monday"
* } as const);
* @param init Enum item object, see usage examples for the way to pass values | 枚举项对象,传值方式参见使用示例
* @returns Enum collection | 枚举集合
*/
export declare function Enum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T): IEnum<T, K, V>;
/**
* EN: Generate an enum based on the Map object
*
* // 示例3(标准写法,推荐):扩展label显示文本
* const Week = Enum({
* Sunday: { value: 0, label: '星期日' },
* Monday: { value: 1, label: '星期一' }
* } as const);
* CN: 基于Map对象生成枚举
*
* // 示例4(推荐):省略label,value的默认值为key
* const Week = Enum({
* Sunday: { label: '星期日' }, // 等价于 { value: "Sunday", label: '星期日' }
* Monday: { label: '星期一' } // 等价于 { value: "Monday", label: '星期一' }
* } as const);
* @param init map object, see usage examples for the way to pass values | map对象,传值方式参见使用示例
* @returns Enum collection | 枚举集合
*/
export declare function Enum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T, options: EnumInitOptions<T, K, V>): IEnum<T, K, V>;
/**
* EN: Generate an enum based on an object array
*
* // 示例5:与示例2等价,value的默认值为key
* const Week = Enum({
* Sunday: undefined, // 等价于 { value: "Sunday" }
* Monday: undefined // 等价于 { value: "Sunday" }
* } as const);
* CN: 基于对象数组生成枚举
*
* @param init Enum item array | 枚举项数组
*/
export declare function Enum<T extends Record<string, any>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T[]): IEnum<StandardEnumInit<string, V>, string, V>;
/**
* EN: Generate an enum based on an object array
*
* // 示例6:扩展自定义字段
* const Week = Enum({
* Sunday: { value: 0, label: '星期日', active: true, disabled: false },
* Monday: { value: 0, label: '星期日', active: false, disabled: true }
* } as const);
* // Week.raw('Sunday').active // true
* // Week.raw('Monday').disabled // true
* CN: 基于对象数组生成枚举
*
* // Usage:
*
* // 直接作为Select的数据源
* <Select options={Week.values} />
* // 在头部增加默认选项(默认文本为'全部',value为'')
* <Select options={Week.options({ firstOption: true })} />
* // 在头部增加自定义选项
* <Select options={Week.options({ firstOption: { value: 0, label: '不限' } as const })} />
*
* // 使用AntDesignPro
* <ProFormSelect valueEnum={Week.valuesEnum()} />
*
* // 支持所有数组遍历,但不支持任何形式的修改
* Week.values.length; // 2
* Week.values.map((item) => item.value); // [0, 1],可遍历
* Week.values.forEach(item => { }); // 可遍历
* for (let item of Week.values) { } // 可遍历
* Week.values.push({ value: 2, label: '星期二' }); // ❌ 不可修改
* Week.values[0].label = "foo"; // ❌ 不可修改
*
* // 获取第一个枚举项的值
* Week.values[0].value // 0
*
* // 判断某个值是否有效?
* Week.values.some(item => item.value === 1); // true
* if(1 instance of Week) // true,更简单的用法
*
* // instanceof 判断
* 1 instance of Week // true
* "1" instance of Week // true
* "Monday" instance of Week // true
*
* // 获取某个值的显示文本
* Week.label(1); // 星期一,
* Week.label(Week.Monday); // 星期一
* Week.label('Monday'); // 星期一
*
* // 获取某个枚举项的key
* Week.key(1); // 'Monday'
* Week.key(Week.Monday); // 'Monday'
* Week.key(9); // undefined
*
* // 两个枚举合并(或者扩展某个枚举)
* const myWeek = Enum({
* ...Week.raw(),
* Friday: 5,
* Saturday: 6,
* };
*
* // 给枚举字段声明类型,【强烈建议】
* type Props = {
* week: typeof Week.valueType // 0 | 1
* weekName: typeof Week.keyType // 'Sunday' | 'Monday'
* };
* // 使用valueType类型可以更准确的限定取值范围,比使用number、string这种宽泛的数据类型更好
*
* // 😟命名冲突?
* // 如果Week的key、label、options方法与某个枚举的key重名了,则这些方法会被覆盖掉,
* // 不用担心,在 `Week.values` 下仍然可以访问到这些方法
*
* @param init 枚举项对象,传值方式参见使用示例
* @returns 枚举集合
* @param init Enum item array | 枚举项数组
* @param options Generate options | 生成选项
*/
export declare function Enum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T): IEnum<T, K, V> & Object;
/**
* 从数组构造枚举集合
* @param init 枚举项数组
* @param getValue 枚举项的value字段名,或者获取key值的函数
* @param getLabel 枚举项的label字段名,或者获取key值的函数
* @param getKey 枚举项的key字段名,或者获取key值的函数
*/
export declare function Enum<T extends Record<string, any>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T[], getValue?: keyof T | ((item: T) => V), getLabel?: keyof T | ((item: T) => string), getKey?: keyof T | ((item: T) => string)): IEnum<StandardEnumInit<string, V>, string, V>;
export declare function Enum<T extends Record<string, any>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>>(init: T[], options: EnumInitOptions<T, K, V>): IEnum<StandardEnumInit<string, V>, string, V>;
export declare namespace Enum {
var localize: (<T extends string>(content: T | undefined) => string | T | undefined) | undefined;
}

@@ -21,24 +21,34 @@ "use strict";

/**
* 枚举values集合的访问Symbol,一般情况下使用不到
* EN: Alias of `values`. If the enum contains a field with the same name as `values`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `values` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问
*/
exports.VALUES = Symbol('[values]');
/**
* 枚举keys集合的访问Symbol,一般情况下使用不到
* EN: Alias of `keys`. If the enum contains a field with the same name as `keys`, you can access it by this Symbol as the field name
*
* 如果枚举项中包含 `keys` 保留字的话,会把枚举值集合字段给冲掉,可以通过此Symbol来访问
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问
*/
exports.KEYS = Symbol('[keys]');
function Enum(init, getValue = 'value', getLabel = 'label', getKey = 'key') {
function Enum(init, options) {
if (Array.isArray(init)) {
const initMap = getInitMapFromArray(init, getValue, getLabel, getKey);
return new enum_collection_1.EnumCollectionClass(initMap);
const initMap = getInitMapFromArray(init, options);
return new enum_collection_1.EnumCollectionClass(initMap, options);
}
else {
return new enum_collection_1.EnumCollectionClass(init);
return new enum_collection_1.EnumCollectionClass(init, options);
}
}
exports.Enum = Enum;
function getInitMapFromArray(init, getValue, getLabel, getKey) {
/**
* EN: Global localization function, used to convert enum item text to localized text. Only need to be set once, effective globally, need to be set at the project entry, before running any Enum instance
*
* CN: 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效,需要在项目入口处设置,在运行任何Enum实例之前
*
* @param content Original text | 原始文本
* @returns Localized text | 本地化文本
*/
Enum.localize = undefined;
function getInitMapFromArray(init, options) {
const { getValue = 'value', getLabel = 'label', getKey = 'key', } = options !== null && options !== void 0 ? options : {};
return init.reduce((acc, item) => {

@@ -45,0 +55,0 @@ const value = typeof getValue === 'function' ? getValue(item) : item[getValue];

import type { KEYS, VALUES } from './index';
import type { EnumItemClass } from './enum-item';
/**
* 数组的类型声明
* **EN:** Enum initialization options
*
* **CN:** 枚举初始化选项
*/
export declare type EnumInitOptions<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> = {
/**
* **EN:** The name of the field in the enumeration item that stores the value, or the function to get the key value, default is `value`
*
* **CN:** 枚举项的value字段名,或者获取key值的函数,默认为 `value`
*/
getValue?: keyof T | ((item: T) => V);
/**
* **EN:** The name of the field in the enumeration item that stores the label, or the function to get the key value, default is `label`
*
* **CN:** 枚举项的label字段名,或者获取key值的函数,默认为 `label`
*/
getLabel?: keyof T | ((item: T) => string);
/**
* **EN:** The name of the field in the enumeration item that stores the key, or the function to get the key value, default is `key`
*
* **CN:** 枚举项的key字段名,或者获取key值的函数,默认为 `key`
*/
getKey?: keyof T | ((item: T) => K);
} & EnumItemOptions;
export declare type EnumItemOptions = {
/**
* **EN:** Localization function, used to convert the text of the enumeration item to localized text
*
* **CN:** 本地化函数,用于把枚举项文本转换为本地化文本
*
* @param content Original text | 原始文本
* @returns Localized text | 本地化文本
*/
localize?: <T extends string>(content: T | undefined) => T | string | undefined;
};
/**
* **EN:** Enum collection interface
*
* Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you can only use `type`
*
* **CN:** 数组的类型声明
*
* 本来可以直接使用`EnumClass`, 但是TS不允许`class`中自定义索引访问器,只能使用`type`
*/
export declare type IEnum<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> = IEnumValues<T, K, V> & {
[key in K]: ValueTypeFromSingleInit<T[key], key>;
[key in K]: ValueTypeFromSingleInit<T[key], key, T[K] extends number | undefined ? number : key>;
} & (T extends {

@@ -16,4 +56,8 @@ values: unknown;

/**
* 所有枚举项的数组,可以直接作为AntDesign组件的数据源
* **EN:** All enumeration items in the array, can be used directly as the data source of the AntDesign component
*
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any modification methods
*
* **CN:** 所有枚举项的数组,可以直接作为AntDesign组件的数据源
*
* 仅支持 ReadonlyArray<T> 中的只读方法,不支持push、pop等任何修改的方法

@@ -28,4 +72,8 @@ */

/**
* 获取枚举项的key列表
* **EN:** Get the key list of the enumeration item
*
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any modification methods
*
* **CN:** 获取枚举项的key列表
*
* 常在typescript作为类型声明使用,例如: `type Props = { week: typeof Week['keys'] }`

@@ -36,52 +84,69 @@ */

/**
* 枚举项集合接口,不包含从数组集成的成员
* **EN:** Enum item collection interface, excluding members inherited from the array
*
* **CN:** 枚举项集合接口,不包含从数组集成的成员
*
* @export
* @interface IEnumValues
* @template T 枚举集合初始化数据的类型
* @template T Enum collection initialization data type | 枚举集合初始化数据的类型
*/
export interface IEnumValues<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> {
/**
* 获取某个枚举项的label显示名称
* @param value 枚举项的value或key
* @returns {string | undefined} 枚举项的label显示名称
* **EN:** Get the enumeration item by key or value
*
* **CN:** 获取某个枚举项的label显示名称
*
* @param value Enum item value or key | 枚举项的value或key
* @returns {string | undefined} Display name of the enumeration item | 枚举项的label显示名称
*/
label(keyOrValue?: string | number): string | undefined;
/**
* 获取某个枚举项对应的key
* **EN:** Get the key corresponding to a certain enumeration item
*
* **CN:** 获取某个枚举项对应的key
*/
key(value?: string | number): K | undefined;
/**
* 判断某个枚举项是否存在
* @param keyOrValue 枚举项的key或value
* **EN:** Get the value corresponding to a certain enumeration item
*
* **CN:** 判断某个枚举项是否存在
*
* @param keyOrValue Enum item key or value | 枚举项的key或value
*/
has(keyOrValue?: string | number): boolean;
/**
* 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
* **EN:** Generate an array of data sources that meet the AntDesign specification, which can be directly passed to the `options` of components such as Select, Radio, and Checkbox
*
* The data format is: `[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* 数据格式为:`[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*/
options(): EnumOption<K, V>[];
options(): EnumItemOptionData<K, V>[];
/**
* 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
* **EN:** Generate an array of data sources that meet the AntDesign specification, which can be directly passed to the `options` of components such as Select, Radio, and Checkbox
*
* @param config 自定义选项
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* @param config Custom options | 自定义选项
*/
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[];
/**
* 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
* **EN:** Generate an array of data sources that meet the AntDesign specification, which can be directly passed to the `options` of components such as Select, Radio, and Checkbox
*
* @param config 自定义选项
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* @param config Custom options | 自定义选项
*/
options<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumOption<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
options<FK, FV>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[];
/**
* 生成一个符合AntDesignPro规范的枚举集合对象。
* **EN:** Generate an object that meets the AntDesignPro specification for the enumeration set
*
* 数据结构为:
* The data structure is: `{ 0: { text: "Sunday" }, 1: { text: "Monday" } }`
*
* @example
* // 对象的`key`为枚举项的值,`value`为枚举项的label名称
* {
* 0: { text: "星期日" },
* 1: { text: "星期一" },
* };
* **CN:** 生成一个符合AntDesignPro规范的枚举集合对象。
*
* 数据结构为:`{ 0: { text: "Sunday" }, 1: { text: "Monday" } }`
*
* @see https://procomponents.ant.design/components/schema#valueenum-1

@@ -94,12 +159,10 @@ * @see https://procomponents.ant.design/components/field-set#proformselect

/**
* 生成一个filters数组,可以直接传递给AntDesign Table组件Column的filters属性,作为列的筛选项
* **EN:** Generate a data source that meets the specification of the column filter function of the AntDesign Table component
*
* 数据结构为:
* The data structure is: `[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]`
*
* @example
* [
* { value: 0, text: "星期日" },
* { value: 1, text: "星期一" },
* ]
* **CN:** 为AntDesign Table组件的列筛选功能生成符合规范的数据源
*
* 数据结构为:`[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]`
*
* @see https://ant.design/components/table-cn#components-table-demo-head

@@ -110,4 +173,17 @@ * @see https://ant.design/components/table-cn#column

/**
* 获取枚举集合的初始化对象
* @return {T} 初始化对象集合
* **EN:** Generate a data source that meets the specification of the AntDesign Menu, Dropdown and other components
*
* The data structure is: `[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]`
*
* **CN:** 为 AntDesign Menu、Dropdown 等组件生成符合规范的数据源
*
* 数据结构为:`[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]`
*/
menus(): MenuItemOption<V>[];
/**
* **EN:** Get the enumeration item by key or value
*
* **CN:** 获取枚举集合的初始化对象
*
* @return {T} Enum collection initialization object | 初始化对象集合
* @memberof IEnumValues

@@ -117,4 +193,7 @@ */

/**
* 获取某个枚举项的原始初始化对象。如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
* @param keyOrValue 枚举key或value
* **EN:** Get the original initialization object of a certain enumeration item. If custom fields are added to the enumeration item, you can use this method to get them.
*
* **CN:** 获取某个枚举项的原始初始化对象。如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
*
* @param keyOrValue Enum key or value | 枚举key或value
*/

@@ -124,4 +203,8 @@ raw(keyOrValue: V | K): T[K];

/**
* 所有枚举值的数据类型
* **EN:** The data type of all enumeration values
*
* 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* **CN:** 所有枚举值的数据类型
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用

@@ -131,15 +214,18 @@ *

*
* // 声明变量的类型
* // Declare the type of the variable | 声明变量的类型
* const week: typeof Week.valueType = Week.Monday; // 0
*
* // 声明类型字段
* // Declare type field | 声明类型字段
* type Props = {
* week: typeof Week.valueType // 0 | 1
* };
* // 使用valueType类型可以更准确的限定取值范围,比使用number、string这种宽泛的数据类型更好
*/
valueType: V;
/**
* 所有枚举key的数据类型
* **EN:** The data type of all enumeration keys
*
* 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* **CN:** 所有枚举key的数据类型
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用

@@ -149,18 +235,19 @@ *

*
* // 声明变量的类型
* // Declare the type of the variable | 声明变量的类型
* const weekName: typeof Week.keyType = "Sunday"; // "Sunday" | "Monday"
*
* // 声明类型字段
* // Declare type field | 声明类型字段
* type Props = {
* weekName: typeof Week.keyType // "Sunday" | "Monday"
* };
* // 使用keyType类型可以更准确的限定取值范围,比使用string这种宽泛的数据类型更好
*/
keyType: K;
/**
* 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
* **EN:** The type of the original initialization object of the enumeration item. If custom fields are added to the enumeration item, you can use this method to get them.
*
* **CN:** 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
*/
rawType: T[K];
}
export declare type EnumInit<K extends keyof any = string, V extends EnumValue = EnumValue> = NumberEnumInit<K> | StringEnumInit<K> | StandardEnumInit<K, V> | ValueOnlyEnumInit<K, V> | LabelOnlyEnumInit<K> | CompactEnumInit<K> | OmitEnumInit<K>;
export declare type EnumInit<K extends keyof any = string, V extends EnumValue = EnumValue> = NumberEnumInit<K> | StringEnumInit<K> | StandardEnumInit<K, V> | ValueOnlyEnumInit<K, V> | LabelOnlyEnumInit<K> | CompactEnumInit<K> | AutoIncrementedEnumInit<K>;
export declare type NumberEnumInit<K extends keyof any> = Record<K, number>;

@@ -172,3 +259,5 @@ export declare type StringEnumInit<K extends keyof any> = Record<K, string>;

export declare type CompactEnumInit<K extends keyof any> = Record<K, CompactEnumItemInit>;
export declare type OmitEnumInit<K extends keyof any> = Record<K, undefined>;
export declare type AutoIncrementedEnumInit<K extends keyof any> = Record<K, undefined>;
/** @deprecated Use `AutoIncrementedEnumInit` instead */
export declare type OmitEnumInit<K extends keyof any> = AutoIncrementedEnumInit<K>;
export declare type EnumItemInit<V extends EnumValue = EnumValue> = EnumValue | StandardEnumItemInit<V> | ValueOnlyEnumItemInit<V> | LabelOnlyEnumItemInit | CompactEnumItemInit | undefined;

@@ -186,72 +275,84 @@ export declare type StandardEnumItemInit<V extends EnumValue> = {

export declare type CompactEnumItemInit = Record<string, never>;
/**
* 由枚举项生成的作为Select组件数据源的数据结构
*/
export declare type EnumOption<K, V> = {
/**
* 选项的值
*/
/** Data structure of ant-design Select options */
export declare type EnumItemOptionData<K, V> = {
/** Option value */
value: V;
/**
* 选项的显示文本
*/
/** Option label */
label: string;
/**
* 选项的key,默认使用`value`
*/
/** Option key, default is `value` */
key: K;
};
/**
* Table列筛选项的数据结构
*/
/** Data structure of column filter items of ant-design Table */
export declare type ColumnFilterItem<V> = {
/**
* 显示文本
*/
/** Display name */
text: string;
/**
* 值
*/
/** Value */
value: V;
};
/**
* 枚举值的类型,支持number、string、symbol
*/
/** Data structure of ant-design Menu items */
export declare type MenuItemOption<V> = {
/** Key of menu item */
key: V;
/** Menu item text */
label: string;
};
/** Enum value type, support number, string, symbol */
export declare type EnumValue = keyof any;
/**
* 获取枚举初始化对象中key的类型
*/
/** Enum key collection */
export declare type EnumKey<T> = keyof T;
/**
* options方法的更多选项
*/
/** More options for the options method */
export declare type OptionsConfig = object;
export declare type BooleanFirstOptionConfig<B extends boolean> = {
export declare type BooleanFirstOptionConfig<V> = {
/**
* 在头部添加一个默认选项。
* **EN:** Add a default option at the top
* - `true`: the option uses the default value, `value` is `''`, `label` is `'All'`;
* - `false`: the default option is not added;
*
* 如果为`true`,则选项使用默认值,`value`为`''`,`label`为`'全部'`;
* 如果为`false`,则不添加默认选项;
* **CN:** 在头部添加一个默认选项
*
* - `true`:选项使用默认值,`value`为`''`,`label`为`'全部'`
* - `false`:不添加默认选项
*
* @default false
*/
firstOption?: B;
firstOption: boolean;
/**
* **EN:** Default option value, default is `''`
*
* **CN:** 默认选项的值,默认为`''`
*
* @default ''
*/
firstOptionValue?: V;
/**
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called
*
* **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法
*/
firstOptionLabel?: string;
};
export declare type ObjectFirstOptionConfig<K, V> = {
/**
* 首行选项的配置
* **EN:** Configuration of the first option
*
* **CN:** 首行选项的配置
*/
firstOption?: EnumOptionConfig<K, V>;
/**
* **EN:** Add a default option at the top
*
* **CN:** 默认选项的值,默认为`''`
*/
firstOptionValue?: never;
/**
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called
*
* **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法
*/
firstOptionLabel?: never;
};
export declare type EnumOptionConfig<K, V> = Omit<EnumOption<K, V>, 'key'> & Partial<Pick<EnumOption<K, V>, 'key'>>;
/**
* 从枚举集合或枚举项的初始化对象推断value类型
*/
/**
* 从枚举项的初始化对象推断value类型
*/
export declare type ValueTypeFromSingleInit<T, FB = string> = T extends EnumValue ? T : T extends StandardEnumItemInit<infer V> ? V : T extends ValueOnlyEnumItemInit<infer V> ? V : T extends LabelOnlyEnumItemInit ? FB : T extends CompactEnumItemInit ? FB : T extends undefined ? FB : never;
/**
* 从枚举集合初始化对象推断value类型
*/
export declare type ValueTypeFromEnumInit<T, K extends EnumKey<T> = EnumKey<T>> = T extends NumberEnumInit<K> ? number : T extends StringEnumInit<K> ? string : T extends StandardEnumInit<K, infer V> ? V : T extends ValueOnlyEnumInit<K, infer V> ? V : T extends LabelOnlyEnumInit<K> ? K : T extends CompactEnumInit<K> ? K : T extends OmitEnumInit<K> ? K : K;
export declare type EnumOptionConfig<K, V> = Omit<EnumItemOptionData<K, V>, 'key'> & Partial<Pick<EnumItemOptionData<K, V>, 'key'>>;
/** Infer the value type from the initialization object of the enumeration item */
export declare type ValueTypeFromSingleInit<T, Key = string, Fallback = Key> = T extends EnumValue ? T : T extends StandardEnumItemInit<infer V> ? V : T extends ValueOnlyEnumItemInit<infer V> ? V : T extends LabelOnlyEnumItemInit ? Key : T extends CompactEnumItemInit ? Key : T extends undefined ? Fallback : never;
/** Infer the value type from the initialization object of the enumeration collection */
export declare type ValueTypeFromEnumInit<T, K extends EnumKey<T> = EnumKey<T>> = T extends NumberEnumInit<K> ? number : T extends StringEnumInit<K> ? string : T extends StandardEnumInit<K, infer V> ? V : T extends ValueOnlyEnumInit<K, infer V> ? V : T extends LabelOnlyEnumInit<K> ? K : T extends CompactEnumInit<K> ? K : T extends AutoIncrementedEnumInit<K> ? K : K;
{
"name": "enum-plus",
"version": "1.0.3",
"description": "A powerful enum library, like typescript enum but more than that",
"version": "2.0.1",
"description": "A drop-in replacement library for enum, tiny and powerful, like native enum but much more than that",
"keywords": [
"enum",
"typescript"
"typescript-library"
],

@@ -18,3 +18,3 @@ "homepage": "https://github.com/shijistar/enum-plus",

"license": "MIT",
"author": "shijistar",
"author": "shijistar@gmail.com",
"main": "lib/index.js",

@@ -21,0 +21,0 @@ "types": "lib/index.d.ts",

@@ -0,26 +1,70 @@

<!-- markdownlint-disable MD009 -->
# enum-plus
An enumeration library similar to typescript's `enum` keyword, but extended with some enhanced features.
[English](./README.md) | [中文](./README.zh-CN.md)
生成一个枚举集合,枚举值支持 `number` 和 `string` 两种类型。
> Like native `enum`, but much better than that!
[![npm version](https://img.shields.io/npm/v/enum-plus.svg)](https://www.npmjs.com/package/enum-plus)
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/enum-plus)](https://bundlephobia.com/result?p=enum-plus)
[![npm downloads](https://img.shields.io/npm/dm/enum-plus.svg)](https://www.npmjs.com/package/enum-plus)
![GitHub License](https://img.shields.io/github/license/shijistar/enum-plus?label=License&color=%23F68F1E)
⬇️ &nbsp;&nbsp; [Introduction](#introduction) | [Features](#features) | [Installation](#installation) | [Enum Definition](#enum-definition) | [API](#api) | [Usage](#usage) | [Localization](#localization) &nbsp;&nbsp;⬇️
## Introduction
`enum-plus` is an enhanced enum library that is fully compatible with the basic usage of native `enum`, while supporting extending display text, binding to UI components, and providing rich extension methods. It is a lightweight, zero-dependency, 100% TypeScript implementation tool that is suitable for a variety of front-end frameworks and supports localization.
After extending the display name of the enum item, it can be used to generate dropdowns, checkboxes, and other components with a single line of code. By using the extension methods of the enum, you can easily traverse the array of enum items, get the display text of a certain enum value, determine whether a value exists, etc. The display text of the enum item supports localization, which can return the corresponding text according to the current language environment, making the display text of the enum item more flexible and more in line with user needs.
What other exciting features are there? Please continue to explore the technical documentation below!
## Features
- Fully compatible with native `enum` usage
- Supports multiple data types such as `number` and `string`
- Support extending display text for enum items>
- Display text supports localization, you can use any internationalization library
- Support converting enum values to display text, making the code more concise
- Enum items support extending any number of custom fields
- Supports binding enums to [AntDesign](https://ant.design/components/overview), [ElementPlus](https://element-plus.org/en-US/component/overview.html), [Material-UI](https://mui.com/material-ui) or any other libraries, in a single line of code
- Zero dependencies, pure native JavaScript, can be applied to any front-end framework
- 100% TypeScript implementation, good support for type inference
- Lightweight (only 2KB+ gzipped)
## Installation
Install using yarn:
Install using npm:
```bash
yarn add enum-plus
npm install enum-plus
```
Or npm:
Install using pnpm:
```bash
npm install enum-plus
pnpm add enum-plus
```
## 枚举定义
Install using bun:
示例 1:number 类型
```bash
bun add enum-plus
```
```typescript
Or using yarn:
```bash
yarn add enum-plus
```
## Enum Definition
Create an enum, enum values support both `number` and `string` types
#### Example 1: Basic usage, almost the same as native enum
```js
import { Enum } from 'enum-plus';

@@ -32,115 +76,317 @@

} as const);
Week.Monday; // 1
```
示例 2:string 类型
#### Example 2: string value type
```typescript
```js
import { Enum } from 'enum-plus';
const Week = Enum({
Sunday: 'Sunday',
Monday: 'Monday',
Sunday: 'Sun',
Monday: 'Mon',
} as const);
Week.Monday; // 'Mon'
```
示例 3(标准写法,推荐):扩展 label 显示文本
#### 👍👍 [Recommended] Example 3 (standard usage): With key, value, and display text
```typescript
```js
import { Enum } from 'enum-plus';
const Week = Enum({
Sunday: { value: 0, label: '星期日' },
Monday: { value: 1, label: '星期一' },
Sunday: { value: 0, label: 'Sunday' }, // this example does not consider localization
Monday: { value: 1, label: 'Monday' }, // this example does not consider localization
} as const);
Week.Monday; // 1
Week.label(1); // Monday (this is display text, not key)
```
示例 4(推荐):省略 label,value 的默认值为 key
#### 👍 Example 4: Omit the value field, automatically degrade to use the key field
```typescript
```js
import { Enum } from 'enum-plus';
const Week = Enum({
Sunday: { label: '星期日' }, // 等价于 { value: "Sunday", label: '星期日' }
Monday: { label: '星期一' }, // 等价于 { value: "Monday", label: '星期一' }
Sunday: { label: 'Sunday' }, // Equivalent to { value: "Sunday", label: 'Sunday' }
Monday: { label: 'Monday' }, // Equivalent to { value: "Monday", label: 'Monday' }
} as const);
Week.Monday; // 'Monday'
Week.label('Monday'); // Monday
```
示例 5:与示例 2 等价,value 的默认值为 key
#### Example 5: Create an enum dynamically
```typescript
````js
Sometimes we need to create an enum dynamically using data returned by an api, in this case, we can use an array to initialize the enum
```js
import { Enum } from 'enum-plus';
const Week = Enum({
Sunday: undefined, // 等价于 { value: "Sunday" }
Monday: undefined, // 等价于 { value: "Sunday" }
} as const);
const petTypes = await getPetsData();
// [ { id: 1, code: 'dog', name: 'Dog' },
// { id: 2, code: 'cat', name: 'Cat' },
// { id: 3, code: 'rabbit', name: 'Rabbit' } ];
const PetTypes = Enum(petTypes, {
getValue: 'id',
getLabel: 'name',
getKey: 'code', // Optional, if omitted, value is used as Key as fallback
});
Week.values; // Output is:
// [ { value: 1, label: 'Dog', key: 'dog' },
// { value: 2, label: 'Cat', key: 'cat' },
// { value: 3, label: 'Rabbit', key: 'rabbit' } ]
````
## API
### Pick enum value
`Enum.XXX`
Like native `enum`, pick a value of an enum item from the enum type
```js
Week.Monday; // 1
Week.Sunday; // 0
```
示例 6:扩展自定义字段
---
```typescript
import { Enum } from 'enum-plus';
### values
`{value, label, key, raw}[]`
Get a read-only array containing all enum items, which can be easily traversed. Since it conforms to the data specification of [AntDesign](https://github.com/ant-design/ant-design) components, it supports one-click conversion of enums into components such as dropdowns and checkboxes, with just a single line of code. For more details, please refer to the examples below.
---
### keys
`string[]`
Get a read-only array containing all `Key` of the enum items
---
### label
<sup>**_[Function]_**</sup> `label(keyOrValue?: string | number): string | undefined`
Get the display text of an enum item based on a certain enum value or Key. If localization is setup, the localized text will be returned.
```js
Week.label(1); // Monday
Week.label('Monday'); // Monday (this is label, not key)
```
---
### key
<sup>**_[Function]_**</sup> `key(value?: string | number): string | undefined`
Get the Key of an enum item based on the enum value, if the Key is not found, return `undefined`.
```js
Week.key(1); // Monday (this is key, not label)
```
---
### has
<sup>**_[Function]_**</sup> `has(keyOrValue?: string | number): boolean`
Determine whether a certain enum item (value or Key) exists
```js
Week.has(1); // true
Week.has('Sunday'); // true
Week.has(9); // false
Week.has('Birthday'); // false
```
---
### options
<sup>**_[Function]_**</sup> `options(config?: OptionsConfig): {value, label}[]`
`options` is similar to `values`, both return an array containing all enum items. The difference is that the elements returned by `options` only contain the `label` and `value` fields. At the same time, the `options` method supports inserting a default element at the beginning of the array, which is generally used for the default option of components such as dropdowns, representing all, none, or unlimited, etc., of course, you can also customize this default option
---
### valuesEnum
<sup>**_[Function]_**</sup> `valuesEnum(): Record<V, { text: string }>`
Generate an enum collection object that conforms to the [AntDesignPro](https://procomponents.ant.design/en-US/components/schema) specification, which can be passed to components like `ProFormField`, `ProTable`
The data format is:
```js
{
0: { text: 'Sunday' },
1: { text: 'Monday' },
}
```
---
### filters
<sup>**_[Function]_**</sup> `filters(): { text, value }[]`
Generate an array of filters that can be passed directly to the `Column.filters` of the [AntDesign](https://ant.design/components/table#table-demo-head) Table component as a list of filtered items for the column, displaying a dropdown filter box in the table header to filter table data
The data format is:
```js
[
{ text: 'Sunday', value: 0 },
{ text: 'Monday', value: 1 },
];
```
---
### raw
<sup>**_[Override^1]_**</sup> `raw(): Record<K, T[K]>`
<br/>
<sup>**_[Override^2]_**</sup> `raw(keyOrValue: V | K): T[K]`
The first overload without parameters returns the initialization object of the enum collection, which is used to initialize the Enum original init object.
The second overload method is used to process a single enum item. Get the original initialization object of the enum item based on the enum value or enum Key, that is, the return value of the first method is part of the return value of the second method. In addition, if additional extension fields are added to the enum item, they can also be obtained in this way
```js
const Week = Enum({
Sunday: { value: 0, label: '星期日', active: true, disabled: false },
Monday: { value: 0, label: '星期日', active: false, disabled: true },
Sunday: { value: 0, label: 'Sunday' },
Monday: { value: 1, label: 'Monday' },
} as const);
// Week.raw('Sunday').active // true
// Week.raw('Monday').disabled // true
Week.raw(); // { Sunday: { value: 0, label: 'Sunday' }, Monday: { value: 1, label: 'Monday' } }
Week.raw(0); // { value: 0, label: 'Sunday' }
Week.raw('Monday'); // { value: 1, label: 'Monday' }
```
## 使用方法
---
直接作为 Select 的数据源
### valueType <sup>**_[Type-ONLY]_**</sup>
```tsx
<Select options={Week.values} />
`value1 | value2 | ...`
In TypeScript, get a union type containing all enum values, used to narrow the data type of variables or component properties, avoid using `number`, `string` and other overly broad types, improve code readability and type safety
```typescript
const weekValue: typeof Week.valueType = 1;
const weeks: typeof Week.valueType[] = [0, 1];
type WeekValues = typeof Week.valueType; // 0 | 1
```
在头部增加默认选项(默认文本为'全部',value 为'')
> Note that this is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception
```tsx
<Select options={Week.options({ firstOption: true })} />
---
### keyType <sup>**_[Type-ONLY]_**</sup>
`key1 | key2 | ...`
Similar to `valueType`, get a union type containing all enum Keys
```typescript
const weekKey: typeof Week.keyType = 'Monday';
const weekKeys: typeof Week.keyType[] = ['Sunday', 'Monday'];
type WeekKeys = typeof Week.keyType; // 'Sunday' | 'Monday'
```
在头部增加自定义选项
> Note that this is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception
```tsx
<Select options={Week.options({ firstOption: { value: 0, label: '不限' } as const })} />
---
### rawType <sup>**_[Type-ONLY]_**</sup>
`{ value: V, label: string, [...] }`
Similar to the `raw` method without parameters, but the `raw` method supports runtime calls, while `rawType` can only be used to constrain types
> Note that this is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception
---
## Usage
#### Access enum items, consistent with native enum usage
```js
const Week = Enum({
Sunday: { value: 0, label: 'Sunday' },
Monday: { value: 1, label: 'Monday' },
} as const);
Week.Monday; // 1
Week.Sunday; // 0
```
使用 AntDesignPro
---
```tsx
<ProFormSelect valueEnum={Week.valuesEnum()} />
#### Keep Jsdoc comments, more friendly code hints
In the code editor, hover over an enum item to display detailed Jsdoc comments about the enum item, without having to go back to the enum definition. In addition, when entering `HttpCodes.`, the editor will automatically prompt the enum item list, switch enum items through the up and down keys, and also display detailed information
```js
const HttpCodes = Enum({
/** Code400: Bad Request. The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing) */
E400: { value: 400, label: 'Bad Request' },
/** Code400: Unauthorized. The client must authenticate itself to get the requested response */
E401: { value: 401, label: 'Unauthorized' },
/** Code403: Forbidden. The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the server knows the client's identity */
E403: { value: 0, label: 'Forbidden' },
/** Code404: Not Found. The server can not find the requested resource. In a browser, this means the URL is not recognized */
E404: { value: 1, label: 'Not Found' },
} as const);
HttpCodes.E404; // Hover over E404 to display Jsdoc documentation
```
支持所有数组遍历,但不支持任何形式的修改
> In the above code example, the interpretation of Http status codes is based on [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
```typescript
Week.values.length; // 2
Week.values.map((item) => item.value); // [0, 1],可遍历
Week.values.forEach((item) => {}); // 可遍历
for (let item of Week.values) {
} // 可遍历
Week.values.push({ value: 2, label: '星期二' }); // ❌ 不可修改
Week.values[0].label = 'foo'; // ❌ 不可修改
---
#### Get array of enum items
```js
Week.values; // Output is:
// [
// { value: 0, label: 'Sunday', key: 'Sunday', raw: { value: 0, label: 'Sunday' } },
// { value: 1, label: 'Monday', key: 'Monday', raw: { value: 1, label: 'Monday' } },
// ]
```
获取第一个枚举项的值
---
```typescript
#### Get the value of the first enum item
```js
Week.values[0].value; // 0
```
判断某个值是否有效?
---
```typescript
#### Determine whether a certain value is included in the enum
```js
Week.values.some(item => item.value === 1); // true
if(1 instance of Week) // true,更简单的用法
Week.has(1); // true
1 instance of Week; // true
```
`instanceof` 操作符
---
```typescript
#### `instanceof` operator
```js
1 instance of Week // true

@@ -151,41 +397,249 @@ "1" instance of Week // true

获取某个值的显示文本
---
```typescript
Week.label(1); // 星期一,
Week.label(Week.Monday); // 星期一
Week.label('Monday'); // 星期一
#### Support traversing the array of enum items, but not modifying
```js
Week.values.length; // 2
Week.values.map((item) => item.value); // [0, 1], ✅ Traversable
Week.values.forEach((item) => {}); // ✅ Traversable
for (let item of Week.values) {
// ✅ Traversable
}
Week.values.push({ value: 2, label: 'Tuesday' }); // ❌ Not modifiable
Week.values.splice(0, 1); // ❌ Not modifiable
Week.values[0].label = 'foo'; // ❌ Not modifiable
```
获取某个枚举项的 key
---
```typescript
Week.key(1); // 'Monday'
Week.key(Week.Monday); // 'Monday'
Week.key(9); // undefined
#### Get the display text of a certain value
```js
Week.label(1); // Monday
Week.label(Week.Monday); // Monday
Week.label('Monday'); // Monday
```
两个枚举合并(或者扩展某个枚举)
---
```typescript
#### Get the key of a certain enum item
```js
Week.key(1); // 'Monday', this is label, not key
Week.key(Week.Monday); // 'Monday', this is label, not key
Week.key(9); // undefined, not found
```
---
#### Add custom fields
```js
const Week = Enum({
Sunday: { value: 0, label: 'Sunday', active: true, disabled: false },
Monday: { value: 1, label: 'Monday', active: false, disabled: true },
} as const);
Week.raw(0).active // true
Week.raw(Week.Sunday).active // true
Week.raw('Sunday').active // true
```
---
#### Optimization and syntactic sugars for [AntDesign](https://github.com/ant-design/ant-design)
- `values` as the data source for components like `Select`, `Checkbox`
```jsx
import { Select } from 'antd';
<Select options={Week.values} />;
```
- `options` method is similar to `values`, but can add a default option at the top
```jsx
<Select options={Week.options({ firstOption: true })} />
// [
// { value: '', label: 'All' },
// { value: 0, label: 'Sunday' },
// { value: 1, label: 'Monday' }
// ]
// Add custom option at the top
<Select options={Week.options({ firstOption: { value: 0, label: 'Unlimited' } })} />
```
- `menus` method can generate data sources for [AntDesign](https://github.com/ant-design/ant-design) `Menu`, `Dropdown` components, the format is: `{ key: number|string, label: string }[]`
```jsx
import { Menu } from 'antd';
<Menu items={Week.menus()} />;
```
- `filters` method can generate data sources for the `Column filters` feature of the [AntDesign](https://github.com/ant-design/ant-design) `Table` component, the format is: `{ text: string, value: number|string }[]`
```jsx
import { Table } from 'antd';
const columns = [
{
title: 'week',
dataIndex: 'week',
filters: Week.filters(),
},
];
// Add column filter at table header
<Table columns={columns} />;
```
- `valuesEnum` method can generate data sources for `ProFormFields`, `ProTable` components of [AntDesignPro](https://github.com/ant-design/pro-components), which is a data structure similar to `Map`, the format is: `{ [key: number|string]: { text: string } }`
```jsx
import { ProTable } from '@ant-design/pro-components';
<ProFormSelect valueEnum={Week.valuesEnum()} />;
```
---
#### Merge two enums (or extend an enum)
```js
const myWeek = Enum({
...Week.raw(),
Friday: 5,
Saturday: 6,
};
...Week.raw(),
Friday: { value: 5, label: 'Friday' },
Saturday: { value: 6, label: 'Saturday' },
});
```
给枚举字段声明类型,【强烈建议】
---
#### Narrowing data types with enum value sequences &nbsp;&nbsp;<sup>_[TypeScript ONLY]_</sup>
By using the `valueType` type constraint, you can narrow the field type from the broad `number` or `string` type to a limited sequence of enum values, which not only reduces the possibility of erroneous assignments, but also improves the readability of the code.
```typescript
type Props = {
week: typeof Week.valueType; // 0 | 1
weekName: typeof Week.keyType; // 'Sunday' | 'Monday'
const weekValue: number = 8; // 👎 Any number can be assigned to the week enum, even if it is wrong
const weekName: string = 'Birthday'; // 👎 Any string can be assigned to the week enum, even if it is wrong
const badWeekValue: typeof Week.valueType = 8; // ❌ Type error, 8 is not a valid week enum value
const badWeekName: typeof Week.keyType = 'Birthday'; // ❌ Type error, 'Birthday' is not a valid week enum name
const goodWeekValue: typeof Week.valueType = 1; // ✅ Type correct, 1 is a valid week enum value
const goodWeekName: typeof Week.keyType = 'Monday'; // ✅ Type correct, 'Monday' is a valid week enum name
type FooProps = {
value?: typeof Week.valueType; // 👍 Component property type constraint, prevent erroneous assignment, and also prompt which values are valid
names?: typeof Week.keyType[]; // 👍 Component property type constraint, prevent erroneous assignment, and also prompt which values are valid
};
```
使用 valueType 类型可以更准确的限定取值范围,比使用 number、string 这种宽泛的数据类型更好
---
😟 命名冲突?
#### 😟 Naming conflict?
如果 `Week` 的 `key`、`label`、`options` 方法与某个枚举的 key 重名了,则这些方法会被覆盖掉。不用担心,在 `Week.values` 下仍然可以访问到这些方法
Here are some edge cases for using enums. As seen from the above examples, we can quickly access enum items through `Week.XXX`, but what if the key of an enum item conflicts with the name of an enum method?
We know that there are methods like `label`, `key`, `options` on the enum type. If they have the same name as an enum item, the enum item's value has a higher priority and will override these methods. But don't worry, you can access them under `values`. Please refer to the code example below:
```js
const Week = Enum({
foo: { value: 1 },
bar: { value: 2 },
keys: { value: 3 }, // Naming conflict
label: { value: 4 }, // Naming conflict
} as const);
Week.keys; // 3, enum item has higher priority and will override the method
Week.label; // 4, enum item has higher priority and will override the method
// You can access these methods through values 🙂
Week.values.keys // ['foo', 'bar', 'keys', 'label']
Week.values.label(1); // 'foo'
```
An even more extreme case, what if `values` conflicts with the name of an enum item? Don't worry, you can still access the `values` array through an alias field. Refer to the example below:
```js
import { VALUES } from 'enum-plus';
const Week = Enum({
foo: { value: 1 },
bar: { value: 2 },
values: { value: 3 }, // Naming conflict
} as const);
Week.values; // 3, enum item has higher priority and will override values
Week[VALUES]; // VALUES is an alias Symbol
// [
// { value: 1, key: 'foo', label: 'foo' },
// { value: 2, key: 'bar', label: 'bar' },
// { value: 3, key: 'values', label: 'values' }
// ]
// Equivalent to the original Week.values 🙂
```
---
## Localization
`enum-plus` does not provide internationalization functionality itself, but supports custom localization methods through the `localize` optional parameter. You can declare a localization method in your project to convert the input enum `label` into the corresponding localized text. You need to maintain the language yourself and return the corresponding text for the current language in the `localize` method. If possible, it is strongly recommended that you use a popular internationalization library, such as `i18next`
Here is a simple example, but the first method is not a good practice because it is not flexible enough, and is only used to demonstrate basic functionality
```tsx
import { Enum } from 'enum-plus';
import i18next from 'i18next';
import Localize from './Localize';
let lang = 'zh-CN';
const setLang = (l: string) => {
lang = l;
};
// ❌ This is not a good example, just to demonstrate basic functionality, please use other methods later
const sillyLocalize = (content: string) => {
if (lang === 'zh-CN') {
switch (content) {
case 'week.sunday':
return '星期日';
case 'week.monday':
return '星期一';
default:
return content;
}
} else {
switch (content) {
case 'week.sunday':
return 'Sunday';
case 'week.monday':
return 'Monday';
default:
return content;
}
}
};
// ✅ Recommended to use i18next or other internationalization libraries
const i18nLocalize = (content: string | undefined) => i18next.t(content);
// ✅ Or encapsulate it into a basic component
const componentLocalize = (content: string | undefined) => <Localize value={content} />;
const Week = Enum(
{
Sunday: { value: 0, label: 'week.sunday' },
Monday: { value: 1, label: 'week.monday' },
} as const,
{
localize: sillyLocalize,
// localize: i18nLocalize, // 👍 Recommended to use i18n
// localize: componentLocalize, // 👍 Recommended to use component
}
);
setLang('zh-CN');
Week.label(1); // 星期一
setLang('en-US');
Week.label(1); // Monday
```
Setting each enum type individually can be cumbersome. You can also set localization globally using the `Enum.localize` method. If both static settings and initialization options are provided, the initialization options take precedence.
```js
Enum.localize = sillyLocalize;
```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc