Skip to content

Commit

Permalink
Replacing DOM magic with ref
Browse files Browse the repository at this point in the history
  • Loading branch information
George Hotelling committed Jul 12, 2021
1 parent 63328fd commit 2be2b54
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions packages/block-library/src/navigation/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useState, useEffect, useMemo, Platform } from '@wordpress/element';
import {
useState,
useEffect,
useMemo,
useRef,
Platform,
} from '@wordpress/element';
import {
InnerBlocks,
__experimentalUseInnerBlocksProps as useInnerBlocksProps,
Expand Down Expand Up @@ -47,16 +53,11 @@ const LAYOUT = {
alignments: [],
};

function getBlockDOMNode( clientId, doc ) {
return doc.getElementById( 'block-' + clientId );
}

function getComputedStyle( node ) {
return node.ownerDocument.defaultView.getComputedStyle( node );
}

function detectColors( clientId, setColor, setBackground ) {
const colorsDetectionElement = getBlockDOMNode( clientId, document );
function detectColors( colorsDetectionElement, setColor, setBackground ) {
if ( ! colorsDetectionElement ) {
return;
}
Expand Down Expand Up @@ -97,7 +98,6 @@ function Navigation( {
setOverlayBackgroundColor,
overlayTextColor,
setOverlayTextColor,
subMenuClientId,
hasSubmenuIndicatorSetting = true,
hasItemJustificationControls = true,
hasColorSettings = true,
Expand All @@ -111,7 +111,10 @@ function Navigation( {

const { selectBlock } = useDispatch( blockEditorStore );

const navRef = useRef();

const blockProps = useBlockProps( {
ref: navRef,
className: classnames( className, {
[ `items-justified-${ attributes.itemsJustification }` ]: attributes.itemsJustification,
'is-vertical': attributes.orientation === 'vertical',
Expand Down Expand Up @@ -178,10 +181,17 @@ function Navigation( {
if ( ! enableContrastChecking ) {
return;
}
detectColors( clientId, setDetectedColor, setDetectedBackgroundColor );
if ( subMenuClientId ) {
detectColors(
navRef.current,
setDetectedColor,
setDetectedBackgroundColor
);
const subMenuElement = navRef.current.querySelector(
'[data-type="core/navigation-link"] [data-type="core/navigation-link"]'
);
if ( subMenuElement ) {
detectColors(
subMenuClientId,
subMenuElement,
setDetectedOverlayColor,
setDetectedOverlayBackgroundColor
);
Expand Down Expand Up @@ -326,14 +336,9 @@ export default compose( [
selectedBlockId,
] )?.length;

const subMenuClientId = innerBlocks.find(
( b ) => b.innerBlocks.length
)?.innerBlocks[ 0 ]?.clientId;

return {
isImmediateParentOfSelectedBlock,
selectedBlockHasDescendants,
subMenuClientId,
hasExistingNavItems: !! innerBlocks.length,

// This prop is already available but computing it here ensures it's
Expand Down

0 comments on commit 2be2b54

Please sign in to comment.