To expand on your answer
We introduced commands as the primary mechanism to handle input events because we will prevent them by default via event.preventDefault
(and users may still want to listen to them or override them).
Focus was not strictly necessary but it felt natural to follow the same command pattern.
// Commands are subscriptions so the default state is important!
const [hasFocus, setHasFocus] = useState(() => {
return editor.getRootElement() === document.activeElement);
});
useLayoutEffect(() => {
setHasFocus(editor.getRootElement() === document.activeElement);
return mergeRegister(
editor.registerCommand(FOCUS_COMMAND, () => { ... }),
editor.registerCommand(BLUR_COMMAND, () => { ... }),
);
}, [editor]);
When possible you should avoid useState
altogether since React re-renders are expensive (if you don't need to display something different when this value changes).
Note that the EditorState does not have information on whether the input is focused.
editor.getRootElement() === document.activeElement
- is this a reliable way? If so, why use anything else? I was hesitant to use such solution, because root element has sub-elements and I'm not sure which one has focus 3. you advise againstuseState
, yet you use it in your example - so would you use it for focus, or not? 4. what doesmergeRegister
do? – Sugarcoat