79 lines
4.7 KiB
JavaScript
79 lines
4.7 KiB
JavaScript
(() => {
|
|
'use strict';
|
|
const config = document.querySelector('[data-home-palette]'), img = document.querySelector('body > .home-wallpaper');
|
|
if (!config || !img || !window.HomePalette) return;
|
|
const body = document.body, core = window.HomePalette, forced = matchMedia('(forced-colors: active)');
|
|
let options = {mode:config.dataset.mode, strength:Number(config.dataset.strength), brightness:config.dataset.brightness};
|
|
let palette = null, pending = false, attempted = false;
|
|
const originals = new Map();
|
|
const restore = () => {
|
|
for (const [key, value] of originals) { if (value[0]) body.style.setProperty(key,...value); else body.style.removeProperty(key); }
|
|
originals.clear(); delete body.dataset.homePaletteActive;
|
|
};
|
|
const valid = p => p && ['average','accent'].every(k => Array.isArray(p[k]) && p[k].length === 3 && p[k].every(v => Number.isFinite(v) && v >= 0 && v <= 255)) && Number.isFinite(p.coverage) && p.coverage > 0 && p.coverage <= 1;
|
|
const cacheName = 'pageswiki.wallpaper-palette.v1';
|
|
const key = /^[a-f0-9]{64}$/.test(config.dataset.key || '') ? config.dataset.domain + ':' + config.dataset.key : '';
|
|
const cacheRead = () => { try { const rows = JSON.parse(sessionStorage.getItem(cacheName) || '[]'); if (!Array.isArray(rows) || rows.length > 24) return; const row = rows.find(x => x.key === key); if (row && valid(row.palette)) return row.palette; } catch {} };
|
|
const cacheWrite = p => {
|
|
if (!key) return;
|
|
let rows=[];
|
|
try { rows=JSON.parse(sessionStorage.getItem(cacheName) || '[]'); } catch {}
|
|
if (!Array.isArray(rows)) rows=[];
|
|
rows=rows.filter(x => x && x.key !== key && valid(x.palette)).slice(-23);
|
|
rows.push({key,palette:p});
|
|
try { sessionStorage.setItem(cacheName, JSON.stringify(rows)); } catch {}
|
|
};
|
|
// Resolve custom-theme CSS colors (including color-mix) through computed style.
|
|
function baseColors() {
|
|
const probe = document.createElement('span'), canvas = document.createElement('canvas');
|
|
canvas.width=canvas.height=1;
|
|
const ctx=canvas.getContext('2d',{willReadFrequently:true});
|
|
probe.hidden=true; body.append(probe);
|
|
try {
|
|
const read = name => { probe.style.color=`var(--${name})`; ctx.clearRect(0,0,1,1); ctx.fillStyle=getComputedStyle(probe).color; ctx.fillRect(0,0,1,1); return [...ctx.getImageData(0,0,1,1).data].slice(0,3); };
|
|
return {bg:read('bg'), fg:read('fg'), accent:read('accent')};
|
|
} finally { probe.remove(); }
|
|
}
|
|
function apply() {
|
|
restore();
|
|
if (!palette || options.mode === 'off' || !options.strength || forced.matches) return;
|
|
try {
|
|
const glass = parseFloat(getComputedStyle(body).getPropertyValue('--home-glass-opacity')) / 100;
|
|
const values=core.colors(palette,baseColors(),{...options,opacity:Number(getComputedStyle(img).opacity),glass:Number.isFinite(glass)?glass:.58});
|
|
if (!Object.keys(values).length) return;
|
|
for (const [name,value] of Object.entries(values)) { originals.set(name,[body.style.getPropertyValue(name),body.style.getPropertyPriority(name)]); body.style.setProperty(name,value); }
|
|
body.dataset.homePaletteActive=options.mode;
|
|
} catch { restore(); }
|
|
}
|
|
function schedule() {
|
|
if (options.mode === 'off' || !options.strength || forced.matches) { restore(); return; }
|
|
if (palette) { apply(); return; }
|
|
if (!img.complete || !img.naturalWidth || pending || attempted) return;
|
|
pending=true;
|
|
const work=() => {
|
|
pending=false;
|
|
if (options.mode === 'off' || !options.strength || forced.matches) return;
|
|
attempted=true;
|
|
try {
|
|
palette=key && cacheRead();
|
|
if (!palette) {
|
|
const canvas=document.createElement('canvas'); canvas.width=canvas.height=64;
|
|
const ctx=canvas.getContext('2d',{willReadFrequently:true});
|
|
// Reuse the already displayed/decoded image: no second fetch or random pick.
|
|
ctx.drawImage(img,0,0,64,64); palette=core.extract(ctx.getImageData(0,0,64,64).data);
|
|
if (valid(palette)) { cacheWrite(palette); config.dataset.paletteSource='image'; }
|
|
} else config.dataset.paletteSource='cache';
|
|
if (valid(palette)) apply();
|
|
} catch { palette=null; restore(); }
|
|
};
|
|
if ('requestIdleCallback' in window) requestIdleCallback(work,{timeout:1500}); else setTimeout(work,32);
|
|
}
|
|
document.addEventListener('pageswiki:home-appearance', event => { if (event.detail) options={...options,...event.detail}; schedule(); });
|
|
document.addEventListener('pageswiki:theme',schedule);
|
|
document.addEventListener('load', event => { if (event.target instanceof HTMLLinkElement && event.target.rel === 'stylesheet') schedule(); },true);
|
|
forced.addEventListener('change',schedule);
|
|
img.addEventListener('load',schedule);
|
|
img.addEventListener('error',() => { palette=null; restore(); });
|
|
schedule();
|
|
})();
|