Comparing version 2.0.3 to 2.1.0-beta.0
@@ -1,5 +0,17 @@ | ||
<!-- markdownlint-disable MD009, MD024 --> | ||
<!-- markdownlint-disable MD009 MD024 --> | ||
# enum-plus Changelog | ||
## 2.1.0 | ||
2025-2-8 | ||
### Features | ||
- 🔥 Adds `toSelect` method, deprecated ~~`options`~~ method | ||
- 🔥 Adds `toMenu` method, deprecated ~~`menus`~~ method | ||
- 🔥 Adds `toFilter` method, deprecated ~~`filters`~~ method | ||
- 🔥 Adds `toValueMap` method, ~~`valuesEnum`~~ method | ||
- 🔥 Support global extending, you can add custom methods to Enums | ||
## 2.0.3 | ||
@@ -6,0 +18,0 @@ |
@@ -1,8 +0,19 @@ | ||
import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumItemOptionData, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem, EnumItemOptions, MenuItemOption } from './types'; | ||
import { EnumValuesArray } from './enum-values'; | ||
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumItemOptionData, EnumItemOptions, EnumKey, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types'; | ||
declare global { | ||
export interface EnumExtension<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> { | ||
} | ||
} /** | ||
* **EN:** Enum collection extension base class, used to extend the Enums | ||
* | ||
* **CN:** 枚举集合扩展基类,用于扩展枚举 | ||
*/ | ||
export declare class EnumExtensionClass<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> implements EnumExtension<T, K, V> { | ||
} | ||
/** | ||
* EN: Enum collection | ||
* CN: 枚举项集合 | ||
* **EN:** Enum collection | ||
* | ||
* **CN:** 枚举项集合 | ||
*/ | ||
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> { | ||
export declare class EnumCollectionClass<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> extends EnumExtensionClass<T, K, V> implements IEnumValues<T, K, V> { | ||
readonly values: EnumValuesArray<T, K, V>; | ||
@@ -14,10 +25,22 @@ readonly keys: K[]; | ||
has(keyOrValue?: string | number): boolean; | ||
toSelect(): EnumItemOptionData<K, V>[]; | ||
toSelect(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
toSelect<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** @deprecated use `toSelect` instead */ | ||
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)>[]; | ||
options(config: object & BooleanFirstOptionConfig<V>): EnumItemOptionData<'' | K, '' | V>[]; | ||
options<FK, FV>(config: object & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
toMenu(): MenuItemOption<V>[]; | ||
/** @deprecated use `toMenu` instead */ | ||
menus(): MenuItemOption<V>[]; | ||
toFilter(): ColumnFilterItem<V>[]; | ||
/** @deprecated use `toFilter` instead */ | ||
filters(): ColumnFilterItem<V>[]; | ||
toValueMap(): Record<V, { | ||
text: string; | ||
}>; | ||
/** @deprecated use `toValueMap` instead */ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
menus(): MenuItemOption<V>[]; | ||
filters(): ColumnFilterItem<V>[]; | ||
raw(): T; | ||
@@ -24,0 +47,0 @@ raw(keyOrValue: V | K): T[K]; |
@@ -1,10 +0,15 @@ | ||
import { KEYS, VALUES } from './index'; | ||
import { EnumItemClass } from './enum-item'; | ||
import { EnumValuesArray } from './enum-values'; | ||
import { KEYS, VALUES } from './index'; | ||
// eslint-disable-next-line @typescript-eslint/no-extraneous-class | ||
export class EnumExtensionClass { | ||
} | ||
/** | ||
* EN: Enum collection | ||
* CN: 枚举项集合 | ||
* **EN:** Enum collection | ||
* | ||
* **CN:** 枚举项集合 | ||
*/ | ||
export class EnumCollectionClass { | ||
export class EnumCollectionClass extends EnumExtensionClass { | ||
constructor(init = {}, options) { | ||
super(); | ||
const keys = Object.keys(init); | ||
@@ -14,6 +19,6 @@ const parsed = keys.map((key) => parseEnumItem(init[key], key, { typeInit: init, keys })); | ||
const { value } = parsed[index]; | ||
// @ts-expect-error: dynamically define property | ||
// @ts-expect-error: because of dynamically define property | ||
this[key] = value; | ||
}); | ||
// @ts-expect-error: if init contains keys, use KEYS to avoid naming conflicts | ||
// @ts-expect-error: because use KEYS to avoid naming conflicts in case of 'keys' field name is taken | ||
this[Object.keys(init).some((k) => k === 'keys') ? KEYS : 'keys'] = keys; | ||
@@ -25,9 +30,9 @@ // Build enum item data | ||
})); | ||
// @ts-expect-error: if init contains values, use VALUES to avoid naming conflicts | ||
// @ts-expect-error: because use VALUES to avoid naming conflicts in case of 'values' field name is taken | ||
this[Object.keys(init).some((k) => k === 'values') ? VALUES : 'values'] = values; | ||
// Override some system methods | ||
// @ts-expect-error: Override Object.toString method for better type display | ||
// @ts-expect-error: because override Object.toString method for better type display | ||
this[Symbol.toStringTag] = 'EnumCollection'; | ||
// Override the `instanceof` operator rule | ||
// @ts-expect-error: Override the instanceof operator | ||
// @ts-expect-error: because override the instanceof operator | ||
this[Symbol.hasInstance] = (instance) => { | ||
@@ -52,15 +57,29 @@ // intentionally use == to support both number and string format value | ||
} | ||
toSelect(config) { | ||
return this.values.toSelect(config); | ||
} | ||
options(config) { | ||
// @ts-ignore: call the options method of values | ||
return this.values.options(config); | ||
} | ||
valuesEnum() { | ||
return this.values.valuesEnum(); | ||
toMenu() { | ||
return this.values.toMenu(); | ||
} | ||
/** @deprecated use `toMenu` instead */ | ||
menus() { | ||
return this.values.menus(); | ||
} | ||
toFilter() { | ||
return this.values.toFilter(); | ||
} | ||
/** @deprecated use `toFilter` instead */ | ||
filters() { | ||
return this.values.filters(); | ||
} | ||
toValueMap() { | ||
return this.values.toValueMap(); | ||
} | ||
/** @deprecated use `toValueMap` instead */ | ||
valuesEnum() { | ||
return this.values.valuesEnum(); | ||
} | ||
raw(value) { | ||
@@ -132,2 +151,3 @@ if (value !== undefined) { | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
function inferFromNull(key, options) { | ||
@@ -134,0 +154,0 @@ const { typeInit, keys } = options; |
import type { EnumItemInit, EnumItemOptions, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types'; | ||
/** | ||
* Enum item class | ||
* | ||
* @template V General type of value | ||
@@ -20,2 +21,3 @@ * @template K General type of key | ||
* Instantiate an enum item | ||
* | ||
* @param key Enum item key | ||
@@ -22,0 +24,0 @@ * @param value Enum item value |
@@ -16,2 +16,3 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
* Enum item class | ||
* | ||
* @template V General type of value | ||
@@ -24,2 +25,3 @@ * @template K General type of key | ||
* Instantiate an enum item | ||
* | ||
* @param key Enum item key | ||
@@ -70,5 +72,5 @@ * @param value Enum item value | ||
// Override some system methods | ||
// @ts-ignore: Override Object.toString method to display type more friendly | ||
// @ts-expect-error: because override Object.toString method to display type more friendly | ||
this[Symbol.toStringTag] = 'EnumItem'; | ||
// @ts-ignore: Override Object.toPrimitive method to return enum value | ||
// @ts-expect-error: because override Object.toPrimitive method to return enum value | ||
this[Symbol.toPrimitive] = (hint) => { | ||
@@ -75,0 +77,0 @@ if (hint === 'number') { |
import type { EnumItemClass } from './enum-item'; | ||
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumKey, EnumItemOptionData, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit, EnumItemOptions } from './types'; | ||
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumItemOptionData, EnumItemOptions, EnumKey, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types'; | ||
/** | ||
* Enum items array, mostly are simple wrappers for EnumCollectionClass | ||
* | ||
* @template T Type of the initialization data of the enum collection | ||
* | ||
* @class EnumValuesArray | ||
* | ||
* @extends {EnumItemClass<T, K, V>[]} | ||
* | ||
* @export | ||
* @class EnumValuesArray | ||
* @extends {Array<EnumItemClass<T, K, V>>} | ||
* | ||
* @implements {IEnumValues<T, K, V>} | ||
* @template T Type of the initialization data of the enum collection | ||
*/ | ||
@@ -17,5 +21,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> { | ||
* | ||
* @memberof EnumValuesArray | ||
* | ||
* @param {T} raw Original initialization data object | ||
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array | ||
* @memberof EnumValuesArray | ||
*/ | ||
@@ -26,9 +31,23 @@ constructor(raw: T, options: EnumItemOptions | undefined, ...items: EnumItemClass<T[K], K, V>[]); | ||
has(keyOrValue?: string | number): boolean; | ||
toSelect(): EnumItemOptionData<K, V>[]; | ||
toSelect(config?: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
toSelect<FK = never, FV = never>(config?: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(): EnumItemOptionData<K, V>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(config?: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options<FK = never, FV = never>(config?: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
toValueMap(): Record<V, { | ||
text: string; | ||
}>; | ||
/** @deprecated Use `toValueMap` instead */ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
toMenu(): MenuItemOption<V>[]; | ||
/** @deprecated Use `toMenu` instead */ | ||
menus(): MenuItemOption<V>[]; | ||
toFilter(): ColumnFilterItem<V>[]; | ||
/** @deprecated Use `toFilter` instead */ | ||
filters(): ColumnFilterItem<V>[]; | ||
@@ -38,14 +57,8 @@ raw(): T; | ||
raw(value: unknown): T[K] | undefined; | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get valueType(): V; | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get keyType(): K; | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get rawType(): T[K]; | ||
} |
@@ -17,7 +17,11 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
* | ||
* @template T Type of the initialization data of the enum collection | ||
* | ||
* @class EnumValuesArray | ||
* | ||
* @extends {EnumItemClass<T, K, V>[]} | ||
* | ||
* @export | ||
* @class EnumValuesArray | ||
* @extends {Array<EnumItemClass<T, K, V>>} | ||
* | ||
* @implements {IEnumValues<T, K, V>} | ||
* @template T Type of the initialization data of the enum collection | ||
*/ | ||
@@ -28,5 +32,6 @@ export class EnumValuesArray extends Array { | ||
* | ||
* @memberof EnumValuesArray | ||
* | ||
* @param {T} raw Original initialization data object | ||
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array | ||
* @memberof EnumValuesArray | ||
*/ | ||
@@ -61,3 +66,3 @@ constructor(raw, options, ...items) { | ||
} | ||
options(config = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f")) { | ||
toSelect(config = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f")) { | ||
var _a, _b, _c; | ||
@@ -83,3 +88,7 @@ const { firstOption = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f").firstOption } = config; | ||
} | ||
valuesEnum() { | ||
/** @deprecated Use `toSelect` instead */ | ||
options(config) { | ||
return this.toSelect(config); | ||
} | ||
toValueMap() { | ||
const itemsMap = {}; | ||
@@ -92,8 +101,20 @@ for (let i = 0; i < this.length; i++) { | ||
} | ||
menus() { | ||
/** @deprecated Use `toValueMap` instead */ | ||
valuesEnum() { | ||
return this.toValueMap(); | ||
} | ||
toMenu() { | ||
return this.map(({ value, label }) => ({ key: value, label })); | ||
} | ||
filters() { | ||
/** @deprecated Use `toMenu` instead */ | ||
menus() { | ||
return this.toMenu(); | ||
} | ||
toFilter() { | ||
return this.map(({ value, label }) => ({ text: label, value })); | ||
} | ||
/** @deprecated Use `toFilter` instead */ | ||
filters() { | ||
return this.toFilter(); | ||
} | ||
raw(value) { | ||
@@ -119,17 +140,11 @@ if (value == null) { | ||
} | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get 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 method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get 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 method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get rawType() { | ||
@@ -136,0 +151,0 @@ 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'); |
import type { EnumInit, EnumInitOptions, EnumItemOptions, EnumKey, EnumValue, IEnum, StandardEnumInit, ValueTypeFromSingleInit } from './types'; | ||
export * from './types'; | ||
export type { EnumInit, EnumItemInit, EnumKey, EnumValue, ValueTypeFromSingleInit, EnumOptionConfig, BuiltInResources, EnumItemOptionData, MenuItemOption, ColumnFilterItem, EnumInitOptions, } from './types'; | ||
/** | ||
* 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 | ||
* **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 | ||
* | ||
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
export declare const VALUES: unique 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 | ||
* **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 | ||
* | ||
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
export declare const KEYS: unique symbol; | ||
/** | ||
* EN: Generate an enum collection, the enum value supports `number` and `string` types, and the enum name supports localization solutions | ||
* **EN:** Generate an enum collection, the enum value supports `number` and `string` types, and the | ||
* enum name supports localization solutions | ||
* | ||
* CN: 生成一个枚举集合,枚举值支持`number`和`string`类型,枚举名称支持本地化方案 | ||
* **CN:** 生成一个枚举集合,枚举值支持`number`和`string`类型,枚举名称支持本地化方案 | ||
* | ||
* @example | ||
* const Week = Enum({ | ||
* Sunday: { value: 0, label: 'Sunday' }, | ||
* Monday: { value: 1, label: 'Monday' } | ||
* } as const); | ||
* const Week = Enum({ | ||
* Sunday: { value: 0, label: 'Sunday' }, | ||
* Monday: { value: 1, label: '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 | ||
* @param init the init object, see usage examples for the way to pass values | 初始化对象,传值方式参见使用示例 | ||
* | ||
* CN: 基于Map对象生成枚举 | ||
* | ||
* @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>; | ||
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> & EnumExtension<T, K, V>; | ||
/** | ||
* EN: Generate an enum based on an object array | ||
* **EN:** Generate an enum based on an object array | ||
* | ||
* CN: 基于对象数组生成枚举 | ||
* **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 | ||
* @example | ||
* const Week = Enum([ | ||
* { value: 0, label: 'Sunday', key: 'Sun' }, | ||
* { value: 1, label: 'Monday', key: 'Mon' }, | ||
* ]); | ||
* | ||
* CN: 基于对象数组生成枚举 | ||
* @param init Init objects array | 初始化对象数组 | ||
* @param options Generate options | 生成选项 | ||
* | ||
* @param init Enum item array | 枚举项数组 | ||
* @param options Generate options | 生成选项 | ||
* @returns Enum collection | 枚举集合 | ||
*/ | ||
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 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> & EnumExtension<T, K, V>; | ||
export declare namespace Enum { | ||
var localize: <T extends "enum-plus.options.all" | (string & {})>(content: T | undefined) => string | T | undefined; | ||
export var localize: <T extends import("./types").BuiltInResources | (string & {})>(content: T | undefined) => T | string | undefined; | ||
var _a: (obj: Record<string, unknown> | undefined) => void; | ||
export { _a as extends }; | ||
} | ||
/** | ||
* **EN**: Default global localization function, only used to resolve built-in resources into English, does not provide actual localization functions | ||
* **EN:** Default global localization function, only used to resolve built-in resources into | ||
* English, does not provide actual localization functions | ||
* | ||
* **CN**: 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* **CN:** 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* | ||
@@ -68,2 +66,2 @@ * @summary | ||
*/ | ||
export declare const DefaultLocalize: NonNullable<EnumItemOptions['localize']>; | ||
export declare const defaultLocalize: NonNullable<EnumItemOptions['localize']>; |
@@ -1,15 +0,17 @@ | ||
import { EnumCollectionClass } from './enum-collection'; | ||
export * from './types'; | ||
import { EnumCollectionClass, EnumExtensionClass } from './enum-collection'; | ||
/** | ||
* 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 | ||
* **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 | ||
* | ||
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
export const VALUES = Symbol('[values]'); | ||
/** | ||
* 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 | ||
* **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 | ||
* | ||
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
export const KEYS = Symbol('[keys]'); | ||
let enumExtensions; | ||
export function Enum(init, options) { | ||
@@ -25,5 +27,6 @@ if (Array.isArray(init)) { | ||
/** | ||
* **EN**: Default global localization function, only used to resolve built-in resources into English, does not provide actual localization functions | ||
* **EN:** Default global localization function, only used to resolve built-in resources into | ||
* English, does not provide actual localization functions | ||
* | ||
* **CN**: 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* **CN:** 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* | ||
@@ -34,3 +37,3 @@ * @summary | ||
*/ | ||
export const DefaultLocalize = (content) => { | ||
export const defaultLocalize = (content) => { | ||
if (content === 'enum-plus.options.all') { | ||
@@ -42,9 +45,12 @@ return 'All'; | ||
/** | ||
* EN: Global localization function, used to convert enum item text to localized text. Only need to be set once, effective globally. This method need to be set at the project entry, before running any Enum instance | ||
* **EN:** Global localization function, used to convert enum item text to localized text. Only need | ||
* to be set once, effective globally. This method need to be set at the project entry, before | ||
* running any Enum instance | ||
* | ||
* If you want to provide a custom localization function, be sure to resolve and localize the following built-in resources: | ||
* If you want to provide a custom localization function, be sure to resolve and localize the | ||
* following built-in resources: | ||
* | ||
* - `enum-plus.options.all` => `All` | ||
* | ||
* CN: 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效。需要在项目入口处设置,且在运行任何Enum实例之前 | ||
* **CN:** 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效。需要在项目入口处设置,且在运行任何Enum实例之前 | ||
* | ||
@@ -55,5 +61,20 @@ * 如果要提供自定义的本地化函数,请务必解析并本地化以下内置资源: | ||
*/ | ||
Enum.localize = DefaultLocalize; | ||
Enum.localize = defaultLocalize; | ||
/** | ||
* **EN:** Add global extension methods to the enum, and all enum instances will have these new | ||
* extension methods | ||
* | ||
* **CN:** 为枚举增加全局扩展方法,所有枚举实例都会具有这些新扩展方法 | ||
* | ||
* @param obj Extension content, must be an object | 扩展内容,必须是一个对象 | ||
*/ | ||
Enum.extends = function (obj) { | ||
if (obj !== undefined && Object.prototype.toString.call(obj) !== '[object Object]') { | ||
throw new Error('The extension of Enum must be an object'); | ||
} | ||
enumExtensions = obj !== undefined ? obj : {}; | ||
Object.setPrototypeOf(EnumExtensionClass.prototype, enumExtensions); | ||
}; | ||
function getInitMapFromArray(init, options) { | ||
const { getValue = 'value', getLabel = 'label', getKey = 'key', } = options !== null && options !== void 0 ? options : {}; | ||
const { getValue = 'value', getLabel = 'label', getKey = 'key' } = options !== null && options !== void 0 ? options : {}; | ||
return init.reduce((acc, item) => { | ||
@@ -60,0 +81,0 @@ const value = typeof getValue === 'function' ? getValue(item) : item[getValue]; |
@@ -0,3 +1,3 @@ | ||
import type { EnumItemClass } from './enum-item'; | ||
import type { KEYS, VALUES } from './index'; | ||
import type { EnumItemClass } from './enum-item'; | ||
/** | ||
@@ -8,5 +8,6 @@ * **EN:** Enum initialization options | ||
*/ | ||
export declare type EnumInitOptions<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> = { | ||
export 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` | ||
* **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` | ||
* | ||
@@ -17,3 +18,4 @@ * **CN:** 枚举项的value字段名,或者获取key值的函数,默认为 `value` | ||
/** | ||
* **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` | ||
* **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` | ||
* | ||
@@ -24,3 +26,4 @@ * **CN:** 枚举项的label字段名,或者获取key值的函数,默认为 `label` | ||
/** | ||
* **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` | ||
* **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` | ||
* | ||
@@ -31,5 +34,6 @@ * **CN:** 枚举项的key字段名,或者获取key值的函数,默认为 `key` | ||
} & EnumItemOptions; | ||
export declare type EnumItemOptions = { | ||
export interface EnumItemOptions { | ||
/** | ||
* **EN:** Localization function, used to convert the text of the enumeration item to localized text | ||
* **EN:** Localization function, used to convert the text of the enumeration item to localized | ||
* text | ||
* | ||
@@ -39,10 +43,12 @@ * **CN:** 本地化函数,用于把枚举项文本转换为本地化文本 | ||
* @param content Original text | 原始文本 | ||
* | ||
* @returns Localized text | 本地化文本 | ||
*/ | ||
localize?: <T extends BuiltInResources | (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` | ||
* Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you | ||
* can only use `type` | ||
* | ||
@@ -53,3 +59,3 @@ * **CN:** 数组的类型声明 | ||
*/ | ||
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> & { | ||
export 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, T[K] extends number | undefined ? number : key>; | ||
@@ -62,5 +68,7 @@ } & (T extends { | ||
/** | ||
* **EN:** All enumeration items in the array, can be used directly as the data source of the AntDesign component | ||
* **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 | ||
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any | ||
* modification methods | ||
* | ||
@@ -80,3 +88,4 @@ * **CN:** 所有枚举项的数组,可以直接作为AntDesign组件的数据源 | ||
* | ||
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any modification methods | ||
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any | ||
* modification methods | ||
* | ||
@@ -94,5 +103,7 @@ * **CN:** 获取枚举项的key列表 | ||
* | ||
* @template T Enum collection initialization data type | 枚举集合初始化数据的类型 | ||
* | ||
* @export | ||
* | ||
* @interface IEnumValues | ||
* @template T Enum collection initialization data type | 枚举集合初始化数据的类型 | ||
*/ | ||
@@ -106,2 +117,3 @@ export interface IEnumValues<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> { | ||
* @param value Enum item value or key | 枚举项的value或key | ||
* | ||
* @returns {string | undefined} Display name of the enumeration item | 枚举项的label显示名称 | ||
@@ -125,65 +137,113 @@ */ | ||
/** | ||
* **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:** Generate an array of objects that can be bound to those `options like` of components | ||
* such as Select, Radio, and Checkbox, following the data specification of ant-design | ||
* | ||
* The data format is: `[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]` | ||
* **CN:** 生成一个对象数组,可以绑定到 Select、Radio、Checkbox 等组件的`options`,遵循 ant-design 的数据规范 | ||
* | ||
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options` | ||
* @example | ||
* [ | ||
* { value: 0, label: 'Sunday' }, | ||
* { value: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* 数据格式为:`[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]` | ||
* @see https://ant.design/components/checkbox-cn#option | ||
*/ | ||
options(): EnumItemOptionData<K, V>[]; | ||
toSelect(): EnumItemOptionData<K, V>[]; | ||
/** | ||
* **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:** Generate an array of objects that can be bound to those `options like` of components | ||
* such as Select, Radio, and Checkbox, following the data specification of ant-design | ||
* | ||
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options` | ||
* **CN:** 生成一个对象数组,可以绑定到 Select、Radio、Checkbox 等组件的`options`,遵循 ant-design 的数据规范 | ||
* | ||
* @example | ||
* [ | ||
* { value: 0, label: 'Sunday' }, | ||
* { value: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* @param config Custom options | 自定义选项 | ||
* | ||
* @see https://ant.design/components/checkbox-cn#option | ||
*/ | ||
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
toSelect(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
/** | ||
* **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:** Generate an array of objects that can be bound to those `options like` of components | ||
* such as Select, Radio, and Checkbox, following the data specification of ant-design | ||
* | ||
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options` | ||
* **CN:** 生成一个对象数组,可以绑定到 Select、Radio、Checkbox 等组件的`options`,遵循 ant-design 的数据规范 | ||
* | ||
* @example | ||
* [ | ||
* { value: 0, label: 'Sunday' }, | ||
* { value: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* @param config Custom options | 自定义选项 | ||
* | ||
* @see https://ant.design/components/checkbox-cn#option | ||
*/ | ||
toSelect<FK, FV>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(): EnumItemOptionData<K, V>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options<FK, FV>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** | ||
* **EN:** Generate an object that meets the AntDesignPro specification for the enumeration set | ||
* **EN:** Generate an object array that can be bound to the data source of components such as | ||
* Menu and Dropdown, following the data specification of ant-design | ||
* | ||
* The data structure is: `{ 0: { text: "Sunday" }, 1: { text: "Monday" } }` | ||
* **CN:** 生成一个对象数组,可以绑定到 Menu、Dropdown 等组件的数据源,遵循 ant-design 的数据规范 | ||
* | ||
* **CN:** 生成一个符合AntDesignPro规范的枚举集合对象。 | ||
* @example | ||
* [ | ||
* { key: 0, label: 'Sunday' }, | ||
* { key: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* 数据结构为:`{ 0: { text: "Sunday" }, 1: { text: "Monday" } }` | ||
* | ||
* @see https://procomponents.ant.design/components/schema#valueenum-1 | ||
* @see https://procomponents.ant.design/components/field-set#proformselect | ||
* @see https://ant.design/components/menu-cn#itemtype | ||
*/ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
toMenu(): MenuItemOption<V>[]; | ||
/** @deprecated Use `toMenu` instead */ | ||
menus(): MenuItemOption<V>[]; | ||
/** | ||
* **EN:** Generate a data source that meets the specification of the column filter function of the AntDesign Table component | ||
* **EN:** Generate an object array that can add filtering function to table columns, following | ||
* the data specification of ant-design Table component | ||
* | ||
* The data structure is: `[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]` | ||
* **CN:** 生成一个对象数组,可以给表格列增加筛选功能,遵循 ant-design Table 组件的数据规范 | ||
* | ||
* **CN:** 为AntDesign Table组件的列筛选功能生成符合规范的数据源 | ||
* @example | ||
* [ | ||
* { text: 'Sunday', value: 0 }, | ||
* { text: 'Monday', value: 1 }, | ||
* ]; | ||
* | ||
* 数据结构为:`[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]` | ||
* | ||
* @see https://ant.design/components/table-cn#components-table-demo-head | ||
* @see https://ant.design/components/table-cn#column | ||
*/ | ||
toFilter(): ColumnFilterItem<V>[]; | ||
/** @deprecated Use `toFilter` instead */ | ||
filters(): ColumnFilterItem<V>[]; | ||
/** | ||
* **EN:** Generate a data source that meets the specification of the AntDesign Menu, Dropdown and other components | ||
* **EN:** Generate a Map object that can be used to bind Select, Checkbox and other form | ||
* components, following the data specification of ant-design-pro | ||
* | ||
* The data structure is: `[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]` | ||
* **CN:** 生成一个Map对象,可以用来绑定Select、Checkbox等表单组件,遵循 ant-design-pro 的数据规范 | ||
* | ||
* **CN:** 为 AntDesign Menu、Dropdown 等组件生成符合规范的数据源 | ||
* @example | ||
* { | ||
* "0": { "text": "Sunday" }, | ||
* "1": { "text": "Monday" } | ||
* } | ||
* | ||
* 数据结构为:`[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]` | ||
* @see https://procomponents.ant.design/components/schema#valueenum-1 | ||
* @see https://procomponents.ant.design/components/field-set#proformselect | ||
*/ | ||
menus(): MenuItemOption<V>[]; | ||
toValueMap(): Record<V, { | ||
text: string; | ||
}>; | ||
/** @deprecated Use `toValueMap` instead */ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
/** | ||
@@ -194,8 +254,10 @@ * **EN:** Get the enumeration item by key or value | ||
* | ||
* @return {T} Enum collection initialization object | 初始化对象集合 | ||
* @memberof IEnumValues | ||
* | ||
* @returns {T} Enum collection initialization object | 初始化对象集合 | ||
*/ | ||
raw(): T; | ||
/** | ||
* **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. | ||
* **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. | ||
* | ||
@@ -218,10 +280,9 @@ * **CN:** 获取某个枚举项的原始初始化对象。如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。 | ||
* @example | ||
* // Declare the type of the variable | 声明变量的类型 | ||
* const week: typeof Week.valueType = Week.Monday; // 0 | ||
* | ||
* // 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 | ||
* }; | ||
* // Declare type field | 声明类型字段 | ||
* type Props = { | ||
* week: typeof Week.valueType; // 0 | 1 | ||
* }; | ||
*/ | ||
@@ -239,14 +300,14 @@ valueType: V; | ||
* @example | ||
* // Declare the type of the variable | 声明变量的类型 | ||
* const weekName: typeof Week.keyType = 'Sunday'; // "Sunday" | "Monday" | ||
* | ||
* // 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" | ||
* }; | ||
* // Declare type field | 声明类型字段 | ||
* type Props = { | ||
* weekName: typeof Week.keyType; // "Sunday" | "Monday" | ||
* }; | ||
*/ | ||
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. | ||
* **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. | ||
* | ||
@@ -257,26 +318,26 @@ * **CN:** 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。 | ||
} | ||
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>; | ||
export declare type StringEnumInit<K extends keyof any> = Record<K, string>; | ||
export declare type StandardEnumInit<K extends keyof any, V extends EnumValue> = Record<K, StandardEnumItemInit<V>>; | ||
export declare type ValueOnlyEnumInit<K extends keyof any, V extends EnumValue> = Record<K, ValueOnlyEnumItemInit<V>>; | ||
export declare type LabelOnlyEnumInit<K extends keyof any> = Record<K, LabelOnlyEnumItemInit>; | ||
export declare type CompactEnumInit<K extends keyof any> = Record<K, CompactEnumItemInit>; | ||
export declare type AutoIncrementedEnumInit<K extends keyof any> = Record<K, undefined>; | ||
export 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 type NumberEnumInit<K extends keyof any> = Record<K, number>; | ||
export type StringEnumInit<K extends keyof any> = Record<K, string>; | ||
export type StandardEnumInit<K extends keyof any, V extends EnumValue> = Record<K, StandardEnumItemInit<V>>; | ||
export type ValueOnlyEnumInit<K extends keyof any, V extends EnumValue> = Record<K, ValueOnlyEnumItemInit<V>>; | ||
export type LabelOnlyEnumInit<K extends keyof any> = Record<K, LabelOnlyEnumItemInit>; | ||
export type CompactEnumInit<K extends keyof any> = Record<K, CompactEnumItemInit>; | ||
export 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; | ||
export declare type StandardEnumItemInit<V extends EnumValue> = { | ||
export type OmitEnumInit<K extends keyof any> = AutoIncrementedEnumInit<K>; | ||
export type EnumItemInit<V extends EnumValue = EnumValue> = EnumValue | StandardEnumItemInit<V> | ValueOnlyEnumItemInit<V> | LabelOnlyEnumItemInit | CompactEnumItemInit | undefined; | ||
export interface StandardEnumItemInit<V extends EnumValue> { | ||
value: V; | ||
label: string; | ||
}; | ||
export declare type ValueOnlyEnumItemInit<V extends EnumValue> = { | ||
} | ||
export interface ValueOnlyEnumItemInit<V extends EnumValue> { | ||
value: V; | ||
}; | ||
export declare type LabelOnlyEnumItemInit = { | ||
} | ||
export interface LabelOnlyEnumItemInit { | ||
label: string; | ||
}; | ||
export declare type CompactEnumItemInit = Record<string, never>; | ||
} | ||
export type CompactEnumItemInit = Record<string, never>; | ||
/** Data structure of ant-design Select options */ | ||
export declare type EnumItemOptionData<K, V> = { | ||
export interface EnumItemOptionData<K, V> { | ||
/** Option value */ | ||
@@ -288,5 +349,5 @@ value: V; | ||
key: K; | ||
}; | ||
} | ||
/** Data structure of column filter items of ant-design Table */ | ||
export declare type ColumnFilterItem<V> = { | ||
export interface ColumnFilterItem<V> { | ||
/** Display name */ | ||
@@ -296,5 +357,5 @@ text: string; | ||
value: V; | ||
}; | ||
} | ||
/** Data structure of ant-design Menu items */ | ||
export declare type MenuItemOption<V> = { | ||
export interface MenuItemOption<V> { | ||
/** Key of menu item */ | ||
@@ -304,12 +365,13 @@ key: V; | ||
label: string; | ||
}; | ||
} | ||
/** Enum value type, support number, string, symbol */ | ||
export declare type EnumValue = keyof any; | ||
export type EnumValue = keyof any; | ||
/** Enum key collection */ | ||
export declare type EnumKey<T> = keyof T; | ||
export type EnumKey<T> = keyof T; | ||
/** More options for the options method */ | ||
export declare type OptionsConfig = object; | ||
export declare type BooleanFirstOptionConfig<V> = { | ||
export type OptionsConfig = object; | ||
export interface BooleanFirstOptionConfig<V> { | ||
/** | ||
* **EN:** Add a default option at the top | ||
* | ||
* - `true`: the option uses the default value, `value` is `''`, `label` is `'All'`; | ||
@@ -335,3 +397,4 @@ * - `false`: the default option is not added; | ||
/** | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the | ||
* localization method will be automatically called | ||
* | ||
@@ -341,4 +404,4 @@ * **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 | ||
firstOptionLabel?: string; | ||
}; | ||
export declare type ObjectFirstOptionConfig<K, V> = { | ||
} | ||
export interface ObjectFirstOptionConfig<K, V> { | ||
/** | ||
@@ -357,3 +420,4 @@ * **EN:** Configuration of the first option | ||
/** | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the | ||
* localization method will be automatically called | ||
* | ||
@@ -363,9 +427,9 @@ * **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 | ||
firstOptionLabel?: never; | ||
}; | ||
} | ||
/** Built-in resources */ | ||
export declare type BuiltInResources = 'enum-plus.options.all'; | ||
export declare type EnumOptionConfig<K, V> = Omit<EnumItemOptionData<K, V>, 'key'> & Partial<Pick<EnumItemOptionData<K, V>, 'key'>>; | ||
export type BuiltInResources = 'enum-plus.options.all'; | ||
export 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; | ||
export 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; | ||
export 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,8 +0,19 @@ | ||
import type { BooleanFirstOptionConfig, IEnumValues, ObjectFirstOptionConfig, OptionsConfig, EnumInit, EnumKey, EnumItemOptionData, EnumValue, ValueTypeFromSingleInit, ColumnFilterItem, EnumItemOptions, MenuItemOption } from './types'; | ||
import { EnumValuesArray } from './enum-values'; | ||
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumItemOptionData, EnumItemOptions, EnumKey, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types'; | ||
declare global { | ||
export interface EnumExtension<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> { | ||
} | ||
} /** | ||
* **EN:** Enum collection extension base class, used to extend the Enums | ||
* | ||
* **CN:** 枚举集合扩展基类,用于扩展枚举 | ||
*/ | ||
export declare class EnumExtensionClass<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> implements EnumExtension<T, K, V> { | ||
} | ||
/** | ||
* EN: Enum collection | ||
* CN: 枚举项集合 | ||
* **EN:** Enum collection | ||
* | ||
* **CN:** 枚举项集合 | ||
*/ | ||
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> { | ||
export declare class EnumCollectionClass<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> extends EnumExtensionClass<T, K, V> implements IEnumValues<T, K, V> { | ||
readonly values: EnumValuesArray<T, K, V>; | ||
@@ -14,10 +25,22 @@ readonly keys: K[]; | ||
has(keyOrValue?: string | number): boolean; | ||
toSelect(): EnumItemOptionData<K, V>[]; | ||
toSelect(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
toSelect<FK = never, FV = never>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** @deprecated use `toSelect` instead */ | ||
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)>[]; | ||
options(config: object & BooleanFirstOptionConfig<V>): EnumItemOptionData<'' | K, '' | V>[]; | ||
options<FK, FV>(config: object & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
toMenu(): MenuItemOption<V>[]; | ||
/** @deprecated use `toMenu` instead */ | ||
menus(): MenuItemOption<V>[]; | ||
toFilter(): ColumnFilterItem<V>[]; | ||
/** @deprecated use `toFilter` instead */ | ||
filters(): ColumnFilterItem<V>[]; | ||
toValueMap(): Record<V, { | ||
text: string; | ||
}>; | ||
/** @deprecated use `toValueMap` instead */ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
menus(): MenuItemOption<V>[]; | ||
filters(): ColumnFilterItem<V>[]; | ||
raw(): T; | ||
@@ -24,0 +47,0 @@ raw(keyOrValue: V | K): T[K]; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.EnumCollectionClass = void 0; | ||
const index_1 = require("./index"); | ||
exports.EnumCollectionClass = exports.EnumExtensionClass = void 0; | ||
const enum_item_1 = require("./enum-item"); | ||
const enum_values_1 = require("./enum-values"); | ||
const index_1 = require("./index"); | ||
// eslint-disable-next-line @typescript-eslint/no-extraneous-class | ||
class EnumExtensionClass { | ||
} | ||
exports.EnumExtensionClass = EnumExtensionClass; | ||
/** | ||
* EN: Enum collection | ||
* CN: 枚举项集合 | ||
* **EN:** Enum collection | ||
* | ||
* **CN:** 枚举项集合 | ||
*/ | ||
class EnumCollectionClass { | ||
class EnumCollectionClass extends EnumExtensionClass { | ||
constructor(init = {}, options) { | ||
super(); | ||
const keys = Object.keys(init); | ||
@@ -17,6 +23,6 @@ const parsed = keys.map((key) => parseEnumItem(init[key], key, { typeInit: init, keys })); | ||
const { value } = parsed[index]; | ||
// @ts-expect-error: dynamically define property | ||
// @ts-expect-error: because of dynamically define property | ||
this[key] = value; | ||
}); | ||
// @ts-expect-error: if init contains keys, use KEYS to avoid naming conflicts | ||
// @ts-expect-error: because use KEYS to avoid naming conflicts in case of 'keys' field name is taken | ||
this[Object.keys(init).some((k) => k === 'keys') ? index_1.KEYS : 'keys'] = keys; | ||
@@ -28,9 +34,9 @@ // Build enum item data | ||
})); | ||
// @ts-expect-error: if init contains values, use VALUES to avoid naming conflicts | ||
// @ts-expect-error: because use VALUES to avoid naming conflicts in case of 'values' field name is taken | ||
this[Object.keys(init).some((k) => k === 'values') ? index_1.VALUES : 'values'] = values; | ||
// Override some system methods | ||
// @ts-expect-error: Override Object.toString method for better type display | ||
// @ts-expect-error: because override Object.toString method for better type display | ||
this[Symbol.toStringTag] = 'EnumCollection'; | ||
// Override the `instanceof` operator rule | ||
// @ts-expect-error: Override the instanceof operator | ||
// @ts-expect-error: because override the instanceof operator | ||
this[Symbol.hasInstance] = (instance) => { | ||
@@ -55,15 +61,29 @@ // intentionally use == to support both number and string format value | ||
} | ||
toSelect(config) { | ||
return this.values.toSelect(config); | ||
} | ||
options(config) { | ||
// @ts-ignore: call the options method of values | ||
return this.values.options(config); | ||
} | ||
valuesEnum() { | ||
return this.values.valuesEnum(); | ||
toMenu() { | ||
return this.values.toMenu(); | ||
} | ||
/** @deprecated use `toMenu` instead */ | ||
menus() { | ||
return this.values.menus(); | ||
} | ||
toFilter() { | ||
return this.values.toFilter(); | ||
} | ||
/** @deprecated use `toFilter` instead */ | ||
filters() { | ||
return this.values.filters(); | ||
} | ||
toValueMap() { | ||
return this.values.toValueMap(); | ||
} | ||
/** @deprecated use `toValueMap` instead */ | ||
valuesEnum() { | ||
return this.values.valuesEnum(); | ||
} | ||
raw(value) { | ||
@@ -136,2 +156,3 @@ if (value !== undefined) { | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
function inferFromNull(key, options) { | ||
@@ -138,0 +159,0 @@ const { typeInit, keys } = options; |
import type { EnumItemInit, EnumItemOptions, EnumKey, EnumValue, ValueTypeFromSingleInit } from './types'; | ||
/** | ||
* Enum item class | ||
* | ||
* @template V General type of value | ||
@@ -20,2 +21,3 @@ * @template K General type of key | ||
* Instantiate an enum item | ||
* | ||
* @param key Enum item key | ||
@@ -22,0 +24,0 @@ * @param value Enum item value |
@@ -19,2 +19,3 @@ "use strict"; | ||
* Enum item class | ||
* | ||
* @template V General type of value | ||
@@ -27,2 +28,3 @@ * @template K General type of key | ||
* Instantiate an enum item | ||
* | ||
* @param key Enum item key | ||
@@ -73,5 +75,5 @@ * @param value Enum item value | ||
// Override some system methods | ||
// @ts-ignore: Override Object.toString method to display type more friendly | ||
// @ts-expect-error: because override Object.toString method to display type more friendly | ||
this[Symbol.toStringTag] = 'EnumItem'; | ||
// @ts-ignore: Override Object.toPrimitive method to return enum value | ||
// @ts-expect-error: because override Object.toPrimitive method to return enum value | ||
this[Symbol.toPrimitive] = (hint) => { | ||
@@ -78,0 +80,0 @@ if (hint === 'number') { |
import type { EnumItemClass } from './enum-item'; | ||
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumKey, EnumItemOptionData, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit, EnumItemOptions } from './types'; | ||
import type { BooleanFirstOptionConfig, ColumnFilterItem, EnumInit, EnumItemOptionData, EnumItemOptions, EnumKey, EnumValue, IEnumValues, MenuItemOption, ObjectFirstOptionConfig, OptionsConfig, ValueTypeFromSingleInit } from './types'; | ||
/** | ||
* Enum items array, mostly are simple wrappers for EnumCollectionClass | ||
* | ||
* @template T Type of the initialization data of the enum collection | ||
* | ||
* @class EnumValuesArray | ||
* | ||
* @extends {EnumItemClass<T, K, V>[]} | ||
* | ||
* @export | ||
* @class EnumValuesArray | ||
* @extends {Array<EnumItemClass<T, K, V>>} | ||
* | ||
* @implements {IEnumValues<T, K, V>} | ||
* @template T Type of the initialization data of the enum collection | ||
*/ | ||
@@ -17,5 +21,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> { | ||
* | ||
* @memberof EnumValuesArray | ||
* | ||
* @param {T} raw Original initialization data object | ||
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array | ||
* @memberof EnumValuesArray | ||
*/ | ||
@@ -26,9 +31,23 @@ constructor(raw: T, options: EnumItemOptions | undefined, ...items: EnumItemClass<T[K], K, V>[]); | ||
has(keyOrValue?: string | number): boolean; | ||
toSelect(): EnumItemOptionData<K, V>[]; | ||
toSelect(config?: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
toSelect<FK = never, FV = never>(config?: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(): EnumItemOptionData<K, V>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(config?: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options<FK = never, FV = never>(config?: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
toValueMap(): Record<V, { | ||
text: string; | ||
}>; | ||
/** @deprecated Use `toValueMap` instead */ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
toMenu(): MenuItemOption<V>[]; | ||
/** @deprecated Use `toMenu` instead */ | ||
menus(): MenuItemOption<V>[]; | ||
toFilter(): ColumnFilterItem<V>[]; | ||
/** @deprecated Use `toFilter` instead */ | ||
filters(): ColumnFilterItem<V>[]; | ||
@@ -38,14 +57,8 @@ raw(): T; | ||
raw(value: unknown): T[K] | undefined; | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get valueType(): V; | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get keyType(): K; | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get rawType(): T[K]; | ||
} |
@@ -20,7 +20,11 @@ "use strict"; | ||
* | ||
* @template T Type of the initialization data of the enum collection | ||
* | ||
* @class EnumValuesArray | ||
* | ||
* @extends {EnumItemClass<T, K, V>[]} | ||
* | ||
* @export | ||
* @class EnumValuesArray | ||
* @extends {Array<EnumItemClass<T, K, V>>} | ||
* | ||
* @implements {IEnumValues<T, K, V>} | ||
* @template T Type of the initialization data of the enum collection | ||
*/ | ||
@@ -31,5 +35,6 @@ class EnumValuesArray extends Array { | ||
* | ||
* @memberof EnumValuesArray | ||
* | ||
* @param {T} raw Original initialization data object | ||
* @param {...EnumItemClass<T[K], K, V>[]} items Enum item instance array | ||
* @memberof EnumValuesArray | ||
*/ | ||
@@ -64,3 +69,3 @@ constructor(raw, options, ...items) { | ||
} | ||
options(config = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f")) { | ||
toSelect(config = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f")) { | ||
var _a, _b, _c; | ||
@@ -86,3 +91,7 @@ const { firstOption = __classPrivateFieldGet(this, _EnumValuesArray_optionsConfigDefaults, "f").firstOption } = config; | ||
} | ||
valuesEnum() { | ||
/** @deprecated Use `toSelect` instead */ | ||
options(config) { | ||
return this.toSelect(config); | ||
} | ||
toValueMap() { | ||
const itemsMap = {}; | ||
@@ -95,8 +104,20 @@ for (let i = 0; i < this.length; i++) { | ||
} | ||
menus() { | ||
/** @deprecated Use `toValueMap` instead */ | ||
valuesEnum() { | ||
return this.toValueMap(); | ||
} | ||
toMenu() { | ||
return this.map(({ value, label }) => ({ key: value, label })); | ||
} | ||
filters() { | ||
/** @deprecated Use `toMenu` instead */ | ||
menus() { | ||
return this.toMenu(); | ||
} | ||
toFilter() { | ||
return this.map(({ value, label }) => ({ text: label, value })); | ||
} | ||
/** @deprecated Use `toFilter` instead */ | ||
filters() { | ||
return this.toFilter(); | ||
} | ||
raw(value) { | ||
@@ -122,17 +143,11 @@ if (value == null) { | ||
} | ||
/** | ||
* @deprecated Stub method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get 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 method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get 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 method, only for typing usages, not for runtime calling | ||
*/ | ||
/** @deprecated Stub method, only for typing usages, not for runtime calling */ | ||
get rawType() { | ||
@@ -139,0 +154,0 @@ 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'); |
import type { EnumInit, EnumInitOptions, EnumItemOptions, EnumKey, EnumValue, IEnum, StandardEnumInit, ValueTypeFromSingleInit } from './types'; | ||
export * from './types'; | ||
export type { EnumInit, EnumItemInit, EnumKey, EnumValue, ValueTypeFromSingleInit, EnumOptionConfig, BuiltInResources, EnumItemOptionData, MenuItemOption, ColumnFilterItem, EnumInitOptions, } from './types'; | ||
/** | ||
* 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 | ||
* **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 | ||
* | ||
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
export declare const VALUES: unique 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 | ||
* **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 | ||
* | ||
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
export declare const KEYS: unique symbol; | ||
/** | ||
* EN: Generate an enum collection, the enum value supports `number` and `string` types, and the enum name supports localization solutions | ||
* **EN:** Generate an enum collection, the enum value supports `number` and `string` types, and the | ||
* enum name supports localization solutions | ||
* | ||
* CN: 生成一个枚举集合,枚举值支持`number`和`string`类型,枚举名称支持本地化方案 | ||
* **CN:** 生成一个枚举集合,枚举值支持`number`和`string`类型,枚举名称支持本地化方案 | ||
* | ||
* @example | ||
* const Week = Enum({ | ||
* Sunday: { value: 0, label: 'Sunday' }, | ||
* Monday: { value: 1, label: 'Monday' } | ||
* } as const); | ||
* const Week = Enum({ | ||
* Sunday: { value: 0, label: 'Sunday' }, | ||
* Monday: { value: 1, label: '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 | ||
* @param init the init object, see usage examples for the way to pass values | 初始化对象,传值方式参见使用示例 | ||
* | ||
* CN: 基于Map对象生成枚举 | ||
* | ||
* @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>; | ||
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> & EnumExtension<T, K, V>; | ||
/** | ||
* EN: Generate an enum based on an object array | ||
* **EN:** Generate an enum based on an object array | ||
* | ||
* CN: 基于对象数组生成枚举 | ||
* **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 | ||
* @example | ||
* const Week = Enum([ | ||
* { value: 0, label: 'Sunday', key: 'Sun' }, | ||
* { value: 1, label: 'Monday', key: 'Mon' }, | ||
* ]); | ||
* | ||
* CN: 基于对象数组生成枚举 | ||
* @param init Init objects array | 初始化对象数组 | ||
* @param options Generate options | 生成选项 | ||
* | ||
* @param init Enum item array | 枚举项数组 | ||
* @param options Generate options | 生成选项 | ||
* @returns Enum collection | 枚举集合 | ||
*/ | ||
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 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> & EnumExtension<T, K, V>; | ||
export declare namespace Enum { | ||
var localize: <T extends "enum-plus.options.all" | (string & {})>(content: T | undefined) => string | T | undefined; | ||
export var localize: <T extends import("./types").BuiltInResources | (string & {})>(content: T | undefined) => T | string | undefined; | ||
var _a: (obj: Record<string, unknown> | undefined) => void; | ||
export { _a as extends }; | ||
} | ||
/** | ||
* **EN**: Default global localization function, only used to resolve built-in resources into English, does not provide actual localization functions | ||
* **EN:** Default global localization function, only used to resolve built-in resources into | ||
* English, does not provide actual localization functions | ||
* | ||
* **CN**: 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* **CN:** 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* | ||
@@ -68,2 +66,2 @@ * @summary | ||
*/ | ||
export declare const DefaultLocalize: NonNullable<EnumItemOptions['localize']>; | ||
export declare const defaultLocalize: NonNullable<EnumItemOptions['localize']>; |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.DefaultLocalize = exports.Enum = exports.KEYS = exports.VALUES = void 0; | ||
exports.defaultLocalize = exports.KEYS = exports.VALUES = void 0; | ||
exports.Enum = Enum; | ||
const enum_collection_1 = require("./enum-collection"); | ||
__exportStar(require("./types"), exports); | ||
/** | ||
* 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 | ||
* **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 | ||
* | ||
* CN: 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举`values`集合的别名。如果枚举中包含了`values`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
exports.VALUES = Symbol('[values]'); | ||
/** | ||
* 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 | ||
* **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 | ||
* | ||
* CN: 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
* **CN:** 枚举keys集合的别名。如果枚举中包含了`keys`的同名字段,可以通过此Symbol作为字段名来访问 | ||
*/ | ||
exports.KEYS = Symbol('[keys]'); | ||
let enumExtensions; | ||
function Enum(init, options) { | ||
@@ -41,7 +30,7 @@ if (Array.isArray(init)) { | ||
} | ||
exports.Enum = Enum; | ||
/** | ||
* **EN**: Default global localization function, only used to resolve built-in resources into English, does not provide actual localization functions | ||
* **EN:** Default global localization function, only used to resolve built-in resources into | ||
* English, does not provide actual localization functions | ||
* | ||
* **CN**: 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* **CN:** 默认的全局本地化函数,仅用于将内置资源解析为英文,并不提供实际的本地化功能 | ||
* | ||
@@ -52,3 +41,3 @@ * @summary | ||
*/ | ||
const DefaultLocalize = (content) => { | ||
const defaultLocalize = (content) => { | ||
if (content === 'enum-plus.options.all') { | ||
@@ -59,11 +48,14 @@ return 'All'; | ||
}; | ||
exports.DefaultLocalize = DefaultLocalize; | ||
exports.defaultLocalize = defaultLocalize; | ||
/** | ||
* EN: Global localization function, used to convert enum item text to localized text. Only need to be set once, effective globally. This method need to be set at the project entry, before running any Enum instance | ||
* **EN:** Global localization function, used to convert enum item text to localized text. Only need | ||
* to be set once, effective globally. This method need to be set at the project entry, before | ||
* running any Enum instance | ||
* | ||
* If you want to provide a custom localization function, be sure to resolve and localize the following built-in resources: | ||
* If you want to provide a custom localization function, be sure to resolve and localize the | ||
* following built-in resources: | ||
* | ||
* - `enum-plus.options.all` => `All` | ||
* | ||
* CN: 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效。需要在项目入口处设置,且在运行任何Enum实例之前 | ||
* **CN:** 全局本地化函数,用于把枚举项文本转换为本地化文本。只需要设置一次,全局生效。需要在项目入口处设置,且在运行任何Enum实例之前 | ||
* | ||
@@ -74,5 +66,20 @@ * 如果要提供自定义的本地化函数,请务必解析并本地化以下内置资源: | ||
*/ | ||
Enum.localize = exports.DefaultLocalize; | ||
Enum.localize = exports.defaultLocalize; | ||
/** | ||
* **EN:** Add global extension methods to the enum, and all enum instances will have these new | ||
* extension methods | ||
* | ||
* **CN:** 为枚举增加全局扩展方法,所有枚举实例都会具有这些新扩展方法 | ||
* | ||
* @param obj Extension content, must be an object | 扩展内容,必须是一个对象 | ||
*/ | ||
Enum.extends = function (obj) { | ||
if (obj !== undefined && Object.prototype.toString.call(obj) !== '[object Object]') { | ||
throw new Error('The extension of Enum must be an object'); | ||
} | ||
enumExtensions = obj !== undefined ? obj : {}; | ||
Object.setPrototypeOf(enum_collection_1.EnumExtensionClass.prototype, enumExtensions); | ||
}; | ||
function getInitMapFromArray(init, options) { | ||
const { getValue = 'value', getLabel = 'label', getKey = 'key', } = options !== null && options !== void 0 ? options : {}; | ||
const { getValue = 'value', getLabel = 'label', getKey = 'key' } = options !== null && options !== void 0 ? options : {}; | ||
return init.reduce((acc, item) => { | ||
@@ -79,0 +86,0 @@ const value = typeof getValue === 'function' ? getValue(item) : item[getValue]; |
@@ -0,3 +1,3 @@ | ||
import type { EnumItemClass } from './enum-item'; | ||
import type { KEYS, VALUES } from './index'; | ||
import type { EnumItemClass } from './enum-item'; | ||
/** | ||
@@ -8,5 +8,6 @@ * **EN:** Enum initialization options | ||
*/ | ||
export declare type EnumInitOptions<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> = { | ||
export 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` | ||
* **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` | ||
* | ||
@@ -17,3 +18,4 @@ * **CN:** 枚举项的value字段名,或者获取key值的函数,默认为 `value` | ||
/** | ||
* **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` | ||
* **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` | ||
* | ||
@@ -24,3 +26,4 @@ * **CN:** 枚举项的label字段名,或者获取key值的函数,默认为 `label` | ||
/** | ||
* **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` | ||
* **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` | ||
* | ||
@@ -31,5 +34,6 @@ * **CN:** 枚举项的key字段名,或者获取key值的函数,默认为 `key` | ||
} & EnumItemOptions; | ||
export declare type EnumItemOptions = { | ||
export interface EnumItemOptions { | ||
/** | ||
* **EN:** Localization function, used to convert the text of the enumeration item to localized text | ||
* **EN:** Localization function, used to convert the text of the enumeration item to localized | ||
* text | ||
* | ||
@@ -39,10 +43,12 @@ * **CN:** 本地化函数,用于把枚举项文本转换为本地化文本 | ||
* @param content Original text | 原始文本 | ||
* | ||
* @returns Localized text | 本地化文本 | ||
*/ | ||
localize?: <T extends BuiltInResources | (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` | ||
* Should directly use `EnumClass`, but TS does not allow custom index accessors in `class`, so you | ||
* can only use `type` | ||
* | ||
@@ -53,3 +59,3 @@ * **CN:** 数组的类型声明 | ||
*/ | ||
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> & { | ||
export 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, T[K] extends number | undefined ? number : key>; | ||
@@ -62,5 +68,7 @@ } & (T extends { | ||
/** | ||
* **EN:** All enumeration items in the array, can be used directly as the data source of the AntDesign component | ||
* **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 | ||
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any | ||
* modification methods | ||
* | ||
@@ -80,3 +88,4 @@ * **CN:** 所有枚举项的数组,可以直接作为AntDesign组件的数据源 | ||
* | ||
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any modification methods | ||
* Only supports read-only methods in ReadonlyArray<T>, does not support push, pop, and any | ||
* modification methods | ||
* | ||
@@ -94,5 +103,7 @@ * **CN:** 获取枚举项的key列表 | ||
* | ||
* @template T Enum collection initialization data type | 枚举集合初始化数据的类型 | ||
* | ||
* @export | ||
* | ||
* @interface IEnumValues | ||
* @template T Enum collection initialization data type | 枚举集合初始化数据的类型 | ||
*/ | ||
@@ -106,2 +117,3 @@ export interface IEnumValues<T extends EnumInit<K, V>, K extends EnumKey<T> = EnumKey<T>, V extends EnumValue = ValueTypeFromSingleInit<T[K], K>> { | ||
* @param value Enum item value or key | 枚举项的value或key | ||
* | ||
* @returns {string | undefined} Display name of the enumeration item | 枚举项的label显示名称 | ||
@@ -125,65 +137,113 @@ */ | ||
/** | ||
* **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:** Generate an array of objects that can be bound to those `options like` of components | ||
* such as Select, Radio, and Checkbox, following the data specification of ant-design | ||
* | ||
* The data format is: `[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]` | ||
* **CN:** 生成一个对象数组,可以绑定到 Select、Radio、Checkbox 等组件的`options`,遵循 ant-design 的数据规范 | ||
* | ||
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options` | ||
* @example | ||
* [ | ||
* { value: 0, label: 'Sunday' }, | ||
* { value: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* 数据格式为:`[{ value: 0, label: 'Sunday' }, { value: 1, label: 'Monday' }]` | ||
* @see https://ant.design/components/checkbox-cn#option | ||
*/ | ||
options(): EnumItemOptionData<K, V>[]; | ||
toSelect(): EnumItemOptionData<K, V>[]; | ||
/** | ||
* **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:** Generate an array of objects that can be bound to those `options like` of components | ||
* such as Select, Radio, and Checkbox, following the data specification of ant-design | ||
* | ||
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options` | ||
* **CN:** 生成一个对象数组,可以绑定到 Select、Radio、Checkbox 等组件的`options`,遵循 ant-design 的数据规范 | ||
* | ||
* @example | ||
* [ | ||
* { value: 0, label: 'Sunday' }, | ||
* { value: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* @param config Custom options | 自定义选项 | ||
* | ||
* @see https://ant.design/components/checkbox-cn#option | ||
*/ | ||
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
toSelect(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
/** | ||
* **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:** Generate an array of objects that can be bound to those `options like` of components | ||
* such as Select, Radio, and Checkbox, following the data specification of ant-design | ||
* | ||
* **CN:** 生成符合AntDesign规范的下拉数据源数组,可以直接传给Select、Radio、Checkbox等组件的`options` | ||
* **CN:** 生成一个对象数组,可以绑定到 Select、Radio、Checkbox 等组件的`options`,遵循 ant-design 的数据规范 | ||
* | ||
* @example | ||
* [ | ||
* { value: 0, label: 'Sunday' }, | ||
* { value: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* @param config Custom options | 自定义选项 | ||
* | ||
* @see https://ant.design/components/checkbox-cn#option | ||
*/ | ||
toSelect<FK, FV>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(): EnumItemOptionData<K, V>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options(config: OptionsConfig & BooleanFirstOptionConfig<V>): EnumItemOptionData<K | '', V | ''>[]; | ||
/** @deprecated Use `toSelect` instead */ | ||
options<FK, FV>(config: OptionsConfig & ObjectFirstOptionConfig<FK, FV>): EnumItemOptionData<K | (FK extends never ? FV : FK), V | (FV extends never ? V : FV)>[]; | ||
/** | ||
* **EN:** Generate an object that meets the AntDesignPro specification for the enumeration set | ||
* **EN:** Generate an object array that can be bound to the data source of components such as | ||
* Menu and Dropdown, following the data specification of ant-design | ||
* | ||
* The data structure is: `{ 0: { text: "Sunday" }, 1: { text: "Monday" } }` | ||
* **CN:** 生成一个对象数组,可以绑定到 Menu、Dropdown 等组件的数据源,遵循 ant-design 的数据规范 | ||
* | ||
* **CN:** 生成一个符合AntDesignPro规范的枚举集合对象。 | ||
* @example | ||
* [ | ||
* { key: 0, label: 'Sunday' }, | ||
* { key: 1, label: 'Monday' }, | ||
* ]; | ||
* | ||
* 数据结构为:`{ 0: { text: "Sunday" }, 1: { text: "Monday" } }` | ||
* | ||
* @see https://procomponents.ant.design/components/schema#valueenum-1 | ||
* @see https://procomponents.ant.design/components/field-set#proformselect | ||
* @see https://ant.design/components/menu-cn#itemtype | ||
*/ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
toMenu(): MenuItemOption<V>[]; | ||
/** @deprecated Use `toMenu` instead */ | ||
menus(): MenuItemOption<V>[]; | ||
/** | ||
* **EN:** Generate a data source that meets the specification of the column filter function of the AntDesign Table component | ||
* **EN:** Generate an object array that can add filtering function to table columns, following | ||
* the data specification of ant-design Table component | ||
* | ||
* The data structure is: `[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]` | ||
* **CN:** 生成一个对象数组,可以给表格列增加筛选功能,遵循 ant-design Table 组件的数据规范 | ||
* | ||
* **CN:** 为AntDesign Table组件的列筛选功能生成符合规范的数据源 | ||
* @example | ||
* [ | ||
* { text: 'Sunday', value: 0 }, | ||
* { text: 'Monday', value: 1 }, | ||
* ]; | ||
* | ||
* 数据结构为:`[{ text: "Sunday", value: 0 }, { text: "Monday", value: 1 }]` | ||
* | ||
* @see https://ant.design/components/table-cn#components-table-demo-head | ||
* @see https://ant.design/components/table-cn#column | ||
*/ | ||
toFilter(): ColumnFilterItem<V>[]; | ||
/** @deprecated Use `toFilter` instead */ | ||
filters(): ColumnFilterItem<V>[]; | ||
/** | ||
* **EN:** Generate a data source that meets the specification of the AntDesign Menu, Dropdown and other components | ||
* **EN:** Generate a Map object that can be used to bind Select, Checkbox and other form | ||
* components, following the data specification of ant-design-pro | ||
* | ||
* The data structure is: `[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]` | ||
* **CN:** 生成一个Map对象,可以用来绑定Select、Checkbox等表单组件,遵循 ant-design-pro 的数据规范 | ||
* | ||
* **CN:** 为 AntDesign Menu、Dropdown 等组件生成符合规范的数据源 | ||
* @example | ||
* { | ||
* "0": { "text": "Sunday" }, | ||
* "1": { "text": "Monday" } | ||
* } | ||
* | ||
* 数据结构为:`[{ key: 0, label: "Sunday" }, { key: 1, label: "Monday" }]` | ||
* @see https://procomponents.ant.design/components/schema#valueenum-1 | ||
* @see https://procomponents.ant.design/components/field-set#proformselect | ||
*/ | ||
menus(): MenuItemOption<V>[]; | ||
toValueMap(): Record<V, { | ||
text: string; | ||
}>; | ||
/** @deprecated Use `toValueMap` instead */ | ||
valuesEnum(): Record<V, { | ||
text: string; | ||
}>; | ||
/** | ||
@@ -194,8 +254,10 @@ * **EN:** Get the enumeration item by key or value | ||
* | ||
* @return {T} Enum collection initialization object | 初始化对象集合 | ||
* @memberof IEnumValues | ||
* | ||
* @returns {T} Enum collection initialization object | 初始化对象集合 | ||
*/ | ||
raw(): T; | ||
/** | ||
* **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. | ||
* **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. | ||
* | ||
@@ -218,10 +280,9 @@ * **CN:** 获取某个枚举项的原始初始化对象。如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。 | ||
* @example | ||
* // Declare the type of the variable | 声明变量的类型 | ||
* const week: typeof Week.valueType = Week.Monday; // 0 | ||
* | ||
* // 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 | ||
* }; | ||
* // Declare type field | 声明类型字段 | ||
* type Props = { | ||
* week: typeof Week.valueType; // 0 | 1 | ||
* }; | ||
*/ | ||
@@ -239,14 +300,14 @@ valueType: V; | ||
* @example | ||
* // Declare the type of the variable | 声明变量的类型 | ||
* const weekName: typeof Week.keyType = 'Sunday'; // "Sunday" | "Monday" | ||
* | ||
* // 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" | ||
* }; | ||
* // Declare type field | 声明类型字段 | ||
* type Props = { | ||
* weekName: typeof Week.keyType; // "Sunday" | "Monday" | ||
* }; | ||
*/ | ||
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. | ||
* **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. | ||
* | ||
@@ -257,26 +318,26 @@ * **CN:** 枚举项原始初始化对象的类型,如果在枚举项上增加了自定义字段的话,可以用这种方式获取到。 | ||
} | ||
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>; | ||
export declare type StringEnumInit<K extends keyof any> = Record<K, string>; | ||
export declare type StandardEnumInit<K extends keyof any, V extends EnumValue> = Record<K, StandardEnumItemInit<V>>; | ||
export declare type ValueOnlyEnumInit<K extends keyof any, V extends EnumValue> = Record<K, ValueOnlyEnumItemInit<V>>; | ||
export declare type LabelOnlyEnumInit<K extends keyof any> = Record<K, LabelOnlyEnumItemInit>; | ||
export declare type CompactEnumInit<K extends keyof any> = Record<K, CompactEnumItemInit>; | ||
export declare type AutoIncrementedEnumInit<K extends keyof any> = Record<K, undefined>; | ||
export 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 type NumberEnumInit<K extends keyof any> = Record<K, number>; | ||
export type StringEnumInit<K extends keyof any> = Record<K, string>; | ||
export type StandardEnumInit<K extends keyof any, V extends EnumValue> = Record<K, StandardEnumItemInit<V>>; | ||
export type ValueOnlyEnumInit<K extends keyof any, V extends EnumValue> = Record<K, ValueOnlyEnumItemInit<V>>; | ||
export type LabelOnlyEnumInit<K extends keyof any> = Record<K, LabelOnlyEnumItemInit>; | ||
export type CompactEnumInit<K extends keyof any> = Record<K, CompactEnumItemInit>; | ||
export 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; | ||
export declare type StandardEnumItemInit<V extends EnumValue> = { | ||
export type OmitEnumInit<K extends keyof any> = AutoIncrementedEnumInit<K>; | ||
export type EnumItemInit<V extends EnumValue = EnumValue> = EnumValue | StandardEnumItemInit<V> | ValueOnlyEnumItemInit<V> | LabelOnlyEnumItemInit | CompactEnumItemInit | undefined; | ||
export interface StandardEnumItemInit<V extends EnumValue> { | ||
value: V; | ||
label: string; | ||
}; | ||
export declare type ValueOnlyEnumItemInit<V extends EnumValue> = { | ||
} | ||
export interface ValueOnlyEnumItemInit<V extends EnumValue> { | ||
value: V; | ||
}; | ||
export declare type LabelOnlyEnumItemInit = { | ||
} | ||
export interface LabelOnlyEnumItemInit { | ||
label: string; | ||
}; | ||
export declare type CompactEnumItemInit = Record<string, never>; | ||
} | ||
export type CompactEnumItemInit = Record<string, never>; | ||
/** Data structure of ant-design Select options */ | ||
export declare type EnumItemOptionData<K, V> = { | ||
export interface EnumItemOptionData<K, V> { | ||
/** Option value */ | ||
@@ -288,5 +349,5 @@ value: V; | ||
key: K; | ||
}; | ||
} | ||
/** Data structure of column filter items of ant-design Table */ | ||
export declare type ColumnFilterItem<V> = { | ||
export interface ColumnFilterItem<V> { | ||
/** Display name */ | ||
@@ -296,5 +357,5 @@ text: string; | ||
value: V; | ||
}; | ||
} | ||
/** Data structure of ant-design Menu items */ | ||
export declare type MenuItemOption<V> = { | ||
export interface MenuItemOption<V> { | ||
/** Key of menu item */ | ||
@@ -304,12 +365,13 @@ key: V; | ||
label: string; | ||
}; | ||
} | ||
/** Enum value type, support number, string, symbol */ | ||
export declare type EnumValue = keyof any; | ||
export type EnumValue = keyof any; | ||
/** Enum key collection */ | ||
export declare type EnumKey<T> = keyof T; | ||
export type EnumKey<T> = keyof T; | ||
/** More options for the options method */ | ||
export declare type OptionsConfig = object; | ||
export declare type BooleanFirstOptionConfig<V> = { | ||
export type OptionsConfig = object; | ||
export interface BooleanFirstOptionConfig<V> { | ||
/** | ||
* **EN:** Add a default option at the top | ||
* | ||
* - `true`: the option uses the default value, `value` is `''`, `label` is `'All'`; | ||
@@ -335,3 +397,4 @@ * - `false`: the default option is not added; | ||
/** | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the | ||
* localization method will be automatically called | ||
* | ||
@@ -341,4 +404,4 @@ * **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 | ||
firstOptionLabel?: string; | ||
}; | ||
export declare type ObjectFirstOptionConfig<K, V> = { | ||
} | ||
export interface ObjectFirstOptionConfig<K, V> { | ||
/** | ||
@@ -357,3 +420,4 @@ * **EN:** Configuration of the first option | ||
/** | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the localization method will be automatically called | ||
* **EN:** Default option label, default is `'All'`. If a localization method is set, the | ||
* localization method will be automatically called | ||
* | ||
@@ -363,9 +427,9 @@ * **CN:** 默认选项的显示文本,默认为`'All'`。如果设置了本地化方法,则会自动调用本地化方法 | ||
firstOptionLabel?: never; | ||
}; | ||
} | ||
/** Built-in resources */ | ||
export declare type BuiltInResources = 'enum-plus.options.all'; | ||
export declare type EnumOptionConfig<K, V> = Omit<EnumItemOptionData<K, V>, 'key'> & Partial<Pick<EnumItemOptionData<K, V>, 'key'>>; | ||
export type BuiltInResources = 'enum-plus.options.all'; | ||
export 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; | ||
export 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; | ||
export 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": "2.0.3", | ||
"version": "2.1.0-beta.0", | ||
"description": "A drop-in replacement library for enum, tiny and powerful, like native enum but much more than that", | ||
@@ -18,4 +18,5 @@ "keywords": [ | ||
"license": "MIT", | ||
"author": "shijistar@gmail.com", | ||
"author": "李凤宝(Leo) <shijistar@gmail.com>", | ||
"main": "lib/index.js", | ||
"module": "es/index.js", | ||
"types": "lib/index.d.ts", | ||
@@ -29,30 +30,16 @@ "files": [ | ||
"build": "run-p build:lib build:es", | ||
"build:es": "tsc -p tsconfig.es.json", | ||
"build:lib": "tsc -p tsconfig.lib.json", | ||
"build:es": "tsc -p tsconfig.es.json", | ||
"build:test": "tsc -p tsconfig.test.json", | ||
"prepublishOnly": "npm run test && npm run build", | ||
"test": "jest" | ||
"test": "jest", | ||
"prepare": "husky" | ||
}, | ||
"prettier": "./.prettierrc.json", | ||
"dependencies": {}, | ||
"devDependencies": { | ||
"@types/jest": "29.1.1", | ||
"@typescript-eslint/eslint-plugin": "5.39.0", | ||
"@typescript-eslint/parser": "5.39.0", | ||
"eslint": "8.24.0", | ||
"eslint-config-prettier": "8.5.0", | ||
"eslint-config-standard": "17.0.0", | ||
"eslint-plugin-eslint-comments": "3.2.0", | ||
"eslint-plugin-import": "2.26.0", | ||
"eslint-plugin-jest": "27.1.1", | ||
"eslint-plugin-node": "11.1.0", | ||
"eslint-plugin-prettier": "4.0.0", | ||
"eslint-plugin-promise": "6.0.1", | ||
"jest": "29.1.2", | ||
"lodash": "4.17.21", | ||
"npm-run-all": "4.1.5", | ||
"prettier": "2.7.1", | ||
"prettier-plugin-packagejson": "2.3.0", | ||
"ts-jest": "29.0.3", | ||
"typescript": "4.8.4" | ||
"@tiny-codes/code-style-all-in-one": "^1.1.1", | ||
"@types/jest": "^29.5.14", | ||
"jest": "^29.7.0", | ||
"npm-run-all2": "^7.0.2", | ||
"ts-jest": "^29.2.5", | ||
"typescript": "^5.7.3" | ||
}, | ||
@@ -59,0 +46,0 @@ "publishConfig": { |
202
README.md
@@ -14,3 +14,3 @@ <!-- markdownlint-disable MD009 --> | ||
⬇️ [Introduction](#introduction) | [Features](#features) | [Installation](#installation) | [Enum Definition](#enum-definition) | [API](#api) | [Usage](#usage) | [Localization](#localization) ⬇️ | ||
⬇️ [Introduction](#introduction) | [Features](#features) | [Installation](#installation) | [Enum Definition](#enum-definition) | [API](#api) | [Usage](#usage) | [Localization](#localization) | [Global Extension](#global-extension) ⬇️ | ||
@@ -29,7 +29,8 @@ ## Introduction | ||
- 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 | ||
- Support extending display text for enum items | ||
- Supports localization of display texts, is compatible with any internationalization library | ||
- Supports 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 | ||
- Supports binding enums to [Ant Design](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 | ||
- Supports Node.js environment, supports server-side rendering (SSR) | ||
- Zero dependencies, pure native JavaScript, can be applied to any front-end framework | ||
@@ -116,3 +117,3 @@ - 100% TypeScript implementation, good support for type inference | ||
Week.Monday; // 'Monday' | ||
Week.label('Monday'); // Monday | ||
Week.label(/*key*/ 'Monday'); // Monday, output display text | ||
``` | ||
@@ -215,23 +216,29 @@ | ||
### options | ||
### toSelect | ||
<sup>**_[Function]_**</sup> `options(config?: OptionsConfig): {value, label}[]` | ||
<sup>**_[Function]_**</sup> `toSelect(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 | ||
`toSelect` is similar to `values`, both return an array containing all enum items. The difference is that the elements returned by `toSelect` only contain the `label` and `value` fields. At the same time, the `toSelect` 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 | ||
### toMenu | ||
<sup>**_[Function]_**</sup> `valuesEnum(): Record<V, { text: string }>` | ||
<sup>**_[Function]_**</sup> `toMenu(): { key, label }[]` | ||
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` | ||
Generate an object array that can be bound to the `Menu`, `Dropdown` components of [Ant Design](https://ant.design/components/menu) | ||
```js | ||
import { Menu } from 'antd'; | ||
<Menu items={Week.toMenu()} />; | ||
``` | ||
The data format is: | ||
```js | ||
{ | ||
0: { text: 'Sunday' }, | ||
1: { text: 'Monday' }, | ||
} | ||
[ | ||
{ key: 0, label: 'Sunday' }, | ||
{ key: 1, label: 'Monday' }, | ||
]; | ||
``` | ||
@@ -241,7 +248,7 @@ | ||
### filters | ||
### toFilter | ||
<sup>**_[Function]_**</sup> `filters(): { text, value }[]` | ||
<sup>**_[Function]_**</sup> `toFilter(): { 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 | ||
Generate an array of filters that can be passed directly to the `Column.filters` of the [Ant Design](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 | ||
@@ -259,2 +266,19 @@ The data format is: | ||
### toValueMap | ||
<sup>**_[Function]_**</sup> `toValueMap(): Record<V, { text: string }>` | ||
Generate an enum collection object that conforms to the [Ant Design Pro](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' }, | ||
} | ||
``` | ||
--- | ||
### raw | ||
@@ -291,3 +315,3 @@ | ||
const weekValue: typeof Week.valueType = 1; | ||
const weeks: typeof Week.valueType[] = [0, 1]; | ||
const weeks: (typeof Week.valueType)[] = [0, 1]; | ||
type WeekValues = typeof Week.valueType; // 0 | 1 | ||
@@ -308,3 +332,3 @@ ``` | ||
const weekKey: typeof Week.keyType = 'Monday'; | ||
const weekKeys: typeof Week.keyType[] = ['Sunday', 'Monday']; | ||
const weekKeys: (typeof Week.keyType)[] = ['Sunday', 'Monday']; | ||
type WeekKeys = typeof Week.keyType; // 'Sunday' | 'Monday' | ||
@@ -329,3 +353,3 @@ ``` | ||
#### Access enum items, consistent with native enum usage | ||
#### Pick enum values, consistent with native enum usage | ||
@@ -344,5 +368,5 @@ ```js | ||
#### Keep Jsdoc comments, more friendly code hints | ||
#### Support 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 | ||
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 you can also see the detailed Jsdoc comments of each one. | ||
@@ -361,10 +385,10 @@ ```js | ||
HttpCodes.E404; // Hover over E404 to display Jsdoc documentation | ||
HttpCodes.E404; // Hover over E404 to display full Jsdoc comments | ||
``` | ||
> 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) | ||
> In the above example, the interpretation of Http status is referenced from [MDN](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status) | ||
--- | ||
#### Get array of enum items | ||
#### Get an array of all enum items | ||
@@ -381,3 +405,3 @@ ```js | ||
#### Get the value of the first enum item | ||
#### Get the first enum value | ||
@@ -390,7 +414,7 @@ ```js | ||
#### Determine whether a certain value is included in the enum | ||
#### Check if a value is a valid enum value | ||
```js | ||
Week.has(1); // true | ||
Week.values.some(item => item.value === 1); // true | ||
Week.has(1); // true | ||
1 instance of Week; // true | ||
@@ -411,3 +435,3 @@ ``` | ||
#### Support traversing the array of enum items, but not modifying | ||
#### Support traversing enum items array, readonly | ||
@@ -428,3 +452,3 @@ ```js | ||
#### Get the display text of a certain value | ||
#### Get enum display text by value (or key) | ||
@@ -439,3 +463,3 @@ ```js | ||
#### Get the key of a certain enum item | ||
#### Get enum key by value | ||
@@ -445,3 +469,3 @@ ```js | ||
Week.key(Week.Monday); // 'Monday', this is label, not key | ||
Week.key(9); // undefined, not found | ||
Week.key(9); // undefined, because it does not exist | ||
``` | ||
@@ -451,3 +475,3 @@ | ||
#### Add custom fields | ||
#### Extend custom fields, unlimited | ||
@@ -470,6 +494,8 @@ ```js | ||
[AntDesign](https://ant.design/components/select-cn) Select | ||
[Ant Design](https://ant.design/components/select) | [Arco Design](https://arco.design/react/en-US/components/select) | ||
Select | ||
```jsx | ||
```tsx | ||
import { Select } from 'antd'; | ||
<Select options={Week.values} />; | ||
@@ -480,4 +506,5 @@ ``` | ||
```jsx | ||
import { Select, MenuItem } from '@mui/material'; | ||
```tsx | ||
import { MenuItem, Select } from '@mui/material'; | ||
<Select> | ||
@@ -492,21 +519,28 @@ {Week.values.map((item) => ( | ||
[Kendo UI](https://www.telerik.com/kendo-angular-ui/components/dropdowns/select/) Select | ||
[Kendo UI](https://www.telerik.com/kendo-react-ui/components/dropdowns/dropdownlist) Select | ||
```jsx | ||
```tsx | ||
import { DropDownList } from '@progress/kendo-react-dropdowns'; | ||
<DropDownList data={Week.values} textField="label" dataItemKey="value" />; | ||
``` | ||
[ElementPlus](https://element-plus.org/zh-CN/component/select.html) Select | ||
[ElementPlus](https://element-plus.org/en-US/component/select.html) Select | ||
```jsx | ||
```tsx | ||
<el-select> | ||
<el-option v-for="item in Week.values" :key="item.value" :label="item.label" :value="item.value" /> | ||
<el-option v-for="item in Week.values" v-bind="item" /> | ||
</el-select> | ||
``` | ||
[Ant Design Vue](https://antdv.com/components/select) | [Arc Design](https://arco.design/vue/en-US/component/select) Select | ||
```tsx | ||
<a-select :options="Week.values" /> | ||
``` | ||
[Vuetify](https://vuetifyjs.com/en/components/selects/) Select | ||
```jsx | ||
<v-select :items="Week.values" item-title="label" item-value="value" /> | ||
```tsx | ||
<v-select :items="Week.values" item-title="label" /> | ||
``` | ||
@@ -534,3 +568,3 @@ | ||
- `options` method is similar to `values`, but is allowed to add a default option at the top. The default option can be a boolean value or a custom object. | ||
- `toSelect` method is similar to `values`, but is allowed to add a default option at the top. The default option can be a boolean value or a custom object. | ||
@@ -540,4 +574,4 @@ - If set to a boolean value, the default option is `{ value: '', label: 'All' }`, the display name only supports English. If you need localization, please parse and process the built-in resource key `enum-plus.options.all` in the localization method. For more details about localization, please refer to the [Localization](#localization) section | ||
```jsx | ||
<Select options={Week.options({ firstOption: true })} /> | ||
```tsx | ||
<Select options={Week.toSelect({ firstOption: true })} /> | ||
// [ | ||
@@ -550,16 +584,18 @@ // { value: '', label: 'All' }, | ||
// Add custom option at the top | ||
<Select options={Week.options({ firstOption: { value: 0, label: 'Unlimited' } })} /> | ||
<Select options={Week.toSelect({ 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 }[]` | ||
- `toMenu` method can generate data sources for [Ant Design](https://github.com/ant-design/ant-design) `Menu`, `Dropdown` components, the format is: `{ key: number|string, label: string } []` | ||
```jsx | ||
```tsx | ||
import { Menu } from 'antd'; | ||
<Menu items={Week.menus()} />; | ||
<Menu items={Week.toMenu()} />; | ||
``` | ||
- `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 }[]` | ||
- `toFilter` method can generate an object array for binding the `column filter` function to the table, displaying a dropdown filter box in the table header to filter table data. The object structure follows the data specification of [Ant Design](https://ant.design/components/table#table-demo-head) Table component, the format is: `{ text: string, value: number|string } []` | ||
```jsx | ||
```tsx | ||
import { Table } from 'antd'; | ||
const columns = [ | ||
@@ -569,3 +605,3 @@ { | ||
dataIndex: 'week', | ||
filters: Week.filters(), | ||
filters: Week.toFilter(), | ||
}, | ||
@@ -577,6 +613,7 @@ ]; | ||
- `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 } }` | ||
- `toValueMap` method can generate data sources for `ProFormFields`, `ProTable` components of [Ant Design Pro](https://github.com/ant-design/pro-components), which is a data structure similar to `Map`, the format is: `{ [key: number|string]: { text: string } }` | ||
```jsx | ||
```tsx | ||
import { ProTable } from '@ant-design/pro-components'; | ||
<ProFormSelect valueEnum={Week.valuesEnum()} />; | ||
@@ -615,3 +652,3 @@ ``` | ||
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 | ||
names?: (typeof Week.keyType)[]; // 👍 Component property type constraint, prevent erroneous assignment, and also prompt which values are valid | ||
}; | ||
@@ -626,3 +663,3 @@ ``` | ||
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: | ||
We know that there are methods like `label`, `key`, `toSelect` 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: | ||
@@ -735,1 +772,46 @@ ```js | ||
``` | ||
--- | ||
## Global Extension | ||
`Enum` has provided some helpful methods, but if these methods are not enough to you, you can add custom extension functions via the `Enum.extend` method. These extension methods will be added to all enum types, even if the enum type has been created before the extension, it will take effect immediately | ||
_**App.ts**_ | ||
```tsx | ||
Enum.extend({ | ||
isWeekend() { | ||
return this.value === 0 || this.value === 6; | ||
}, | ||
reversedValues(this: ReturnType<typeof Enum>) { | ||
return this.values.reverse(); | ||
}, | ||
}); | ||
``` | ||
If you are using TypeScript, you probably need to further extend the enum type declaration to get better type hints. Create or edit a declaration file in your project (e.g. `global.d.ts`) and extend the global type. This file can be placed in the root directory of the project or any other directory, just make sure TypeScript can find it | ||
_**global.d.ts**_ | ||
```tsx | ||
import type { EnumItemInit } from 'enum-plus'; | ||
import type { EnumItemClass } from 'enum-plus/lib/enum-item'; | ||
declare global { | ||
export interface EnumExtension<T, K, V> { | ||
isWeekend: (value: number) => boolean; | ||
reversedValues: () => EnumItemClass<EnumItemInit<V>, K, V>[]; | ||
} | ||
} | ||
``` | ||
Please note that you are not required to import types such as `EnumItemInit` and `EnumItemClass`, they are only used in this example to provide better type hints | ||
`EnumExtension` is a generic interface that accepts three type parameters, which are: | ||
- `T`: Initialization object of the enum type | ||
- `K`: Key value of the enum item | ||
- `V`: Value of the enum item | ||
If you want to provide more friendly type hints in the extension methods, you may need to use these type parameters. These are all optional, if your extension method is as simple as `isWeekend`, you can completely ignore them |
@@ -14,3 +14,3 @@ <!-- markdownlint-disable MD009 --> | ||
⬇️ [简介](#简介) | [特性](#特性) | [安装](#安装) | [枚举定义](#枚举定义) | [API](#api) | [使用方法](#使用方法) | [本地化](#本地化) ⬇️ | ||
⬇️ [简介](#简介) | [特性](#特性) | [安装](#安装) | [枚举定义](#枚举定义) | [API](#api) | [使用方法](#使用方法) | [本地化](#本地化) | [全局扩展](#全局扩展) ⬇️ | ||
@@ -30,6 +30,7 @@ ## 简介 | ||
- 支持枚举项扩展显示文本 | ||
- 显示文本支持本地化,可以使用任意国际化类库 | ||
- 支持本地化显示文本,可以使用任意国际化类库 | ||
- 支持枚举值转换为显示文本,代码更简洁 | ||
- 枚举项支持扩展任意个自定义字段 | ||
- 支持将枚举绑定到 [AntDesign](https://ant.design/components/overview-cn)、[ElementPlus](https://element-plus.org/zh-CN/component/select.html)、[Material-UI](https://mui.com/material-ui) 或任意其它组件库,只要一行代码 | ||
- 支持将枚举绑定到 [Ant Design](https://ant-design.antgroup.com/components/overview-cn)、[ElementPlus](https://element-plus.org/zh-CN/component/select.html)、[Material-UI](https://mui.com/material-ui) 或任意其它组件库,只要一行代码 | ||
- 支持 Node.js 环境,支持服务端渲染(SSR) | ||
- 零依赖,纯原生 JavaScript,可以应用在任意前端框架中 | ||
@@ -160,3 +161,3 @@ - 100% TypeScript 实现,支持类型推断 | ||
获取一个包含全部枚举项的只读数组,可以方便地遍历枚举项。由于符合 [AntDesign](https://github.com/ant-design/ant-design) 组件的数据规范,因此支持将枚举一键转换成下拉框、复选框等组件,只需要一行代码,更多详情可以参考后面的例子 | ||
获取一个包含全部枚举项的只读数组,可以方便地遍历枚举项。由于符合 [Ant Design](https://github.com/ant-design/ant-design) 组件的数据规范,因此支持将枚举一键转换成下拉框、复选框等组件,只需要一行代码,更多详情可以参考后面的例子 | ||
@@ -213,23 +214,29 @@ --- | ||
### options | ||
### toSelect | ||
<sup>**_[方法]_**</sup> `options(config?: OptionsConfig): {value, label}[]` | ||
<sup>**_[方法]_**</sup> `toSelect(config?: OptionsConfig): {value, label}[]` | ||
`options`与`values`相似,都是返回一个包含全部枚举项的数组。区别是,options 返回的元素只包含`label`和`value`两个字段,同时,options 方法支持在数组头部插入一个默认元素,一般用于下拉框等组件的默认选项,表示全部、无值或不限等,当然你也能够自定义这个默认选项 | ||
`toSelect`与`values`相似,都是返回一个包含全部枚举项的数组。区别是,`toSelect`返回的元素只包含`label`和`value`两个字段,同时,`toSelect`方法支持在数组头部插入一个默认元素,一般用于下拉框等组件的默认选项,表示全部、无值或不限等,当然你也能够自定义这个默认选项 | ||
--- | ||
### valuesEnum | ||
### toMenu | ||
<sup>**_[方法]_**</sup> `valuesEnum(): Record<V, { text: string }>` | ||
<sup>**_[方法]_**</sup> `toMenu(): { key, label }[]` | ||
生成一个符合 [AntDesignPro](https://procomponents.ant.design/components/schema#valueenum) 规范的枚举集合对象,可以传递给 `ProFormField`、`ProTable` 组件。 | ||
生成一个对象数组,可以绑定给 [Ant Design](https://ant-design.antgroup.com/components/menu-cn) 的`Menu`、`Dropdown`等组件 | ||
```js | ||
import { Menu } from 'antd'; | ||
<Menu items={Week.toMenu()} />; | ||
``` | ||
数据格式为: | ||
```js | ||
{ | ||
0: { text: '星期日' }, | ||
1: { text: '星期一' }, | ||
} | ||
[ | ||
{ key: 0, label: '星期日' }, | ||
{ key: 1, label: '星期一' }, | ||
]; | ||
``` | ||
@@ -239,7 +246,7 @@ | ||
### filters | ||
### toFilter | ||
<sup>**_[方法]_**</sup> `filters(): { text, value }[]` | ||
<sup>**_[方法]_**</sup> `toFilter(): { text, value }[]` | ||
生成一个 filters 数组,可以直接传递给 [AntDesign](https://ant.design/components/table-cn#table-demo-head) Table 组件的列配置,在表头中显示一个下拉筛选框,用来过滤表格数据 | ||
生成一个 filters 数组,可以直接传递给 [Ant Design](https://ant-design.antgroup.com/components/table-cn#table-demo-head) Table 组件的列配置,在表头中显示一个下拉筛选框,用来过滤表格数据 | ||
@@ -257,2 +264,19 @@ 数据格式为: | ||
### toValueMap | ||
<sup>**_[方法]_**</sup> `toValueMap(): Record<V, { text: string }>` | ||
生成一个符合 [Ant Design Pro](https://procomponents.ant.design/components/schema#valueenum) 规范的枚举集合对象,可以传递给 `ProFormField`、`ProTable` 等组件。 | ||
数据格式为: | ||
```js | ||
{ | ||
0: { text: '星期日' }, | ||
1: { text: '星期一' }, | ||
} | ||
``` | ||
--- | ||
### raw | ||
@@ -289,3 +313,3 @@ | ||
const weekValue: typeof Week.valueType = 1; | ||
const weeks: typeof Week.valueType[] = [0, 1]; | ||
const weeks: (typeof Week.valueType)[] = [0, 1]; | ||
type WeekValues = typeof Week.valueType; // 0 | 1 | ||
@@ -306,3 +330,3 @@ ``` | ||
const weekKey: typeof Week.keyType = 'Monday'; | ||
const weekKeys: typeof Week.keyType[] = ['Sunday', 'Monday']; | ||
const weekKeys: (typeof Week.keyType)[] = ['Sunday', 'Monday']; | ||
type WeekKeys = typeof Week.keyType; // 'Sunday' | 'Monday' | ||
@@ -327,3 +351,3 @@ ``` | ||
#### 访问枚举项,与原生枚举用法一致 | ||
#### 拾取枚举值,与原生枚举用法一致 | ||
@@ -342,3 +366,3 @@ ```js | ||
#### 可保留 Jsdoc 注释,代码提示更友好 | ||
#### 支持添加 Jsdoc 注释,代码提示更友好 | ||
@@ -359,3 +383,3 @@ 在代码编辑器中,将光标悬停在枚举项上,即可显示关于该枚举项的详细 Jsdoc 注释,而不必再转到枚举定义处查看。另外,在输入`HttpCodes.`时,编辑器也会自动提示枚举项列表,通过键盘上下键切换枚举项,也可以展示详细信息 | ||
HttpCodes.E404; // 将光标悬停在 E404 上,将显示Jsdoc文档注释 | ||
HttpCodes.E404; // 将光标悬停在 E404 上,将显示完整的Jsdoc文档注释 | ||
``` | ||
@@ -367,3 +391,3 @@ | ||
#### 获取枚举项数组 | ||
#### 获取包含全部枚举项的数组 | ||
@@ -380,3 +404,3 @@ ```js | ||
#### 获取第一个枚举项的值 | ||
#### 获取第一个枚举值 | ||
@@ -389,7 +413,7 @@ ```js | ||
#### 判断枚举中是否包含某个值 | ||
#### 检查一个值是否一个有效的枚举值 | ||
```js | ||
Week.has(1); // true | ||
Week.values.some(item => item.value === 1); // true | ||
Week.has(1); // true | ||
1 instance of Week; // true | ||
@@ -426,3 +450,3 @@ ``` | ||
#### 获取某个值的显示文本 | ||
#### 枚举值(或Key)转换为显示文本 | ||
@@ -437,3 +461,3 @@ ```js | ||
#### 获取某个枚举项的 key | ||
#### 枚举值转换为Key | ||
@@ -443,3 +467,3 @@ ```js | ||
Week.key(Week.Monday); // 'Monday' | ||
Week.key(9); // undefined, 不存在 | ||
Week.key(9); // undefined, 因为不存在 | ||
``` | ||
@@ -449,3 +473,3 @@ | ||
#### 添加扩展字段 | ||
#### 添加扩展字段,数量无限制 | ||
@@ -468,6 +492,8 @@ ```js | ||
[AntDesign](https://ant.design/components/select-cn) Select | ||
[Ant Design](https://ant-design.antgroup.com/components/select-cn) | [Arco Design](https://arco.design/react/components/select) | ||
Select | ||
```jsx | ||
```tsx | ||
import { Select } from 'antd'; | ||
<Select options={Week.values} />; | ||
@@ -478,4 +504,5 @@ ``` | ||
```jsx | ||
import { Select, MenuItem } from '@mui/material'; | ||
```tsx | ||
import { MenuItem, Select } from '@mui/material'; | ||
<Select> | ||
@@ -490,6 +517,7 @@ {Week.values.map((item) => ( | ||
[Kendo UI](https://www.telerik.com/kendo-angular-ui/components/dropdowns/select/) Select | ||
[Kendo UI](https://www.telerik.com/kendo-react-ui/components/dropdowns/dropdownlist) Select | ||
```jsx | ||
```tsx | ||
import { DropDownList } from '@progress/kendo-react-dropdowns'; | ||
<DropDownList data={Week.values} textField="label" dataItemKey="value" />; | ||
@@ -500,14 +528,20 @@ ``` | ||
```jsx | ||
```tsx | ||
<el-select> | ||
<el-option v-for="item in Week.values" :key="item.value" :label="item.label" :value="item.value" /> | ||
<el-option v-for="item in Week.values" v-bind="item" /> | ||
</el-select> | ||
``` | ||
[Vuetify](https://vuetifyjs.com/en/components/selects/) Select | ||
[Ant Design Vue](https://antdv.com/components/select-cn) | [Arc Design](https://arco.design/vue/component/select) Select | ||
```jsx | ||
<v-select :items="Week.values" item-title="label" item-value="value" /> | ||
```tsx | ||
<a-select :options="Week.values" /> | ||
``` | ||
[Vuetify](https://vuetifyjs.com/zh-Hans/components/selects) Select | ||
```tsx | ||
<v-select :items="Week.values" item-title="label" /> | ||
``` | ||
[Angular Material](https://material.angular.io/components/select/overview) Select | ||
@@ -533,3 +567,3 @@ | ||
- `options`方法与`values`类似,但允许在头部增加一个默认选项。默认选项可以是一个布尔值,也可以是一个自定义对象。 | ||
- `toSelect`方法与`values`类似,但允许在头部增加一个默认选项。默认选项可以是一个布尔值,也可以是一个自定义对象。 | ||
@@ -539,4 +573,4 @@ - 如果是布尔值,则默认选项为`{ value: '', label: 'All' }`,显示名称只支持英文。如果希望支持本地化,请在本地化方法中解析并处理`enum-plus.options.all`这个内置资源。关于本地化的更多详情,请参考[本地化](#本地化)章节 | ||
```jsx | ||
<Select options={Week.options({ firstOption: true })} /> | ||
```tsx | ||
<Select options={Week.toSelect({ firstOption: true })} /> | ||
// [ | ||
@@ -549,16 +583,18 @@ // { value: '', label: 'All' }, | ||
// 自定义头部默认选项 | ||
<Select options={Week.options({ firstOption: { value: 0, label: '不限' } })} /> | ||
<Select options={Week.toSelect({ firstOption: { value: 0, label: '不限' } })} /> | ||
``` | ||
- `menus`方法可以为 [AntDesign](https://github.com/ant-design/ant-design) `Menu`、`Dropdown` 等组件生成数据源,格式为:`{ key: number|string, label: string }[]` | ||
- `toMenu`方法可以为 [Ant Design](https://github.com/ant-design/ant-design) `Menu`、`Dropdown` 等组件生成数据源,格式为:`{ key: number|string, label: string } []` | ||
```jsx | ||
```tsx | ||
import { Menu } from 'antd'; | ||
<Menu items={Week.menus()} />; | ||
<Menu items={Week.toMenu()} />; | ||
``` | ||
- `filters`方法可以为 [AntDesign](https://github.com/ant-design/ant-design) `Table` 组件的`列筛选`功能生成数据源,格式为:`{ text: string, value: number|string }[]` | ||
- `toFilter`方法可以生成一个对象数组,为表格绑定`列筛选`功能,列头中显示一个下拉筛选框,用来过滤表格数据。对象结构遵循 [Ant Design](https://ant-design.antgroup.com/components/table-cn#table-demo-head) 的数据规范,格式为:`{ text: string, value: number|string } []` | ||
```jsx | ||
```tsx | ||
import { Table } from 'antd'; | ||
const columns = [ | ||
@@ -568,3 +604,3 @@ { | ||
dataIndex: 'week', | ||
filters: Week.filters(), | ||
filters: Week.toFilter(), | ||
}, | ||
@@ -576,7 +612,8 @@ ]; | ||
- `valuesEnum`方法可以为 [AntDesignPro](https://github.com/ant-design/pro-components) 的`ProFormFields`、`ProTable`等组件生成数据源,这是一个类似 Map 的数据结构,格式为:`{ [key: number|string]: { text: string } }` | ||
- `toValueMap`方法可以为 [Ant Design Pro](https://github.com/ant-design/pro-components) 的`ProFormFields`、`ProTable`等组件生成数据源,这是一个类似 Map 的数据结构,格式为:`{ [key: number|string]: { text: string } }` | ||
```jsx | ||
```tsx | ||
import { ProTable } from '@ant-design/pro-components'; | ||
<ProFormSelect valueEnum={Week.valuesEnum()} />; | ||
<ProFormSelect valueEnum={Week.toValueMap()} />; | ||
``` | ||
@@ -614,3 +651,3 @@ | ||
value?: typeof Week.valueType; // 👍 组件属性类型约束,可以防止错误赋值,还能智能提示有效值有哪些 | ||
names?: typeof Week.keyType[]; // 👍 组件属性类型约束,可以防止错误赋值,还能智能提示有效值有哪些 | ||
names?: (typeof Week.keyType)[]; // 👍 组件属性类型约束,可以防止错误赋值,还能智能提示有效值有哪些 | ||
}; | ||
@@ -625,3 +662,3 @@ ``` | ||
我们知道枚举类型上还存在 `label`、`key`、`options` 等方法,如果与某个枚举项重名,枚举项的值优先级更高,会覆盖掉这些方法。但不用担心,你可以在 `values` 下访问到它们。请参考下面的代码示例: | ||
我们知道枚举类型上还存在 `label`、`key`、`toSelect` 等方法,如果与某个枚举项重名,枚举项的值优先级更高,会覆盖掉这些方法。但不用担心,你可以在 `values` 下访问到它们。请参考下面的代码示例: | ||
@@ -734,1 +771,46 @@ ```js | ||
``` | ||
--- | ||
## 全局扩展 | ||
`Enum`已经提供了一些常用的方法,但如果这些方法还不能满足你的需求,你可以通过 `Enum.extend` 方法来添加自定义扩展函数。这些扩展方法将会被添加到所有的枚举类型上,即便是在扩展之前已经创建的枚举类型,也会立即生效 | ||
_**App.ts**_ | ||
```tsx | ||
Enum.extend({ | ||
isWeekend() { | ||
return this.value === 0 || this.value === 6; | ||
}, | ||
reversedValues(this: ReturnType<typeof Enum>) { | ||
return this.values.reverse(); | ||
}, | ||
}); | ||
``` | ||
如果你在使用 TypeScript,你可能需要再扩展一下枚举类型声明,这样可以获得更好的类型提示。在你的项目中创建或编辑一个声明文件(例如 `global.d.ts`),并在其中扩展全局类型。此文件可以放在项目的根目录或任意目录下,只要确保 TypeScript 能够找到它 | ||
_**global.d.ts**_ | ||
```tsx | ||
import type { EnumItemInit } from 'enum-plus'; | ||
import type { EnumItemClass } from 'enum-plus/lib/enum-item'; | ||
declare global { | ||
export interface EnumExtension<T, K, V> { | ||
isWeekend: (value: number) => boolean; | ||
reversedValues: () => EnumItemClass<EnumItemInit<V>, K, V>[]; | ||
} | ||
} | ||
``` | ||
请注意,你不是必须导入`EnumItemInit`和`EnumItemClass`这些类型,这些仅在这个示例中被使用,为了添加更友好的类型提示。 | ||
`EnumExtension`接口是一个泛型接口,它接受三个类型参数,分别是: | ||
- `T`: 枚举类型的初始化对象 | ||
- `K`: 枚举项的键值 | ||
- `V`: 枚举项的值 | ||
如果你希望在扩展方法中提供更友好的类型提示,你或许可能需要使用到这些类型参数。这些都是可选的,如果你的扩展方法像`isWeekend`这样简单,那么你完全可以忽略它们 |
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
Unpublished package
Supply chain riskPackage version was not found on the registry. It may exist on a different registry and need to be configured to pull from that registry.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
Unpopular package
QualityThis package is not very popular.
Found 1 instance in 1 package
178715
6
2315
0
789
1
2