Skip to content

Commit f41fd6b

Browse files
committed
refactor(react): replace emoji observer with button lifecycle registration
1 parent 2d8a6e6 commit f41fd6b

2 files changed

Lines changed: 78 additions & 50 deletions

File tree

‎packages/react/src/components/SuggestionMenu/EmojiPicker/InlineEmojiPicker.tsx‎

Lines changed: 62 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from "frimousse";
88
import {
99
createContext,
10+
useCallback,
1011
useContext,
1112
useEffect,
1213
useMemo,
@@ -19,6 +20,7 @@ import { useBlockNoteEditor } from "../../../hooks/useBlockNoteEditor.js";
1920
import { useEditorDOMElement } from "../../../hooks/useEditorDomElement.js";
2021
import { useDictionary } from "../../../i18n/dictionary.js";
2122
import { resolveBlockNoteEmojiData } from "../../../util/emojiPickerData.js";
23+
import { useMergeRefs } from "../../../util/mergeRefs.js";
2224
import { ActiveEmojiDisplay } from "../../Comments/FrimoussePicker.js";
2325
import { getSuggestionMenuItemId } from "../getSuggestionMenuItemId.js";
2426
import { useCloseSuggestionMenuNoItems } from "../hooks/useCloseSuggestionMenuNoItems.js";
@@ -31,20 +33,38 @@ import {
3133
} from "./emojiPickerModel.js";
3234

3335
const SelectedEmojiContext = createContext<string | undefined>(undefined);
36+
const RegisterEmojiContext = createContext<
37+
((emoji: string, button: HTMLButtonElement) => () => void) | undefined
38+
>(undefined);
3439
const INITIAL_POSITION: EmojiPosition = { row: 0, column: 0 };
3540

3641
function InlineEmojiPickerEmoji({
3742
emoji,
43+
ref,
3844
...props
3945
}: EmojiPickerListEmojiProps) {
4046
const selectedChar = useContext(SelectedEmojiContext);
4147
const selected = emoji.emoji === selectedChar;
48+
const registerEmoji = useContext(RegisterEmojiContext);
49+
const buttonRef = useRef<HTMLButtonElement>(null);
50+
const mergedRef = useMergeRefs([ref, buttonRef]);
51+
const columnIndex = props["aria-colindex"];
52+
53+
useEffect(() => {
54+
const button = buttonRef.current;
55+
// Frimousse also renders these components in a hidden sizing row.
56+
if (button?.closest("[aria-rowindex]")) {
57+
return registerEmoji?.(emoji.emoji, button);
58+
}
59+
return undefined;
60+
}, [emoji.emoji, columnIndex, registerEmoji]);
4261

4362
return (
4463
<button
4564
type="button"
4665
className="bn-frimousse-emoji"
4766
{...props}
67+
ref={mergedRef}
4868
data-selected={selected ? "" : undefined}
4969
// Editor navigation owns selection; Frimousse still handles pointer/clicks.
5070
data-active={undefined}
@@ -65,28 +85,17 @@ type ResolvedEmojiData = {
6585
};
6686

6787
function findButtonAtPosition(
68-
root: HTMLElement,
88+
buttons: Map<string, HTMLButtonElement>,
6989
position: EmojiPosition,
7090
emoji: string,
7191
): HTMLButtonElement | null {
72-
const row = root.querySelector<HTMLElement>(
73-
`[aria-rowindex="${position.row}"]`,
74-
);
75-
const button = row?.querySelectorAll<HTMLButtonElement>(
76-
".bn-frimousse-emoji",
77-
)[position.column];
78-
return button?.textContent === emoji ? button : null;
79-
}
80-
81-
function markButtonSelected(
82-
root: HTMLElement,
83-
button: HTMLButtonElement,
84-
selectedIndex: number,
85-
) {
86-
root
87-
.querySelectorAll<HTMLElement>("[id^='bn-suggestion-menu-item-']")
88-
.forEach((element) => element.removeAttribute("id"));
89-
button.id = getSuggestionMenuItemId(selectedIndex)!;
92+
const button = buttons.get(emoji);
93+
return button?.closest("[aria-rowindex]")?.getAttribute("aria-rowindex") ===
94+
String(position.row) &&
95+
button.getAttribute("aria-colindex") === String(position.column) &&
96+
button.textContent === emoji
97+
? button
98+
: null;
9099
}
91100

92101
function scrollViewportTo(
@@ -133,6 +142,21 @@ function InlineEmojiPickerContent(props: {
133142
useBlockNoteContext()!.setContentEditableProps!;
134143
const dict = useDictionary();
135144
const [skinTone] = useSkinTone();
145+
const buttons = useRef(new Map<string, HTMLButtonElement>());
146+
const syncSelectedButton = useRef<(() => void) | undefined>(undefined);
147+
const registerEmoji = useCallback(
148+
(emoji: string, button: HTMLButtonElement) => {
149+
buttons.current.set(emoji, button);
150+
syncSelectedButton.current?.();
151+
return () => {
152+
if (buttons.current.get(emoji) === button) {
153+
buttons.current.delete(emoji);
154+
syncSelectedButton.current?.();
155+
}
156+
};
157+
},
158+
[],
159+
);
136160

137161
const rows = useMemo(() => (data ? getEmojiPickerRows(data) : []), [data]);
138162
const [selection, setSelection] = useState({
@@ -174,8 +198,7 @@ function InlineEmojiPickerContent(props: {
174198
}, [setContentEditableProps]);
175199

176200
// Frimousse publishes its imperative Root ref after child layout effects.
177-
// Wait until passive effects to synchronize the mounted button and observe
178-
// asynchronous loading/virtualization.
201+
// Wait until passive effects before scrolling to an unmounted selection.
179202
useEffect(() => {
180203
function setActiveDescendant(id: string | undefined) {
181204
setContentEditableProps((props) =>
@@ -193,16 +216,20 @@ function InlineEmojiPickerContent(props: {
193216
// Scroll only once per selection change. Subsequent virtualization updates
194217
// must keep accessibility in sync without undoing manual mouse scrolling.
195218
let scrollPending = true;
196-
const pickerRoot = root;
197219
const selectedCharValue = selectedChar;
198220
const selectedIndexValue = selectedIndex;
221+
let activeButton: HTMLButtonElement | null = null;
199222

200223
function updateSelectedButton() {
201224
const btn = findButtonAtPosition(
202-
pickerRoot,
225+
buttons.current,
203226
selectedPosition,
204227
selectedCharValue,
205228
);
229+
if (activeButton !== btn) {
230+
activeButton?.removeAttribute("id");
231+
activeButton = btn;
232+
}
206233
if (!btn) {
207234
setActiveDescendant(undefined);
208235
return;
@@ -212,27 +239,21 @@ function InlineEmojiPickerContent(props: {
212239
scrollPending = false;
213240
btn.scrollIntoView({ block: "nearest", behavior: "instant" });
214241
}
215-
markButtonSelected(pickerRoot, btn, selectedIndexValue);
242+
btn.id = getSuggestionMenuItemId(selectedIndexValue)!;
216243
setActiveDescendant(btn.id);
217244
}
218245

219-
// Frimousse filters asynchronously and virtualizes rows independently of our
220-
// selection. Track mounted buttons to keep aria-activedescendant valid when
221-
// manual scrolling removes/restores them. Text changes also matter: changing
222-
// skin tone can reuse the same button instead of mounting a new one.
223-
const observer = new MutationObserver(updateSelectedButton);
224-
225-
observer.observe(root, {
226-
characterData: true,
227-
childList: true,
228-
subtree: true,
229-
});
230-
if (!findButtonAtPosition(root, selectedPosition, selectedChar)) {
246+
// Button effects report async filtering, virtualization and skin-tone changes.
247+
syncSelectedButton.current = updateSelectedButton;
248+
if (
249+
!findButtonAtPosition(buttons.current, selectedPosition, selectedChar)
250+
) {
231251
scrollViewportTo(root, selectedPosition, selectedRow.categoryIndex);
232252
}
233253
updateSelectedButton();
234254
return () => {
235-
observer.disconnect();
255+
syncSelectedButton.current = undefined;
256+
activeButton?.removeAttribute("id");
236257
setActiveDescendant(undefined);
237258
};
238259
}, [
@@ -268,10 +289,8 @@ function InlineEmojiPickerContent(props: {
268289
event.stopPropagation();
269290
// Frimousse schedules filtering asynchronously. Only insert once its
270291
// rendered grid has caught up with the keyboard model's selection.
271-
const root = rootRef.current;
272292
if (
273-
root &&
274-
findButtonAtPosition(root, selectedPosition, selectedChar)
293+
findButtonAtPosition(buttons.current, selectedPosition, selectedChar)
275294
) {
276295
insertEmoji(selectedChar);
277296
}
@@ -287,7 +306,6 @@ function InlineEmojiPickerContent(props: {
287306
editorDOMElement,
288307
insertEmoji,
289308
query,
290-
rootRef,
291309
selectedChar,
292310
selectedPosition,
293311
]);
@@ -307,7 +325,9 @@ function InlineEmojiPickerContent(props: {
307325
{dict.emoji_picker.search_no_results}
308326
</EmojiPicker.Empty>
309327
<SelectedEmojiContext.Provider value={selectedChar}>
310-
<EmojiPicker.List components={inlineEmojiPickerComponents} />
328+
<RegisterEmojiContext.Provider value={registerEmoji}>
329+
<EmojiPicker.List components={inlineEmojiPickerComponents} />
330+
</RegisterEmojiContext.Provider>
311331
</SelectedEmojiContext.Provider>
312332
</EmojiPicker.Viewport>
313333
<div className="bn-frimousse-footer">

‎tests/src/end-to-end/emojipicker/emojipicker.test.tsx‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,11 @@ describe("Check Emoji Picker Functionality", () => {
240240
const selected = document.querySelector<HTMLButtonElement>(
241241
".bn-frimousse-emoji[data-selected]",
242242
);
243-
if (selected?.textContent !== "🔟") {
243+
if (
244+
selected?.closest("[aria-rowindex]")?.getAttribute("aria-rowindex") !==
245+
"1" ||
246+
selected.getAttribute("aria-colindex") !== "3"
247+
) {
244248
throw new Error("Selection did not clamp to the partial row");
245249
}
246250
return selected;
@@ -300,7 +304,7 @@ describe("Check Emoji Picker Functionality", () => {
300304
if (key === "ArrowRight" || key === "ArrowDown") {
301305
await userEvent.keyboard("{ArrowRight}".repeat(8) + "{ArrowDown}");
302306
await waitForSelector(
303-
'.bn-frimousse-emoji[data-selected][aria-label="Keycap: 10"]',
307+
'[aria-rowindex="1"] .bn-frimousse-emoji[data-selected][aria-colindex="3"]',
304308
);
305309
}
306310
const offset = editorCaretOffset(editor);
@@ -377,15 +381,18 @@ describe("Check Emoji Picker Functionality", () => {
377381
const editor = await waitForSelector(EDITOR_SELECTOR);
378382
await userEvent.keyboard(":keycap");
379383
await waitForSelector(
380-
'.bn-frimousse-emoji[data-selected][aria-label="Keycap: #"]',
384+
'[aria-rowindex="0"] .bn-frimousse-emoji[data-selected][aria-colindex="0"]',
381385
);
382386
await userEvent.keyboard("{ArrowRight}");
383387

384388
await vi.waitFor(() => {
385389
const selected = document.querySelector(
386390
".bn-frimousse-emoji[data-selected]",
387391
);
388-
expect(selected?.getAttribute("aria-label")).toBe("Keycap: *");
392+
expect(selected?.getAttribute("aria-colindex")).toBe("1");
393+
expect(
394+
selected?.closest("[aria-rowindex]")?.getAttribute("aria-rowindex"),
395+
).toBe("0");
389396
expect(selected?.getAttribute("aria-selected")).toBe("true");
390397
expect(
391398
document.querySelectorAll('.bn-frimousse-emoji[aria-selected="true"]'),
@@ -394,7 +401,8 @@ describe("Check Emoji Picker Functionality", () => {
394401
});
395402

396403
// Query again after Frimousse's asynchronous filtering/virtualization.
397-
const firstSelector = '.bn-frimousse-emoji[aria-label="Keycap: #"]';
404+
const firstSelector =
405+
'[aria-rowindex="0"] .bn-frimousse-emoji[aria-colindex="0"]';
398406
const first = await waitForSelector(firstSelector);
399407
first.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
400408
await new Promise(requestAnimationFrame);
@@ -457,11 +465,11 @@ describe("Check Emoji Picker Functionality", () => {
457465
const viewport = await waitForSelector("[frimousse-viewport]");
458466
await waitForSelectedEmoji();
459467

460-
// Native scrolling, like a wheel/scrollbar, must not cause the DOM
461-
// observer to pull the unchanged keyboard selection back into view.
468+
// Native scrolling, like a wheel/scrollbar, must not pull the unchanged
469+
// keyboard selection back into view.
462470
async function scrollTo(top: number) {
463471
viewport.scrollTop = top;
464-
// Allow scroll events, virtualization, and its MutationObserver to run.
472+
// Allow scroll events, virtualization, and button effects to run.
465473
for (let frame = 0; frame < 3; frame++) {
466474
await new Promise(requestAnimationFrame);
467475
}

0 commit comments

Comments
 (0)