Skip to content

Commit

Permalink
Fix Chrome quirk causing initial focus to fail
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Apr 20, 2021
1 parent 8e3b979 commit 71ae9a2
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/useEditable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,12 +453,12 @@ export const useEditable = (
element.focus();
};

const onFocus = () => {
state.position = getPosition(element);
};

const onBlur = () => {
state.position = null;
const onSelect = (event: Event) => {
// Chrome Quirk: The contenteditable may lose its selection immediately on first focus
state.position =
window.getSelection()!.rangeCount && event.target === element
? getPosition(element)
: null;
};

const onPaste = (event: HTMLElementEventMap['paste']) => {
Expand All @@ -469,16 +469,14 @@ export const useEditable = (
flushChanges();
};

document.addEventListener('selectstart', onSelect);
window.addEventListener('keydown', onKeyDown);
element.addEventListener('focus', onFocus);
element.addEventListener('blur', onBlur);
element.addEventListener('paste', onPaste);
element.addEventListener('keyup', onKeyUp);

return () => {
document.removeEventListener('selectstart', onSelect);
window.removeEventListener('keydown', onKeyDown);
element.removeEventListener('focus', onFocus);
element.removeEventListener('blur', onBlur);
element.removeEventListener('paste', onPaste);
element.removeEventListener('keyup', onKeyUp);
element.style.whiteSpace = prevWhiteSpace;
Expand Down

0 comments on commit 71ae9a2

Please sign in to comment.