stylus/manage/manage.js

725 lines
22 KiB
JavaScript
Raw Normal View History

2018-01-01 17:02:49 +00:00
/*
global messageBox getStyleWithNoCode retranslateCSS
global filtersSelector filterAndAppend urlFilterParam showFiltersStats
2018-01-01 17:02:49 +00:00
global checkUpdate handleUpdateInstalled
global objectDiff
global configDialog
2018-10-06 05:27:58 +00:00
global sorter msg
2018-01-01 17:02:49 +00:00
*/
'use strict';
2015-01-30 17:31:20 +00:00
let installed;
const ENTRY_ID_PREFIX_RAW = 'style-';
const ENTRY_ID_PREFIX = '#' + ENTRY_ID_PREFIX_RAW;
const newUI = {
enabled: prefs.get('manage.newUI'),
favicons: prefs.get('manage.newUI.favicons'),
faviconsGray: prefs.get('manage.newUI.faviconsGray'),
targets: prefs.get('manage.newUI.targets'),
renderClass() {
document.documentElement.classList.toggle('newUI', newUI.enabled);
},
};
newUI.renderClass();
2017-12-26 05:54:01 +00:00
requestAnimationFrame(usePrefsDuringPageLoad);
2018-01-25 01:42:02 +00:00
const TARGET_TYPES = ['domains', 'urls', 'urlPrefixes', 'regexps', 'exclusions'];
const GET_FAVICON_URL = 'https://www.google.com/s2/favicons?domain=';
const OWN_ICON = chrome.runtime.getManifest().icons['16'];
const handleEvent = {};
Promise.all([
2018-10-04 17:03:40 +00:00
API.getStylesInfo(),
2018-01-01 17:02:49 +00:00
urlFilterParam && API.searchDB({query: 'url:' + urlFilterParam}),
onDOMready().then(initGlobalEvents),
2018-01-01 17:02:49 +00:00
]).then(args => {
showStyles(...args);
});
2018-10-06 05:02:45 +00:00
msg.onExtension(onRuntimeMessage);
function onRuntimeMessage(msg) {
switch (msg.method) {
case 'styleUpdated':
case 'styleAdded':
handleUpdate(msg.style, msg);
break;
case 'styleDeleted':
handleDelete(msg.id);
break;
case 'styleApply':
case 'styleReplaceAll':
break;
default:
return;
}
setTimeout(sorter.updateStripes, 0, {onlyWhenColumnsChanged: true});
}
2015-01-30 17:31:20 +00:00
function initGlobalEvents() {
installed = $('#installed');
installed.onclick = handleEvent.entryClicked;
$('#manage-options-button').onclick = () => chrome.runtime.openOptionsPage();
2018-04-12 18:02:34 +00:00
{
const btn = $('#manage-shortcuts-button');
btn.onclick = btn.onclick || (() => openURL({url: URLS.configureCommands}));
}
$$('#header a[href^="http"]').forEach(a => (a.onclick = handleEvent.external));
2017-12-23 00:11:46 +00:00
// show date installed & last update on hover
installed.addEventListener('mouseover', handleEvent.lazyAddEntryTitle);
installed.addEventListener('mouseout', handleEvent.lazyAddEntryTitle);
document.addEventListener('visibilitychange', onVisibilityChange);
$$('[data-toggle-on-click]').forEach(el => {
// dataset on SVG doesn't work in Chrome 49-??, works in 57+
const target = $(el.getAttribute('data-toggle-on-click'));
el.onclick = event => {
event.preventDefault();
target.classList.toggle('hidden');
if (target.classList.contains('hidden')) {
el.removeAttribute('open');
} else {
el.setAttribute('open', '');
}
};
});
// triggered automatically by setupLivePrefs() below
2017-04-13 07:54:56 +00:00
enforceInputRange($('#manage.newUI.targets'));
// N.B. triggers existing onchange listeners
setupLivePrefs();
2017-12-23 00:11:46 +00:00
sorter.init();
$$('[id^="manage.newUI"]')
.forEach(el => (el.oninput = (el.onchange = switchUI)));
switchUI({styleOnly: true});
// translate CSS manually
document.head.appendChild($create('style', `
.disabled h2::after {
content: "${t('genericDisabledLabel')}";
}
#update-all-no-updates[data-skipped-edited="true"]::after {
content: " ${t('updateAllCheckSucceededSomeEdited')}";
}
body.all-styles-hidden-by-filters::after {
content: "${t('filteredStylesAllHidden')}";
}
`));
2015-01-30 17:31:20 +00:00
}
2018-01-01 17:02:49 +00:00
function showStyles(styles = [], matchUrlIds) {
2017-12-23 00:11:46 +00:00
const sorted = sorter.sort({
styles: styles.map(style => ({
style,
2018-01-25 01:42:02 +00:00
name: (style.name || '').toLocaleLowerCase() + '\n' + style.name,
2017-12-23 00:11:46 +00:00
})),
});
let index = 0;
let firstRun = true;
2017-12-23 00:11:46 +00:00
installed.dataset.total = styles.length;
const scrollY = (history.state || {}).scrollY;
const shouldRenderAll = scrollY > window.innerHeight || sessionStorage.justEditedStyleId;
const renderBin = document.createDocumentFragment();
if (scrollY) {
renderStyles();
} else {
requestAnimationFrame(renderStyles);
}
function renderStyles() {
const t0 = performance.now();
let rendered = 0;
2017-07-12 20:44:59 +00:00
while (
index < sorted.length &&
// eslint-disable-next-line no-unmodified-loop-condition
(shouldRenderAll || ++rendered < 20 || performance.now() - t0 < 10)
2017-07-12 20:44:59 +00:00
) {
2018-01-01 17:02:49 +00:00
const info = sorted[index++];
const entry = createStyleElement(info);
if (matchUrlIds && !matchUrlIds.includes(info.style.id)) {
entry.classList.add('not-matching');
rendered--;
}
renderBin.appendChild(entry);
}
filterAndAppend({container: renderBin}).then(sorter.updateStripes);
if (index < sorted.length) {
requestAnimationFrame(renderStyles);
if (firstRun) setTimeout(getFaviconImgSrc);
firstRun = false;
return;
}
setTimeout(getFaviconImgSrc);
if (sessionStorage.justEditedStyleId) {
highlightEditedStyle();
} else if ('scrollY' in (history.state || {})) {
setTimeout(window.scrollTo, 0, 0, history.state.scrollY);
}
}
2015-01-30 17:31:20 +00:00
}
function createStyleElement({style, name}) {
// query the sub-elements just once, then reuse the references
if ((createStyleElement.parts || {}).newUI !== newUI.enabled) {
const entry = template[`style${newUI.enabled ? 'Compact' : ''}`];
createStyleElement.parts = {
newUI: newUI.enabled,
entry,
entryClassBase: entry.className,
checker: $('.checker', entry) || {},
nameLink: $('.style-name-link', entry),
editLink: $('.style-edit-link', entry) || {},
editHrefBase: 'edit.html?id=',
homepage: $('.homepage', entry),
homepageIcon: template[`homepageIcon${newUI.enabled ? 'Small' : 'Big'}`],
appliesTo: $('.applies-to', entry),
targets: $('.targets', entry),
expander: $('.expander', entry),
decorations: {
urlPrefixesAfter: '*',
regexpsBefore: '/',
regexpsAfter: '/',
},
2018-01-04 19:35:12 +00:00
oldConfigure: !newUI.enabled && $('.configure-usercss', entry),
oldCheckUpdate: !newUI.enabled && $('.check-update', entry),
oldUpdate: !newUI.enabled && $('.update', entry),
};
}
const parts = createStyleElement.parts;
2018-10-04 17:03:40 +00:00
const configurable = style.usercssData && style.usercssData.vars && Object.keys(style.usercssData.vars).length > 0;
parts.checker.checked = style.enabled;
parts.nameLink.textContent = tWordBreak(style.name);
parts.nameLink.href = parts.editLink.href = parts.editHrefBase + style.id;
parts.homepage.href = parts.homepage.title = style.url || '';
if (!newUI.enabled) {
2018-01-04 19:35:12 +00:00
parts.oldConfigure.classList.toggle('hidden', !configurable);
parts.oldCheckUpdate.classList.toggle('hidden', !style.updateUrl);
parts.oldUpdate.classList.toggle('hidden', !style.updateUrl);
}
// clear the code to free up some memory
// (note, style is already a deep copy)
style.sourceCode = null;
style.sections.forEach(section => (section.code = null));
const entry = parts.entry.cloneNode(true);
entry.id = ENTRY_ID_PREFIX_RAW + style.id;
entry.styleId = style.id;
entry.styleNameLowerCase = name || style.name.toLocaleLowerCase();
entry.styleMeta = style;
entry.className = parts.entryClassBase + ' ' +
(style.enabled ? 'enabled' : 'disabled') +
(style.updateUrl ? ' updatable' : '') +
(style.usercssData ? ' usercss' : '');
2017-09-01 10:24:32 +00:00
if (style.url) {
$('.homepage', entry).appendChild(parts.homepageIcon.cloneNode(true));
}
if (style.updateUrl && newUI.enabled) {
$('.actions', entry).appendChild(template.updaterIcons.cloneNode(true));
}
2018-01-04 19:35:12 +00:00
if (configurable && newUI.enabled) {
Add: install styles from *.user.css file Fix: handle dup name+namespace Fix: eslint eqeqeq Fix: trim @name's spaces Add: check update for userstyle Add: build CSS variable Fix: only check dup when id is not provided Refactor: userStyle2json -> userstyle.json Add: style for input Add: config dialog Fix: preserve config during update Fix: onchange doesn't fire on keyboard enter event Fix: remove empty file Add: validator. Metas must stay in the same line Add: warn the user if installation failed Fix: add some delay before starting installation Add: open the editor after first installation Fix: add openEditor to globals Fix: i18n Add: preprocessor. Move userstyle.build to background page. Fix: remove unused global Fix: preserved unknown prop in saveStyleSource() like saveStyle() Add: edit userstyle source Fix: load preprocessor dynamically Fix: load content script dynamically Fix: buildCode is async function Fix: drop Object.entries Fix: style.sections is undefined Fix: don't hide the name input but disable it Fix: query the style before installation Revert: changes to editor, editor.html Refactor: use term `usercss` instead of `userstyle` Fix: don't show homepage action for usercss Refactor: move script-loader to js/ Refactor: pull out mozParser Fix: code style Fix: we don't need to build meta anymore Fix: use saveUsercss instead of saveStyle to get responsed error Fix: last is undefined, load script error Fix: switch to moz-format Fix: drop injectContentScript. Move usercss check into install-user-css Fix: response -> respond Fix: globals -> global Fix: queryUsercss -> filterUsercss Fix: add processUsercss function Fix: only open editor for usercss Fix: remove findupUsercss fixme Fix: globals -> global Fix: globals -> global Fix: global pollution Revert: update.js Refactor: checkStyle Add: support usercss Fix: no need to getURL in background page Fix: merget semver.js into usercss.js Fix: drop all_urls in match pattern Fix: drop respondWithError Move stylus -> stylus-lang Add stylus-lang/readme Fix: use include_globs Fix: global pollution
2017-08-05 16:49:25 +00:00
$('.actions', entry).appendChild(template.configureIcon.cloneNode(true));
}
createStyleTargetsElement({entry, style});
return entry;
}
function createStyleTargetsElement({entry, style}) {
const parts = createStyleElement.parts;
const entryTargets = $('.targets', entry);
const targets = parts.targets.cloneNode(true);
let container = targets;
let numTargets = 0;
const displayed = new Set();
for (const type of TARGET_TYPES) {
2018-01-25 01:42:02 +00:00
const isExcluded = type === 'exclusions';
const sections = isExcluded ? [''] : style.sections;
if (isExcluded && !newUI.enabled && Object.keys(style.exclusions || {}).length > 0) {
$('.applies-to', entry).insertAdjacentElement('afterend', template.excludedOn.cloneNode(true));
container = $('.excluded-on .targets', entry);
numTargets = 1;
}
for (const section of sections) {
const target = isExcluded ? Object.keys(style.exclusions || {}) : section[type] || [];
for (const targetValue of target) {
if (displayed.has(targetValue)) {
continue;
}
displayed.add(targetValue);
const element = template.appliesToTarget.cloneNode(true);
if (!newUI.enabled) {
2017-07-16 18:02:00 +00:00
if (numTargets === 10) {
container = container.appendChild(template.extraAppliesTo.cloneNode(true));
} else if (numTargets > 0) {
container.appendChild(template.appliesToSeparator.cloneNode(true));
}
}
element.dataset.type = type;
element.appendChild(
document.createTextNode(
(parts.decorations[type + 'Before'] || '') +
targetValue +
(parts.decorations[type + 'After'] || '')));
container.appendChild(element);
numTargets++;
}
}
}
if (newUI.enabled) {
if (numTargets > newUI.targets) {
$('.applies-to', entry).classList.add('has-more');
}
}
if (numTargets) {
entryTargets.parentElement.replaceChild(targets, entryTargets);
} else if (!entry.classList.contains('global') ||
!entryTargets.firstElementChild) {
if (entryTargets.firstElementChild) {
entryTargets.textContent = '';
}
entryTargets.appendChild(template.appliesToEverything.cloneNode(true));
}
entry.classList.toggle('global', !numTargets);
2015-01-30 17:31:20 +00:00
}
2018-01-11 21:53:22 +00:00
function getFaviconImgSrc(container = installed) {
if (!newUI.enabled || !newUI.favicons) return;
const regexpRemoveNegativeLookAhead = /(\?!([^)]+\))|\(\?![\w(]+[^)]+[\w|)]+)/g;
// replace extra characters & all but the first group entry "(abc|def|ghi)xyz" => abcxyz
const regexpReplaceExtraCharacters = /[\\(]|((\|\w+)+\))/g;
2018-07-28 18:05:20 +00:00
const regexpMatchRegExp = /[\w-]+[.(]+(com|org|co|net|im|io|edu|gov|biz|info|de|cn|uk|nl|eu|ru)\b/g;
const regexpMatchDomain = /^.*?:\/\/([^/]+)/;
2018-07-28 18:05:20 +00:00
for (const target of $$('.target', container)) {
const type = target.dataset.type;
const targetValue = target.textContent;
2018-07-28 18:04:29 +00:00
if (!targetValue) continue;
let favicon = '';
if (type === 'domains') {
favicon = GET_FAVICON_URL + targetValue;
} else if (targetValue.includes('chrome-extension:') || targetValue.includes('moz-extension:')) {
favicon = OWN_ICON;
2018-01-25 01:42:02 +00:00
} else if (type === 'regexps' || type === 'exclusions') {
favicon = targetValue
.replace(regexpRemoveNegativeLookAhead, '')
.replace(regexpReplaceExtraCharacters, '')
.match(regexpMatchRegExp);
favicon = favicon ? GET_FAVICON_URL + favicon.shift() : '';
} else {
favicon = targetValue.includes('://') && targetValue.match(regexpMatchDomain);
favicon = favicon ? GET_FAVICON_URL + favicon[1] : '';
}
if (favicon) {
const img = target.children[0];
if (!img || img.localName !== 'img') {
target.insertAdjacentElement('afterbegin', document.createElement('img'))
.dataset.src = favicon;
} else if ((img.dataset.src || img.src) !== favicon) {
img.src = '';
img.dataset.src = favicon;
}
}
}
handleEvent.loadFavicons();
}
Object.assign(handleEvent, {
ENTRY_ROUTES: {
'.checker, .enable, .disable': 'toggle',
'.style-name': 'name',
'.homepage': 'external',
'.check-update': 'check',
'.update': 'update',
'.delete': 'delete',
'.applies-to .expander': 'expandTargets',
'.configure-usercss': 'config'
Add: install styles from *.user.css file Fix: handle dup name+namespace Fix: eslint eqeqeq Fix: trim @name's spaces Add: check update for userstyle Add: build CSS variable Fix: only check dup when id is not provided Refactor: userStyle2json -> userstyle.json Add: style for input Add: config dialog Fix: preserve config during update Fix: onchange doesn't fire on keyboard enter event Fix: remove empty file Add: validator. Metas must stay in the same line Add: warn the user if installation failed Fix: add some delay before starting installation Add: open the editor after first installation Fix: add openEditor to globals Fix: i18n Add: preprocessor. Move userstyle.build to background page. Fix: remove unused global Fix: preserved unknown prop in saveStyleSource() like saveStyle() Add: edit userstyle source Fix: load preprocessor dynamically Fix: load content script dynamically Fix: buildCode is async function Fix: drop Object.entries Fix: style.sections is undefined Fix: don't hide the name input but disable it Fix: query the style before installation Revert: changes to editor, editor.html Refactor: use term `usercss` instead of `userstyle` Fix: don't show homepage action for usercss Refactor: move script-loader to js/ Refactor: pull out mozParser Fix: code style Fix: we don't need to build meta anymore Fix: use saveUsercss instead of saveStyle to get responsed error Fix: last is undefined, load script error Fix: switch to moz-format Fix: drop injectContentScript. Move usercss check into install-user-css Fix: response -> respond Fix: globals -> global Fix: queryUsercss -> filterUsercss Fix: add processUsercss function Fix: only open editor for usercss Fix: remove findupUsercss fixme Fix: globals -> global Fix: globals -> global Fix: global pollution Revert: update.js Refactor: checkStyle Add: support usercss Fix: no need to getURL in background page Fix: merget semver.js into usercss.js Fix: drop all_urls in match pattern Fix: drop respondWithError Move stylus -> stylus-lang Add stylus-lang/readme Fix: use include_globs Fix: global pollution
2017-08-05 16:49:25 +00:00
},
entryClicked(event) {
const target = event.target;
const entry = target.closest('.entry');
for (const selector in handleEvent.ENTRY_ROUTES) {
2017-07-16 18:02:00 +00:00
for (let el = target; el && el !== entry; el = el.parentElement) {
if (el.matches(selector)) {
const handler = handleEvent.ENTRY_ROUTES[selector];
return handleEvent[handler].call(el, event, entry);
}
}
}
},
name(event) {
if (newUI.enabled) handleEvent.edit(event);
},
edit(event) {
if (event.altKey) {
return;
}
event.preventDefault();
event.stopPropagation();
2017-07-16 18:02:00 +00:00
const left = event.button === 0;
const middle = event.button === 1;
const shift = event.shiftKey;
const ctrl = event.ctrlKey;
const openWindow = left && shift && !ctrl;
const openBackgroundTab = (middle && !shift) || (left && ctrl && !shift);
const openForegroundTab = (middle && shift) || (left && ctrl && shift);
const url = $('[href]', event.target.closest('.entry')).href;
if (openWindow || openBackgroundTab || openForegroundTab) {
2017-11-25 13:24:07 +00:00
if (chrome.windows && openWindow) {
chrome.windows.create(Object.assign(prefs.get('windowPosition'), {url}));
} else {
getOwnTab().then(({index}) => {
openURL({
url,
index: index + 1,
active: openForegroundTab
});
});
}
} else {
onVisibilityChange();
getActiveTab().then(tab => {
sessionStorageHash('manageStylesHistory').set(tab.id, url);
location.href = url;
});
}
},
toggle(event, entry) {
2018-10-04 17:03:40 +00:00
API.toggleStyle(entry.styleId, this.matches('.enable') || this.checked);
},
check(event, entry) {
event.preventDefault();
2018-01-01 17:02:49 +00:00
checkUpdate(entry, {single: true});
},
update(event, entry) {
event.preventDefault();
2018-01-01 17:02:49 +00:00
const json = entry.updatedCode;
json.id = entry.styleId;
2018-10-07 14:59:31 +00:00
// json.reason = 'update';
API[json.usercssData ? 'installUsercss' : 'installStyle'](json);
},
delete(event, entry) {
event.preventDefault();
const id = entry.styleId;
animateElement(entry);
messageBox({
title: t('deleteStyleConfirm'),
2018-01-01 17:02:49 +00:00
contents: entry.styleMeta.name,
className: 'danger center',
buttons: [t('confirmDelete'), t('confirmCancel')],
})
.then(({button}) => {
if (button === 0) {
2018-10-05 10:47:52 +00:00
API.deleteStyle(id);
}
});
},
external(event) {
if (event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey) {
// Shift-click = the built-in 'open in a new window' action
return;
}
getOwnTab().then(({index}) => {
openURL({
url: event.target.closest('a').href,
index: index + 1,
active: !event.ctrlKey || event.shiftKey,
});
});
event.preventDefault();
},
expandTargets(event) {
event.preventDefault();
this.closest('.applies-to').classList.toggle('expanded');
},
loadFavicons({all = false} = {}) {
if (!installed.firstElementChild) return;
let favicons = [];
if (all) {
favicons = $$('img[data-src]', installed);
} else {
const {left, top} = installed.firstElementChild.getBoundingClientRect();
const x = Math.max(0, left);
const y = Math.max(0, top);
const first = document.elementFromPoint(x, y);
const lastOffset = first.offsetTop + window.innerHeight;
const numTargets = prefs.get('manage.newUI.targets');
let entry = first && first.closest('.entry') || installed.children[0];
while (entry && entry.offsetTop <= lastOffset) {
favicons.push(...$$('img', entry).slice(0, numTargets).filter(img => img.dataset.src));
entry = entry.nextElementSibling;
}
}
let i = 0;
for (const img of favicons) {
img.src = img.dataset.src;
delete img.dataset.src;
// loading too many icons at once will block the page while the new layout is recalculated
if (++i > 100) break;
}
if ($('img[data-src]', installed)) {
debounce(handleEvent.loadFavicons, 1, {all: true});
}
},
config(event, {styleMeta}) {
event.preventDefault();
configDialog(styleMeta);
},
2017-12-23 00:11:46 +00:00
lazyAddEntryTitle({type, target}) {
const cell = target.closest('h2.style-name');
if (cell) {
const link = $('.style-name-link', cell);
if (type === 'mouseover' && !link.title) {
debounce(handleEvent.addEntryTitle, 50, link);
} else {
debounce.unregister(handleEvent.addEntryTitle);
}
}
},
addEntryTitle(link) {
const entry = link.closest('.entry');
link.title = [
{prop: 'installDate', name: 'dateInstalled'},
{prop: 'updateDate', name: 'dateUpdated'},
].map(({prop, name}) =>
t(name) + ': ' + (formatDate(entry.styleMeta[prop]) || '—')).join('\n');
}
});
2015-01-30 17:31:20 +00:00
2018-07-21 18:04:47 +00:00
function handleUpdate(style, {reason, method} = {}) {
if (reason === 'editPreview') return;
// the style was toggled and refreshAllTabs() sent a mini-notification,
// but we've already processed 'styleUpdated' sent directly from notifyAllTabs()
if (!style.sections) return;
let entry;
let oldEntry = $(ENTRY_ID_PREFIX + style.id);
2017-07-16 18:02:00 +00:00
if (oldEntry && method === 'styleUpdated') {
2017-04-26 15:35:00 +00:00
handleToggledOrCodeOnly();
}
entry = entry || createStyleElement({style});
if (oldEntry) {
2017-07-16 18:02:00 +00:00
if (oldEntry.styleNameLowerCase === entry.styleNameLowerCase) {
installed.replaceChild(entry, oldEntry);
} else {
oldEntry.remove();
}
}
if ((reason === 'update' || reason === 'install') && entry.matches('.updatable')) {
handleUpdateInstalled(entry, reason);
}
filterAndAppend({entry}).then(sorter.update);
2017-07-16 18:02:00 +00:00
if (!entry.matches('.hidden') && reason !== 'import') {
animateElement(entry);
2018-01-01 17:02:49 +00:00
requestAnimationFrame(() => scrollElementIntoView(entry));
}
getFaviconImgSrc(entry);
2017-04-26 15:35:00 +00:00
function handleToggledOrCodeOnly() {
const newStyleMeta = getStyleWithNoCode(style);
const diff = objectDiff(oldEntry.styleMeta, newStyleMeta)
.filter(({key, path}) => path || (!key.startsWith('original') && !key.endsWith('Date')));
2017-07-16 18:02:00 +00:00
if (diff.length === 0) {
// only code was modified
entry = oldEntry;
oldEntry = null;
}
2017-07-16 18:02:00 +00:00
if (diff.length === 1 && diff[0].key === 'enabled') {
oldEntry.classList.toggle('enabled', style.enabled);
oldEntry.classList.toggle('disabled', !style.enabled);
$$('.checker', oldEntry).forEach(el => (el.checked = style.enabled));
oldEntry.styleMeta = newStyleMeta;
entry = oldEntry;
oldEntry = null;
}
}
2015-01-30 17:31:20 +00:00
}
2015-01-30 17:31:20 +00:00
function handleDelete(id) {
const node = $(ENTRY_ID_PREFIX + id);
if (node) {
node.remove();
if (node.matches('.can-update')) {
const btnApply = $('#apply-all-updates');
btnApply.dataset.value = Number(btnApply.dataset.value) - 1;
}
showFiltersStats();
}
2015-01-30 17:31:20 +00:00
}
function switchUI({styleOnly} = {}) {
const current = {};
const changed = {};
let someChanged = false;
// ensure the global option is processed first
for (const el of [$('#manage.newUI'), ...$$('[id^="manage.newUI."]')]) {
const id = el.id.replace(/^manage\.newUI\.?/, '') || 'enabled';
2017-07-16 18:02:00 +00:00
const value = el.type === 'checkbox' ? el.checked : Number(el.value);
const valueChanged = value !== newUI[id] && (id === 'enabled' || current.enabled);
current[id] = value;
changed[id] = valueChanged;
someChanged |= valueChanged;
}
if (!styleOnly && !someChanged) {
return;
}
Object.assign(newUI, current);
newUI.renderClass();
installed.classList.toggle('has-favicons', newUI.favicons);
$('#style-overrides').textContent = `
.newUI .targets {
max-height: ${newUI.targets * 18}px;
}
2018-01-25 01:42:02 +00:00
.newUI .target[data-type="exclusions"]:before {
content: '${t('exclusionsPrefix')}';
}
` + (newUI.faviconsGray ? `
.newUI .target img {
-webkit-filter: grayscale(1);
filter: grayscale(1);
opacity: .25;
}
` : `
.newUI .target img {
-webkit-filter: none;
filter: none;
opacity: 1;
}
`) + (CHROME >= 3004 ? `
.newUI .entry {
contain: strict;
}
.newUI .entry > * {
contain: content;
}
.newUI .entry .actions {
contain: none;
}
.newUI .target {
contain: layout style;
}
.newUI .target img {
contain: layout style size;
}
.newUI .entry.can-update,
.newUI .entry.update-problem,
.newUI .entry.update-done {
contain: none;
}
` : '');
if (styleOnly) {
return;
}
const missingFavicons = newUI.enabled && newUI.favicons && !$('.applies-to img');
if (changed.enabled || (missingFavicons && !createStyleElement.parts)) {
2017-07-19 08:19:15 +00:00
installed.textContent = '';
2018-10-05 10:47:52 +00:00
API.getStylesInfo().then(showStyles);
return;
}
if (changed.targets) {
for (const targets of $$('.entry .targets')) {
const hasMore = targets.children.length > newUI.targets;
targets.parentElement.classList.toggle('has-more', hasMore);
}
return;
}
if (missingFavicons) {
debounce(getFaviconImgSrc);
return;
}
}
function onVisibilityChange() {
switch (document.visibilityState) {
// page restored without reloading via history navigation (currently only in FF)
// the catch here is that DOM may be outdated so we'll at least refresh the just edited style
// assuming other changes aren't important enough to justify making a complicated DOM sync
case 'visible':
if (sessionStorage.justEditedStyleId) {
2018-10-05 10:47:52 +00:00
API.getStylesInfo({
id: sessionStorage.justEditedStyleId
}).then(([style]) => {
handleUpdate(style, {method: 'styleUpdated'});
});
delete sessionStorage.justEditedStyleId;
}
break;
// going away
case 'hidden':
history.replaceState({scrollY: window.scrollY}, document.title);
break;
}
}
function highlightEditedStyle() {
if (!sessionStorage.justEditedStyleId) return;
const entry = $(ENTRY_ID_PREFIX + sessionStorage.justEditedStyleId);
delete sessionStorage.justEditedStyleId;
if (entry) {
animateElement(entry);
requestAnimationFrame(() => scrollElementIntoView(entry));
}
}
function usePrefsDuringPageLoad() {
2017-12-26 05:54:01 +00:00
for (const id of Object.getOwnPropertyNames(prefs.readOnlyValues)) {
const value = prefs.readOnlyValues[id];
if (value !== true) continue;
const el = document.getElementById(id) ||
id.includes('expanded') && $(`details[data-pref="${id}"]`);
if (!el) continue;
if (el.type === 'checkbox') {
el.checked = value;
} else if (el.localName === 'details') {
el.open = value;
} else {
el.value = value;
2017-08-22 14:22:15 +00:00
}
}
if (!VIVALDI) {
$$('#header select').forEach(el => el.adjustWidth());
}
2018-04-12 18:02:34 +00:00
if (FIREFOX && 'update' in (chrome.commands || {})) {
const btn = $('#manage-shortcuts-button');
btn.classList.remove('chromium-only');
btn.onclick = API.optionsCustomizeHotkeys;
}
}