-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathliterals.ts
71 lines (58 loc) · 2.13 KB
/
literals.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export interface TemplateTag<R = string> {
// Any is the only way here.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(template: TemplateStringsArray, ...substitutions: any[]): R;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function oneLine(strings: TemplateStringsArray, ...values: any[]) {
const endResult = String.raw(strings, ...values);
return endResult.replace(/(?:\r?\n(?:\s*))+/gm, ' ').trim();
}
export function indentBy(indentations: number): TemplateTag {
let i = '';
while (indentations--) {
i += ' ';
}
return (strings, ...values) => {
return i + stripIndent(strings, ...values).replace(/\n/g, '\n' + i);
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function stripIndent(strings: TemplateStringsArray, ...values: any[]) {
const endResult = String.raw(strings, ...values);
// remove the shortest leading indentation from each line
const match = endResult.match(/^[ \t]*(?=\S)/gm);
// return early if there's nothing to strip
if (match === null) {
return endResult;
}
const indent = Math.min(...match.map((el) => el.length));
const regexp = new RegExp('^[ \\t]{' + indent + '}', 'gm');
return (indent > 0 ? endResult.replace(regexp, '') : endResult).trim();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function stripIndents(strings: TemplateStringsArray, ...values: any[]) {
return String.raw(strings, ...values)
.split('\n')
.map((line) => line.trim())
.join('\n')
.trim();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function trimNewlines(strings: TemplateStringsArray, ...values: any[]) {
const endResult = String.raw(strings, ...values);
return (
endResult
// Remove the newline at the start.
.replace(/^(?:\r?\n)+/, '')
// Remove the newline at the end and following whitespace.
.replace(/(?:\r?\n(?:\s*))$/, '')
);
}