Skip to content

Commit

Permalink
Merge branch 'main' into DOP-4961
Browse files Browse the repository at this point in the history
  • Loading branch information
branberry authored Sep 13, 2024
2 parents 86c920d + fd564e8 commit 708c600
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 136 deletions.
8 changes: 0 additions & 8 deletions gatsby-ssr.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ export const onRenderBody = ({ setHeadComponents }) => {
__html: `!function(e,n){var t=document.createElement("script"),o=null,x="pathway";t.async=!0,t.src='https://'+x+'.mongodb.com/'+(e?x+'-debug.js':''),document.head.append(t),t.addEventListener("load",function(){o=window.pathway.default,(n&&o.configure(n)),o.createProfile("mongodbcom").load(),window.segment=o})}();`,
}}
/>,
// Delighted
<script
key="delighted"
type="text/javascript"
dangerouslySetInnerHTML={{
__html: `!function(e,t,r,n){if(!e[n]){for(var a=e[n]=[],i=["survey","reset","config","init","set","get","event","identify","track","page","screen","group","alias"],s=0;s<i.length;s++){var c=i[s];a[c]=a[c]||function(e){return function(){var t=Array.prototype.slice.call(arguments);a.push([e,t])}}(c)}a.SNIPPET_VERSION="1.0.1";var o=t.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://d2yyd1h5u9mauk.cloudfront.net/integrations/web/v1/library/"+r+"/"+n+".js";var l=t.getElementsByTagName("script")[0];l.parentNode.insertBefore(o,l)}}(window,document,"Dk30CC86ba0nATlK","delighted");`,
}}
/>,
// Client-side redirect based on browser's language settings
<script
key="browser-lang-redirect"
Expand Down
57 changes: 38 additions & 19 deletions src/components/Collapsible/index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { useLocation } from '@gatsbyjs/reach-router';
import Box from '@leafygreen-ui/box';
import Icon from '@leafygreen-ui/icon';
import IconButton from '@leafygreen-ui/icon-button';
import { cx } from '@leafygreen-ui/emotion';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';
import { Body } from '@leafygreen-ui/typography';
import { findAllNestedAttribute } from '../../utils/find-all-nested-attribute';
import { isBrowser } from '../../utils/is-browser';
import { reportAnalytics } from '../../utils/report-analytics';
import ComponentFactory from '../ComponentFactory';
import Heading from '../Heading';
import { collapsibleStyle, headerContainerStyle, headerStyle, iconStyle, innerContentStyle } from './styles';
import './styles.css';

const Collapsible = ({ nodeData: { children, options }, ...rest }) => {
const { darkMode } = useDarkMode();
const { id, heading, sub_heading: subHeading } = options;
const [open, setOpen] = useState(false);
const { hash } = useLocation();
const headingNodeData = useMemo(
() => ({
id,
children: [{ type: 'text', value: heading }],
}),
[heading, id]
);

// get a list of all ids in collapsible content
// in order to set collapsible open, if any are found in url hash
const childrenHashIds = useMemo(() => {
return findAllNestedAttribute(children, 'id');
}, [children]);

const [open, setOpen] = useState(false);
const headingNodeData = {
id,
children: [{ type: 'text', value: heading }],
};

const onIconClick = useCallback(() => {
reportAnalytics('CollapsibleClicked', {
Expand All @@ -34,12 +38,31 @@ const Collapsible = ({ nodeData: { children, options }, ...rest }) => {
setOpen(!open);
}, [heading, open]);

// open the collapsible if the hash in URL is equal to collapsible heading id,
// or if the collapsible's children has the id
useEffect(() => {
if (!isBrowser) {
return;
}
const hashId = hash?.slice(1) ?? '';
if (id === hashId || childrenHashIds.includes(hashId)) {
return setOpen(true);
}
}, [childrenHashIds, hash, id]);

const rendered = useRef(false);

// on first open, scroll the child with the URL hash id into view
useEffect(() => {
if (!open) return;
if (rendered.current) return;
rendered.current = true;
const hashId = hash?.slice(1) ?? '';
if (id === hashId) {
setOpen(true);
if (childrenHashIds.includes(hashId)) {
const child = document?.querySelector(`#${hashId}`);
child && child.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth' });
}
}, [hash, id]);
}, [childrenHashIds, hash, open]);

return (
<Box className={cx('collapsible', collapsibleStyle)}>
Expand All @@ -50,11 +73,7 @@ const Collapsible = ({ nodeData: { children, options }, ...rest }) => {
</Heading>
<Body baseFontSize={13}>{subHeading}</Body>
</Box>
<IconButton
className={iconStyle(darkMode)}
aria-labelledby={'Expand the collapsed content'}
onClick={onIconClick}
>
<IconButton className={iconStyle} aria-labelledby={'Expand the collapsed content'} onClick={onIconClick}>
<Icon glyph={open ? 'ChevronDown' : 'ChevronRight'} />
</IconButton>
</Box>
Expand Down
6 changes: 3 additions & 3 deletions src/components/Collapsible/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ export const headerStyle = css`
margin-top: 0;
`;

export const iconStyle = (darkMode) => css`
export const iconStyle = css`
align-self: center;
flex-shrink: 0;
${!darkMode && `color: ${palette.gray.dark1}`}
`;

export const innerContentStyle = (open) => css`
overflow: hidden;
height: 0;
visibility: hidden;
color: --font-color-primary;
${open && `height: auto;`}
${open && `visibility: visible;`}
`;
28 changes: 0 additions & 28 deletions src/hooks/useDelightedSurvey.js

This file was deleted.

2 changes: 0 additions & 2 deletions src/layouts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import Header from '../components/Header';
import { Sidenav } from '../components/Sidenav';
import RootProvider from '../components/RootProvider';
import { getTemplate } from '../utils/get-template';
import { useDelightedSurvey } from '../hooks/useDelightedSurvey';
import { usePresentationMode } from '../hooks/use-presentation-mode';
import { theme } from '../theme/docsTheme';
import useSnootyMetadata from '../utils/use-snooty-metadata';
Expand Down Expand Up @@ -99,7 +98,6 @@ const DefaultLayout = ({ children, data: { page }, pageContext: { slug, repoBran
() => page?.ast?.options?.title || slugToTitle?.[slug === '/' ? 'index' : slug],
[slug] // eslint-disable-line react-hooks/exhaustive-deps
);
useDelightedSurvey(slug, project);

return (
<>
Expand Down
2 changes: 0 additions & 2 deletions src/layouts/preview-layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import PreviewHeader from '../components/Header/preview-header';
import { Sidenav } from '../components/Sidenav';
import RootProvider from '../components/RootProvider';
import { getTemplate } from '../utils/get-template';
import { useDelightedSurvey } from '../hooks/useDelightedSurvey';
import { theme } from '../theme/docsTheme';
import { MetadataProvider } from '../utils/use-snooty-metadata';

Expand Down Expand Up @@ -142,7 +141,6 @@ const DefaultLayout = ({
const { chapters, guides, slugToTitle, toctree, eol } = metadata;

const pageTitle = React.useMemo(() => page?.options?.title || slugToTitle?.[slug === '/' ? 'index' : slug], [slug]); // eslint-disable-line react-hooks/exhaustive-deps
useDelightedSurvey(slug, metadata.project);

return (
<>
Expand Down
19 changes: 19 additions & 0 deletions src/utils/find-all-nested-attribute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Search all children nodes for attribute
* @param {node[]} nodes
* @param {string} attribute
* @returns {string[]}
*/
export const findAllNestedAttribute = (nodes, attribute) => {
const results = [];
const searchNode = (node) => {
if (Object.hasOwn(node, attribute)) {
results.push(node[attribute]);
}
if (node.children) {
node.children.forEach(searchNode);
}
};
nodes.forEach(searchNode);
return results;
};
1 change: 0 additions & 1 deletion tests/unit/Collapsible.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ describe('collapsible component', () => {
let icon = button.querySelector('[role=img]');
expect(icon.getAttribute('aria-label')).toContain('Chevron');
expect(icon.getAttribute('aria-label')).toContain('Right');
expect(collapsedContent).not.toBeVisible();

await act(async () => {
button.click();
Expand Down
3 changes: 1 addition & 2 deletions tests/unit/__snapshots__/Collapsible.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ exports[`collapsible component renders all the content in the options and childr
-webkit-flex-shrink: 0;
-ms-flex-negative: 0;
flex-shrink: 0;
color: #5C6C75;
}
.emotion-8:before {
Expand Down Expand Up @@ -175,7 +174,7 @@ exports[`collapsible component renders all the content in the options and childr
.emotion-10 {
overflow: hidden;
height: 0;
visibility: hidden;
color: --font-color-primary;
}
.emotion-11 {
Expand Down
71 changes: 0 additions & 71 deletions tests/unit/useDelightedSurvey.test.js

This file was deleted.

18 changes: 18 additions & 0 deletions tests/unit/utils/find-all-nested-attribute.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { findAllNestedAttribute } from '../../../src/utils/find-all-nested-attribute';
import figureData from '../data/Figure.test.json';
import headingData from '../data/Heading.test.json';
import footnoteData from '../data/Footnote.test.json';

describe('findAllNestedAttribute', () => {
it('gets all attribute from one level of children', () => {
const res = findAllNestedAttribute([figureData, headingData, footnoteData], 'id');
expect(res).toEqual(['create-an-administrative-username-and-password', 'id8']);
});

it('gets all attributes from multiple children levels', () => {
const headingWithChildren = { ...headingData };
headingWithChildren.children = [headingData, footnoteData];
const res = findAllNestedAttribute([headingWithChildren], 'type');
expect(res).toEqual(['heading', 'heading', 'text', 'footnote', 'paragraph', 'text']);
});
});

0 comments on commit 708c600

Please sign in to comment.