Skip to content

Commit

Permalink
override font-family-modern font weight live
Browse files Browse the repository at this point in the history
  • Loading branch information
marcustyphoon committed Jan 31, 2025
1 parent 66da7ca commit 7ee54a1
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ const applyFontFamily = async function () {
'--font-family-modern',
fontFamily === 'custom' ? customFontFamily : fontFamily
);
const { fontWeightOverride } = await import(browser.runtime.getURL('/override_font_weight.js'));
document.getElementById('palettes-for-tumblr-override')?.remove();
(fontFamily === 'custom' ? customFontFamily : fontFamily) &&
document.documentElement.append(fontWeightOverride);
};

const applyFontSize = async function () {
Expand Down
2 changes: 1 addition & 1 deletion src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
},
"permissions": [ "storage" ],
"web_accessible_resources": [{
"resources": [ "*.json" ],
"resources": [ "*.json", "*.js" ],
"matches": [ "*://www.tumblr.com/*" ]
}],

Expand Down
49 changes: 49 additions & 0 deletions src/override_font_weight.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
await new Promise((resolve) =>
document.readyState === 'loading'
? document.addEventListener('readystatechange', resolve, { once: true })
: resolve()
);

export const fontWeightOverride = Object.assign(document.createElement('style'), {
id: 'palettes-for-tumblr-override'
});

const getSelectorsFromUrl = async (url) => {
const cssText = await fetch(url).then(response => response.text());
const sheet = await new CSSStyleSheet().replace(cssText);

const allCssStyleRules = [...sheet.cssRules]
.filter((rule) => rule instanceof CSSStyleRule && rule.style)
.map(({ selectorText, style }) => ({
selectorText,
rules: Object.fromEntries([...style].map((key) => [key, style.getPropertyValue(key)]))
}));

return allCssStyleRules
.filter(
({ rules }) =>
rules['font-family'] === 'var(--font-family-modern)' &&
rules['font-weight'] === '350'
)
.map(({ selectorText }) => selectorText);
};

const cache = {};

const processLinkElements = async () => {
[...document.head.querySelectorAll('link[rel="stylesheet"][href^="https://assets.tumblr.com/pop/"]')]
.map(element => element.href)
.forEach(url => {
cache[url] ??= getSelectorsFromUrl(url);
});

const selectors = await Promise.all(Object.values(cache)).then(results => results.flat());
fontWeightOverride.textContent = `
${selectors.join(', ')} {
font-weight: normal;
}
`;
};

processLinkElements();
new MutationObserver(processLinkElements).observe(document.head, { childList: true });

0 comments on commit 7ee54a1

Please sign in to comment.