5e5fecbcfe
* section labels, TOC, speedups and fixes * show section numbers in widgets * debounce livePreview in usercss editor * better fixed header and compact layout compatibility * fix section sizing for compact layout + layout speedup * DocFuncMapper + cosmetics + fix Clone button * don't run linter during initSections * remove unused/unnecessary DOM polyfills * report invalid @document function as parser error * rewrite section finder * simplify focusedViaClick * simplify setPreprocessor and make it synchronous * throttle offscreen line widgets in usercss with lots of sections * add on, off aliases for add/removeEventListener + onOff * use on/off aliases in changed files * use getters in more places
75 lines
2.0 KiB
JavaScript
75 lines
2.0 KiB
JavaScript
/* global messageBox editor $ prefs */
|
|
/* exported createLivePreview */
|
|
'use strict';
|
|
|
|
function createLivePreview(preprocess, shouldShow) {
|
|
let data;
|
|
let previewer;
|
|
let enabled = prefs.get('editor.livePreview');
|
|
const label = $('#preview-label');
|
|
const errorContainer = $('#preview-errors');
|
|
|
|
prefs.subscribe(['editor.livePreview'], (key, value) => {
|
|
if (value && data && data.id && (data.enabled || editor.dirty.has('enabled'))) {
|
|
previewer = createPreviewer();
|
|
previewer.update(data);
|
|
}
|
|
if (!value && previewer) {
|
|
previewer.disconnect();
|
|
previewer = null;
|
|
}
|
|
enabled = value;
|
|
});
|
|
if (shouldShow != null) show(shouldShow);
|
|
return {update, show};
|
|
|
|
function show(state) {
|
|
label.classList.toggle('hidden', !state);
|
|
}
|
|
|
|
function update(_data) {
|
|
data = _data;
|
|
if (!previewer) {
|
|
if (!data.id || !data.enabled || !enabled) {
|
|
return;
|
|
}
|
|
previewer = createPreviewer();
|
|
}
|
|
previewer.update(data);
|
|
}
|
|
|
|
function createPreviewer() {
|
|
const port = chrome.runtime.connect({
|
|
name: 'livePreview'
|
|
});
|
|
port.onDisconnect.addListener(err => {
|
|
throw err;
|
|
});
|
|
return {update, disconnect};
|
|
|
|
function update(data) {
|
|
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 = editor.getEditors()[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');
|
|
}
|
|
);
|
|
}
|
|
|
|
function disconnect() {
|
|
port.disconnect();
|
|
}
|
|
}
|
|
}
|