-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.ts
107 lines (94 loc) · 2.42 KB
/
utilities.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { Constants, UnsupportedValueError } from './types-and-constants';
/**
* A utility function for joining template strings and extra values.
*
* @internal
* @category Implementation Details
*
* @param strings - The template strings array.
* @param extras - The extra values to join with the template strings.
* @returns The joined string.
*/
export function joinParts(
strings: TemplateStringsArray,
extras: string[]
): string {
let className = '';
let i = 0;
while (true) {
const str = strings[i] || '';
const extra = extras[i] || '';
const next = `${str} ${extra}`.trim();
if (next) {
className += ` ${next}`;
}
i += 1;
if (i >= strings.length && i >= extras.length) {
className = className.trim();
break;
}
}
return className.trim();
}
/**
* Convert a value to a string suitable for use in a CSS declaration.
*
* @internal
* @category Implementation Details
*
* @param value - The value to serialize.
* @returns The serialized value.
* @throws `UnsupportedValueError` - If the value type is not supported.
*/
export function serializeStyleValue(value: unknown): string {
switch (typeof value) {
case 'string': {
const nextValue = value.trim();
if (Constants.CSS_VAR_PATTERN.test(nextValue)) {
return `var(${nextValue})`;
} else {
return nextValue;
}
}
case 'boolean':
case 'number': {
return `${value}`;
}
case 'function': {
return `${serializeStyleValue(value())}`;
}
case 'object': {
if (value === null) {
return '';
}
// explicit fallthrough
}
default: {
const err: UnsupportedValueError = Object.assign(
new Error(`Unsupported value type: ${typeof value}`),
{
name: 'UnsupportedValueError',
value,
}
);
throw err;
}
}
}
/**
* A utility function for serializing cache key values. This function uses `JSON.stringify` to serialize the value. If the value is a function, it will be serialized via `.toString()`.
*
* @internal
* @category Implementation Details
*
* @param value - The cache key value to serialize.
* @returns The serialized cache key value.
*/
export function serializeCacheKeyValue(value: unknown): string {
return JSON.stringify(value, (_, inner) => {
if (typeof inner === 'function') {
return inner.toString();
}
return inner;
});
}