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
import { html, RawHTML } from "https://esm.town/v/postpostscript/html";
export function multiFormat<R extends MultiFormat = { text: string }>(
strings: TemplateStringsArray,
...replacements: (string | R)[]
) {
return strings.reduce((res, string, index) => {
let toAdd = { text: string } as R;
if (replacements.length >= index + 1) {
const replacement = replacements[index];
toAdd = combineMultiFormat([
toAdd,
typeof replacement === "string"
? { text: replacement }
: replacement,
]);
}
return combineMultiFormat([res, toAdd]);
}, {
text: "",
} as R);
}
export const DEFAULT_TRANSFORMERS: Transformers<MultiFormatWithHTML> = {
html(value: string) {
if (value instanceof RawHTML) {
return value;
}
return new RawHTML(html`${value}`.replace(/\n/g, "\n<br>")) as string;
},
};
export function combineMultiFormat<R extends MultiFormat>(
values: (R | string)[],
transformers = DEFAULT_TRANSFORMERS as Transformers<R>,
) {
if (values.length === 1) {
return normalizeMultiFormat(values[0]);
}
const keys = new Set(
["text", ...values].map(value => {
return typeof value === "string"
? []
: Object.keys(value);
}).flat(),
);
return Object.fromEntries([...keys].map(key => {
const normalize = transformers[key]
? (value: string) => transformers[key](value)
: (value: string) => value;
return [
key,
values.slice(1).reduce<string>(
(res, value) => {
return addStrings(
res,
isString(value)
? normalize(value)
: getMultiFormatValue(value, key),
);
},
isString(values[0]) ? normalize(values[0]) : getMultiFormatValue(values[0], key, transformers),
),
];
})) as R;
}
export function joinMultiFormat<R extends MultiFormat>(values: (R | string)[], join: R | string) {
if (!values.length) {
return {
text: "",
};
}
let res = normalizeMultiFormat(values[0]);
for (const value of values.slice(1)) {
res = combineMultiFormat([
res,
join,
value,
]);
}
return res;
}
export function normalizeMultiFormat<R extends MultiFormat>(value: R | string | number | boolean | null | undefined) {
if (isString(value)) {
return { text: value };
}
if (typeof value === "object") {
return value;
}
return { text: toString(value) };
}
export function getMultiFormatValue<R extends MultiFormat, K extends keyof R>(
value: R,
key: K,
transformers: Transformers<R> = DEFAULT_TRANSFORMERS,
) {