Compare commits

...

8 Commits

Author SHA1 Message Date
tophf
fc39f0d5a6 parserlib: dot-separated layer names 2022-10-19 22:47:19 +03:00
tophf
1725c0ecb9 show installed styles in popup finder
fixes #1488
2022-10-12 20:04:45 +03:00
tophf
79dff2775b add upDownKeyJumps option, remove left/right 2022-10-08 13:07:57 +03:00
tophf
b22bbaaec0 make <iframe> more evident 2022-10-08 13:05:40 +03:00
tophf
fff59ee12f use a self-explanatory "..." in #write-for-frames 2022-09-17 21:42:39 +03:00
tophf
540e2af62c micro-optimize colorConverter.parse
#hex, named colors: 15x faster
rgb() and other functions: 1.6x faster
2022-09-17 20:10:18 +03:00
tophf
0128489bbb unbork rgb colors with % 2022-09-17 01:29:11 +03:00
dependabot[bot]
a5b11ac687
Bump node-forge and web-ext (#1474) 2022-09-16 16:24:27 +03:00
17 changed files with 2520 additions and 5306 deletions

View File

@ -186,6 +186,10 @@
"message": "Theme", "message": "Theme",
"description": "Label for the style editor's CSS theme." "description": "Label for the style editor's CSS theme."
}, },
"cm_arrowKeysTraverse": {
"message": "Arrow keys ↑↓ traverse sections",
"description": "Label for the option in the editor."
},
"colorpickerPaletteHint": { "colorpickerPaletteHint": {
"message": "Right-click a swatch to cycle through its source lines" "message": "Right-click a swatch to cycle through its source lines"
}, },

View File

@ -199,6 +199,18 @@ const styleMan = (() => {
getOrder: () => orderWrap.value, getOrder: () => orderWrap.value,
/** @returns {Promise<string | {[remoteId:string]: styleId}>}>} */
async getRemoteInfo(id) {
if (ready.then) await ready;
if (id) return calcRemoteId(id2style(id));
const res = {};
for (const {style} of dataMap.values()) {
const [rid, vars] = calcRemoteId(style);
if (rid) res[rid] = [style.id, vars];
}
return res;
},
/** @returns {Promise<StyleSectionsToApply>} */ /** @returns {Promise<StyleSectionsToApply>} */
async getSectionsByUrl(url, id, isInitialApply) { async getSectionsByUrl(url, id, isInitialApply) {
if (ready.then) await ready; if (ready.then) await ready;
@ -366,6 +378,17 @@ const styleMan = (() => {
return id2style(uuidIndex.get(uuid)); return id2style(uuidIndex.get(uuid));
} }
function calcRemoteId({md5Url, updateUrl, usercssData: ucd} = {}) {
let id;
id = (id = /\d+/.test(md5Url) || URLS.extractUsoArchiveId(updateUrl)) && `uso-${id}`
|| (id = URLS.extractUSwId(updateUrl)) && `usw-${id}`
|| '';
return id && [
id,
ucd && !isEmptyObj(ucd.vars),
];
}
/** @returns {StyleObj} */ /** @returns {StyleObj} */
function createNewStyle() { function createNewStyle() {
return /** @namespace StyleObj */ { return /** @namespace StyleObj */ {

View File

@ -338,6 +338,12 @@
<svg class="svg-icon checked"><use xlink:href="#svg-icon-checked"/></svg> <svg class="svg-icon checked"><use xlink:href="#svg-icon-checked"/></svg>
</label> </label>
</div> </div>
<div class="option sectioned-only">
<label i18n="cm_arrowKeysTraverse">
<input id="editor.arrowKeysTraverse" type="checkbox">
<svg class="svg-icon checked"><use xlink:href="#svg-icon-checked"/></svg>
</label>
</div>
<div class="option"> <div class="option">
<label i18n="cm_colorpicker"> <label i18n="cm_colorpicker">
<input id="editor.colorpicker" type="checkbox"> <input id="editor.colorpicker" type="checkbox">

View File

@ -67,6 +67,7 @@
k.slice('editor.'.length); k.slice('editor.'.length);
const prefKeys = prefs.knownKeys.filter(k => const prefKeys = prefs.knownKeys.filter(k =>
k !== 'editor.colorpicker' && // handled in colorpicker-helper.js k !== 'editor.colorpicker' && // handled in colorpicker-helper.js
k !== 'editor.arrowKeysTraverse' && // handled in sections-editor.js
prefToCmOpt(k) in CodeMirror.defaults); prefToCmOpt(k) in CodeMirror.defaults);
const {insertTab, insertSoftTab} = CodeMirror.commands; const {insertTab, insertSoftTab} = CodeMirror.commands;

View File

@ -75,8 +75,8 @@ html:not(.is-new-style) #heading::before {
right: 24px; right: 24px;
} }
/************ checkbox & select************/ /************ checkbox & select************/
.options-column > div[class="option"] { .options-column > .option {
margin-bottom: 4px; margin-bottom: .25rem;
} }
.options-column > .usercss-only { .options-column > .usercss-only {
@ -107,6 +107,8 @@ label {
} }
#sections { #sections {
padding-left: var(--header-width); padding-left: var(--header-width);
}
.usercss #sections {
min-height: 0; min-height: 0;
height: 100%; height: 100%;
} }

View File

@ -31,6 +31,7 @@ function createSection(originalSection, genId, si) {
value: originalSection.code, value: originalSection.code,
}); });
el.CodeMirror = cm; // used by getAssociatedEditor el.CodeMirror = cm; // used by getAssociatedEditor
cm.el = el;
editor.applyScrollInfo(cm, si); editor.applyScrollInfo(cm, si);
const changeListeners = new Set(); const changeListeners = new Set();
@ -114,49 +115,10 @@ function createSection(originalSection, genId, si) {
changeGeneration = newGeneration; changeGeneration = newGeneration;
emitSectionChange('code'); emitSectionChange('code');
}); });
cm.display.wrapper.on('keydown', event => handleKeydown(cm, event), true);
$('.test-regexp', el).onclick = () => updateRegexpTester(true); $('.test-regexp', el).onclick = () => updateRegexpTester(true);
initBeautifyButton($('.beautify-section', el), [cm]); initBeautifyButton($('.beautify-section', el), [cm]);
} }
function handleKeydown(cm, event) {
if (event.shiftKey || event.altKey || event.metaKey) {
return;
}
const {key} = event;
const {line, ch} = cm.getCursor();
switch (key) {
case 'ArrowLeft':
if (line || ch) {
return;
}
// fallthrough
case 'ArrowUp':
cm = line === 0 && editor.prevEditor(cm, false);
if (!cm) {
return;
}
event.preventDefault();
event.stopPropagation();
cm.setCursor(cm.doc.size - 1, key === 'ArrowLeft' ? 1e20 : ch);
break;
case 'ArrowRight':
if (line < cm.doc.size - 1 || ch < cm.getLine(line).length - 1) {
return;
}
// fallthrough
case 'ArrowDown':
cm = line === cm.doc.size - 1 && editor.nextEditor(cm, false);
if (!cm) {
return;
}
event.preventDefault();
event.stopPropagation();
cm.setCursor(0, 0);
break;
}
}
async function updateRegexpTester(toggle) { async function updateRegexpTester(toggle) {
const isLoaded = typeof regexpTester === 'object' || const isLoaded = typeof regexpTester === 'object' ||
toggle && await require(['/edit/regexp-tester']); /* global regexpTester */ toggle && await require(['/edit/regexp-tester']); /* global regexpTester */

View File

@ -6,6 +6,7 @@
/* global createSection */// sections-editor-section.js /* global createSection */// sections-editor-section.js
/* global editor */ /* global editor */
/* global linterMan */ /* global linterMan */
/* global prefs */
/* global styleSectionsEqual */ // sections-util.js /* global styleSectionsEqual */ // sections-util.js
/* global t */// localization.js /* global t */// localization.js
'use strict'; 'use strict';
@ -21,6 +22,7 @@ function SectionsEditor() {
let sectionOrder = ''; let sectionOrder = '';
let headerOffset; // in compact mode the header is at the top so it reduces the available height let headerOffset; // in compact mode the header is at the top so it reduces the available height
let cmExtrasHeight; // resize grip + borders let cmExtrasHeight; // resize grip + borders
let upDownJumps;
updateMeta(); updateMeta();
rerouteHotkeys.toggle(true); // enabled initially because we don't always focus a CodeMirror rerouteHotkeys.toggle(true); // enabled initially because we don't always focus a CodeMirror
@ -30,6 +32,10 @@ function SectionsEditor() {
$('#from-mozilla').on('click', () => showMozillaFormatImport()); $('#from-mozilla').on('click', () => showMozillaFormatImport());
document.on('wheel', scrollEntirePageOnCtrlShift, {passive: false}); document.on('wheel', scrollEntirePageOnCtrlShift, {passive: false});
CodeMirror.defaults.extraKeys['Shift-Ctrl-Wheel'] = 'scrollWindow'; CodeMirror.defaults.extraKeys['Shift-Ctrl-Wheel'] = 'scrollWindow';
prefs.subscribe('editor.arrowKeysTraverse', (_, val) => {
for (const {cm} of sections) handleKeydownSetup(cm, val);
upDownJumps = val;
}, {runNow: true});
/** @namespace Editor */ /** @namespace Editor */
Object.assign(editor, { Object.assign(editor, {
@ -70,15 +76,15 @@ function SectionsEditor() {
} }
}, },
nextEditor(cm, cycle = true) { nextEditor(cm, upDown) {
return cycle || cm !== findLast(sections, s => !s.removed).cm return !upDown || cm !== findLast(sections, s => !s.removed).cm
? nextPrevEditor(cm, 1) ? nextPrevEditor(cm, 1, upDown)
: null; : null;
}, },
prevEditor(cm, cycle = true) { prevEditor(cm, upDown) {
return cycle || cm !== sections.find(s => !s.removed).cm return !upDown || cm !== sections.find(s => !s.removed).cm
? nextPrevEditor(cm, -1) ? nextPrevEditor(cm, -1, upDown)
: null; : null;
}, },
@ -112,14 +118,16 @@ function SectionsEditor() {
editor.useSavedStyle(newStyle); editor.useSavedStyle(newStyle);
}, },
scrollToEditor(cm) { scrollToEditor(cm, partial) {
const {el} = sections.find(s => s.cm === cm); const cc = partial && cm.cursorCoords(true, 'window');
const r = el.getBoundingClientRect(); const {top: y1, bottom: y2} = cm.el.getBoundingClientRect();
const h = window.innerHeight; const rc = container.getBoundingClientRect();
if (r.bottom > h && r.top > 0 || const rcY1 = Math.max(rc.top, 0);
r.bottom < h && r.top < 0) { const rcY2 = Math.min(rc.bottom, innerHeight);
window.scrollBy(0, (r.top + r.bottom - h) / 2 | 0); const bad = partial
} ? cc.top < rcY1 || cc.top > rcY2 - 30
: y1 >= rcY1 ^ y2 <= rcY2;
if (bad) window.scrollBy(0, (y1 + y2 - rcY2 + rcY1) / 2 | 0);
}, },
}); });
@ -291,10 +299,36 @@ function SectionsEditor() {
} }
} }
function nextPrevEditor(cm, direction) { function handleKeydown(event) {
if (event.shiftKey || event.altKey || event.metaKey ||
event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
return;
}
let pos;
let cm = this.CodeMirror;
const {line, ch} = cm.getCursor();
if (event.key === 'ArrowUp') {
cm = line === 0 && editor.prevEditor(cm, true);
pos = cm && [cm.doc.size - 1, ch];
} else {
cm = line === cm.doc.size - 1 && editor.nextEditor(cm, true);
pos = cm && [0, 0];
}
if (cm) {
cm.setCursor(...pos);
event.preventDefault();
event.stopPropagation();
}
}
function handleKeydownSetup(cm, state) {
cm.display.wrapper[state ? 'on' : 'off']('keydown', handleKeydown, true);
}
function nextPrevEditor(cm, direction, upDown) {
const editors = editor.getEditors(); const editors = editor.getEditors();
cm = editors[(editors.indexOf(cm) + direction + editors.length) % editors.length]; cm = editors[(editors.indexOf(cm) + direction + editors.length) % editors.length];
editor.scrollToEditor(cm); editor.scrollToEditor(cm, upDown);
cm.focus(); cm.focus();
return cm; return cm;
} }
@ -577,6 +611,9 @@ function SectionsEditor() {
cm.focus(); cm.focus();
editor.scrollToEditor(cm); editor.scrollToEditor(cm);
} }
if (upDownJumps) {
handleKeydownSetup(cm, true);
}
updateSectionOrder(); updateSectionOrder();
updateLivePreview(); updateLivePreview();
section.onChange(updateLivePreview); section.onChange(updateLivePreview);

View File

@ -1,32 +1,23 @@
'use strict'; 'use strict';
const colorConverter = (() => { const colorConverter = (NAMED_COLORS => {
const RXS_NUM = /\s*([+-]?(?:\d+\.?\d*|\d*\.\d+))(?:e[+-]?\d+)?/.source; // All groups in RXS_NUM must use ?: in order to enable \1 in RX_COLOR.rgb
const RXS_NUM_ANGLE = `${RXS_NUM}(deg|g?rad|turn)?`; const RXS_NUM = /\s*[+-]?(\.\d+|\d+(\.\d*)?)(e[+-]?\d+)?/.source.replace(/\(/g, '(?:');
const RXS_ANGLE = '(?:deg|g?rad|turn)?';
const expandRe = re => RegExp(re.source.replace(/N/g, RXS_NUM).replace(/A/g, RXS_ANGLE), 'iy');
const RX_COLOR = { const RX_COLOR = {
hex: /#([a-f\d]{3}(?:[a-f\d](?:[a-f\d]{2}){0,2})?)\b/iy, hex: /#([a-f\d]{3}(?:[a-f\d](?:[a-f\d]{2}){0,2})?)\b/iy,
hsl: new RegExp([
// num_or_angle, pct, pct [ , num_or_pct]? // num_or_angle, pct, pct [ , num_or_pct]?
`^(${RXS_NUM_ANGLE})\\s*,(${RXS_NUM}%\\s*(,|$)){2}(${RXS_NUM}%?)?\\s*$`,
// num_or_angle pct pct [ / num_or_pct]? // num_or_angle pct pct [ / num_or_pct]?
`^(${RXS_NUM_ANGLE})\\s+(${RXS_NUM}%\\s*(\\s|$)){2}(/${RXS_NUM}%?)?\\s*$`, hsl: expandRe(/^NA(\s*(,N%\s*){2}(,N%?\s*)?|(\s+N%){2}\s*(\/N%?\s*)?)$/),
].join('|'), 'iy'), // num_or_angle|none pct|none pct|none [ / num_or_pct|none ]?
hwb: expandRe(/^(NA|none)(\s+(N%|none)){2}\s*(\/(N%?|none)\s*)?$/),
hwb: new RegExp(
// num|angle|none pct|none pct|none [ / num|pct|none ]?
`^(${RXS_NUM_ANGLE}|none)(\\s+(${RXS_NUM}%|none)){2}(\\s+|$)(/${RXS_NUM}%?|none)?\\s*$`,
'iy'),
rgb: new RegExp([
// num, num, num [ , num_or_pct]? // num, num, num [ , num_or_pct]?
// pct, pct, pct [ , num_or_pct]? // pct, pct, pct [ , num_or_pct]?
`^((${RXS_NUM}\\s*(,|$)){3}|(${RXS_NUM}%\\s*(,|$)){3})(${RXS_NUM}%?)?\\s*$`,
// num num num [ / num_or_pct]? // num num num [ / num_or_pct]?
// pct pct pct [ / num_or_pct]? // pct pct pct [ / num_or_pct]?
`^((${RXS_NUM}\\s*(\\s|$)){3}|(${RXS_NUM}%\\s*(\\s|$)){3})(/${RXS_NUM}%?)?\\s*$`, rgb: expandRe(/^N(%?)(\s*,N\1\s*,N\1\s*(,N%?\s*)?|\s+N\1\s+N\1\s*(\/N%?\s*)?)$/),
].join('|'), 'iy'),
}; };
const ANGLE_TO_DEG = { const ANGLE_TO_DEG = {
grad: 360 / 400, grad: 360 / 400,
@ -51,6 +42,7 @@ const colorConverter = (() => {
'v' in c ? 'hsv' : 'v' in c ? 'hsv' :
'l' in c ? 'hsl' : 'l' in c ? 'hsl' :
undefined; undefined;
let HEX;
return { return {
parse, parse,
@ -64,8 +56,8 @@ const colorConverter = (() => {
snapToInt, snapToInt,
testAt, testAt,
ALPHA_DIGITS: 3, ALPHA_DIGITS: 3,
NAMED_COLORS,
RX_COLOR, RX_COLOR,
// NAMED_COLORS is added below
}; };
function format(color = '', type = color.type, {hexUppercase, usoMode, round} = {}) { function format(color = '', type = color.type, {hexUppercase, usoMode, round} = {}) {
@ -95,57 +87,71 @@ const colorConverter = (() => {
} }
} }
function parse(str) { function parse(s) {
if (typeof str !== 'string') return; if (typeof s !== 'string' || !(s = s.trim())) {
str = str.trim().toLowerCase(); return;
if (!str) return; } else if (s[0] === '#') {
return parseHex(s);
if (str[0] !== '#' && !str.includes('(')) { } else if (s.endsWith(')') && (s = s.match(/^(hwb|(hsl|rgb)a?)\(\s*([^)]+)/i))) {
// eslint-disable-next-line no-use-before-define return parseFunc((s[2] || s[1]).toLowerCase(), s[3]);
str = colorConverter.NAMED_COLORS.get(str); } else {
if (!str) return; return colorConverter.NAMED_COLORS.get(s.toLowerCase());
}
} }
if (str[0] === '#') { function initHexMap() {
if (!testAt(RX_COLOR.hex, 0, str)) { HEX = Array(256).fill(-0xFFFF); // ensuring a PACKED_SMI array
for (let i = 48; i < 58; i++) HEX[i] = i - 48; // 0123456789
for (let i = 65; i < 71; i++) HEX[i] = i - 65 + 10; // ABCDEF
for (let i = 97; i < 103; i++) HEX[i] = i - 97 + 10; // abcdef
}
function parseHex(str) {
if (!HEX) initHexMap();
let r, g, b, a;
const len = str.length;
if (len === 4 || len === 5
? (r = HEX[str.charCodeAt(1)] * 0x11) >= 0 &&
(g = HEX[str.charCodeAt(2)] * 0x11) >= 0 &&
(b = HEX[str.charCodeAt(3)] * 0x11) >= 0 &&
(len < 5 || (a = HEX[str.charCodeAt(4)] * 0x11 / 255) >= 0)
: (len === 7 || len === 9) &&
(r = HEX[str.charCodeAt(1)] * 0x10 + HEX[str.charCodeAt(2)]) >= 0 &&
(g = HEX[str.charCodeAt(3)] * 0x10 + HEX[str.charCodeAt(4)]) >= 0 &&
(b = HEX[str.charCodeAt(5)] * 0x10 + HEX[str.charCodeAt(6)]) >= 0 &&
(len < 9 || (a = (HEX[str.charCodeAt(7)] * 0x10 + HEX[str.charCodeAt(8)]) / 255) >= 0)
) {
return {type: 'hex', r, g, b, a};
}
}
function parseFunc(type, val) {
if (!testAt(RX_COLOR[type], 0, val)) {
return; return;
} }
str = str.slice(1); // Not using destructuring because it's slow
const [r, g, b, a = 255] = str.length <= 4 ? const parts = val.trim().split(/\s*[,/]\s*|\s+/);
str.match(/(.)/g).map(c => parseInt(c + c, 16)) : const n1 = parseFloat(parts[0]);
str.match(/(..)/g).map(c => parseInt(c, 16)); const n2 = parseFloat(parts[1]);
return { const n3 = parseFloat(parts[2]);
type: 'hex', const nA = parseFloat(parts[3]);
r, const a = isNaN(nA) ? undefined : constrain(0, 1, parts[3].endsWith('%') ? nA / 100 : nA);
g,
b,
a: a === 255 ? undefined : a / 255,
};
}
const [, func, type = func, value] = str.match(/^((rgb|hsl)a?|hwb)\(\s*(.*?)\s*\)|$/);
if (!func || !testAt(RX_COLOR[type], 0, value)) {
return;
}
const [s1, s2, s3, sA] = value.split(/\s*[,/]\s*|\s+/);
const a = isNaN(sA) ? 1 : constrain(0, 1, sA / (sA.endsWith('%') ? 100 : 1));
if (type === 'rgb') { if (type === 'rgb') {
const k = s1.endsWith('%') ? 2.55 : 1; const k = parts[0].endsWith('%') ? 2.55 : 1;
return { return {
type, type,
r: constrain(0, 255, Math.round(s1 * k)), r: constrain(0, 255, Math.round(n1 * k)),
g: constrain(0, 255, Math.round(s2 * k)), g: constrain(0, 255, Math.round(n2 * k)),
b: constrain(0, 255, Math.round(s3 * k)), b: constrain(0, 255, Math.round(n3 * k)),
a, a,
}; };
} }
const h = constrainHue(parseFloat(s1) * (ANGLE_TO_DEG[s1.match(/\D*$/)[0]] || 1)); const h = constrainHue(n1 * (ANGLE_TO_DEG[parts[0].match(/\D*$/)[0].toLowerCase()] || 1));
const n2 = constrain(0, 100, parseFloat(s2) || 0); const n2c = constrain(0, 100, n2 || 0);
const n3 = constrain(0, 100, parseFloat(s3) || 0); const n3c = constrain(0, 100, n3 || 0);
return type === 'hwb' return type === 'hwb'
? {type, h, w: n2, b: n3, a} ? {type, h, w: n2c, b: n3c, a}
: {type, h, s: n2, l: n3, a}; : {type, h, s: n2c, l: n3c, a};
} }
function formatAlpha(a) { function formatAlpha(a) {
@ -265,157 +271,154 @@ const colorConverter = (() => {
rx.lastIndex = index; rx.lastIndex = index;
return rx.test(text); return rx.test(text);
} }
})(); })(new Map([
['transparent', {r: 0, g: 0, b: 0, a: 0, type: 'rgb'}],
colorConverter.NAMED_COLORS = new Map([ ['aliceblue', {r: 240, g: 248, b: 255, type: 'hex'}],
['transparent', 'rgba(0, 0, 0, 0)'], ['antiquewhite', {r: 250, g: 235, b: 215, type: 'hex'}],
// CSS4 named colors ['aqua', {r: 0, g: 255, b: 255, type: 'hex'}],
['aliceblue', '#f0f8ff'], ['aquamarine', {r: 127, g: 255, b: 212, type: 'hex'}],
['antiquewhite', '#faebd7'], ['azure', {r: 240, g: 255, b: 255, type: 'hex'}],
['aqua', '#00ffff'], ['beige', {r: 245, g: 245, b: 220, type: 'hex'}],
['aquamarine', '#7fffd4'], ['bisque', {r: 255, g: 228, b: 196, type: 'hex'}],
['azure', '#f0ffff'], ['black', {r: 0, g: 0, b: 0, type: 'hex'}],
['beige', '#f5f5dc'], ['blanchedalmond', {r: 255, g: 235, b: 205, type: 'hex'}],
['bisque', '#ffe4c4'], ['blue', {r: 0, g: 0, b: 255, type: 'hex'}],
['black', '#000000'], ['blueviolet', {r: 138, g: 43, b: 226, type: 'hex'}],
['blanchedalmond', '#ffebcd'], ['brown', {r: 165, g: 42, b: 42, type: 'hex'}],
['blue', '#0000ff'], ['burlywood', {r: 222, g: 184, b: 135, type: 'hex'}],
['blueviolet', '#8a2be2'], ['cadetblue', {r: 95, g: 158, b: 160, type: 'hex'}],
['brown', '#a52a2a'], ['chartreuse', {r: 127, g: 255, b: 0, type: 'hex'}],
['burlywood', '#deb887'], ['chocolate', {r: 210, g: 105, b: 30, type: 'hex'}],
['cadetblue', '#5f9ea0'], ['coral', {r: 255, g: 127, b: 80, type: 'hex'}],
['chartreuse', '#7fff00'], ['cornflowerblue', {r: 100, g: 149, b: 237, type: 'hex'}],
['chocolate', '#d2691e'], ['cornsilk', {r: 255, g: 248, b: 220, type: 'hex'}],
['coral', '#ff7f50'], ['crimson', {r: 220, g: 20, b: 60, type: 'hex'}],
['cornflowerblue', '#6495ed'], ['cyan', {r: 0, g: 255, b: 255, type: 'hex'}],
['cornsilk', '#fff8dc'], ['darkblue', {r: 0, g: 0, b: 139, type: 'hex'}],
['crimson', '#dc143c'], ['darkcyan', {r: 0, g: 139, b: 139, type: 'hex'}],
['cyan', '#00ffff'], ['darkgoldenrod', {r: 184, g: 134, b: 11, type: 'hex'}],
['darkblue', '#00008b'], ['darkgray', {r: 169, g: 169, b: 169, type: 'hex'}],
['darkcyan', '#008b8b'], ['darkgrey', {r: 169, g: 169, b: 169, type: 'hex'}],
['darkgoldenrod', '#b8860b'], ['darkgreen', {r: 0, g: 100, b: 0, type: 'hex'}],
['darkgray', '#a9a9a9'], ['darkkhaki', {r: 189, g: 183, b: 107, type: 'hex'}],
['darkgrey', '#a9a9a9'], ['darkmagenta', {r: 139, g: 0, b: 139, type: 'hex'}],
['darkgreen', '#006400'], ['darkolivegreen', {r: 85, g: 107, b: 47, type: 'hex'}],
['darkkhaki', '#bdb76b'], ['darkorange', {r: 255, g: 140, b: 0, type: 'hex'}],
['darkmagenta', '#8b008b'], ['darkorchid', {r: 153, g: 50, b: 204, type: 'hex'}],
['darkolivegreen', '#556b2f'], ['darkred', {r: 139, g: 0, b: 0, type: 'hex'}],
['darkorange', '#ff8c00'], ['darksalmon', {r: 233, g: 150, b: 122, type: 'hex'}],
['darkorchid', '#9932cc'], ['darkseagreen', {r: 143, g: 188, b: 143, type: 'hex'}],
['darkred', '#8b0000'], ['darkslateblue', {r: 72, g: 61, b: 139, type: 'hex'}],
['darksalmon', '#e9967a'], ['darkslategray', {r: 47, g: 79, b: 79, type: 'hex'}],
['darkseagreen', '#8fbc8f'], ['darkslategrey', {r: 47, g: 79, b: 79, type: 'hex'}],
['darkslateblue', '#483d8b'], ['darkturquoise', {r: 0, g: 206, b: 209, type: 'hex'}],
['darkslategray', '#2f4f4f'], ['darkviolet', {r: 148, g: 0, b: 211, type: 'hex'}],
['darkslategrey', '#2f4f4f'], ['deeppink', {r: 255, g: 20, b: 147, type: 'hex'}],
['darkturquoise', '#00ced1'], ['deepskyblue', {r: 0, g: 191, b: 255, type: 'hex'}],
['darkviolet', '#9400d3'], ['dimgray', {r: 105, g: 105, b: 105, type: 'hex'}],
['deeppink', '#ff1493'], ['dimgrey', {r: 105, g: 105, b: 105, type: 'hex'}],
['deepskyblue', '#00bfff'], ['dodgerblue', {r: 30, g: 144, b: 255, type: 'hex'}],
['dimgray', '#696969'], ['firebrick', {r: 178, g: 34, b: 34, type: 'hex'}],
['dimgrey', '#696969'], ['floralwhite', {r: 255, g: 250, b: 240, type: 'hex'}],
['dodgerblue', '#1e90ff'], ['forestgreen', {r: 34, g: 139, b: 34, type: 'hex'}],
['firebrick', '#b22222'], ['fuchsia', {r: 255, g: 0, b: 255, type: 'hex'}],
['floralwhite', '#fffaf0'], ['gainsboro', {r: 220, g: 220, b: 220, type: 'hex'}],
['forestgreen', '#228b22'], ['ghostwhite', {r: 248, g: 248, b: 255, type: 'hex'}],
['fuchsia', '#ff00ff'], ['gold', {r: 255, g: 215, b: 0, type: 'hex'}],
['gainsboro', '#dcdcdc'], ['goldenrod', {r: 218, g: 165, b: 32, type: 'hex'}],
['ghostwhite', '#f8f8ff'], ['gray', {r: 128, g: 128, b: 128, type: 'hex'}],
['gold', '#ffd700'], ['grey', {r: 128, g: 128, b: 128, type: 'hex'}],
['goldenrod', '#daa520'], ['green', {r: 0, g: 128, b: 0, type: 'hex'}],
['gray', '#808080'], ['greenyellow', {r: 173, g: 255, b: 47, type: 'hex'}],
['grey', '#808080'], ['honeydew', {r: 240, g: 255, b: 240, type: 'hex'}],
['green', '#008000'], ['hotpink', {r: 255, g: 105, b: 180, type: 'hex'}],
['greenyellow', '#adff2f'], ['indianred', {r: 205, g: 92, b: 92, type: 'hex'}],
['honeydew', '#f0fff0'], ['indigo', {r: 75, g: 0, b: 130, type: 'hex'}],
['hotpink', '#ff69b4'], ['ivory', {r: 255, g: 255, b: 240, type: 'hex'}],
['indianred', '#cd5c5c'], ['khaki', {r: 240, g: 230, b: 140, type: 'hex'}],
['indigo', '#4b0082'], ['lavender', {r: 230, g: 230, b: 250, type: 'hex'}],
['ivory', '#fffff0'], ['lavenderblush', {r: 255, g: 240, b: 245, type: 'hex'}],
['khaki', '#f0e68c'], ['lawngreen', {r: 124, g: 252, b: 0, type: 'hex'}],
['lavender', '#e6e6fa'], ['lemonchiffon', {r: 255, g: 250, b: 205, type: 'hex'}],
['lavenderblush', '#fff0f5'], ['lightblue', {r: 173, g: 216, b: 230, type: 'hex'}],
['lawngreen', '#7cfc00'], ['lightcoral', {r: 240, g: 128, b: 128, type: 'hex'}],
['lemonchiffon', '#fffacd'], ['lightcyan', {r: 224, g: 255, b: 255, type: 'hex'}],
['lightblue', '#add8e6'], ['lightgoldenrodyellow', {r: 250, g: 250, b: 210, type: 'hex'}],
['lightcoral', '#f08080'], ['lightgray', {r: 211, g: 211, b: 211, type: 'hex'}],
['lightcyan', '#e0ffff'], ['lightgrey', {r: 211, g: 211, b: 211, type: 'hex'}],
['lightgoldenrodyellow', '#fafad2'], ['lightgreen', {r: 144, g: 238, b: 144, type: 'hex'}],
['lightgray', '#d3d3d3'], ['lightpink', {r: 255, g: 182, b: 193, type: 'hex'}],
['lightgrey', '#d3d3d3'], ['lightsalmon', {r: 255, g: 160, b: 122, type: 'hex'}],
['lightgreen', '#90ee90'], ['lightseagreen', {r: 32, g: 178, b: 170, type: 'hex'}],
['lightpink', '#ffb6c1'], ['lightskyblue', {r: 135, g: 206, b: 250, type: 'hex'}],
['lightsalmon', '#ffa07a'], ['lightslategray', {r: 119, g: 136, b: 153, type: 'hex'}],
['lightseagreen', '#20b2aa'], ['lightslategrey', {r: 119, g: 136, b: 153, type: 'hex'}],
['lightskyblue', '#87cefa'], ['lightsteelblue', {r: 176, g: 196, b: 222, type: 'hex'}],
['lightslategray', '#778899'], ['lightyellow', {r: 255, g: 255, b: 224, type: 'hex'}],
['lightslategrey', '#778899'], ['lime', {r: 0, g: 255, b: 0, type: 'hex'}],
['lightsteelblue', '#b0c4de'], ['limegreen', {r: 50, g: 205, b: 50, type: 'hex'}],
['lightyellow', '#ffffe0'], ['linen', {r: 250, g: 240, b: 230, type: 'hex'}],
['lime', '#00ff00'], ['magenta', {r: 255, g: 0, b: 255, type: 'hex'}],
['limegreen', '#32cd32'], ['maroon', {r: 128, g: 0, b: 0, type: 'hex'}],
['linen', '#faf0e6'], ['mediumaquamarine', {r: 102, g: 205, b: 170, type: 'hex'}],
['magenta', '#ff00ff'], ['mediumblue', {r: 0, g: 0, b: 205, type: 'hex'}],
['maroon', '#800000'], ['mediumorchid', {r: 186, g: 85, b: 211, type: 'hex'}],
['mediumaquamarine', '#66cdaa'], ['mediumpurple', {r: 147, g: 112, b: 219, type: 'hex'}],
['mediumblue', '#0000cd'], ['mediumseagreen', {r: 60, g: 179, b: 113, type: 'hex'}],
['mediumorchid', '#ba55d3'], ['mediumslateblue', {r: 123, g: 104, b: 238, type: 'hex'}],
['mediumpurple', '#9370db'], ['mediumspringgreen', {r: 0, g: 250, b: 154, type: 'hex'}],
['mediumseagreen', '#3cb371'], ['mediumturquoise', {r: 72, g: 209, b: 204, type: 'hex'}],
['mediumslateblue', '#7b68ee'], ['mediumvioletred', {r: 199, g: 21, b: 133, type: 'hex'}],
['mediumspringgreen', '#00fa9a'], ['midnightblue', {r: 25, g: 25, b: 112, type: 'hex'}],
['mediumturquoise', '#48d1cc'], ['mintcream', {r: 245, g: 255, b: 250, type: 'hex'}],
['mediumvioletred', '#c71585'], ['mistyrose', {r: 255, g: 228, b: 225, type: 'hex'}],
['midnightblue', '#191970'], ['moccasin', {r: 255, g: 228, b: 181, type: 'hex'}],
['mintcream', '#f5fffa'], ['navajowhite', {r: 255, g: 222, b: 173, type: 'hex'}],
['mistyrose', '#ffe4e1'], ['navy', {r: 0, g: 0, b: 128, type: 'hex'}],
['moccasin', '#ffe4b5'], ['oldlace', {r: 253, g: 245, b: 230, type: 'hex'}],
['navajowhite', '#ffdead'], ['olive', {r: 128, g: 128, b: 0, type: 'hex'}],
['navy', '#000080'], ['olivedrab', {r: 107, g: 142, b: 35, type: 'hex'}],
['oldlace', '#fdf5e6'], ['orange', {r: 255, g: 165, b: 0, type: 'hex'}],
['olive', '#808000'], ['orangered', {r: 255, g: 69, b: 0, type: 'hex'}],
['olivedrab', '#6b8e23'], ['orchid', {r: 218, g: 112, b: 214, type: 'hex'}],
['orange', '#ffa500'], ['palegoldenrod', {r: 238, g: 232, b: 170, type: 'hex'}],
['orangered', '#ff4500'], ['palegreen', {r: 152, g: 251, b: 152, type: 'hex'}],
['orchid', '#da70d6'], ['paleturquoise', {r: 175, g: 238, b: 238, type: 'hex'}],
['palegoldenrod', '#eee8aa'], ['palevioletred', {r: 219, g: 112, b: 147, type: 'hex'}],
['palegreen', '#98fb98'], ['papayawhip', {r: 255, g: 239, b: 213, type: 'hex'}],
['paleturquoise', '#afeeee'], ['peachpuff', {r: 255, g: 218, b: 185, type: 'hex'}],
['palevioletred', '#db7093'], ['peru', {r: 205, g: 133, b: 63, type: 'hex'}],
['papayawhip', '#ffefd5'], ['pink', {r: 255, g: 192, b: 203, type: 'hex'}],
['peachpuff', '#ffdab9'], ['plum', {r: 221, g: 160, b: 221, type: 'hex'}],
['peru', '#cd853f'], ['powderblue', {r: 176, g: 224, b: 230, type: 'hex'}],
['pink', '#ffc0cb'], ['purple', {r: 128, g: 0, b: 128, type: 'hex'}],
['plum', '#dda0dd'], ['rebeccapurple', {r: 102, g: 51, b: 153, type: 'hex'}],
['powderblue', '#b0e0e6'], ['red', {r: 255, g: 0, b: 0, type: 'hex'}],
['purple', '#800080'], ['rosybrown', {r: 188, g: 143, b: 143, type: 'hex'}],
['rebeccapurple', '#663399'], ['royalblue', {r: 65, g: 105, b: 225, type: 'hex'}],
['red', '#ff0000'], ['saddlebrown', {r: 139, g: 69, b: 19, type: 'hex'}],
['rosybrown', '#bc8f8f'], ['salmon', {r: 250, g: 128, b: 114, type: 'hex'}],
['royalblue', '#4169e1'], ['sandybrown', {r: 244, g: 164, b: 96, type: 'hex'}],
['saddlebrown', '#8b4513'], ['seagreen', {r: 46, g: 139, b: 87, type: 'hex'}],
['salmon', '#fa8072'], ['seashell', {r: 255, g: 245, b: 238, type: 'hex'}],
['sandybrown', '#f4a460'], ['sienna', {r: 160, g: 82, b: 45, type: 'hex'}],
['seagreen', '#2e8b57'], ['silver', {r: 192, g: 192, b: 192, type: 'hex'}],
['seashell', '#fff5ee'], ['skyblue', {r: 135, g: 206, b: 235, type: 'hex'}],
['sienna', '#a0522d'], ['slateblue', {r: 106, g: 90, b: 205, type: 'hex'}],
['silver', '#c0c0c0'], ['slategray', {r: 112, g: 128, b: 144, type: 'hex'}],
['skyblue', '#87ceeb'], ['slategrey', {r: 112, g: 128, b: 144, type: 'hex'}],
['slateblue', '#6a5acd'], ['snow', {r: 255, g: 250, b: 250, type: 'hex'}],
['slategray', '#708090'], ['springgreen', {r: 0, g: 255, b: 127, type: 'hex'}],
['slategrey', '#708090'], ['steelblue', {r: 70, g: 130, b: 180, type: 'hex'}],
['snow', '#fffafa'], ['tan', {r: 210, g: 180, b: 140, type: 'hex'}],
['springgreen', '#00ff7f'], ['teal', {r: 0, g: 128, b: 128, type: 'hex'}],
['steelblue', '#4682b4'], ['thistle', {r: 216, g: 191, b: 216, type: 'hex'}],
['tan', '#d2b48c'], ['tomato', {r: 255, g: 99, b: 71, type: 'hex'}],
['teal', '#008080'], ['turquoise', {r: 64, g: 224, b: 208, type: 'hex'}],
['thistle', '#d8bfd8'], ['violet', {r: 238, g: 130, b: 238, type: 'hex'}],
['tomato', '#ff6347'], ['wheat', {r: 245, g: 222, b: 179, type: 'hex'}],
['turquoise', '#40e0d0'], ['white', {r: 255, g: 255, b: 255, type: 'hex'}],
['violet', '#ee82ee'], ['whitesmoke', {r: 245, g: 245, b: 245, type: 'hex'}],
['wheat', '#f5deb3'], ['yellow', {r: 255, g: 255, b: 0, type: 'hex'}],
['white', '#ffffff'], ['yellowgreen', {r: 154, g: 205, b: 50, type: 'hex'}],
['whitesmoke', '#f5f5f5'], ]));
['yellow', '#ffff00'],
['yellowgreen', '#9acd32'],
]);

View File

@ -3503,7 +3503,7 @@ self.parserlib = (() => {
do { do {
this._ws(); this._ws();
if ((t = stream.get(true)).type === Tokens.IDENT) { if ((t = stream.get(true)).type === Tokens.IDENT) {
ids.push(t.value); ids.push(this._layerName(t));
this._ws(); this._ws();
t = stream.get(true); t = stream.get(true);
} }
@ -3521,6 +3521,16 @@ self.parserlib = (() => {
this._ws(); this._ws();
} }
_layerName(start) {
let res = '';
const stream = this._tokenStream;
for (let t; (t = start || stream.match(Tokens.IDENT));) {
res += t.value + (stream.match(Tokens.DOT) ? '.' : '');
start = false;
}
return res;
}
_stylesheet() { _stylesheet() {
const stream = this._tokenStream; const stream = this._tokenStream;
this.fire('startstylesheet'); this.fire('startstylesheet');
@ -3590,7 +3600,7 @@ self.parserlib = (() => {
this._ws(); this._ws();
t = stream.get(true); t = stream.get(true);
if (/^layer(\()?$/i.test(t.value)) { if (/^layer(\()?$/i.test(t.value)) {
layer = RegExp.$1 ? stream.mustMatch(Tokens.IDENT) : ''; layer = RegExp.$1 ? this._layerName() : '';
if (layer) stream.mustMatch(Tokens.RPAREN); if (layer) stream.mustMatch(Tokens.RPAREN);
this._ws(); this._ws();
t = stream.get(true); t = stream.get(true);

View File

@ -99,7 +99,7 @@
// "Delete" item in context menu for browsers that don't have it // "Delete" item in context menu for browsers that don't have it
'editor.contextDelete': false, 'editor.contextDelete': false,
'editor.selectByTokens': true, 'editor.selectByTokens': true,
'editor.arrowKeysTraverse': true,
'editor.appliesToLineWidget': true, // show applies-to line widget on the editor 'editor.appliesToLineWidget': true, // show applies-to line widget on the editor
'editor.autosaveDraft': 10, // seconds 'editor.autosaveDraft': 10, // seconds
'editor.livePreview': true, 'editor.livePreview': true,

7070
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -27,7 +27,7 @@
"glob": "^8.0.3", "glob": "^8.0.3",
"node-fetch": "^2.6.7", "node-fetch": "^2.6.7",
"sync-version": "^1.0.1", "sync-version": "^1.0.1",
"web-ext": "^6.8.0" "web-ext": "^7.2.0"
}, },
"scripts": { "scripts": {
"lint": "eslint \"**/*.js\" --cache", "lint": "eslint \"**/*.js\" --cache",

View File

@ -98,6 +98,10 @@
</div> </div>
</template> </template>
<template data-id="writeForFrames">
<div id="write-for-frames" tabindex="0">&lt;iframe&gt;...</div>
</template>
<script src="js/polyfill.js"></script> <script src="js/polyfill.js"></script>
<script src="js/msg.js"></script> <script src="js/msg.js"></script>
<script src="js/toolbox.js"></script> <script src="js/toolbox.js"></script>
@ -143,7 +147,6 @@
<svg class="svg-icon checked"><use xlink:href="#svg-icon-checked"/></svg> <svg class="svg-icon checked"><use xlink:href="#svg-icon-checked"/></svg>
<div>U</div> <div>U</div>
</label> </label>
<a id="write-for-frames" title="&lsaquo;iframe&rsaquo;..." tabindex="0" hidden></a>
<span id="write-style-for" i18n="writeStyleFor"></span> <span id="write-style-for" i18n="writeStyleFor"></span>
</div> </div>
</div> </div>

View File

@ -491,6 +491,7 @@ a:hover .svg-icon {
margin-left: .5rem; margin-left: .5rem;
} }
#write-for-frames::before,
.match .match::before { .match .match::before {
content: ""; content: "";
width: .25rem; width: .25rem;
@ -510,33 +511,18 @@ a:hover .svg-icon {
display: none; display: none;
} }
#write-for-frames:not([hidden]) { #write-for-frames {
position: relative; cursor: pointer;
width: 5px; margin: 0 0 -.25em .5rem;
height: 5px; color: var(--c50);
display: inline-block; transition: color .2s;
margin: 0 2px 2px; }
--dash: transparent 2px, currentColor 2px, currentColor 3px, transparent 3px; #write-for-frames:hover {
background: linear-gradient(var(--dash)), linear-gradient(90deg, var(--dash)); color: var(--fg);
} }
#write-for-frames.expanded { #write-style:not(.expanded) .match:not([data-frame-id="0"]),
background: linear-gradient(var(--dash)); #write-style:not(.expanded) .match .match {
}
#write-for-frames::after {
position: absolute;
margin: -2px;
border: 1px solid currentColor;
content: "";
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#write-for-frames:not(.expanded) ~ .match:not([data-frame-id="0"]),
#write-for-frames:not(.expanded) ~ .match .match {
display: none; display: none;
} }

View File

@ -144,10 +144,15 @@ async function initPopup(frames) {
} }
frames.forEach(createWriterElement); frames.forEach(createWriterElement);
Object.assign($('#write-for-frames'), {
onclick: e => e.currentTarget.classList.toggle('expanded'), if (frames.length > 1 && $('.match .match:not(.dupe)')) {
hidden: frames.length < 2 || !$('.match .match:not(.dupe)'), $('#write-style').append(Object.assign(t.template.writeForFrames, {
}); onclick() {
this.remove();
$('#write-style').classList.add('expanded');
},
}));
}
const isStore = tabURL.startsWith(URLS.browserWebStore); const isStore = tabURL.startsWith(URLS.browserWebStore);
if (isStore && !FIREFOX) { if (isStore && !FIREFOX) {

View File

@ -134,6 +134,10 @@
width: 100%; width: 100%;
} }
.search-result[data-installed] {
box-shadow: 1px 1px 10px darkcyan;
border-color: darkcyan;
}
.search-result:not([data-installed]) .search-result-actions { .search-result:not([data-installed]) .search-result-actions {
opacity: 0; opacity: 0;
transition: opacity .5s; transition: opacity .5s;

View File

@ -2,7 +2,7 @@
/* global $entry tabURL */// popup.js /* global $entry tabURL */// popup.js
/* global API */// msg.js /* global API */// msg.js
/* global Events */ /* global Events */
/* global FIREFOX URLS debounce download stringAsRegExp tryRegExp tryURL */// toolbox.js /* global FIREFOX URLS debounce download isEmptyObj stringAsRegExp tryRegExp tryURL */// toolbox.js
/* global prefs */ /* global prefs */
/* global t */// localization.js /* global t */// localization.js
'use strict'; 'use strict';
@ -27,7 +27,7 @@
/** /**
* @typedef IndexEntry * @typedef IndexEntry
* @prop {'uso' | 'uso-android'} f - format * @prop {'uso' | 'uso-android'} f - format
* @prop {Number} i - id * @prop {Number} i - id, later replaced with string like `uso-123`
* @prop {string} n - name * @prop {string} n - name
* @prop {string} c - category * @prop {string} c - category
* @prop {Number} u - updatedTime * @prop {Number} u - updatedTime
@ -39,8 +39,8 @@
* @prop {string} sn - screenshotName * @prop {string} sn - screenshotName
* @prop {boolean} sa - screenshotArchived * @prop {boolean} sa - screenshotArchived
* *
* @prop {boolean} _installed * @prop {number} _styleId - installed style id
* @prop {number} _installedStyleId * @prop {boolean} _styleVars - installed style has vars
* @prop {number} _year * @prop {number} _year
*/ */
/** @type IndexEntry[] */ /** @type IndexEntry[] */
@ -73,6 +73,7 @@
const entry = el.closest(RESULT_SEL); const entry = el.closest(RESULT_SEL);
return {entry, result: entry && entry._result}; return {entry, result: entry && entry._result};
}; };
const rid2id = rid => rid.split('-')[1];
Events.searchInline = () => { Events.searchInline = () => {
calcCategory(); calcCategory();
ready = start(); ready = start();
@ -158,18 +159,22 @@
window.on('styleDeleted', ({detail: {style: {id}}}) => { window.on('styleDeleted', ({detail: {style: {id}}}) => {
restoreScrollPosition(); restoreScrollPosition();
const result = results.find(r => r._installedStyleId === id); const r = results.find(r => r._styleId === id);
if (result) { if (r) {
API.uso.pingback(result.i, false); if (r.f) API.uso.pingback(rid2id(r.i), false);
renderActionButtons(result.i, -1); delete r._styleId;
renderActionButtons(r.i);
} }
}); });
window.on('styleAdded', async ({detail: {style}}) => { window.on('styleAdded', async ({detail: {style}}) => {
restoreScrollPosition(); restoreScrollPosition();
const id = calcId(style) || calcId(await API.styles.get(style.id)); const ri = await API.styles.getRemoteInfo(style.id);
if (id && results.find(r => r.i === id)) { const r = ri && results.find(r => ri[0] === r.i);
renderActionButtons(id, style.id); if (r) {
r._styleId = style.id;
r._styleVars = ri[1];
renderActionButtons(ri[0]);
} }
}); });
@ -209,9 +214,10 @@
results = await search({retry}); results = await search({retry});
} }
if (results.length) { if (results.length) {
const installedStyles = await API.styles.getAll(); const info = await API.styles.getRemoteInfo();
const allSupportedIds = new Set(installedStyles.map(calcId)); for (const r of results) {
results = results.filter(r => !allSupportedIds.has(r.i)); [r._styleId, r._styleVars] = info[r.i] || [];
}
} }
if (!keepYears) resultsAllYears = results; if (!keepYears) resultsAllYears = results;
renderYears(); renderYears();
@ -330,7 +336,7 @@
function createSearchResultNode(result) { function createSearchResultNode(result) {
const entry = t.template.searchResult.cloneNode(true); const entry = t.template.searchResult.cloneNode(true);
const { const {
i: id, i: rid,
n: name, n: name,
r: rating, r: rating,
u: updateTime, u: updateTime,
@ -342,7 +348,8 @@
sn: shot, sn: shot,
f: fmt, f: fmt,
} = entry._result = result; } = entry._result = result;
entry.id = RESULT_ID_PREFIX + id; const id = rid2id(rid);
entry.id = RESULT_ID_PREFIX + rid;
// title // title
Object.assign($('.search-result-title', entry), { Object.assign($('.search-result-title', entry), {
onclick: Events.openURLandHide, onclick: Events.openURLandHide,
@ -421,22 +428,19 @@
} }
} }
function renderActionButtons(entry, installedId) { function renderActionButtons(entry) {
if (Number(entry)) { if (typeof entry !== 'object') {
entry = $('#' + RESULT_ID_PREFIX + entry); entry = $('#' + RESULT_ID_PREFIX + entry);
} }
if (!entry) return; if (!entry) return;
const result = entry._result; const result = entry._result;
if (typeof installedId === 'number') { const installedId = result._styleId;
result._installed = installedId > 0; const isInstalled = installedId > 0; // must be boolean for comparisons below
result._installedStyleId = installedId;
}
const isInstalled = result._installed;
const status = $('.search-result-status', entry).textContent = const status = $('.search-result-status', entry).textContent =
isInstalled ? t('clickToUninstall') : isInstalled ? t('clickToUninstall') :
entry.dataset.noImage != null ? t('installButton') : entry.dataset.noImage != null ? t('installButton') :
''; '';
const notMatching = installedId > 0 && !$entry(installedId); const notMatching = isInstalled && !$entry(installedId);
if (notMatching !== entry.classList.contains('not-matching')) { if (notMatching !== entry.classList.contains('not-matching')) {
entry.classList.toggle('not-matching'); entry.classList.toggle('not-matching');
if (notMatching) { if (notMatching) {
@ -456,6 +460,7 @@
disabled: notMatching, disabled: notMatching,
}); });
toggleDataset(entry, 'installed', isInstalled); toggleDataset(entry, 'installed', isInstalled);
toggleDataset(entry, 'customizable', result._styleVars);
} }
function renderFullInfo(entry, style) { function renderFullInfo(entry, style) {
@ -469,17 +474,20 @@
textContent: description, textContent: description,
title: description, title: description,
}); });
vars = !isEmptyObj(vars);
entry._result._styleVars = vars;
toggleDataset(entry, 'customizable', vars); toggleDataset(entry, 'customizable', vars);
} }
function configure() { function configure() {
const styleEntry = $entry($resultEntry(this).result._installedStyleId); const styleEntry = $entry($resultEntry(this).result._styleId);
Events.configure.call(this, {target: styleEntry}); Events.configure.call(this, {target: styleEntry});
} }
async function install() { async function install() {
const {entry, result} = $resultEntry(this); const {entry, result} = $resultEntry(this);
const {i: id, f: fmt} = result; const {f: fmt} = result;
const id = rid2id(result.i);
const installButton = $('.search-result-install', entry); const installButton = $('.search-result-install', entry);
showSpinner(entry); showSpinner(entry);
@ -507,7 +515,7 @@
function uninstall() { function uninstall() {
const {entry, result} = $resultEntry(this); const {entry, result} = $resultEntry(this);
saveScrollPosition(entry); saveScrollPosition(entry);
API.styles.delete(result._installedStyleId); API.styles.delete(result._styleId);
} }
function saveScrollPosition(entry) { function saveScrollPosition(entry) {
@ -553,10 +561,11 @@
async function fetchIndex() { async function fetchIndex() {
const timer = setTimeout(showSpinner, BUSY_DELAY, dom.list); const timer = setTimeout(showSpinner, BUSY_DELAY, dom.list);
const jobs = [ const jobs = [
[INDEX_URL, json => json.filter(entry => entry.f === 'uso')], [INDEX_URL, 'uso', json => json.filter(v => v.f === 'uso')],
[USW_INDEX_URL, json => json.data], [USW_INDEX_URL, 'usw', json => json.data],
].map(async ([url, transform]) => { ].map(async ([url, prefix, transform]) => {
const res = transform(await download(url, {responseType: 'json'})); const res = transform(await download(url, {responseType: 'json'}));
for (const v of res) v.i = `${prefix}-${v.i}`;
index = index ? index.concat(res) : res; index = index ? index.concat(res) : res;
if (index !== res) ready = ready.then(start); if (index !== res) ready = ready.then(start);
}); });
@ -607,17 +616,4 @@
: b[order] - a[order] : b[order] - a[order]
) || b.t - a.t; ) || b.t - a.t;
} }
function calcUsoId({md5Url: m, updateUrl}) {
return Number(m && m.match(/\d+|$/)[0]) ||
URLS.extractUsoArchiveId(updateUrl);
}
function calcUswId({updateUrl}) {
return URLS.extractUSwId(updateUrl) || 0;
}
function calcId(style) {
return calcUsoId(style) || calcUswId(style);
}
})(); })();