Files
zyt/admin/tests/stats-theme-pilots.test.cjs
T

149 lines
6.8 KiB
JavaScript

const assert = require('node:assert/strict')
const path = require('node:path')
const test = require('node:test')
const { buildSync } = require('esbuild')
const { createPinia } = require('pinia')
const vue = require('vue')
const admin = path.resolve(__dirname, '..')
function compile(file) {
return buildSync({
absWorkingDir: admin, entryPoints: [file], alias: { '@': path.join(admin, 'src') },
bundle: true, packages: 'external', platform: 'node', format: 'cjs', write: false
}).outputFiles[0].text
}
const hookSource = compile('src/hooks/useStatsChartPalette.ts')
const settingsSource = compile('src/stores/modules/setting.ts')
function load(source, globals = {}, imports = {}) {
const mod = { exports: {} }
new Function('module', 'exports', 'require', ...Object.keys(globals), source)(
mod, mod.exports, id => imports[id] || require(id), ...Object.values(globals))
return mod.exports
}
// Independent WCAG relative-luminance check; don't use the hook's own contrast helper.
function contrast(a, b) {
function luminance(color) {
const channels = color.match(/\w\w/g).map(x => parseInt(x, 16) / 255)
return channels.reduce((sum, c, i) => sum + [0.2126, 0.7152, 0.0722][i] *
(c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4), 0)
}
const l = [luminance(a), luminance(b)].sort((x, y) => y - x)
return (l[0] + 0.05) / (l[1] + 0.05)
}
test('custom accents remain literal where legible; marks, text and muted labels meet contrast on both surfaces', () => {
const { statsChartPalette } = load(hookSource)
for (const dark of [false, true]) {
for (const accent of ['#5d87ff', '#6b34c2', '#ffffef', '#030303', '#27eb77']) {
const tokens = { '--el-color-primary': accent, '--zyt-muted': dark ? '#111' : '#eee' }
const p = statsChartPalette(key => tokens[key] || '', dark)
assert.equal(p.accent, accent)
for (const key of ['accentInk', 'accentText', 'muted', 'surface', 'ink', 'soft', 'grid', 'border']) {
assert.match(p[key], /^#[a-f\d]{6}$/i, key)
}
for (const [key, min] of [['accentInk', 3], ['accentText', 4.5], ['muted', 4.5]]) {
assert.ok(contrast(p[key], p.surface) >= min, `${accent} ${key} on ${p.surface}`)
if (key !== 'muted' && contrast(accent, p.surface) >= min) assert.equal(p[key], accent)
}
}
}
})
// Run the production Pinia stylesheet writer against a small DOM. Deliver only mutations
// actually subscribed to, in batches: assigning style.textContent is NOT an html attribute change.
function harness() {
const listeners = new Set()
class MutationObserver {
constructor(callback) { this.callback = callback; this.targets = new Map(); this.pending = [] }
observe(target, options) { this.targets.set(target, options); listeners.add(this) }
disconnect() { this.targets.clear(); this.pending = []; listeners.delete(this) }
}
function emit(target, type, attributeName) {
for (const listener of listeners) {
const opts = listener.targets.get(target)
if (opts?.[type] && (!attributeName || !opts.attributeFilter || opts.attributeFilter.includes(attributeName))) {
listener.pending.push({ target, type, attributeName })
}
}
}
function flush() {
for (const listener of listeners) {
if (listener.pending.length) listener.callback(listener.pending.splice(0))
}
}
let dark = false
const sheets = new Map()
const root = { dataset: { adminUi: 'v2' }, classList: { contains: key => key === 'dark' && dark } }
const head = { appendChild(sheet) { sheets.set(sheet.id, sheet); emit(head, 'childList') } }
const document = { documentElement: root, head, getElementById: id => sheets.get(id) || null,
createElement(tag) {
assert.equal(tag, 'style')
let css = ''
return { id: '', get textContent() { return css },
set textContent(value) { css = value; emit(this, 'childList') } }
}
}
const getComputedStyle = () => ({
getPropertyValue(key) {
const css = sheets.get('art-theme-vars')?.textContent || ''
return css.match(new RegExp('[{;]' + key + ':([^;}]+)'))?.[1] || ''
}
})
const events = {}
const lifecycles = { ...vue }
for (const name of ['onActivated', 'onDeactivated', 'onMounted', 'onScopeDispose']) {
lifecycles[name] = callback => { events[name] = callback }
}
const { useStatsChartPalette } = load(hookSource, { document, getComputedStyle, MutationObserver }, { vue: lifecycles })
const settings = load(settingsSource, { document }).useSettingStore(createPinia())
const palette = useStatsChartPalette()
return { events, palette, flush, sheets, listeners,
pick(hex) { settings.setSetting({ key: 'theme', value: hex }); settings.setTheme(dark); flush() },
mode(value) { root.dataset.adminUi = value; emit(root, 'attributes', 'data-admin-ui'); flush() },
dark(value) { dark = value; emit(root, 'attributes', 'class'); settings.setTheme(dark); flush() }
}
}
test('an open page follows initial stylesheet insertion and subsequent picker writes to the same style node', () => {
const h = harness()
h.events.onMounted()
h.events.onActivated()
assert.equal(h.listeners.size, 1)
h.pick('#8833aa')
const initialSheet = h.sheets.get('art-theme-vars')
assert.ok(initialSheet)
assert.equal(h.palette.value.accent, '#8833aa')
h.pick('#bb3311')
assert.equal(h.sheets.get('art-theme-vars'), initialSheet)
assert.equal(h.palette.value.accentInk, '#bb3311')
const light = h.palette.value
h.dark(true)
assert.equal(h.palette.value.dark, true)
assert.notEqual(h.palette.value.surface, light.surface)
assert.notEqual(h.palette.value.grid, light.grid)
assert.ok(contrast(h.palette.value.grid, h.palette.value.surface) < 2)
h.events.onScopeDispose()
assert.equal(h.listeners.size, 0)
})
test('cached pages disconnect, catch up on reactivation, and relinquish the V2 palette in classic mode', () => {
const h = harness()
h.pick('#4411aa') // The sheet may predate the component mount.
h.events.onMounted()
assert.equal(h.palette.value.accent, '#4411aa')
h.events.onDeactivated()
assert.equal(h.listeners.size, 0)
h.pick('#224455')
assert.equal(h.palette.value.accent, '#4411aa')
h.events.onActivated()
assert.equal(h.palette.value.accent, '#224455')
h.mode('legacy')
assert.equal(h.palette.value, null)
h.mode('v2')
assert.equal(h.palette.value.accent, '#224455')
h.events.onScopeDispose()
h.pick('#331177')
assert.equal(h.palette.value.accent, '#224455')
assert.equal(h.listeners.size, 0)
})