WIP: kill cachedStyles

This commit is contained in:
eight 2018-10-11 00:54:38 +08:00
parent 7eba890a21
commit ba64b95575
42 changed files with 188 additions and 222 deletions

View File

@ -475,3 +475,15 @@ function updateAllTabsIcon() {
tabs.map(t => updateIcon({tab: t}))
);
}
function openEditor({id}) {
let url = '/edit.html';
if (id) {
url += `?id=${id}`;
}
if (chrome.windows && prefs.get('openEditInWindow')) {
chrome.windows.create(Object.assign({url}, prefs.get('windowPosition')));
} else {
openURL({url});
}
}

View File

@ -1,6 +1,7 @@
/* eslint no-eq-null: 0, eqeqeq: [2, "smart"] */
/* global createCache db calcStyleDigest normalizeStyleSections db promisify
/* global createCache db calcStyleDigest db tryRegExp
getStyleWithNoCode msg */
/* exported styleManager */
'use strict';
/*

View File

@ -1,4 +1,4 @@
/* global getStyles API_METHODS styleManager */
/* global API_METHODS styleManager CHROME prefs */
'use strict';
API_METHODS.styleViaAPI = !CHROME && (() => {

View File

@ -1,9 +1,7 @@
/*
global styleSectionsEqual
global calcStyleDigest cachedStyles getStyleWithNoCode
global usercss semverCompare
global API_METHODS styleManager
*/
/* global styleSectionsEqual prefs download tryJSONparse ignoreChromeError
calcStyleDigest getStyleWithNoCode debounce chromeLocal
usercss semverCompare
API_METHODS styleManager */
'use strict';
(() => {
@ -70,7 +68,7 @@ global API_METHODS styleManager
function checkStyle({
id,
style = cachedStyles.byId.get(id),
style,
port,
save = true,
ignoreDigest,
@ -89,7 +87,7 @@ global API_METHODS styleManager
'ignoreDigest' option is set on the second manual individual update check on the manage page.
*/
return Promise.resolve(style)
return fetchStyle()
.then([calcStyleDigest][!ignoreDigest ? 0 : 'skip'])
.then([checkIfEdited][!ignoreDigest ? 0 : 'skip'])
.then([maybeUpdateUSO, maybeUpdateUsercss][style.usercssData ? 1 : 0])
@ -97,6 +95,16 @@ global API_METHODS styleManager
.then(reportSuccess)
.catch(reportFailure);
function fetchStyle() {
if (style) {
return Promise.resolve();
}
return styleManager.get(id)
.then(_style => {
style = _style;
});
}
function reportSuccess(saved) {
log(STATES.UPDATED + ` #${style.id} ${style.name}`);
const info = {updated: true, style: saved};

View File

@ -1,4 +1,5 @@
/* global API_METHODS usercss chromeLocal styleManager */
/* global API_METHODS usercss chromeLocal styleManager FIREFOX deepCopy openURL
download */
'use strict';
(() => {

View File

@ -1,5 +1,5 @@
/* eslint no-var: 0 */
/* global msg */
/* global msg API prefs */
'use strict';
(() => {
@ -79,18 +79,18 @@
* @param {Function} callback
* @returns {Boolean|undefined}
*/
function getStylesFallback(msg) {
if (window !== parent &&
location.href !== 'about:blank') {
try {
if (parent.location.origin === location.origin &&
parent.location.href !== location.href) {
chrome.runtime.connect({name: 'getStyles:' + JSON.stringify(msg)});
return true;
}
} catch (e) {}
}
}
// function getStylesFallback(msg) {
// if (window !== parent &&
// location.href !== 'about:blank') {
// try {
// if (parent.location.origin === location.origin &&
// parent.location.href !== location.href) {
// chrome.runtime.connect({name: 'getStyles:' + JSON.stringify(msg)});
// return true;
// }
// } catch (e) {}
// }
// }
function applyOnMessage(request) {
if (!chrome.app && document instanceof XMLDocument && request.method !== 'ping') {
@ -320,34 +320,6 @@
return el;
}
function setContentsInPageContext() {
try {
(document.head || ROOT).appendChild(document.createElement('script')).text = `(${queue => {
document.currentScript.remove();
for (const {id, code} of queue) {
const el = document.getElementById(id) ||
document.querySelector('style.stylus[id="' + id + '"]');
if (!el) continue;
const {disabled} = el.sheet;
el.textContent = code;
el.sheet.disabled = disabled;
}
}})(${JSON.stringify(pageContextQueue)})`;
} catch (e) {}
let failedSome;
for (const {el, code} of pageContextQueue) {
if (el.textContent !== code) {
el.textContent = code;
failedSome = true;
}
}
if (failedSome) {
console.debug('Could not set code of some styles in page context, ' +
'see https://github.com/openstyles/stylus/issues/461');
}
pageContextQueue.length = 0;
}
function addStyleElement(newElement) {
if (!ROOT) {
return;
@ -412,14 +384,6 @@
return parseInt(el.id.substr(ID_PREFIX.length));
}
function countStylesInHash(styleHash) {
let num = 0;
for (const k in styleHash) {
num += !isNaN(parseInt(k)) ? 1 : 0;
}
return num;
}
function orphanCheck() {
if (chrome.i18n && chrome.i18n.getUILanguage()) {
return true;

View File

@ -1,3 +1,4 @@
/* global API */
'use strict';
(() => {

View File

@ -1,3 +1,4 @@
/* global API */
'use strict';
(() => {

View File

@ -1,4 +1,4 @@
/* global cloneInto msg */
/* global cloneInto msg API */
'use strict';
(() => {

View File

@ -1,4 +1,6 @@
/* global regExpTester debounce messageBox CodeMirror template colorMimicry msg */
/* global regExpTester debounce messageBox CodeMirror template colorMimicry msg
$ $create t prefs tryCatch */
/* exported createAppliesToLineWidget */
'use strict';
function createAppliesToLineWidget(cm) {

View File

@ -1,7 +1,5 @@
/*
global CodeMirror loadScript css_beautify
global getSectionForChild showHelp
*/
/* global loadScript css_beautify showHelp prefs t $ $create */
/* exported beautify */
'use strict';
function beautify(scope) {

View File

@ -1,4 +1,4 @@
/* global CodeMirror prefs loadScript editor */
/* global CodeMirror prefs loadScript editor $ template */
'use strict';

View File

@ -1,4 +1,5 @@
/* global CodeMirror loadScript rerouteHotkeys */
/* global CodeMirror loadScript rerouteHotkeys prefs $ debounce $create */
/* exported cmFactory */
'use strict';
/*
All cm instances created by this module are collected so we can broadcast prefs

View File

@ -1,4 +1,4 @@
/* global CodeMirror loadScript showHelp cmFactory */
/* global CodeMirror showHelp cmFactory onDOMready $ $create prefs t */
'use strict';
(() => {

View File

@ -1,16 +1,13 @@
/*
global CodeMirror loadScript
global createSourceEditor
global closeCurrentTab regExpTester messageBox
global setupCodeMirror
global beautify
global sectionsToMozFormat
global moveFocus editorWorker msg createSectionsEditor rerouteHotkeys
/* global CodeMirror onDOMready prefs setupLivePrefs $ $$ $create t tHTML
createSourceEditor queryTabs sessionStorageHash getOwnTab FIREFOX API tryCatch
closeCurrentTab messageBox debounce
beautify
moveFocus msg createSectionsEditor rerouteHotkeys
*/
/* exported showCodeMirrorPopup */
'use strict';
let saveSizeOnClose;
let ownTabId;
// direct & reverse mapping of @-moz-document keywords and internal property names
const propertyToCss = {urls: 'url', urlPrefixes: 'url-prefix', domains: 'domain', regexps: 'regexp'};
@ -242,29 +239,6 @@ prefs.subscribe(['editor.smartIndent'], (key, value) =>
CodeMirror.setOption('smartIndent', value));
function preinit() {
// make querySelectorAll enumeration code readable
// FIXME: don't extend native
['forEach', 'some', 'indexOf', 'map'].forEach(method => {
NodeList.prototype[method] = Array.prototype[method];
});
// eslint-disable-next-line no-extend-native
Object.defineProperties(Array.prototype, {
last: {
get() {
return this[this.length - 1];
},
},
rotate: {
value: function (amount) {
// negative amount == rotate left
const r = this.slice(-amount, this.length);
Array.prototype.push.apply(r, this.slice(0, this.length - r.length));
return r;
},
},
});
// preload the theme so that CodeMirror can calculate its metrics in DOMContentLoaded->setupLivePrefs()
new MutationObserver((mutations, observer) => {
const themeElement = $('#cm-theme');
@ -302,7 +276,7 @@ function preinit() {
}
getOwnTab().then(tab => {
ownTabId = tab.id;
const ownTabId = tab.id;
// use browser history back when 'back to manage' is clicked
if (sessionStorageHash('manageStylesHistory').value[ownTabId] === location.href) {
@ -446,21 +420,6 @@ function initStyleData() {
}
}
function showSectionHelp(event) {
event.preventDefault();
showHelp(t('styleSectionsTitle'), t('sectionHelp'));
}
function showAppliesToHelp(event) {
event.preventDefault();
showHelp(t('appliesLabel'), t('appliesHelp'));
}
function showToMozillaHelp(event) {
event.preventDefault();
showHelp(t('styleMozillaFormatHeading'), t('styleToMozillaFormatHelp'));
}
function showHelp(title = '', body) {
const div = $('#help-popup');
div.className = '';
@ -559,20 +518,6 @@ function showCodeMirrorPopup(title, html, options) {
return popup;
}
function setGlobalProgress(done, total) {
const progressElement = $('#global-progress') ||
total && document.body.appendChild($create('#global-progress'));
if (total) {
const progress = (done / Math.max(done, total) * 100).toFixed(1);
progressElement.style.borderLeftWidth = progress + 'vw';
setTimeout(() => {
progressElement.title = progress + '%';
});
} else {
$.remove(progressElement);
}
}
function hideLintHeaderOnScroll() {
// workaround part2 for the <details> not showing its toggle icon: hide <summary> on scroll
const newOpacity = this.scrollTop === 0 ? '' : '0';
@ -610,14 +555,3 @@ function isWindowMaximized() {
window.outerHeight < screen.availHeight + 10
);
}
function toggleContextMenuDelete(event) {
if (chrome.contextMenus && event.button === 2 && prefs.get('editor.contextDelete')) {
chrome.contextMenus.update('editor.contextDelete', {
enabled: Boolean(
this.selectionStart !== this.selectionEnd ||
this.somethingSelected && this.somethingSelected()
),
}, ignoreChromeError);
}
}

View File

@ -1,3 +1,4 @@
/* exported editorWorker */
'use strict';
// eslint-disable-next-line no-var

View File

@ -1,8 +1,4 @@
/*
global messageBox resolveWith
gloabl editor showHelp getSectionsHashes
global popupExclusions
*/
/* global showHelp $ $$ debounce API template t */
'use strict';
const exclusions = (() => {
@ -142,9 +138,9 @@ const exclusions = (() => {
if (msg.method === 'exclusionsUpdated' && msg.style && msg.style.exclusions) {
update({list: Object.keys(msg.style.exclusions), isUpdating: true});
// update popup, if loaded
if (typeof popupExclusions !== 'undefined') {
popupExclusions.selectExclusions(msg.style.exclusions);
}
// if (typeof popupExclusions !== 'undefined') {
// popupExclusions.selectExclusions(msg.style.exclusions);
// }
}
}
@ -162,7 +158,6 @@ const exclusions = (() => {
style.exclusions = exclusionList;
style.reason = 'exclusionsUpdated';
API.saveStyle(style);
notifyAllTabs({method: 'exclusionsUpdated', style, id, excluded: exclusionList});
});
}

View File

@ -1,6 +1,5 @@
/* global CodeMirror */
/* global focusAccessibility */
/* global colorMimicry editor */
/* global CodeMirror focusAccessibility colorMimicry editor
onDOMready $ $$ $create t debounce tryRegExp stringAsRegExp template */
'use strict';
onDOMready().then(() => {

View File

@ -1,5 +1,6 @@
/* global memoize editorWorker showCodeMirrorPopup loadScript messageBox
LINTER_DEFAULTS rerouteHotkeys */
LINTER_DEFAULTS rerouteHotkeys $ $create $createLink tryJSONparse t
chromeSync */
'use strict';
(() => {

View File

@ -1,7 +1,7 @@
/* exported LINTER_DEFAULTS */
'use strict';
// eslint-disable-next-line no-var
var LINTER_DEFAULTS = (() => {
const LINTER_DEFAULTS = (() => {
const SEVERITY = {severity: 'warning'};
const STYLELINT = {
// 'sugarss' is a indent-based syntax like Sass or Stylus

View File

@ -1,4 +1,4 @@
/* global LINTER_DEFAULTS linter editorWorker */
/* global LINTER_DEFAULTS linter editorWorker prefs chromeSync */
'use strict';
(() => {

View File

@ -1,4 +1,5 @@
/* global showHelp editorWorker memoize */
/* global showHelp editorWorker memoize $ $create $createLink t */
/* exported createLinterHelpDialog */
'use strict';
function createLinterHelpDialog(getIssues) {

View File

@ -1,4 +1,5 @@
/* global linter */
/* global linter API */
/* exported createMetaCompiler */
'use strict';
function createMetaCompiler(cm) {

View File

@ -1,7 +1,6 @@
/* global linter editor clipString createLinterHelpDialog makeSectionVisible */
/* global linter editor clipString createLinterHelpDialog $ $create */
'use strict';
// eslint-disable-next-line no-var
Object.assign(linter, (() => {
const tables = new Map();
const helpDialog = createLinterHelpDialog(getIssues);

View File

@ -1,7 +1,8 @@
/* global prefs */
'use strict';
// eslint-disable-next-line no-var
var linter = (() => {
/* exported linter */
const linter = (() => {
const lintingUpdatedListeners = [];
const unhookListeners = [];
const linters = [];

View File

@ -1,4 +1,5 @@
/* global messageBox editor */
/* global messageBox editor $ prefs */
/* exported createLivePreview */
'use strict';
function createLivePreview(preprocess) {

View File

@ -1,4 +1,4 @@
/* global CodeMirror */
/* global CodeMirror prefs */
'use strict';
(() => {

View File

@ -1,8 +1,8 @@
/* global showHelp */
/* global showHelp $ $create tryRegExp queryTabs URLS t template openURL */
/* exported regExpTester */
'use strict';
// eslint-disable-next-line no-var
var regExpTester = (() => {
const regExpTester = (() => {
const GET_FAVICON_URL = 'https://www.google.com/s2/favicons?domain=';
const OWN_ICON = chrome.runtime.getManifest().icons['16'];
const cachedRegexps = new Map();

View File

@ -1,4 +1,5 @@
/* global CodeMirror editor */
/* global CodeMirror editor debounce */
/* exported rerouteHotkeys */
'use strict';
const rerouteHotkeys = (() => {

View File

@ -1,10 +1,11 @@
/* global dirtyReporter showToMozillaHelp
showSectionHelp toggleContextMenuDelete setGlobalProgress maximizeCodeHeight
CodeMirror nextPrevEditorOnKeydown showAppliesToHelp propertyToCss
/* global dirtyReporter showHelp prefs ignoreChromeError
CodeMirror propertyToCss
regExpTester linter createLivePreview showCodeMirrorPopup
sectionsToMozFormat editorWorker messageBox clipString beautify
rerouteHotkeys cmFactory CssToProperty
rerouteHotkeys cmFactory CssToProperty template $ $$ $create t FIREFOX API
debounce tryRegExp
*/
/* exported createSectionsEditor */
'use strict';
function createResizeGrip(cm) {
@ -98,6 +99,7 @@ function createSectionsEditor(style) {
$('#to-mozilla-help').addEventListener('click', showToMozillaHelp);
$('#from-mozilla').addEventListener('click', () => fromMozillaFormat());
$('#save-button').addEventListener('click', saveStyle);
// FIXME: this element doesn't exist?
$('#sections-help').addEventListener('click', showSectionHelp);
document.addEventListener('wheel', scrollEntirePageOnCtrlShift);
@ -148,6 +150,46 @@ function createSectionsEditor(style) {
getSearchableInputs,
};
function toggleContextMenuDelete(event) {
if (chrome.contextMenus && event.button === 2 && prefs.get('editor.contextDelete')) {
chrome.contextMenus.update('editor.contextDelete', {
enabled: Boolean(
this.selectionStart !== this.selectionEnd ||
this.somethingSelected && this.somethingSelected()
),
}, ignoreChromeError);
}
}
function setGlobalProgress(done, total) {
const progressElement = $('#global-progress') ||
total && document.body.appendChild($create('#global-progress'));
if (total) {
const progress = (done / Math.max(done, total) * 100).toFixed(1);
progressElement.style.borderLeftWidth = progress + 'vw';
setTimeout(() => {
progressElement.title = progress + '%';
});
} else {
$.remove(progressElement);
}
}
function showToMozillaHelp(event) {
event.preventDefault();
showHelp(t('styleMozillaFormatHeading'), t('styleToMozillaFormatHelp'));
}
function showAppliesToHelp(event) {
event.preventDefault();
showHelp(t('appliesLabel'), t('appliesHelp'));
}
function showSectionHelp(event) {
event.preventDefault();
showHelp(t('styleSectionsTitle'), t('sectionHelp'));
}
function getSearchableInputs(cm) {
return sections.find(s => s.cm === cm).appliesTo.map(a => a.valueEl).filter(Boolean);
}

View File

@ -1,4 +1,5 @@
/* global CodeMirror showHelp */
/* global CodeMirror showHelp onDOMready $ $$ $create template t
prefs stringAsRegExp */
'use strict';
onDOMready().then(() => {

View File

@ -1,9 +1,9 @@
/*
global CodeMirror dirtyReporter
global createAppliesToLineWidget messageBox
global sectionsToMozFormat
global createMetaCompiler linter createLivePreview cmFactory
*/
/* global dirtyReporter
createAppliesToLineWidget messageBox
sectionsToMozFormat
createMetaCompiler linter createLivePreview cmFactory $ $create API prefs t
chromeSync */
/* exported createSourceEditor */
'use strict';
function createSourceEditor(style) {

View File

@ -1,3 +1,4 @@
/* exported dirtyReporter memoize clipString sectionsToMozFormat */
'use strict';
function dirtyReporter() {

View File

@ -1,5 +1,5 @@
/* global CodeMirror semverCompare closeCurrentTab */
/* global messageBox download chromeLocal */
/* global CodeMirror semverCompare closeCurrentTab messageBox download
$ $$ $create $createLink t prefs API getTab */
'use strict';
(() => {

View File

@ -1,5 +1,7 @@
/* exported createCache */
'use strict';
// create a FIFO limit-size map.
function createCache(size = 1000) {
const map = new Map();
const buffer = Array(size);

View File

@ -1,9 +1,35 @@
/* global prefs */
/* exported scrollElementIntoView animateElement enforceInputRange $createLink
setupLivePrefs moveFocus */
'use strict';
if (!/^Win\d+/.test(navigator.platform)) {
document.documentElement.classList.add('non-windows');
}
// make querySelectorAll enumeration code readable
// FIXME: avoid extending native?
['forEach', 'some', 'indexOf', 'map'].forEach(method => {
NodeList.prototype[method] = Array.prototype[method];
});
// eslint-disable-next-line no-extend-native
Object.defineProperties(Array.prototype, {
last: {
get() {
return this[this.length - 1];
},
},
rotate: {
value: function (amount) {
// negative amount == rotate left
const r = this.slice(-amount, this.length);
Array.prototype.push.apply(r, this.slice(0, this.length - r.length));
return r;
},
},
});
// polyfill for old browsers to enable [...results] and for-of
for (const type of [NodeList, NamedNodeMap, HTMLCollection, HTMLAllCollection]) {
if (!type.prototype[Symbol.iterator]) {

View File

@ -1,3 +1,5 @@
/* global tryCatch */
/* exported tHTML formatDate */
'use strict';
const template = {};

View File

@ -1,14 +1,13 @@
/*
global BG: true
global FIREFOX: true
global onRuntimeMessage applyOnMessage
*/
/* exported getActiveTab onTabReady stringAsRegExp getTabRealURL openURL
getStyleWithNoCode tryRegExp sessionStorageHash download
closeCurrentTab */
'use strict';
const CHROME = Boolean(chrome.app) && parseInt(navigator.userAgent.match(/Chrom\w+\/(?:\d+\.){2}(\d+)|$/)[1]);
const OPERA = Boolean(chrome.app) && parseFloat(navigator.userAgent.match(/\bOPR\/(\d+\.\d+)|$/)[1]);
const VIVALDI = Boolean(chrome.app) && navigator.userAgent.includes('Vivaldi');
const ANDROID = !chrome.windows;
// FIXME: who use this?
// const ANDROID = !chrome.windows;
let FIREFOX = !chrome.app && parseFloat(navigator.userAgent.match(/\bFirefox\/(\d+\.\d+)|$/)[1]);
if (!CHROME && !chrome.browserAction.openPopup) {
@ -120,13 +119,6 @@ function getActiveTab() {
.then(tabs => tabs[0]);
}
function getActiveTabRealURL() {
return getActiveTab()
.then(getTabRealURL);
}
function getTabRealURL(tab) {
return new Promise(resolve => {
if (tab.url !== 'chrome://newtab/' || URLS.chromeProtectsNTP) {
@ -487,27 +479,6 @@ function download(url, {
}
}
function invokeOrPostpone(isInvoke, fn, ...args) {
return isInvoke
? fn(...args)
: setTimeout(invokeOrPostpone, 0, true, fn, ...args);
}
function openEditor({id}) {
let url = '/edit.html';
if (id) {
url += `?id=${id}`;
}
if (chrome.windows && prefs.get('openEditInWindow')) {
chrome.windows.create(Object.assign({url}, prefs.get('windowPosition')));
} else {
openURL({url});
}
}
function closeCurrentTab() {
// https://bugzilla.mozilla.org/show_bug.cgi?id=1409375
getOwnTab().then(tab => {
@ -516,6 +487,3 @@ function closeCurrentTab() {
}
});
}
// FIXME: remove this when #510 is merged
function notifyAllTabs() {}

View File

@ -1,4 +1,5 @@
/* global parserlib */
/* exported parseMozFormat */
'use strict';
/**

View File

@ -1,4 +1,5 @@
/* global promisify deepCopy */
/* exported msg API */
// deepCopy is only used if the script is executed in extension pages.
'use strict';

View File

@ -1,4 +1,3 @@
/* global deepCopy debounce API tryJSONparse chromeSync FIREFOX CHROME */
/* exported prefs */
'use strict';

View File

@ -1,4 +1,4 @@
/* global loadScript tryJSONparse API */
/* global loadScript tryJSONparse */
/* exported chromeLocal chromeSync */
'use strict';