stylus/edit/live-preview.js

73 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-10-08 12:12:39 +00:00
/* global editors messageBox */
2018-10-08 09:49:57 +00:00
'use strict';
2018-10-08 12:12:39 +00:00
function createLivePreview(preprocess) {
2018-10-08 10:38:01 +00:00
let data;
2018-10-08 09:49:57 +00:00
let previewer;
2018-10-08 12:12:39 +00:00
let enabled = prefs.get('editor.livePreview');
const label = $('#preview-label');
const errorContainer = $('#preview-errors');
2018-10-08 10:38:01 +00:00
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;
}
2018-10-08 12:12:39 +00:00
enabled = value;
2018-10-08 10:38:01 +00:00
});
return {update, show};
2018-10-08 09:49:57 +00:00
2018-10-08 10:38:01 +00:00
function show(state) {
2018-10-08 12:12:39 +00:00
label.classList.toggle('hidden', !state);
2018-10-08 10:38:01 +00:00
}
function update(_data) {
data = _data;
2018-10-08 09:49:57 +00:00
if (!previewer) {
2018-10-08 12:12:39 +00:00
if (!data.id || !data.enabled || !enabled) {
2018-10-08 09:49:57 +00:00
return;
}
previewer = createPreviewer();
}
previewer.update(data);
}
function createPreviewer() {
const port = chrome.runtime.connect({
name: 'livePreview'
});
2018-10-10 07:04:03 +00:00
port.onDisconnect.addListener(err => {
2018-10-08 09:49:57 +00:00
throw err;
});
2018-10-08 10:38:01 +00:00
return {update, disconnect};
2018-10-08 09:49:57 +00:00
function update(data) {
2018-10-08 12:12:39 +00:00
Promise.resolve()
.then(() => preprocess ? preprocess(data) : data)
.then(data => port.postMessage(data))
.then(
() => errorContainer.classList.add('hidden'),
err => {
if (Array.isArray(err)) {
err = err.join('\n');
} else if (err && err.index !== undefined) {
// FIXME: this would fail if editors[0].getValue() !== data.sourceCode
const pos = editors[0].posFromIndex(err.index);
err.message = `${pos.line}:${pos.ch} ${err.message || String(err)}`;
}
errorContainer.classList.remove('hidden');
errorContainer.onclick = () => messageBox.alert(err.message || String(err), 'pre');
}
);
2018-10-08 09:49:57 +00:00
}
2018-10-08 10:38:01 +00:00
function disconnect() {
port.disconnect();
}
2018-10-08 09:49:57 +00:00
}
}