| 1 |
import { Children, cloneElement, Fragment, useCallback, useEffect, useRef, useState } from 'react'; |
| 2 |
import { css } from '@patternfly/react-styles'; |
| 3 |
import styles from '@patternfly/react-styles/css/components/JumpLinks/jump-links'; |
| 4 |
import sidebarStyles from '@patternfly/react-styles/css/components/Sidebar/sidebar'; |
| 5 |
import RhMicronsCaretDownIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-down-icon'; |
| 6 |
import cssToggleDisplayVar from '@patternfly/react-tokens/dist/esm/c_jump_links__toggle_Display'; |
| 7 |
import { Button } from '../Button'; |
| 8 |
import { JumpLinksItem, JumpLinksItemProps } from './JumpLinksItem'; |
| 9 |
import { JumpLinksList } from './JumpLinksList'; |
| 10 |
import { canUseDOM, formatBreakpointMods } from '../../helpers/util'; |
| 11 |
import { useSSRSafeId } from '../../helpers'; |
| 12 |
|
| 13 |
export interface JumpLinksProps extends Omit<React.HTMLProps<HTMLElement>, 'label'> { |
| 14 |
/** Whether to center children. */ |
| 15 |
isCentered?: boolean; |
| 16 |
/** Whether the layout of children is vertical or horizontal. */ |
| 17 |
isVertical?: boolean; |
| 18 |
/** Label to add to nav element. */ |
| 19 |
label?: React.ReactNode; |
| 20 |
/** Flag to always show the label when using `expandable` */ |
| 21 |
alwaysShowLabel?: boolean; |
| 22 |
/** Adds an accessible label to the internal nav element. Defaults to the value of the label prop. */ |
| 23 |
'aria-label'?: string; |
| 24 |
/** Reference to the scrollable element to spy on. Takes precedence over scrollableSelector. Not passing a scrollableRef or scrollableSelector disables spying. */ |
| 25 |
scrollableRef?: HTMLElement | (() => HTMLElement) | React.RefObject<HTMLElement | null>; |
| 26 |
/** Selector for the scrollable element to spy on. Not passing a scrollableSelector or scrollableRef disables spying. */ |
| 27 |
scrollableSelector?: string; |
| 28 |
/** The index of the child Jump link to make active. */ |
| 29 |
activeIndex?: number; |
| 30 |
/** Children nodes */ |
| 31 |
children?: React.ReactNode; |
| 32 |
/** Offset to add to `scrollPosition`, potentially for a masthead which content scrolls under. */ |
| 33 |
offset?: number; |
| 34 |
/** When to collapse/expand at different breakpoints */ |
| 35 |
expandable?: { |
| 36 |
default?: 'expandable' | 'nonExpandable'; |
| 37 |
sm?: 'expandable' | 'nonExpandable'; |
| 38 |
md?: 'expandable' | 'nonExpandable'; |
| 39 |
lg?: 'expandable' | 'nonExpandable'; |
| 40 |
xl?: 'expandable' | 'nonExpandable'; |
| 41 |
'2xl'?: 'expandable' | 'nonExpandable'; |
| 42 |
}; |
| 43 |
/** On mobile whether or not the JumpLinks starts out expanded */ |
| 44 |
isExpanded?: boolean; |
| 45 |
/** Aria label for expandable toggle */ |
| 46 |
toggleAriaLabel?: string; |
| 47 |
/** Class for nav */ |
| 48 |
className?: string; |
| 49 |
/** Whether the current entry in the navigation history should be replaced when a JumpLinksItem is clicked. By default a new entry will be pushed to the navigation history. */ |
| 50 |
shouldReplaceNavHistory?: boolean; |
| 51 |
/** Custom ID applied to label if alwaysShowLabel is applied, or expandable toggle. This is used for internal logic related to aria-label and aria-labelledby */ |
| 52 |
labelId?: string; |
| 53 |
} |
| 54 |
|
| 55 |
// Recursively find JumpLinkItems and return an array of all their scrollNodes |
| 56 |
const getScrollItems = (children: React.ReactNode, res: HTMLElement[]) => { |
| 57 |
Children.forEach(children, (child: any) => { |
| 58 |
if (canUseDOM && document.getElementById && document.querySelector && child.type === JumpLinksItem) { |
| 59 |
const scrollNode = child.props.node || child.props.href; |
| 60 |
if (typeof scrollNode === 'string') { |
| 61 |
if (scrollNode.startsWith('#')) { |
| 62 |
// Allow spaces and other special characters as `id`s to be nicer to consumers |
| 63 |
// https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html |
| 64 |
res.push(document.getElementById(scrollNode.substr(1)) as HTMLElement); |
| 65 |
} else { |
| 66 |
res.push(document.querySelector(scrollNode) as HTMLElement); |
| 67 |
} |
| 68 |
} else if (scrollNode instanceof HTMLElement) { |
| 69 |
res.push(scrollNode); |
| 70 |
} |
| 71 |
} |
| 72 |
if ([Fragment, JumpLinksList, JumpLinksItem].includes(child.type)) { |
| 73 |
getScrollItems(child.props.children, res); |
| 74 |
} |
| 75 |
}); |
| 76 |
return res; |
| 77 |
}; |
| 78 |
|
| 79 |
function isResponsive(jumpLinks: HTMLElement) { |
| 80 |
// https://github.com/patternfly/patternfly/blob/main/src/patternfly/components/JumpLinks/jump-links.scss#L103 |
| 81 |
return jumpLinks && getComputedStyle(jumpLinks).getPropertyValue(cssToggleDisplayVar.name).includes('block'); |
| 82 |
} |
| 83 |
|
| 84 |
export const JumpLinks: React.FunctionComponent<JumpLinksProps> = ({ |
| 85 |
isCentered, |
| 86 |
isVertical, |
| 87 |
children, |
| 88 |
label, |
| 89 |
'aria-label': ariaLabel = typeof label === 'string' ? label : null, |
| 90 |
scrollableRef, |
| 91 |
scrollableSelector, |
| 92 |
activeIndex: activeIndexProp = 0, |
| 93 |
offset = 0, |
| 94 |
expandable, |
| 95 |
isExpanded: isExpandedProp = false, |
| 96 |
alwaysShowLabel = true, |
| 97 |
toggleAriaLabel = 'Toggle jump links', |
| 98 |
className, |
| 99 |
shouldReplaceNavHistory = false, |
| 100 |
labelId, |
| 101 |
...props |
| 102 |
}: JumpLinksProps) => { |
| 103 |
const generatedId = useSSRSafeId(); |
| 104 |
const hasScrollSpy = Boolean(scrollableRef || scrollableSelector); |
| 105 |
const [scrollItems, setScrollItems] = useState(hasScrollSpy ? getScrollItems(children, []) : []); |
| 106 |
const [activeIndex, setActiveIndex] = useState(activeIndexProp); |
| 107 |
const [isExpanded, setIsExpanded] = useState(isExpandedProp); |
| 108 |
// Boolean to disable scroll listener from overriding active state of clicked jumplink |
| 109 |
const isLinkClicked = useRef(false); |
| 110 |
const navRef = useRef<HTMLElement>(undefined); |
| 111 |
|
| 112 |
let scrollableElement: HTMLElement; |
| 113 |
|
| 114 |
if (!label && !ariaLabel) { |
| 115 |
// eslint-disable-next-line no-console |
| 116 |
console.warn('JumpLinks: for accessibility reasons, an aria-label should be specified if no label is provided'); |
| 117 |
} |
| 118 |
if (!label && !toggleAriaLabel && expandable) { |
| 119 |
// eslint-disable-next-line no-console |
| 120 |
console.warn('JumpLinks: for accessibility reasons, a toggleAriaLabel should be specified if no label is provided'); |
| 121 |
} |
| 122 |
|
| 123 |
const getScrollableElement = () => { |
| 124 |
if (scrollableRef) { |
| 125 |
if (scrollableRef instanceof HTMLElement) { |
| 126 |
return scrollableRef; |
| 127 |
} else if (typeof scrollableRef === 'function') { |
| 128 |
return scrollableRef(); |
| 129 |
} |
| 130 |
return (scrollableRef as React.RefObject<HTMLElement | null>).current; |
| 131 |
} else if (scrollableSelector) { |
| 132 |
return document.querySelector(scrollableSelector) as HTMLElement; |
| 133 |
} |
| 134 |
}; |
| 135 |
|
| 136 |
const scrollSpy = useCallback(() => { |
| 137 |
if (!canUseDOM || !hasScrollSpy || !(scrollableElement instanceof HTMLElement)) { |
| 138 |
return; |
| 139 |
} |
| 140 |
if (isLinkClicked.current) { |
| 141 |
isLinkClicked.current = false; |
| 142 |
return; |
| 143 |
} |
| 144 |
const scrollPosition = Math.ceil(scrollableElement.scrollTop + offset); |
| 145 |
window.requestAnimationFrame(() => { |
| 146 |
let newScrollItems = scrollItems; |
| 147 |
// Items might have rendered after this component or offsetTop values may need |
| 148 |
// to be updated. Do a quick refresh. |
| 149 |
const requiresRefresh = |
| 150 |
newScrollItems.every((e) => !e?.offsetTop) || !newScrollItems[0] || newScrollItems.includes(null); |
| 151 |
if (requiresRefresh) { |
| 152 |
newScrollItems = getScrollItems(children, []); |
| 153 |
setScrollItems(newScrollItems); |
| 154 |
} |
| 155 |
|
| 156 |
const scrollElements = newScrollItems |
| 157 |
.map((e, index) => ({ |
| 158 |
y: e ? e.offsetTop : null, |
| 159 |
index |
| 160 |
})) |
| 161 |
.filter(({ y }) => y !== null) |
| 162 |
.sort((e1, e2) => e2.y - e1.y); |
| 163 |
for (const { y, index } of scrollElements) { |
| 164 |
if (scrollPosition >= y) { |
| 165 |
return setActiveIndex(index); |
| 166 |
} |
| 167 |
} |
| 168 |
}); |
| 169 |
}, [scrollItems, hasScrollSpy, scrollableElement, offset]); |
| 170 |
|
| 171 |
useEffect(() => { |
| 172 |
scrollableElement = getScrollableElement(); |
| 173 |
if (!(scrollableElement instanceof HTMLElement)) { |
| 174 |
return; |
| 175 |
} |
| 176 |
scrollableElement.addEventListener('scroll', scrollSpy); |
| 177 |
|
| 178 |
return () => scrollableElement.removeEventListener('scroll', scrollSpy); |
| 179 |
}, [scrollableElement, scrollSpy, getScrollableElement]); |
| 180 |
|
| 181 |
useEffect(() => { |
| 182 |
scrollSpy(); |
| 183 |
}, []); |
| 184 |
|
| 185 |
let jumpLinkIndex = 0; |
| 186 |
const cloneChildren = (children: React.ReactNode): React.ReactNode => |
| 187 |
!hasScrollSpy |
| 188 |
? children |
| 189 |
: Children.map(children, (child: any) => { |
| 190 |
if (child.type === JumpLinksItem) { |
| 191 |
const { onClick: onClickProp, isActive: isActiveProp } = child.props; |
| 192 |
const itemIndex = jumpLinkIndex++; |
| 193 |
const scrollItem = scrollItems[itemIndex]; |
| 194 |
return cloneElement(child as React.ReactElement<JumpLinksItemProps>, { |
| 195 |
onClick(ev: React.MouseEvent) { |
| 196 |
isLinkClicked.current = true; |
| 197 |
// Items might have rendered after this component. Do a quick refresh. |
| 198 |
let newScrollItems; |
| 199 |
if (!scrollItem) { |
| 200 |
newScrollItems = getScrollItems(children, []); |
| 201 |
setScrollItems(newScrollItems); |
| 202 |
} |
| 203 |
const newScrollItem = scrollItem || newScrollItems[itemIndex]; |
| 204 |
|
| 205 |
if (newScrollItem) { |
| 206 |
// we have to support scrolling to an offset due to sticky sidebar |
| 207 |
const scrollableElement = getScrollableElement() as HTMLElement; |
| 208 |
if (scrollableElement instanceof HTMLElement) { |
| 209 |
if (isResponsive(navRef.current)) { |
| 210 |
// Remove class immediately so we can get collapsed height |
| 211 |
if (navRef.current) { |
| 212 |
navRef.current.classList.remove(styles.modifiers.expanded); |
| 213 |
} |
| 214 |
let stickyParent = navRef.current && navRef.current.parentElement; |
| 215 |
while (stickyParent && !stickyParent.classList.contains(sidebarStyles.modifiers.sticky)) { |
| 216 |
stickyParent = stickyParent.parentElement; |
| 217 |
} |
| 218 |
setIsExpanded(false); |
| 219 |
if (stickyParent) { |
| 220 |
offset += stickyParent.scrollHeight; |
| 221 |
} |
| 222 |
} |
| 223 |
scrollableElement.scrollTo(0, newScrollItem.offsetTop - offset); |
| 224 |
} |
| 225 |
newScrollItem.focus(); |
| 226 |
if (shouldReplaceNavHistory) { |
| 227 |
window.history.replaceState('', '', (ev.currentTarget as HTMLAnchorElement).href); |
| 228 |
} else { |
| 229 |
window.history.pushState('', '', (ev.currentTarget as HTMLAnchorElement).href); |
| 230 |
} |
| 231 |
ev.preventDefault(); |
| 232 |
setActiveIndex(itemIndex); |
| 233 |
} |
| 234 |
if (onClickProp) { |
| 235 |
onClickProp(ev); |
| 236 |
} |
| 237 |
}, |
| 238 |
isActive: isActiveProp || activeIndex === itemIndex, |
| 239 |
children: cloneChildren(child.props.children) |
| 240 |
}); |
| 241 |
} else if (child.type === Fragment) { |
| 242 |
return cloneChildren(child.props.children); |
| 243 |
} else if (child.type === JumpLinksList) { |
| 244 |
return cloneElement(child, { children: cloneChildren(child.props.children) }); |
| 245 |
} |
| 246 |
return child; |
| 247 |
}); |
| 248 |
|
| 249 |
const id = labelId ?? generatedId; |
| 250 |
const hasAriaLabelledBy = expandable || (label && alwaysShowLabel); |
| 251 |
const computedAriaLabel = hasAriaLabelledBy ? null : ariaLabel; |
| 252 |
const computedAriaLabelledBy = hasAriaLabelledBy ? id : null; |
| 253 |
|
| 254 |
return ( |
| 255 |
<nav |
| 256 |
className={css( |
| 257 |
styles.jumpLinks, |
| 258 |
isCentered && styles.modifiers.center, |
| 259 |
isVertical && styles.modifiers.vertical, |
| 260 |
formatBreakpointMods(expandable, styles), |
| 261 |
isExpanded && styles.modifiers.expanded, |
| 262 |
className |
| 263 |
)} |
| 264 |
aria-label={computedAriaLabel} |
| 265 |
ref={navRef} |
| 266 |
aria-labelledby={computedAriaLabelledBy} |
| 267 |
{...props} |
| 268 |
> |
| 269 |
<div className={styles.jumpLinksMain}> |
| 270 |
<div className={css(`${styles.jumpLinks}__header`)}> |
| 271 |
{expandable && ( |
| 272 |
<div className={styles.jumpLinksToggle}> |
| 273 |
<Button |
| 274 |
variant="plain" |
| 275 |
onClick={() => setIsExpanded(!isExpanded)} |
| 276 |
aria-label={label ? null : toggleAriaLabel} |
| 277 |
aria-expanded={isExpanded} |
| 278 |
icon={ |
| 279 |
<span className={styles.jumpLinksToggleIcon}> |
| 280 |
<RhMicronsCaretDownIcon /> |
| 281 |
</span> |
| 282 |
} |
| 283 |
id={id} |
| 284 |
> |
| 285 |
{label && label} |
| 286 |
</Button> |
| 287 |
</div> |
| 288 |
)} |
| 289 |
{label && alwaysShowLabel && !expandable && ( |
| 290 |
<div className={css(styles.jumpLinksLabel)} id={id}> |
| 291 |
{label} |
| 292 |
</div> |
| 293 |
)} |
| 294 |
</div> |
| 295 |
<ul |
| 296 |
aria-label={computedAriaLabel} |
| 297 |
aria-labelledby={computedAriaLabelledBy} |
| 298 |
className={styles.jumpLinksList} |
| 299 |
role="list" |
| 300 |
> |
| 301 |
{cloneChildren(children)} |
| 302 |
</ul> |
| 303 |
</div> |
| 304 |
</nav> |
| 305 |
); |
| 306 |
}; |
| 307 |
JumpLinks.displayName = 'JumpLinks'; |