diff --git a/CHANGELOG.md b/CHANGELOG.md index 0856200..2a5cee4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - Card DOM (`src/card.js`): adds, updates and removes an artwork image at the start of a media card's info container. The image stays hidden until it loads, and only `https:` or image `data:` sources are set. - Runtime (`src/runtime.js`, `src/install.js`): watches Zen's media cards and each playing tab's metadata, and keeps every card's artwork in step with the track it shows, picking an image sized for the screen's pixel density. Disabling the mod or re-running it removes all artwork and listeners. - Sine manifest (`theme.json`) and a minimal `chrome.css` that sizes the thumbnail, so the mod can be installed from this repository. +- Artwork styles, chosen under the mod's settings in Sine (`preferences.json`, pref `zen-media-viz.artwork-style`): a small thumbnail beside the title (default), a large centered cover above the title, or the artwork behind the whole card, which grows to a square on hover so the whole cover shows. Changing the style applies at once. +- The media card's buttons show a pointer cursor. +- The small thumbnail hides in very narrow sidebars, and artwork is fetched again at a higher resolution when the window moves to a denser screen. - Claude Code project skills: `unslop` (code style, summarized in the contributing guide), `mine` (attribution policy) and `ship-it` (commit, review and fix loop). [Unreleased]: https://github.com/rodzy/Zen-Media-Viz/commits/main diff --git a/CLAUDE.md b/CLAUDE.md index 19a292b..04e60b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,13 +16,13 @@ A Zen Browser mod, loaded by the Sine mod manager, that shows album artwork in Z ## Architecture - `src/*.js` are ES modules. `build.mjs` (esbuild) bundles `src/index.js` into one IIFE, `zen-media-viz.uc.js`, at the repo root. **The bundle is generated but committed**: Sine installs straight from the GitHub repo and only executes `.uc.js` (not `.uc.mjs`). After changing `src/`, run `npm run build` and commit the bundle too. Never hand-edit it. -- Sine integration: `theme.json` and `chrome.css` at the repo root (from Sine's source, `CosmoCreeper/Sine` `src/core/manager.sys.mjs` and `utils.sys.mjs`). `scripts` maps a path relative to the repo root to `{ include: [...] }`; `*` in a pattern is a wildcard and the pattern must match the whole window URL. Only `.uc.js` scripts are loaded as classic subscripts, once per matching window after its `load` event; `style.chrome` is applied as a user stylesheet. Mods outside Sine's store run JS only when the user allows unsafe JS in Sine's settings. Sine gives the window `addUnloadListener(callback)`: it calls the callback when the mod is disabled and before re-running the script into an open window; with `supportsUnload: true` Sine doesn't ask for a restart on disable. `src/install.js` registers `window.ZenMediaViz.destroy()` there and also calls any previous instance's `destroy()` before starting. +- Sine integration: `theme.json` and `chrome.css` at the repo root (from Sine's source, `CosmoCreeper/Sine` `src/core/manager.sys.mjs` and `utils.sys.mjs`). `scripts` maps a path relative to the repo root to `{ include: [...] }`; `*` in a pattern is a wildcard and the pattern must match the whole window URL. Only `.uc.js` scripts are loaded as classic subscripts, once per matching window after its `load` event; `style.chrome` is applied as a user stylesheet. Mods outside Sine's store run JS only when the user allows unsafe JS in Sine's settings. Sine gives the window `addUnloadListener(callback)`: it calls the callback when the mod is disabled and before re-running the script into an open window; with `supportsUnload: true` Sine doesn't ask for a restart on disable. `src/install.js` registers `window.ZenMediaViz.destroy()` there and also calls any previous instance's `destroy()` before starting. Mod settings live in `preferences.json` (Sine renders `dropdown`, `checkbox`, `string` and `separator` entries, stored as `about:config` prefs). `src/settings.js` reads them through the injected `Services.prefs` and observes changes. `chrome.css` is loaded as a **user** sheet, so overriding one of Zen's own rules needs `!important`; Zen's card styles are in `zen-browser/desktop` `src/zen/media/zen-media-controls.css`. - **Injected globals:** logic modules never read `gBrowser`, `gZenMediaController`, `window` or `document` directly; they take them as parameters. Only `src/index.js` touches the real window. Tests pass fakes. DOM tests opt in with `// @vitest-environment happy-dom` (default environment is `node`). - Zen/Firefox APIs relied on (from `zen-browser/desktop` `src/zen/media/` and Firefox's `MediaController.webidl`), verified on Zen 1.24.3b (Gecko 160.0.1) by the spike (`docs/spike.md`, `npm run spike`). Its report is the fixture `test/fixtures/zen-1.24.3b.json`, and `test/zen-fixture.test.js` pins the facts below: - Media cards: `#zen-media-controls-toolbar` > `.zen-media-card` (cloned from `#zen-media-card-template`, which sits inside the toolbar) > `.zen-media-main-vbox` > `vbox` > `.zen-media-info-container` > `.zen-media-info-vbox` > `.zen-media-title` / `.zen-media-artist`. Use descendant selectors, not child chains. Zen sets only title and artist; it ignores artwork. The recorded card had a `playing` class; per Zen's source, cards are created `hidden` and shown when their tab isn't selected. - Cards carry no attribute naming their controller or browser (only `class`, `style`, `hidden`). Match cards to controllers by title and artist. From Zen's source, not verified by the spike: the card-to-controller map is a private field, and `gZenMediaController.frontCard` returns a card object with `element`, `browser` and `controller`, but only for the front visible card. - `tab.linkedBrowser.browsingContext.mediaController.getMetadata()` returns `{title, artist, album, artwork: [{src, sizes, type}]}` with absolute `src`. It **throws** `NS_ERROR_NOT_AVAILABLE` when the controller is inactive. The controller fires `metadatachange`. - - `browser.xhtml`'s CSP is `script-src chrome: moz-src: resource:; frame-src chrome:; object-src 'none';`, with no `img-src`, so it shouldn't restrict images (confirm a real artwork image renders once the mod runs in Zen, Milestone 5). Limiting artwork to `https:`/`data:` sources is the mod's own choice: no plain `http:`, and no `blob:` or privileged schemes from the page. + - `browser.xhtml`'s CSP is `script-src chrome: moz-src: resource:; frame-src chrome:; object-src 'none';`, with no `img-src`, so it doesn't restrict images (confirmed: real artwork renders in the card on Zen 1.24.3b, macOS). Limiting artwork to `https:`/`data:` sources is the mod's own choice: no plain `http:`, and no `blob:` or privileged schemes from the page. - Anything that can't be tested under Node goes in `docs/manual-testing.md`. ## Workflow diff --git a/chrome.css b/chrome.css index 8889706..b89320c 100644 --- a/chrome.css +++ b/chrome.css @@ -1,12 +1,121 @@ +#zen-media-controls-toolbar { + --zen-media-viz-thumbnail-size: 48px; + --zen-media-viz-cover-size: min(100cqw - 32px, 220px); + --zen-media-viz-text-room: 76px; + --zen-media-viz-background-opacity: 0.35; + --zen-media-viz-easing: var(--zen-media-stack-easing, ease-out); +} + .zen-media-viz-artwork { - flex: none; - width: 36px; - height: 36px; - margin-inline-end: 8px; - border-radius: 4px; + pointer-events: none; object-fit: cover; + + &[hidden] { + display: none !important; + } +} + +.zen-media-info-container:has(> .zen-media-viz-artwork:not([hidden])) > .zen-media-info-vbox { + overflow-x: clip !important; + width: auto !important; + min-width: 0 !important; + + &::before { + display: none !important; + } +} + +#zen-media-controls-toolbar[zen-media-viz-style="small"] { + .zen-media-info-container > .zen-media-info-vbox { + flex: 1 1 0 !important; + align-self: center; + } + + .zen-media-viz-artwork { + flex: none; + align-self: center; + width: var(--zen-media-viz-thumbnail-size); + height: var(--zen-media-viz-thumbnail-size); + margin-inline-end: 10px; + border-radius: 6px; + } +} + +@container (min-width: 181px) { + #zen-media-controls-toolbar[zen-media-viz-style="small"]:hover + .zen-media-info-container.show-on-hover:has(> .zen-media-viz-artwork:not([hidden])) { + max-height: calc(var(--zen-media-viz-thumbnail-size) + 2 * var(--zen-space-5, 6px)) !important; + } +} + +@container (max-width: 180px) { + #zen-media-controls-toolbar[zen-media-viz-style="small"] .zen-media-viz-artwork { + display: none; + } +} + +#zen-media-controls-toolbar[zen-media-viz-style="large"] { + .zen-media-info-container { + flex-wrap: wrap; + } + + &:hover .zen-media-info-container.show-on-hover:has(> .zen-media-viz-artwork:not([hidden])) { + max-height: calc(var(--zen-media-viz-cover-size) + var(--zen-media-viz-text-room)) !important; + } + + .zen-media-info-container > .zen-media-info-vbox { + flex: 1 1 50% !important; + } + + .zen-media-viz-artwork { + flex: none; + width: var(--zen-media-viz-cover-size); + height: var(--zen-media-viz-cover-size); + margin-inline: calc((100% - var(--zen-media-viz-cover-size)) / 2); + margin-block-end: 8px; + border-radius: 8px; + box-shadow: 0 2px 8px rgb(0 0 0 / 0.25); + } +} + +#zen-media-controls-toolbar[zen-media-viz-style="background"] { + .zen-media-card:has(> .zen-media-viz-artwork:not([hidden])) { + min-height: 0; + + &:not([zen-removing], [zen-hiding], [zen-reindexing]) { + transition: + transform 0.35s var(--zen-media-viz-easing), + opacity 0.3s var(--zen-media-viz-easing), + filter 0.3s var(--zen-media-viz-easing), + padding 0.3s ease-out, + min-height 0.35s var(--zen-media-viz-easing) !important; + } + } + + &:hover .zen-media-card:has(> .zen-media-viz-artwork:not([hidden])) { + min-height: 100cqw; + + .zen-media-main-vbox > vbox:first-child { + flex: 1; + } + + .zen-media-progress-hbox { + flex-grow: 0 !important; + margin-top: auto; + } + } + + .zen-media-card > .zen-media-viz-artwork { + position: absolute; + inset: 0; + z-index: -1; + width: 100%; + height: 100%; + border-radius: inherit; + opacity: var(--zen-media-viz-background-opacity); + } } -.zen-media-viz-artwork[hidden] { - display: none; +#zen-media-controls-toolbar .zen-media-card toolbarbutton:not([disabled]) { + cursor: pointer !important; } diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 25052b1..30ac74b 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -24,3 +24,15 @@ Allow JavaScript from unofficial sources in Sine's settings, install the mod fro - [ ] A track without artwork shows no thumbnail and no broken image. - [ ] Disabling the mod in Sine removes the artwork without a restart; enabling it again brings it back, with only one thumbnail per card. - [ ] Opening a new window shows artwork there too. + +## Artwork styles + +Change **Artwork style** in the mod's settings in Sine while a track is playing. Each change should apply without reloading. + +- [ ] **Small thumbnail beside the title:** on hover, a 48px square sits left of the title. The start of the title isn't covered or faded, and the artist and close button still fit. +- [ ] **Large cover above the title:** on hover, the card grows smoothly to show a centered square cover with the title, artist and close button below it. Closing is just as smooth. +- [ ] **Artwork behind the whole card:** the artwork sits dimmed behind the resting card. On hover the card grows to a square and the whole cover shows, with the title at the top and the progress bar and controls together at the bottom, all readable. +- [ ] Switching back to the small thumbnail leaves one thumbnail per card and nothing behind the card. +- [ ] Narrowing the sidebar until the card is very thin hides the small thumbnail instead of squeezing the title. +- [ ] Try each style with a light and a dark Zen theme. +- [ ] The pointer turns into a hand over every button on the card (play/pause, previous, next, mute, close, picture-in-picture and the tab button on the left). diff --git a/docs/roadmap.md b/docs/roadmap.md index 672ac50..024a9f4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -2,15 +2,15 @@ The first release is built in milestones. Each milestone is one pull request, written test-first. -| # | Milestone | What it delivers | Status | -| --- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------ | -| 0 | Open-source & tooling shell | Test, lint, format and bundle tooling, CI, contributor docs and templates | Done | -| 1 | Spike & fixtures | A read-only console snippet that checks Zen's media card DOM and real metadata on the maintainer's Zen version, saved as test fixtures | Done | -| 2 | Artwork selection | `src/artwork.js`: parse `sizes`, filter to usable `https:`/`data:` sources, pick the best image | Done | -| 3 | Controller matching | `src/controllers.js`: safely read metadata from each tab's media controller and match it to a media card | Done | -| 4 | Card DOM | `src/card.js`: add, update and remove the thumbnail element in a media card | Done | -| 5 | Runtime wiring & Sine | Watch cards and metadata changes, clean teardown, `theme.json`, first run inside Zen | Done | -| 6 | Styling & polish | `chrome.css` for the thumbnail, narrow-sidebar and collapsed states, manual checklist | Next | -| 7 | Release v0.1.0 | Install guide, screenshot, version bump and tag | | +| # | Milestone | What it delivers | Status | +| --- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | +| 0 | Open-source & tooling shell | Test, lint, format and bundle tooling, CI, contributor docs and templates | Done | +| 1 | Spike & fixtures | A read-only console snippet that checks Zen's media card DOM and real metadata on the maintainer's Zen version, saved as test fixtures | Done | +| 2 | Artwork selection | `src/artwork.js`: parse `sizes`, filter to usable `https:`/`data:` sources, pick the best image | Done | +| 3 | Controller matching | `src/controllers.js`: safely read metadata from each tab's media controller and match it to a media card | Done | +| 4 | Card DOM | `src/card.js`: add, update and remove the thumbnail element in a media card | Done | +| 5 | Runtime wiring & Sine | Watch cards and metadata changes, clean teardown, `theme.json`, first run inside Zen | Done | +| 6 | Styling & settings | Artwork styles chosen in Sine's settings (small thumbnail, large cover, background), narrow-sidebar handling, pixel-density updates, manual checklist | Done | +| 7 | Release v0.1.0 | Install guide, screenshot, version bump and tag | Next | Ideas for after v0.1.0 are tracked as [issues](https://github.com/rodzy/Zen-Media-Viz/issues). diff --git a/preferences.json b/preferences.json new file mode 100644 index 0000000..1a65d62 --- /dev/null +++ b/preferences.json @@ -0,0 +1,14 @@ +[ + { + "type": "dropdown", + "property": "zen-media-viz.artwork-style", + "label": "Artwork style", + "defaultValue": "small", + "placeholder": false, + "options": [ + { "value": "small", "label": "Small thumbnail beside the title" }, + { "value": "large", "label": "Large cover above the title" }, + { "value": "background", "label": "Artwork behind the whole card" } + ] + } +] diff --git a/src/card.js b/src/card.js index f06ffd0..398d479 100644 --- a/src/card.js +++ b/src/card.js @@ -6,30 +6,33 @@ const INFO_CONTAINER_SELECTOR = ".zen-media-info-container"; const findArtwork = (card) => card.querySelector(`.${ARTWORK_CLASS}`); -function createArtwork(container) { - const image = container.ownerDocument.createElementNS(HTML_NS, "img"); +function createArtwork(document) { + const image = document.createElementNS(HTML_NS, "img"); image.className = ARTWORK_CLASS; image.alt = ""; image.setAttribute("referrerpolicy", "no-referrer"); image.addEventListener("load", () => { image.hidden = false; }); - container.prepend(image); return image; } +const artworkHost = (card, asBackground) => + asBackground ? card : card.querySelector(INFO_CONTAINER_SELECTOR); + export function removeArtwork(card) { findArtwork(card)?.remove(); } -export function showArtwork(card, src) { +export function showArtwork(card, src, { asBackground = false } = {}) { if (!isUsableSrc(src)) { removeArtwork(card); return; } - const container = card.querySelector(INFO_CONTAINER_SELECTOR); - if (!container) return; - const image = findArtwork(card) ?? createArtwork(container); + const host = artworkHost(card, asBackground); + if (!host) return; + const image = findArtwork(card) ?? createArtwork(card.ownerDocument); + if (host.firstElementChild !== image) host.prepend(image); if (image.getAttribute("src") === src) return; image.hidden = true; image.setAttribute("src", src); diff --git a/src/install.js b/src/install.js index 37d219a..0e928a8 100644 --- a/src/install.js +++ b/src/install.js @@ -12,7 +12,11 @@ function destroyPrevious(window) { export function install(window) { destroyPrevious(window); try { - const mediaViz = startMediaViz({ window, gBrowser: window.gBrowser }); + const mediaViz = startMediaViz({ + window, + gBrowser: window.gBrowser, + prefs: window.Services.prefs, + }); const handle = { destroy() { mediaViz.destroy(); diff --git a/src/runtime.js b/src/runtime.js index ca3fb27..9d8ffc5 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -2,11 +2,15 @@ import { pickArtwork } from "./artwork.js"; import { removeArtwork, showArtwork } from "./card.js"; import { matchCards, mediaSessions } from "./controllers.js"; import { logError } from "./log.js"; +import { readArtworkStyle, watchArtworkStyle } from "./settings.js"; const TOOLBAR_SELECTOR = "#zen-media-controls-toolbar"; const CARD_SELECTOR = ":scope > .zen-media-card"; const TRACK_LABEL_SELECTOR = ".zen-media-title, .zen-media-artist"; -const ARTWORK_CSS_PX = 36; +const STYLE_ATTRIBUTE = "zen-media-viz-style"; +const COVER_CSS_PX = 240; +const BACKGROUND_CSS_PX = 400; +const ARTWORK_CSS_PX = { small: 48, large: COVER_CSS_PX, background: BACKGROUND_CSS_PX }; const WATCHED_MUTATIONS = { childList: true, characterData: true, subtree: true }; const cardsIn = (toolbar) => [...toolbar.querySelectorAll(CARD_SELECTOR)]; @@ -16,11 +20,13 @@ function isTrackChange(toolbar, { target }) { return target === toolbar || Boolean(elementOf(target)?.closest(TRACK_LABEL_SELECTOR)); } -function renderArtwork(cards, sessions, { minPx }) { +function renderArtwork(cards, sessions, { style, pixelRatio }) { const matches = matchCards(cards, sessions); + const minPx = ARTWORK_CSS_PX[style] * pixelRatio; + const asBackground = style === "background"; for (const card of cards) { const artwork = matches.get(card)?.metadata.artwork ?? []; - showArtwork(card, pickArtwork(artwork, { minPx })); + showArtwork(card, pickArtwork(artwork, { minPx }), { asBackground }); } } @@ -42,30 +48,51 @@ function observeTrackChanges({ MutationObserver }, toolbar, onChange) { return observer; } -export function startMediaViz({ window, gBrowser }) { - const toolbar = window.document.querySelector(TOOLBAR_SELECTOR); - if (!toolbar) throw new Error(`${TOOLBAR_SELECTOR} not found`); - const teardown = new AbortController(); +function watchPixelRatio(window, onChange, { signal }) { + const query = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`); + const rearm = () => { + onChange(); + watchPixelRatio(window, onChange, { signal }); + }; + query.addEventListener("change", rearm, { once: true, signal }); +} +function artworkRefresher({ window, gBrowser, toolbar }, teardown) { const refresh = () => { try { const sessions = mediaSessions(gBrowser); sessions.forEach(watchController); renderArtwork(cardsIn(toolbar), sessions, { - minPx: ARTWORK_CSS_PX * window.devicePixelRatio, + style: toolbar.getAttribute(STYLE_ATTRIBUTE), + pixelRatio: window.devicePixelRatio, }); } catch (error) { logError(error); } }; const watchController = controllerWatcher(refresh, teardown); + return refresh; +} + +export function startMediaViz({ window, gBrowser, prefs }) { + const toolbar = window.document.querySelector(TOOLBAR_SELECTOR); + if (!toolbar) throw new Error(`${TOOLBAR_SELECTOR} not found`); + const teardown = new AbortController(); + const refresh = artworkRefresher({ window, gBrowser, toolbar }, teardown); + const applyStyle = (style) => { + toolbar.setAttribute(STYLE_ATTRIBUTE, style); + refresh(); + }; + watchArtworkStyle(prefs, applyStyle, teardown); + watchPixelRatio(window, refresh, teardown); const observer = observeTrackChanges(window, toolbar, refresh); - refresh(); + applyStyle(readArtworkStyle(prefs)); return { destroy() { observer.disconnect(); teardown.abort(); + toolbar.removeAttribute(STYLE_ATTRIBUTE); cardsIn(toolbar).forEach(removeArtwork); }, }; diff --git a/src/settings.js b/src/settings.js new file mode 100644 index 0000000..6eabfaa --- /dev/null +++ b/src/settings.js @@ -0,0 +1,24 @@ +export const ARTWORK_STYLE_PREF = "zen-media-viz.artwork-style"; +export const ARTWORK_STYLES = ["small", "large", "background"]; +const DEFAULT_STYLE = "small"; + +function readStoredStyle(prefs) { + try { + return prefs.getStringPref(ARTWORK_STYLE_PREF, DEFAULT_STYLE); + } catch { + return DEFAULT_STYLE; + } +} + +export function readArtworkStyle(prefs) { + const style = readStoredStyle(prefs); + return ARTWORK_STYLES.includes(style) ? style : DEFAULT_STYLE; +} + +export function watchArtworkStyle(prefs, onChange, { signal }) { + const observer = { observe: () => onChange(readArtworkStyle(prefs)) }; + prefs.addObserver(ARTWORK_STYLE_PREF, observer); + signal.addEventListener("abort", () => prefs.removeObserver(ARTWORK_STYLE_PREF, observer), { + once: true, + }); +} diff --git a/test/card.test.js b/test/card.test.js index 024dcdf..ae2de6e 100644 --- a/test/card.test.js +++ b/test/card.test.js @@ -128,6 +128,40 @@ describe("showArtwork", () => { }); }); +describe("showArtwork as a background", () => { + it("adds the image as the first child of the card", () => { + const card = recordedCard(); + + showArtwork(card, COVER, { asBackground: true }); + + expect(card.firstElementChild).toBe(artworkOf(card)[0]); + }); + + it("moves the image between the card and its info container", () => { + const card = recordedCard(); + showArtwork(card, COVER); + const [image] = artworkOf(card); + + showArtwork(card, COVER, { asBackground: true }); + const asBackground = image.parentElement; + showArtwork(card, COVER); + + expect(asBackground).toBe(card); + expect(image.parentElement.classList.contains("zen-media-info-container")).toBe(true); + expect([...artworkOf(card)]).toEqual([image]); + }); + + it("keeps a loaded image visible when it only moves", () => { + const card = recordedCard(); + showArtwork(card, COVER); + const image = loaded(artworkOf(card)[0]); + + showArtwork(card, COVER, { asBackground: true }); + + expect(image.hidden).toBe(false); + }); +}); + describe("removeArtwork", () => { it("removes the image from the card", () => { const card = recordedCard(); diff --git a/test/install.test.js b/test/install.test.js index 44fc16a..e2443c7 100644 --- a/test/install.test.js +++ b/test/install.test.js @@ -18,7 +18,16 @@ function mountToolbar() { const artworkCount = () => document.querySelectorAll(".zen-media-viz-artwork").length; function fakeWindow(overrides = {}) { - return Object.assign(Object.create(window), { gBrowser: { tabs: [playingTab()] } }, overrides); + const prefs = { + getStringPref: (name, fallback) => fallback, + addObserver: () => {}, + removeObserver: () => {}, + }; + return Object.assign( + Object.create(window), + { gBrowser: { tabs: [playingTab()] }, Services: { prefs } }, + overrides, + ); } afterEach(() => { diff --git a/test/runtime.test.js b/test/runtime.test.js index a6049d2..1bd971f 100644 --- a/test/runtime.test.js +++ b/test/runtime.test.js @@ -1,6 +1,7 @@ // @vitest-environment happy-dom import { afterEach, describe, expect, it, vi } from "vitest"; import { startMediaViz } from "../src/runtime.js"; +import { ARTWORK_STYLE_PREF } from "../src/settings.js"; import report from "./fixtures/zen-1.24.3b.json" with { type: "json" }; const [recorded] = report.controllers.active; @@ -54,8 +55,35 @@ function addCard(toolbar, title, artist) { let running = null; -function start(controllers) { - running = startMediaViz({ window, gBrowser: { tabs: controllers.map(tab) } }); +function fakePrefs(style) { + let observer = null; + return { + getStringPref: (name, fallback) => style ?? fallback, + addObserver: (name, added) => { + observer = added; + }, + removeObserver: () => { + observer = null; + }, + setStyle(next) { + style = next; + observer?.observe(null, "nsPref:changed", ARTWORK_STYLE_PREF); + }, + }; +} + +function fakeMediaQueries() { + const queries = []; + vi.spyOn(window, "matchMedia").mockImplementation((media) => { + const query = Object.assign(new EventTarget(), { media, matches: true }); + queries.push(query); + return query; + }); + return queries; +} + +function start(controllers, prefs = fakePrefs()) { + running = startMediaViz({ window, gBrowser: { tabs: controllers.map(tab) }, prefs }); return running; } @@ -87,6 +115,59 @@ describe("startMediaViz", () => { expect(artworkSrc(cardOf(toolbar))).toContain(size); }); + it("asks for a sharper image again when the window moves to a denser screen", () => { + const toolbar = mountToolbar(); + const queries = fakeMediaQueries(); + const ratio = vi.spyOn(window, "devicePixelRatio", "get").mockReturnValue(1); + start([new FakeController(recorded.metadata)]); + + ratio.mockReturnValue(4); + queries.at(-1).dispatchEvent(new Event("change")); + + expect(artworkSrc(cardOf(toolbar))).toContain("=w226-h226"); + expect(queries.at(-1).media).toBe("(resolution: 4dppx)"); + }); + + it("marks the toolbar with the chosen artwork style", () => { + const toolbar = mountToolbar(); + + start([], fakePrefs("large")); + + expect(toolbar.getAttribute("zen-media-viz-style")).toBe("large"); + }); + + it("puts the artwork behind the whole card in the background style", () => { + const toolbar = mountToolbar(); + + start([new FakeController(recorded.metadata)], fakePrefs("background")); + + expect(cardOf(toolbar).firstElementChild.classList.contains("zen-media-viz-artwork")).toBe( + true, + ); + }); + + it.each(["large", "background"])("picks a cover-sized image in the %s style", (style) => { + const toolbar = mountToolbar(); + vi.spyOn(window, "devicePixelRatio", "get").mockReturnValue(1); + + start([new FakeController(recorded.metadata)], fakePrefs(style)); + + expect(artworkSrc(cardOf(toolbar))).toContain("=w544-h544"); + }); + + it("restyles the cards when the artwork style setting changes", () => { + const toolbar = mountToolbar(); + const prefs = fakePrefs(); + start([new FakeController(recorded.metadata)], prefs); + + prefs.setStyle("background"); + + expect(toolbar.getAttribute("zen-media-viz-style")).toBe("background"); + expect(cardOf(toolbar).firstElementChild.classList.contains("zen-media-viz-artwork")).toBe( + true, + ); + }); + it("updates the artwork when the tab's metadata changes", () => { const toolbar = mountToolbar(); const controller = new FakeController(track("Flames of Fate", "DJ Noriken")); @@ -170,6 +251,36 @@ describe("startMediaViz", () => { }); describe("destroy", () => { + it("removes the style mark from the toolbar", () => { + const toolbar = mountToolbar(); + + start([], fakePrefs("large")).destroy(); + + expect(toolbar.hasAttribute("zen-media-viz-style")).toBe(false); + }); + + it("stops reacting to the artwork style setting", () => { + const toolbar = mountToolbar(); + const prefs = fakePrefs(); + start([], prefs).destroy(); + + prefs.setStyle("large"); + + expect(toolbar.hasAttribute("zen-media-viz-style")).toBe(false); + }); + + it("stops reacting to pixel density changes", () => { + mountToolbar(); + const queries = fakeMediaQueries(); + const controller = new FakeController(recorded.metadata); + start([controller]).destroy(); + const getMetadata = vi.spyOn(controller, "getMetadata"); + + queries.at(-1).dispatchEvent(new Event("change")); + + expect(getMetadata).not.toHaveBeenCalled(); + }); + it("removes the artwork from every card", () => { const toolbar = mountToolbar(); const viz = start([new FakeController(track("Flames of Fate", "DJ Noriken"))]); diff --git a/test/settings.test.js b/test/settings.test.js new file mode 100644 index 0000000..4c9d41d --- /dev/null +++ b/test/settings.test.js @@ -0,0 +1,93 @@ +import { describe, expect, it, vi } from "vitest"; +import { + ARTWORK_STYLES, + ARTWORK_STYLE_PREF, + readArtworkStyle, + watchArtworkStyle, +} from "../src/settings.js"; +import preferences from "../preferences.json" with { type: "json" }; + +function fakePrefs(values = {}) { + const observers = new Map(); + return { + getStringPref: (name, fallback) => values[name] ?? fallback, + addObserver: (name, observer) => observers.set(name, observer), + removeObserver: (name, observer) => { + if (observers.get(name) === observer) observers.delete(name); + }, + set(name, value) { + values[name] = value; + observers.get(name)?.observe(null, "nsPref:changed", name); + }, + observerCount: () => observers.size, + }; +} + +describe("readArtworkStyle", () => { + it("defaults to the small thumbnail", () => { + expect(readArtworkStyle(fakePrefs())).toBe("small"); + }); + + it.each(ARTWORK_STYLES)("reads the %s style", (style) => { + expect(readArtworkStyle(fakePrefs({ [ARTWORK_STYLE_PREF]: style }))).toBe(style); + }); + + it.each(["huge", "background-blur"])( + "falls back to the small thumbnail for the unknown style %s", + (style) => { + expect(readArtworkStyle(fakePrefs({ [ARTWORK_STYLE_PREF]: style }))).toBe("small"); + }, + ); +}); + +describe("readArtworkStyle with a pref of another type", () => { + it("falls back to the small thumbnail", () => { + const prefs = { + getStringPref: () => { + throw Object.assign(new Error(""), { name: "NS_ERROR_UNEXPECTED" }); + }, + }; + + expect(readArtworkStyle(prefs)).toBe("small"); + }); +}); + +describe("watchArtworkStyle", () => { + it("reports the new style when the pref changes", () => { + const prefs = fakePrefs(); + const onChange = vi.fn(); + watchArtworkStyle(prefs, onChange, new AbortController()); + + prefs.set(ARTWORK_STYLE_PREF, "large"); + + expect(onChange).toHaveBeenCalledWith("large"); + }); + + it("stops watching when aborted", () => { + const prefs = fakePrefs(); + const onChange = vi.fn(); + const teardown = new AbortController(); + watchArtworkStyle(prefs, onChange, teardown); + + teardown.abort(); + prefs.set(ARTWORK_STYLE_PREF, "large"); + + expect(onChange).not.toHaveBeenCalled(); + expect(prefs.observerCount()).toBe(0); + }); +}); + +describe("preferences.json", () => { + const [stylePref] = preferences; + + it("offers every artwork style in a dropdown", () => { + expect(stylePref.type).toBe("dropdown"); + expect(stylePref.property).toBe(ARTWORK_STYLE_PREF); + expect(stylePref.options.map(({ value }) => value)).toEqual(ARTWORK_STYLES); + }); + + it("defaults to the small thumbnail without an empty choice", () => { + expect(stylePref.defaultValue).toBe("small"); + expect(stylePref.placeholder).toBe(false); + }); +}); diff --git a/test/theme.test.js b/test/theme.test.js index cc8a159..fc80054 100644 --- a/test/theme.test.js +++ b/test/theme.test.js @@ -12,7 +12,7 @@ describe("theme.json", () => { }); it("points at files that exist in the repository", () => { - const paths = [...Object.keys(theme.scripts), theme.style.chrome]; + const paths = [...Object.keys(theme.scripts), theme.style.chrome, theme.preferences]; expect(paths.filter((path) => !existsSync(repoFile(path)))).toEqual([]); }); diff --git a/theme.json b/theme.json index aeaf81b..0d51385 100644 --- a/theme.json +++ b/theme.json @@ -8,6 +8,7 @@ "author": "rodzy", "tags": ["media", "sidebar", "artwork"], "style": { "chrome": "chrome.css" }, + "preferences": "preferences.json", "scripts": { "zen-media-viz.uc.js": { "include": ["chrome://browser/content/browser.xhtml"] diff --git a/zen-media-viz.uc.js b/zen-media-viz.uc.js index 55e6226..6053b42 100644 --- a/zen-media-viz.uc.js +++ b/zen-media-viz.uc.js @@ -52,28 +52,29 @@ var ARTWORK_CLASS = "zen-media-viz-artwork"; var INFO_CONTAINER_SELECTOR = ".zen-media-info-container"; var findArtwork = (card) => card.querySelector(`.${ARTWORK_CLASS}`); - function createArtwork(container) { - const image = container.ownerDocument.createElementNS(HTML_NS, "img"); + function createArtwork(document) { + const image = document.createElementNS(HTML_NS, "img"); image.className = ARTWORK_CLASS; image.alt = ""; image.setAttribute("referrerpolicy", "no-referrer"); image.addEventListener("load", () => { image.hidden = false; }); - container.prepend(image); return image; } + var artworkHost = (card, asBackground) => asBackground ? card : card.querySelector(INFO_CONTAINER_SELECTOR); function removeArtwork(card) { findArtwork(card)?.remove(); } - function showArtwork(card, src) { + function showArtwork(card, src, { asBackground = false } = {}) { if (!isUsableSrc(src)) { removeArtwork(card); return; } - const container = card.querySelector(INFO_CONTAINER_SELECTOR); - if (!container) return; - const image = findArtwork(card) ?? createArtwork(container); + const host = artworkHost(card, asBackground); + if (!host) return; + const image = findArtwork(card) ?? createArtwork(card.ownerDocument); + if (host.firstElementChild !== image) host.prepend(image); if (image.getAttribute("src") === src) return; image.hidden = true; image.setAttribute("src", src); @@ -124,22 +125,50 @@ return matches; } + // src/settings.js + var ARTWORK_STYLE_PREF = "zen-media-viz.artwork-style"; + var ARTWORK_STYLES = ["small", "large", "background"]; + var DEFAULT_STYLE = "small"; + function readStoredStyle(prefs) { + try { + return prefs.getStringPref(ARTWORK_STYLE_PREF, DEFAULT_STYLE); + } catch { + return DEFAULT_STYLE; + } + } + function readArtworkStyle(prefs) { + const style = readStoredStyle(prefs); + return ARTWORK_STYLES.includes(style) ? style : DEFAULT_STYLE; + } + function watchArtworkStyle(prefs, onChange, { signal }) { + const observer = { observe: () => onChange(readArtworkStyle(prefs)) }; + prefs.addObserver(ARTWORK_STYLE_PREF, observer); + signal.addEventListener("abort", () => prefs.removeObserver(ARTWORK_STYLE_PREF, observer), { + once: true + }); + } + // src/runtime.js var TOOLBAR_SELECTOR = "#zen-media-controls-toolbar"; var CARD_SELECTOR = ":scope > .zen-media-card"; var TRACK_LABEL_SELECTOR = ".zen-media-title, .zen-media-artist"; - var ARTWORK_CSS_PX = 36; + var STYLE_ATTRIBUTE = "zen-media-viz-style"; + var COVER_CSS_PX = 240; + var BACKGROUND_CSS_PX = 400; + var ARTWORK_CSS_PX = { small: 48, large: COVER_CSS_PX, background: BACKGROUND_CSS_PX }; var WATCHED_MUTATIONS = { childList: true, characterData: true, subtree: true }; var cardsIn = (toolbar) => [...toolbar.querySelectorAll(CARD_SELECTOR)]; var elementOf = (node) => node.nodeType === node.ELEMENT_NODE ? node : node.parentElement; function isTrackChange(toolbar, { target }) { return target === toolbar || Boolean(elementOf(target)?.closest(TRACK_LABEL_SELECTOR)); } - function renderArtwork(cards, sessions, { minPx }) { + function renderArtwork(cards, sessions, { style, pixelRatio }) { const matches = matchCards(cards, sessions); + const minPx = ARTWORK_CSS_PX[style] * pixelRatio; + const asBackground = style === "background"; for (const card of cards) { const artwork = matches.get(card)?.metadata.artwork ?? []; - showArtwork(card, pickArtwork(artwork, { minPx })); + showArtwork(card, pickArtwork(artwork, { minPx }), { asBackground }); } } function controllerWatcher(onChange, { signal }) { @@ -158,28 +187,48 @@ observer.observe(toolbar, WATCHED_MUTATIONS); return observer; } - function startMediaViz({ window: window2, gBrowser }) { - const toolbar = window2.document.querySelector(TOOLBAR_SELECTOR); - if (!toolbar) throw new Error(`${TOOLBAR_SELECTOR} not found`); - const teardown = new AbortController(); + function watchPixelRatio(window2, onChange, { signal }) { + const query = window2.matchMedia(`(resolution: ${window2.devicePixelRatio}dppx)`); + const rearm = () => { + onChange(); + watchPixelRatio(window2, onChange, { signal }); + }; + query.addEventListener("change", rearm, { once: true, signal }); + } + function artworkRefresher({ window: window2, gBrowser, toolbar }, teardown) { const refresh = () => { try { const sessions = mediaSessions(gBrowser); sessions.forEach(watchController); renderArtwork(cardsIn(toolbar), sessions, { - minPx: ARTWORK_CSS_PX * window2.devicePixelRatio + style: toolbar.getAttribute(STYLE_ATTRIBUTE), + pixelRatio: window2.devicePixelRatio }); } catch (error) { logError(error); } }; const watchController = controllerWatcher(refresh, teardown); + return refresh; + } + function startMediaViz({ window: window2, gBrowser, prefs }) { + const toolbar = window2.document.querySelector(TOOLBAR_SELECTOR); + if (!toolbar) throw new Error(`${TOOLBAR_SELECTOR} not found`); + const teardown = new AbortController(); + const refresh = artworkRefresher({ window: window2, gBrowser, toolbar }, teardown); + const applyStyle = (style) => { + toolbar.setAttribute(STYLE_ATTRIBUTE, style); + refresh(); + }; + watchArtworkStyle(prefs, applyStyle, teardown); + watchPixelRatio(window2, refresh, teardown); const observer = observeTrackChanges(window2, toolbar, refresh); - refresh(); + applyStyle(readArtworkStyle(prefs)); return { destroy() { observer.disconnect(); teardown.abort(); + toolbar.removeAttribute(STYLE_ATTRIBUTE); cardsIn(toolbar).forEach(removeArtwork); } }; @@ -196,7 +245,11 @@ function install(window2) { destroyPrevious(window2); try { - const mediaViz = startMediaViz({ window: window2, gBrowser: window2.gBrowser }); + const mediaViz = startMediaViz({ + window: window2, + gBrowser: window2.gBrowser, + prefs: window2.Services.prefs + }); const handle = { destroy() { mediaViz.destroy();