From 1ab0d3bf57ec63ef262c754c20e14c722c592c9c Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 26 Nov 2026 19:21:00 +0200 Subject: [PATCH] Keep focus in the import wizard and drop searches after leaving details The wizard dialog leaves the DOM without close(), so focus fell to the page body. Closing it now returns focus to the button that opened it, or to New import, unless it closes to navigate, and each new step focuses the dialog title. Leaving the details clears a pending entry search, and entries are not loaded without an import, so /api/imports/null/items is never requested. Co-Authored-By: Claude Opus 5.5 --- templates/player/imports_scripts.html | 28 ++++++++++-- templates/player/imports_wizard.html | 2 +- tests/library_import.test.cjs | 64 +++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 7 deletions(-) diff --git a/templates/player/imports_scripts.html b/templates/player/imports_scripts.html index 2459567..b788783 100644 --- a/templates/player/imports_scripts.html +++ b/templates/player/imports_scripts.html @@ -172,7 +172,7 @@ document.addEventListener('alpine:init', () => { retryPanel: false, retryFederated: false, busy: false, choosing: null, wizard: emptyWizard(), - _navigation: 0, _items: 0, _timer: null, _search: null, _signature: '', + _navigation: 0, _items: 0, _timer: null, _search: null, _opener: null, _signature: '', text(key, values) { const label = labels[key] ?? key; @@ -276,6 +276,8 @@ document.addEventListener('alpine:init', () => { }, async enter(options = {}) { const token = ++this._navigation; + clearTimeout(this._search); + this._search = null; this.navigate('#imports', 'imports', options); this.detail = null; this.detailId = null; @@ -298,6 +300,8 @@ document.addEventListener('alpine:init', () => { const token = ++this._navigation; this.navigate('#imports/' + id, 'import_detail', options); if (this.detailId !== id) { + clearTimeout(this._search); + this._search = null; this.detail = null; this.items = []; this.itemsLoaded = false; @@ -424,6 +428,7 @@ document.addEventListener('alpine:init', () => { }, async loadItems(append = false) { const id = this.detailId; + if (!id) return; const token = ++this._items; this.itemsLoading = true; try { @@ -561,24 +566,40 @@ document.addEventListener('alpine:init', () => { // --------------------------------------------------------------- startWizard(provider = '') { Alpine.store('user').menuOpen = false; + this._opener = document.activeElement; this.wizard = {...emptyWizard(), open: true, provider}; if (!this.providersLoaded) this.loadProviders().catch(error => { this.wizard.error = error.message; }); }, - async closeWizard(dialog) { + // The dialog leaves the DOM without close(), so focus goes back to the + // button that opened it, unless the wizard closes to navigate. + async closeWizard(dialog, restoreFocus = true) { + const opener = this._opener; + this._opener = null; const close = () => { this.wizard = emptyWizard(); + if (restoreFocus) Alpine.nextTick(() => { + const target = opener?.isConnected ? opener + : document.querySelector('.library-imports .release-action-btn.primary') || document.querySelector('.library-imports h1'); + target?.focus({preventScroll: true}); + }); }; if (dialog) await finishPlayerDialog(dialog, close); else close(); }, + // A new step replaces the focused control, so the title takes focus. + focusWizardTitle() { + Alpine.nextTick(() => document.getElementById('import-wizard-title')?.focus()); + }, chooseMethod(provider, method) { this.wizard = {...emptyWizard(), open: true, provider, method, step: method === 'api' ? 'connect' : 'upload'}; + this.focusWizardTitle(); // A sign-in from earlier in this session may still be valid. if (method === 'api') return this.loadApiPlaylists(true); }, back() { const {provider} = this.wizard; this.wizard = {...emptyWizard(), open: true, provider}; + this.focusWizardTitle(); }, signIn(provider = this.wizard.provider) { location.assign(`/api/imports/providers/${encodeURIComponent(provider)}/authorize`); @@ -738,6 +759,7 @@ document.addEventListener('alpine:init', () => { } if (!preview.federated_search_available) wizard.federated = false; this.federatedAvailable = !!preview.federated_search_available; + this.focusWizardTitle(); }, selectable(playlist) { return playlist.available !== false && !playlist.already_imported_in; }, selectAll(value) { @@ -771,7 +793,7 @@ document.addEventListener('alpine:init', () => { federated_search: wizard.federated && this.federatedAvailable, confirm_similar: selection.filter(playlist => playlist.similar_to).map(playlist => playlist.source_key), })}); - await this.closeWizard(document.querySelector('.import-wizard[open]')); + await this.closeWizard(document.querySelector('.import-wizard[open]'), false); return this.open(result.id); } catch (error) { if (this.wizard !== wizard) return; diff --git a/templates/player/imports_wizard.html b/templates/player/imports_wizard.html index be61078..40d92ca 100644 --- a/templates/player/imports_wizard.html +++ b/templates/player/imports_wizard.html @@ -90,7 +90,7 @@ diff --git a/tests/library_import.test.cjs b/tests/library_import.test.cjs index 7158309..637029d 100644 --- a/tests/library_import.test.cjs +++ b/tests/library_import.test.cjs @@ -11,7 +11,7 @@ const MiB = 1024 * 1024; // Values from the script's realm are compared by structure. const same = (actual, expected) => assert.deepEqual(JSON.parse(JSON.stringify(actual ?? null)), expected ?? null); -function setup(responder = () => ({json: {}})) { +function setup(responder = () => ({json: {}}), elements = {}) { const calls = [], timers = [], assigned = [], replaced = []; const stores = { library: {view: 'artists', _activeHash: '', _beginNavigation(hash) { this._activeHash = hash; }, _afterNavigation() {}}, @@ -20,8 +20,10 @@ function setup(responder = () => ({json: {}})) { playlists: {reloads: 0, reload() { this.reloads += 1; }}, }; const context = { - document: {documentElement: {lang: 'en'}, addEventListener(_, fn) { fn(); }, querySelector: () => null}, - Alpine: {store(name, value) { if (value) stores[name] = value; return stores[name]; }}, + document: {documentElement: {lang: 'en'}, addEventListener(_, fn) { fn(); }, + querySelector: selector => elements[selector] || null, getElementById: id => elements['#' + id] || null, + get activeElement() { return elements.active || null; }}, + Alpine: {store(name, value) { if (value) stores[name] = value; return stores[name]; }, nextTick: fn => fn()}, fetch: async (url, options = {}) => { const call = {url, method: options.method || 'GET', body: options.body === undefined ? undefined : JSON.parse(options.body)}; calls.push(call); @@ -351,6 +353,51 @@ test('a sign-in from earlier in the session is used without asking again', async assert.equal(store.wizard.error, ''); }); +test('focus returns to the opener when the wizard closes and moves to the title on a new step', async () => { + const focused = []; + const element = name => ({isConnected: true, focus() { focused.push(name); }}); + const elements = {active: element('opener'), '#import-wizard-title': element('title'), + '.library-imports .release-action-btn.primary': element('new import')}; + const {store} = setup(() => preview([playlist('a')]), elements); + store.startWizard(); + store.chooseMethod('spotify', 'file'); + store.back(); + store.applyPreview(preview([playlist('a')]).json); + same(focused, ['title', 'title', 'title']); + await store.closeWizard({}); + assert.equal(store.wizard.open, false); + same(focused.at(-1), 'opener'); + // An opener that left the page gives way to the New import button. + elements.active = {...element('gone'), isConnected: false}; + store.startWizard(); + await store.closeWizard({}); + same(focused.at(-1), 'new import'); + // Closing to navigate leaves focus to the navigation. + store.startWizard(); + await store.closeWizard({}, false); + same(focused.at(-1), 'new import'); + assert.equal(focused.length, 5); +}); + +test('a pending search does not load entries after leaving the details', async () => { + const {store, calls, timers} = setup(call => call.url === '/api/imports' + ? {json: {imports: []}} : call.url === '/api/imports/providers' ? {json: {providers: []}} + : call.url.includes('/items') ? {json: {items: [], next: null}} : {json: {id: 5, status: 'done', statistics: {}}}); + await store.route(5, '', {fromHash: true}); + store.filter.q = 'song'; + store.searchChanged(); + const search = timers.at(-1); + assert.equal(search.ms, 300); + await store.route(null, '', {fromHash: true}); + assert.equal(store.detailId, null); + const before = calls.length; + await search.fn(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(calls.length, before); + assert.ok(!calls.some(call => call.url.includes('/null/'))); + assert.equal(store.message, ''); +}); + test('progress follows the phase of a running import', () => { const {store} = setup(); same(store.progress({status: 'running', phase: 'resolve_local', statistics: {total: 10, pending: 4}}), {value: 6, max: 10}); @@ -407,3 +454,14 @@ test('import templates parse without a browser', () => { for (const match of html.matchAll(/