diff --git a/CHANGELOG.md b/CHANGELOG.md index f5cf6ea..0856200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - Artwork selection (`src/artwork.js`): parses Media Session `sizes`, keeps only `https:` and image `data:` sources and picks the smallest image whose shorter side is big enough, falling back to the largest. - Controller matching (`src/controllers.js`): reads metadata from each tab's media controller, treating an inactive controller (`NS_ERROR_NOT_AVAILABLE`) as no session, and matches each media card to a session by its title and artist, giving each session to at most one card. - 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. - 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 b284bd9..19a292b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,7 @@ 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`, `chrome.css`) arrives in Milestone 5; until then the mod can't be installed. Sine reads `theme.json` at the repo root. Scripts listed under `scripts` with `include: ["chrome://browser/content/browser.xhtml"]` run once per browser window after its `load` event; `chrome.css` is applied as a user stylesheet. Sine can re-run the script into an already-open window when the mod is enabled, so the entry point must tear down any previous instance (`window.ZenMediaViz.destroy()`). +- 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. - **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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3360870..cdc6935 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ npm test | ----------------------- | ------------------------------------------------------------------- | | `npm test` | Run the test suite once | | `npm run test:watch` | Re-run tests as you edit | -| `npx vitest run ` | Run one test file, e.g. `npx vitest run test/smoke.test.js` | +| `npx vitest run ` | Run one test file, e.g. `npx vitest run test/artwork.test.js` | | `npx vitest run -t "x"` | Run only tests whose name matches `x` | | `npm run lint` | ESLint | | `npm run format` | Format everything with Prettier (`format:check` only reports) | @@ -60,7 +60,7 @@ Some things can't be tested under Node: real XUL layout, the browser's content-s ## Testing in Zen -The mod becomes installable in Milestone 5 of the [roadmap](docs/roadmap.md), when `theme.json` lands. From then on: +To try your changes in a real browser: 1. Install [Sine](https://github.com/CosmoCreeper/Sine) in Zen. 2. In Sine's settings, turn on installing JavaScript from unofficial sources. diff --git a/chrome.css b/chrome.css new file mode 100644 index 0000000..8889706 --- /dev/null +++ b/chrome.css @@ -0,0 +1,12 @@ +.zen-media-viz-artwork { + flex: none; + width: 36px; + height: 36px; + margin-inline-end: 8px; + border-radius: 4px; + object-fit: cover; +} + +.zen-media-viz-artwork[hidden] { + display: none; +} diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 565435f..25052b1 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -13,3 +13,14 @@ Items are added as features land. ## Spike - [ ] Pasting the `npm run spike` snippet into the Browser Console logs `[zen-media-viz] Spike report copied to the clipboard.` and the clipboard holds the JSON report. + +## Artwork + +Allow JavaScript from unofficial sources in Sine's settings, install the mod from this repository, and play a track with artwork (for example on [YouTube Music](https://music.youtube.com)) in one tab while another tab is selected. + +- [ ] The media card in the sidebar shows the track's artwork next to the title, and no `[zen-media-viz]` errors appear in the Browser Console. +- [ ] Skipping to the next track replaces the artwork with the new track's. +- [ ] With two tabs playing different tracks, each card shows its own track's artwork. +- [ ] 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. diff --git a/docs/roadmap.md b/docs/roadmap.md index d555f6c..672ac50 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,8 +9,8 @@ The first release is built in milestones. Each milestone is one pull request, wr | 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 | Next | -| 6 | Styling & polish | `chrome.css` for the thumbnail, narrow-sidebar and collapsed states, manual checklist | | +| 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 | | Ideas for after v0.1.0 are tracked as [issues](https://github.com/rodzy/Zen-Media-Viz/issues). diff --git a/src/controllers.js b/src/controllers.js index c979534..4c23b48 100644 --- a/src/controllers.js +++ b/src/controllers.js @@ -1,3 +1,5 @@ +import { logError } from "./log.js"; + const NOT_AVAILABLE = "NS_ERROR_NOT_AVAILABLE"; const TITLE_SELECTOR = ".zen-media-title"; const ARTIST_SELECTOR = ".zen-media-artist"; @@ -14,8 +16,13 @@ export function readMetadata(controller) { function sessionOf({ linkedBrowser: browser }) { const controller = browser?.browsingContext?.mediaController; if (!controller) return null; - const metadata = readMetadata(controller); - return metadata && { browser, metadata }; + try { + const metadata = readMetadata(controller); + return metadata && { browser, metadata }; + } catch (error) { + logError(error); + return null; + } } export function mediaSessions({ tabs }) { diff --git a/src/index.js b/src/index.js index 98894b8..419a13a 100644 --- a/src/index.js +++ b/src/index.js @@ -1 +1,3 @@ -export const MOD_NAME = "zen-media-viz"; +import { install } from "./install.js"; + +install(window); diff --git a/src/install.js b/src/install.js new file mode 100644 index 0000000..37d219a --- /dev/null +++ b/src/install.js @@ -0,0 +1,27 @@ +import { logError } from "./log.js"; +import { startMediaViz } from "./runtime.js"; + +function destroyPrevious(window) { + try { + window.ZenMediaViz?.destroy(); + } catch (error) { + logError(error); + } +} + +export function install(window) { + destroyPrevious(window); + try { + const mediaViz = startMediaViz({ window, gBrowser: window.gBrowser }); + const handle = { + destroy() { + mediaViz.destroy(); + if (window.ZenMediaViz === handle) delete window.ZenMediaViz; + }, + }; + window.ZenMediaViz = handle; + window.addUnloadListener?.(handle.destroy); + } catch (error) { + logError(error); + } +} diff --git a/src/log.js b/src/log.js new file mode 100644 index 0000000..17b5f37 --- /dev/null +++ b/src/log.js @@ -0,0 +1,5 @@ +const LOG_PREFIX = "[zen-media-viz]"; + +export function logError(error) { + console.error(LOG_PREFIX, error); +} diff --git a/src/runtime.js b/src/runtime.js new file mode 100644 index 0000000..ca3fb27 --- /dev/null +++ b/src/runtime.js @@ -0,0 +1,72 @@ +import { pickArtwork } from "./artwork.js"; +import { removeArtwork, showArtwork } from "./card.js"; +import { matchCards, mediaSessions } from "./controllers.js"; +import { logError } from "./log.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 WATCHED_MUTATIONS = { childList: true, characterData: true, subtree: true }; + +const cardsIn = (toolbar) => [...toolbar.querySelectorAll(CARD_SELECTOR)]; +const 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 }) { + const matches = matchCards(cards, sessions); + for (const card of cards) { + const artwork = matches.get(card)?.metadata.artwork ?? []; + showArtwork(card, pickArtwork(artwork, { minPx })); + } +} + +function controllerWatcher(onChange, { signal }) { + const watched = new WeakSet(); + return ({ browser }) => { + const controller = browser.browsingContext.mediaController; + if (watched.has(controller)) return; + watched.add(controller); + controller.addEventListener("metadatachange", onChange, { signal }); + }; +} + +function observeTrackChanges({ MutationObserver }, toolbar, onChange) { + const observer = new MutationObserver((records) => { + if (records.some((record) => isTrackChange(toolbar, record))) onChange(); + }); + observer.observe(toolbar, WATCHED_MUTATIONS); + 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(); + + const refresh = () => { + try { + const sessions = mediaSessions(gBrowser); + sessions.forEach(watchController); + renderArtwork(cardsIn(toolbar), sessions, { + minPx: ARTWORK_CSS_PX * window.devicePixelRatio, + }); + } catch (error) { + logError(error); + } + }; + const watchController = controllerWatcher(refresh, teardown); + const observer = observeTrackChanges(window, toolbar, refresh); + refresh(); + + return { + destroy() { + observer.disconnect(); + teardown.abort(); + cardsIn(toolbar).forEach(removeArtwork); + }, + }; +} diff --git a/test/controllers.test.js b/test/controllers.test.js index 4a0fe4b..7c0fdfd 100644 --- a/test/controllers.test.js +++ b/test/controllers.test.js @@ -1,5 +1,5 @@ // @vitest-environment happy-dom -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { matchCards, mediaSessions, readCardTrack, readMetadata } from "../src/controllers.js"; import report from "./fixtures/zen-1.24.3b.json" with { type: "json" }; @@ -82,6 +82,23 @@ describe("mediaSessions", () => { expect(mediaSessions({ tabs }).map(({ metadata }) => metadata.title)).toEqual(["Song"]); }); + it("logs and skips a tab whose controller fails, keeping the other tabs", () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const failure = new TypeError("boom"); + const broken = { + getMetadata: () => { + throw failure; + }, + }; + const tabs = [tab(broken), tab(controller(track("Song", "Band")))]; + + const titles = mediaSessions({ tabs }).map(({ metadata }) => metadata.title); + + expect(titles).toEqual(["Song"]); + expect(error).toHaveBeenCalledWith("[zen-media-viz]", failure); + error.mockRestore(); + }); + it("skips tabs without a browser, browsing context or controller", () => { const tabs = [{}, { linkedBrowser: {} }, { linkedBrowser: { browsingContext: {} } }]; diff --git a/test/install.test.js b/test/install.test.js new file mode 100644 index 0000000..44fc16a --- /dev/null +++ b/test/install.test.js @@ -0,0 +1,118 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from "vitest"; +import { install } from "../src/install.js"; +import report from "./fixtures/zen-1.24.3b.json" with { type: "json" }; + +const [recorded] = report.controllers.active; + +function playingTab() { + const controller = Object.assign(new EventTarget(), { getMetadata: () => recorded.metadata }); + return { linkedBrowser: { browsingContext: { mediaController: controller } } }; +} + +function mountToolbar() { + const parsed = new DOMParser().parseFromString(report.toolbar.html, "application/xml"); + document.body.replaceChildren(document.importNode(parsed.documentElement, true)); +} + +const artworkCount = () => document.querySelectorAll(".zen-media-viz-artwork").length; + +function fakeWindow(overrides = {}) { + return Object.assign(Object.create(window), { gBrowser: { tabs: [playingTab()] } }, overrides); +} + +afterEach(() => { + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +describe("install", () => { + it("starts the mod and exposes it as ZenMediaViz", () => { + mountToolbar(); + const target = fakeWindow(); + + install(target); + + expect(artworkCount()).toBe(1); + expect(typeof target.ZenMediaViz.destroy).toBe("function"); + }); + + it("tears down a previous instance before starting again", () => { + mountToolbar(); + const target = fakeWindow(); + install(target); + const previous = target.ZenMediaViz; + const destroy = vi.spyOn(previous, "destroy"); + + install(target); + + expect(destroy).toHaveBeenCalledOnce(); + expect(target.ZenMediaViz).not.toBe(previous); + expect(artworkCount()).toBe(1); + }); + + it("starts again and logs when the previous instance fails to tear down", () => { + mountToolbar(); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const failure = new Error("stale"); + const target = fakeWindow({ + ZenMediaViz: { + destroy: () => { + throw failure; + }, + }, + }); + + install(target); + + expect(error).toHaveBeenCalledWith("[zen-media-viz]", failure); + expect(artworkCount()).toBe(1); + }); + + it("removes the artwork and the global on destroy", () => { + mountToolbar(); + const target = fakeWindow(); + install(target); + + target.ZenMediaViz.destroy(); + + expect(artworkCount()).toBe(0); + expect(target.ZenMediaViz).toBeUndefined(); + }); + + it("leaves a newer instance in place when an old one is destroyed", () => { + mountToolbar(); + const target = fakeWindow(); + install(target); + const stale = target.ZenMediaViz; + install(target); + const current = target.ZenMediaViz; + + stale.destroy(); + + expect(target.ZenMediaViz).toBe(current); + }); + + it("registers its teardown with Sine's unload listener", () => { + mountToolbar(); + const addUnloadListener = vi.fn(); + const target = fakeWindow({ addUnloadListener }); + install(target); + const [unload] = addUnloadListener.mock.calls[0]; + + unload(); + + expect(artworkCount()).toBe(0); + expect(target.ZenMediaViz).toBeUndefined(); + }); + + it("logs and leaves the window alone when the media toolbar is missing", () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const target = fakeWindow(); + + install(target); + + expect(error).toHaveBeenCalledWith("[zen-media-viz]", expect.any(Error)); + expect(target.ZenMediaViz).toBeUndefined(); + }); +}); diff --git a/test/runtime.test.js b/test/runtime.test.js new file mode 100644 index 0000000..a6049d2 --- /dev/null +++ b/test/runtime.test.js @@ -0,0 +1,201 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from "vitest"; +import { startMediaViz } from "../src/runtime.js"; +import report from "./fixtures/zen-1.24.3b.json" with { type: "json" }; + +const [recorded] = report.controllers.active; +const COVER = "https://a.test/cover.jpg"; +const OTHER_COVER = "https://a.test/other.jpg"; + +class FakeController extends EventTarget { + constructor(metadata) { + super(); + this.metadata = metadata; + } + + getMetadata() { + return this.metadata; + } + + change(metadata) { + this.metadata = metadata; + this.dispatchEvent(new Event("metadatachange")); + } +} + +function track(title, artist, src = COVER) { + return { title, artist, album: "", artwork: [{ src, sizes: "96x96", type: "image/jpeg" }] }; +} + +const tab = (controller) => ({ + linkedBrowser: { browsingContext: { mediaController: controller } }, +}); + +function mountToolbar() { + const parsed = new DOMParser().parseFromString(report.toolbar.html, "application/xml"); + const toolbar = document.importNode(parsed.documentElement, true); + document.body.replaceChildren(toolbar); + return toolbar; +} + +const cardOf = (toolbar) => toolbar.querySelector(":scope > .zen-media-card"); +const artworkSrc = (card) => + card.querySelector(".zen-media-viz-artwork")?.getAttribute("src") ?? null; +const settle = () => new Promise((resolve) => setTimeout(resolve)); + +function addCard(toolbar, title, artist) { + const card = cardOf(toolbar).cloneNode(true); + card.querySelector(".zen-media-viz-artwork")?.remove(); + card.querySelector(".zen-media-title").textContent = title; + card.querySelector(".zen-media-artist").textContent = artist; + toolbar.append(card); + return card; +} + +let running = null; + +function start(controllers) { + running = startMediaViz({ window, gBrowser: { tabs: controllers.map(tab) } }); + return running; +} + +afterEach(() => { + running?.destroy(); + running = null; + vi.restoreAllMocks(); +}); + +describe("startMediaViz", () => { + it("shows artwork on the card of the playing tab", () => { + const toolbar = mountToolbar(); + + start([new FakeController(recorded.metadata)]); + + expect(artworkSrc(cardOf(toolbar))).toMatch(/^https:\/\/yt3\.googleusercontent\.com\//); + }); + + it.each([ + [1, "=w60-h60"], + [2, "=w120-h120"], + [4, "=w226-h226"], + ])("picks an image big enough at a pixel density of %d", (ratio, size) => { + const toolbar = mountToolbar(); + vi.spyOn(window, "devicePixelRatio", "get").mockReturnValue(ratio); + + start([new FakeController(recorded.metadata)]); + + expect(artworkSrc(cardOf(toolbar))).toContain(size); + }); + + it("updates the artwork when the tab's metadata changes", () => { + const toolbar = mountToolbar(); + const controller = new FakeController(track("Flames of Fate", "DJ Noriken")); + start([controller]); + + controller.change(track("Flames of Fate", "DJ Noriken", OTHER_COVER)); + + expect(artworkSrc(cardOf(toolbar))).toBe(OTHER_COVER); + }); + + it("follows the card when it switches to another track", async () => { + const toolbar = mountToolbar(); + const controller = new FakeController(track("Flames of Fate", "DJ Noriken")); + start([controller]); + + controller.metadata = track("Next Song", "Band", OTHER_COVER); + cardOf(toolbar).querySelector(".zen-media-title").textContent = "Next Song"; + cardOf(toolbar).querySelector(".zen-media-artist").textContent = "Band"; + await settle(); + + expect(artworkSrc(cardOf(toolbar))).toBe(OTHER_COVER); + }); + + it("adds artwork to a card that appears later", async () => { + const toolbar = mountToolbar(); + start([ + new FakeController(track("Flames of Fate", "DJ Noriken")), + new FakeController(track("Other Song", "Other Band", OTHER_COVER)), + ]); + + const card = addCard(toolbar, "Other Song", "Other Band"); + await settle(); + + expect(artworkSrc(card)).toBe(OTHER_COVER); + }); + + it("removes the artwork when the card no longer matches a playing tab", async () => { + const toolbar = mountToolbar(); + start([new FakeController(track("Flames of Fate", "DJ Noriken"))]); + + cardOf(toolbar).querySelector(".zen-media-title").textContent = "Unknown"; + await settle(); + + expect(artworkSrc(cardOf(toolbar))).toBeNull(); + }); + + it("does not reread metadata when only the playback time changes", async () => { + const toolbar = mountToolbar(); + const controller = new FakeController(track("Flames of Fate", "DJ Noriken")); + start([controller]); + const getMetadata = vi.spyOn(controller, "getMetadata"); + + cardOf(toolbar).querySelector(".zen-media-current-time").textContent = "1:34"; + await settle(); + + expect(getMetadata).not.toHaveBeenCalled(); + }); + + it("keeps working and logs when reading metadata fails", async () => { + const toolbar = mountToolbar(); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const controller = new FakeController(track("Flames of Fate", "DJ Noriken")); + start([controller]); + const failure = new TypeError("boom"); + vi.spyOn(controller, "getMetadata").mockImplementationOnce(() => { + throw failure; + }); + + controller.dispatchEvent(new Event("metadatachange")); + controller.change(track("Flames of Fate", "DJ Noriken", OTHER_COVER)); + + expect(error).toHaveBeenCalledWith("[zen-media-viz]", failure); + expect(artworkSrc(cardOf(toolbar))).toBe(OTHER_COVER); + }); + + it("throws when the media toolbar is missing", () => { + document.body.replaceChildren(); + + expect(() => start([])).toThrow("#zen-media-controls-toolbar"); + }); +}); + +describe("destroy", () => { + it("removes the artwork from every card", () => { + const toolbar = mountToolbar(); + const viz = start([new FakeController(track("Flames of Fate", "DJ Noriken"))]); + + viz.destroy(); + + expect(artworkSrc(cardOf(toolbar))).toBeNull(); + }); + + it("stops reacting to metadata changes", () => { + const toolbar = mountToolbar(); + const controller = new FakeController(track("Flames of Fate", "DJ Noriken")); + start([controller]).destroy(); + + controller.change(track("Flames of Fate", "DJ Noriken", OTHER_COVER)); + + expect(artworkSrc(cardOf(toolbar))).toBeNull(); + }); + + it("stops reacting to card changes", async () => { + const toolbar = mountToolbar(); + start([new FakeController(track("Other Song", "Other Band"))]).destroy(); + + const card = addCard(toolbar, "Other Song", "Other Band"); + await settle(); + + expect(artworkSrc(card)).toBeNull(); + }); +}); diff --git a/test/smoke.test.js b/test/smoke.test.js deleted file mode 100644 index 4191d42..0000000 --- a/test/smoke.test.js +++ /dev/null @@ -1,8 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { MOD_NAME } from "../src/index.js"; - -describe("test harness", () => { - it("imports mod source", () => { - expect(MOD_NAME).toBe("zen-media-viz"); - }); -}); diff --git a/test/theme.test.js b/test/theme.test.js new file mode 100644 index 0000000..cc8a159 --- /dev/null +++ b/test/theme.test.js @@ -0,0 +1,31 @@ +import { existsSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import pkg from "../package.json" with { type: "json" }; +import theme from "../theme.json" with { type: "json" }; + +const BROWSER_WINDOW = "chrome://browser/content/browser.xhtml"; +const repoFile = (path) => new URL(`../${path}`, import.meta.url); + +describe("theme.json", () => { + it("runs the bundled script in browser windows", () => { + expect(theme.scripts).toEqual({ "zen-media-viz.uc.js": { include: [BROWSER_WINDOW] } }); + }); + + it("points at files that exist in the repository", () => { + const paths = [...Object.keys(theme.scripts), theme.style.chrome]; + + expect(paths.filter((path) => !existsSync(repoFile(path)))).toEqual([]); + }); + + it("names a script Sine loads as a classic userscript", () => { + expect(Object.keys(theme.scripts).every((path) => path.endsWith(".uc.js"))).toBe(true); + }); + + it("matches the package version", () => { + expect(theme.version).toBe(pkg.version); + }); + + it("tells Sine the mod can be disabled without a restart", () => { + expect(theme.supportsUnload).toBe(true); + }); +}); diff --git a/theme.json b/theme.json new file mode 100644 index 0000000..aeaf81b --- /dev/null +++ b/theme.json @@ -0,0 +1,17 @@ +{ + "id": "zen-media-viz", + "name": "Zen Media Viz", + "description": "Shows album artwork in Zen's sidebar media player.", + "homepage": "https://github.com/rodzy/Zen-Media-Viz", + "readme": "https://raw.githubusercontent.com/rodzy/Zen-Media-Viz/main/README.md", + "version": "0.0.0", + "author": "rodzy", + "tags": ["media", "sidebar", "artwork"], + "style": { "chrome": "chrome.css" }, + "scripts": { + "zen-media-viz.uc.js": { + "include": ["chrome://browser/content/browser.xhtml"] + } + }, + "supportsUnload": true +} diff --git a/zen-media-viz.uc.js b/zen-media-viz.uc.js index 0e5efc7..55e6226 100644 --- a/zen-media-viz.uc.js +++ b/zen-media-viz.uc.js @@ -7,6 +7,209 @@ // ==/UserScript== // GENERATED FILE. Do not edit by hand: change src/ and run `npm run build`. (() => { + // src/log.js + var LOG_PREFIX = "[zen-media-viz]"; + function logError(error) { + console.error(LOG_PREFIX, error); + } + + // src/artwork.js + var SIZE_PATTERN = /^([1-9]\d*)x([1-9]\d*)$/i; + var SCALABLE_SIZE = { widthPx: Infinity, heightPx: Infinity }; + function parseSize(token) { + if (token.toLowerCase() === "any") return SCALABLE_SIZE; + const match = SIZE_PATTERN.exec(token); + if (!match) return null; + const [, width, height] = match; + return { widthPx: Number(width), heightPx: Number(height) }; + } + function parseSizes(sizes = "") { + return sizes.split(/\s+/).filter(Boolean).map(parseSize).filter((size) => size !== null); + } + var isImageDataUrl = ({ protocol, pathname }) => protocol === "data:" && pathname.toLowerCase().startsWith("image/"); + function isUsableSrc(src) { + const url = URL.parse(src); + if (!url) return false; + return url.protocol === "https:" || isImageDataUrl(url); + } + function largestEdgePx(sizes) { + return parseSizes(sizes).reduce( + (maxPx, { widthPx, heightPx }) => Math.max(maxPx, Math.min(widthPx, heightPx)), + 0 + ); + } + var smallest = (images) => images.reduce((best, image) => image.edgePx < best.edgePx ? image : best); + var largest = (images) => images.reduce((best, image) => image.edgePx > best.edgePx ? image : best); + function pickArtwork(artwork, { minPx }) { + const candidates = artwork.filter(({ src }) => isUsableSrc(src)).map(({ src, sizes }) => ({ src, edgePx: largestEdgePx(sizes) })); + if (candidates.length === 0) return null; + const bigEnough = candidates.filter(({ edgePx }) => edgePx >= minPx); + return (bigEnough.length > 0 ? smallest(bigEnough) : largest(candidates)).src; + } + + // src/card.js + var HTML_NS = "http://www.w3.org/1999/xhtml"; + 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"); + image.className = ARTWORK_CLASS; + image.alt = ""; + image.setAttribute("referrerpolicy", "no-referrer"); + image.addEventListener("load", () => { + image.hidden = false; + }); + container.prepend(image); + return image; + } + function removeArtwork(card) { + findArtwork(card)?.remove(); + } + function showArtwork(card, src) { + if (!isUsableSrc(src)) { + removeArtwork(card); + return; + } + const container = card.querySelector(INFO_CONTAINER_SELECTOR); + if (!container) return; + const image = findArtwork(card) ?? createArtwork(container); + if (image.getAttribute("src") === src) return; + image.hidden = true; + image.setAttribute("src", src); + } + + // src/controllers.js + var NOT_AVAILABLE = "NS_ERROR_NOT_AVAILABLE"; + var TITLE_SELECTOR = ".zen-media-title"; + var ARTIST_SELECTOR = ".zen-media-artist"; + function readMetadata(controller) { + try { + return controller.getMetadata(); + } catch (error) { + if (error?.name === NOT_AVAILABLE) return null; + throw error; + } + } + function sessionOf({ linkedBrowser: browser }) { + const controller = browser?.browsingContext?.mediaController; + if (!controller) return null; + try { + const metadata = readMetadata(controller); + return metadata && { browser, metadata }; + } catch (error) { + logError(error); + return null; + } + } + function mediaSessions({ tabs }) { + return [...tabs].map(sessionOf).filter((session) => session !== null); + } + var labelText = (card, selector) => card.querySelector(selector)?.textContent ?? ""; + function readCardTrack(card) { + return { title: labelText(card, TITLE_SELECTOR), artist: labelText(card, ARTIST_SELECTOR) }; + } + var isSameTrack = ({ title, artist }, metadata) => title === metadata.title && artist === metadata.artist; + function matchCards(cards, sessions) { + const unclaimed = new Set(sessions); + const matches = /* @__PURE__ */ new Map(); + for (const card of cards) { + const shown = readCardTrack(card); + if (!shown.title) continue; + const session = unclaimed.values().find(({ metadata }) => isSameTrack(shown, metadata)); + if (!session) continue; + unclaimed.delete(session); + matches.set(card, session); + } + return matches; + } + + // 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 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 }) { + const matches = matchCards(cards, sessions); + for (const card of cards) { + const artwork = matches.get(card)?.metadata.artwork ?? []; + showArtwork(card, pickArtwork(artwork, { minPx })); + } + } + function controllerWatcher(onChange, { signal }) { + const watched = /* @__PURE__ */ new WeakSet(); + return ({ browser }) => { + const controller = browser.browsingContext.mediaController; + if (watched.has(controller)) return; + watched.add(controller); + controller.addEventListener("metadatachange", onChange, { signal }); + }; + } + function observeTrackChanges({ MutationObserver }, toolbar, onChange) { + const observer = new MutationObserver((records) => { + if (records.some((record) => isTrackChange(toolbar, record))) onChange(); + }); + 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(); + const refresh = () => { + try { + const sessions = mediaSessions(gBrowser); + sessions.forEach(watchController); + renderArtwork(cardsIn(toolbar), sessions, { + minPx: ARTWORK_CSS_PX * window2.devicePixelRatio + }); + } catch (error) { + logError(error); + } + }; + const watchController = controllerWatcher(refresh, teardown); + const observer = observeTrackChanges(window2, toolbar, refresh); + refresh(); + return { + destroy() { + observer.disconnect(); + teardown.abort(); + cardsIn(toolbar).forEach(removeArtwork); + } + }; + } + + // src/install.js + function destroyPrevious(window2) { + try { + window2.ZenMediaViz?.destroy(); + } catch (error) { + logError(error); + } + } + function install(window2) { + destroyPrevious(window2); + try { + const mediaViz = startMediaViz({ window: window2, gBrowser: window2.gBrowser }); + const handle = { + destroy() { + mediaViz.destroy(); + if (window2.ZenMediaViz === handle) delete window2.ZenMediaViz; + } + }; + window2.ZenMediaViz = handle; + window2.addUnloadListener?.(handle.destroy); + } catch (error) { + logError(error); + } + } + // src/index.js - var MOD_NAME = "zen-media-viz"; + install(window); })();