#109 Added observer to react to late changes of a badge class

This commit is contained in:
Serraniel 2020-12-23 20:01:06 +01:00
parent a362b1fee4
commit 2e61cf3ede
Signed by: Serraniel
GPG key ID: 3690B4E7364525D3

View file

@ -4,6 +4,8 @@ import * as core from '../utils/aniwatchCore';
import * as helper from '../utils/helpers'; import * as helper from '../utils/helpers';
const BADGE_CLASS = 'label'; const BADGE_CLASS = 'label';
const DARKCOLOR_CLASS = 'awp-fontColor-dark';
const __observedBadges = [];
export function init() { export function init() {
getGlobalConfiguration().getProperty(SETTINGS_websiteOptimizeFontColors, value => { getGlobalConfiguration().getProperty(SETTINGS_websiteOptimizeFontColors, value => {
@ -24,27 +26,57 @@ export function init() {
} }
function checkRunColorOptimization(node) { function checkRunColorOptimization(node) {
// run the scripts // run the scripts
if (helper.isHtmlElement(node)) { if (helper.isHtmlElement(node)) {
if (node.classList.contains(BADGE_CLASS)) { if (node.classList.contains(BADGE_CLASS)) {
tryRegisterObserverForBadge(node);
optimizeFontColorsBadges(node); optimizeFontColorsBadges(node);
} }
else { else {
node.querySelectorAll(`.${BADGE_CLASS}`).forEach(element => { node.querySelectorAll(`.${BADGE_CLASS}`).forEach(element => {
tryRegisterObserverForBadge(element);
optimizeFontColorsBadges(element); optimizeFontColorsBadges(element);
}); });
} }
} }
} }
function tryRegisterObserverForBadge(badge) {
// some badges change there color via late loading so we also have to observe the classlist
// example: Navigating from a list to an anime -> "Currently Airing" late loads the color badge
// this only happens when navigating from a list, direct loading works
if (__observedBadges.indexOf(badge) >= 0) {
return;
}
let obsever = new MutationObserver(mutations => {
mutations.forEach(mutation => {
// prevent recursive calls when our class is added / removed
if ((mutation.oldValue?.indexOf(DARKCOLOR_CLASS) ?? -1 ^ mutation.target?.classList?.indexOf(DARKCOLOR_CLASS) ?? -1) === 0) {
return;
}
else {
optimizeFontColorsBadges(mutation.target);
}
});
});
obsever.observe(badge, {
attributes: true,
attributeFilter: ['class'],
attributeOldValue: true,
});
__observedBadges.push(badge);
}
function optimizeFontColorsBadges(badge) { function optimizeFontColorsBadges(badge) {
let colorStr = window.getComputedStyle(badge, null).getPropertyValue('background-color'); let colorStr = window.getComputedStyle(badge, null).getPropertyValue('background-color');
if (colorStr.length > 0) { // some elements do not have a computed background color // some elements do not have a computed background color
if (colorStr.length > 0) {
let color = new Color(colorStr) let color = new Color(colorStr)
if (color.isLight()) { badge.classList.toggle(DARKCOLOR_CLASS, color.isLight());
badge.classList.add('awp-fontColor-dark')
}
} }
} }