Skip to content

Commit

Permalink
feat(zbugs): Auto focus EmojiPicker
Browse files Browse the repository at this point in the history
This required some fun coding... MutationObserver to the
rescue.

I also filed an issue to support this better:

nolanlawson/emoji-picker-element#470
  • Loading branch information
arv committed Oct 29, 2024
1 parent 5ca7044 commit e7f952d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
9 changes: 3 additions & 6 deletions apps/zbugs/src/components/emoji-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,20 +148,17 @@ function normalizeEmoji(emoji: string): string {
}

function groupAndSortEmojis(emojis: Emoji[]): Record<string, Emoji[]> {
// Sort the emojis by creation time. Not sure how to sort this with ZQL.
const sortedEmojis = [...emojis].sort((a, b) => a.created - b.created);
const rv: Record<string, Emoji[]> = {};
for (const emoji of emojis) {
for (const emoji of sortedEmojis) {
const normalizedEmoji = normalizeEmoji(emoji.value);
if (!rv[normalizedEmoji]) {
rv[normalizedEmoji] = [];
}
rv[normalizedEmoji].push(emoji);
}

// Sort the emojis by creation time. Not sure how to sort this with ZQL.
for (const key in rv) {
rv[key] = rv[key].sort((a, b) => a.created - b.created);
}

return rv;
}

Expand Down
25 changes: 25 additions & 0 deletions apps/zbugs/src/components/emoji-picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,31 @@ export function EmojiPicker({onEmojiChange}: Props) {
el.addEventListener('emoji-click', onEmojiClick);
el.addEventListener('skin-tone-change', onSkinToneChange);
lastPicker.current = el;

// The emoji-picker-element does not allow auto focusing the search input
// when it's first rendered. We can work around this by observing the
// shadow DOM and focusing the search input when it's added to the DOM.
if (el.shadowRoot) {
const m = new MutationObserver(records => {
for (const record of records) {
for (const node of record.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
const search = (node as Element).querySelector('#search');
if (search) {
(search as HTMLElement).focus();
m.disconnect();
}
return;
}
}
}
});

m.observe(el.shadowRoot, {
subtree: true,
childList: true,
});
}
}
};

Expand Down

0 comments on commit e7f952d

Please sign in to comment.