Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file>` | Run one test file, e.g. `npx vitest run test/smoke.test.js` |
| `npx vitest run <file>` | 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) |
Expand Down Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions chrome.css
Original file line number Diff line number Diff line change
@@ -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;
}
11 changes: 11 additions & 0 deletions docs/manual-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 2 additions & 2 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
11 changes: 9 additions & 2 deletions src/controllers.js
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 }) {
Expand Down
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const MOD_NAME = "zen-media-viz";
import { install } from "./install.js";

install(window);
27 changes: 27 additions & 0 deletions src/install.js
Original file line number Diff line number Diff line change
@@ -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);
}
}
5 changes: 5 additions & 0 deletions src/log.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const LOG_PREFIX = "[zen-media-viz]";

export function logError(error) {
console.error(LOG_PREFIX, error);
}
72 changes: 72 additions & 0 deletions src/runtime.js
Original file line number Diff line number Diff line change
@@ -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);
},
};
}
19 changes: 18 additions & 1 deletion test/controllers.test.js
Original file line number Diff line number Diff line change
@@ -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" };

Expand Down Expand Up @@ -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: {} } }];

Expand Down
118 changes: 118 additions & 0 deletions test/install.test.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading