carbon-react
Version:
A library of reusable React components for easily building user interfaces.
2 lines (1 loc) • 2.42 kB
JavaScript
import{jsxs as t,jsx as e}from"react/jsx-runtime";import n,{useMemo as r,useState as o,useRef as i,useCallback as a,useEffect as c}from"react";import{isFragment as l}from"react-is";import s from"invariant";import m from"lodash/throttle";import{defaultFocusableSelectors as d}from"../../__internal__/focus-trap/focus-trap-utils.js";import p from"../../__internal__/utils/helpers/events/events.js";import{StyledAnchorNavigation as u,StyledNavigation as h,StyledContent as v}from"./anchor-navigation.style.js";import f from"./anchor-navigation-item/anchor-navigation-item.component.js";const g=({children:g,stickyNavigation:y,"data-element":w,"data-role":N})=>{s(l(y),"`stickyNavigation` prop in `AnchorNavigation` should be a React Fragment.");const b=r((()=>!n.Children.toArray(y.props.children).find((t=>!n.isValidElement(t)||"AnchorNavigationItem"!==t.type.displayName))),[y]);s(b,`\`stickyNavigation\` prop in \`AnchorNavigation\` should be a React Fragment that only contains children of type \`${f.displayName}\``);const[A,_]=o(0),k=i(n.Children.map(y.props.children,(t=>t.props.target))),C=i(null),R=i(null),j=i(!0),E=i(),x=a((()=>{if(null===R.current)return;const t=k.current.map((({current:t},e)=>[e,null==t?void 0:t.getBoundingClientRect().top])).filter((t=>void 0!==t[1])),{top:e}=R.current.getBoundingClientRect(),n=t.reduce(((n,r)=>{const[o,i]=r;return i-200>e?n:i>t[n][1]?o:n}),t[0][0]);_(n)}),[]),T=r((()=>m((()=>{j.current?x():(void 0!==E.current&&window.clearTimeout(E.current),E.current=setTimeout((()=>{j.current=!0}),150))}),100)),[x]);c((()=>(window.addEventListener("scroll",T,!0),()=>window.removeEventListener("scroll",T,!0))),[T]);const B=t=>{const e=k.current[t].current;var n;null!==e&&(e.dataset.carbonAnchornavRef||(e.dataset.carbonAnchornavRef="true"),(n=e).matches(d)||n.setAttribute("tabindex","-1"),n.focus({preventScroll:!0}),window.setTimeout((()=>{j.current=!1,e.scrollIntoView({block:"start",inline:"nearest",behavior:"smooth"}),_(t)}),10))};return t(u,{ref:C,"data-component":"anchor-navigation","data-element":w,"data-role":N,children:[e(h,{ref:R,"data-element":"anchor-sticky-navigation",children:n.Children.map(y.props.children,((t,e)=>n.cloneElement(t,{href:t.props.href||"#",isSelected:e===A,onClick:t=>((t,e)=>{t.preventDefault(),B(e)})(t,e),onKeyDown:t=>((t,e)=>{p.isEnterKey(t)&&B(e)})(t,e)})))}),e(v,{children:g})]})};g.displayName="AnchorNavigation";export{g as default};