-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
86 lines (80 loc) · 3.19 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
'use strict';
const fs = require('fs');
const csvSync = require('csv-parse/lib/sync');
const parse = require('csv-parse/lib/sync');
const path = require('path');
const url = require('url');
const iconv = require('iconv-lite');
function buildTable(csvData, useHeader, exHeaders) {
let html = "<table>";
if (!useHeader && exHeaders != null) {
let th = exHeaders.split(',');
if (th.length !== csvData[0].length) throw new Error("invalid data in exHeaders.");
html += "<tr>";
html += th.map((col) => "<th>"+render2Html(col)+"</th>" ).join('');
html += "</tr>";
}
for(let i=0; i<csvData.length; i++) {
if (useHeader && i==0) {
html += "<tr>";
html += csvData[i].map((col) => "<th>"+render2Html(col)+"</th>" ).join('');
html += "</tr>";
continue;
}
html += "<tr>";
html += csvData[i].map((col) => "<td>"+render2Html(col)+"</td>" ).join('');
html += "</tr>";
}
html += "</table>";
return html;
}
function render2Html(text){
if(!text){
return " ";
}
return text
.replace(/\n/g,"<br>")
.replace(/ /g,"<span style='padding-left: 0.6rem'></span>")
.replace(/\t/g,"<span style='padding-left: 2.4rem'></span>");
}
const DEF_ENCODE = "utf-8";
module.exports = {
blocks: {
includeCsv: {
process: function(blk) {
const tagBody = blk.body;
const tagSrc = blk.kwargs.src;
const linkSrc = (blk.kwargs.linkSrc || true) === true;
const useHeader = blk.kwargs.useHeader || false;
const encoding = blk.kwargs.encoding || null;
const exHeaders = blk.kwargs.exHeaders || null;
const limit = blk.kwargs.limit || Infinity;
let csvData = null;
let relativeSrcPath = null; //css filepath from docment root
if (tagSrc) { // contents from file
const ctxFilePath = (this.ctx.file || {}).path || this.ctx.ctx.file.path || null;
const bookRootPath = this.book.root || this.output.root();
relativeSrcPath = url.resolve(ctxFilePath, tagSrc);
let filePath = decodeURI(path.resolve(bookRootPath, relativeSrcPath));
let data = fs.readFileSync(filePath);
// support various encodings
if (encoding) {
data = iconv.decode(data, encoding);
}
csvData = csvSync(data);
} else { // contents from tag body
csvData = parse(tagBody, {skip_empty_lines: true});
}
if (limit != Infinity) {
csvData = csvData.slice(0, limit);
}
let table = buildTable(csvData, useHeader, exHeaders); // build table html tags
if (tagSrc) {
const link = linkSrc ? `<a href="/${relativeSrcPath}" target="_blank">${tagSrc}</a>` : "";
table = `${link} ${table}`;
}
return table;
}
}
}
};