/**
* @module themes
* @description Color presets and default options for WaveformPlayer
*/
import type {WaveformMarker} from './types.js';
import {
parseColor,
perceivedBrightness,
toArray,
toBool,
toEnum,
toFiniteNumber,
toNumberArray,
DEFAULT_SAMPLES
} from './utils.js';
/**
* Brightness (0–255) above which a backdrop counts as light.
* @type {number}
* @private
*/
const LIGHT_THRESHOLD = 128;
/**
* Does `` or `
` explicitly signal the given colour scheme via a
* known class name (`dark`, `dark-mode`, `theme-dark`) or theme attribute
* (`data-theme`, and `data-color-scheme` on the root)?
* @param scheme - Scheme to look for.
* @returns True if the page explicitly hints at `scheme`.
* @private
*/
function hasThemeHint(scheme: 'dark' | 'light'): boolean {
const root = document.documentElement;
const body = document.body;
return (
root.classList.contains(scheme) ||
root.classList.contains(`${scheme}-mode`) ||
root.classList.contains(`theme-${scheme}`) ||
root.getAttribute('data-theme') === scheme ||
root.getAttribute('data-color-scheme') === scheme ||
body.classList.contains(scheme) ||
body.classList.contains(`${scheme}-mode`) ||
body.getAttribute('data-theme') === scheme
);
}
/**
* Collect what the page paints behind `el`.
*
* Walks `el` and its ancestors up to `` (through shadow-root hosts),
* alpha-compositing each element's
* background *colour* front-to-back. Walking the chain (rather than reading
* `` alone) is what makes real layouts work: plenty of pages paint their
* background on a wrapper `
` or on `` instead of ``, and a
* player sitting inside a dark card on an otherwise light page should theme to
* the card.
*
* Compositing rather than taking the first colour found means translucent
* layers — an `rgba(0, 0, 0, 0.04)` tint over white, say — score as what the eye
* sees instead of as their own colour. Brightness is linear in R/G/B, so
* blending per-layer brightnesses is equivalent to blending the colours.
*
* Background *images* and gradients can't be scored from CSS, so a page painted
* only that way contributes no colour here and is classified by
* {@link detectCanvasScheme} instead.
*
* @param el - Element to start from (the player's container).
* @returns Premultiplied brightness, and how much
* of the stack is opaque (0–1).
* @private
*/
function collectBackdrop(el: Element): {sum: number, alpha: number} {
let sum = 0;
let alpha = 0;
// At a shadow root parentElement is null; continue from the shadow host,
// or a player inside a web component / extension UI stops reading the
// page at its own boundary and misses the card it sits on.
const up = (node: Element): Element | null => node.parentElement || (node as any).getRootNode?.().host || null;
for (let node: Element | null = el; node && node.nodeType === 1 && alpha < 0.995; node = up(node)) {
const c = parseColor(getComputedStyle(node).backgroundColor);
if (!c || c.a <= 0) continue;
// Each layer only shows through however much is still see-through.
const weight = c.a * (1 - alpha);
sum += ((c.r * 299 + c.g * 587 + c.b * 114) / 1000) * weight;
alpha += weight;
}
return {sum, alpha};
}
/**
* Scheme of the canvas — what is visible wherever the page paints no background
* colour of its own.
*
* Read from the page's *resolved text colour*. `color` initially resolves to the
* `canvastext` system colour, which browsers flip to white exactly when the
* document's used colour-scheme is dark, so it reports the palette the page is
* actually designed for. It is also the only signal that sees the
* `` form — Chrome reports
* `normal` for the computed `color-scheme` property there, so reading that
* instead would miss the exact setup in #21.
*
* Deliberately NOT `prefers-color-scheme`. That describes the **user**, not the
* page, and what browsers paint behind an unpainted page under a dark
* preference turns out to be engine-specific — measured by screenshotting the
* same page in both engines: Chromium composites a dark `#121212` base
* background, WebKit keeps it white. Since no scripted signal can tell those
* apart, we believe the page instead: black text means it was designed light,
* so it gets the light preset. That is right in WebKit, and in Chromium it only
* loses on a page whose own text is already unreadable against that same dark
* base background. The media query survives purely as a last resort for
* environments with no resolvable text colour.
*
* @returns Scheme of the canvas behind the page.
* @private
*/
function detectCanvasScheme(): 'dark' | 'light' {
// Light text ⇒ the page is painted for a dark canvas, and vice versa.
const text = perceivedBrightness(getComputedStyle(document.body).color);
if (text !== null) return text > LIGHT_THRESHOLD ? 'dark' : 'light';
if (window.matchMedia) {
if (window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';
if (window.matchMedia('(prefers-color-scheme: light)').matches) return 'light';
}
// Knowing nothing at all keeps the historic default — most audio players
// are dark.
return 'dark';
}
/**
* Detect the appropriate color scheme for the player from the surrounding page.
*
* Resolution order, first match wins:
* 1. Explicit theme hints on ``/`` — class names
* (`dark`, `dark-mode`, `theme-dark`, light equivalents) and data
* attributes (`data-theme`, `data-color-scheme`).
* 2. The backdrop actually visible behind the player — every background from
* `el` up through `` ({@link collectBackdrop}), composited over the
* canvas ({@link detectCanvasScheme}). >128 = light, <128 = dark.
* 3. The canvas scheme alone, for the knife-edge case where the composite
* lands exactly on the threshold.
*
* @param el - The player's container, so a player inside a themed
* card picks up that card. Defaults to ``.
* @returns The detected scheme, either `'dark'` or `'light'`.
*/
export function detectColorScheme(el?: Element): 'dark' | 'light' {
// 1. Explicit theme class names / data attributes win.
if (hasThemeHint('dark')) return 'dark';
if (hasThemeHint('light')) return 'light';
try {
// 2. What the player is actually sitting on.
const start = (el && el.nodeType === 1) ? el : document.body;
const {sum, alpha} = collectBackdrop(start);
// Whatever transparency is left over after the page's own layers shows
// the canvas through.
const canvas = detectCanvasScheme();
const brightness = sum + (canvas === 'dark' ? 0 : 255) * (1 - alpha);
if (brightness > LIGHT_THRESHOLD) return 'light';
if (brightness < LIGHT_THRESHOLD) return 'dark';
// 3. Dead-centre grey tells us nothing; go with the canvas.
return canvas;
} catch (e) {
// No usable computed styles (SSR shim, detached document) — most audio
// players are dark, so that stays the fallback.
return 'dark';
}
}
/**
* Built-in colour presets keyed by scheme name.
*
* Each preset is a flat map of the player's themeable colour tokens
* (waveform, progress, button, text, background, border). They are deliberately
* simple translucent black/white values so they sit on any host background, and
* any individual token can be overridden per-instance via the matching
* `*Color` option in {@link DEFAULT_OPTIONS}.
*
* @type {Object>}
* @property {Object} dark Light-on-dark token set.
* @property {Object} light Dark-on-light token set.
*/
export const COLOR_PRESETS: Record = {
dark: {
waveformColor: 'rgba(255, 255, 255, 0.3)',
progressColor: 'rgba(255, 255, 255, 0.9)'
},
light: {
waveformColor: 'rgba(0, 0, 0, 0.2)',
progressColor: 'rgba(0, 0, 0, 0.8)'
}
};
/**
* Resolve a colour preset by name, falling back to auto-detection.
*
* When `presetName` names a known preset it is returned as-is; otherwise
* (null, undefined, or an unrecognised name) the scheme is auto-detected via
* {@link detectColorScheme} and the corresponding preset is returned.
*
* @param presetName - Preset name (`'dark'` or `'light'`), or
* null/invalid to trigger auto-detection.
* @param el - Container passed through to {@link detectColorScheme}
* so detection reads the backdrop behind this player, not just ``.
* @returns The matching colour token map from
* {@link COLOR_PRESETS}.
*/
export function getColorPreset(presetName: string | null, el?: Element): { waveformColor: string; progressColor: string } {
// If explicitly set to a valid preset, use it
if (presetName && COLOR_PRESETS[presetName]) {
return COLOR_PRESETS[presetName];
}
// Auto-detect if not specified or invalid
const detected = detectColorScheme(el);
return COLOR_PRESETS[detected];
}
/**
* Default option set for a {@link WaveformPlayer} instance.
*
* User-supplied options are merged over this object, so every supported option
* is enumerated here with its baseline value. `null` colour tokens mean "inherit
* from the resolved {@link COLOR_PRESETS} preset"; `null` content/callback
* fields mean "unset". See the grouped inline comments for per-field notes,
* notably the `audioMode` self/external distinction and the `accessibleSeek`
* keyboard slider.
*
* @type {Object}
*/
export const DEFAULT_OPTIONS = {
// Core settings
url: '',
height: 64,
// Source peak resolution for LIVE decode (ignored when peaks are supplied).
// The drawer resamples these to fit canvasWidth / (barWidth + barSpacing)
// bars, so this is fidelity headroom, not the visible bar count. 1800 (the
// SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
// every-frame scan means a higher value costs no extra extraction time.
samples: DEFAULT_SAMPLES,
preload: 'metadata',
// Known track length in seconds, used until the audio's own metadata
// arrives — chiefly with preload 'none', where that is only on play. The
// time readout, markers, hover time, the seek slider and Media Session use
// it meanwhile; a seek in that window is remembered and applied once the
// audio can seek. null = wait for the metadata, as before. Per-track.
duration: null,
// Defer the expensive work — assigning the audio source, fetching a peaks
// sidecar, decoding, drawing — until the player comes within 200px of the
// viewport (one shared IntersectionObserver), or until something needs
// it (play, a seek, loadTrack). For pages with many players.
lazy: false,
// CORS mode for the underlying