From 2e61cf3ede106ada67b9423c9e489012be78b102 Mon Sep 17 00:00:00 2001 From: Serraniel Date: Wed, 23 Dec 2020 20:01:06 +0100 Subject: [PATCH] #109 Added observer to react to late changes of a badge class --- src/javascript/enhancements/fontColor.js | 42 +++++++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/src/javascript/enhancements/fontColor.js b/src/javascript/enhancements/fontColor.js index 54ea387..6d3ddeb 100644 --- a/src/javascript/enhancements/fontColor.js +++ b/src/javascript/enhancements/fontColor.js @@ -4,6 +4,8 @@ import * as core from '../utils/aniwatchCore'; import * as helper from '../utils/helpers'; const BADGE_CLASS = 'label'; +const DARKCOLOR_CLASS = 'awp-fontColor-dark'; +const __observedBadges = []; export function init() { getGlobalConfiguration().getProperty(SETTINGS_websiteOptimizeFontColors, value => { @@ -24,27 +26,57 @@ export function init() { } function checkRunColorOptimization(node) { - // run the scripts if (helper.isHtmlElement(node)) { if (node.classList.contains(BADGE_CLASS)) { + tryRegisterObserverForBadge(node); optimizeFontColorsBadges(node); } else { node.querySelectorAll(`.${BADGE_CLASS}`).forEach(element => { + tryRegisterObserverForBadge(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) { 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) - if (color.isLight()) { - badge.classList.add('awp-fontColor-dark') - } + badge.classList.toggle(DARKCOLOR_CLASS, color.isLight()); } } \ No newline at end of file