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