From 3d259c07186c2751a3adf3ed4f8e71a83436a77a Mon Sep 17 00:00:00 2001 From: Gilles Devillard Date: Fri, 16 Jul 2021 15:00:45 +0100 Subject: [PATCH] Overwrite Switcher component --- .../components/Switcher/Switcher.js | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 src/gatsby-theme-carbon/components/Switcher/Switcher.js diff --git a/src/gatsby-theme-carbon/components/Switcher/Switcher.js b/src/gatsby-theme-carbon/components/Switcher/Switcher.js new file mode 100644 index 0000000..2756ced --- /dev/null +++ b/src/gatsby-theme-carbon/components/Switcher/Switcher.js @@ -0,0 +1,141 @@ +import React, { + useContext, + useRef, + useLayoutEffect, + useEffect, + useState, +} from 'react'; +import cx from 'classnames'; +import useMedia from 'use-media'; +import { Locked16 } from '@carbon/icons-react'; +import NavContext from 'gatsby-theme-carbon/src/util/context/NavContext'; +import { nav, open, divider, link, linkDisabled } from 'gatsby-theme-carbon/src/components/Switcher/Switcher.module.scss'; + +const Switcher = ({ children }) => { + const lgBreakpoint = useMedia('min-width: 1056px'); + const { switcherIsOpen, toggleNavState } = useContext(NavContext); + const listRef = useRef(null); + const [height, setHeight] = useState(0); + + useEffect(() => { + const collapseOpenNavs = function (e) { + if (e.which === 27) { + toggleNavState('switcherIsOpen', 'close'); + } + }; + + document.addEventListener('keyup', collapseOpenNavs); + + return function cleanup() { + document.removeEventListener('keyup', collapseOpenNavs); + }; + }, [toggleNavState]); + + // calculate and update height + useLayoutEffect(() => { + if (switcherIsOpen) { + setHeight(listRef.current.offsetHeight + 40); + } else { + setHeight(0); + } + }, [listRef, switcherIsOpen]); + + const maxHeight = !lgBreakpoint && switcherIsOpen ? '100%' : `${height}px`; + + return ( + + ); +}; + +export const SwitcherDivider = (props) => ( +
  • + +
  • +); + +export const SwitcherLink = ({ + disabled, + children, + isInternal, + href: hrefProp, + ...rest +}) => { + const href = disabled || !hrefProp ? undefined : hrefProp; + const className = disabled ? linkDisabled : link; + const { switcherIsOpen } = useContext(NavContext); + const openTabIndex = disabled ? '-1' : 0; + + return ( +
  • + + {children} + {isInternal && } + +
  • + ); +}; + +// https://css-tricks.com/using-css-transitions-auto-dimensions/ +// Note: if you change this, update the max-height in the switcher stylesheet +const DefaultChildren = () => ( + <> + Foundations + + IBM Brand Center + + + IBM Design Language + + Implementation + + Carbon Design System + + + Carbon for IBM.com + + + IBM Event Design + + Practices + + Enterprise Design Thinking + + + IBM Accessibility + + + IBM Design for AI + + + IBM Design Research + + + IBM iX + + Community + + IBM Design + + + Racial Equity in Design + + +); + +Switcher.defaultProps = { + children: , +}; + +export default Switcher;