diff --git a/CHANGELOG.md b/CHANGELOG.md index 70b4360..79d94b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,4 +2,17 @@ All notable changes to this project will be documented in this file. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/2.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). \ No newline at end of file +The format is based on [Keep a Changelog](https://keepachangelog.com/en/2.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Changed + +- Replaced the separate "Metronome" text toggle and settings icon with a single icon button. Clicking it opens the settings pop-up, whose "Enabled" checkbox is now the only on/off control; the icon itself still lights up whenever the metronome is enabled. (#12) +- Updated the README to describe where the icon actually surfaces per app version: the v3 "Plugins" rail popover vs. the classic v2 controls bar (the v3 transport bar, where the speed slider lives, is host-native-only and can't host plugin controls directly). + +### Fixed + +- Re-injecting the button on a page that still has the pre-consolidation two-button DOM (e.g. a stale tab that hasn't reloaded since an update) now correctly detects and replaces it, instead of misreading the old text toggle as the new consolidated button. +- Re-injecting the button when the consolidated control is missing its popover now rebuilds the complete control instead of leaving the settings icon unusable. +- Re-injecting on a page still carrying the released 1.0.1 DOM now removes the legacy volume/flash/subdivision/count-in controls it appended directly to the controls bar, instead of stranding them below the new popover-backed controls. diff --git a/README.md b/README.md index 553aa12..194e392 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A plugin for [feedBack](https://github.com/got-feedback/feedback) that adds an a - **Audible click** — plays a sine tone on every beat, with a higher pitch on downbeats (measure starts) - **Visual flash** — subtle amber glow on the highway canvas on each beat (brighter on downbeats) - **Tempo-synced** — follows the song's actual beat map, including tempo changes -- **Toggle button** — click "Metronome" in the player controls to enable/disable +- **Single icon button** — click the metronome icon to open a settings pop-up (enable/disable, volume, flash, subdivision, count-in); the pop-up's "Enabled" checkbox is the on/off toggle - **Zero setup** — no configuration needed, works with any song ## Installation @@ -18,7 +18,12 @@ git clone https://github.com/got-feedback/feedback-plugin-metronome.git metronom docker compose restart ``` -A "Metronome" button will appear in the player controls bar when you play a song. +A metronome icon appears when you play a song. Where it shows up depends on the app version: + +- **v0.3.0+ ("fee[dB]ack" v3 UI)** — the icon lives in the player's "Plugins" rail popover (hover the left icon rail during playback and open the plugin controls group). The v3 transport bar itself — where the speed slider lives — is reserved for host-native controls only, so the icon doesn't sit directly beside it. +- **Classic v2 UI** — the icon sits directly in the player controls bar. + +Click it to open the settings pop-up: check "Enabled" to turn the click on/off, and adjust volume, flash, subdivision, or count-in from the same panel. The icon itself lights up whenever the metronome is enabled, even with the pop-up closed. ## How It Works diff --git a/assets/plugin.css b/assets/plugin.css index 5ca65dd..e4d6d60 100644 --- a/assets/plugin.css +++ b/assets/plugin.css @@ -24,8 +24,18 @@ } } +.met-wrap { + position: relative; + display: inline-flex; + align-items: center; + gap: 0.25rem; +} + .met-btn { - padding: 0.375rem 0.75rem; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.375rem; border-radius: 0.5rem; font-size: 0.75rem; color: var(--met-fg); @@ -79,6 +89,33 @@ display: none !important; } +.met-popover { + position: absolute; + bottom: calc(100% + 0.5rem); + right: 0; + z-index: 30; + display: flex; + flex-direction: column; + gap: 0.5rem; + min-width: 10rem; + padding: 0.625rem; + border: 1px solid var(--met-border); + border-radius: 0.5rem; + background-color: var(--met-bg); + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35); +} + +.met-row { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.met-row .met-range { + flex: 1; + width: auto; +} + /* Plugin-owned elements (not host-themed classes) always get baseline styling. */ #met-count-in-overlay span { font-size: 120px; diff --git a/plugin.json b/plugin.json index 85a0426..a0a4a16 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "metronome", "name": "Metronome", - "version": "1.0.1", + "version": "1.2.0", "private": false, "script": "screen.js", "styles": "assets/plugin.css", diff --git a/screen.js b/screen.js index ca1ca94..527e63a 100644 --- a/screen.js +++ b/screen.js @@ -156,20 +156,57 @@ function _metInjectButton() { const controls = slot || document.getElementById('player-controls'); if (!controls) return; const existingBtn = document.getElementById('btn-metronome'); - if (existingBtn) { + // Gate reuse on `aria-haspopup` rather than just the id existing: a + // pre-consolidation page (the old classic-text-toggle-plus-icon pair) + // also used id="btn-metronome" for its text-only toggle button, which + // has none of the new single button's markup. Reusing that element + // as-is would rebind the popover-opening handler onto a stale text + // button that still reads "Metronome" instead of showing the icon. + const existingPopover = document.getElementById('met-popover'); + const isConsolidatedBtn = !!(existingBtn && existingPopover && + typeof existingBtn.getAttribute === 'function' && + existingBtn.getAttribute('aria-haspopup') === 'true'); + if (isConsolidatedBtn) { + const existingEnabledCheck = document.getElementById('met-enabled-check'); const existingSlider = document.getElementById('met-volume'); const existingFlashCheck = document.getElementById('met-flash-check'); const existingSubdivSel = document.getElementById('met-subdiv'); const existingCountInCheck = document.getElementById('met-count-in-check'); - existingBtn.onclick = _metToggle; + existingBtn.onclick = _metTogglePopover; + if (existingEnabledCheck) _metBindEnabledCheck(existingEnabledCheck); if (existingSlider) _metBindVolumeSlider(existingSlider); if (existingFlashCheck) _metBindFlashCheck(existingFlashCheck); if (existingSubdivSel) _metBindSubdivSelect(existingSubdivSel); if (existingCountInCheck) _metBindCountInCheck(existingCountInCheck); + _metInstallPopoverDismissHook(); _metSyncUi(); return; } + // Stale DOM: a pre-consolidation classic toggle (+ its separate settings + // icon), or an interrupted prior injection. Drop whatever's left rather + // than appending a duplicate alongside it below, which would leave + // _metSyncUi() updating the first DOM match while a second, orphaned + // control goes stale. + const staleWrap = document.getElementById('met-wrap'); + if (staleWrap) { + staleWrap.remove(); + } else { + if (existingBtn) existingBtn.remove(); + const staleSettingsBtn = document.getElementById('btn-metronome-settings'); + if (staleSettingsBtn) staleSettingsBtn.remove(); + // The released 1.0.1 build appended the volume/flash/subdivision/ + // count-in controls directly to #player-controls (no #met-wrap), + // and _metSyncUi no longer manages those ids — drop whichever + // survived a live upgrade so they don't strand dead chrome in the + // controls bar next to the fresh popover-backed control set. + ['met-volume', 'met-vol-label', 'met-flash-label', 'met-subdiv', 'met-count-in-label'] + .forEach((id) => { + const legacy = document.getElementById(id); + if (legacy) legacy.remove(); + }); + } + const lyricsBtn = document.getElementById('btn-lyrics'); // In the v3 slot we always append in order rather than anchoring to a // node that may not even be a child of the slot. @@ -179,44 +216,87 @@ function _metInjectButton() { else controls.appendChild(el); }; + // Single consolidated button (design feedback on issue #12: a separate + // text toggle next to the icon was repetitive). Clicking it opens the + // settings pop-up, whose "Enabled" checkbox is now the only on/off + // control — the button itself still reflects enabled state visually + // via the met-btn--active class (see _metSyncUi). + const wrap = document.createElement('div'); + wrap.id = 'met-wrap'; + wrap.className = 'met-wrap'; + insert(wrap); + const btn = document.createElement('button'); btn.id = 'btn-metronome'; btn.className = 'met-btn'; - btn.textContent = 'Metronome'; - btn.title = 'Toggle metronome click'; - btn.onclick = _metToggle; - insert(btn); - + btn.innerHTML = _MET_ICON_SVG; + btn.title = 'Metronome settings'; + btn.setAttribute('aria-label', 'Metronome settings'); + btn.setAttribute('aria-haspopup', 'true'); + btn.setAttribute('aria-expanded', 'false'); + btn.setAttribute('aria-controls', 'met-popover'); + btn.onclick = _metTogglePopover; + wrap.appendChild(btn); + + const popover = document.createElement('div'); + popover.id = 'met-popover'; + popover.className = 'met-popover met-hidden'; + // Listen on `wrap`, not `popover`: opening the popover doesn't move + // focus into it, so an Escape pressed immediately after the click that + // opened it still targets the settings button — a listener scoped to + // the popover alone would never see that keydown. `wrap` is an + // ancestor of both the button and the popover, so it catches Escape + // from either. + wrap.addEventListener('keydown', function(e) { + if (e.key === 'Escape' || e.key === 'Esc') { _metClosePopover(); btn.focus(); } + }); + wrap.appendChild(popover); + + const enabledLabel = document.createElement('label'); + enabledLabel.id = 'met-enabled-label'; + enabledLabel.className = 'met-toggle'; + const enabledCheck = document.createElement('input'); + enabledCheck.type = 'checkbox'; + enabledCheck.id = 'met-enabled-check'; + enabledCheck.className = 'met-checkbox'; + enabledLabel.appendChild(enabledCheck); + enabledLabel.appendChild(document.createTextNode(' Enabled')); + popover.appendChild(enabledLabel); + _metBindEnabledCheck(enabledCheck); + + const volRow = document.createElement('div'); + volRow.className = 'met-row'; const slider = document.createElement('input'); slider.type = 'range'; slider.id = 'met-volume'; slider.min = '0'; slider.max = '100'; - slider.className = 'met-range met-hidden'; + slider.className = 'met-range'; _metBindVolumeSlider(slider); - insert(slider); + volRow.appendChild(slider); const label = document.createElement('span'); label.id = 'met-vol-label'; - label.className = 'met-label met-hidden'; + label.className = 'met-label'; label.textContent = `${Math.round(_metSettings.volume * 100)}%`; - insert(label); + volRow.appendChild(label); + popover.appendChild(volRow); const flashLabel = document.createElement('label'); flashLabel.id = 'met-flash-label'; - flashLabel.className = 'met-toggle met-hidden'; + flashLabel.className = 'met-toggle'; const flashCheck = document.createElement('input'); flashCheck.type = 'checkbox'; flashCheck.id = 'met-flash-check'; flashCheck.className = 'met-checkbox'; flashLabel.appendChild(flashCheck); flashLabel.appendChild(document.createTextNode(' Flash')); - insert(flashLabel); + popover.appendChild(flashLabel); _metBindFlashCheck(flashCheck); const subdivSel = document.createElement('select'); subdivSel.id = 'met-subdiv'; - subdivSel.className = 'met-select met-hidden'; + subdivSel.className = 'met-select'; subdivSel.title = 'Subdivision clicks'; [['none', 'Beats only'], ['eighth', '8th notes'], ['triplet', 'Triplets']].forEach(([val, text]) => { const opt = document.createElement('option'); @@ -224,12 +304,12 @@ function _metInjectButton() { opt.textContent = text; subdivSel.appendChild(opt); }); - insert(subdivSel); + popover.appendChild(subdivSel); _metBindSubdivSelect(subdivSel); const countInLabel = document.createElement('label'); countInLabel.id = 'met-count-in-label'; - countInLabel.className = 'met-toggle met-hidden'; + countInLabel.className = 'met-toggle'; countInLabel.title = 'Show 4-3-2-1 countdown before the first beat'; const countInCheck = document.createElement('input'); countInCheck.type = 'checkbox'; @@ -237,29 +317,78 @@ function _metInjectButton() { countInCheck.className = 'met-checkbox'; countInLabel.appendChild(countInCheck); countInLabel.appendChild(document.createTextNode(' Count-in')); - insert(countInLabel); + popover.appendChild(countInLabel); _metBindCountInCheck(countInCheck); + _metInstallPopoverDismissHook(); _metSyncUi(); } +// Classic metronome triangle-with-pendulum glyph (issue #12: "should have +// the classic metronome shape"). +const _MET_ICON_SVG = + ''; + +function _metBindEnabledCheck(check) { + if (check._metEnabledListener) check.removeEventListener('change', check._metEnabledListener); + check.checked = !!_metSettings.enabled; + check._metEnabledListener = function() { _metToggle(); }; + check.addEventListener('change', check._metEnabledListener); +} + +function _metSetPopoverOpen(open) { + const popover = document.getElementById('met-popover'); + const btn = document.getElementById('btn-metronome'); + if (!popover) return; + popover.classList.toggle('met-hidden', !open); + if (btn) btn.setAttribute('aria-expanded', open ? 'true' : 'false'); +} + +function _metTogglePopover(e) { + if (e && typeof e.stopPropagation === 'function') e.stopPropagation(); + const popover = document.getElementById('met-popover'); + if (!popover) return; + _metSetPopoverOpen(popover.classList.contains('met-hidden')); +} + +function _metClosePopover() { + _metSetPopoverOpen(false); +} + +// Closes the settings pop-up on an outside click. Installed once per page +// (guarded like the other document-level hooks in this file). +const MET_POPOVER_DISMISS_INSTALLED_KEY = '__slopsmithMetronomePopoverDismissInstalled'; +function _metInstallPopoverDismissHook() { + if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return; + if (window[MET_POPOVER_DISMISS_INSTALLED_KEY]) return; + document.addEventListener('click', function(e) { + const wrap = document.getElementById('met-wrap'); + const popover = document.getElementById('met-popover'); + if (!wrap || !popover) return; + if (typeof wrap.contains === 'function' && wrap.contains(e.target)) return; + _metClosePopover(); + }); + window[MET_POPOVER_DISMISS_INSTALLED_KEY] = true; +} + function _metSyncUi() { const enabled = _metSettings.enabled; const btn = document.getElementById('btn-metronome'); - const slider = document.getElementById('met-volume'); - const label = document.getElementById('met-vol-label'); - const flashLabel = document.getElementById('met-flash-label'); - const subdivSel = document.getElementById('met-subdiv'); - const countInLabel = document.getElementById('met-count-in-label'); + const enabledCheck = document.getElementById('met-enabled-check'); if (btn) { btn.className = enabled ? 'met-btn met-btn--active' : 'met-btn'; - btn.textContent = enabled ? 'Metronome ✓' : 'Metronome'; + const stateLabel = enabled ? 'Metronome settings (on)' : 'Metronome settings (off)'; + btn.title = stateLabel; + btn.setAttribute('aria-label', stateLabel); } - if (slider) slider.classList.toggle('met-hidden', !enabled); - if (label) label.classList.toggle('met-hidden', !enabled); - if (flashLabel) flashLabel.classList.toggle('met-hidden', !enabled); - if (subdivSel) subdivSel.classList.toggle('met-hidden', !enabled); - if (countInLabel) countInLabel.classList.toggle('met-hidden', !enabled); + if (enabledCheck) enabledCheck.checked = enabled; } function _metToggle() { @@ -491,6 +620,8 @@ if (typeof module !== 'undefined' && module.exports) { module.exports = { _metSettings, _metState, _metClick, _metFlash, _metBindVolumeSlider, _metBindFlashCheck, _metBindSubdivSelect, _metBindCountInCheck, + _metBindEnabledCheck, _metTogglePopover, _metClosePopover, _metSetPopoverOpen, + _metInstallPopoverDismissHook, _metInjectButton, _metSyncUi, _metToggle, _metSetVolume, _metSaveSettings, _metGetHighway, _metEnsureDrawHookInstalled, _metTick, _metUpdateCountIn, _metClearCountIn, diff --git a/tests/screen.test.js b/tests/screen.test.js index b1f5f0f..afe095e 100644 --- a/tests/screen.test.js +++ b/tests/screen.test.js @@ -195,10 +195,17 @@ test('_metSetVolume saves settings to localStorage', () => { // --- Fake DOM helpers for the UI-injection / count-in overlay tests below --- function makeFakeElement(tag) { + // Real class-token set, kept in sync with `className` both ways (like + // a real browser's classList/className) rather than a one-off + // `_hidden` boolean — so tests exercise the same `classList.contains` + // read path production code uses. + let classNameStr = ''; + const tokens = () => classNameStr.split(/\s+/).filter(Boolean); const el = { tagName: tag, id: '', - className: '', + get className() { return classNameStr; }, + set className(v) { classNameStr = v || ''; }, textContent: '', title: '', children: [], @@ -207,18 +214,37 @@ function makeFakeElement(tag) { parentNode: null, _listeners: {}, classList: { - _hidden: false, - toggle(cls, force) { if (cls === 'hidden' || cls === 'met-hidden') this._hidden = force; }, - add() {}, - remove() {}, + contains(cls) { return tokens().includes(cls); }, + add(cls) { if (!tokens().includes(cls)) classNameStr = (classNameStr + ' ' + cls).trim(); }, + remove(cls) { classNameStr = tokens().filter((t) => t !== cls).join(' '); }, + toggle(cls, force) { + const has = tokens().includes(cls); + const want = force === undefined ? !has : force; + if (want) this.add(cls); else this.remove(cls); + return want; + }, }, appendChild(child) { el.children.push(child); child.parentNode = el; return child; }, insertBefore(child, ref) { el.children.push(child); child.parentNode = el; return child; }, removeChild(child) { el.children = el.children.filter((c) => c !== child); child.parentNode = null; return child; }, - remove() { if (el.parentNode) el.parentNode.removeChild(el); el._detached = true; }, + remove() { + if (el.parentNode) el.parentNode.removeChild(el); + // Real getElementById can never find a node whose subtree was + // removed, including its descendants — mark the whole subtree + // detached, not just the removed root, so the fake's flat + // getElementById lookup (below) matches that. + (function markDetached(node) { + node._detached = true; + if (Array.isArray(node.children)) node.children.forEach(markDetached); + })(el); + }, addEventListener(type, fn) { (el._listeners[type] = el._listeners[type] || []).push(fn); }, removeEventListener(type, fn) { if (el._listeners[type]) el._listeners[type] = el._listeners[type].filter((f) => f !== fn); }, querySelector() { return null; }, + setAttribute(name, value) { el[name] = value; }, + getAttribute(name) { return name in el ? el[name] : null; }, + focus() {}, + contains(node) { return el.children.includes(node) || el.children.some((c) => typeof c.contains === 'function' && c.contains(node)); }, }; return el; } @@ -227,11 +253,17 @@ function makeFakeDocument() { const created = []; const body = makeFakeElement('body'); created.push(body); + const listeners = {}; return { body, createElement(tag) { const el = makeFakeElement(tag); created.push(el); return el; }, createTextNode(text) { return { nodeType: 3, textContent: text }; }, getElementById(id) { return created.find((e) => e.id === id && !e._detached) || null; }, + addEventListener(type, fn) { (listeners[type] = listeners[type] || []).push(fn); }, + removeEventListener(type, fn) { if (listeners[type]) listeners[type] = listeners[type].filter((f) => f !== fn); }, + // Test helper (not part of the real Document API): fire a fake + // event at every listener registered for `type`. + _dispatch(type, event) { (listeners[type] || []).forEach((fn) => fn(event)); }, }; } @@ -447,7 +479,7 @@ test('_metInjectButton mounts into window.feedBack.ui.playerControlSlot() in v3' mod._metInjectButton(); assert.equal(legacyControls.children.length, 0); - assert.ok(slot.children.some((c) => c.id === 'btn-metronome')); + assert.ok(slot.children.some((c) => c.children && c.children.some((g) => g.id === 'btn-metronome'))); }); test('_metInjectButton falls back to legacy #player-controls when playerControlSlot() throws', () => { @@ -466,7 +498,7 @@ test('_metInjectButton falls back to legacy #player-controls when playerControlS global.window.feedBack = { uiVersion: 'v3', ui: { playerControlSlot: () => { throw new Error('boom'); } } }; mod._metInjectButton(); - assert.ok(legacyControls.children.some((c) => c.id === 'btn-metronome')); + assert.ok(legacyControls.children.some((c) => c.children && c.children.some((g) => g.id === 'btn-metronome'))); }); test('_metInjectButton keeps legacy behavior unchanged when window.feedBack is absent', () => { @@ -482,7 +514,211 @@ test('_metInjectButton keeps legacy behavior unchanged when window.feedBack is a global.document.getElementById = (id) => (id === 'player-controls' ? legacyControls : null); mod._metInjectButton(); - assert.ok(legacyControls.children.some((c) => c.id === 'btn-metronome')); + assert.ok(legacyControls.children.some((c) => c.children && c.children.some((g) => g.id === 'btn-metronome'))); +}); + +// --- Issue #12 pullfrog review follow-up: popover open/close, outside-click +// dismissal, and the enabled-check binding --- + +function setupPopoverTest() { + global.window = {}; + const doc = makeFakeDocument(); + global.document = doc; + global.localStorage = { _store: {}, getItem(k) { return this._store[k] ?? null; }, setItem(k, v) { this._store[k] = v; }, clear() { this._store = {}; } }; + const controls = doc.createElement('div'); + controls.id = 'player-controls'; + const file = path.join(__dirname, '..', 'screen.js'); + delete require.cache[require.resolve(file)]; + const mod = require(file); + mod._metInjectButton(); + return { + mod, doc, + wrap: doc.getElementById('met-wrap'), + btn: doc.getElementById('btn-metronome'), + popover: doc.getElementById('met-popover'), + }; +} + +test('clicking the icon button toggles the popover hidden <-> visible and syncs aria-expanded', () => { + const { mod, btn, popover } = setupPopoverTest(); + assert.ok(popover.classList.contains('met-hidden')); + assert.equal(btn['aria-expanded'], 'false'); + + mod._metTogglePopover({ stopPropagation() {} }); + assert.ok(!popover.classList.contains('met-hidden')); + assert.equal(btn['aria-expanded'], 'true'); + + mod._metTogglePopover({ stopPropagation() {} }); + assert.ok(popover.classList.contains('met-hidden')); + assert.equal(btn['aria-expanded'], 'false'); +}); + +test('a click outside #met-wrap closes the open popover', () => { + const { mod, doc, btn, popover } = setupPopoverTest(); + mod._metTogglePopover({ stopPropagation() {} }); + assert.ok(!popover.classList.contains('met-hidden')); + + const outsideEl = doc.createElement('div'); + doc._dispatch('click', { target: outsideEl }); + assert.ok(popover.classList.contains('met-hidden')); + assert.equal(btn['aria-expanded'], 'false'); +}); + +test('a click inside #met-wrap does not close the popover', () => { + const { mod, doc, popover } = setupPopoverTest(); + mod._metTogglePopover({ stopPropagation() {} }); + assert.ok(!popover.classList.contains('met-hidden')); + + // A click on the popover itself (a descendant of #met-wrap) must not + // be treated as "outside". + doc._dispatch('click', { target: popover }); + assert.ok(!popover.classList.contains('met-hidden')); +}); + +test('Escape closes the popover and returns focus to the button', () => { + const { mod, wrap, popover, btn } = setupPopoverTest(); + mod._metTogglePopover({ stopPropagation() {} }); + assert.ok(!popover.classList.contains('met-hidden')); + + let focused = false; + btn.focus = () => { focused = true; }; + // The keydown listener lives on `wrap`, not `popover` — opening the + // popover never moves focus into it, so a CodeRabbit review flagged + // that an Escape fired immediately after open (while focus is still on + // the settings button) would never reach a popover-scoped listener. + // Dispatch from wrap, the shared ancestor, to match. + wrap._listeners.keydown[0]({ key: 'Escape' }); + assert.ok(popover.classList.contains('met-hidden')); + assert.ok(focused); +}); + +test('re-invoking _metInjectButton after an older two-button version left its DOM behind replaces it with the single consolidated button', () => { + const { mod, doc, wrap } = setupPopoverTest(); + // Simulate a page that still has the pre-consolidation DOM: a classic + // text toggle at id="btn-metronome" (no aria-haspopup) plus a separate + // id="btn-metronome-settings" icon button and its popover. + doc.getElementById('btn-metronome').remove(); + const oldToggle = doc.createElement('button'); + oldToggle.id = 'btn-metronome'; + oldToggle.className = 'met-btn'; + oldToggle.textContent = 'Metronome'; + wrap.appendChild(oldToggle); + const oldSettingsBtn = doc.createElement('button'); + oldSettingsBtn.id = 'btn-metronome-settings'; + wrap.appendChild(oldSettingsBtn); + + mod._metInjectButton(); + + const newBtn = doc.getElementById('btn-metronome'); + assert.ok(newBtn, 'consolidated button must exist after re-injection'); + assert.notEqual(newBtn, oldToggle, 'the stale classic toggle must be replaced, not reused'); + assert.equal(newBtn.getAttribute('aria-haspopup'), 'true', 'the rebuilt button must be the consolidated icon button'); + assert.equal(doc.getElementById('btn-metronome-settings'), null, 'the stale separate settings button id must be gone'); + // Exactly one #met-wrap must exist under the controls parent — no + // duplicate left behind from the stale state. + const controls = doc.getElementById('player-controls') || wrap.parentNode; + const wraps = controls.children.filter((c) => c.id === 'met-wrap'); + assert.equal(wraps.length, 1, 'must not leave a duplicate #met-wrap behind'); +}); + +test('re-injecting after the released 1.0.1 build removes its legacy top-level controls instead of stranding them', () => { + global.window = {}; + const doc = makeFakeDocument(); + global.document = doc; + global.localStorage = { _store: {}, getItem(k) { return this._store[k] ?? null; }, setItem(k, v) { this._store[k] = v; }, clear() { this._store = {}; } }; + const controls = doc.createElement('div'); + controls.id = 'player-controls'; + const file = path.join(__dirname, '..', 'screen.js'); + delete require.cache[require.resolve(file)]; + const mod = require(file); + + // Released 1.0.1 shape: no #met-wrap — the classic text toggle and the + // five controls sit directly under #player-controls, and _metSyncUi no + // longer updates those ids. + const oldToggle = doc.createElement('button'); + oldToggle.id = 'btn-metronome'; + oldToggle.textContent = 'Metronome'; + controls.appendChild(oldToggle); + const legacy = {}; + ['met-volume', 'met-vol-label', 'met-flash-label', 'met-subdiv', 'met-count-in-label'] + .forEach((id) => { + const tag = id === 'met-subdiv' ? 'select' : id === 'met-vol-label' ? 'span' : id === 'met-volume' ? 'input' : 'label'; + const el = doc.createElement(tag); + el.id = id; + controls.appendChild(el); + legacy[id] = el; + }); + + mod._metInjectButton(); + + const newBtn = doc.getElementById('btn-metronome'); + assert.ok(newBtn, 'a consolidated button must exist after re-injection'); + assert.notEqual(newBtn, oldToggle, 'the 1.0.1 text toggle must be replaced, not reused'); + assert.equal(newBtn.getAttribute('aria-haspopup'), 'true', 'the rebuilt button must be the consolidated icon button'); + Object.keys(legacy).forEach((id) => { + assert.equal(legacy[id]._detached, true, `legacy #${id} must not be stranded in the controls bar`); + }); + assert.ok(doc.getElementById('met-volume'), 'the fresh popover control set must provide #met-volume'); + assert.ok(doc.getElementById('met-popover'), 'the rebuild must recreate the popover'); +}); + +test('toggling #met-enabled-check flips _metSettings.enabled', () => { + const { mod, doc } = setupPopoverTest(); + const check = doc.getElementById('met-enabled-check'); + assert.equal(mod._metSettings.enabled, false); + check.checked = true; + check._listeners.change[0](); + assert.equal(mod._metSettings.enabled, true); +}); + +// --- A single consolidated button replaces the separate classic toggle + +// icon pair (design feedback: two buttons for one feature was repetitive). + +test('_metInjectButton creates exactly one consolidated button, not a separate toggle', () => { + const { doc, btn } = setupPopoverTest(); + assert.ok(btn, '#btn-metronome consolidated button must exist'); + assert.equal(btn.getAttribute('aria-haspopup'), 'true'); + assert.equal(doc.getElementById('btn-metronome-settings'), null, 'no separate settings-button id should exist'); +}); + +test('clicking the button opens the popover without touching _metSettings.enabled', () => { + const { mod, btn, popover } = setupPopoverTest(); + assert.equal(mod._metSettings.enabled, false); + btn.onclick({ stopPropagation() {} }); + assert.ok(!popover.classList.contains('met-hidden')); + assert.equal(mod._metSettings.enabled, false); +}); + +test('_metSyncUi updates the button active class and title/aria-label to reflect enabled state', () => { + const { mod, btn } = setupPopoverTest(); + assert.ok(!btn.className.includes('met-btn--active')); + assert.equal(btn.title, 'Metronome settings (off)'); + + mod._metToggle(); + + assert.ok(btn.className.includes('met-btn--active')); + assert.equal(btn.title, 'Metronome settings (on)'); + assert.equal(btn['aria-label'], 'Metronome settings (on)'); +}); + +test('re-invoking _metInjectButton rewires onclick on the existing button rather than duplicating it', () => { + const { mod, doc, btn } = setupPopoverTest(); + mod._metInjectButton(); + assert.equal(doc.getElementById('btn-metronome'), btn, 'must reuse the same button element'); +}); + +test('re-injection rebuilds controls when the consolidated button has no popover', () => { + const { mod, doc, wrap, btn } = setupPopoverTest(); + const oldPopover = doc.getElementById('met-popover'); + oldPopover.remove(); + + mod._metInjectButton(); + + const newBtn = doc.getElementById('btn-metronome'); + assert.ok(newBtn); + assert.notEqual(newBtn, btn); + assert.ok(doc.getElementById('met-popover')); + assert.notEqual(doc.getElementById('met-wrap'), wrap); }); // --- Issues #3/#6: tick-interval start/stop helpers used by the navigation hook ---