From 36a92d332fd9f762e40279f5583a940bf61d0780 Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Wed, 10 Jan 2024 21:08:02 +0000 Subject: [PATCH] Expose API to allow triggering the anchor to be recomputed --- packages/rich-text/src/component/use-anchor.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/rich-text/src/component/use-anchor.js b/packages/rich-text/src/component/use-anchor.js index 7ea3281cb60d3..ce571858a9b99 100644 --- a/packages/rich-text/src/component/use-anchor.js +++ b/packages/rich-text/src/component/use-anchor.js @@ -1,7 +1,7 @@ /** * WordPress dependencies */ -import { useState, useLayoutEffect } from '@wordpress/element'; +import { useState, useLayoutEffect, useCallback } from '@wordpress/element'; /** @typedef {import('../register-format-type').WPFormat} WPFormat */ /** @typedef {import('../types').RichTextValue} RichTextValue */ @@ -142,17 +142,15 @@ export function useAnchor( { editableContentElement, settings = {} } ) { getAnchor( editableContentElement, tagName, className ) ); + const callback = useCallback( () => { + setAnchor( getAnchor( editableContentElement, tagName, className ) ); + }, [ className, editableContentElement, tagName ] ); + useLayoutEffect( () => { if ( ! editableContentElement ) return; const { ownerDocument } = editableContentElement; - function callback() { - setAnchor( - getAnchor( editableContentElement, tagName, className ) - ); - } - function attach() { ownerDocument.addEventListener( 'selectionchange', callback ); } @@ -174,7 +172,8 @@ export function useAnchor( { editableContentElement, settings = {} } ) { editableContentElement.removeEventListener( 'focusin', attach ); editableContentElement.removeEventListener( 'focusout', detach ); }; - }, [ editableContentElement, tagName, className ] ); + }, [ editableContentElement, tagName, className, callback ] ); + anchor.update = callback; return anchor; }