This repository was archived by the owner on Oct 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
53 lines (47 loc) · 1.61 KB
/
index.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
import { parse, parseFragment, serialize } from '../lib/parse5';
// export const DEFAULT_MINIFY_OPTIONS: htmlMinifier.Options = {
// collapseBooleanAttributes: true,
// collapseWhitespace: true,
// minifyCSS: true,
// minifyJS: true,
// processConditionalComments: true,
// quoteCharacter: '"',
// removeComments: true,
// removeOptionalTags: true,
// removeRedundantAttributes: true,
// removeScriptTypeAttributes: true,
// removeStyleLinkTypeAttributes: true,
// sortAttributes: true,
// sortClassName: true,
// trimCustomFragments: true,
// };
async function processLiterals(strings: TemplateStringsArray, ...exps: any[]): Promise<string> {
const listTask = exps.map(async (n) => {
const tasks = (Array.isArray(n) ? n : [n])
.map(async o => 'function' === typeof(o) ? o() : o);
return Promise.all(tasks);
});
const done = await Promise.all(listTask);
const doneLen = done.length;
return strings.reduce((p, n, i) => {
const nTask = done[i] ;
const joined = Array.isArray(nTask) ? nTask.join('') : nTask;
return `${p}${i >= doneLen ? n : `${n}${joined}`}`;
}, '');
}
async function parsePartial(
fn: typeof parse | typeof parseFragment,
strings: TemplateStringsArray,
...exps: any[]
) {
try {
const content = await processLiterals(strings, ...exps);
return serialize(fn(content));
} catch (e) {
throw e;
}
}
export const html = async (s: TemplateStringsArray, ...e: any[]) =>
parsePartial(c => parse(`<!doctype html>${c}`), s, ...e);
export const htmlFragment = async (s: TemplateStringsArray, ...e: any[]) =>
parsePartial(parseFragment, s, ...e);