diff --git a/edit/live-preview.js b/edit/live-preview.js index c18cdca7..7b53b52a 100644 --- a/edit/live-preview.js +++ b/edit/live-preview.js @@ -1,10 +1,40 @@ 'use strict'; function createLivePreview() { + let data; let previewer; - return {update}; + let hidden; + let node; + document.addEventListener('DOMContentLoaded', () => { + node = $('#preview-label'); + if (hidden !== undefined) { + node.classList.toggle('hidden', hidden); + } + }, {once: true}); + prefs.subscribe(['editor.livePreview'], (key, value) => { + if (value && data && data.id && data.enabled) { + previewer = createPreviewer; + previewer.update(data); + } + if (!value && previewer) { + previewer.disconnect(); + previewer = null; + } + }); + return {update, show}; - function update(data) { + function show(state) { + if (hidden === !state) { + return; + } + hidden = !state; + if (node) { + node.classList.toggle('hidden', hidden); + } + } + + function update(_data) { + data = _data; if (!previewer) { if (!data.id || !data.enabled) { return; @@ -21,10 +51,14 @@ function createLivePreview() { port.onDisconnet.addListener(err => { throw err; }); - return {update}; + return {update, disconnect}; function update(data) { port.postMessage(data); } + + function disconnect() { + port.disconnect(); + } } } diff --git a/edit/source-editor.js b/edit/source-editor.js index 22d10002..75bca459 100644 --- a/edit/source-editor.js +++ b/edit/source-editor.js @@ -38,7 +38,7 @@ function createSourceEditor(style) { editors.push(cm); const livePreview = createLivePreview(); - livePreview.enable(Boolean(style.id)); + livePreview.show(Boolean(style.id)); $('#enabled').onchange = function () { const value = this.checked; @@ -199,6 +199,7 @@ function createSourceEditor(style) { if (codeIsUpdated === false || sameCode) { updateEnvironment(); dirty.clear('enabled'); + updateLivePreview(); return; } @@ -211,6 +212,10 @@ function createSourceEditor(style) { cm.setCursor(cursor); savedGeneration = cm.changeGeneration(); } + if (sameCode) { + // the code is same but the environment is changed + updateLivePreview(); + } dirty.clear(); }); @@ -223,7 +228,7 @@ function createSourceEditor(style) { styleId = style.id; $('#preview-label').classList.remove('hidden'); updateMeta(); - livePreview.enable(Boolean(style.id)); + livePreview.show(Boolean(style.id)); } }