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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- Spike: `npm run spike` prints a read-only Browser Console snippet that reports Zen's media card DOM and media controller metadata ([docs/spike.md](docs/spike.md)).
- Test fixture recorded with the spike on Zen 1.24.3b, with tests that pin the media card DOM, metadata and CSP facts the mod relies on.
- 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.
- 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
4 changes: 2 additions & 2 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ The first release is built in milestones. Each milestone is one pull request, wr
| 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 | Next |
| 4 | Card DOM | `src/card.js`: add, update and remove the thumbnail element in a media card | |
| 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 | Next |
| 5 | Runtime wiring & Sine | Watch cards and metadata changes, clean teardown, `theme.json`, first run inside Zen | |
| 6 | Styling & polish | `chrome.css` for the thumbnail, narrow-sidebar and collapsed states, manual checklist | |
| 7 | Release v0.1.0 | Install guide, screenshot, version bump and tag | |
Expand Down
46 changes: 46 additions & 0 deletions src/controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const NOT_AVAILABLE = "NS_ERROR_NOT_AVAILABLE";
const TITLE_SELECTOR = ".zen-media-title";
const ARTIST_SELECTOR = ".zen-media-artist";

export 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;
const metadata = readMetadata(controller);
return metadata && { browser, metadata };
}

export function mediaSessions({ tabs }) {
return [...tabs].map(sessionOf).filter((session) => session !== null);
}

const labelText = (card, selector) => card.querySelector(selector)?.textContent ?? "";

export function readCardTrack(card) {
return { title: labelText(card, TITLE_SELECTOR), artist: labelText(card, ARTIST_SELECTOR) };
}

const isSameTrack = ({ title, artist }, metadata) =>
title === metadata.title && artist === metadata.artist;

export function matchCards(cards, sessions) {
const unclaimed = new Set(sessions);
const matches = 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;
}
183 changes: 183 additions & 0 deletions test/controllers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import { matchCards, mediaSessions, readCardTrack, readMetadata } from "../src/controllers.js";
import report from "./fixtures/zen-1.24.3b.json" with { type: "json" };

function notAvailable() {
return Object.assign(new Error(""), { name: "NS_ERROR_NOT_AVAILABLE" });
}

function controller(metadata) {
return { getMetadata: () => metadata };
}

function inactiveController() {
return {
getMetadata: () => {
throw notAvailable();
},
};
}

function tab(mediaController) {
return { linkedBrowser: { browsingContext: { mediaController } } };
}

function track(title, artist) {
return { title, artist, album: "", artwork: [] };
}

function card(title, artist) {
const element = document.createElement("toolbaritem");
element.className = "zen-media-card";
element.innerHTML = `<vbox><vbox class="zen-media-info-vbox"><label class="zen-media-title"></label><label class="zen-media-artist"></label></vbox></vbox>`;
element.querySelector(".zen-media-title").textContent = title;
element.querySelector(".zen-media-artist").textContent = artist;
return element;
}

function session(title, artist) {
return { browser: {}, metadata: track(title, artist) };
}

function fixtureCards() {
const toolbar = new DOMParser().parseFromString(report.toolbar.html, "application/xml");
return [...toolbar.querySelectorAll("toolbar > .zen-media-card")];
}

describe("readMetadata", () => {
it("returns the controller's metadata", () => {
const metadata = track("Song", "Band");

expect(readMetadata(controller(metadata))).toBe(metadata);
});

it("returns null when the controller is inactive", () => {
expect(readMetadata(inactiveController())).toBeNull();
});

it("rethrows other errors", () => {
const broken = {
getMetadata: () => {
throw new TypeError("boom");
},
};

expect(() => readMetadata(broken)).toThrow(TypeError);
});
});

describe("mediaSessions", () => {
it("pairs each tab's browser with its controller's metadata", () => {
const playing = tab(controller(track("Song", "Band")));

expect(mediaSessions({ tabs: [playing] })).toEqual([
{ browser: playing.linkedBrowser, metadata: track("Song", "Band") },
]);
});

it("skips tabs whose controller is inactive", () => {
const tabs = [tab(inactiveController()), tab(controller(track("Song", "Band")))];

expect(mediaSessions({ tabs }).map(({ metadata }) => metadata.title)).toEqual(["Song"]);
});

it("skips tabs without a browser, browsing context or controller", () => {
const tabs = [{}, { linkedBrowser: {} }, { linkedBrowser: { browsingContext: {} } }];

expect(mediaSessions({ tabs })).toEqual([]);
});

it("returns no sessions when there are no tabs", () => {
expect(mediaSessions({ tabs: [] })).toEqual([]);
});
});

describe("readCardTrack", () => {
it("reads the title and artist shown on a card", () => {
expect(readCardTrack(card("Song", "Band"))).toEqual({ title: "Song", artist: "Band" });
});

it("reads empty strings from a card without labels", () => {
expect(readCardTrack(document.createElement("toolbaritem"))).toEqual({
title: "",
artist: "",
});
});

it("reads the recorded Zen 1.24.3b card", () => {
const [recorded] = fixtureCards();

expect(readCardTrack(recorded)).toEqual({ title: "Flames of Fate", artist: "DJ Noriken" });
});
});

describe("matchCards", () => {
it("matches a card to the session with the same title and artist", () => {
const songCard = card("Song", "Band");
const other = session("Other", "Band");
const song = session("Song", "Band");

expect(matchCards([songCard], [other, song])).toEqual(new Map([[songCard, song]]));
});

it("does not match a session whose artist differs", () => {
expect(matchCards([card("Song", "Band")], [session("Song", "Cover Band")]).size).toBe(0);
});

it("gives each session to at most one card", () => {
const first = card("Song", "Band");
const second = card("Song", "Band");
const firstSession = session("Song", "Band");
const secondSession = session("Song", "Band");

const matches = matchCards([first, second], [firstSession, secondSession]);

expect(matches.get(first)).toBe(firstSession);
expect(matches.get(second)).toBe(secondSession);
});

it("leaves a card unmatched when every matching session is taken", () => {
const second = card("Song", "Band");

const matches = matchCards([card("Song", "Band"), second], [session("Song", "Band")]);

expect(matches.has(second)).toBe(false);
});

it("matches each card to its own session whatever order the sessions come in", () => {
const songCard = card("Song", "Band");
const otherCard = card("Other", "Band");
const song = session("Song", "Band");
const other = session("Other", "Band");

const matches = matchCards([songCard, otherCard], [other, song]);

expect(matches).toEqual(
new Map([
[songCard, song],
[otherCard, other],
]),
);
});

it("leaves a card unmatched when its tab's controller has gone inactive", () => {
const tabs = [tab(inactiveController()), tab(controller(track("Other", "Band")))];

expect(matchCards([card("Song", "Band")], mediaSessions({ tabs })).size).toBe(0);
});

it("does not match a card that shows no title yet", () => {
expect(matchCards([card("", "")], [session("", "")]).size).toBe(0);
});

it("matches the recorded Zen 1.24.3b card to its tab's controller", () => {
const [recorded] = fixtureCards();
const [active] = report.controllers.active;
const playing = tab(controller(active.metadata));

const matches = matchCards([recorded], mediaSessions({ tabs: [playing] }));

expect(matches.get(recorded)?.browser).toBe(playing.linkedBrowser);
});
});