simplify and speed up init in manage/edit

This commit is contained in:
tophf 2022-02-20 19:11:21 +03:00
parent 90a71c0afc
commit 38ddf5d79d
7 changed files with 22 additions and 54 deletions

View File

@ -1,4 +1,4 @@
/* global $$ $ $create messageBoxProxy waitForSheet */// dom.js /* global $$ $ $create messageBoxProxy */// dom.js
/* global API msg */// msg.js /* global API msg */// msg.js
/* global CodeMirror */ /* global CodeMirror */
/* global SectionsEditor */ /* global SectionsEditor */
@ -17,11 +17,9 @@
document.body.appendChild(t.template.body); document.body.appendChild(t.template.body);
baseInit.ready.then(async () => { EditorMethods();
[editor.template] = await Promise.all([editor.template, waitForSheet()]); editor.livePreview = LivePreview();
(editor.isUsercss ? SourceEditor : SectionsEditor)(); (editor.isUsercss ? SourceEditor : SectionsEditor)().then(() => {
await editor.ready;
editor.ready = true;
editor.dirty.onChange(editor.updateDirty); editor.dirty.onChange(editor.updateDirty);
prefs.subscribe('editor.linter', () => linterMan.run()); prefs.subscribe('editor.linter', () => linterMan.run());
@ -55,7 +53,7 @@ baseInit.ready.then(async () => {
'/edit/drafts', '/edit/drafts',
'/edit/global-search', '/edit/global-search',
]); ]);
}).then(() => {
// Set up mini-header on scroll // Set up mini-header on scroll
const {isUsercss} = editor; const {isUsercss} = editor;
const el = $create({ const el = $create({
@ -183,7 +181,7 @@ window.on('beforeunload', e => {
//#endregion //#endregion
//#region editor methods //#region editor methods
(() => { function EditorMethods() {
const toc = []; const toc = [];
const {dirty} = editor; const {dirty} = editor;
let {style} = editor; let {style} = editor;
@ -312,12 +310,12 @@ window.on('beforeunload', e => {
editor.updateMeta(); editor.updateMeta();
}, },
}); });
})(); }
//#endregion //#endregion
//#region editor livePreview //#region editor livePreview
editor.livePreview = (() => { function LivePreview() {
let data; let data;
let port; let port;
let preprocess; let preprocess;
@ -383,7 +381,7 @@ editor.livePreview = (() => {
}; };
} }
} }
})(); }
//#endregion //#endregion
//#region colorpickerHelper //#region colorpickerHelper

View File

@ -23,7 +23,7 @@ function createSection(originalSection, genId, si) {
const elLabel = $('.code-label', el); const elLabel = $('.code-label', el);
const cm = cmFactory.create(wrapper => { const cm = cmFactory.create(wrapper => {
// making it tall during initial load so IntersectionObserver sees only one adjacent CM // making it tall during initial load so IntersectionObserver sees only one adjacent CM
if (editor.ready !== true) { if (editor.loading) {
wrapper.style.height = si ? si.height : '100vh'; wrapper.style.height = si ? si.height : '100vh';
} }
elLabel.after(wrapper); elLabel.after(wrapper);

View File

@ -123,7 +123,7 @@ function SectionsEditor() {
}, },
}); });
editor.ready = initSections(style.sections); return initSections(style.sections);
/** @param {EditorSection} section */ /** @param {EditorSection} section */
function fitToContent(section) { function fitToContent(section) {
@ -473,7 +473,7 @@ function SectionsEditor() {
keepDirty = false, keepDirty = false,
si = editor.scrollInfo, si = editor.scrollInfo,
} = {}) { } = {}) {
editor.ready = false; Object.assign(editor, /** @namespace Editor */ {loading: true});
if (replace) { if (replace) {
sections.forEach(s => s.remove(true)); sections.forEach(s => s.remove(true));
sections.length = 0; sections.length = 0;
@ -511,7 +511,7 @@ function SectionsEditor() {
} }
container.style.removeProperty('height'); container.style.removeProperty('height');
setGlobalProgress(); setGlobalProgress();
editor.ready = true; editor.loading = false;
} }
/** @param {EditorSection} section */ /** @param {EditorSection} section */

View File

@ -14,7 +14,7 @@
'use strict'; 'use strict';
/* exported SourceEditor */ /* exported SourceEditor */
function SourceEditor() { async function SourceEditor() {
const {style, /** @type DirtyReporter */dirty} = editor; const {style, /** @type DirtyReporter */dirty} = editor;
const DEFAULT_TEMPLATE = ` const DEFAULT_TEMPLATE = `
/* ==UserStyle== /* ==UserStyle==
@ -38,7 +38,7 @@ function SourceEditor() {
const sectionFinder = MozSectionFinder(cm); const sectionFinder = MozSectionFinder(cm);
const sectionWidget = MozSectionWidget(cm, sectionFinder); const sectionWidget = MozSectionWidget(cm, sectionFinder);
editor.livePreview.init(preprocess); editor.livePreview.init(preprocess);
if (!style.id) setupNewStyle(); if (!style.id) setupNewStyle(await editor.template);
createMetaCompiler(meta => { createMetaCompiler(meta => {
style.usercssData = meta; style.usercssData = meta;
style.name = meta.name; style.name = meta.name;
@ -168,7 +168,7 @@ function SourceEditor() {
return name; return name;
} }
function setupNewStyle() { function setupNewStyle(tpl) {
const comment = `/* ${t('usercssReplaceTemplateSectionBody')} */`; const comment = `/* ${t('usercssReplaceTemplateSectionBody')} */`;
const sec0 = style.sections[0]; const sec0 = style.sections[0];
sec0.code = ' '.repeat(prefs.get('editor.tabSize')) + comment; sec0.code = ' '.repeat(prefs.get('editor.tabSize')) + comment;
@ -176,7 +176,7 @@ function SourceEditor() {
sec0.domains = ['example.com']; sec0.domains = ['example.com'];
} }
style.name = [style.name, new Date().toLocaleString()].filter(Boolean).join(' - '); style.name = [style.name, new Date().toLocaleString()].filter(Boolean).join(' - ');
style.sourceCode = (editor.template || DEFAULT_TEMPLATE) style.sourceCode = (tpl || DEFAULT_TEMPLATE)
.replace(/(@name)(?:([\t\x20]+).*|\n)/, (_, k, space) => `${k}${space || ' '}${style.name}`) .replace(/(@name)(?:([\t\x20]+).*|\n)/, (_, k, space) => `${k}${space || ' '}${style.name}`)
.replace(/\s*@-moz-document[^{]*{([^}]*)}\s*$/g, // stripping dummy sections .replace(/\s*@-moz-document[^{]*{([^}]*)}\s*$/g, // stripping dummy sections
(s, body) => body.trim() === comment ? '\n\n' : s) (s, body) => body.trim() === comment ? '\n\n' : s)

View File

@ -16,7 +16,6 @@
setupLivePrefs setupLivePrefs
showSpinner showSpinner
toggleDataset toggleDataset
waitForSheet
*/ */
Object.assign(EventTarget.prototype, { Object.assign(EventTarget.prototype, {
@ -405,20 +404,6 @@ function waitForSelector(selector, {recur, stopOnDomReady = true} = {}) {
}); });
} }
/**
* Forcing layout while the main stylesheet is still loading breaks page appearance
* so we'll wait until it loads (0-1 frames in Chrome, Firefox occasionally needs 2-3).
*/
async function waitForSheet({
href = location.pathname.replace('.html', '.css'),
maxFrames = FIREFOX ? 10 : 1,
} = {}) {
const el = $(`link[href$="${href}"]`);
for (let i = 0; i < maxFrames && !el.sheet; i++) {
await new Promise(requestAnimationFrame);
}
}
//#endregion //#endregion
//#region Internals //#region Internals

View File

@ -142,9 +142,7 @@ function filterOnChange({target: el, forceRefilter, alreadySearched}) {
hide: buildFilter(true), hide: buildFilter(true),
unhide: buildFilter(false), unhide: buildFilter(false),
}); });
if (installed) { reapplyFilter(installed, alreadySearched).then(sorter.updateStripes);
reapplyFilter(installed, alreadySearched).then(sorter.updateStripes);
}
} }
/* exported filterAndAppend */ /* exported filterAndAppend */

View File

@ -6,21 +6,12 @@
/* global router */ /* global router */
/* global sorter */ /* global sorter */
/* global t */// localization.js /* global t */// localization.js
/* global /* global $ $$ $create animateElement setupLivePrefs */// dom.js
$
$$
$create
animateElement
setupLivePrefs
waitForSelector
waitForSheet
*/// dom.js
'use strict'; 'use strict';
document.body.appendChild(t.template.body); document.body.appendChild(t.template.body);
/** @type {HTMLElement} */ const installed = $('#installed');
let installed;
const changeQueue = []; const changeQueue = [];
changeQueue.THROTTLE = 100; // ms changeQueue.THROTTLE = 100; // ms
@ -50,14 +41,12 @@ newUI.renderClass();
(async function init() { (async function init() {
const query = router.getSearch('search'); const query = router.getSearch('search');
const [styles, ids, el] = await Promise.all([ const [styles, ids] = await Promise.all([
API.styles.getAll(), API.styles.getAll(),
query && API.styles.searchDB({query, mode: router.getSearch('searchMode')}), query && API.styles.searchDB({query, mode: router.getSearch('searchMode')}),
// needed to avoid flicker due to an extra frame and layout shift // needed to avoid flicker due to an extra frame and layout shift
waitForSelector('#installed'),
prefs.ready, prefs.ready,
]); ]);
installed = el;
installed.on('click', Events.entryClicked); installed.on('click', Events.entryClicked);
installed.on('mouseover', Events.lazyAddEntryTitle, {passive: true}); installed.on('mouseover', Events.lazyAddEntryTitle, {passive: true});
installed.on('mouseout', Events.lazyAddEntryTitle, {passive: true}); installed.on('mouseout', Events.lazyAddEntryTitle, {passive: true});
@ -82,9 +71,7 @@ newUI.renderClass();
}}`); }}`);
if (!UA.vivaldi) { if (!UA.vivaldi) {
waitForSheet().then(() => { fitSelectBoxesIn($('#filters'));
fitSelectBoxesIn($('#filters'));
});
} }
if (CHROME >= 80 && CHROME <= 88) { if (CHROME >= 80 && CHROME <= 88) {
// Wrong checkboxes are randomly checked after going back in history, https://crbug.com/1138598 // Wrong checkboxes are randomly checked after going back in history, https://crbug.com/1138598