From a7cd4f679122e2cf450ad6a8f3c9e27b74c07739 Mon Sep 17 00:00:00 2001 From: Benjamin Pick Date: Wed, 19 Dec 2018 09:54:27 +0100 Subject: [PATCH] Implement serialized themes --- src/contents.js | 36 ++++++++++++++++++++++++++---------- src/themes.js | 14 +++++++++++++- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/src/contents.js b/src/contents.js index 49d9100..ca9388b 100644 --- a/src/contents.js +++ b/src/contents.js @@ -676,6 +676,31 @@ class Contents { }.bind(this)); } + _getStylesheetNode() { + var styleEl; + var key = "epubjs-inserted-css"; + + // Check if link already exists + styleEl = this.document.getElementById("#"+key); + if (!styleEl) { + styleEl = this.document.createElement("style"); + styleEl.id = key; + // Append style element to head + this.document.head.appendChild(styleEl); + } + return styleEl; + } + + /** + * Append stylesheet css + * @param {string} serializedCss + */ + addStylesheetSerialized(serializedCss) { + var styleEl; + styleEl = this._getStylesheetNode(); + styleEl.innerText = serializedCss; + } + /** * Append stylesheet rules to a generate stylesheet * Array: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule @@ -685,19 +710,10 @@ class Contents { addStylesheetRules(rules) { var styleEl; var styleSheet; - var key = "epubjs-inserted-css"; if(!this.document || !rules || rules.length === 0) return; - // Check if link already exists - styleEl = this.document.getElementById("#"+key); - if (!styleEl) { - styleEl = this.document.createElement("style"); - styleEl.id = key; - } - - // Append style element to head - this.document.head.appendChild(styleEl); + styleEl = this._getStylesheetNode(); // Grab style sheet styleSheet = styleEl.sheet; diff --git a/src/themes.js b/src/themes.js index 5ac94ed..7fafcb1 100644 --- a/src/themes.js +++ b/src/themes.js @@ -82,6 +82,18 @@ class Themes { } } + /** + * Register a theme by passing its css as string + * @param {string} name + * @param {string} css + */ + registerCss (name, css) { + this._themes[name] = { "serialized" : css }; + if (this._injected[name]) { + this.update(name); + } + } + /** * Register a url * @param {string} name @@ -176,7 +188,7 @@ class Themes { if (theme.url) { contents.addStylesheet(theme.url); } else if (theme.serialized) { - // TODO: handle serialized + contents.addStylesheetSerialized(theme.serialized); } else if (theme.rules) { contents.addStylesheetRules(theme.rules); theme.injected = true;