feat: adapt home appearance to wallpaper colors
Build and publish container images / images (push) Successful in 10m56s
Release container images / release (push) Successful in 18s

This commit is contained in:
Anya Tokugawa committed 2026-11-07 22:51:56 +09:00
1 parent c7aa4fd7dd
commit 0964fdc5b7
23 files changed
+628 -32

No files matched your search

+19 -3
View File
@@ -8,23 +8,35 @@
if (!open || !dialog || !form || !input || !output || !status) return;
let saved = Number(input.value);
const paletteNames = ['home_palette_mode','home_palette_strength','home_palette_brightness'];
let savedPalette = paletteNames.map(name => form.elements[name]?.value);
const palettePreview = () => {
const strength = Number(form.elements.home_palette_strength?.value ?? 35);
const label = form.querySelector('[data-palette-strength]');
if (label) label.textContent = `${strength}%`;
document.dispatchEvent(new CustomEvent('pageswiki:home-appearance', {detail:{mode:form.elements.home_palette_mode?.value || 'off', strength, brightness:form.elements.home_palette_brightness?.value || 'preserve'}}));
};
const preview = value => {
const transparency = Math.max(0, Math.min(85, Number(value) || 0));
document.body.style.setProperty('--home-glass-opacity', `${100 - transparency}%`);
output.value = `${transparency}%`;
output.textContent = `${transparency}%`;
palettePreview();
};
const restore = () => {
input.value = String(saved);
paletteNames.forEach((name,i) => { if (form.elements[name]) form.elements[name].value=savedPalette[i]; });
preview(saved);
status.textContent = '';
};
const close = () => {
if (form.querySelector('[type=submit]').disabled) return;
restore();
dialog.close();
};
input.addEventListener('input', () => preview(input.value));
paletteNames.forEach(name => form.elements[name]?.addEventListener('input',palettePreview));
open.addEventListener('click', () => {
restore();
dialog.showModal();
@@ -46,25 +58,29 @@
event.preventDefault();
const submit = form.querySelector('[type=submit]');
if (submit.disabled) return;
const submitted = new URLSearchParams(new FormData(form));
const controls = [...form.querySelectorAll('input,select,button')].filter(node => !node.disabled);
controls.forEach(node => { node.disabled=true; });
submit.disabled = true;
status.textContent = '';
try {
const response = await fetch(form.action, {
method: 'POST',
body: new URLSearchParams(new FormData(form)),
body: submitted,
headers: {Accept: 'application/json'},
signal: AbortSignal.timeout(15000),
});
if (!response.ok) throw new Error((await response.text()).trim());
await response.json();
saved = Number(input.value);
saved = Number(submitted.get('home_glass_transparency'));
savedPalette = paletteNames.map(name => submitted.get(name));
preview(saved);
status.textContent = form.dataset.saved;
window.setTimeout(() => dialog.open && dialog.close(), 350);
} catch (error) {
status.textContent = error.message;
} finally {
submit.disabled = false;
controls.forEach(node => { node.disabled=false; });
}
});
})();
+58
View File
@@ -0,0 +1,58 @@
/* Bounded, dependency-free palette math; also exercised by node --test. */
((root) => {
'use strict';
const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const mix = (a, b, n) => a.map((x, i) => x * (1 - n) + b[i] * n);
const luminance = c => c.map(x => { x /= 255; return x <= .04045 ? x / 12.92 : ((x + .055) / 1.055) ** 2.4; }).reduce((a, x, i) => a + x * [.2126, .7152, .0722][i], 0);
const contrast = (a, b) => (Math.max(luminance(a), luminance(b)) + .05) / (Math.min(luminance(a), luminance(b)) + .05);
const ink = bg => contrast([255,255,255], bg) >= contrast([0,0,0], bg) ? [255,255,255] : [0,0,0];
const readable = (c, bg, ratio) => {
const end = ink(bg);
for (let n = 0; n <= 20; n++) { const v = mix(c, end, n / 20); if (contrast(v, bg) >= ratio) return v; }
return end;
};
const css = c => '#' + c.map(v => Math.round(clamp(v,0,255)).toString(16).padStart(2,'0')).join('');
function extract(pixels) {
if (!pixels || pixels.length > 64 * 64 * 4 || pixels.length % 4) return null;
const bins = new Map(), sum = [0,0,0]; let weight = 0;
for (let i = 0; i < pixels.length; i += 4) {
const a = pixels[i+3] / 255; if (a < .06) continue;
const c = [pixels[i], pixels[i+1], pixels[i+2]], key = c.map(x => x >> 5).join(',');
const bin = bins.get(key) || {sum:[0,0,0], weight:0};
c.forEach((v,j) => { sum[j] += v*a; bin.sum[j] += v*a; });
bin.weight += a; weight += a; bins.set(key, bin);
}
if (!weight) return null;
const average = sum.map(x => x / weight); let accent = average, best = 0;
for (const bin of bins.values()) {
const c = bin.sum.map(x => x / bin.weight), hi = Math.max(...c), lo = Math.min(...c);
const saturation = hi ? (hi-lo)/hi : 0, light = luminance(c);
const score = Math.sqrt(bin.weight) * saturation * (light > .025 && light < .85 ? 1 : .1);
if (score > best) { best = score; accent = c; }
}
return {average, accent, coverage:weight / (pixels.length / 4)};
}
function colors(p, base, opts) {
if (!p || opts.mode === 'off' || !opts.strength || opts.opacity <= 0) return {};
const strength = clamp(opts.strength / 100), opacity = clamp(opts.opacity * p.coverage);
const backdrop = mix(base.bg, p.average, opacity);
const dark = opts.brightness === 'auto' && opts.mode === 'surface' ? luminance(backdrop) < .36 : luminance(base.bg) < .36;
const neutral = dark ? [18,20,26] : [244,246,250];
const hue = mix(p.average, p.accent, .35);
const tinted = mix(neutral, hue, dark ? .23 : .12);
const bg = opts.mode === 'surface' ? mix(opts.brightness === 'auto' ? neutral : base.bg, tinted, strength) : base.bg;
const behind = mix(bg, p.average, opacity), glass = mix(behind, bg, clamp(opts.glass));
const accent = readable(mix(base.accent, p.accent, strength), glass, 3);
const result = {'--accent':css(accent), '--link':css(readable(accent, glass, 4.5)), '--link-hover':css(readable(accent,glass,7))};
if (opts.mode !== 'surface') return result;
const fg = readable(dark ? [238,242,248] : [22,25,32], glass, 7);
Object.assign(result, {'--bg':css(bg), '--panel':css(bg), '--fg':css(fg), '--muted':css(readable(mix(fg,glass,.3),glass,4.5)),
'--border':css(mix(bg,accent,.32)), '--border-soft':css(mix(bg,accent,.18)),
'--input-bg':css(bg), '--input-fg':css(fg), '--input-border':css(mix(bg,accent,.4)),
'--button-bg':css(bg), '--button-fg':css(fg), '--button-border':css(mix(bg,accent,.4)), '--button-hover-bg':css(mix(bg,accent,.12))});
return result;
}
const api = {extract, colors, luminance, contrast, mix};
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.HomePalette = api;
})(globalThis);
+48
View File
@@ -0,0 +1,48 @@
const test=require('node:test'), assert=require('node:assert/strict');
const p=require('./home-palette-core.js');
const pixels=(color,count=4096)=>new Uint8ClampedArray(Array.from({length:count},()=>color).flat());
const rgb=hex=>[1,3,5].map(i=>parseInt(hex.slice(i,i+2),16));
const base={bg:[17,17,17],fg:[240,240,240],accent:[176,119,255]};
const opts={mode:'surface',strength:35,brightness:'preserve',opacity:.4,glass:.58};
test('bounded transparent and invalid input',()=>{
assert.equal(p.extract(pixels([0,0,0,0])),null);
assert.equal(p.extract(new Uint8Array(64*64*4+4)),null);
assert.equal(p.extract(new Uint8Array(3)),null);
assert.equal(p.extract(new Uint8Array(0)),null);
});
test('solid colors and alpha coverage',()=>{
assert.deepEqual(p.extract(pixels([10,70,180,255])).average,[10,70,180]);
assert.ok(Math.abs(p.extract(pixels([10,70,180,128])).coverage-128/255)<1e-10);
});
test('colored minority is selected instead of a muddy average',()=>{
const data=pixels([180,180,180,255]);for(let i=0;i<400*4;i+=4)data.set([20,90,220,255],i);
assert.deepEqual(p.extract(data).accent,[20,90,220]);
});
test('off, invisible wallpaper and zero strength preserve all tokens',()=>{
const palette=p.extract(pixels([40,90,220,255]));
for(const change of [{mode:'off'},{strength:0},{opacity:0}])assert.deepEqual(p.colors(palette,base,{...opts,...change}),{});
});
test('accent only never changes surfaces, brightness or semantic colors',()=>{
const c=p.colors(p.extract(pixels([240,100,30,255])),base,{...opts,mode:'accent',brightness:'auto'});
assert.deepEqual(Object.keys(c).sort(),['--accent','--link','--link-hover']);
});
test('dark/light, black/white and colored wallpaper keep readable panel text',()=>{
for(const bg of [[17,17,17],[245,245,245]])for(const color of [[0,0,0],[255,255,255],[200,30,100],[20,90,220]])for(const strength of [5,35,100]) {
const palette=p.extract(pixels([...color,255]));
const c=p.colors(palette,{...base,bg},{...opts,strength});
const surface=rgb(c['--bg']),behind=p.mix(surface,palette.average,opts.opacity),glass=p.mix(behind,surface,opts.glass);
// Target enhanced contrast where possible; mid-tone glass can only provide
// normal contrast even with pure black/white. Allow for RGB rounding.
assert.ok(p.contrast(rgb(c['--fg']),glass)>4.4);
assert.ok(p.contrast(rgb(c['--muted']),glass)>4.4);
assert.ok(!('--danger' in c));
assert.ok(Object.values(c).every(v=>/^#[0-9a-f]{6}$/.test(v)));
}
});
test('auto brightness follows composited wallpaper, not invisible source pixels',()=>{
const palette=p.extract(pixels([255,255,255,255]));
const dark=p.colors(palette,base,{...opts,brightness:'auto',opacity:.1});
const light=p.colors(palette,base,{...opts,brightness:'auto',opacity:1});
assert.ok(p.luminance(rgb(dark['--bg']))<.1);
assert.ok(p.luminance(rgb(light['--bg']))>.5);
});
+78
View File
@@ -0,0 +1,78 @@
(() => {
'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();
})();