Extract useFocusedBlock hook

This commit is contained in:
Matt Sherman 2023-10-27 09:54:25 -04:00
parent 49cba8d5ba
commit a2fb19c6ae
2 changed files with 47 additions and 43 deletions

View File

@ -1,48 +1,7 @@
/**
* External dependencies
* Internal dependencies
*/
import { useEffect, useState } from 'react';
function useFocusedBlock() {
const [ focusedElement, setFocusedElement ] = useState< Element | null >();
useEffect( () => {
function handleFocus( event: FocusEvent ) {
const target = event.target;
if ( ! ( target instanceof Element ) ) {
return;
}
setFocusedElement( target.closest( '[data-block]' ) );
}
const productEditorWrapper = document.querySelector(
'.woocommerce-product-block-editor'
) as HTMLElement | null;
productEditorWrapper?.addEventListener( 'focus', handleFocus, {
capture: true,
} );
return () => {
productEditorWrapper?.removeEventListener( 'focus', handleFocus, {
capture: true,
} );
};
}, [] );
const blockInfo = {
blockName: focusedElement?.getAttribute( 'data-type' ),
templateBlockId: focusedElement?.getAttribute(
'data-template-block-id'
),
templateBlockOrder: focusedElement?.getAttribute(
'data-template-block-order'
),
};
return blockInfo;
}
import { useFocusedBlock } from './hooks/use-focused-block';
export function BlockInspector() {
const { blockName, templateBlockId, templateBlockOrder } =

View File

@ -0,0 +1,45 @@
/**
* External dependencies
*/
import { useEffect, useState } from 'react';
export function useFocusedBlock() {
const [ focusedElement, setFocusedElement ] = useState< Element | null >();
useEffect( () => {
function handleFocus( event: FocusEvent ) {
const target = event.target;
if ( ! ( target instanceof Element ) ) {
return;
}
setFocusedElement( target.closest( '[data-block]' ) );
}
const productEditorWrapper = document.querySelector(
'.woocommerce-product-block-editor'
) as HTMLElement | null;
productEditorWrapper?.addEventListener( 'focus', handleFocus, {
capture: true,
} );
return () => {
productEditorWrapper?.removeEventListener( 'focus', handleFocus, {
capture: true,
} );
};
}, [] );
const blockInfo = {
blockName: focusedElement?.getAttribute( 'data-type' ),
templateBlockId: focusedElement?.getAttribute(
'data-template-block-id'
),
templateBlockOrder: focusedElement?.getAttribute(
'data-template-block-order'
),
};
return blockInfo;
}