breadcrumbs

This commit is contained in:
2025-10-31 17:24:39 +01:00
parent d14d263e8f
commit 1a1e9a80c3
6 changed files with 633 additions and 38 deletions
+431
View File
@@ -0,0 +1,431 @@
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import PropTypes from 'prop-types';
const normalizeEntries = (entries) =>
(Array.isArray(entries) ? entries : [])
.map((entry, index) => {
if (!entry) {
return null;
}
const id = entry.id ?? entry.value ?? index;
const label = entry.label ?? entry.name ?? entry.title ?? '';
const onClick = typeof entry.onClick === 'function' ? entry.onClick : null;
return label ? { id, label, onClick, raw: entry } : null;
})
.filter(Boolean);
const ELLIPSIS = { id: '__breadcrumbs_ellipsis__', label: '…', onClick: null, raw: null };
const BreadcrumbTrail = ({ entries = [], className = '', separator = '/' }) => {
const normalized = useMemo(() => normalizeEntries(entries), [entries]);
const containerRef = useRef(null);
const measurementRef = useRef(null);
const ellipsisRef = useRef(null);
const menuRef = useRef(null);
const [availableWidth, setAvailableWidth] = useState(null);
const [startIndex, setStartIndex] = useState(0);
const [showHiddenMenu, setShowHiddenMenu] = useState(false);
const [menuPosition, setMenuPosition] = useState(null);
useEffect(() => {
setStartIndex(0);
setShowHiddenMenu(false);
setMenuPosition(null);
}, [normalized]);
useEffect(() => {
const container = containerRef.current;
if (!container || typeof ResizeObserver === 'undefined') {
return undefined;
}
const target = container.parentElement || container;
const updateWidth = () => {
const nextWidth = target.getBoundingClientRect().width;
if (!nextWidth) {
return;
}
setAvailableWidth((prev) => (prev && Math.abs(prev - nextWidth) < 0.5 ? prev : nextWidth));
};
updateWidth();
const observer = new ResizeObserver(updateWidth);
observer.observe(target);
return () => observer.disconnect();
}, []);
useLayoutEffect(() => {
if (!normalized.length) {
return;
}
const container = containerRef.current;
const measurement = measurementRef.current;
if (!container || !measurement) {
return;
}
const entryNodes = Array.from(measurement.querySelectorAll('[data-item-type="entry"]'));
if (!entryNodes.length) {
return;
}
const separatorNodes = Array.from(measurement.querySelectorAll('[data-item-type="separator"]'));
const ellipsisNode = measurement.querySelector('[data-item-type="ellipsis"]');
const originalEntryDisplay = entryNodes.map((node) => node.style.display);
const originalSeparatorDisplay = separatorNodes.map((node) => node.style.display);
const originalEllipsisDisplay = ellipsisNode ? ellipsisNode.style.display : null;
const widths = [];
for (let start = 0; start < entryNodes.length; start += 1) {
entryNodes.forEach((node, index) => {
// Hide entries that fall before the visible window.
// eslint-disable-next-line no-param-reassign
node.style.display = index < start ? 'none' : '';
});
separatorNodes.forEach((node) => {
const targetIndex = Number(node.getAttribute('data-target-index'));
// eslint-disable-next-line no-param-reassign
node.style.display = targetIndex < Math.max(start, 1) ? 'none' : '';
});
if (ellipsisNode) {
// eslint-disable-next-line no-param-reassign
ellipsisNode.style.display = start > 0 ? '' : 'none';
}
widths[start] = measurement.getBoundingClientRect().width;
}
entryNodes.forEach((node, index) => {
// eslint-disable-next-line no-param-reassign
node.style.display = originalEntryDisplay[index] ?? '';
});
separatorNodes.forEach((node, index) => {
// eslint-disable-next-line no-param-reassign
node.style.display = originalSeparatorDisplay[index] ?? '';
});
if (ellipsisNode) {
// eslint-disable-next-line no-param-reassign
ellipsisNode.style.display = originalEllipsisDisplay ?? 'none';
}
const available = availableWidth ?? container.clientWidth;
if (!available || !widths.length) {
return;
}
const TOLERANCE = 1;
// Reserve a tiny buffer so the live trail doesn't oscillate when the
// container width barely fits; shrink the measured allowance a bit.
const adjustedAvailable = available * 0.98;
let nextStart = widths.length - 1;
for (let start = 0; start < widths.length; start += 1) {
if (widths[start] <= adjustedAvailable + TOLERANCE) {
nextStart = start;
break;
}
}
if (nextStart !== startIndex) {
setStartIndex(nextStart);
}
}, [normalized, separator, availableWidth, startIndex]);
useEffect(() => {
if (!showHiddenMenu) {
return undefined;
}
if (typeof document === 'undefined') {
setShowHiddenMenu(false);
setMenuPosition(null);
return undefined;
}
const handleGlobalInteraction = (event) => {
const ellipsisEl = ellipsisRef.current;
const menuEl = menuRef.current;
if ((ellipsisEl && ellipsisEl.contains(event.target))
|| (menuEl && menuEl.contains(event.target))) {
return;
}
setShowHiddenMenu(false);
setMenuPosition(null);
};
const handleKey = (event) => {
if (event.key === 'Escape') {
setShowHiddenMenu(false);
setMenuPosition(null);
}
};
document.addEventListener('mousedown', handleGlobalInteraction);
document.addEventListener('touchstart', handleGlobalInteraction, { passive: true });
document.addEventListener('focusin', handleGlobalInteraction);
document.addEventListener('keydown', handleKey);
return () => {
document.removeEventListener('mousedown', handleGlobalInteraction);
document.removeEventListener('touchstart', handleGlobalInteraction);
document.removeEventListener('focusin', handleGlobalInteraction);
document.removeEventListener('keydown', handleKey);
};
}, [showHiddenMenu]);
useEffect(() => {
if (!showHiddenMenu) {
return undefined;
}
if (typeof window === 'undefined') {
setShowHiddenMenu(false);
setMenuPosition(null);
return undefined;
}
const handleWindowChange = () => {
if (!ellipsisRef.current) {
setShowHiddenMenu(false);
setMenuPosition(null);
return;
}
const rect = ellipsisRef.current.getBoundingClientRect();
const menuWidth = 192;
const viewportWidth = window.innerWidth;
const left = Math.min(Math.max(rect.left, 8), Math.max(viewportWidth - menuWidth - 8, 8));
setMenuPosition({
top: rect.bottom + 6,
left,
minWidth: menuWidth,
});
};
handleWindowChange();
window.addEventListener('resize', handleWindowChange);
window.addEventListener('scroll', handleWindowChange, true);
return () => {
window.removeEventListener('resize', handleWindowChange);
window.removeEventListener('scroll', handleWindowChange, true);
};
}, [showHiddenMenu]);
if (!normalized.length) {
return null;
}
const sliceStart = Math.min(startIndex, Math.max(0, normalized.length - 1));
const slice = normalized.slice(sliceStart);
const visibleEntries = sliceStart > 0 ? [ELLIPSIS, ...slice] : slice;
const hiddenEntries = sliceStart > 0 ? normalized.slice(0, sliceStart) : [];
const hasHiddenEntries = hiddenEntries.length > 0;
const wrapperClassName = className
? `breadcrumb-trail ${className}`.trim()
: 'breadcrumb-trail';
useEffect(() => {
if (!hasHiddenEntries && showHiddenMenu) {
setShowHiddenMenu(false);
setMenuPosition(null);
}
}, [hasHiddenEntries, showHiddenMenu]);
return (
<>
<span ref={containerRef} className={wrapperClassName}>
{visibleEntries.map((entry, index) => {
const isEllipsis = entry.id === ELLIPSIS.id;
const isLast = index === visibleEntries.length - 1;
const commonProps = {
className: `breadcrumb-trail__link${isLast && !isEllipsis ? ' is-current' : ''}`,
title: entry.label,
'aria-current': isLast && !isEllipsis ? 'page' : undefined,
};
if (isEllipsis) {
return (
<React.Fragment key="breadcrumb-ellipsis">
{index > 0 ? (
<span className="breadcrumb-trail__separator" aria-hidden="true">
{separator}
</span>
) : null}
<span className="breadcrumb-trail__ellipsis" ref={ellipsisRef}>
<button
type="button"
className="breadcrumb-trail__link breadcrumb-trail__ellipsis-button"
aria-haspopup="menu"
aria-expanded={showHiddenMenu}
onClick={() => {
if (!hasHiddenEntries) {
setShowHiddenMenu(false);
setMenuPosition(null);
return;
}
if (showHiddenMenu) {
setShowHiddenMenu(false);
setMenuPosition(null);
return;
}
if (!ellipsisRef.current) {
setShowHiddenMenu(false);
setMenuPosition(null);
return;
}
const rect = ellipsisRef.current.getBoundingClientRect();
const menuWidth = 192;
const viewportWidth = typeof window !== 'undefined'
? Math.max(window.innerWidth, menuWidth)
: menuWidth;
const left = Math.min(
Math.max(rect.left, 8),
Math.max(viewportWidth - menuWidth - 8, 8),
);
setMenuPosition({
top: rect.bottom + 6,
left,
minWidth: menuWidth,
});
setShowHiddenMenu(true);
}}
title="Show parent folders"
>
{entry.label}
</button>
</span>
</React.Fragment>
);
}
const content = !entry.onClick || isLast
? (
<span key={`${entry.id}-label`} {...commonProps}>
{entry.label}
</span>
)
: (
<button
key={`${entry.id}-button`}
type="button"
{...commonProps}
onClick={() => entry.onClick?.(entry.raw ?? entry)}
>
{entry.label}
</button>
);
return (
<React.Fragment key={entry.id || index}>
{index > 0 ? (
<span className="breadcrumb-trail__separator" aria-hidden="true">
{separator}
</span>
) : null}
{content}
</React.Fragment>
);
})}
</span>
<span
ref={measurementRef}
className="breadcrumb-trail breadcrumb-trail--measure"
aria-hidden="true"
>
<span
className="breadcrumb-trail__link breadcrumb-trail__ellipsis-button"
data-item-type="ellipsis"
style={{ display: 'none' }}
>
{ELLIPSIS.label}
</span>
{normalized.map((entry, index) => (
<React.Fragment key={`measure-${entry.id || index}`}>
{index > 0 ? (
<span
className="breadcrumb-trail__separator"
data-item-type="separator"
data-target-index={index}
>
{separator}
</span>
) : null}
<span
className="breadcrumb-trail__link"
data-item-type="entry"
data-entry-index={index}
>
{entry.label}
</span>
</React.Fragment>
))}
</span>
{showHiddenMenu && hasHiddenEntries && menuPosition && typeof document !== 'undefined'
? createPortal(
<div
className="menu menu--floating"
role="menu"
style={{
position: 'fixed',
top: `${menuPosition.top}px`,
left: `${menuPosition.left}px`,
minWidth: `${menuPosition.minWidth}px`,
}}
ref={menuRef}
>
<div className="menu__list">
{hiddenEntries.map((hiddenEntry) => (
<button
key={hiddenEntry.id}
type="button"
className="menu__item"
role="menuitem"
onClick={() => {
setShowHiddenMenu(false);
setMenuPosition(null);
hiddenEntry.onClick?.(hiddenEntry.raw ?? hiddenEntry);
}}
disabled={!hiddenEntry.onClick}
>
<span className="menu__label">{hiddenEntry.label}</span>
</button>
))}
</div>
</div>,
document.body,
)
: null}
</>
);
};
const breadcrumbEntryShape = PropTypes.shape({
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
name: PropTypes.string,
label: PropTypes.string,
title: PropTypes.string,
onClick: PropTypes.func,
});
BreadcrumbTrail.propTypes = {
entries: PropTypes.arrayOf(breadcrumbEntryShape),
className: PropTypes.string,
separator: PropTypes.string,
};
export default BreadcrumbTrail;