diff --git a/packages/comment-widget/src/emoji-button.ts b/packages/comment-widget/src/emoji-button.ts index 9c90e73..54c24fe 100644 --- a/packages/comment-widget/src/emoji-button.ts +++ b/packages/comment-widget/src/emoji-button.ts @@ -60,12 +60,12 @@ const sharedEmojiPanel = { wrapper: null as HTMLDivElement | null, picker: null as Picker | null, activeButton: null as EmojiButton | null, + styleElement: null as HTMLStyleElement | null, init() { - if (this.wrapper) return this.wrapper; - - const styleElement = document.createElement('style'); - styleElement.textContent = ` + if (!this.styleElement) { + const styleElement = document.createElement('style'); + styleElement.textContent = ` .form__emoji-panel { box-shadow: 0 0.5em 1em rgba(0, 0, 0, 0.1); border-radius: 0.875em; @@ -104,19 +104,35 @@ const sharedEmojiPanel = { --color-border-over: var(--halo-cw-emoji-picker-color-border-over, rgba(0, 0, 0, .1)); } `; - document.head.appendChild(styleElement); + this.styleElement = styleElement; + } + if (!this.styleElement.isConnected) { + document.head.appendChild(this.styleElement); + } - this.wrapper = document.createElement('div'); - this.wrapper.className = 'form__emoji-panel'; - this.wrapper.style.position = 'absolute'; - this.wrapper.style.zIndex = '9999'; - document.body.appendChild(this.wrapper); + if (this.wrapper && !this.wrapper.isConnected) { + // emoji-mart marks the picker as disconnected and stops observing the + // document, so let the next open create a usable instance. + this.picker = null; + this.wrapper.replaceChildren(); + } + if (!this.wrapper) { + this.wrapper = document.createElement('div'); + this.wrapper.className = 'form__emoji-panel'; + this.wrapper.style.position = 'absolute'; + this.wrapper.style.zIndex = '9999'; + this.wrapper.style.display = 'none'; + } + if (!this.wrapper.isConnected) { + document.body.appendChild(this.wrapper); + } return this.wrapper; }, show() { if (this.wrapper) { + this.wrapper.style.display = 'block'; this.wrapper.classList.add('visible'); } }, @@ -124,6 +140,7 @@ const sharedEmojiPanel = { hide() { if (this.wrapper) { this.wrapper.classList.remove('visible'); + this.wrapper.style.display = 'none'; } }, @@ -168,6 +185,7 @@ export class EmojiButton extends LitElement { sharedEmojiPanel.activeButton = null; sharedEmojiPanel.hide(); } + this.emojiPickerVisible = false; super.disconnectedCallback(); } @@ -217,6 +235,8 @@ export class EmojiButton extends LitElement { return; } + sharedEmojiPanel.init(); + if ( sharedEmojiPanel.activeButton && sharedEmojiPanel.activeButton !== this @@ -239,30 +259,35 @@ export class EmojiButton extends LitElement { const { Picker } = await import('emoji-mart'); const { default: data } = await import('@emoji-mart/data'); - sharedEmojiPanel.picker = new Picker({ - data, - autoFocus: focusSearch, - onEmojiSelect: ({ native }: { native: string }) => { - const activeButton = sharedEmojiPanel.activeButton; - if (activeButton) { - activeButton.dispatchEvent( - new CustomEvent('emoji-select', { detail: { native } }) - ); - activeButton.closeEmojiPicker(); - } - }, - i18n: localeMap[getLocale()], - }); + if (!this.isConnected || sharedEmojiPanel.activeButton !== this) { + this.emojiLoading = false; + return; + } - if (sharedEmojiPanel.wrapper) { - sharedEmojiPanel.wrapper.appendChild( + if (!sharedEmojiPanel.picker) { + sharedEmojiPanel.picker = new Picker({ + data, + autoFocus: focusSearch, + onEmojiSelect: ({ native }: { native: string }) => { + const activeButton = sharedEmojiPanel.activeButton; + if (activeButton) { + activeButton.dispatchEvent( + new CustomEvent('emoji-select', { detail: { native } }) + ); + activeButton.closeEmojiPicker(); + } + }, + i18n: localeMap[getLocale()], + }); + + sharedEmojiPanel.wrapper?.appendChild( sharedEmojiPanel.picker as unknown as Node ); - sharedEmojiPanel.show(); } this.emojiPickerVisible = true; this.emojiLoading = false; + sharedEmojiPanel.show(); this.setupFloating(); } diff --git a/packages/comment-widget/tests/browser-helpers.js b/packages/comment-widget/tests/browser-helpers.js index 47beed4..b4f3805 100644 --- a/packages/comment-widget/tests/browser-helpers.js +++ b/packages/comment-widget/tests/browser-helpers.js @@ -1,11 +1,12 @@ import { vi } from 'vitest'; -export function until(predicate) { +export function until(predicate, timeout = 4000) { return vi.waitFor( () => { - if (!predicate()) throw new Error('Timed out waiting for UI'); + if (!predicate()) + throw new Error(`Timed out waiting for UI: ${predicate}`); }, - { timeout: 4000, interval: 20 } + { timeout, interval: 20 } ); } diff --git a/packages/comment-widget/tests/browser-setup.js b/packages/comment-widget/tests/browser-setup.js index 0daa4f2..8883e4c 100644 --- a/packages/comment-widget/tests/browser-setup.js +++ b/packages/comment-widget/tests/browser-setup.js @@ -1,7 +1,7 @@ import { afterEach, vi } from 'vitest'; import '../var.css'; -afterEach(() => { +afterEach(async () => { const url = new URL(location.href); if (url.searchParams.has('comment-page')) { url.searchParams.delete('comment-page'); @@ -12,6 +12,12 @@ afterEach(() => { document.documentElement.lang = 'en'; delete document.body.dataset.colorScheme; localStorage.clear(); + // Test files that share a browser session share IndexedDB too, so leaked + // upload tickets would otherwise break the draft recovery of later files. + await new Promise((resolve) => { + const request = indexedDB.deleteDatabase('halo-comment-uploads'); + request.onsuccess = request.onerror = () => resolve(); + }); // biome-ignore lint/suspicious/noDocumentCookie: Restore the locale cookie used by the widget. document.cookie = 'language=; max-age=0; path=/'; vi.restoreAllMocks(); diff --git a/packages/comment-widget/tests/emoji-panel-concurrent.browser.test.js b/packages/comment-widget/tests/emoji-panel-concurrent.browser.test.js new file mode 100644 index 0000000..eac87e0 --- /dev/null +++ b/packages/comment-widget/tests/emoji-panel-concurrent.browser.test.js @@ -0,0 +1,39 @@ +import { assert, test } from 'vitest'; + +test('Two buttons opening the picker for the first time share one picker', async () => { + document.body.innerHTML = '
'; + await import('../src/index.ts'); + const fixtures = document.querySelector('#fixtures'); + const first = document.createElement('emoji-button'); + const second = document.createElement('emoji-button'); + fixtures.append(first, second); + await Promise.all([first.updateComplete, second.updateComplete]); + + // The picker is loaded lazily, so both buttons still take the async path. + const firstOpening = first.handleOpenEmojiPicker(new MouseEvent('click')); + const secondOpening = second.handleOpenEmojiPicker(new MouseEvent('click')); + await Promise.all([firstOpening, secondOpening]); + await Promise.all([first.updateComplete, second.updateComplete]); + + const wrapper = document.querySelector('.form__emoji-panel'); + assert( + wrapper.querySelectorAll('em-emoji-picker').length === 1, + 'Concurrent openings must create a single picker' + ); + assert( + !first.emojiPickerVisible && + second.emojiPickerVisible && + !first.emojiLoading && + !second.emojiLoading, + 'Only the button that kept the panel open may stay expanded' + ); + assert( + first.shadowRoot.querySelector('button').getAttribute('aria-expanded') === + 'false' && + second.shadowRoot + .querySelector('button') + .getAttribute('aria-expanded') === 'true', + 'The expanded state must match the shared panel state' + ); + second.closeEmojiPicker(); +}); diff --git a/packages/comment-widget/tests/emoji-panel-race.browser.test.js b/packages/comment-widget/tests/emoji-panel-race.browser.test.js new file mode 100644 index 0000000..883193b --- /dev/null +++ b/packages/comment-widget/tests/emoji-panel-race.browser.test.js @@ -0,0 +1,27 @@ +import { assert, test } from 'vitest'; + +test('Emoji panel must not appear when navigation interrupts its first load', async () => { + document.body.innerHTML = '
'; + await import('../src/index.ts'); + const fixtures = document.querySelector('#fixtures'); + const button = document.createElement('emoji-button'); + fixtures.append(button); + await button.updateComplete; + + // This is the first open in this file, so the picker is loaded lazily. + const opening = button.handleOpenEmojiPicker(new MouseEvent('click')); + button.remove(); + fixtures.replaceChildren(); + await opening; + + const wrapper = document.querySelector('.form__emoji-panel'); + assert(wrapper, 'The shared panel must exist'); + assert( + getComputedStyle(wrapper).display === 'none', + 'A page change during loading must not show the panel' + ); + assert( + !wrapper.querySelector('em-emoji-picker'), + 'An interrupted first load must not create a picker' + ); +}); diff --git a/packages/comment-widget/tests/spa-emoji-panel.browser.test.js b/packages/comment-widget/tests/spa-emoji-panel.browser.test.js new file mode 100644 index 0000000..bea4df3 --- /dev/null +++ b/packages/comment-widget/tests/spa-emoji-panel.browser.test.js @@ -0,0 +1,150 @@ +import { assert, test } from 'vitest'; +import { until } from './browser-helpers.js'; + +function emojiPanelStyle() { + return [...document.head.querySelectorAll('style')].find((style) => + style.textContent?.includes('.form__emoji-panel') + ); +} + +function emojiPanelWrapper() { + return document.body.querySelector('.form__emoji-panel'); +} + +test('Emoji panel stays hidden after an SPA page change', async () => { + document.body.innerHTML = '
'; + await import('../src/index.ts'); + const fixtures = document.querySelector('#fixtures'); + const button = document.createElement('emoji-button'); + fixtures.append(button); + await button.updateComplete; + + await button.handleOpenEmojiPicker(new MouseEvent('click')); + await until(() => emojiPanelWrapper()?.querySelector('em-emoji-picker')); + const wrapper = emojiPanelWrapper(); + assert( + getComputedStyle(wrapper).display === 'block', + 'The panel must be visible while open' + ); + + button.closeEmojiPicker(); + assert( + getComputedStyle(wrapper).display === 'none', + 'The panel must be hidden once closed' + ); + + // SwupHeadPlugin removes runtime-injected head tags that are not part of the + // incoming document before replacing the page content. + emojiPanelStyle()?.remove(); + assert( + getComputedStyle(wrapper).display === 'none', + 'The closed panel must stay hidden without the injected styles' + ); + + // The old page is replaced and the next page has no comment widget. + fixtures.replaceChildren(); + assert( + getComputedStyle(wrapper).display === 'none', + 'The panel must stay hidden when no button reconnects' + ); + + // The next page has a comment widget, whose new button restores the styles. + const nextButton = document.createElement('emoji-button'); + fixtures.append(nextButton); + await nextButton.updateComplete; + assert( + emojiPanelStyle(), + 'The panel styles must be restored after a page change' + ); + assert( + wrapper.isConnected && getComputedStyle(wrapper).display === 'none', + 'The shared panel must stay attached and hidden' + ); + + // Navigating away while the panel is open must also close it. + await nextButton.handleOpenEmojiPicker(new MouseEvent('click')); + assert( + getComputedStyle(wrapper).display === 'block', + 'The panel must reopen on the new page' + ); + fixtures.replaceChildren(); + const openedDuringNavigationButton = document.createElement('emoji-button'); + fixtures.append(openedDuringNavigationButton); + await openedDuringNavigationButton.updateComplete; + assert( + getComputedStyle(wrapper).display === 'none', + 'Navigating away must close an open panel' + ); + + // Some hosts replace the whole body instead of a single container. + const detachedPicker = wrapper.querySelector('em-emoji-picker'); + document.body.replaceChildren(); + const bodyReplacedButton = document.createElement('emoji-button'); + document.body.append(bodyReplacedButton); + await bodyReplacedButton.updateComplete; + assert( + wrapper.isConnected && getComputedStyle(wrapper).display === 'none', + 'The shared panel must be reattached when the body is replaced' + ); + + await bodyReplacedButton.handleOpenEmojiPicker(new MouseEvent('click')); + assert( + getComputedStyle(wrapper).display === 'block', + 'The panel must open after recovering from a page change' + ); + const picker = wrapper.querySelector('em-emoji-picker'); + assert( + picker && picker !== detachedPicker, + 'A picker detached from the document must be replaced' + ); + bodyReplacedButton.closeEmojiPicker(); + assert( + getComputedStyle(wrapper).display === 'none', + 'The recovered panel must still close' + ); + + // Losing the styles while the button stays connected must be repaired on the + // next open, not only when a button reconnects. + emojiPanelStyle()?.remove(); + await bodyReplacedButton.handleOpenEmojiPicker(new MouseEvent('click')); + assert(emojiPanelStyle(), 'Opening the panel must restore missing styles'); + assert( + getComputedStyle(wrapper).display === 'block', + 'The panel must open after its styles are restored' + ); + bodyReplacedButton.closeEmojiPicker(); +}); + +test('Reattaching the same button resets its expanded state', async () => { + document.body.innerHTML = '
'; + await import('../src/index.ts'); + const fixtures = document.querySelector('#fixtures'); + const button = document.createElement('emoji-button'); + fixtures.append(button); + await button.updateComplete; + + await button.handleOpenEmojiPicker(new MouseEvent('click')); + const trigger = button.shadowRoot.querySelector('button'); + await button.updateComplete; + assert( + trigger.getAttribute('aria-expanded') === 'true', + 'The open panel must mark the button as expanded' + ); + + button.remove(); + fixtures.append(button); + await button.updateComplete; + assert( + trigger.getAttribute('aria-expanded') === 'false', + 'Reattaching a button must reset its expanded state' + ); + + await button.handleOpenEmojiPicker(new MouseEvent('click')); + await button.updateComplete; + assert( + trigger.getAttribute('aria-expanded') === 'true' && + getComputedStyle(emojiPanelWrapper()).display === 'block', + 'The reattached button must open the panel on the first click' + ); + button.closeEmojiPicker(); +}); diff --git a/packages/comment-widget/tests/submission-storage.browser.test.js b/packages/comment-widget/tests/submission-storage.browser.test.js index e1d32d3..21582ce 100644 --- a/packages/comment-widget/tests/submission-storage.browser.test.js +++ b/packages/comment-widget/tests/submission-storage.browser.test.js @@ -3,6 +3,10 @@ import '../src/comment-form.ts'; import '../src/reply-form.ts'; import { mockApi, until } from './browser-helpers.js'; +// Exhausting the storage quota and mounting a full form is slower on CI +// runners, especially while other browser test files run in parallel. +const SLOW_UI_TIMEOUT = 10_000; + test.each(['disabled', 'denied', 'invalid JSON', 'null'])( 'anonymous form renders when account storage is %s', async (storage) => { @@ -60,7 +64,10 @@ test.each([ owner.currentUser = { metadata: { name: 'admin' }, spec: {} }; owner.comment = { metadata: { name: 'storage-test' } }; document.body.append(owner); - await until(() => owner.baseFormRef.value?.editorRef.value?.editor); + await until( + () => owner.baseFormRef.value?.editorRef.value?.editor, + SLOW_UI_TIMEOUT + ); const form = owner.baseFormRef.value; form.editorRef.value.editor.commands.setContent('

My comment

'); @@ -95,7 +102,10 @@ test.each([ target: form.shadowRoot.querySelector('form'), }) ).not.toThrow(); - await until(() => post.mock.calls.length === 1 && !owner.submitting); + await until( + () => post.mock.calls.length === 1 && !owner.submitting, + SLOW_UI_TIMEOUT + ); const endpoint = '/apis/api.halo.run/v1alpha1/comments'; expect(post.mock.calls[0][0]).toBe( tag === 'comment-form' ? endpoint : `${endpoint}/storage-test/reply` @@ -103,7 +113,7 @@ test.each([ expect(JSON.parse(post.mock.calls[0][1]).content).toBe(content); expect(form.editorRef.value.editor.getText()).toBe(''); expect(localStorage.getItem(form.getDraftSnapshot().key)).toBeNull(); - await until(() => !form.uploading); + await until(() => !form.uploading, SLOW_UI_TIMEOUT); await form.submitData(); expect(post).toHaveBeenCalledTimes(1); }