-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathutils.ts
81 lines (69 loc) · 1.88 KB
/
utils.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
import { CalciteIconPath } from "@esri/calcite-ui-icons";
import { getAssetPath } from "@stencil/core";
import { Scale } from "../interfaces";
export interface FetchIconProps {
icon: string;
scale: Scale;
}
/**
* Icon data cache.
* Exported for testing purposes.
*
* @private
*/
export const iconCache: Record<string, CalciteIconPath> = {};
/**
* Icon request cache.
* Exported for testing purposes.
*
* @private
*/
export const requestCache: Record<string, Promise<CalciteIconPath>> = {};
export const scaleToPx: Record<Scale, number> = {
s: 16,
m: 24,
l: 32
};
export async function fetchIcon({ icon, scale }: FetchIconProps): Promise<CalciteIconPath> {
const size = scaleToPx[scale];
const name = normalizeIconName(icon);
const filled = name.charAt(name.length - 1) === "F";
const iconName = filled ? name.substring(0, name.length - 1) : name;
const id = `${iconName}${size}${filled ? "F" : ""}`;
if (iconCache[id]) {
return iconCache[id];
}
if (!requestCache[id]) {
requestCache[id] = fetch(getAssetPath(`./assets/icon/${id}.json`))
.then((resp) => resp.json())
.catch(() => {
console.error(`"${id}" is not a valid calcite-ui-icon name`);
return "";
});
}
const path = await requestCache[id];
iconCache[id] = path;
return path;
}
/**
* Normalize the icon name to match the path data module exports.
* Exported for testing purposes.
*
* @param name
* @private
*/
export function normalizeIconName(name: string): string {
const numberLeadingName = !isNaN(Number(name.charAt(0)));
const parts = name.split("-");
if (parts.length === 1) {
return numberLeadingName ? `i${name}` : name;
}
return parts
.map((part, index) => {
if (index === 0) {
return numberLeadingName ? `i${part.toUpperCase()}` : part;
}
return part.charAt(0).toUpperCase() + part.slice(1);
})
.join("");
}