Add: livePreview.show

This commit is contained in:
eight 2018-10-08 18:38:01 +08:00
parent 7b5e7c96d5
commit 47b2b4fc49
2 changed files with 44 additions and 5 deletions

View File

@ -1,10 +1,40 @@
'use strict'; 'use strict';
function createLivePreview() { function createLivePreview() {
let data;
let previewer; 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 (!previewer) {
if (!data.id || !data.enabled) { if (!data.id || !data.enabled) {
return; return;
@ -21,10 +51,14 @@ function createLivePreview() {
port.onDisconnet.addListener(err => { port.onDisconnet.addListener(err => {
throw err; throw err;
}); });
return {update}; return {update, disconnect};
function update(data) { function update(data) {
port.postMessage(data); port.postMessage(data);
} }
function disconnect() {
port.disconnect();
}
} }
} }

View File

@ -38,7 +38,7 @@ function createSourceEditor(style) {
editors.push(cm); editors.push(cm);
const livePreview = createLivePreview(); const livePreview = createLivePreview();
livePreview.enable(Boolean(style.id)); livePreview.show(Boolean(style.id));
$('#enabled').onchange = function () { $('#enabled').onchange = function () {
const value = this.checked; const value = this.checked;
@ -199,6 +199,7 @@ function createSourceEditor(style) {
if (codeIsUpdated === false || sameCode) { if (codeIsUpdated === false || sameCode) {
updateEnvironment(); updateEnvironment();
dirty.clear('enabled'); dirty.clear('enabled');
updateLivePreview();
return; return;
} }
@ -211,6 +212,10 @@ function createSourceEditor(style) {
cm.setCursor(cursor); cm.setCursor(cursor);
savedGeneration = cm.changeGeneration(); savedGeneration = cm.changeGeneration();
} }
if (sameCode) {
// the code is same but the environment is changed
updateLivePreview();
}
dirty.clear(); dirty.clear();
}); });
@ -223,7 +228,7 @@ function createSourceEditor(style) {
styleId = style.id; styleId = style.id;
$('#preview-label').classList.remove('hidden'); $('#preview-label').classList.remove('hidden');
updateMeta(); updateMeta();
livePreview.enable(Boolean(style.id)); livePreview.show(Boolean(style.id));
} }
} }