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
79 changes: 52 additions & 27 deletions packages/comment-widget/src/emoji-button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -104,26 +104,43 @@ 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');
}
},

hide() {
if (this.wrapper) {
this.wrapper.classList.remove('visible');
this.wrapper.style.display = 'none';
}
},

Expand Down Expand Up @@ -168,6 +185,7 @@ export class EmojiButton extends LitElement {
sharedEmojiPanel.activeButton = null;
sharedEmojiPanel.hide();
}
this.emojiPickerVisible = false;
super.disconnectedCallback();
}

Expand Down Expand Up @@ -217,6 +235,8 @@ export class EmojiButton extends LitElement {
return;
}

sharedEmojiPanel.init();

if (
sharedEmojiPanel.activeButton &&
sharedEmojiPanel.activeButton !== this
Expand All @@ -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();
}

Expand Down
7 changes: 4 additions & 3 deletions packages/comment-widget/tests/browser-helpers.js
Original file line number Diff line number Diff line change
@@ -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 }
);
}

Expand Down
8 changes: 7 additions & 1 deletion packages/comment-widget/tests/browser-setup.js
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -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 = '<main><div id="fixtures"></div></main>';
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();
});
27 changes: 27 additions & 0 deletions packages/comment-widget/tests/emoji-panel-race.browser.test.js
Original file line number Diff line number Diff line change
@@ -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 = '<main><div id="fixtures"></div></main>';
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'
);
});
150 changes: 150 additions & 0 deletions packages/comment-widget/tests/spa-emoji-panel.browser.test.js
Original file line number Diff line number Diff line change
@@ -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 = '<main><div id="fixtures"></div></main>';
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 = '<main><div id="fixtures"></div></main>';
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();
});
Loading
Loading