-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsite.ts
242 lines (212 loc) · 7.63 KB
/
site.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
* @license
* Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import * as childProcess from "child_process";
import * as fs from 'fs-extra';
import * as path from 'path';
import globcb = require('glob');
import { promisify } from 'util';
import frontMatter = require('front-matter');
import marked = require('marked');
import Prism = require('prismjs');
const glob = promisify(globcb);
const exec = promisify(childProcess.exec);
/**
* Adds classes to the <pre> elements
*/
class CustomRenderer extends marked.Renderer {
code(code: string, language: string, _isEscaped: boolean) {
const prismLanguage = Prism.languages[language];
const highlighted = (prismLanguage === undefined)
? code
: Prism.highlight(code, prismLanguage);
return html`<pre class="code language-${language}" language="${language}">
${highlighted}
</pre>`;
}
}
marked.setOptions({
renderer: new CustomRenderer(),
});
const docsOutDir = path.resolve(__dirname, '../../docs');
const docsSrcDir = path.resolve(__dirname, '../../docs-src');
const root = 'lit-html';
type FileData = {
path: path.ParsedPath;
outPath: string;
attributes: any;
body: string;
}
async function generateDocs() {
await fs.emptyDir(docsOutDir);
const fileNames = await glob('**/*.md', { cwd: docsSrcDir });
// Read in all file data
const files = new Map<string, FileData>(await Promise.all(fileNames.map(async (fileName) => {
const filePath = path.parse(fileName);
const content = await fs.readFile(path.join(docsSrcDir, fileName), 'utf-8');
const pageData = frontMatter(content);
const outPath = `${filePath.dir}/${stripOrdering(filePath.name)}.html`;
return [fileName, {
path: filePath,
outPath,
attributes: pageData.attributes,
body: pageData.body,
}] as [string, FileData];
})));
for (const fileData of files.values()) {
const outDir = path.join(docsOutDir, fileData.path.dir);
await fs.mkdirs(outDir);
const body = marked(fileData.body);
// const section = fileData.path.dir.split(path.sep)[0] || 'home';
const outContent = page(fileData.outPath, body, fileData.attributes, files);
const outPath = path.join(docsOutDir, fileData.outPath);
fs.writeFile(outPath, outContent);
}
fs.copyFileSync(path.join(docsSrcDir, 'index.css'), path.join(docsOutDir, 'index.css'));
fs.copyFileSync(path.resolve(__dirname, '../node_modules/prismjs/themes/prism-okaidia.css'), path.join(docsOutDir, 'prism.css'));
await fs.writeFile(path.join(docsOutDir, '.nojekyll'), '');
await exec('npm run gen-docs', {cwd: '../'});
}
/**
* The main page template
*/
const page = (pagePath: string, content: string, attributes: {[key: string]: string}, files: Map<string, FileData>) => html`
<!doctype html>
<html>
<head>
<title>${attributes.title}</title>
<link rel="stylesheet" href="/${root}/index.css">
<link rel="stylesheet" href="/${root}/prism.css">
</head>
<body>
${sideNav(pagePath, files)}
${topNav(pagePath.split('/')[0])}
<main>
${content}
<main>
<footer>
<p>© 2018 Polymer Authors. Code Licensed under the BSD License. Documentation licensed under CC BY 3.0.</p>
</footer>
</body>
</html>
`;
const topNav = (section: string) => html`
<nav id="top-nav">
<div class="icon-large">lit-html</div>
<ul>
<li ${section === 'home' ? 'class="selected"' : ''}><a href="/${root}/">Home</a></li>
<li ${section === 'guide' ? 'class="selected"' : ''}><a href="/${root}/guide/">Guide</a></li>
<li ${section === 'api' ? 'class="selected"' : ''}><a href="/${root}/api/">API</a></li>
<li><a href="https://github.com/Polymer/lit-html">GitHub</a></li>
</ul>
</nav>
`;
interface Outline extends Map<string, OutlineData> {}
type OutlineData = FileData|Outline;
/**
* Generates an outline of all the files.
*
* The outline is a set of nested maps of filenames to file data.
* The output is sorted with index first, then alpha-by-name
*/
const getOutline = (_pagePath: string, files: Map<string, FileData>) => {
const outline: Outline = new Map();
for (const fileData of files.values()) {
const parts = fileData.path.dir.split(path.sep);
let parent = outline;
for (const part of parts) {
let child = parent.get(part);
if (child === undefined) {
child = new Map() as Outline;
parent.set(part, child);
}
if (child instanceof Map) {
parent = child;
} else {
console.error(child);
throw new Error('oops!');
}
}
parent.set(fileData.path.name, fileData);
}
function sortOutline(unsorted: Outline, sorted: Outline) {
// re-insert index first
sorted.set('index', unsorted.get('index')!);
unsorted.delete('index');
// re-insert other entries in alpha-order
unsorted.forEach((value, key) => {
if (value instanceof Map) {
value = sortOutline(value, new Map());
}
sorted.set(key, value);
});
return sorted;
}
return sortOutline(outline, new Map());
}
const sideNav = (pagePath: string, files: Map<string, FileData>) => {
// Side nav is only rendered for the guide
if (!pagePath.startsWith('guide')) {
return '';
}
// Renders the outline, using the frontmatter from the pages
const renderOutline = (outline: Outline): string => {
return html`
<ul>
${Array.from(outline.entries()).map(([name, data]) => {
// if (name === 'index') {
// return '';
// }
const fileData = (data instanceof Map ? data.get('index') : data) as FileData;
const isFile = !(data instanceof Map);
let url = `/${root}/${fileData.path.dir}/`;
if (isFile) {
url = url + `${stripOrdering(fileData.path.name)}.html`;
}
return html`
<li class="${pagePath === fileData.outPath ? 'selected' : ''}">
<a href="${url}">
${isFile ? fileData.attributes['title'] : name}
</a>
${isFile && pagePath === fileData.outPath ? renderPageOutline(data as FileData) : ''}
${isFile ? '' : renderOutline(data as Outline)}
</li>
`;
})}
</ul>
`;
};
const renderPageOutline = (data: FileData) => {
const tokens = marked.lexer(data.body);
const headers = tokens.filter((t) => t.type === 'heading' && t.depth === 2) as marked.Tokens.Heading[];
return html`
<ul>
${headers.map((header) => {
return html`<li class="page" level="${header.depth}"><a href="#${getId(header.text)}">${header.text.replace('<', '<')}</a></li>`;
})}
</ul>
`;
}
return html`
<nav id="side-nav">
<h1>Guide</h1>
${renderOutline(getOutline(pagePath, files).get('guide') as Outline)}
</nav>
`;
}
// Nearly no-op template tag to get syntax highlighting and support Arrays.
const html = (strings: TemplateStringsArray, ...values: any[]) =>
values.reduce((acc, v, i) => acc + (Array.isArray(v) ? v.join('\n') : String(v)) + strings[i + 1], strings[0]);
const stripOrdering = (filename: string) => filename.replace(/^\d+-/, '');
const getId = (s: string) => s.toLowerCase().replace(/[^\w]+/g, '-');
generateDocs();