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
11
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.0-alpha.2

README.zh-CN.html

19

CHANGELOG.md

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

<!-- markdownlint-disable MD009 -->
# enum-plus Changelog
## 2.0.0
2025-1-23
### Features
- 🔥 Support for localization of enum text
- The `Enum` method now accepts a `localize` option that can be used to localize the enum text
- You can also set the `Enum.localize` 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 @@

7

es/enum-collection.d.ts

@@ -1,2 +0,2 @@

import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumOption, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem } from './types';
import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumOption, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem, EnumItemOptions, MenuItemOption } from './types';
import { EnumValuesArray } from './enum-values';

@@ -32,3 +32,3 @@ /**

readonly keys: K[];
constructor(init?: T);
constructor(init?: T, options?: EnumItemOptions);
key(value?: string | number): K | undefined;

@@ -38,3 +38,3 @@ label(keyOrValue?: string | number): string | undefined;

options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): 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)>[];

@@ -44,2 +44,3 @@ valuesEnum(): Record<V, {

}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -46,0 +47,0 @@ raw(): T;

@@ -31,3 +31,3 @@ import { KEYS, VALUES } from './index';

export class EnumCollectionClass {
constructor(init = {}) {
constructor(init = {}, options) {
const keys = Object.keys(init); // 定义枚举项,可以通过key直接访问,例如 Week.Monday

@@ -45,3 +45,3 @@ keys.forEach((key) => {

const { value, label } = parseEnumItem(init[key], key);
return new EnumItemClass(key, value, label, init[key]);
return new EnumItemClass(key, value, label, init[key], options).readonly();
}));

@@ -56,6 +56,6 @@ // @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突

this[Symbol.hasInstance] = (instance) => {
// value故意使用==,支持数字和字符创格式的value
// value故意使用 ==,支持数字和字符创格式的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);
};

@@ -82,2 +82,5 @@ Object.freeze(this);

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

@@ -84,0 +87,0 @@ return this.values.filters();

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

import type { EnumItemInit, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
import type { EnumItemInit, EnumItemOptions, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
/**
* 枚举项类
* @template V 枚举值的类型
* @template K 枚举项的Key
* @template T 枚举项的初始化对象
*/
export declare class EnumItemClass<T extends EnumItemInit<V>, K extends EnumKey<any> = string, V extends EnumValue = ValueTypeFromSingleInit<T, K>> {
/**
* 枚举项的值
*/
#private;
/** 枚举项的值 */
readonly value: V;
/**
* 枚举项的显示名称
*/
/** 枚举项的显示名称 */
readonly label: string;
/**
* 枚举项的Key
*/
/** 枚举项的Key */
readonly key: K;
/** 原始初始化对象 */
readonly raw: T;
/**
* 原始初始化对象
* 实例化一个枚举项
* @param key 枚举项的Key
* @param value 枚举值
* @param label 枚举项的显示名称
* @param raw 原始初始化对象
* @param 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 '.';
/**
* 枚举项类
* @template V 枚举值的类型
* @template K 枚举项的Key
* @template T 枚举项的初始化对象
*/
export class EnumItemClass {
constructor(key, value, label, raw) {
/**
* 实例化一个枚举项
* @param key 枚举项的Key
* @param value 枚举值
* @param label 枚举项的显示名称
* @param raw 原始初始化对象
* @param 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 __classPrivateFieldGet(target, _EnumItemClass_localize, "f").call(target, target.label);
}
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,2 +61,8 @@ this.value = value;

this.raw = raw;
__classPrivateFieldSet(this, _EnumItemClass_localize, (content) => {
if (typeof localize === 'function') {
return localize(content);
}
return content;
}, "f");
// 重写一些系统方法,不写在class声明上是因为会在ts中多一个Symbol的字段,开发时没必要看到

@@ -14,16 +74,20 @@ // @ts-ignore: 重写Object.toString方法,显示类型更友好

if (hint === 'number') {
// +value
return this.value;
// Number(value), +value
return this.valueOf();
}
else if (hint === 'string') {
// `${value}`
return this.label;
// String(value), `${value}`
return this.toString();
}
// value + ''
return this.label;
// '' + 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;
}

@@ -37,2 +101,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, EnumOption, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types';
/**

@@ -26,3 +26,3 @@ * 枚举项集合数组

options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): 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)>[];

@@ -32,2 +32,3 @@ valuesEnum(): Record<V, {

}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -34,0 +35,0 @@ raw(): T;

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

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

@@ -57,7 +57,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,

@@ -79,2 +81,5 @@ ];

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

@@ -81,0 +86,0 @@ return this.map(({ value, label }) => ({ text: label, value }));

@@ -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 +35,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
*
* 本来可以直接使用`EnumClass`, 但是TS不允许`class`中自定义索引访问器,只能使用`type`
* 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
*
* EN: Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you can only use `type`
*
* CN: 数组的类型声明
*
* 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> & {

@@ -16,5 +56,9 @@ [key in K]: ValueTypeFromSingleInit<T[key], key>;

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

@@ -28,5 +72,9 @@ values: EnumItemClass<T[K], K, V>[] & IEnumValues<T, K, V>;

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

@@ -36,52 +84,69 @@ keys: K[];

/**
* 枚举项集合接口,不包含从数组集成的成员
* 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
*
* EN: The data format is: `[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*
* CN: 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* CN: 数据格式为:`[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*/
options(): EnumOption<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>): EnumOption<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>): EnumOption<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
*
* 数据结构为:
* EN: The data structure is: `{ 0: { text: "Sunday" }, 1: { text: "Monday" } }`
*
* @example
* // 对象的`key`为枚举项的值,`value`为枚举项的label名称
* {
* 0: { text: "星期日" },
* 1: { text: "星期一" },
* };
* CN: 生成一个符合AntDesignPro规范的枚举集合对象。
*
* CN: 数据结构为:`{ 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
*
* 数据结构为:
* EN: The data structure is: `[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]`
*
* @example
* [
* { value: 0, text: "星期日" },
* { value: 1, text: "星期一" },
* ]
* CN: 为AntDesign Table组件的列筛选功能生成符合规范的数据源
*
* CN: 数据结构为:`[{ 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
*
* EN: The data structure is: `[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]`
*
* CN: 为 AntDesign Menu、Dropdown 等组件生成符合规范的数据源
*
* CN: 数据结构为:`[{ 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,37 +203,45 @@ raw(keyOrValue: V | K): T[K];

/**
* 所有枚举值的数据类型
* EN: The data type of all enumeration values
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用
* EN: 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* CN: 所有枚举值的数据类型
*
* CN: 📣 注意:仅可作为类型声明使用,不可在运行时调用
*
* @example
*
* // 声明变量的类型
* // 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
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用
* EN: 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* CN: 所有枚举key的数据类型
*
* CN: 📣 注意:仅可作为类型声明使用,不可在运行时调用
*
* @example
*
* // 声明变量的类型
* // 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: 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
*/

@@ -183,45 +270,32 @@ rawType: T[K];

export declare type CompactEnumItemInit = Record<string, never>;
/**
* 由枚举项生成的作为Select组件数据源的数据结构
*/
/** 由枚举项生成的作为Select组件数据源的数据结构 */
export declare type EnumOption<K, V> = {
/**
* 选项的值
*/
/** 选项的值 */
value: V;
/**
* 选项的显示文本
*/
/** 选项的显示文本 */
label: string;
/**
* 选项的key,默认使用`value`
*/
/** 选项的key,默认使用`value` */
key: K;
};
/**
* Table列筛选项的数据结构
*/
/** Table列筛选项的数据结构 */
export declare type ColumnFilterItem<V> = {
/**
* 显示文本
*/
/** 显示文本 */
text: string;
/**
* 值
*/
/** 值 */
value: V;
};
/**
* 枚举值的类型,支持number、string、symbol
*/
/** 用于生成菜单的数据结构 */
export declare type MenuItemOption<V> = {
/** 枚举值 */
key: V;
/** 显示文本 */
label: string;
};
/** 枚举值的类型,支持number、string、symbol */
export declare type EnumValue = keyof any;
/**
* 获取枚举初始化对象中key的类型
*/
/** 获取枚举初始化对象中key的类型 */
export declare type EnumKey<T> = keyof T;
/**
* options方法的更多选项
*/
/** options方法的更多选项 */
export declare type OptionsConfig = object;
export declare type BooleanFirstOptionConfig<B extends boolean> = {
export declare type BooleanFirstOptionConfig<V> = {
/**

@@ -235,21 +309,21 @@ * 在头部添加一个默认选项。

*/
firstOption?: B;
firstOption: boolean;
/** 默认选项的值,默认为`''` */
firstOptionValue?: V;
/** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 */
firstOptionLabel?: string;
};
export declare type ObjectFirstOptionConfig<K, V> = {
/**
* 首行选项的配置
*/
/** 首行选项的配置 */
firstOption?: EnumOptionConfig<K, V>;
/** 默认选项的值,默认为`''` */
firstOptionValue?: never;
/** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 */
firstOptionLabel?: never;
};
export declare type EnumOptionConfig<K, V> = Omit<EnumOption<K, V>, 'key'> & Partial<Pick<EnumOption<K, V>, 'key'>>;
/**
* 从枚举集合或枚举项的初始化对象推断value类型
*/
/**
* 从枚举项的初始化对象推断value类型
*/
/** 从枚举集合或枚举项的初始化对象推断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类型
*/
/** 从枚举集合初始化对象推断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 {};
// eslint-disable-next-line @typescript-eslint/ban-types
//# sourceMappingURL=types.js.map

@@ -1,2 +0,2 @@

import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumOption, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem } from './types';
import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumOption, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem, EnumItemOptions, MenuItemOption } from './types';
import { EnumValuesArray } from './enum-values';

@@ -32,3 +32,3 @@ /**

readonly keys: K[];
constructor(init?: T);
constructor(init?: T, options?: EnumItemOptions);
key(value?: string | number): K | undefined;

@@ -38,3 +38,3 @@ label(keyOrValue?: string | number): string | undefined;

options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): 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)>[];

@@ -44,2 +44,3 @@ valuesEnum(): Record<V, {

}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -46,0 +47,0 @@ raw(): T;

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

class EnumCollectionClass {
constructor(init = {}) {
constructor(init = {}, options) {
const keys = Object.keys(init); // 定义枚举项,可以通过key直接访问,例如 Week.Monday

@@ -48,3 +48,3 @@ keys.forEach((key) => {

const { value, label } = parseEnumItem(init[key], key);
return new enum_item_1.EnumItemClass(key, value, label, init[key]);
return new enum_item_1.EnumItemClass(key, value, label, init[key], options).readonly();
}));

@@ -59,6 +59,6 @@ // @ts-ignore: 如果init包含values,则使用 VALUES 来避免命名冲突

this[Symbol.hasInstance] = (instance) => {
// value故意使用==,支持数字和字符创格式的value
// value故意使用 ==,支持数字和字符创格式的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);
};

@@ -85,2 +85,5 @@ Object.freeze(this);

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

@@ -87,0 +90,0 @@ return this.values.filters();

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

import type { EnumItemInit, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
import type { EnumItemInit, EnumItemOptions, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types';
/**
* 枚举项类
* @template V 枚举值的类型
* @template K 枚举项的Key
* @template T 枚举项的初始化对象
*/
export declare class EnumItemClass<T extends EnumItemInit<V>, K extends EnumKey<any> = string, V extends EnumValue = ValueTypeFromSingleInit<T, K>> {
/**
* 枚举项的值
*/
#private;
/** 枚举项的值 */
readonly value: V;
/**
* 枚举项的显示名称
*/
/** 枚举项的显示名称 */
readonly label: string;
/**
* 枚举项的Key
*/
/** 枚举项的Key */
readonly key: K;
/** 原始初始化对象 */
readonly raw: T;
/**
* 原始初始化对象
* 实例化一个枚举项
* @param key 枚举项的Key
* @param value 枚举值
* @param label 枚举项的显示名称
* @param raw 原始初始化对象
* @param 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(".");
/**
* 枚举项类
* @template V 枚举值的类型
* @template K 枚举项的Key
* @template T 枚举项的初始化对象
*/
class EnumItemClass {
constructor(key, value, label, raw) {
/**
* 实例化一个枚举项
* @param key 枚举项的Key
* @param value 枚举值
* @param label 枚举项的显示名称
* @param raw 原始初始化对象
* @param 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 __classPrivateFieldGet(target, _EnumItemClass_localize, "f").call(target, target.label);
}
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,2 +64,8 @@ this.value = value;

this.raw = raw;
__classPrivateFieldSet(this, _EnumItemClass_localize, (content) => {
if (typeof localize === 'function') {
return localize(content);
}
return content;
}, "f");
// 重写一些系统方法,不写在class声明上是因为会在ts中多一个Symbol的字段,开发时没必要看到

@@ -17,16 +77,20 @@ // @ts-ignore: 重写Object.toString方法,显示类型更友好

if (hint === 'number') {
// +value
return this.value;
// Number(value), +value
return this.valueOf();
}
else if (hint === 'string') {
// `${value}`
return this.label;
// String(value), `${value}`
return this.toString();
}
// value + ''
return this.label;
// '' + 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;
}

@@ -41,2 +105,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, EnumOption, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types';
/**

@@ -26,3 +26,3 @@ * 枚举项集合数组

options(): EnumOption<K, V>[];
options<B extends boolean>(config: OptionsConfig & BooleanFirstOptionConfig<B>): EnumOption<K | '', V | ''>[];
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): 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)>[];

@@ -32,2 +32,3 @@ valuesEnum(): Record<V, {

}>;
menus(): MenuItemOption<V>[];
filters(): ColumnFilterItem<V>[];

@@ -34,0 +35,0 @@ raw(): T;

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

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() {

@@ -84,0 +89,0 @@ return this.map(({ value, label }) => ({ text: label, value }));

@@ -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,33 @@ "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 +54,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
*
* 本来可以直接使用`EnumClass`, 但是TS不允许`class`中自定义索引访问器,只能使用`type`
* 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
*
* EN: Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you can only use `type`
*
* CN: 数组的类型声明
*
* 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> & {

@@ -16,5 +56,9 @@ [key in K]: ValueTypeFromSingleInit<T[key], key>;

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

@@ -28,5 +72,9 @@ values: EnumItemClass<T[K], K, V>[] & IEnumValues<T, K, V>;

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

@@ -36,52 +84,69 @@ keys: K[];

/**
* 枚举项集合接口,不包含从数组集成的成员
* 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
*
* EN: The data format is: `[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*
* CN: 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options`
*
* CN: 数据格式为:`[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]`
*/
options(): EnumOption<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>): EnumOption<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>): EnumOption<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
*
* 数据结构为:
* EN: The data structure is: `{ 0: { text: "Sunday" }, 1: { text: "Monday" } }`
*
* @example
* // 对象的`key`为枚举项的值,`value`为枚举项的label名称
* {
* 0: { text: "星期日" },
* 1: { text: "星期一" },
* };
* CN: 生成一个符合AntDesignPro规范的枚举集合对象。
*
* CN: 数据结构为:`{ 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
*
* 数据结构为:
* EN: The data structure is: `[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]`
*
* @example
* [
* { value: 0, text: "星期日" },
* { value: 1, text: "星期一" },
* ]
* CN: 为AntDesign Table组件的列筛选功能生成符合规范的数据源
*
* CN: 数据结构为:`[{ 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
*
* EN: The data structure is: `[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]`
*
* CN: 为 AntDesign Menu、Dropdown 等组件生成符合规范的数据源
*
* CN: 数据结构为:`[{ 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,37 +203,45 @@ raw(keyOrValue: V | K): T[K];

/**
* 所有枚举值的数据类型
* EN: The data type of all enumeration values
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用
* EN: 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* CN: 所有枚举值的数据类型
*
* CN: 📣 注意:仅可作为类型声明使用,不可在运行时调用
*
* @example
*
* // 声明变量的类型
* // 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
*
* 📣 注意:仅可作为类型声明使用,不可在运行时调用
* EN: 📣 Note: Can only be used as a type declaration, cannot be called at runtime
*
* CN: 所有枚举key的数据类型
*
* CN: 📣 注意:仅可作为类型声明使用,不可在运行时调用
*
* @example
*
* // 声明变量的类型
* // 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: 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。
*/

@@ -183,45 +270,32 @@ rawType: T[K];

export declare type CompactEnumItemInit = Record<string, never>;
/**
* 由枚举项生成的作为Select组件数据源的数据结构
*/
/** 由枚举项生成的作为Select组件数据源的数据结构 */
export declare type EnumOption<K, V> = {
/**
* 选项的值
*/
/** 选项的值 */
value: V;
/**
* 选项的显示文本
*/
/** 选项的显示文本 */
label: string;
/**
* 选项的key,默认使用`value`
*/
/** 选项的key,默认使用`value` */
key: K;
};
/**
* Table列筛选项的数据结构
*/
/** Table列筛选项的数据结构 */
export declare type ColumnFilterItem<V> = {
/**
* 显示文本
*/
/** 显示文本 */
text: string;
/**
* 值
*/
/** 值 */
value: V;
};
/**
* 枚举值的类型,支持number、string、symbol
*/
/** 用于生成菜单的数据结构 */
export declare type MenuItemOption<V> = {
/** 枚举值 */
key: V;
/** 显示文本 */
label: string;
};
/** 枚举值的类型,支持number、string、symbol */
export declare type EnumValue = keyof any;
/**
* 获取枚举初始化对象中key的类型
*/
/** 获取枚举初始化对象中key的类型 */
export declare type EnumKey<T> = keyof T;
/**
* options方法的更多选项
*/
/** options方法的更多选项 */
export declare type OptionsConfig = object;
export declare type BooleanFirstOptionConfig<B extends boolean> = {
export declare type BooleanFirstOptionConfig<V> = {
/**

@@ -235,21 +309,21 @@ * 在头部添加一个默认选项。

*/
firstOption?: B;
firstOption: boolean;
/** 默认选项的值,默认为`''` */
firstOptionValue?: V;
/** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 */
firstOptionLabel?: string;
};
export declare type ObjectFirstOptionConfig<K, V> = {
/**
* 首行选项的配置
*/
/** 首行选项的配置 */
firstOption?: EnumOptionConfig<K, V>;
/** 默认选项的值,默认为`''` */
firstOptionValue?: never;
/** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 */
firstOptionLabel?: never;
};
export declare type EnumOptionConfig<K, V> = Omit<EnumOption<K, V>, 'key'> & Partial<Pick<EnumOption<K, V>, 'key'>>;
/**
* 从枚举集合或枚举项的初始化对象推断value类型
*/
/**
* 从枚举项的初始化对象推断value类型
*/
/** 从枚举集合或枚举项的初始化对象推断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类型
*/
/** 从枚举集合初始化对象推断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;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// eslint-disable-next-line @typescript-eslint/ban-types
//# sourceMappingURL=types.js.map
{
"name": "enum-plus",
"version": "1.0.3",
"description": "A powerful enum library, like typescript enum but more than that",
"version": "2.0.0-alpha.2",
"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 a perfect replacement for native `enum` types, fully compatible with the basic usage of native `enum` types, and also supports extending display text for enum items, so that enums are no longer just field names and values, but also enum names that can be bound to UI components. More importantly, it provides a set of very useful extension methods that can easily traverse the array of enum items, and even bind the enum directly to components like Select, Checkbox, etc. You can turn an enum into a dropdown with just one line of code.
The display text of enum items can be achieved through localization methods, you can use any popular internationalization library, such as `i18next`, or even use custom components.
What other exciting features are there? Please continue to explore the technical documentation below!
## Features
- Fully compatible with the basic usage of native `enum` types, can be used as a perfect replacement for native `enum`
- Supports multiple data types such as numbers and strings
- Built-in display text for each enum item
- One-click access to the display text of enum values, can also be directly bound to components like Select
- Display text supports localization, can use any internationalization library
- 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) and other component libraries with just one 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 yarn:
```bash
yarn add enum-plus
```
## Enum Definition
Generate an enum collection, 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,262 @@

} as const);
Week.Monday; // 1
```
示例 2:string 类型
#### Example 2: Use string as 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): Include 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 (display text)
```
示例 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
## API
```typescript
import { Enum } from 'enum-plus';
### Pick enum value
const Week = Enum({
Sunday: undefined, // 等价于 { value: "Sunday" }
Monday: undefined, // 等价于 { value: "Sunday" }
} as const);
`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
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
`{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 one 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)
```
## 使用方法
---
直接作为 Select 的数据源
### key
```tsx
<Select options={Week.values} />
<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)
```
在头部增加默认选项(默认文本为'全部',value 为'')
---
```tsx
<Select options={Week.options({ firstOption: true })} />
### 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
```
在头部增加自定义选项
---
```tsx
<Select options={Week.options({ firstOption: { value: 0, label: '不限' } as const })} />
### 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' },
}
```
使用 AntDesignPro
---
```tsx
<ProFormSelect valueEnum={Week.valuesEnum()} />
### 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: 'Sunday' },
Monday: { value: 1, label: 'Monday' },
} as const);
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' }
```
---
### valueType <sup>**_[Type-ONLY]_**</sup>
`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
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'; // ❌ 不可修改
const weekValue: typeof Week.valueType = 1;
const weeks: typeof Week.valueType[] = [0, 1];
type WeekValues = typeof Week.valueType; // 0 | 1
```
获取第一个枚举项的值
> 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
---
### 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
---
### 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
```
#### Get array of enum items
```js
Week.values;
// [
// { value: 0, label: 'Sunday', key: 'Sunday', raw: { value: 0, label: 'Sunday' } },
// { value: 1, label: 'Monday', key: 'Monday', raw: { value: 1, label: 'Monday' } },
// ]
```
#### Get the value of the first enum item
```js
Week.values[0].value; // 0
```
判断某个值是否有效?
#### Determine whether a certain value is included in the enum
```typescript
```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` 操作符
#### `instanceof` operator
```typescript
```js
1 instance of Week // true

@@ -151,41 +342,229 @@ "1" instance of Week // true

获取某个值的显示文本
#### Support traversing the array of enum items, but not modifying
```typescript
Week.label(1); // 星期一,
Week.label(Week.Monday); // 星期一
Week.label('Monday'); // 星期一
```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
#### Get the display text of a certain value
```typescript
Week.key(1); // 'Monday'
Week.key(Week.Monday); // 'Monday'
Week.key(9); // undefined
```js
Week.label(1); // Monday
Week.label(Week.Monday); // Monday
Week.label('Monday'); // Monday
```
两个枚举合并(或者扩展某个枚举)
#### Get the key of a certain enum item
```typescript
```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?
😟 命名冲突?
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?
如果 `Week` 的 `key`、`label`、`options` 方法与某个枚举的 key 重名了,则这些方法会被覆盖掉。不用担心,在 `Week.values` 下仍然可以访问到这些方法
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` itself does not provide internationalization functionality, but you can achieve localized text through the `localize` option. You need to maintain the language in your project and implement text localization in the `localize` method. You can also use any popular internationalization library, such as `i18next`.
```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

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