Skip to content

Commit f6c5e2e

Browse files
author
Smartie
committed
Preserve explicit focus restoration during composer mount
Signed-off-by: Smartie <fb3185faacfc3760b6b4fe0085a8878d8dd537f7a7671c7d3184fe1aa1b04df4@buzz.block.builderlab.xyz>
1 parent 8aaa37c commit f6c5e2e

2 files changed

Lines changed: 44 additions & 2 deletions

File tree

‎src/features/messages/MessageComposer.test.tsx‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,11 +391,41 @@ it("autofocuses each selected conversation once without stealing focus on update
391391
expect(other).toHaveFocus();
392392
h.retarget({ channelId: "another-channel" });
393393
expect(h.input()).toHaveFocus();
394+
h.retarget({ channelId: "keyboard-navigation" });
395+
expect(h.input()).toHaveFocus();
394396
} finally {
395397
other.remove();
396398
}
397399
});
398400

401+
it("lets an explicit focus restoration in the mount commit win", () => {
402+
const h = mount();
403+
h.unmount();
404+
const target = document.createElement("button");
405+
document.body.append(target);
406+
function RestoreFocus() {
407+
useLayoutEffect(() => target.focus(), []);
408+
return null;
409+
}
410+
try {
411+
render(
412+
<>
413+
<MessageComposer
414+
session={h.session}
415+
scope="scope"
416+
channelId="channel"
417+
channelName="General"
418+
autoFocus
419+
/>
420+
<RestoreFocus />
421+
</>,
422+
);
423+
expect(target).toHaveFocus();
424+
} finally {
425+
target.remove();
426+
}
427+
});
428+
399429
it("leaves focus alone unless an enabled composer opts into mount focus", () => {
400430
const h = mount();
401431
expect(h.input()).not.toHaveFocus();

‎src/features/messages/MessageComposer.tsx‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,9 +205,21 @@ function Composer({
205205
const valueRef = useRef(value);
206206
const caret = useRef<number | undefined>(undefined);
207207
const input = useRef<ComposerInputElement>(null);
208-
const focusOnMount = useRef(autoFocus && !disabled);
208+
const focusOnMount = useRef(
209+
autoFocus && !disabled && typeof document !== "undefined"
210+
? document.activeElement
211+
: undefined,
212+
);
209213
useEffect(() => {
210-
if (focusOnMount.current) input.current?.focus();
214+
// A navigation/dialog owner may restore focus during this commit. Let that
215+
// explicit handoff win over the conversation's default initial focus.
216+
const previous = focusOnMount.current;
217+
if (
218+
previous &&
219+
(previous === document.activeElement ||
220+
(!previous.isConnected && document.activeElement === document.body))
221+
)
222+
input.current?.focus();
211223
}, []);
212224
const nonmembers = useNonmemberMentions(session, channelId, () =>
213225
input.current?.focus(),

0 commit comments

Comments
 (0)