/** * Internal dependencies */ import { getCssPathInDocument } from '../css-selector-finder/css-path'; import { getInnerContentEditableElements } from '../css-selector-finder/editable-content'; const ALLOWED_CONTENT_TAGS = [ 'strong', 'b', 'em', 'i', 'u' ] as const; export type CssSelectorDiscovery = { readonly outerHTML: string; readonly allowedTags: ReadonlyArray< string >; }; export function extractCssSelectorMapFromDocument( doc: Document ): Record< string, CssSelectorDiscovery > { const root = doc.querySelector< HTMLElement >( 'main' ) || doc.querySelector< HTMLElement >( '[role="main"]' ) || doc.body; if ( ! root ) { return {}; } return getInnerContentEditableElements( root ) .filter( isRelevantElement ) .reduce( ( selectors, element ) => { const selector = getCssPathInDocument( doc, element ); if ( selector ) { selectors[ selector ] = { outerHTML: element.outerHTML, allowedTags: getAllowedContentTags( element ), }; } return selectors; }, {} as Record< string, CssSelectorDiscovery > ); } function getAllowedContentTags( element: Element ): ReadonlyArray< string > { const allowedTags: Array< string > = [ ...ALLOWED_CONTENT_TAGS ]; if ( element.matches( 'ol, ul' ) ) { allowedTags.push( 'li' ); } if ( ! element.closest( 'a' ) ) { allowedTags.push( 'a' ); } return allowedTags; } function isRelevantElement( el: Element ): el is HTMLElement { const htmlEl = el as HTMLElement; if ( htmlEl.hidden ) { return false; } if ( htmlEl.getAttribute( 'aria-hidden' ) === 'true' ) { return false; } return true; }