From 282b986432e266fc712a8354669ca6fe5fb3dea4 Mon Sep 17 00:00:00 2001 From: Marin Atanasov <8436925+tyxla@users.noreply.github.com> Date: Wed, 21 Aug 2024 18:45:01 +0300 Subject: [PATCH] Rename refs to fix tons of 'Mutating a value' errors --- .../src/components/block-draggable/index.js | 8 +- .../use-scroll-when-dragging.js | 50 +++++------ .../src/components/block-lock/toolbar.js | 6 +- .../block-tools/block-toolbar-popover.js | 8 +- .../src/components/iframe/index.js | 10 +-- .../use-inner-block-template-sync.js | 6 +- .../components/inserter-list-item/index.js | 8 +- .../components/inserter/media-tab/hooks.js | 6 +- .../src/components/link-control/index.js | 14 ++-- .../src/components/provider/use-block-sync.js | 40 ++++----- .../rich-text/use-mark-persistent.js | 10 +-- .../components/writing-flow/use-tab-nav.js | 8 +- .../src/hooks/spacing-visualizer.js | 6 +- .../block-editor/src/hooks/use-zoom-out.js | 14 ++-- packages/block-library/src/freeform/edit.js | 8 +- .../navigation/edit/unsaved-inner-blocks.js | 8 +- .../block-library/src/social-links/edit.js | 6 +- packages/block-library/src/utils/hooks.js | 22 ++--- .../commands/src/components/command-menu.js | 8 +- packages/commands/src/hooks/use-command.js | 6 +- .../src/angle-picker-control/angle-circle.tsx | 20 +++-- .../components/src/clipboard-button/index.tsx | 12 +-- .../src/color-picker/color-copy-button.tsx | 18 ++-- .../gradient-bar/control-points.tsx | 20 ++--- packages/components/src/draggable/index.tsx | 8 +- .../src/input-control/reducer/reducer.ts | 23 +++--- .../components/src/input-control/utils.ts | 6 +- packages/components/src/modal/index.tsx | 10 +-- packages/components/src/navigation/index.tsx | 8 +- .../components/src/palette-edit/index.tsx | 4 +- .../src/slot-fill/bubbles-virtually/fill.tsx | 8 +- packages/components/src/snackbar/index.tsx | 8 +- packages/components/src/tabs/index.tsx | 12 ++- .../toggle-group-control/utils.ts | 14 ++-- .../src/tools-panel/tools-panel/hook.ts | 12 +-- .../src/utils/hooks/use-update-effect.js | 8 +- .../src/hooks/use-copy-on-click/index.js | 10 +-- .../src/hooks/use-focus-on-mount/index.js | 8 +- .../src/hooks/use-focus-outside/index.ts | 22 ++--- .../src/hooks/use-keyboard-shortcut/index.js | 6 +- .../compose/src/hooks/use-merge-refs/index.js | 28 ++++--- .../compose/src/hooks/use-ref-effect/index.ts | 8 +- .../src/hooks/use-resize-observer/index.tsx | 26 +++--- .../use-dispatch/use-dispatch-with-map.js | 8 +- .../dataviews-bulk-actions-toolbar/index.tsx | 12 +-- .../src/dataviews-layouts/table/index.tsx | 6 +- .../editor-initialization/listener-hooks.js | 8 +- .../use-sync-canvas-mode-with-url.js | 27 +++--- .../src/components/document-bar/index.js | 8 +- .../local-autosave-monitor/index.js | 12 +-- .../src/components/preview-dropdown/index.js | 10 +-- .../components/complementary-area/index.js | 22 ++--- packages/rich-text/src/component/index.js | 82 ++++++++++--------- 53 files changed, 382 insertions(+), 364 deletions(-) diff --git a/packages/block-editor/src/components/block-draggable/index.js b/packages/block-editor/src/components/block-draggable/index.js index e1afc1f251384..5bb328f7cf9f5 100644 --- a/packages/block-editor/src/components/block-draggable/index.js +++ b/packages/block-editor/src/components/block-draggable/index.js @@ -62,7 +62,7 @@ const BlockDraggable = ( { [ clientIds ] ); - const isDragging = useRef( false ); + const isDraggingRef = useRef( false ); const [ startScrolling, scrollOnDragOver, stopScrolling ] = useScrollWhenDragging(); @@ -75,7 +75,7 @@ const BlockDraggable = ( { // Stop dragging blocks if the block draggable is unmounted. useEffect( () => { return () => { - if ( isDragging.current ) { + if ( isDraggingRef.current ) { stopDraggingBlocks(); } }; @@ -193,7 +193,7 @@ const BlockDraggable = ( { // frame to enable dragging. window.requestAnimationFrame( () => { startDraggingBlocks( clientIds ); - isDragging.current = true; + isDraggingRef.current = true; startScrolling( event ); @@ -205,7 +205,7 @@ const BlockDraggable = ( { onDragOver={ scrollOnDragOver } onDragEnd={ () => { stopDraggingBlocks(); - isDragging.current = false; + isDraggingRef.current = false; stopScrolling(); diff --git a/packages/block-editor/src/components/block-draggable/use-scroll-when-dragging.js b/packages/block-editor/src/components/block-draggable/use-scroll-when-dragging.js index a01db4927b652..515f3002de934 100644 --- a/packages/block-editor/src/components/block-draggable/use-scroll-when-dragging.js +++ b/packages/block-editor/src/components/block-draggable/use-scroll-when-dragging.js @@ -18,36 +18,36 @@ const VELOCITY_MULTIPLIER = * and `onDragEnd` events respectively. */ export default function useScrollWhenDragging() { - const dragStartY = useRef( null ); - const velocityY = useRef( null ); - const scrollParentY = useRef( null ); - const scrollEditorInterval = useRef( null ); + const dragStartYRef = useRef( null ); + const velocityYRef = useRef( null ); + const scrollParentYRef = useRef( null ); + const scrollEditorIntervalRef = useRef( null ); // Clear interval when unmounting. useEffect( () => () => { - if ( scrollEditorInterval.current ) { - clearInterval( scrollEditorInterval.current ); - scrollEditorInterval.current = null; + if ( scrollEditorIntervalRef.current ) { + clearInterval( scrollEditorIntervalRef.current ); + scrollEditorIntervalRef.current = null; } }, [] ); const startScrolling = useCallback( ( event ) => { - dragStartY.current = event.clientY; + dragStartYRef.current = event.clientY; // Find nearest parent(s) to scroll. - scrollParentY.current = getScrollContainer( event.target ); + scrollParentYRef.current = getScrollContainer( event.target ); - scrollEditorInterval.current = setInterval( () => { - if ( scrollParentY.current && velocityY.current ) { + scrollEditorIntervalRef.current = setInterval( () => { + if ( scrollParentYRef.current && velocityYRef.current ) { const newTop = - scrollParentY.current.scrollTop + velocityY.current; + scrollParentYRef.current.scrollTop + velocityYRef.current; // Setting `behavior: 'smooth'` as a scroll property seems to hurt performance. // Better to use a small scroll interval. - scrollParentY.current.scroll( { + scrollParentYRef.current.scroll( { top: newTop, } ); } @@ -55,14 +55,14 @@ export default function useScrollWhenDragging() { }, [] ); const scrollOnDragOver = useCallback( ( event ) => { - if ( ! scrollParentY.current ) { + if ( ! scrollParentYRef.current ) { return; } - const scrollParentHeight = scrollParentY.current.offsetHeight; + const scrollParentHeight = scrollParentYRef.current.offsetHeight; const offsetDragStartPosition = - dragStartY.current - scrollParentY.current.offsetTop; + dragStartYRef.current - scrollParentYRef.current.offsetTop; const offsetDragPosition = - event.clientY - scrollParentY.current.offsetTop; + event.clientY - scrollParentYRef.current.offsetTop; if ( event.clientY > offsetDragStartPosition ) { // User is dragging downwards. @@ -82,7 +82,7 @@ export default function useScrollWhenDragging() { moveableDistance === 0 || dragDistance === 0 ? 0 : dragDistance / moveableDistance; - velocityY.current = VELOCITY_MULTIPLIER * distancePercentage; + velocityYRef.current = VELOCITY_MULTIPLIER * distancePercentage; } else if ( event.clientY < offsetDragStartPosition ) { // User is dragging upwards. const moveableDistance = Math.max( @@ -99,19 +99,19 @@ export default function useScrollWhenDragging() { moveableDistance === 0 || dragDistance === 0 ? 0 : dragDistance / moveableDistance; - velocityY.current = -VELOCITY_MULTIPLIER * distancePercentage; + velocityYRef.current = -VELOCITY_MULTIPLIER * distancePercentage; } else { - velocityY.current = 0; + velocityYRef.current = 0; } }, [] ); const stopScrolling = () => { - dragStartY.current = null; - scrollParentY.current = null; + dragStartYRef.current = null; + scrollParentYRef.current = null; - if ( scrollEditorInterval.current ) { - clearInterval( scrollEditorInterval.current ); - scrollEditorInterval.current = null; + if ( scrollEditorIntervalRef.current ) { + clearInterval( scrollEditorIntervalRef.current ); + scrollEditorIntervalRef.current = null; } }; diff --git a/packages/block-editor/src/components/block-lock/toolbar.js b/packages/block-editor/src/components/block-lock/toolbar.js index 29bf0cdd6a60c..12376a7b56a5e 100644 --- a/packages/block-editor/src/components/block-lock/toolbar.js +++ b/packages/block-editor/src/components/block-lock/toolbar.js @@ -20,7 +20,7 @@ export default function BlockLockToolbar( { clientId } ) { false ); - const hasLockButtonShown = useRef( false ); + const hasLockButtonShownRef = useRef( false ); // If the block lock button has been shown, we don't want to remove it // from the toolbar until the toolbar is rendered again without it. @@ -29,11 +29,11 @@ export default function BlockLockToolbar( { clientId } ) { // whence it came, and to do that, we need to leave the button in the toolbar. useEffect( () => { if ( isLocked ) { - hasLockButtonShown.current = true; + hasLockButtonShownRef.current = true; } }, [ isLocked ] ); - if ( ! isLocked && ! hasLockButtonShown.current ) { + if ( ! isLocked && ! hasLockButtonShownRef.current ) { return null; } diff --git a/packages/block-editor/src/components/block-tools/block-toolbar-popover.js b/packages/block-editor/src/components/block-tools/block-toolbar-popover.js index eef5b5afca304..8428222268408 100644 --- a/packages/block-editor/src/components/block-tools/block-toolbar-popover.js +++ b/packages/block-editor/src/components/block-tools/block-toolbar-popover.js @@ -36,15 +36,15 @@ export default function BlockToolbarPopover( { }, [ clientId ] ); const { stopTyping } = useDispatch( blockEditorStore ); - const isToolbarForced = useRef( false ); + const isToolbarForcedRef = useRef( false ); useShortcut( 'core/block-editor/focus-toolbar', () => { - isToolbarForced.current = true; + isToolbarForcedRef.current = true; stopTyping( true ); } ); useEffect( () => { - isToolbarForced.current = false; + isToolbarForcedRef.current = false; } ); const popoverProps = useBlockToolbarPopoverProps( { @@ -66,7 +66,7 @@ export default function BlockToolbarPopover( { { if ( ! isZoomedOut ) { - prevContainerWidth.current = containerWidth; + prevContainerWidthRef.current = containerWidth; } }, [ containerWidth, isZoomedOut ] ); @@ -310,7 +310,7 @@ function Iframe( { '--wp-block-editor-iframe-zoom-out-scale', scale === 'default' ? Math.min( containerWidth, maxWidth ) / - prevContainerWidth.current + prevContainerWidthRef.current : scale ); iframeDocument.documentElement.style.setProperty( @@ -331,7 +331,7 @@ function Iframe( { ); iframeDocument.documentElement.style.setProperty( '--wp-block-editor-iframe-zoom-out-prev-container-width', - `${ prevContainerWidth.current }px` + `${ prevContainerWidthRef.current }px` ); return () => { @@ -456,7 +456,7 @@ function Iframe( { '--wp-block-editor-iframe-zoom-out-container-width': isZoomedOut && `${ containerWidth }px`, '--wp-block-editor-iframe-zoom-out-prev-container-width': - isZoomedOut && `${ prevContainerWidth.current }px`, + isZoomedOut && `${ prevContainerWidthRef.current }px`, } } > { iframe } diff --git a/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js b/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js index 020b391039a01..fd801779372aa 100644 --- a/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js +++ b/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js @@ -52,7 +52,7 @@ export default function useInnerBlockTemplateSync( useDispatch( blockEditorStore ); // Maintain a reference to the previous value so we can do a deep equality check. - const existingTemplate = useRef( null ); + const existingTemplateRef = useRef( null ); useLayoutEffect( () => { let isCancelled = false; @@ -76,14 +76,14 @@ export default function useInnerBlockTemplateSync( const hasTemplateChanged = ! fastDeepEqual( template, - existingTemplate.current + existingTemplateRef.current ); if ( ! shouldApplyTemplate || ! hasTemplateChanged ) { return; } - existingTemplate.current = template; + existingTemplateRef.current = template; const nextBlocks = synchronizeBlocksWithTemplate( currentInnerBlocks, template diff --git a/packages/block-editor/src/components/inserter-list-item/index.js b/packages/block-editor/src/components/inserter-list-item/index.js index 4a0ef102e84b0..c5bf211070262 100644 --- a/packages/block-editor/src/components/inserter-list-item/index.js +++ b/packages/block-editor/src/components/inserter-list-item/index.js @@ -32,7 +32,7 @@ function InserterListItem( { isDraggable, ...props } ) { - const isDragging = useRef( false ); + const isDraggingRef = useRef( false ); const itemIconStyle = item.icon ? { backgroundColor: item.icon.background, @@ -70,14 +70,14 @@ function InserterListItem( { ) } draggable={ draggable } onDragStart={ ( event ) => { - isDragging.current = true; + isDraggingRef.current = true; if ( onDragStart ) { onHover( null ); onDragStart( event ); } } } onDragEnd={ ( event ) => { - isDragging.current = false; + isDraggingRef.current = false; if ( onDragEnd ) { onDragEnd( event ); } @@ -110,7 +110,7 @@ function InserterListItem( { } } } onMouseEnter={ () => { - if ( isDragging.current ) { + if ( isDraggingRef.current ) { return; } onHover( item ); diff --git a/packages/block-editor/src/components/inserter/media-tab/hooks.js b/packages/block-editor/src/components/inserter/media-tab/hooks.js index 3a4c8fa9da7df..694b321832422 100644 --- a/packages/block-editor/src/components/inserter/media-tab/hooks.js +++ b/packages/block-editor/src/components/inserter/media-tab/hooks.js @@ -31,18 +31,18 @@ export function useMediaResults( category, query = {} ) { // In the future we could use AbortController to cancel previous // requests, but we don't for now as it involves adding support // for this to `core-data` package. - const lastRequest = useRef(); + const lastRequestRef = useRef(); useEffect( () => { ( async () => { const key = JSON.stringify( { category: category.name, ...query, } ); - lastRequest.current = key; + lastRequestRef.current = key; setIsLoading( true ); setMediaList( [] ); // Empty the previous results. const _media = await category.fetch?.( query ); - if ( key === lastRequest.current ) { + if ( key === lastRequestRef.current ) { setMediaList( _media ); setIsLoading( false ); } diff --git a/packages/block-editor/src/components/link-control/index.js b/packages/block-editor/src/components/link-control/index.js index 576556519fb2f..85626e50fcf2a 100644 --- a/packages/block-editor/src/components/link-control/index.js +++ b/packages/block-editor/src/components/link-control/index.js @@ -180,10 +180,10 @@ function LinkControl( { // Therefore a local state is used as a fallback. const isSettingsOpen = advancedSettingsPreference || settingsOpen; - const isMounting = useRef( true ); + const isMountingRef = useRef( true ); const wrapperNode = useRef(); const textInputRef = useRef(); - const isEndingEditWithFocus = useRef( false ); + const isEndingEditWithFocusRef = useRef( false ); const settingsKeys = settings.map( ( { id } ) => id ); @@ -219,7 +219,7 @@ function LinkControl( { // We don't auto focus into the Link UI on mount // because otherwise using the keyboard to select text // *within* the link format is not possible. - if ( isMounting.current ) { + if ( isMountingRef.current ) { return; } @@ -234,16 +234,16 @@ function LinkControl( { nextFocusTarget.focus(); - isEndingEditWithFocus.current = false; + isEndingEditWithFocusRef.current = false; }, [ isEditingLink, isCreatingPage ] ); // The component mounting reference is maintained separately // to correctly reset values in `StrictMode`. useEffect( () => { - isMounting.current = false; + isMountingRef.current = false; return () => { - isMounting.current = true; + isMountingRef.current = true; }; }, [] ); @@ -254,7 +254,7 @@ function LinkControl( { * the next render, if focus was within the wrapper when editing finished. */ const stopEditing = () => { - isEndingEditWithFocus.current = !! wrapperNode.current?.contains( + isEndingEditWithFocusRef.current = !! wrapperNode.current?.contains( wrapperNode.current.ownerDocument.activeElement ); diff --git a/packages/block-editor/src/components/provider/use-block-sync.js b/packages/block-editor/src/components/provider/use-block-sync.js index 4e9cc9784554f..fa148109d510f 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.js +++ b/packages/block-editor/src/components/provider/use-block-sync.js @@ -91,8 +91,8 @@ export default function useBlockSync( { [ clientId ] ); - const pendingChanges = useRef( { incoming: null, outgoing: [] } ); - const subscribed = useRef( false ); + const pendingChangesRef = useRef( { incoming: null, outgoing: [] } ); + const subscribedRef = useRef( false ); const setControlledBlocks = () => { if ( ! controlledBlocks ) { @@ -113,15 +113,15 @@ export default function useBlockSync( { const storeBlocks = controlledBlocks.map( ( block ) => cloneBlock( block ) ); - if ( subscribed.current ) { - pendingChanges.current.incoming = storeBlocks; + if ( subscribedRef.current ) { + pendingChangesRef.current.incoming = storeBlocks; } __unstableMarkNextChangeAsNotPersistent(); replaceInnerBlocks( clientId, storeBlocks ); } ); } else { - if ( subscribed.current ) { - pendingChanges.current.incoming = controlledBlocks; + if ( subscribedRef.current ) { + pendingChangesRef.current.incoming = controlledBlocks; } resetBlocks( controlledBlocks ); } @@ -153,7 +153,7 @@ export default function useBlockSync( { // Determine if blocks need to be reset when they change. useEffect( () => { - if ( pendingChanges.current.outgoing.includes( controlledBlocks ) ) { + if ( pendingChangesRef.current.outgoing.includes( controlledBlocks ) ) { // Skip block reset if the value matches expected outbound sync // triggered by this component by a preceding change detection. // Only skip if the value matches expectation, since a reset should @@ -161,18 +161,18 @@ export default function useBlockSync( { // to allow that the consumer may apply modifications to reflect // back on the editor. if ( - pendingChanges.current.outgoing[ - pendingChanges.current.outgoing.length - 1 + pendingChangesRef.current.outgoing[ + pendingChangesRef.current.outgoing.length - 1 ] === controlledBlocks ) { - pendingChanges.current.outgoing = []; + pendingChangesRef.current.outgoing = []; } } else if ( getBlocks( clientId ) !== controlledBlocks ) { // Reset changing value in all other cases than the sync described // above. Since this can be reached in an update following an out- // bound sync, unset the outbound value to avoid considering it in // subsequent renders. - pendingChanges.current.outgoing = []; + pendingChangesRef.current.outgoing = []; setControlledBlocks(); if ( controlledSelection ) { @@ -185,19 +185,19 @@ export default function useBlockSync( { } }, [ controlledBlocks, clientId ] ); - const isMounted = useRef( false ); + const isMountedRef = useRef( false ); useEffect( () => { // On mount, controlled blocks are already set in the effect above. - if ( ! isMounted.current ) { - isMounted.current = true; + if ( ! isMountedRef.current ) { + isMountedRef.current = true; return; } // When the block becomes uncontrolled, it means its inner state has been reset // we need to take the blocks again from the external value property. if ( ! isControlled ) { - pendingChanges.current.outgoing = []; + pendingChangesRef.current.outgoing = []; setControlledBlocks(); } }, [ isControlled ] ); @@ -214,7 +214,7 @@ export default function useBlockSync( { let isPersistent = isLastBlockChangePersistent(); let previousAreBlocksDifferent = false; - subscribed.current = true; + subscribedRef.current = true; const unsubscribe = registry.subscribe( () => { // Sometimes, when changing block lists, lingering subscriptions // might trigger before they are cleaned up. If the block for which @@ -243,10 +243,10 @@ export default function useBlockSync( { blocks = newBlocks; if ( areBlocksDifferent && - ( pendingChanges.current.incoming || + ( pendingChangesRef.current.incoming || __unstableIsLastBlockChangeIgnored() ) ) { - pendingChanges.current.incoming = null; + pendingChangesRef.current.incoming = null; isPersistent = newIsPersistent; return; } @@ -266,7 +266,7 @@ export default function useBlockSync( { // We need to be aware that it was caused by an outgoing change // so that we do not treat it as an incoming change later on, // which would cause a block reset. - pendingChanges.current.outgoing.push( blocks ); + pendingChangesRef.current.outgoing.push( blocks ); // Inform the controlling entity that changes have been made to // the block-editor store they should be aware about. @@ -286,7 +286,7 @@ export default function useBlockSync( { }, blockEditorStore ); return () => { - subscribed.current = false; + subscribedRef.current = false; unsubscribe(); }; }, [ registry, clientId ] ); diff --git a/packages/block-editor/src/components/rich-text/use-mark-persistent.js b/packages/block-editor/src/components/rich-text/use-mark-persistent.js index 10e157452fbe2..0be460fedd92f 100644 --- a/packages/block-editor/src/components/rich-text/use-mark-persistent.js +++ b/packages/block-editor/src/components/rich-text/use-mark-persistent.js @@ -10,7 +10,7 @@ import { useDispatch } from '@wordpress/data'; import { store as blockEditorStore } from '../../store'; export function useMarkPersistent( { html, value } ) { - const previousText = useRef(); + const previousTextRef = useRef(); const hasActiveFormats = !! value.activeFormats?.length; const { __unstableMarkLastChangeAsPersistent } = useDispatch( blockEditorStore ); @@ -18,18 +18,18 @@ export function useMarkPersistent( { html, value } ) { // Must be set synchronously to make sure it applies to the last change. useLayoutEffect( () => { // Ignore mount. - if ( ! previousText.current ) { - previousText.current = value.text; + if ( ! previousTextRef.current ) { + previousTextRef.current = value.text; return; } // Text input, so don't create an undo level for every character. // Create an undo level after 1 second of no input. - if ( previousText.current !== value.text ) { + if ( previousTextRef.current !== value.text ) { const timeout = window.setTimeout( () => { __unstableMarkLastChangeAsPersistent(); }, 1000 ); - previousText.current = value.text; + previousTextRef.current = value.text; return () => { window.clearTimeout( timeout ); }; diff --git a/packages/block-editor/src/components/writing-flow/use-tab-nav.js b/packages/block-editor/src/components/writing-flow/use-tab-nav.js index 1394fbbd37e25..b321d7c8d2995 100644 --- a/packages/block-editor/src/components/writing-flow/use-tab-nav.js +++ b/packages/block-editor/src/components/writing-flow/use-tab-nav.js @@ -36,12 +36,12 @@ export default function useTabNav() { // Reference that holds the a flag for enabling or disabling // capturing on the focus capture elements. - const noCapture = useRef(); + const noCaptureRef = useRef(); function onFocusCapture( event ) { // Do not capture incoming focus if set by us in WritingFlow. - if ( noCapture.current ) { - noCapture.current = null; + if ( noCaptureRef.current ) { + noCaptureRef.current = null; } else if ( hasMultiSelection() ) { container.current.focus(); } else if ( getSelectedBlockClientId() ) { @@ -165,7 +165,7 @@ export default function useTabNav() { // Disable focus capturing on the focus capture element, so it // doesn't refocus this block and so it allows default behaviour // (moving focus to the next tabbable element). - noCapture.current = true; + noCaptureRef.current = true; // Focusing the focus capture element, which is located above and // below the editor, should not scroll the page all the way up or diff --git a/packages/block-editor/src/hooks/spacing-visualizer.js b/packages/block-editor/src/hooks/spacing-visualizer.js index 52141d87be715..2f0abe8e0d293 100644 --- a/packages/block-editor/src/hooks/spacing-visualizer.js +++ b/packages/block-editor/src/hooks/spacing-visualizer.js @@ -36,16 +36,16 @@ function SpacingVisualizer( { clientId, value, computeStyle, forceShow } ) { ); }, [ blockElement, value ] ); - const previousValue = useRef( value ); + const previousValueRef = useRef( value ); const [ isActive, setIsActive ] = useState( false ); useEffect( () => { - if ( isShallowEqual( value, previousValue.current ) || forceShow ) { + if ( isShallowEqual( value, previousValueRef.current ) || forceShow ) { return; } setIsActive( true ); - previousValue.current = value; + previousValueRef.current = value; const timeout = setTimeout( () => { setIsActive( false ); diff --git a/packages/block-editor/src/hooks/use-zoom-out.js b/packages/block-editor/src/hooks/use-zoom-out.js index d0d7d0fd4d71c..d7e21ec1be057 100644 --- a/packages/block-editor/src/hooks/use-zoom-out.js +++ b/packages/block-editor/src/hooks/use-zoom-out.js @@ -18,22 +18,22 @@ export function useZoomOut( zoomOut = true ) { const { __unstableSetEditorMode } = useDispatch( blockEditorStore ); const { __unstableGetEditorMode } = useSelect( blockEditorStore ); - const originalEditingMode = useRef( null ); + const originalEditingModeRef = useRef( null ); const mode = __unstableGetEditorMode(); useEffect( () => { // Only set this on mount so we know what to return to when we unmount. - if ( ! originalEditingMode.current ) { - originalEditingMode.current = mode; + if ( ! originalEditingModeRef.current ) { + originalEditingModeRef.current = mode; } return () => { // We need to use __unstableGetEditorMode() here and not `mode`, as mode may not update on unmount if ( __unstableGetEditorMode() === 'zoom-out' && - __unstableGetEditorMode() !== originalEditingMode.current + __unstableGetEditorMode() !== originalEditingModeRef.current ) { - __unstableSetEditorMode( originalEditingMode.current ); + __unstableSetEditorMode( originalEditingModeRef.current ); } }; }, [] ); @@ -45,9 +45,9 @@ export function useZoomOut( zoomOut = true ) { } else if ( ! zoomOut && __unstableGetEditorMode() === 'zoom-out' && - originalEditingMode.current !== mode + originalEditingModeRef.current !== mode ) { - __unstableSetEditorMode( originalEditingMode.current ); + __unstableSetEditorMode( originalEditingModeRef.current ); } }, [ __unstableGetEditorMode, __unstableSetEditorMode, zoomOut ] ); // Mode is deliberately excluded from the dependencies so that the effect does not run when mode changes. } diff --git a/packages/block-library/src/freeform/edit.js b/packages/block-library/src/freeform/edit.js index 9e432992a3005..b0ba245a6e702 100644 --- a/packages/block-library/src/freeform/edit.js +++ b/packages/block-library/src/freeform/edit.js @@ -75,10 +75,10 @@ function ClassicEdit( { onReplace, } ) { const { getMultiSelectedBlockClientIds } = useSelect( blockEditorStore ); - const didMount = useRef( false ); + const didMountRef = useRef( false ); useEffect( () => { - if ( ! didMount.current ) { + if ( ! didMountRef.current ) { return; } @@ -96,7 +96,7 @@ function ClassicEdit( { useEffect( () => { const { baseURL, suffix } = window.wpEditorL10n.tinymce; - didMount.current = true; + didMountRef.current = true; window.tinymce.EditorManager.overrideDefaults( { base_url: baseURL, @@ -230,7 +230,7 @@ function ClassicEdit( { onReadyStateChange ); wp.oldEditor.remove( `editor-${ clientId }` ); - didMount.current = false; + didMountRef.current = false; }; }, [] ); diff --git a/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js b/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js index e5afbc66dd8b5..6cdcaa46f2bac 100644 --- a/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js +++ b/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js @@ -20,13 +20,13 @@ export default function UnsavedInnerBlocks( { createNavigationMenu, hasSelection, } ) { - const originalBlocks = useRef(); + const originalBlocksRef = useRef(); useEffect( () => { // Initially store the uncontrolled inner blocks for // dirty state comparison. - if ( ! originalBlocks?.current ) { - originalBlocks.current = blocks; + if ( ! originalBlocksRef?.current ) { + originalBlocksRef.current = blocks; } }, [ blocks ] ); @@ -38,7 +38,7 @@ export default function UnsavedInnerBlocks( { // entity records. As a result we need to perform a deep equality check skipping // the page list's inner blocks. const innerBlocksAreDirty = areBlocksDirty( - originalBlocks?.current, + originalBlocksRef?.current, blocks ); diff --git a/packages/block-library/src/social-links/edit.js b/packages/block-library/src/social-links/edit.js index bea4a4e6721ec..1bd943de7fb8e 100644 --- a/packages/block-library/src/social-links/edit.js +++ b/packages/block-library/src/social-links/edit.js @@ -59,10 +59,10 @@ export function SocialLinksEdit( props ) { // Remove icon background color when logos only style is selected or // restore it when any other style is selected. - const backgroundBackup = useRef( {} ); + const backgroundBackupRef = useRef( {} ); useEffect( () => { if ( logosOnly ) { - backgroundBackup.current = { + backgroundBackupRef.current = { iconBackgroundColor, iconBackgroundColorValue, customIconBackgroundColor, @@ -73,7 +73,7 @@ export function SocialLinksEdit( props ) { iconBackgroundColorValue: undefined, } ); } else { - setAttributes( { ...backgroundBackup.current } ); + setAttributes( { ...backgroundBackupRef.current } ); } }, [ logosOnly ] ); diff --git a/packages/block-library/src/utils/hooks.js b/packages/block-library/src/utils/hooks.js index f9ad52297c53e..61515306e8bfd 100644 --- a/packages/block-library/src/utils/hooks.js +++ b/packages/block-library/src/utils/hooks.js @@ -37,36 +37,36 @@ export function useCanEditEntity( kind, name, recordId ) { * @param {Function} args.onError Function called when an error happens. */ export function useUploadMediaFromBlobURL( args = {} ) { - const latestArgs = useRef( args ); - const hasUploadStarted = useRef( false ); + const latestArgsRef = useRef( args ); + const hasUploadStartedRef = useRef( false ); const { getSettings } = useSelect( blockEditorStore ); useLayoutEffect( () => { - latestArgs.current = args; + latestArgsRef.current = args; } ); useEffect( () => { // Uploading is a special effect that can't be canceled via the cleanup method. // The extra check avoids duplicate uploads in development mode (React.StrictMode). - if ( hasUploadStarted.current ) { + if ( hasUploadStartedRef.current ) { return; } if ( - ! latestArgs.current.url || - ! isBlobURL( latestArgs.current.url ) + ! latestArgsRef.current.url || + ! isBlobURL( latestArgsRef.current.url ) ) { return; } - const file = getBlobByURL( latestArgs.current.url ); + const file = getBlobByURL( latestArgsRef.current.url ); if ( ! file ) { return; } - const { url, allowedTypes, onChange, onError } = latestArgs.current; + const { url, allowedTypes, onChange, onError } = latestArgsRef.current; const { mediaUpload } = getSettings(); - hasUploadStarted.current = true; + hasUploadStartedRef.current = true; mediaUpload( { filesList: [ file ], @@ -78,12 +78,12 @@ export function useUploadMediaFromBlobURL( args = {} ) { revokeBlobURL( url ); onChange( media ); - hasUploadStarted.current = false; + hasUploadStartedRef.current = false; }, onError: ( message ) => { revokeBlobURL( url ); onError( message ); - hasUploadStarted.current = false; + hasUploadStartedRef.current = false; }, } ); }, [ getSettings ] ); diff --git a/packages/commands/src/components/command-menu.js b/packages/commands/src/components/command-menu.js index ac305246fefb7..55f78ac02c655 100644 --- a/packages/commands/src/components/command-menu.js +++ b/packages/commands/src/components/command-menu.js @@ -79,11 +79,11 @@ export function CommandMenuLoaderWrapper( { hook, search, setLoader, close } ) { // the CommandMenuLoaderWrapper component need to be // remounted on each hook prop change // We use the key state to make sure we do that properly. - const currentLoader = useRef( hook ); + const currentLoaderRef = useRef( hook ); const [ key, setKey ] = useState( 0 ); useEffect( () => { - if ( currentLoader.current !== hook ) { - currentLoader.current = hook; + if ( currentLoaderRef.current !== hook ) { + currentLoaderRef.current = hook; setKey( ( prevKey ) => prevKey + 1 ); } }, [ hook ] ); @@ -91,7 +91,7 @@ export function CommandMenuLoaderWrapper( { hook, search, setLoader, close } ) { return ( { - currentCallback.current = command.callback; + currentCallbackRef.current = command.callback; }, [ command.callback ] ); useEffect( () => { @@ -47,7 +47,7 @@ export default function useCommand( command ) { label: command.label, searchLabel: command.searchLabel, icon: command.icon, - callback: ( ...args ) => currentCallback.current( ...args ), + callback: ( ...args ) => currentCallbackRef.current( ...args ), } ); return () => { unregisterCommand( command.name ); diff --git a/packages/components/src/angle-picker-control/angle-circle.tsx b/packages/components/src/angle-picker-control/angle-circle.tsx index 8558b23279302..52a2d2838a1f2 100644 --- a/packages/components/src/angle-picker-control/angle-circle.tsx +++ b/packages/components/src/angle-picker-control/angle-circle.tsx @@ -28,8 +28,10 @@ function AngleCircle( { ...props }: WordPressComponentProps< AngleCircleProps, 'div' > ) { const angleCircleRef = useRef< HTMLDivElement | null >( null ); - const angleCircleCenter = useRef< { x: number; y: number } | undefined >(); - const previousCursorValue = useRef< CSSStyleDeclaration[ 'cursor' ] >(); + const angleCircleCenterRef = useRef< + { x: number; y: number } | undefined + >(); + const previousCursorValueRef = useRef< CSSStyleDeclaration[ 'cursor' ] >(); const setAngleCircleCenter = () => { if ( angleCircleRef.current === null ) { @@ -37,7 +39,7 @@ function AngleCircle( { } const rect = angleCircleRef.current.getBoundingClientRect(); - angleCircleCenter.current = { + angleCircleCenterRef.current = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2, }; @@ -55,10 +57,10 @@ function AngleCircle( { ( event.target as HTMLDivElement | null )?.focus(); if ( - angleCircleCenter.current !== undefined && + angleCircleCenterRef.current !== undefined && onChange !== undefined ) { - const { x: centerX, y: centerY } = angleCircleCenter.current; + const { x: centerX, y: centerY } = angleCircleCenterRef.current; onChange( getAngle( centerX, centerY, event.clientX, event.clientY ) ); @@ -76,13 +78,13 @@ function AngleCircle( { useEffect( () => { if ( isDragging ) { - if ( previousCursorValue.current === undefined ) { - previousCursorValue.current = document.body.style.cursor; + if ( previousCursorValueRef.current === undefined ) { + previousCursorValueRef.current = document.body.style.cursor; } document.body.style.cursor = 'grabbing'; } else { - document.body.style.cursor = previousCursorValue.current || ''; - previousCursorValue.current = undefined; + document.body.style.cursor = previousCursorValueRef.current || ''; + previousCursorValueRef.current = undefined; } }, [ isDragging ] ); diff --git a/packages/components/src/clipboard-button/index.tsx b/packages/components/src/clipboard-button/index.tsx index 2f66b97a5a00f..0bf7d177e251e 100644 --- a/packages/components/src/clipboard-button/index.tsx +++ b/packages/components/src/clipboard-button/index.tsx @@ -32,21 +32,21 @@ export default function ClipboardButton( { alternative: 'wp.compose.useCopyToClipboard', } ); - const timeoutId = useRef< NodeJS.Timeout >(); + const timeoutIdRef = useRef< NodeJS.Timeout >(); const ref = useCopyToClipboard( text, () => { onCopy(); - if ( timeoutId.current ) { - clearTimeout( timeoutId.current ); + if ( timeoutIdRef.current ) { + clearTimeout( timeoutIdRef.current ); } if ( onFinishCopy ) { - timeoutId.current = setTimeout( () => onFinishCopy(), TIMEOUT ); + timeoutIdRef.current = setTimeout( () => onFinishCopy(), TIMEOUT ); } } ); useEffect( () => { - if ( timeoutId.current ) { - clearTimeout( timeoutId.current ); + if ( timeoutIdRef.current ) { + clearTimeout( timeoutIdRef.current ); } }, [] ); diff --git a/packages/components/src/color-picker/color-copy-button.tsx b/packages/components/src/color-picker/color-copy-button.tsx index 11ff7ca52de78..b8a4822544322 100644 --- a/packages/components/src/color-picker/color-copy-button.tsx +++ b/packages/components/src/color-picker/color-copy-button.tsx @@ -17,7 +17,9 @@ import type { ColorCopyButtonProps } from './types'; export const ColorCopyButton = ( props: ColorCopyButtonProps ) => { const { color, colorType } = props; const [ copiedColor, setCopiedColor ] = useState< string | null >( null ); - const copyTimer = useRef< ReturnType< typeof setTimeout > | undefined >(); + const copyTimerRef = useRef< + ReturnType< typeof setTimeout > | undefined + >(); const copyRef = useCopyToClipboard< HTMLDivElement >( () => { switch ( colorType ) { @@ -34,21 +36,21 @@ export const ColorCopyButton = ( props: ColorCopyButtonProps ) => { } }, () => { - if ( copyTimer.current ) { - clearTimeout( copyTimer.current ); + if ( copyTimerRef.current ) { + clearTimeout( copyTimerRef.current ); } setCopiedColor( color.toHex() ); - copyTimer.current = setTimeout( () => { + copyTimerRef.current = setTimeout( () => { setCopiedColor( null ); - copyTimer.current = undefined; + copyTimerRef.current = undefined; }, 3000 ); } ); useEffect( () => { - // Clear copyTimer on component unmount. + // Clear copyTimerRef on component unmount. return () => { - if ( copyTimer.current ) { - clearTimeout( copyTimer.current ); + if ( copyTimerRef.current ) { + clearTimeout( copyTimerRef.current ); } }; }, [] ); diff --git a/packages/components/src/custom-gradient-picker/gradient-bar/control-points.tsx b/packages/components/src/custom-gradient-picker/gradient-bar/control-points.tsx index e3620655aee1a..a92e973d88c5a 100644 --- a/packages/components/src/custom-gradient-picker/gradient-bar/control-points.tsx +++ b/packages/components/src/custom-gradient-picker/gradient-bar/control-points.tsx @@ -128,11 +128,11 @@ function ControlPoints( { onStopControlPointChange, __experimentalIsRenderedInSidebar, }: ControlPointsProps ) { - const controlPointMoveState = useRef< ControlPointMoveState >(); + const controlPointMoveStateRef = useRef< ControlPointMoveState >(); const onMouseMove = ( event: MouseEvent ) => { if ( - controlPointMoveState.current === undefined || + controlPointMoveStateRef.current === undefined || gradientPickerDomRef.current === null ) { return; @@ -144,14 +144,14 @@ function ControlPoints( { ); const { initialPosition, index, significantMoveHappened } = - controlPointMoveState.current; + controlPointMoveStateRef.current; if ( ! significantMoveHappened && Math.abs( initialPosition - relativePosition ) >= MINIMUM_SIGNIFICANT_MOVE ) { - controlPointMoveState.current.significantMoveHappened = true; + controlPointMoveStateRef.current.significantMoveHappened = true; } onChange( @@ -163,13 +163,13 @@ function ControlPoints( { if ( window && window.removeEventListener && - controlPointMoveState.current && - controlPointMoveState.current.listenersActivated + controlPointMoveStateRef.current && + controlPointMoveStateRef.current.listenersActivated ) { window.removeEventListener( 'mousemove', onMouseMove ); window.removeEventListener( 'mouseup', cleanEventListeners ); onStopControlPointChange(); - controlPointMoveState.current.listenersActivated = false; + controlPointMoveStateRef.current.listenersActivated = false; } }; @@ -202,8 +202,8 @@ function ControlPoints( { key={ index } onClick={ () => { if ( - controlPointMoveState.current && - controlPointMoveState.current + controlPointMoveStateRef.current && + controlPointMoveStateRef.current .significantMoveHappened ) { return; @@ -220,7 +220,7 @@ function ControlPoints( { window && window.addEventListener ) { - controlPointMoveState.current = { + controlPointMoveStateRef.current = { initialPosition, index, significantMoveHappened: false, diff --git a/packages/components/src/draggable/index.tsx b/packages/components/src/draggable/index.tsx index 0a3000538dbf2..b9dea8fed4306 100644 --- a/packages/components/src/draggable/index.tsx +++ b/packages/components/src/draggable/index.tsx @@ -71,7 +71,7 @@ export function Draggable( { __experimentalDragComponent: dragComponent, }: DraggableProps ) { const dragComponentRef = useRef< HTMLDivElement >( null ); - const cleanup = useRef( () => {} ); + const cleanupRef = useRef( () => {} ); /** * Removes the element clone, resets cursor, and removes drag listener. @@ -80,7 +80,7 @@ export function Draggable( { */ function end( event: DragEvent ) { event.preventDefault(); - cleanup.current(); + cleanupRef.current(); if ( onDragEnd ) { onDragEnd( event ); @@ -216,7 +216,7 @@ export function Draggable( { onDragStart( event ); } - cleanup.current = () => { + cleanupRef.current = () => { // Remove drag clone. if ( cloneWrapper && cloneWrapper.parentNode ) { cloneWrapper.parentNode.removeChild( cloneWrapper ); @@ -235,7 +235,7 @@ export function Draggable( { useEffect( () => () => { - cleanup.current(); + cleanupRef.current(); }, [] ); diff --git a/packages/components/src/input-control/reducer/reducer.ts b/packages/components/src/input-control/reducer/reducer.ts index 8e3584d3910d7..51e54d6492f5c 100644 --- a/packages/components/src/input-control/reducer/reducer.ts +++ b/packages/components/src/input-control/reducer/reducer.ts @@ -192,25 +192,28 @@ export function useInputControlStateReducer( const pressDown = createKeyEvent( actions.PRESS_DOWN ); const pressEnter = createKeyEvent( actions.PRESS_ENTER ); - const currentState = useRef( state ); - const refProps = useRef( { value: initialState.value, onChangeHandler } ); + const currentStateRef = useRef( state ); + const refPropsRef = useRef( { + value: initialState.value, + onChangeHandler, + } ); // Freshens refs to props and state so that subsequent effects have access // to their latest values without their changes causing effect runs. useLayoutEffect( () => { - currentState.current = state; - refProps.current = { value: initialState.value, onChangeHandler }; + currentStateRef.current = state; + refPropsRef.current = { value: initialState.value, onChangeHandler }; } ); // Propagates the latest state through onChange. useLayoutEffect( () => { if ( - currentState.current._event !== undefined && - state.value !== refProps.current.value && + currentStateRef.current._event !== undefined && + state.value !== refPropsRef.current.value && ! state.isDirty ) { - refProps.current.onChangeHandler( state.value ?? '', { - event: currentState.current._event as + refPropsRef.current.onChangeHandler( state.value ?? '', { + event: currentStateRef.current._event as | ChangeEvent< HTMLInputElement > | PointerEvent< HTMLInputElement >, } ); @@ -220,8 +223,8 @@ export function useInputControlStateReducer( // Updates the state from props. useLayoutEffect( () => { if ( - initialState.value !== currentState.current.value && - ! currentState.current.isDirty + initialState.value !== currentStateRef.current.value && + ! currentStateRef.current.isDirty ) { dispatch( { type: actions.CONTROL, diff --git a/packages/components/src/input-control/utils.ts b/packages/components/src/input-control/utils.ts index 7e3eb93980800..5bc42312af1f5 100644 --- a/packages/components/src/input-control/utils.ts +++ b/packages/components/src/input-control/utils.ts @@ -73,7 +73,7 @@ export function useDraft( props: { onBlur?: FocusEventHandler; onChange: InputChangeCallback; } ) { - const refPreviousValue = useRef( props.value ); + const previousValueRef = useRef( props.value ); const [ draft, setDraft ] = useState< { value?: string; isStale?: boolean; @@ -84,8 +84,8 @@ export function useDraft( props: { // To do so, it tracks the previous value and marks the draft value as stale // after each render. useLayoutEffect( () => { - const { current: previousValue } = refPreviousValue; - refPreviousValue.current = props.value; + const { current: previousValue } = previousValueRef; + previousValueRef.current = props.value; if ( draft.value !== undefined && ! draft.isStale ) { setDraft( { ...draft, isStale: true } ); } else if ( draft.isStale && props.value !== previousValue ) { diff --git a/packages/components/src/modal/index.tsx b/packages/components/src/modal/index.tsx index b18217cdbaadc..e1f103b98c273 100644 --- a/packages/components/src/modal/index.tsx +++ b/packages/components/src/modal/index.tsx @@ -134,9 +134,9 @@ function UnforwardedModal( }, [] ); // Keeps a fresh ref for the subsequent effect. - const refOnRequestClose = useRef< ModalProps[ 'onRequestClose' ] >(); + const onRequestCloseRef = useRef< ModalProps[ 'onRequestClose' ] >(); useEffect( () => { - refOnRequestClose.current = onRequestClose; + onRequestCloseRef.current = onRequestClose; }, [ onRequestClose ] ); // The list of `onRequestClose` callbacks of open (non-nested) Modals. Only @@ -149,10 +149,10 @@ function UnforwardedModal( // onRequestClose for any prior and/or nested modals as applicable. useEffect( () => { // add this modal instance to the dismissers set - dismissers.add( refOnRequestClose ); + dismissers.add( onRequestCloseRef ); // request that all the other modals close themselves for ( const dismisser of dismissers ) { - if ( dismisser !== refOnRequestClose ) { + if ( dismisser !== onRequestCloseRef ) { dismisser.current?.(); } } @@ -162,7 +162,7 @@ function UnforwardedModal( dismisser.current?.(); } // remove this modal instance from the dismissers set - dismissers.delete( refOnRequestClose ); + dismissers.delete( onRequestCloseRef ); }; }, [ dismissers, nestedDismissers ] ); diff --git a/packages/components/src/navigation/index.tsx b/packages/components/src/navigation/index.tsx index b1c12f59e27a9..0069369f3e00c 100644 --- a/packages/components/src/navigation/index.tsx +++ b/packages/components/src/navigation/index.tsx @@ -93,10 +93,10 @@ export function Navigation( { }; // Used to prevent the sliding animation on mount - const isMounted = useRef( false ); + const isMountedRef = useRef( false ); useEffect( () => { - if ( ! isMounted.current ) { - isMounted.current = true; + if ( ! isMountedRef.current ) { + isMountedRef.current = true; } }, [] ); @@ -130,7 +130,7 @@ export function Navigation( { animateClassName ? clsx( { [ animateClassName ]: - isMounted.current && slideOrigin, + isMountedRef.current && slideOrigin, } ) : undefined } diff --git a/packages/components/src/palette-edit/index.tsx b/packages/components/src/palette-edit/index.tsx index 05866e0ee0564..601ea758b75bb 100644 --- a/packages/components/src/palette-edit/index.tsx +++ b/packages/components/src/palette-edit/index.tsx @@ -275,9 +275,9 @@ function PaletteEditListView< T extends Color | Gradient >( { addColorRef, }: PaletteEditListViewProps< T > ) { // When unmounting the component if there are empty elements (the user did not complete the insertion) clean them. - const elementsReference = useRef< typeof elements >(); + const elementsReferenceRef = useRef< typeof elements >(); useEffect( () => { - elementsReference.current = elements; + elementsReferenceRef.current = elements; }, [ elements ] ); const debounceOnChange = useDebounce( onChange, 100 ); diff --git a/packages/components/src/slot-fill/bubbles-virtually/fill.tsx b/packages/components/src/slot-fill/bubbles-virtually/fill.tsx index 083d7302992dd..3cfadbadc62c4 100644 --- a/packages/components/src/slot-fill/bubbles-virtually/fill.tsx +++ b/packages/components/src/slot-fill/bubbles-virtually/fill.tsx @@ -12,17 +12,17 @@ import type { FillComponentProps } from '../types'; function useForceUpdate() { const [ , setState ] = useState( {} ); - const mounted = useRef( true ); + const mountedRef = useRef( true ); useEffect( () => { - mounted.current = true; + mountedRef.current = true; return () => { - mounted.current = false; + mountedRef.current = false; }; }, [] ); return () => { - if ( mounted.current ) { + if ( mountedRef.current ) { setState( {} ); } }; diff --git a/packages/components/src/snackbar/index.tsx b/packages/components/src/snackbar/index.tsx index 5bd44d8aace33..0f2b74caca7d4 100644 --- a/packages/components/src/snackbar/index.tsx +++ b/packages/components/src/snackbar/index.tsx @@ -96,17 +96,17 @@ function UnforwardedSnackbar( // The `onDismiss/onRemove` can have unstable references, // trigger side-effect cleanup, and reset timers. - const callbackRefs = useRef( { onDismiss, onRemove } ); + const callbacksRef = useRef( { onDismiss, onRemove } ); useLayoutEffect( () => { - callbackRefs.current = { onDismiss, onRemove }; + callbacksRef.current = { onDismiss, onRemove }; } ); useEffect( () => { // Only set up the timeout dismiss if we're not explicitly dismissing. const timeoutHandle = setTimeout( () => { if ( ! explicitDismiss ) { - callbackRefs.current.onDismiss?.(); - callbackRefs.current.onRemove?.(); + callbacksRef.current.onDismiss?.(); + callbacksRef.current.onRemove?.(); } }, NOTICE_TIMEOUT ); diff --git a/packages/components/src/tabs/index.tsx b/packages/components/src/tabs/index.tsx index ef8978b647a90..ca8c5b19bcd62 100644 --- a/packages/components/src/tabs/index.tsx +++ b/packages/components/src/tabs/index.tsx @@ -55,9 +55,9 @@ function Tabs( { // Keep track of whether tabs have been populated. This is used to prevent // certain effects from firing too early while tab data and relevant // variables are undefined during the initial render. - const tabsHavePopulated = useRef( false ); + const tabsHavePopulatedRef = useRef( false ); if ( items.length > 0 ) { - tabsHavePopulated.current = true; + tabsHavePopulatedRef.current = true; } const selectedTab = items.find( ( item ) => item.id === selectedId ); @@ -94,7 +94,7 @@ function Tabs( { if ( firstEnabledTab ) { setSelectedId( firstEnabledTab.id ); - } else if ( tabsHavePopulated.current ) { + } else if ( tabsHavePopulatedRef.current ) { setSelectedId( null ); } } @@ -148,7 +148,11 @@ function Tabs( { // Once the tabs have populated, if the `selectedTabId` still can't be // found, clear the selection. - if ( tabsHavePopulated.current && !! selectedTabId && ! selectedTab ) { + if ( + tabsHavePopulatedRef.current && + !! selectedTabId && + ! selectedTab + ) { setSelectedId( null ); } }, [ isControlled, selectedTab, selectedTabId, setSelectedId ] ); diff --git a/packages/components/src/toggle-group-control/toggle-group-control/utils.ts b/packages/components/src/toggle-group-control/toggle-group-control/utils.ts index fe2b84c5b8123..0cc6dcd743b11 100644 --- a/packages/components/src/toggle-group-control/toggle-group-control/utils.ts +++ b/packages/components/src/toggle-group-control/toggle-group-control/utils.ts @@ -21,23 +21,23 @@ type ValueProp = ToggleGroupControlProps[ 'value' ]; export function useComputeControlledOrUncontrolledValue( valueProp: ValueProp ): { value: ValueProp; defaultValue: ValueProp } { - const isInitialRender = useRef( true ); + const isInitialRenderRef = useRef( true ); const prevValueProp = usePrevious( valueProp ); - const prevIsControlled = useRef( false ); + const prevIsControlledRef = useRef( false ); useEffect( () => { - if ( isInitialRender.current ) { - isInitialRender.current = false; + if ( isInitialRenderRef.current ) { + isInitialRenderRef.current = false; } }, [] ); // Assume the component is being used in controlled mode on the first re-render // that has a different `valueProp` from the previous render. const isControlled = - prevIsControlled.current || - ( ! isInitialRender.current && prevValueProp !== valueProp ); + prevIsControlledRef.current || + ( ! isInitialRenderRef.current && prevValueProp !== valueProp ); useEffect( () => { - prevIsControlled.current = isControlled; + prevIsControlledRef.current = isControlled; }, [ isControlled ] ); if ( isControlled ) { diff --git a/packages/components/src/tools-panel/tools-panel/hook.ts b/packages/components/src/tools-panel/tools-panel/hook.ts index 8742f1c494ce1..931bf2494e6e3 100644 --- a/packages/components/src/tools-panel/tools-panel/hook.ts +++ b/packages/components/src/tools-panel/tools-panel/hook.ts @@ -94,16 +94,16 @@ export function useToolsPanel( ...otherProps } = useContextSystem( props, 'ToolsPanel' ); - const isResetting = useRef( false ); - const wasResetting = isResetting.current; + const isResettingRef = useRef( false ); + const wasResetting = isResettingRef.current; - // `isResetting` is cleared via this hook to effectively batch together + // `isResettingRef` is cleared via this hook to effectively batch together // the resetAll task. Without this, the flag is cleared after the first // control updates and forces a rerender with subsequent controls then // believing they need to reset, unfortunately using stale data. useEffect( () => { if ( wasResetting ) { - isResetting.current = false; + isResettingRef.current = false; } }, [ wasResetting ] ); @@ -303,7 +303,7 @@ export function useToolsPanel( // Resets display of children and executes resetAll callback if available. const resetAllItems = useCallback( () => { if ( typeof resetAll === 'function' ) { - isResetting.current = true; + isResettingRef.current = true; resetAll( resetAllFilters ); } @@ -340,7 +340,7 @@ export function useToolsPanel( firstDisplayedItem, flagItemCustomization, hasMenuItems: !! panelItems.length, - isResetting: isResetting.current, + isResetting: isResettingRef.current, lastDisplayedItem, menuItems, panelId, diff --git a/packages/components/src/utils/hooks/use-update-effect.js b/packages/components/src/utils/hooks/use-update-effect.js index d49ca951cdcff..ed2c3ca436357 100644 --- a/packages/components/src/utils/hooks/use-update-effect.js +++ b/packages/components/src/utils/hooks/use-update-effect.js @@ -12,12 +12,12 @@ import { useRef, useEffect } from '@wordpress/element'; * @param {import('react').DependencyList} deps */ function useUpdateEffect( effect, deps ) { - const mounted = useRef( false ); + const mountedRef = useRef( false ); useEffect( () => { - if ( mounted.current ) { + if ( mountedRef.current ) { return effect(); } - mounted.current = true; + mountedRef.current = true; return undefined; // Disable reasons: // 1. This hook needs to pass a dep list that isn't an array literal @@ -28,7 +28,7 @@ function useUpdateEffect( effect, deps ) { useEffect( () => () => { - mounted.current = false; + mountedRef.current = false; }, [] ); diff --git a/packages/compose/src/hooks/use-copy-on-click/index.js b/packages/compose/src/hooks/use-copy-on-click/index.js index 383be2b957342..eab34045f3c21 100644 --- a/packages/compose/src/hooks/use-copy-on-click/index.js +++ b/packages/compose/src/hooks/use-copy-on-click/index.js @@ -31,7 +31,7 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) { } ); /** @type {import('react').MutableRefObject} */ - const clipboard = useRef(); + const clipboardRef = useRef(); const [ hasCopied, setHasCopied ] = useState( false ); useEffect( () => { @@ -43,11 +43,11 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) { } // Clipboard listens to click events. - clipboard.current = new Clipboard( ref.current, { + clipboardRef.current = new Clipboard( ref.current, { text: () => ( typeof text === 'function' ? text() : text ), } ); - clipboard.current.on( 'success', ( { clearSelection, trigger } ) => { + clipboardRef.current.on( 'success', ( { clearSelection, trigger } ) => { // Clearing selection will move focus back to the triggering button, // ensuring that it is not reset to the body, and further that it is // kept within the rendered node. @@ -66,8 +66,8 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) { } ); return () => { - if ( clipboard.current ) { - clipboard.current.destroy(); + if ( clipboardRef.current ) { + clipboardRef.current.destroy(); } clearTimeout( timeoutId ); }; diff --git a/packages/compose/src/hooks/use-focus-on-mount/index.js b/packages/compose/src/hooks/use-focus-on-mount/index.js index db1f2dcdbe3ea..77bee27772d2d 100644 --- a/packages/compose/src/hooks/use-focus-on-mount/index.js +++ b/packages/compose/src/hooks/use-focus-on-mount/index.js @@ -49,7 +49,7 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) { }; /** @type {import('react').MutableRefObject | undefined>} */ - const timerId = useRef(); + const timerIdRef = useRef(); useEffect( () => { focusOnMountRef.current = focusOnMount; @@ -65,7 +65,7 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) { } if ( focusOnMountRef.current === 'firstElement' ) { - timerId.current = setTimeout( () => { + timerIdRef.current = setTimeout( () => { const firstTabbable = focus.tabbable.find( node )[ 0 ]; if ( firstTabbable ) { @@ -79,8 +79,8 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) { setFocus( node ); return () => { - if ( timerId.current ) { - clearTimeout( timerId.current ); + if ( timerIdRef.current ) { + clearTimeout( timerIdRef.current ); } }; }, [] ); diff --git a/packages/compose/src/hooks/use-focus-outside/index.ts b/packages/compose/src/hooks/use-focus-outside/index.ts index 3d85b588a9ab3..812621a09d21d 100644 --- a/packages/compose/src/hooks/use-focus-outside/index.ts +++ b/packages/compose/src/hooks/use-focus-outside/index.ts @@ -71,20 +71,20 @@ type UseFocusOutsideReturn = { export default function useFocusOutside( onFocusOutside: ( ( event: React.FocusEvent ) => void ) | undefined ): UseFocusOutsideReturn { - const currentOnFocusOutside = useRef( onFocusOutside ); + const currentOnFocusOutsideRef = useRef( onFocusOutside ); useEffect( () => { - currentOnFocusOutside.current = onFocusOutside; + currentOnFocusOutsideRef.current = onFocusOutside; }, [ onFocusOutside ] ); - const preventBlurCheck = useRef( false ); + const preventBlurCheckRef = useRef( false ); - const blurCheckTimeoutId = useRef< number | undefined >(); + const blurCheckTimeoutIdRef = useRef< number | undefined >(); /** * Cancel a blur check timeout. */ const cancelBlurCheck = useCallback( () => { - clearTimeout( blurCheckTimeoutId.current ); + clearTimeout( blurCheckTimeoutIdRef.current ); }, [] ); // Cancel blur checks on unmount. @@ -116,9 +116,9 @@ export default function useFocusOutside( const isInteractionEnd = [ 'mouseup', 'touchend' ].includes( type ); if ( isInteractionEnd ) { - preventBlurCheck.current = false; + preventBlurCheckRef.current = false; } else if ( isFocusNormalizedButton( target ) ) { - preventBlurCheck.current = true; + preventBlurCheckRef.current = true; } }, [] ); @@ -135,7 +135,7 @@ export default function useFocusOutside( event.persist(); // Skip blur check if clicking button. See `normalizeButtonFocus`. - if ( preventBlurCheck.current ) { + if ( preventBlurCheckRef.current ) { return; } @@ -156,7 +156,7 @@ export default function useFocusOutside( return; } - blurCheckTimeoutId.current = setTimeout( () => { + blurCheckTimeoutIdRef.current = setTimeout( () => { // If document is not focused then focus should remain // inside the wrapped component and therefore we cancel // this blur event thereby leaving focus in place. @@ -166,8 +166,8 @@ export default function useFocusOutside( return; } - if ( 'function' === typeof currentOnFocusOutside.current ) { - currentOnFocusOutside.current( event ); + if ( 'function' === typeof currentOnFocusOutsideRef.current ) { + currentOnFocusOutsideRef.current( event ); } }, 0 ); }, [] ); diff --git a/packages/compose/src/hooks/use-keyboard-shortcut/index.js b/packages/compose/src/hooks/use-keyboard-shortcut/index.js index be27d15864633..be3f3a2554c7f 100644 --- a/packages/compose/src/hooks/use-keyboard-shortcut/index.js +++ b/packages/compose/src/hooks/use-keyboard-shortcut/index.js @@ -42,9 +42,9 @@ function useKeyboardShortcut( target, } = {} ) { - const currentCallback = useRef( callback ); + const currentCallbackRef = useRef( callback ); useEffect( () => { - currentCallback.current = callback; + currentCallbackRef.current = callback; }, [ callback ] ); useEffect( () => { @@ -93,7 +93,7 @@ function useKeyboardShortcut( /** @type {[e: import('mousetrap').ExtendedKeyboardEvent, combo: string]} */ ...args ) => /* eslint-enable jsdoc/valid-types */ - currentCallback.current( ...args ), + currentCallbackRef.current( ...args ), eventName ); } ); diff --git a/packages/compose/src/hooks/use-merge-refs/index.js b/packages/compose/src/hooks/use-merge-refs/index.js index f39160444c522..ed7f4247018be 100644 --- a/packages/compose/src/hooks/use-merge-refs/index.js +++ b/packages/compose/src/hooks/use-merge-refs/index.js @@ -71,28 +71,28 @@ function assignRef( ref, value ) { */ export default function useMergeRefs( refs ) { const element = useRef(); - const isAttached = useRef( false ); - const didElementChange = useRef( false ); + const isAttachedRef = useRef( false ); + const didElementChangeRef = useRef( false ); /* eslint-disable jsdoc/no-undefined-types */ /** @type {import('react').MutableRefObject} */ /* eslint-enable jsdoc/no-undefined-types */ - const previousRefs = useRef( [] ); - const currentRefs = useRef( refs ); + const previousRefsRef = useRef( [] ); + const currentRefsRef = useRef( refs ); // Update on render before the ref callback is called, so the ref callback // always has access to the current refs. - currentRefs.current = refs; + currentRefsRef.current = refs; // If any of the refs change, call the previous ref with `null` and the new // ref with the node, except when the element changes in the same cycle, in // which case the ref callbacks will already have been called. useLayoutEffect( () => { if ( - didElementChange.current === false && - isAttached.current === true + didElementChangeRef.current === false && + isAttachedRef.current === true ) { refs.forEach( ( ref, index ) => { - const previousRef = previousRefs.current[ index ]; + const previousRef = previousRefsRef.current[ index ]; if ( ref !== previousRef ) { assignRef( previousRef, null ); assignRef( ref, element.current ); @@ -100,13 +100,13 @@ export default function useMergeRefs( refs ) { } ); } - previousRefs.current = refs; + previousRefsRef.current = refs; }, refs ); // No dependencies, must be reset after every render so ref callbacks are // correctly called after a ref change. useLayoutEffect( () => { - didElementChange.current = false; + didElementChangeRef.current = false; } ); // There should be no dependencies so that `callback` is only called when @@ -116,12 +116,14 @@ export default function useMergeRefs( refs ) { // dependency change. assignRef( element, value ); - didElementChange.current = true; - isAttached.current = value !== null; + didElementChangeRef.current = true; + isAttachedRef.current = value !== null; // When an element changes, the current ref callback should be called // with the new element and the previous one with `null`. - const refsToAssign = value ? currentRefs.current : previousRefs.current; + const refsToAssign = value + ? currentRefsRef.current + : previousRefsRef.current; // Update the latest refs. for ( const ref of refsToAssign ) { diff --git a/packages/compose/src/hooks/use-ref-effect/index.ts b/packages/compose/src/hooks/use-ref-effect/index.ts index 06d826229980c..89cc3bc2392c2 100644 --- a/packages/compose/src/hooks/use-ref-effect/index.ts +++ b/packages/compose/src/hooks/use-ref-effect/index.ts @@ -31,12 +31,12 @@ export default function useRefEffect< TElement = Node >( callback: ( node: TElement ) => ( () => void ) | void, dependencies: DependencyList ): RefCallback< TElement | null > { - const cleanup = useRef< ( () => void ) | void >(); + const cleanupRef = useRef< ( () => void ) | void >(); return useCallback( ( node: TElement | null ) => { if ( node ) { - cleanup.current = callback( node ); - } else if ( cleanup.current ) { - cleanup.current(); + cleanupRef.current = callback( node ); + } else if ( cleanupRef.current ) { + cleanupRef.current(); } }, dependencies ); } diff --git a/packages/compose/src/hooks/use-resize-observer/index.tsx b/packages/compose/src/hooks/use-resize-observer/index.tsx index 21fcd0bff4f4d..c8c964228edfc 100644 --- a/packages/compose/src/hooks/use-resize-observer/index.tsx +++ b/packages/compose/src/hooks/use-resize-observer/index.tsx @@ -25,7 +25,7 @@ function useResolvedElement< T extends HTMLElement >( subscriber: ( element: T ) => SubscriberResponse, refOrElement?: T | RefObject< T > | null ): RefCallback< T > { - const callbackRefElement = useRef< T | null >( null ); + const callbackElementRef = useRef< T | null >( null ); const lastReportRef = useRef< { reporter: () => void; element: T | null; @@ -34,8 +34,8 @@ function useResolvedElement< T extends HTMLElement >( const callSubscriber = useCallback( () => { let element = null; - if ( callbackRefElement.current ) { - element = callbackRefElement.current; + if ( callbackElementRef.current ) { + element = callbackElementRef.current; } else if ( refOrElement ) { if ( refOrElement instanceof HTMLElement ) { element = refOrElement; @@ -80,7 +80,7 @@ function useResolvedElement< T extends HTMLElement >( return useCallback< RefCallback< T > >( ( element ) => { - callbackRefElement.current = element; + callbackElementRef.current = element; callSubscriber(); }, [ callSubscriber ] @@ -200,16 +200,16 @@ function useResizeObserver< T extends HTMLElement >( // In certain edge cases the RO might want to report a size change just after // the component unmounted. - const didUnmount = useRef( false ); + const didUnmountRef = useRef( false ); useEffect( () => { - didUnmount.current = false; + didUnmountRef.current = false; return () => { - didUnmount.current = true; + didUnmountRef.current = true; }; }, [] ); // Using a ref to track the previous width / height to avoid unnecessary renders. - const previous: { + const previousRef: { current: { width?: number; height?: number; @@ -270,18 +270,18 @@ function useResizeObserver< T extends HTMLElement >( : undefined; if ( - previous.current.width !== newWidth || - previous.current.height !== newHeight + previousRef.current.width !== newWidth || + previousRef.current.height !== newHeight ) { const newSize = { width: newWidth, height: newHeight, }; - previous.current.width = newWidth; - previous.current.height = newHeight; + previousRef.current.width = newWidth; + previousRef.current.height = newHeight; if ( onResizeRef.current ) { onResizeRef.current( newSize ); - } else if ( ! didUnmount.current ) { + } else if ( ! didUnmountRef.current ) { setSize( newSize ); } } diff --git a/packages/data/src/components/use-dispatch/use-dispatch-with-map.js b/packages/data/src/components/use-dispatch/use-dispatch-with-map.js index 7b595b9740eeb..f6fce490a6887 100644 --- a/packages/data/src/components/use-dispatch/use-dispatch-with-map.js +++ b/packages/data/src/components/use-dispatch/use-dispatch-with-map.js @@ -25,14 +25,14 @@ import useRegistry from '../registry-provider/use-registry'; */ const useDispatchWithMap = ( dispatchMap, deps ) => { const registry = useRegistry(); - const currentDispatchMap = useRef( dispatchMap ); + const currentDispatchMapRef = useRef( dispatchMap ); useIsomorphicLayoutEffect( () => { - currentDispatchMap.current = dispatchMap; + currentDispatchMapRef.current = dispatchMap; } ); return useMemo( () => { - const currentDispatchProps = currentDispatchMap.current( + const currentDispatchProps = currentDispatchMapRef.current( registry.dispatch, registry ); @@ -48,7 +48,7 @@ const useDispatchWithMap = ( dispatchMap, deps ) => { return [ propName, ( ...args ) => - currentDispatchMap + currentDispatchMapRef .current( registry.dispatch, registry ) [ propName ]( ...args ), ]; diff --git a/packages/dataviews/src/components/dataviews-bulk-actions-toolbar/index.tsx b/packages/dataviews/src/components/dataviews-bulk-actions-toolbar/index.tsx index c25328db6a108..09e9d5f9df812 100644 --- a/packages/dataviews/src/components/dataviews-bulk-actions-toolbar/index.tsx +++ b/packages/dataviews/src/components/dataviews-bulk-actions-toolbar/index.tsx @@ -183,10 +183,10 @@ function ToolbarContent< Item >( { const [ actionInProgress, setActionInProgress ] = useState< string | null >( null ); - const buttons = useRef< JSX.Element | null >( null ); + const buttonsRef = useRef< JSX.Element | null >( null ); if ( ! actionInProgress ) { - if ( buttons.current ) { - buttons.current = null; + if ( buttonsRef.current ) { + buttonsRef.current = null; } return renderToolbarContent( selection, @@ -196,8 +196,8 @@ function ToolbarContent< Item >( { setActionInProgress, onChangeSelection ); - } else if ( ! buttons.current ) { - buttons.current = renderToolbarContent( + } else if ( ! buttonsRef.current ) { + buttonsRef.current = renderToolbarContent( selection, actionsToShow, selectedItems, @@ -206,7 +206,7 @@ function ToolbarContent< Item >( { onChangeSelection ); } - return buttons.current; + return buttonsRef.current; } function _BulkActionsToolbar() { diff --git a/packages/dataviews/src/dataviews-layouts/table/index.tsx b/packages/dataviews/src/dataviews-layouts/table/index.tsx index df66f225988a7..a4adde7fb382f 100644 --- a/packages/dataviews/src/dataviews-layouts/table/index.tsx +++ b/packages/dataviews/src/dataviews-layouts/table/index.tsx @@ -212,7 +212,7 @@ function TableRow< Item >( { // Will be set to true if `onTouchStart` fires. This happens before // `onClick` and can be used to exclude touchscreen devices from certain // behaviours. - const isTouchDevice = useRef( false ); + const isTouchDeviceRef = useRef( false ); const columns = view.fields || fields.map( ( f ) => f.id ); return ( @@ -225,14 +225,14 @@ function TableRow< Item >( { onMouseEnter={ handleMouseEnter } onMouseLeave={ handleMouseLeave } onTouchStart={ () => { - isTouchDevice.current = true; + isTouchDeviceRef.current = true; } } onClick={ () => { if ( ! hasPossibleBulkAction ) { return; } if ( - ! isTouchDevice.current && + ! isTouchDeviceRef.current && document.getSelection()?.type !== 'Range' ) { onChangeSelection( diff --git a/packages/edit-post/src/components/editor-initialization/listener-hooks.js b/packages/edit-post/src/components/editor-initialization/listener-hooks.js index 786be08fdca0c..968031d59adbc 100644 --- a/packages/edit-post/src/components/editor-initialization/listener-hooks.js +++ b/packages/edit-post/src/components/editor-initialization/listener-hooks.js @@ -24,18 +24,18 @@ export const useUpdatePostLinkListener = () => { } ), [] ); - const nodeToUpdate = useRef(); + const nodeToUpdateRef = useRef(); useEffect( () => { - nodeToUpdate.current = + nodeToUpdateRef.current = document.querySelector( VIEW_AS_PREVIEW_LINK_SELECTOR ) || document.querySelector( VIEW_AS_LINK_SELECTOR ); }, [] ); useEffect( () => { - if ( ! newPermalink || ! nodeToUpdate.current ) { + if ( ! newPermalink || ! nodeToUpdateRef.current ) { return; } - nodeToUpdate.current.setAttribute( 'href', newPermalink ); + nodeToUpdateRef.current.setAttribute( 'href', newPermalink ); }, [ newPermalink ] ); }; diff --git a/packages/edit-site/src/components/sync-state-with-url/use-sync-canvas-mode-with-url.js b/packages/edit-site/src/components/sync-state-with-url/use-sync-canvas-mode-with-url.js index 9f0c8dd9a0e11..d9295f83ee245 100644 --- a/packages/edit-site/src/components/sync-state-with-url/use-sync-canvas-mode-with-url.js +++ b/packages/edit-site/src/components/sync-state-with-url/use-sync-canvas-mode-with-url.js @@ -21,48 +21,51 @@ export default function useSyncCanvasModeWithURL() { [] ); const { setCanvasMode } = unlock( useDispatch( editSiteStore ) ); - const currentCanvasMode = useRef( canvasMode ); + const currentCanvasModeRef = useRef( canvasMode ); const { canvas: canvasInUrl } = params; - const currentCanvasInUrl = useRef( canvasInUrl ); - const currentUrlParams = useRef( params ); + const currentCanvasInUrlRef = useRef( canvasInUrl ); + const currentUrlParamsRef = useRef( params ); useEffect( () => { - currentUrlParams.current = params; + currentUrlParamsRef.current = params; }, [ params ] ); useEffect( () => { - currentCanvasMode.current = canvasMode; + currentCanvasModeRef.current = canvasMode; if ( canvasMode === 'init' ) { return; } if ( canvasMode === 'edit' && - currentCanvasInUrl.current !== canvasMode + currentCanvasInUrlRef.current !== canvasMode ) { history.push( { - ...currentUrlParams.current, + ...currentUrlParamsRef.current, canvas: 'edit', } ); } if ( canvasMode === 'view' && - currentCanvasInUrl.current !== undefined + currentCanvasInUrlRef.current !== undefined ) { history.push( { - ...currentUrlParams.current, + ...currentUrlParamsRef.current, canvas: undefined, } ); } }, [ canvasMode, history ] ); useEffect( () => { - currentCanvasInUrl.current = canvasInUrl; - if ( canvasInUrl !== 'edit' && currentCanvasMode.current !== 'view' ) { + currentCanvasInUrlRef.current = canvasInUrl; + if ( + canvasInUrl !== 'edit' && + currentCanvasModeRef.current !== 'view' + ) { setCanvasMode( 'view' ); } else if ( canvasInUrl === 'edit' && - currentCanvasMode.current !== 'edit' + currentCanvasModeRef.current !== 'edit' ) { setCanvasMode( 'edit' ); } diff --git a/packages/editor/src/components/document-bar/index.js b/packages/editor/src/components/document-bar/index.js index da3d886c125f4..f71cbce23fdaf 100644 --- a/packages/editor/src/components/document-bar/index.js +++ b/packages/editor/src/components/document-bar/index.js @@ -120,9 +120,9 @@ export default function DocumentBar( props ) { const title = props.title || entityTitle; const icon = props.icon || templateIcon; - const mounted = useRef( false ); + const mountedRef = useRef( false ); useEffect( () => { - mounted.current = true; + mountedRef.current = true; }, [] ); return ( @@ -143,7 +143,7 @@ export default function DocumentBar( props ) { } } size="compact" initial={ - mounted.current + mountedRef.current ? { opacity: 0, transform: 'translateX(15%)' } : false // Don't show entry animation when DocumentBar mounts. } @@ -170,7 +170,7 @@ export default function DocumentBar( props ) { // Force entry animation when the back button is added or removed. key={ hasBackButton } initial={ - mounted.current + mountedRef.current ? { opacity: 0, transform: hasBackButton diff --git a/packages/editor/src/components/local-autosave-monitor/index.js b/packages/editor/src/components/local-autosave-monitor/index.js index f999cf9ef8534..ad4e40d15d5c5 100644 --- a/packages/editor/src/components/local-autosave-monitor/index.js +++ b/packages/editor/src/components/local-autosave-monitor/index.js @@ -144,20 +144,20 @@ function useAutosavePurge() { [] ); - const lastIsDirty = useRef( isDirty ); - const lastIsAutosaving = useRef( isAutosaving ); + const lastIsDirtyRef = useRef( isDirty ); + const lastIsAutosavingRef = useRef( isAutosaving ); useEffect( () => { if ( ! didError && - ( ( lastIsAutosaving.current && ! isAutosaving ) || - ( lastIsDirty.current && ! isDirty ) ) + ( ( lastIsAutosavingRef.current && ! isAutosaving ) || + ( lastIsDirtyRef.current && ! isDirty ) ) ) { localAutosaveClear( postId, isEditedPostNew ); } - lastIsDirty.current = isDirty; - lastIsAutosaving.current = isAutosaving; + lastIsDirtyRef.current = isDirty; + lastIsAutosavingRef.current = isAutosaving; }, [ isDirty, isAutosaving, didError ] ); // Once the isEditedPostNew changes from true to false, let's clear the auto-draft autosave. diff --git a/packages/editor/src/components/preview-dropdown/index.js b/packages/editor/src/components/preview-dropdown/index.js index 6554f7c0228a7..ef41fc087f1d2 100644 --- a/packages/editor/src/components/preview-dropdown/index.js +++ b/packages/editor/src/components/preview-dropdown/index.js @@ -58,18 +58,18 @@ export default function PreviewDropdown( { forceIsAutosaveable, disabled } ) { /** * Save the original editing mode in a ref to restore it when we exit zoom out. */ - const originalEditingMode = useRef( editorMode ); + const originalEditingModeRef = useRef( editorMode ); useEffect( () => { if ( editorMode !== 'zoom-out' ) { - originalEditingMode.current = editorMode; + originalEditingModeRef.current = editorMode; } return () => { if ( editorMode === 'zoom-out' && - editorMode !== originalEditingMode.current + editorMode !== originalEditingModeRef.current ) { - __unstableSetEditorMode( originalEditingMode.current ); + __unstableSetEditorMode( originalEditingModeRef.current ); } }; }, [ editorMode, __unstableSetEditorMode ] ); @@ -136,7 +136,7 @@ export default function PreviewDropdown( { forceIsAutosaveable, disabled } ) { * @param {string} value The device type. */ const onSelect = ( value ) => { - let newEditorMode = originalEditingMode.current; + let newEditorMode = originalEditingModeRef.current; if ( value === 'ZoomOut' ) { newEditorMode = 'zoom-out'; diff --git a/packages/interface/src/components/complementary-area/index.js b/packages/interface/src/components/complementary-area/index.js index b37b8b7da33d0..363a6ee9dea76 100644 --- a/packages/interface/src/components/complementary-area/index.js +++ b/packages/interface/src/components/complementary-area/index.js @@ -119,42 +119,42 @@ function useAdjustComplementaryListener( isActive, isSmall ) { - const previousIsSmall = useRef( false ); - const shouldOpenWhenNotSmall = useRef( false ); + const previousIsSmallRef = useRef( false ); + const shouldOpenWhenNotSmallRef = useRef( false ); const { enableComplementaryArea, disableComplementaryArea } = useDispatch( interfaceStore ); useEffect( () => { // If the complementary area is active and the editor is switching from // a big to a small window size. - if ( isActive && isSmall && ! previousIsSmall.current ) { + if ( isActive && isSmall && ! previousIsSmallRef.current ) { disableComplementaryArea( scope ); // Flag the complementary area to be reopened when the window size // goes from small to big. - shouldOpenWhenNotSmall.current = true; + shouldOpenWhenNotSmallRef.current = true; } else if ( // If there is a flag indicating the complementary area should be // enabled when we go from small to big window size and we are going // from a small to big window size. - shouldOpenWhenNotSmall.current && + shouldOpenWhenNotSmallRef.current && ! isSmall && - previousIsSmall.current + previousIsSmallRef.current ) { // Remove the flag indicating the complementary area should be // enabled. - shouldOpenWhenNotSmall.current = false; + shouldOpenWhenNotSmallRef.current = false; enableComplementaryArea( scope, identifier ); } else if ( // If the flag is indicating the current complementary should be // reopened but another complementary area becomes active, remove // the flag. - shouldOpenWhenNotSmall.current && + shouldOpenWhenNotSmallRef.current && activeArea && activeArea !== identifier ) { - shouldOpenWhenNotSmall.current = false; + shouldOpenWhenNotSmallRef.current = false; } - if ( isSmall !== previousIsSmall.current ) { - previousIsSmall.current = isSmall; + if ( isSmall !== previousIsSmallRef.current ) { + previousIsSmallRef.current = isSmall; } }, [ isActive, diff --git a/packages/rich-text/src/component/index.js b/packages/rich-text/src/component/index.js index 2606ae9f902fa..600fc0faff520 100644 --- a/packages/rich-text/src/component/index.js +++ b/packages/rich-text/src/component/index.js @@ -60,46 +60,48 @@ export function useRichText( { } // Internal values are updated synchronously, unlike props and state. - const _value = useRef( value ); - const record = useRef(); + const _valueRef = useRef( value ); + const recordRef = useRef(); function setRecordFromProps() { - _value.current = value; - record.current = value; + _valueRef.current = value; + recordRef.current = value; if ( ! ( value instanceof RichTextData ) ) { - record.current = value + recordRef.current = value ? RichTextData.fromHTMLString( value, { preserveWhiteSpace } ) : RichTextData.empty(); } // To do: make rich text internally work with RichTextData. - record.current = { - text: record.current.text, - formats: record.current.formats, - replacements: record.current.replacements, + recordRef.current = { + text: recordRef.current.text, + formats: recordRef.current.formats, + replacements: recordRef.current.replacements, }; if ( disableFormats ) { - record.current.formats = Array( value.length ); - record.current.replacements = Array( value.length ); + recordRef.current.formats = Array( value.length ); + recordRef.current.replacements = Array( value.length ); } if ( __unstableAfterParse ) { - record.current.formats = __unstableAfterParse( record.current ); + recordRef.current.formats = __unstableAfterParse( + recordRef.current + ); } - record.current.start = selectionStart; - record.current.end = selectionEnd; + recordRef.current.start = selectionStart; + recordRef.current.end = selectionEnd; } - const hadSelectionUpdate = useRef( false ); + const hadSelectionUpdateRef = useRef( false ); - if ( ! record.current ) { - hadSelectionUpdate.current = isSelected; + if ( ! recordRef.current ) { + hadSelectionUpdateRef.current = isSelected; setRecordFromProps(); } else if ( - selectionStart !== record.current.start || - selectionEnd !== record.current.end + selectionStart !== recordRef.current.start || + selectionEnd !== recordRef.current.end ) { - hadSelectionUpdate.current = isSelected; - record.current = { - ...record.current, + hadSelectionUpdateRef.current = isSelected; + recordRef.current = { + ...recordRef.current, start: selectionStart, end: selectionEnd, activeFormats: undefined, @@ -113,34 +115,34 @@ export function useRichText( { * @param {Object} newRecord The record to sync and apply. */ function handleChange( newRecord ) { - record.current = newRecord; + recordRef.current = newRecord; applyRecord( newRecord ); if ( disableFormats ) { - _value.current = newRecord.text; + _valueRef.current = newRecord.text; } else { const newFormats = __unstableBeforeSerialize ? __unstableBeforeSerialize( newRecord ) : newRecord.formats; newRecord = { ...newRecord, formats: newFormats }; if ( typeof value === 'string' ) { - _value.current = toHTMLString( { + _valueRef.current = toHTMLString( { value: newRecord, preserveWhiteSpace, } ); } else { - _value.current = new RichTextData( newRecord ); + _valueRef.current = new RichTextData( newRecord ); } } - const { start, end, formats, text } = record.current; + const { start, end, formats, text } = recordRef.current; // Selection must be updated first, so it is recorded in history when // the content change happens. // We batch both calls to only attempt to rerender once. registry.batch( () => { onSelectionChange( start, end ); - onChange( _value.current, { + onChange( _valueRef.current, { __unstableFormats: formats, __unstableText: text, } ); @@ -150,14 +152,14 @@ export function useRichText( { function applyFromProps() { setRecordFromProps(); - applyRecord( record.current ); + applyRecord( recordRef.current ); } - const didMount = useRef( false ); + const didMountRef = useRef( false ); // Value updates must happen synchonously to avoid overwriting newer values. useLayoutEffect( () => { - if ( didMount.current && value !== _value.current ) { + if ( didMountRef.current && value !== _valueRef.current ) { applyFromProps(); forceRender(); } @@ -165,7 +167,7 @@ export function useRichText( { // Value updates must happen synchonously to avoid overwriting newer values. useLayoutEffect( () => { - if ( ! hadSelectionUpdate.current ) { + if ( ! hadSelectionUpdateRef.current ) { return; } @@ -173,16 +175,16 @@ export function useRichText( { ref.current.focus(); } - applyRecord( record.current ); - hadSelectionUpdate.current = false; - }, [ hadSelectionUpdate.current ] ); + applyRecord( recordRef.current ); + hadSelectionUpdateRef.current = false; + }, [ hadSelectionUpdateRef.current ] ); const mergedRefs = useMergeRefs( [ ref, useDefaultStyle(), - useBoundaryStyle( { record } ), + useBoundaryStyle( { record: recordRef } ), useEventListeners( { - record, + record: recordRef, handleChange, applyRecord, createRecord, @@ -192,18 +194,18 @@ export function useRichText( { } ), useRefEffect( () => { applyFromProps(); - didMount.current = true; + didMountRef.current = true; }, [ placeholder, ...__unstableDependencies ] ), ] ); return { - value: record.current, + value: recordRef.current, // A function to get the most recent value so event handlers in // useRichText implementations have access to it. For example when // listening to input events, we internally update the state, but this // state is not yet available to the input event handler because React // may re-render asynchronously. - getValue: () => record.current, + getValue: () => recordRef.current, onChange: handleChange, ref: mergedRefs, };