-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
547 lines (486 loc) · 17.4 KB
/
index.js
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
const isGithub = window.location.host === "pedroth.github.io";
const NABLA_WORD = isGithub ? "/nabladown.js" : ""
const { maybe, stream } = await import(NABLA_WORD + "/dist/web/index.js")
const { render } = await import(NABLA_WORD + "/dist/web/Render.js")
const { render: codeRender } = await import(NABLA_WORD + "/dist/web/CodeRender/CodeRender.js");
const { render: mathRender } = await import(NABLA_WORD + "/dist/web/MathRender.js");
const { render: nablaRender, renderToString } = await import(NABLA_WORD + "/dist/web/NabladownRender.js");
const { parse } = await import(NABLA_WORD + "/dist/web/Parser.js");
const { tokenizer } = await import(NABLA_WORD + "/dist/web/Lexer.js");
//========================================================================================
/* *
* NABLADOWN LOCAL STORAGE *
* */
//========================================================================================
const NablaLocalStorage = (() => {
const namespace = "nabladown";
return {
getItem: key => {
const ls = localStorage.getItem(namespace) || "{}";
return JSON.parse(ls)[key];
},
setItem: (key, value) => {
const ls = JSON.parse(localStorage.getItem(namespace)) || {};
ls[key] = value;
localStorage.setItem(namespace, JSON.stringify(ls));
return this;
}
};
})();
//========================================================================================
/* *
* UTILS *
* */
//========================================================================================
function debounce(lambda, debounceTimeInMillis = 500) {
let timerId;
return function (...vars) {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
lambda(...vars);
}, debounceTimeInMillis);
return true;
};
}
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
async function getTimedValue(lambda) {
const t = performance.now();
const value = await lambda()
return [value, 1e-3 * (performance.now() - t)];
}
/**
* () => Maybe<Worker>
*/
function getParseWorker() {
return maybe(window.Worker)
.map(() => isGithub
? new Worker("/nabladown.js/worker.js", { type: "module" })
: new Worker("/worker.js", { type: "module" })
)
.map(parseWorker => {
parseWorker.onmessage = e => {
console.log("Message received from worker", e);
const { ast, time, inputText } = e.data;
selectedRender(ast, inputText);
console.log(`Parsed in ${time} seconds`);
};
return parseWorker;
})
}
async function getInput() {
const NABLA_DOC_ADDRESS = "/test/resources/test2.nd";
return (
getURLData() ||
NablaLocalStorage.getItem("input") ||
await fetch(NABLA_DOC_ADDRESS)
.then(data => {
if (!data.ok) return fetch(NABLA_WORD + NABLA_DOC_ADDRESS)
return data;
})
.then(data => data.text()) ||
"#$\\nabla$ Nabladown`.js`\n <span style='background: blue'>Check it out</span> [here](https://www.github.com/pedroth/nabladown.js)\n"
);
}
function getSelectedRenderName() {
return NablaLocalStorage.getItem("selectedRender") || "Nabla";
}
function downloadNablaDownURL(output) {
const file = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NablaDown Output</title>
</head>
<body>
${output.innerHTML}
</body>
</html>`;
return URL.createObjectURL(
new Blob([file], { type: "text/plain;charset=utf-8" })
);
}
function getURLData() {
const url = window.location.href;
const split = url.split("#text=");
if (split.length <= 1) return undefined;
return decodeURI(split[1]);
}
//========================================================================================
/* *
* UI *
* */
//========================================================================================
function renderFactory({ selectedRender, exportHTMLIcon, output }) {
// render function
return async (tree, input) => {
// save previous scroll before removing children
const previousScroll = NablaLocalStorage.getItem("outputScroll");
removeAllChildNodes(output);
const [outputDOM, time] = await getTimedValue(async () => await selectedRender(tree, input))
output.appendChild(outputDOM);
output.scrollTop = previousScroll;
console.log(`Rendered in ${time} seconds`);
setTimeout(() => {
exportHTMLIcon.children[0].href = downloadNablaDownURL(output)
}, 100);
};
}
async function renderEditor(anchor) {
// eslint-disable-next-line no-undef
require.config({ paths: { vs: './vs-monaco/package/min/vs' } });
return new Promise((re) => {
// eslint-disable-next-line no-undef
require(['vs/editor/editor.main'], function () {
// eslint-disable-next-line no-undef
re(monaco.editor.create(anchor, {
value: "",
fontSize: "16",
theme: "vs-dark",
lineNumbers: "on",
insertSpaces: false,
language: "markdown",
automaticLayout: true,
wordWrap: "wordWrapColumn",
}));
})
});
}
function addEditorEventListener({
editor,
maybeParserWorker
}) {
editor.onDidChangeModelContent(
debounce(() => {
const newInput = editor.getValue();
NablaLocalStorage.setItem("input", newInput);
maybeParserWorker
.map(parseWorker => {
parseWorker.postMessage(newInput);
return parseWorker;
})
.orElse(() => {
selectedRender(parse(newInput), newInput);
})
})
);
}
function renderGithub() {
const icon = document.createElement("i");
icon.setAttribute("class", "material-icons");
const hyperLink = document.createElement("a");
hyperLink.setAttribute("title", "Github")
hyperLink.setAttribute("href", "https://www.github.com/pedroth/nabladown.js")
hyperLink.setAttribute("target", "_blank")
hyperLink.setAttribute("rel", "noopener")
hyperLink.innerText = "code";
icon.appendChild(hyperLink);
return icon;
}
function renderExportHTML() {
const icon = document.createElement("i");
icon.setAttribute("class", "material-icons");
const hyperLink = document.createElement("a");
hyperLink.setAttribute("title", "Export html")
hyperLink.setAttribute("href", "javascript:void(0)")
hyperLink.setAttribute("rel", "noopener")
hyperLink.innerText = "download";
icon.appendChild(hyperLink);
return icon;
}
function renderPermalink(editor) {
const icon = document.createElement("i");
icon.setAttribute("class", "material-icons");
const hyperLink = document.createElement("a");
hyperLink.setAttribute("title", "Permalink")
hyperLink.setAttribute("href", "javascript:void(0)")
hyperLink.innerText = "link";
hyperLink.addEventListener("click", () => {
const url = window.location.href;
const baseUrl = url.split("#text=")[0];
window.location.href = baseUrl + "#text=" + encodeURI(editor.getValue());
});
icon.appendChild(hyperLink);
return icon;
}
function renderOutputSelector(props) {
let { renderTypes, editor, exportHTMLIcon, output } = props;
const selector = document.createElement("select");
selector.setAttribute("class", "selector")
selector.setAttribute("title", "renders")
selector.setAttribute("name", "renders")
Object.keys(renderTypes).forEach(name => {
const option = document.createElement("option");
option.setAttribute("value", name);
if (getSelectedRenderName() === name) option.setAttribute("selected", "");
option.innerText = name;
selector.appendChild(option);
});
selector.addEventListener("change", e => {
const renderName = e.target.value;
selectedRender = renderFactory({
selectedRender: renderTypes[renderName],
exportHTMLIcon,
output
});
NablaLocalStorage.setItem("selectedRender", renderName);
const input = editor.getValue();
selectedRender(parse(input), input);
});
return selector;
}
function renderToolsUI({ renderTypes, editor, output }) {
const toolsDiv = document.createElement("div");
toolsDiv.setAttribute("class", "tools");
toolsDiv.appendChild(renderGithub());
const exportHTMLIcon = renderExportHTML();
toolsDiv.appendChild(exportHTMLIcon);
toolsDiv.appendChild(renderPermalink(editor));
toolsDiv.appendChild(renderOutputSelector({
renderTypes,
editor,
output,
exportHTMLIcon,
}));
return { tools: toolsDiv, exportHTMLIcon }
}
function renderTitle() {
const div = document.createElement("div")
div.setAttribute("class", "title")
const h1 = document.createElement("h1");
h1.innerText = `∇Nabladown.js`;
div.appendChild(h1);
return div;
}
function onResize(inOut, input, output) {
const style = inOut.style;
if (window.innerWidth >= window.innerHeight) {
style["flex-direction"] = "row";
input.style.width = `${window.innerWidth / 2}px`;
input.style.height = `${window.innerHeight * 0.92}px`;
output.style.width = `${window.innerWidth / 2}px`;
output.style.height = `${window.innerHeight * 0.92}px`;
} else {
style["flex-direction"] = "column";
input.style.width = `${100}%`;
input.style.height = `${window.innerHeight / 2}px`;
output.style.width = `${100}%`;
output.style.height = `${window.innerHeight / 2}px`;
}
}
/**
* from https://github.com/phuocng/html-dom/blob/master/assets/demo/create-resizable-split-views/index.html
* @param {DOMNode} leftSide
* @param {DOMNode} rightSide
* @param {DOMNode} resizer
*/
function createDraggableResizer(leftSide, rightSide, resizer) {
// The current position of mouse
let x = 0;
let leftWidth = 0;
// Handle the mousedown event
// that's triggered when user drags the resizer
const mouseDownHandler = function (e) {
// Get the current mouse position
x = e.clientX;
leftWidth = leftSide.getBoundingClientRect().width;
// Attach the listeners to `document`
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function (e) {
// How far the mouse has been moved
const dx = e.clientX - x;
const newLeftWidth = ((leftWidth + dx) * 100) / resizer.parentNode.getBoundingClientRect().width;
leftSide.style.width = `${newLeftWidth}%`;
resizer.style.cursor = 'col-resize';
document.body.style.cursor = 'col-resize';
leftSide.style.userSelect = 'none';
leftSide.style.pointerEvents = 'none';
rightSide.style.userSelect = 'none';
rightSide.style.pointerEvents = 'none';
};
const mouseUpHandler = function () {
resizer.style.removeProperty('cursor');
document.body.style.removeProperty('cursor');
leftSide.style.removeProperty('user-select');
leftSide.style.removeProperty('pointer-events');
rightSide.style.removeProperty('user-select');
rightSide.style.removeProperty('pointer-events');
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
// Attach the handler
resizer.addEventListener('mousedown', mouseDownHandler);
}
async function renderInputOutput() {
const inputOutput = document.createElement("div");
inputOutput.setAttribute("class", "composer");
const input = document.createElement("div");
input.setAttribute("class", "input");
const resizer = document.createElement("div");
resizer.setAttribute("class", "resizer");
const output = document.createElement("div");
output.addEventListener("scroll", e => {
NablaLocalStorage.setItem("outputScroll", e.target.scrollTop);
});
output.setAttribute("class", "output");
createDraggableResizer(input, output, resizer);
inputOutput.appendChild(input)
inputOutput.appendChild(resizer)
inputOutput.appendChild(output)
onResize(inputOutput, input, output);
window.addEventListener("resize", () => onResize(inputOutput, input, output));
const editor = await renderEditor(input)
return { inputOutput, editor, input, output }
}
async function renderUI(renderTypes) {
const title = renderTitle();
const { inputOutput, editor, output } = await renderInputOutput();
const { tools, exportHTMLIcon } = renderToolsUI({ renderTypes, editor, output });
return { tools, title, inputOutput, editor, exportHTMLIcon, output }
}
function renderLoading() {
const loadingIcon = document.createElement("div");
loadingIcon.classList.add("loader")
loadingIcon.innerHTML = '<svg class="spinner" viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg" ><path fill="currentColor" stroke="currentColor" stroke-width="4" stroke-linecap="round" d="M25,5 L25,45 M5,25 L45,25"></path>';
document.body.appendChild(loadingIcon);
return {
UI: loadingIcon,
disable: () => {
loadingIcon.classList.remove("loader")
loadingIcon.classList.add("disabled")
}
};
}
//========================================================================================
/* *
* RENDERS *
* */
//========================================================================================
const tokenRender = (_, input) => {
let streamOfTokens = tokenizer(stream(input));
const listOfTokens = [];
while (!streamOfTokens.isEmpty()) {
listOfTokens.push(JSON.stringify(streamOfTokens.head()))
streamOfTokens = streamOfTokens.tail();
}
const container = document.createElement("code");
container.innerText = listOfTokens.join("\n");
container.addEventListener("click", () => {
window.getSelection().selectAllChildren(
container
);
})
return container;
}
const nablaStrRender = async ast => {
let content = await renderToString(ast, { isFormatted: true });
content = `
\`\`\` html
${content.replaceAll("```", "\\`\\`\\`")}
\`\`\`
`;
return codeRender(parse(content));
};
const astRender = (ast) => {
let content = JSON.stringify(ast, null, 3);
if (content.length > 45000) {
const container = document.createElement("pre");
container.innerText = content;
container.addEventListener("click", () => {
window.getSelection().selectAllChildren(
container
);
})
return container;
}
content = `
\`\`\` json
${content.replaceAll("```", "\\`\\`\\`")}
\`\`\`
`;
const newAst = parse(content);
return codeRender(newAst)
.then(dom => {
Array(...dom.getElementsByTagName("code")).forEach(code => {
code.innerHTML = code.innerHTML.replaceAll("\\`\\`\\`", "```")
})
return dom;
});
}
const astViewerRender = ast => {
const json = JSON.stringify(ast, null, 3)
const container = document.createElement("iframe");
container.setAttribute("src", "https://jsoncrack.com/widget");
container.setAttribute("id", "CRACK");
container.setAttribute("width", "100%");
container.setAttribute("height", "100%");
setTimeout(() => {
container.contentWindow.postMessage(
{
json
},
"*"
)
}, 1000);
return container;
}
//========================================================================================
/* *
* MAIN *
* */
//========================================================================================
// Global selectedRender
let selectedRender = () => { }
(async () => {
const renderTypes = {
Vanilla: render,
Math: mathRender,
Code: codeRender,
Nabla: nablaRender,
NablaString: nablaStrRender,
"Tokens": tokenRender,
"AST": astRender,
"AST viewer": astViewerRender
};
const loading = renderLoading();
// render UI
const {
tools,
title,
inputOutput,
editor,
exportHTMLIcon,
output
} = await renderUI(renderTypes);
const root = document.getElementById("root");
root.appendChild(tools)
root.appendChild(title)
root.appendChild(inputOutput)
editor.setValue(await getInput());
// setup parse worker
const maybeParserWorker = getParseWorker();
// select render
selectedRender = renderFactory({
selectedRender: renderTypes[getSelectedRenderName()],
exportHTMLIcon,
output
});
// first render when worker exists
maybeParserWorker.map(() => {
const input = editor.getValue();
selectedRender(parse(input), input)
.then(() => root.classList.add("loaded"));
})
addEditorEventListener({ editor, maybeParserWorker });
loading.disable()
})();