UNPKG

@scania/tegel

Version:
69 lines (63 loc) 2.93 kB
import { d as dfs } from './p-52bf0fdf.js'; /** * Checks if the given element is a heading element (h1-h6) or has a role of "heading". * * @param {HTMLElement} el - The element to check. * @returns {boolean} - True if the element is a heading element, false otherwise. */ const isHeadingElement = (el) => { const tagName = el.tagName.toLowerCase(); const role = el.getAttribute('role'); return ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tagName) || role === 'heading'; }; // A higher-order function to find the nested child of siblings matching a predicate, // based on a sibling traversal function (getNextSibling or getPreviousSibling). function getNestedChildOfSiblingsMatching(element, searchPredicate, siblingTraversalFn) { // Start with the sibling of the provided element. let sibling = siblingTraversalFn(element); // Iterate through the siblings until there are no more siblings. while (sibling) { // Use the dfs helper function to find the deeply nested child // that matches the given criteria within the current sibling. const nestedChild = dfs(sibling, searchPredicate); // If a matching deeply nested child is found, return it. if (nestedChild) { return nestedChild; } // Move on to the next sibling. sibling = siblingTraversalFn(sibling); } // If no matching deeply nested child is found, return null. return null; } const getPreviousSibling = (element) => element.previousElementSibling; /** * Searches for a previous sibling element that has a nested child element matching the provided search predicate. * The search starts from the given element and proceeds to its previous siblings, diving deep into each sibling's descendants. * * @param {HTMLElement} element - The starting element to begin the search from. * @param {(el: HTMLElement) => boolean} searchPredicate - A predicate function that checks if an element matches the desired condition. * @returns {HTMLElement | null} - The matching nested child element, or null if no matching element is found. * * @example * // HTML structure: * // <div> * // <h1>Heading 1</h1> * // <ul role="list"> * // <li>Item 1</li> * // </ul> * // </div> * // <div> * // <h2>Heading 2</h2> * // <ul role="list"> * // <li>Item 2</li> * // </ul> * // </div> * * const searchPredicate = (el) => el.tagName.toLowerCase() === 'h2'; * const startingElement = document.querySelector('[role="list"]'); * const headingEl = getPreviousNestedChildOfSiblingsMatching(startingElement, searchPredicate); * console.log(headingEl); // Logs the <h2>Heading 2</h2> element */ const getPreviousNestedChildOfSiblingsMatching = (element, searchPredicate) => getNestedChildOfSiblingsMatching(element, searchPredicate, getPreviousSibling); export { getPreviousNestedChildOfSiblingsMatching as g, isHeadingElement as i };