UNPKG

@wordpress/block-editor

Version:
8 lines (7 loc) 2.85 kB
{ "version": 3, "sources": ["../../../../src/components/block-list/use-block-props/use-focus-handler.js"], "sourcesContent": ["/**\n * WordPress dependencies\n */\nimport { useSelect, useDispatch } from '@wordpress/data';\nimport { useRefEffect } from '@wordpress/compose';\n\n/**\n * Internal dependencies\n */\nimport { isInsideRootBlock } from '../../../utils/dom';\nimport { store as blockEditorStore } from '../../../store';\n\n/**\n * Selects the block if it receives focus.\n *\n * @param {string} clientId Block client ID.\n */\nexport function useFocusHandler( clientId ) {\n\tconst { isBlockSelected } = useSelect( blockEditorStore );\n\tconst { selectBlock, selectionChange } = useDispatch( blockEditorStore );\n\n\treturn useRefEffect(\n\t\t( node ) => {\n\t\t\t/**\n\t\t\t * Marks the block as selected when focused and not already\n\t\t\t * selected. This specifically handles the case where block does not\n\t\t\t * set focus on its own (via `setFocus`), typically if there is no\n\t\t\t * focusable input in the block.\n\t\t\t *\n\t\t\t * @param {FocusEvent} event Focus event.\n\t\t\t */\n\t\t\tfunction onFocus( event ) {\n\t\t\t\t// When the whole editor is editable, let writing flow handle\n\t\t\t\t// selection.\n\t\t\t\tif (\n\t\t\t\t\tnode.parentElement.closest( '[contenteditable=\"true\"]' )\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check synchronously because a non-selected block might be\n\t\t\t\t// getting data through `useSelect` asynchronously.\n\t\t\t\tif ( isBlockSelected( clientId ) ) {\n\t\t\t\t\t// Potentially change selection away from rich text.\n\t\t\t\t\tif ( ! event.target.isContentEditable ) {\n\t\t\t\t\t\tselectionChange( clientId );\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// If an inner block is focussed, that block is responsible for\n\t\t\t\t// setting the selected block.\n\t\t\t\tif ( ! isInsideRootBlock( node, event.target ) ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tselectBlock( clientId );\n\t\t\t}\n\n\t\t\tnode.addEventListener( 'focusin', onFocus );\n\n\t\t\treturn () => {\n\t\t\t\tnode.removeEventListener( 'focusin', onFocus );\n\t\t\t};\n\t\t},\n\t\t[ isBlockSelected, selectBlock ]\n\t);\n}\n"], "mappings": ";AAGA,SAAS,WAAW,mBAAmB;AACvC,SAAS,oBAAoB;AAK7B,SAAS,yBAAyB;AAClC,SAAS,SAAS,wBAAwB;AAOnC,SAAS,gBAAiB,UAAW;AAC3C,QAAM,EAAE,gBAAgB,IAAI,UAAW,gBAAiB;AACxD,QAAM,EAAE,aAAa,gBAAgB,IAAI,YAAa,gBAAiB;AAEvE,SAAO;AAAA,IACN,CAAE,SAAU;AASX,eAAS,QAAS,OAAQ;AAGzB,YACC,KAAK,cAAc,QAAS,0BAA2B,GACtD;AACD;AAAA,QACD;AAIA,YAAK,gBAAiB,QAAS,GAAI;AAElC,cAAK,CAAE,MAAM,OAAO,mBAAoB;AACvC,4BAAiB,QAAS;AAAA,UAC3B;AACA;AAAA,QACD;AAIA,YAAK,CAAE,kBAAmB,MAAM,MAAM,MAAO,GAAI;AAChD;AAAA,QACD;AAEA,oBAAa,QAAS;AAAA,MACvB;AAEA,WAAK,iBAAkB,WAAW,OAAQ;AAE1C,aAAO,MAAM;AACZ,aAAK,oBAAqB,WAAW,OAAQ;AAAA,MAC9C;AAAA,IACD;AAAA,IACA,CAAE,iBAAiB,WAAY;AAAA,EAChC;AACD;", "names": [] }