Skip to content

Instantly share code, notes, and snippets.

@trueadm
Created March 6, 2021 13:20
Show Gist options
  • Save trueadm/d2035524ee98171eb4b768f03883a039 to your computer and use it in GitHub Desktop.
Save trueadm/d2035524ee98171eb4b768f03883a039 to your computer and use it in GitHub Desktop.
import {useEffect} from 'react';
const originalSetBaseAndExtent = Selection.prototype.setBaseAndExtent;
export default function useEventRecorder() {
useEffect(() => {
const records = [];
let isComposing = false;
const onSelectionChange = (event: Event) => {
if (isComposing) {
return;
}
const sel = window.getSelection();
for (let i = 0; i < records.length; i++) {
const record = records[i];
if (
sel.anchorNode === record.anchorNode &&
sel.focusNode === record.focusNode &&
sel.anchorOffset === record.anchorOffset &&
sel.focusOffset === record.focusOffset
) {
console.log('Imperative selection', record, performance.now());
records.splice(i, 1);
return;
}
}
console.log('User selection', sel, performance.now());
};
const onCompositionStart = () => {
isComposing = true;
}
const onCompositionEnd = () => {
window.setTimeout(() => {
isComposing = false;
})
}
Selection.prototype.setBaseAndExtent = function(anchorNode, anchorOffset, focusNode, focusOffset) {
records.push({
anchorNode,
anchorOffset,
focusNode,
focusOffset,
});
return originalSetBaseAndExtent.call(
this,
anchorNode,
anchorOffset,
focusNode,
focusOffset,
);
}
document.addEventListener('selectionchange', onSelectionChange, true);
document.addEventListener('compositionstart', onCompositionStart, true);
document.addEventListener('compositionend', onCompositionEnd);
return () => {
Selection.prototype.setBaseAndExtent = originalSetBaseAndExtent;
document.removeEventListener('selectionchange', onSelectionChange, true);
document.removeEventListener('compositionstart', onCompositionStart, true);
document.removeEventListener('compositionend', onCompositionEnd);
};
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment