stylus/background/style-manager.js

460 lines
13 KiB
JavaScript
Raw Normal View History

2018-10-05 10:47:52 +00:00
/* eslint no-eq-null: 0, eqeqeq: [2, "smart"] */
/* global createCache db calcStyleDigest normalizeStyleSections db promisify
getStyleWithNoCode */
2018-10-04 04:46:19 +00:00
'use strict';
2018-10-03 19:35:07 +00:00
const styleManager = (() => {
const preparing = prepare();
2018-10-04 04:46:19 +00:00
const styles = new Map();
2018-10-03 19:35:07 +00:00
const cachedStyleForUrl = createCache();
const compiledRe = createCache();
const compiledExclusion = createCache();
const BAD_MATCHER = {test: () => false};
2018-10-04 17:03:40 +00:00
const tabQuery = promisify(chrome.tabs.query.bind(chrome.tabs));
const tabSendMessage = promisify(chrome.tabs.sendMessage.bind(chrome.tabs));
const runtimeSendMessage = promisify(chrome.runtime.sendMessage.bind(chrome.runtime));
2018-10-03 19:35:07 +00:00
// FIXME: do we have to prepare `styles` map for all methods?
return ensurePrepared({
2018-10-05 10:47:52 +00:00
// styles,
// cachedStyleForUrl,
2018-10-04 17:03:40 +00:00
getStylesInfo,
getSectionsByUrl,
2018-10-03 19:35:07 +00:00
installStyle,
deleteStyle,
setStyleExclusions,
2018-10-04 17:03:40 +00:00
editSave,
2018-10-05 10:47:52 +00:00
toggleStyle,
getAllStyles, // used by import-export
getStylesInfoForUrl, // used by popup
countStyles,
2018-10-03 19:35:07 +00:00
// TODO: get all styles API?
// TODO: get style by ID?
});
2018-10-05 10:47:52 +00:00
function getAllStyles() {
return [...styles.values()].map(s => s.data);
}
2018-10-04 17:03:40 +00:00
function toggleStyle(id, enabled) {
const style = styles.get(id);
2018-10-05 10:47:52 +00:00
const newData = Object.assign({}, style.data, {enabled});
return saveStyle(newData)
.then(newData => {
style.data = newData;
return emitChanges({
method: 'styleUpdated',
codeIsUpdated: false,
style: {id, enabled}
}, style.appliesTo);
})
.then(() => id);
2018-10-04 17:03:40 +00:00
}
2018-10-05 13:28:19 +00:00
function emitChangesToTabs(getMessage, appliesTo, ignoreExtension = false) {
// FIXME: does `discarded` work in old browsers?
// TODO: send to activated tabs first?
return tabQuery({discarded: false})
.then(tabs => {
const pending = [];
for (const tab of tabs) {
if (
!URLS.supported(tab.url) ||
ignoreExtension && isExtensionUrl(tab.url) ||
appliesTo && !appliesTo.has(tab.url)
) {
continue;
}
const message = typeof getMessage === 'function' ? getMessage(tab) : getMessage;
if (message) {
pending.push(tabSendMessage(tab.id, message));
}
}
return Promise.all(pending);
});
}
2018-10-05 10:47:52 +00:00
function emitChanges(message, appliesTo) {
const pending = runtimeSendMessage(message);
if (appliesTo && [...appliesTo].every(isExtensionUrl)) {
return pending;
}
2018-10-05 13:28:19 +00:00
return Promise.all([
pending,
emitChangesToTabs(message, appliesTo, true),
]);
2018-10-05 10:47:52 +00:00
}
function isExtensionUrl(url) {
return /^\w+?-extension:\/\//.test(url);
}
function getStylesInfo(filter) {
if (filter && filter.id) {
return [getStyleWithNoCode(styles.get(filter.id).data)];
}
return [...styles.values()]
.filter(s => !filter || filterMatchStyle(filter, s.data))
.map(s => getStyleWithNoCode(s.data));
}
2018-10-05 13:28:19 +00:00
function countStyles(filter) {
if (!filter) {
return styles.size;
}
if (filter.id) {
return styles.has(filter.id) ? 1 : 0;
}
return [...styles.values()]
.filter(s => filterMatchStyle(filter, s.data))
.length;
}
2018-10-05 10:47:52 +00:00
function filterMatchStyle(filter, style) {
for (const key of Object.keys(filter)) {
if (filter[key] !== style[key]) {
return false;
}
}
return true;
2018-10-04 17:03:40 +00:00
}
2018-10-05 13:28:19 +00:00
function editSave(style) {
return saveStyle(style);
}
2018-10-03 19:35:07 +00:00
function setStyleExclusions() {}
function ensurePrepared(methods) {
for (const [name, fn] in Object.entries(methods)) {
methods[name] = (...args) =>
preparing.then(() => fn(...args));
}
return methods;
}
function deleteStyle(id) {
2018-10-05 10:47:52 +00:00
const style = styles.get(id);
2018-10-03 19:35:07 +00:00
return db.exec('delete', id)
.then(() => {
2018-10-05 10:47:52 +00:00
for (const url of style.appliesTo) {
const cache = cachedStyleForUrl.get(url);
delete cache[id];
}
styles.delete(id);
return emitChanges({
method: 'styleDeleted',
data: {id}
});
})
.then(() => id);
2018-10-03 19:35:07 +00:00
}
2018-10-05 13:28:19 +00:00
function createNewStyle() {
return {
enabled: true,
updateUrl: null,
md5Url: null,
url: null,
originalMd5: null,
installDate: Date.now()
};
}
function installStyle(data) {
let style = styles.get(style.id);
if (!style) {
data = Object.assign(createNewStyle(), data);
} else {
data = Object.assign({}, style.data, data);
}
// FIXME: update installDate?
return calcStyleDigest(data)
2018-10-03 19:35:07 +00:00
.then(digest => {
2018-10-05 13:28:19 +00:00
data.originalDigest = digest;
return saveStyle(data);
2018-10-03 19:35:07 +00:00
})
2018-10-05 13:28:19 +00:00
.then(newData => {
2018-10-03 19:35:07 +00:00
// FIXME: do we really need to clear the entire cache?
2018-10-05 13:28:19 +00:00
// cachedStyleForUrl.clear();
if (!style) {
const appliesTo = new Set();
styles.set(newData.id, {
appliesTo,
data: newData
});
// update cache
tabQuery()
.then(tabs => {
for (const tab of tabs) {
// FIXME: switch to something like `shouldApplyTo` that doesn't use code
const code = getAppliedCode(tab.url, newData);
if (!code) {
continue;
}
const cache = cachedStyleForUrl.get(tab.url);
if (!cache) {
continue;
}
cache[newData.id] = code;
appliesTo.add(tab.url);
}
return emitChanges()
})
}
const appliesTo = style.appliesTo;
style.appliesTo = new Set;
for (const url of style.appliesTo) {
cachedStyleForUrl.delete(url);
}
emitChanges()
2018-10-03 19:35:07 +00:00
// FIXME: invalid signature
notifyAllTabs();
2018-10-04 04:46:19 +00:00
return style;
2018-10-03 19:35:07 +00:00
});
}
function importStyle(style) {
// FIXME: move this to importer
// style.originalDigest = style.originalDigest || style.styleDigest; // TODO: remove in the future
// delete style.styleDigest; // TODO: remove in the future
// if (typeof style.originalDigest !== 'string' || style.originalDigest.length !== 40) {
// delete style.originalDigest;
// }
}
function saveStyle(style) {
return (style.id == null ? getNewStyle() : getOldStyle())
.then(oldStyle => {
style = Object.assign(oldStyle, style);
2018-10-05 10:47:52 +00:00
// FIXME: why we always run `normalizeStyleSections` at each `saveStyle`?
2018-10-03 19:35:07 +00:00
style.sections = normalizeStyleSections(style);
2018-10-04 04:46:19 +00:00
return db.exec('put', style);
2018-10-03 19:35:07 +00:00
})
.then(event => {
if (style.id == null) {
style.id = event.target.result;
}
return style;
});
function getOldStyle() {
return db.exec('get', style.id)
.then((event, store) => {
if (!event.target.result) {
throw new Error(`Unknown style id: ${style.id}`);
}
return event.target.result;
});
}
// FIXME: don't overwrite style name when the name is empty
function getNewStyle() {
2018-10-05 13:28:19 +00:00
return Promise.resolve();
2018-10-03 19:35:07 +00:00
}
}
2018-10-05 10:47:52 +00:00
function getStylesInfoForUrl(url) {
}
function getSectionsByUrl(url, filterId) {
2018-10-03 19:35:07 +00:00
let result = cachedStyleForUrl.get(url);
if (!result) {
2018-10-05 10:47:52 +00:00
result = {};
for (const {appliesTo, data} of styles.values()) {
2018-10-05 13:28:19 +00:00
const code = getAppliedCode(url, data);
2018-10-05 10:47:52 +00:00
if (code) {
result[data.id] = code;
appliesTo.add(url);
2018-10-03 19:35:07 +00:00
}
}
2018-10-05 10:47:52 +00:00
cachedStyleForUrl.set(url, result);
}
if (filterId) {
return {[filterId]: result[filterId]};
2018-10-03 19:35:07 +00:00
}
return result;
}
2018-10-05 13:28:19 +00:00
function getAppliedCode(url, data) {
if (!urlMatchStyle(url, data)) {
return;
}
let code = '';
for (const section of data.sections) {
if (urlMatchSection(url, section)) {
code += section.code;
}
}
return code;
}
2018-10-03 19:35:07 +00:00
function prepare() {
return db.exec('getAll').then(event => {
2018-10-05 10:47:52 +00:00
const styleList = event.target.result;
if (!styleList) {
return;
}
2018-10-03 19:35:07 +00:00
for (const style of styleList) {
2018-10-05 10:47:52 +00:00
styles.set(style.id, {
appliesTo: new Set(),
data: style
});
2018-10-03 19:35:07 +00:00
if (!style.name) {
style.name = 'ID: ' + style.id;
}
}
});
}
function urlMatchStyle(url, style) {
2018-10-04 04:46:19 +00:00
if (style.exclusions && style.exclusions.some(e => compileExclusion(e).test(url))) {
2018-10-03 19:35:07 +00:00
return false;
}
return true;
}
function urlMatchSection(url, section) {
// FIXME: match sub domains?
if (section.domains && section.domains.includes(getDomain(url))) {
return true;
}
if (section.urlPrefixes && section.urlPrefixes.some(p => url.startsWith(p))) {
return true;
}
if (section.urls && section.urls.includes(getUrlNoHash(url))) {
return true;
}
if (section.regexps && section.regexps.some(r => compileRe(r).test(url))) {
return true;
}
return false;
}
function compileRe(text) {
let re = compiledRe.get(text);
if (!re) {
// FIXME: it should be `$({text})$` but we don't use the standard for compatibility
re = tryRegExp(`^${text}$`);
if (!re) {
re = BAD_MATCHER;
}
compiledRe.set(text, re);
}
return re;
}
function compileExclusion(text) {
let re = compiledExclusion.get(text);
if (!re) {
re = tryRegExp(buildGlob(text));
if (!re) {
re = BAD_MATCHER;
}
compiledExclusion.set(text, re);
}
return re;
}
function buildGlob(text) {
const prefix = text[0] === '^' ? '' : '\\b';
const suffix = text[text.length - 1] === '$' ? '' : '\\b';
return `${prefix}${escape(text)}${suffix}`;
function escape(text) {
// FIXME: using .* everywhere is slow
return text.replace(/[.*]/g, m => m === '.' ? '\\.' : '.*');
}
}
function getDomain(url) {
// FIXME: use a naive regexp
return url.match(/\w+:\/\//);
}
function getUrlNoHash(url) {
return url.split('#')[0];
}
2018-10-04 17:03:40 +00:00
2018-10-05 10:47:52 +00:00
// function cleanData(method, data) {
// if (
// (method === 'styleUpdated' || method === 'styleAdded') &&
// (data.sections || data.sourceCode)
// ) {
2018-10-04 17:03:40 +00:00
// apply/popup/manage use only meta for these two methods,
// editor may need the full code but can fetch it directly,
// so we send just the meta to avoid spamming lots of tabs with huge styles
2018-10-05 10:47:52 +00:00
// return getStyleWithNoCode(data);
// }
// return data;
// }
2018-10-04 17:03:40 +00:00
function isExtensionStyle(id) {
// TODO
// const style = styles.get(id);
// if (!style)
return false;
}
2018-10-05 10:47:52 +00:00
// function emitChanges(method, data) {
// const pendingPrivilage = runtimeSendMessage({method, cleanData(method, data)});
2018-10-04 17:03:40 +00:00
// const affectsAll = !msg.affects || msg.affects.all;
// const affectsOwnOriginOnly =
// !affectsAll && (msg.affects.editor || msg.affects.manager);
// const affectsTabs = affectsAll || affectsOwnOriginOnly;
// const affectsIcon = affectsAll || msg.affects.icon;
// const affectsPopup = affectsAll || msg.affects.popup;
// const affectsSelf = affectsPopup || msg.prefs;
// notify all open extension pages and popups
// if (affectsSelf) {
// msg.tabId = undefined;
// sendMessage(msg, ignoreChromeError);
// }
// notify tabs
2018-10-05 10:47:52 +00:00
// if (affectsTabs || affectsIcon) {
// const notifyTab = tab => {
// if (!styleUpdated
// && (affectsTabs || URLS.optionsUI.includes(tab.url))
2018-10-04 17:03:40 +00:00
// own pages are already notified via sendMessage
2018-10-05 10:47:52 +00:00
// && !(affectsSelf && tab.url.startsWith(URLS.ownOrigin))
2018-10-04 17:03:40 +00:00
// skip lazy-loaded aka unloaded tabs that seem to start loading on message in FF
2018-10-05 10:47:52 +00:00
// && (!FIREFOX || tab.width)) {
// msg.tabId = tab.id;
// sendMessage(msg, ignoreChromeError);
// }
// if (affectsIcon) {
2018-10-04 17:03:40 +00:00
// eslint-disable-next-line no-use-before-define
// debounce(API.updateIcon, 0, {tab});
2018-10-05 10:47:52 +00:00
// }
// };
2018-10-04 17:03:40 +00:00
// list all tabs including chrome-extension:// which can be ours
2018-10-05 10:47:52 +00:00
// Promise.all([
// queryTabs(isExtensionStyle(data.id) ? {url: URLS.ownOrigin + '*'} : {}),
// getActiveTab(),
// ]).then(([tabs, activeTab]) => {
// const activeTabId = activeTab && activeTab.id;
// for (const tab of tabs) {
// invokeOrPostpone(tab.id === activeTabId, notifyTab, tab);
// }
// });
// }
2018-10-04 17:03:40 +00:00
// notify self: the message no longer is sent to the origin in new Chrome
2018-10-05 10:47:52 +00:00
// if (typeof onRuntimeMessage !== 'undefined') {
// onRuntimeMessage(originalMessage);
// }
2018-10-04 17:03:40 +00:00
// notify apply.js on own pages
2018-10-05 10:47:52 +00:00
// if (typeof applyOnMessage !== 'undefined') {
// applyOnMessage(originalMessage);
// }
2018-10-04 17:03:40 +00:00
// propagate saved style state/code efficiently
2018-10-05 10:47:52 +00:00
// if (styleUpdated) {
// msg.refreshOwnTabs = false;
// API.refreshAllTabs(msg);
// }
// }
2018-10-03 19:35:07 +00:00
})();
2018-10-05 10:47:52 +00:00
function notifyAllTabs() {}