-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
83 lines (74 loc) · 2.39 KB
/
utils.js
File metadata and controls
83 lines (74 loc) · 2.39 KB
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
const {readFile} = require('fs/promises');
const Prism = require('prismjs');
const loadLanguages = require('prismjs/components/');
loadLanguages(['ts', 'swift', 'php', 'java', 'kotlin'])
const newFileName = () => {
const d = new Date();
const adjustedISO = new Date(d.getTime() - d.getTimezoneOffset() * 60 * 1000)
.toISOString()
.substr(0, 19)
.replace('T', ' ');
return `code2pdf_${adjustedISO}.pdf`;
};
const extractExtension = (path) => {
const fileExtMatch = path.match(/\.([^.]+)$/);
if (!fileExtMatch) return;
return fileExtMatch[1];
};
const validExtensions = ['js', 'c', 'cpp', 'cs', 'css', 'html', 'xml', 'svg', 'ts', 'swift', 'java', 'kt', 'php'];
const getLanguage = (path) => {
const extension = extractExtension(path);
let language = 'none';
switch (extension) {
case 'ts':
language = 'typescript';
break;
case 'js':
language = 'javascript';
break;
case 'c':
case 'cpp':
case 'cs':
language = 'clike';
break;
case 'swift':
language = 'swift';
break;
case 'css':
language = 'css';
break;
case 'html':
case 'xml':
case 'svg':
language = 'markup';
case 'php':
language = 'php';
case 'kt':
launguage = 'kotlin';
case 'java':
language = 'java'
}
return language;
};
const makeHtml = async (path) => {
const lang = getLanguage(path);
const code = await readFile(path, 'utf8');
// Static generation of line numbers
// https://stackoverflow.com/a/59577306/1615721
// https://github.com/PrismJS/prism/blob/master/plugins/line-numbers/prism-line-numbers.js#L109
const NEW_LINE_EXP = /\n(?!$)/g;
let lineNumbersWrapper;
Prism.hooks.add('after-tokenize', function (env) {
const match = env.code.match(NEW_LINE_EXP);
const linesNum = match ? match.length + 1 : 1;
const lines = new Array(linesNum + 1).join('<span></span>');
lineNumbersWrapper = `<span aria-hidden="true" class="line-numbers-rows">${lines}</span>`;
});
let formatted = Prism.highlight(code, Prism.languages[lang], lang);
if (lineNumbersWrapper) formatted += lineNumbersWrapper;
return `<h2>${path}</h2><pre class='line-numbers language-${lang}'><code class='language-${lang}'>${formatted}</code></pre><hr />`;
};
exports.extractExtension = extractExtension;
exports.validExtensions = validExtensions;
exports.newFileName = newFileName;
exports.makeHtml = makeHtml;