aboutsummaryrefslogtreecommitdiff
path: root/lib/document-to-html.js
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2013-04-01 15:24:41 +0100
committerMichael Williamson <mike@zwobble.org>2013-04-01 15:25:53 +0100
commit6fdee5a4b57832682e1c43156b2e075a5552f595 (patch)
treea10d7fd5c2a74102a5314678e55f906af8e0c0f5 /lib/document-to-html.js
parent5c7aa27a92265e0890f3b970ca8102751e0d7e01 (diff)
Move document conversion into document-to-html module
Diffstat (limited to 'lib/document-to-html.js')
-rw-r--r--lib/document-to-html.js80
1 files changed, 80 insertions, 0 deletions
diff --git a/lib/document-to-html.js b/lib/document-to-html.js
new file mode 100644
index 0000000..caccb6f
--- /dev/null
+++ b/lib/document-to-html.js
@@ -0,0 +1,80 @@
+var q = require("q");
+
+var styles = require("./styles");
+var HtmlGenerator = require("./html-generator").HtmlGenerator;
+
+exports.DocumentConverter = DocumentConverter;
+
+
+function DocumentConverter(options) {
+ options = options || {};
+ var defaultParagraphStyle = options.defaultParagraphStyle || styles.topLevelElement("p");
+
+ var paragraphStyleMap = options.paragraphStyleMap || {};
+ var runStyleMap = options.runStyleMap || {};
+
+ function convertToHtml(document) {
+ var html = new HtmlGenerator();
+ elementToHtml(document, html);
+ html.closeAll();
+
+ return q.when({
+ html: html.asString()
+ });
+ }
+
+ function convertElements(elements, html) {
+ elements.forEach(function(element) {
+ elementToHtml(element, html);
+ });
+ }
+
+ function elementToHtml(element, html) {
+ var handler = elementConverters[element.type];
+ if (handler) {
+ handler(element, html);
+ }
+ }
+
+ function convertParagraph(element, html) {
+ html.style(styleForParagraph(element));
+ convertElements(element.children, html);
+ }
+
+ function styleForParagraph(element) {
+ return paragraphStyleMap[element.properties.styleName] || defaultParagraphStyle;
+ }
+
+ function convertRun(run, html) {
+ var runHtml = new HtmlGenerator();
+ if (run.properties.styleName) {
+ var style = runStyleMap[run.properties.styleName];
+ if (style) {
+ runHtml.style(style);
+ }
+ }
+ if (run.properties.isBold) {
+ runHtml.push(styles.element("strong"));
+ }
+ if (run.properties.isItalic) {
+ runHtml.push(styles.element("em"));
+ }
+ convertElements(run.children, runHtml);
+ runHtml.closeAll();
+ html.append(runHtml);
+ }
+
+ var elementConverters = {
+ "document": function(document, html) {
+ convertElements(document.children, html);
+ },
+ "paragraph": convertParagraph,
+ "run": convertRun,
+ "text": function(element, html) {
+ html.text(element.value);
+ }
+ };
+ return {
+ convertToHtml: convertToHtml
+ }
+}