UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

103 lines (102 loc) 3.3 kB
"use client"; import _pushInstanceProperty from "core-js-pure/stable/instance/push.js"; import { useCallback, useEffect, useRef } from 'react'; function isHighlighted(cell) { return cell.classList.contains('dnb-table__td--highlight') || cell.classList.contains('dnb-table__th--highlight'); } function applyHighlight(table) { const highlightedColumns = new Set(); const thElements = table.querySelectorAll('thead th.dnb-table__th--highlight'); for (const th of Array.from(thElements)) { highlightedColumns.add(th.cellIndex); } const applied = []; for (let r = 0; r < table.rows.length; r++) { const row = table.rows[r]; for (let c = 0; c < row.cells.length; c++) { const cell = row.cells[c]; if (cell.tagName === 'TD' && highlightedColumns.has(c) && !cell.classList.contains('dnb-table__td--highlight')) { cell.classList.add('dnb-table__td--highlight'); _pushInstanceProperty(applied).call(applied, { cell, classes: ['dnb-table__td--highlight'] }); } } } for (let r = 0; r < table.rows.length; r++) { const row = table.rows[r]; const prevRow = r > 0 ? table.rows[r - 1] : null; for (let c = 0; c < row.cells.length; c++) { const cell = row.cells[c]; const cellIsHighlighted = isHighlighted(cell); if (cellIsHighlighted) { const prevCell = prevRow === null || prevRow === void 0 ? void 0 : prevRow.cells[c]; if (prevCell && isHighlighted(prevCell)) { cell.classList.add('dnb-table__td--highlight-border'); _pushInstanceProperty(applied).call(applied, { cell, classes: ['dnb-table__td--highlight-border'] }); } continue; } const classes = []; const leftCell = row.cells[c - 1]; if (leftCell && isHighlighted(leftCell)) { _pushInstanceProperty(classes).call(classes, 'dnb-table--highlight-neighbor-left'); } const rightCell = row.cells[c + 1]; if (rightCell && isHighlighted(rightCell)) { _pushInstanceProperty(classes).call(classes, 'dnb-table--highlight-neighbor-right'); } const topCell = prevRow === null || prevRow === void 0 ? void 0 : prevRow.cells[c]; if (topCell && isHighlighted(topCell)) { _pushInstanceProperty(classes).call(classes, 'dnb-table--highlight-neighbor-top'); } if (classes.length > 0) { cell.classList.add(...classes); _pushInstanceProperty(applied).call(applied, { cell, classes }); } } } return () => { for (const { cell, classes } of applied) { cell.classList.remove(...classes); } }; } export function useTableHighlight({ enabled = true } = {}) { const ref = useRef(null); const getTable = useCallback(() => { const el = ref.current; if (!el) { return null; } if (el.tagName === 'TABLE') { return el; } return el.querySelector('table'); }, []); useEffect(() => { const el = ref.current; if (!el || !enabled) { return undefined; } const table = getTable(); if (!table) { return undefined; } return applyHighlight(table); }); return ref; } //# sourceMappingURL=useTableHighlight.js.map