Skip to content

Commit

Permalink
Don't call selection change if range hasn't changed
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Feb 24, 2023
1 parent 0381c93 commit d16ec3e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 16 deletions.
1 change: 0 additions & 1 deletion packages/rich-text/src/component/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,6 @@ export function useRichText( {
applyRecord,
createRecord,
handleChange,
isSelected,
onSelectionChange,
} ),
useSelectionChangeCompat(),
Expand Down
19 changes: 4 additions & 15 deletions packages/rich-text/src/component/use-input-and-selection.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,11 @@ export function useInputAndSelection( props ) {

/**
* Syncs the selection to local state. A callback for the
* `selectionchange` native events.
*
* @param {Event} event
* `selectionchange` event.
*/
function handleSelectionChange( event ) {
const {
record,
applyRecord,
createRecord,
isSelected,
onSelectionChange,
} = propsRef.current;
function handleSelectionChange() {
const { record, applyRecord, createRecord, onSelectionChange } =
propsRef.current;

// Check if the implementor disabled editing. `contentEditable`
// does disable input, but not text selection, so we must ignore
Expand Down Expand Up @@ -178,10 +171,6 @@ export function useInputAndSelection( props ) {
return;
}

if ( event.type !== 'selectionchange' && ! isSelected ) {
return;
}

// In case of a keyboard event, ignore selection changes during
// composition.
if ( isComposing ) {
Expand Down
11 changes: 11 additions & 0 deletions packages/rich-text/src/component/use-selection-change-compat.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ import { useRefEffect } from '@wordpress/compose';
export function useSelectionChangeCompat() {
return useRefEffect( ( element ) => {
const { ownerDocument } = element;
const { defaultView } = ownerDocument;
const selection = defaultView.getSelection();

let range;

function getRange() {
return selection.rangeCount ? selection.getRangeAt( 0 ) : null;
}

function onDown( event ) {
const type = event.type === 'keydown' ? 'keyup' : 'pointerup';
Expand All @@ -30,12 +38,15 @@ export function useSelectionChangeCompat() {

function onUp() {
onCancel();
if ( range === getRange() ) return;
ownerDocument.dispatchEvent( new Event( 'selectionchange' ) );
}

ownerDocument.addEventListener( type, onUp );
ownerDocument.addEventListener( 'selectionchange', onCancel );
ownerDocument.addEventListener( 'input', onCancel );

range = getRange();
}

element.addEventListener( 'pointerdown', onDown );
Expand Down

0 comments on commit d16ec3e

Please sign in to comment.