-
Notifications
You must be signed in to change notification settings - Fork 2
/
EnumTypeConverter.ts
85 lines (73 loc) · 2.14 KB
/
EnumTypeConverter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module TypeConverters
*/
import type {
EnumerationChoice,
EnumerationChoicesInfo,
Primitives,
PropertyDescription,
} from "@itwin/appui-abstract";
import { StandardTypeNames } from "@itwin/appui-abstract";
import { TypeConverter } from "./TypeConverter";
import { TypeConverterManager } from "./TypeConverterManager";
/**
* Enum Type Converter.
* @public
*/
export class EnumTypeConverter extends TypeConverter {
public override convertPropertyToString(
propertyDescription: PropertyDescription,
value?: Primitives.Enum
): string | Promise<string> {
if (value === undefined) return "";
if (propertyDescription.enum) {
return this.getMatchingStringValue(propertyDescription.enum, value);
}
return super.convertToString(value);
}
private async getMatchingStringValue(
enumVal: EnumerationChoicesInfo,
value: Primitives.Enum
) {
let choices: EnumerationChoice[] = [];
if (enumVal.choices instanceof Promise) {
choices = await enumVal.choices;
} else {
choices = enumVal.choices;
}
const pos = this.getPosition(choices, value);
if (-1 !== pos) return choices[pos].label;
return this.convertToString(value);
}
private getPosition(
choices: EnumerationChoice[],
value: Primitives.Enum
): number {
for (let i = 0; i < choices.length; ++i) {
if (choices[i].value === value) return i;
}
return -1;
}
public sortCompare(
a: Primitives.Enum,
b: Primitives.Enum,
ignoreCase?: boolean
): number {
if (isNaN(+a) || isNaN(+b)) {
return TypeConverterManager.getConverter("string").sortCompare(
a,
b,
ignoreCase
);
}
return +a - +b;
}
}
TypeConverterManager.registerConverter(
StandardTypeNames.Enum,
EnumTypeConverter
);