polen
Version:
A framework for delightful GraphQL developer portals
48 lines • 2 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { Link as LinkReactRouter, useLocation } from 'react-router';
// todo: #lib/kit-temp does not work as import
import { ObjPartition } from '../../lib/kit-temp.js';
import { useClientOnly } from '../hooks/useClientOnly.js';
import { LinkRadix } from './RadixLink.js';
const reactRouterPropKeys = [
`discover`,
`prefetch`,
`reloadDocument`,
`replace`,
`state`,
`preventScrollReset`,
`relative`,
`to`,
`viewTransition`,
`children`,
];
export const Link = props => {
const location = useLocation();
const toPathExp = typeof props.to === `string` ? props.to : props.to.pathname || ``;
const active = useClientOnly(() => getPathActiveReport(toPathExp, location.pathname), { is: false, isDirect: false, isDescendant: false });
const { picked: reactRouterProps, omitted: radixProps } = ObjPartition(props, reactRouterPropKeys);
// Only add data attributes if they're true
const linkRadixProps = {
...radixProps,
asChild: true,
...(active.is && { 'data-active': true }),
...(active.isDirect && { 'data-active-direct': true }),
...(active.isDescendant && { 'data-active-descendant': true }),
};
return (_jsx(LinkRadix, { ...linkRadixProps, children: _jsx(LinkReactRouter, { ...reactRouterProps }) }));
};
export const getPathActiveReport = (pathExp, currentPathExp) => {
// Normalize both paths for comparison
const normalizedPath = pathExp.startsWith(`/`) ? pathExp.slice(1) : pathExp;
const normalizedCurrentPath = currentPathExp.startsWith(`/`) ? currentPathExp.slice(1) : currentPathExp;
const isDirect = normalizedCurrentPath === normalizedPath;
const isDescendant = normalizedCurrentPath.startsWith(normalizedPath + `/`)
&& normalizedCurrentPath !== normalizedPath;
const is = isDirect || isDescendant;
return {
is,
isDirect,
isDescendant,
};
};
//# sourceMappingURL=Link.js.map