1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-16 06:44:50 +00:00
TiddlyWiki5/core/modules/parsers/csvparser.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2014-03-31 11:41:02 +00:00
/*\
title: $:/core/modules/parsers/csvparser.js
type: application/javascript
module-type: parser
The CSV text parser processes CSV files into a table wrapped in a scrollable widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var CsvParser = function(type,text,options) {
2022-11-20 17:51:01 +00:00
// Special handler for tab-delimited files
if (type === 'text/tab-delimited-values' && !options.separator) {
options.separator = "\t";
}
2014-03-31 11:41:02 +00:00
// Table framework
this.tree = [{
"type": "scrollable", "children": [{
2014-03-31 11:41:02 +00:00
"type": "element", "tag": "table", "children": [{
"type": "element", "tag": "tbody", "children": []
}], "attributes": {
"class": {"type": "string", "value": "tc-csv-table"}
2014-03-31 11:41:02 +00:00
}
}]
}];
// Split the text into lines
2022-11-20 17:51:01 +00:00
var lines = $tw.utils.parseCsvString(text, options),
2014-03-31 11:41:02 +00:00
tag = "th";
2022-11-20 17:51:01 +00:00
var maxColumns = 0;
$tw.utils.each(lines, function(columns) {
maxColumns = Math.max(columns.length, maxColumns);
});
2014-03-31 11:41:02 +00:00
for(var line=0; line<lines.length; line++) {
2022-11-20 17:51:01 +00:00
var columns = lines[line];
var row = {
"type": "element", "tag": "tr", "children": []
};
for(var column=0; column<maxColumns; column++) {
row.children.push({
"type": "element", "tag": tag, "children": [{
"type": "text",
"text": columns[column] || ''
}]
});
2014-03-31 11:41:02 +00:00
}
2022-11-20 17:51:01 +00:00
tag = "td";
this.tree[0].children[0].children[0].children.push(row);
2014-03-31 11:41:02 +00:00
}
};
exports["text/csv"] = CsvParser;
2022-11-20 17:51:01 +00:00
exports["text/tab-delimited-values"] = CsvParser;
2014-03-31 11:41:02 +00:00
})();