Skip to content

Commit

Permalink
fix 50199b5: getByUrl + rework and reuse getCore
Browse files Browse the repository at this point in the history
  • Loading branch information
tophf committed Jan 14, 2025
1 parent 43e06d5 commit acade5d
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 62 deletions.
2 changes: 1 addition & 1 deletion src/background/set-client-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const PROVIDERS = {
query,
mode: sp.get('searchMode') || prefs.__values['manage.searchMode'],
}),
styles: __.MV3 ? styleMan.getCodelessStyles() : styleMan.getAll(),
styles: __.MV3 ? styleMan.getCore({sections: true, size: true}) : styleMan.getAll(),
sync: syncMan.getStatus(true),
};
},
Expand Down
49 changes: 27 additions & 22 deletions src/background/style-manager/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {IMPORT_THROTTLE, kUrl, UCD} from '@/js/consts';
import {IMPORT_THROTTLE, k_size, kUrl, UCD} from '@/js/consts';
import * as prefs from '@/js/prefs';
import {calcStyleDigest, styleCodeEmpty} from '@/js/sections-util';
import {isEmptyObj, mapObj} from '@/js/util';
import {calcObjSize, mapObj} from '@/js/util';
import {broadcast} from '../broadcast';
import * as colorScheme from '../color-scheme';
import {bgBusy, bgInit, uuidIndex} from '../common';
Expand Down Expand Up @@ -133,11 +133,8 @@ export function getByUrl(url, id = null) {
// FIXME: do we want to cache this? Who would like to open popup rapidly
// or search the DB with the same URL?
const result = [];
const styles = id
? [getById(id)].filter(Boolean)
: dataMap.values();
const query = {url};
for (const {style} of styles) {
for (const {style} of id ? [dataMap.get(id)].filter(Boolean) : dataMap.values()) {
let empty = true;
let excluded = false;
let excludedScheme = false;
Expand Down Expand Up @@ -176,31 +173,39 @@ export function getByUrl(url, id = null) {
included,
sectionMatched,
sloppy,
style: getCodelessStyles([style.id], true)[0],
style: getCore({id: style.id}),
});
}
}
return result;
}

export function getCodelessStyles(ids, forPopup) {
/**
* @param {{}} [opts]
* @param {number} [opts.id] - process and return only one style
* @param {boolean} [opts.code] - include `code` and `sourceCode`
* @param {boolean} [opts.sections] - include `sections`
* @param {boolean} [opts.vars] - include `usercssData.vars`
* @return {StyleObj[] | StyleObj}
*/
export function getCore({id, code, sections, size, vars} = {}) {
const res = [];
for (const v of ids || dataMap.values()) {
const style = {...(ids ? dataMap.get(v) : v).style};
let dst;
if (!forPopup) {
dst = [];
for (let i = 0, src = style.sections; i < src.length; i++) {
dst[i] = {...src[i], code: undefined};
}
} else if (UCD in style) {
style[UCD] = {vars: !isEmptyObj(style[UCD].vars) && {foo: 1}};
}
style.sourceCode = undefined;
style.sections = dst;
for (let style of id ? [dataMap.get(id)] : dataMap.values()) {
style = {...style.style};
let tmp;
if (size)
style[k_size] = calcObjSize(style);
if (!code && sections)
tmp = style.sections.map(sec => ({...sec, code: undefined}));
if (!code || !sections)
style.sections = tmp;
if (!code)
style.sourceCode = undefined;
if (!vars && (tmp = style[UCD]))
style[UCD] = {...tmp, vars: Object.keys(tmp.vars || {}).length ? {foo: 1} : undefined};
res.push(style);
}
return res;
return id ? res[0] : res;
}

/** @returns {string | {[remoteId:string]: styleId}}>} */
Expand Down
8 changes: 4 additions & 4 deletions src/edit/on-msg-extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ async function handleExternalUpdate({style, reason}) {
editor.updateMeta();
return;
}
style = await API.styles.get(style.id);
style = await API.styles.getCore({id: style.id, vars: true});
if (reason === 'config') {
for (const key in editor.style) if (!(key in style)) delete editor.style[key];
delete style.sourceCode;
delete style.sections;
for (const key in editor.style)
if (key !== 'sourceCode' && key !== 'sections' && !(key in style))
delete editor.style[key];
delete style.name;
delete style.enabled;
Object.assign(editor.style, style);
Expand Down
1 change: 1 addition & 0 deletions src/js/consts.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const kUrls = 'urls';
export const k_busy = '_busy';
export const k_deepCopy = '_deepCopy';
export const k_msgExec = '_msgExec';
export const k_size = '_size';

export const CACHE_DB = 'cache';
export const DB = 'stylish';
Expand Down
6 changes: 2 additions & 4 deletions src/js/dlg/config-dialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,9 @@ export default async function configDialog(style) {
if (!vars.some(va => va.dirty || anyChangeIsDirty && va.value !== va.savedValue)) {
return;
}
const bgStyle = style.id && await API.styles.get(style.id).catch(() => ({}));
style = style.sections ? Object.assign({}, style) : style;
const bgStyle = style.id &&
await API.styles.getCore({id: style.id, vars: true}).catch(() => ({}));
style.enabled = true;
style.sourceCode = null;
style.sections = null;
const styleVars = style[UCD].vars;
const bgVars = !style.id ? styleVars : bgStyle[UCD]?.vars || {};
const invalid = [];
Expand Down
13 changes: 13 additions & 0 deletions src/js/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ export const makePropertyPopProxy = data => new Proxy(data, {
)),
});

export function calcObjSize(obj) {
if (obj === true || obj == null) return 4;
if (obj === false) return 5;
let v = typeof obj;
if (v === 'string') return obj.length + 2; // inaccurate but fast
if (v === 'number') return (v = obj) >= 0 && v < 10 ? 1 : Math.ceil(Math.log10(v < 0 ? -v : v));
if (v !== 'object') return `${obj}`.length;
let sum = 1;
if (Array.isArray(obj)) for (v of obj) sum += calcObjSize(v) + 1;
else for (const k in obj) sum += k.length + 3 + calcObjSize(obj[k]) + 1;
return sum;
}

export function isEmptyObj(obj) {
if (obj) {
for (const k in obj) {
Expand Down
5 changes: 2 additions & 3 deletions src/manage/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {filterAndAppend, showFiltersStats} from './filters';
import {createStyleElement, createTargetsElement, renderFavs, updateTotal} from './render';
import * as sorter from './sorter';
import {checkUpdate, handleUpdateInstalled} from './updater-ui';
import {installed, newUI, objectDiff, queue, removeStyleCode, styleToDummyEntry} from './util';
import {installed, newUI, objectDiff, queue, styleToDummyEntry} from './util';

for (const a of $$('#header a[href^="http"]')) a.onclick = openLink;
installed.on('click', onEntryClicked);
Expand Down Expand Up @@ -202,7 +202,6 @@ function handleUpdate(style, {reason, method} = {}) {
renderFavs(entry);

function handleToggledOrCodeOnly() {
removeStyleCode(style);
const diff = objectDiff(oldEntry.styleMeta, style)
.filter(({key, path}) => path || !/^_|(Date|Digest|Md5)$/.test(key));
if (diff.length === 0) {
Expand All @@ -222,7 +221,7 @@ function handleUpdate(style, {reason, method} = {}) {
}

async function handleUpdateForId(id, opts) {
handleUpdate(await API.styles.get(id), opts);
handleUpdate(await API.styles.getCore({id, sections: true, size: true}), opts);
}

export function handleVisibilityChange(e) {
Expand Down
3 changes: 1 addition & 2 deletions src/manage/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {isEmptyObj, sessionStore, t} from '@/js/util';
import {filterAndAppend} from './filters';
import {renderFavs} from './render';
import * as sorter from './sorter';
import {installed, newUI, padLeft, removeStyleCode, styleToDummyEntry} from './util';
import {installed, newUI, padLeft, styleToDummyEntry} from './util';

export * from './render-favs';

Expand Down Expand Up @@ -110,7 +110,6 @@ export function createStyleElement({styleMeta: style, styleNameLC: nameLC, style
partOldConfigure.classList.toggle('hidden', !configurable);
partOldCheckUpdate.classList.toggle('hidden', !updateUrl);
}
removeStyleCode(style);
// Now that we assigned the parts, we can clone the element
const entry = partEntry.cloneNode(true);
entry.id = kStyleIdPrefix + style.id;
Expand Down
29 changes: 4 additions & 25 deletions src/manage/util.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {k_size} from '@/js/consts';
import {cssFieldSizing} from '@/js/dom';
import {template} from '@/js/localization';
import * as newUI from './new-ui';
Expand All @@ -9,36 +10,12 @@ export const queue = Object.assign([], {
styles: new Map(),
});

export function calcObjSize(obj) {
if (obj === true || obj == null) return 4;
if (obj === false) return 5;
let v = typeof obj;
if (v === 'string') return obj.length + 2; // inaccurate but fast
if (v === 'number') return (v = obj) >= 0 && v < 10 ? 1 : Math.ceil(Math.log10(v < 0 ? -v : v));
if (v !== 'object') return `${obj}`.length;
let sum = 1;
if (Array.isArray(obj)) for (v of obj) sum += calcObjSize(v) + 1;
else for (const k in obj) sum += k.length + 3 + calcObjSize(obj[k]) + 1;
return sum;
}

/** Adding spaces so CSS can detect "bigness" of a value via amount of spaces at the beginning */
export function padLeft(val, width) {
val = `${val}`;
return ' '.repeat(Math.max(0, width - val.length)) + val;
}

/** Clearing the code to free up some memory */
export function removeStyleCode(style) {
let sum = (style.sourceCode || '').length || 0;
style.sections.forEach(s => {
sum += (s.code || '').length;
s.code = null;
});
style.sourceCode = null;
Object.defineProperty(style, '_codeSize', {value: sum, writable: true}); // non-enumerable!
}

export function objectDiff(first, second, path = '') {
const diff = [];
for (const key in first) {
Expand Down Expand Up @@ -79,9 +56,11 @@ export function objectDiff(first, second, path = '') {

export function styleToDummyEntry(style) {
const name = style.customName || style.name || '';
const size = style[k_size];
delete style[k_size];
return {
styleMeta: style,
styleSize: calcObjSize(style) + (style._codeSize || 0),
styleSize: size,
// sort case-insensitively the whole list then sort dupes like `Foo` and `foo` case-sensitively
styleNameLC: name.toLocaleLowerCase() + '\n' + name,
};
Expand Down
3 changes: 2 additions & 1 deletion src/popup/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const menuExclusions = [];

export function configure(event, entry) {
if (!this.target) {
hotkeys.pause(async () => configDialog(await API.styles.get(entry.styleId)));
hotkeys.pause(async () =>
configDialog(await API.styles.getCore({id: entry.styleId, vars: true})));
} else {
openURLandHide.call(this, event);
}
Expand Down

0 comments on commit acade5d

Please sign in to comment.