From 60d94df67145da61c4e1eb281116e5d3493dce95 Mon Sep 17 00:00:00 2001
From: 43081j <43081j@users.noreply.github.com>
Date: Wed, 5 Oct 2016 22:25:11 +0100
Subject: [PATCH 1/4] add data-binding functionality & expose highlight
Fixes #24 by exposing the highlighter functionality to data-binding and
programatic use.
Also now checks that the host exists before dealing with event listeners.
---
prism-highlighter.html | 46 +++++++++++++++++++++++++++++++++++++----
test/prism-element.html | 37 +++++++++++++++++++++++++++++++++
2 files changed, 79 insertions(+), 4 deletions(-)
diff --git a/prism-highlighter.html b/prism-highlighter.html
index 0458466..9b4f33c 100644
--- a/prism-highlighter.html
+++ b/prism-highlighter.html
@@ -38,16 +38,54 @@
is: 'prism-highlighter',
+ properties: {
+ code: {
+ type: String
+ },
+ lang: {
+ type: String,
+ value: null
+ },
+ highlighted: {
+ type: String,
+ computed: '_computeHighlighted(code, lang)'
+ }
+ },
+
ready: function() {
this._handler = this._highlight.bind(this);
},
attached: function() {
- (this.parentElement || this.parentNode.host).addEventListener(HIGHLIGHT_EVENT, this._handler);
+ var host = this.parentElement || (this.parentNode && this.parentNode.host);
+ if(host) {
+ host.addEventListener(HIGHLIGHT_EVENT, this._handler);
+ }
},
detached: function() {
- (this.parentElement || this.parentNode.host).removeEventListener(HIGHLIGHT_EVENT, this._handler);
+ var host = this.parentElement || (this.parentNode && this.parentNode.host);
+ if(host) {
+ host.removeEventListener(HIGHLIGHT_EVENT, this._handler);
+ }
+ },
+
+ /**
+ * Highlight the given code with an
+ * optional language hint specified.
+ *
+ * @param {string} code The source being highlighted
+ * @param {string=} lang A language hint (e.g. "js").
+ */
+ highlight: function(code, lang) {
+ return Prism.highlight(code, this._detectLang(code, lang));
+ },
+
+ _computeHighlighted: function(code, lang) {
+ if(!code) {
+ return;
+ }
+ return this.highlight(code, lang);
},
/**
@@ -64,14 +102,14 @@
event.stopPropagation();
var detail = event.detail;
- detail.code = Prism.highlight(detail.code, this._detectLang(detail.code, detail.lang));
+ detail.code = this.highlight(detail.code, detail.lang);
},
/**
* Picks a Prism formatter based on the `lang` hint and `code`.
*
* @param {string} code The source being highlighted.
- * @param {string=} lang A language hint (e.g. ````LANG`).
+ * @param {string=} lang A language hint (e.g. "js").
* @return {!prism.Lang}
*/
_detectLang: function(code, lang) {
diff --git a/test/prism-element.html b/test/prism-element.html
index 98bd0db..ceceeed 100644
--- a/test/prism-element.html
+++ b/test/prism-element.html
@@ -38,6 +38,12 @@
+
+
+
+
+
+