Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Refactor and fix AppLayout and side navigation panel state and behaviour #1434

Merged
merged 17 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions pages/side-navigation/app-layout.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,14 @@ const items: SideNavigationProps.Item[] = [
];

export default function SideNavigationPage() {
const [open, setOpen] = React.useState(true);

return (
<AppLayout
toolsHide={true}
navigationOpen={true}
navigationOpen={open}
onNavigationChange={({ detail }) => {
setOpen(detail.open);
}}
contentType="form"
ariaLabels={{ navigationClose: 'Close' }}
navigation={
Expand Down
333 changes: 173 additions & 160 deletions src/app-layout/__tests__/common.test.tsx

Large diffs are not rendered by default.

128 changes: 108 additions & 20 deletions src/app-layout/__tests__/mobile.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React from 'react';
import React, { useState } from 'react';
import { act } from 'react-dom/test-utils';
import {
describeEachThemeAppLayout,
Expand All @@ -19,12 +19,33 @@ import toolbarStyles from '../../../lib/components/app-layout/mobile-toolbar/sty
import testUtilsStyles from '../../../lib/components/app-layout/test-classes/styles.css.js';
import visualRefreshRefactoredStyles from '../../../lib/components/app-layout/visual-refresh/styles.css.js';
import { findUpUntil } from '../../../lib/components/internal/utils/dom';
import SideNavigation from '../../../lib/components/side-navigation';

jest.mock('@cloudscape-design/component-toolkit/internal', () => ({
...jest.requireActual('@cloudscape-design/component-toolkit/internal'),
isMotionDisabled: jest.fn().mockReturnValue(true),
}));

function AppLayoutWithControlledNavigation({
initialNavigationOpen,
navigation,
}: {
initialNavigationOpen: boolean;
navigation: React.ReactNode;
}) {
const [navigationOpen, setNavigationOpen] = useState(initialNavigationOpen);

return (
<AppLayout
navigationOpen={navigationOpen}
onNavigationChange={({ detail }) => {
setNavigationOpen(detail.open);
}}
navigation={navigation}
/>
);
}

describeEachThemeAppLayout(true, theme => {
// In refactored Visual Refresh different styles are used compared to Classic
const mobileBarClassName = theme === 'refresh' ? testUtilsStyles['mobile-bar'] : toolbarStyles['mobile-bar'];
Expand All @@ -43,6 +64,37 @@ describeEachThemeAppLayout(true, theme => {
expect(wrapper.findToolsToggle().getElement()).toBeEnabled();
});

test('AppLayout with controlled navigation has navigation forcely closed on initial load', () => {
const { wrapper } = renderComponent(
<AppLayoutWithControlledNavigation
initialNavigationOpen={true}
navigation={
<>
<h1>Navigation</h1>
<a href="test">Link</a>
</>
}
/>
);
// AppLayout forcely closes the navigation on the first load on mobile, so the main content is visible
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);
});

test('AppLayout with uncontrolled navigation has navigation forcely closed on initial load', () => {
const { wrapper } = renderComponent(
<AppLayout
navigation={
<>
<h1>Navigation</h1>
<a href="test">Link</a>
</>
}
/>
);
// AppLayout forcely closes the navigation on the first load on mobile, so the main content is visible
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);
});

test('renders open navigation state', () => {
const { wrapper } = renderComponent(<AppLayout navigationOpen={true} onNavigationChange={() => {}} />);
expect(wrapper.findNavigation()).toBeTruthy();
Expand Down Expand Up @@ -83,30 +135,58 @@ describeEachThemeAppLayout(true, theme => {
});

test('closes navigation when clicking on links', () => {
const onNavigationChange = jest.fn();
const { wrapper } = renderComponent(
<AppLayout
navigationOpen={true}
onNavigationChange={onNavigationChange}
<AppLayoutWithControlledNavigation
initialNavigationOpen={true}
navigation={
<>
<h1>Navigation</h1>
<a href="#">Link</a>
<a href="test">Link</a>
</>
}
/>
);
// AppLayout forcely closes the navigation on the first load on mobile, so the main content is visible
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);

wrapper.findNavigationToggle().click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(false);

wrapper.findNavigation().find('a')!.click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);
});

test('closes navigation when clicking on a link in the Side Navigation component', () => {
const { wrapper } = renderComponent(
<AppLayoutWithControlledNavigation
initialNavigationOpen={true}
navigation={
<SideNavigation
items={[
{
type: 'link',
text: 'Page 1',
href: '#/page1',
},
]}
/>
}
/>
);
// AppLayout forcely closes the navigation on the first load on mobile, so the main content is visible
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);

wrapper.findNavigationToggle().click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(false);

expect(onNavigationChange).toHaveBeenCalledWith(expect.objectContaining({ detail: { open: false } }));
wrapper.findNavigation().find('a')!.click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);
});

test('does not close navigation when anchor without href was clicked', () => {
const onNavigationChange = jest.fn();
const { wrapper } = renderComponent(
<AppLayout
navigationOpen={true}
onNavigationChange={onNavigationChange}
<AppLayoutWithControlledNavigation
initialNavigationOpen={true}
navigation={
<>
<h1>Navigation</h1>
Expand All @@ -115,28 +195,36 @@ describeEachThemeAppLayout(true, theme => {
}
/>
);
wrapper.findNavigation().find('a')!.click();
// AppLayout forcely closes the navigation on the first load on mobile, so the main content is visible
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);

wrapper.findNavigationToggle().click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(false);

expect(onNavigationChange).not.toHaveBeenCalled();
wrapper.findNavigation().find('a')!.click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(false);
});

test('does not close navigation when other elements were clicked', () => {
const onNavigationChange = jest.fn();
const { wrapper } = renderComponent(
<AppLayout
navigationOpen={true}
onNavigationChange={onNavigationChange}
<AppLayoutWithControlledNavigation
initialNavigationOpen={true}
navigation={
<>
<h1>Navigation</h1>
<a href="#">Link</a>
<a>Link</a>
</>
}
/>
);
wrapper.findNavigation().find('h1')!.click();
// AppLayout forcely closes the navigation on the first load on mobile, so the main content is visible
expect(isDrawerClosed(wrapper.findNavigation())).toBe(true);

expect(onNavigationChange).not.toHaveBeenCalled();
wrapper.findNavigationToggle().click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(false);

wrapper.findNavigation().find('h1')!.click();
expect(isDrawerClosed(wrapper.findNavigation())).toBe(false);
});

test('does not close tools when clicking on any element', () => {
Expand Down
4 changes: 2 additions & 2 deletions src/app-layout/__tests__/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function describeEachThemeAppLayout(isMobile: boolean, callback: (theme:
}
}

export function describeEachAppLayout(callback: () => void) {
export function describeEachAppLayout(callback: (size: 'desktop' | 'mobile') => void) {
for (const theme of ['refresh', 'classic']) {
for (const size of ['desktop', 'mobile']) {
describe(`Theme=${theme}, Size=${size}`, () => {
Expand All @@ -87,7 +87,7 @@ export function describeEachAppLayout(callback: () => void) {
(useMobile as jest.Mock).mockReset();
(useVisualRefresh as jest.Mock).mockReset();
});
callback();
callback(size as 'desktop' | 'mobile');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: Instead of casting the value of the variable (technically not safe), it would be better to cast the array that you iterate over (const size of ['desktop', 'mobile'] as const)

});
}
}
Expand Down
20 changes: 12 additions & 8 deletions src/app-layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,14 +170,11 @@ const OldAppLayout = React.forwardRef(
setLastInteraction: setDrawerLastInteraction,
} = useDrawerFocusControl([activeDrawer?.resizable], toolsOpen || activeDrawer !== undefined, true);

const onNavigationToggle = useCallback(
(open: boolean) => {
setNavigationOpen(open);
focusNavButtons();
fireNonCancelableEvent(onNavigationChange, { open });
},
[setNavigationOpen, onNavigationChange, focusNavButtons]
);
const onNavigationToggle = useStableCallback((open: boolean) => {
setNavigationOpen(open);
focusNavButtons();
fireNonCancelableEvent(onNavigationChange, { open });
});
const onToolsToggle = useCallback(
(open: boolean) => {
setToolsOpen(open);
Expand All @@ -197,6 +194,13 @@ const OldAppLayout = React.forwardRef(
}
};

useEffect(() => {
// Close navigation drawer on mobile so that the main content is visible
if (isMobile) {
onNavigationToggle(false);
}
}, [isMobile, onNavigationToggle]);

const navigationVisible = !navigationHide && navigationOpen;
const toolsVisible = !toolsHide && toolsOpen;

Expand Down
22 changes: 13 additions & 9 deletions src/app-layout/visual-refresh/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { SplitPanelSideToggleProps } from '../../internal/context/split-panel-co
import { useObservedElement } from '../utils/use-observed-element';
import { useMobile } from '../../internal/hooks/use-mobile';
import { DrawerItem, InternalDrawerProps } from '../drawer/interfaces';
import { warnOnce } from '@cloudscape-design/component-toolkit/internal';
import { useStableCallback, warnOnce } from '@cloudscape-design/component-toolkit/internal';
import useResize from '../utils/use-resize';
import styles from './styles.css.js';
import { useContainerQuery } from '@cloudscape-design/component-toolkit';
Expand Down Expand Up @@ -178,14 +178,18 @@ export const AppLayoutInternalsProvider = React.forwardRef(

const { refs: navigationRefs, setFocus: focusNavButtons } = useFocusControl(isNavigationOpen);

const handleNavigationClick = useCallback(
function handleNavigationChange(isOpen: boolean) {
setIsNavigationOpen(isOpen);
focusNavButtons();
fireNonCancelableEvent(props.onNavigationChange, { open: isOpen });
},
[props.onNavigationChange, setIsNavigationOpen, focusNavButtons]
);
const handleNavigationClick = useStableCallback(function handleNavigationChange(isOpen: boolean) {
setIsNavigationOpen(isOpen);
focusNavButtons();
fireNonCancelableEvent(props.onNavigationChange, { open: isOpen });
});

useEffect(() => {
// Close navigation drawer on mobile so that the main content is visible
if (isMobile) {
handleNavigationClick(false);
}
}, [isMobile, handleNavigationClick]);

/**
* The useControllable hook will set the default value and manage either
Expand Down
17 changes: 15 additions & 2 deletions src/expandable-section/expandable-section-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ interface ExpandableDefaultHeaderProps {

interface ExpandableNavigationHeaderProps extends Omit<ExpandableDefaultHeaderProps, 'onKeyUp' | 'onKeyDown'> {
ariaLabelledBy?: string;
disableExpandChangeOnHeaderTextClick?: boolean;
}

interface ExpandableHeaderTextWrapperProps extends ExpandableDefaultHeaderProps {
Expand All @@ -49,6 +50,7 @@ interface ExpandableSectionHeaderProps extends Omit<ExpandableDefaultHeaderProps
headerActions?: ReactNode;
headingTagOverride?: ExpandableSectionProps.HeadingTag;
ariaLabelledBy?: string;
disableExpandChangeOnHeaderTextClick?: boolean;
}

const ExpandableDeprecatedHeader = ({
Expand Down Expand Up @@ -93,20 +95,29 @@ const ExpandableNavigationHeader = ({
expanded,
children,
icon,
disableExpandChangeOnHeaderTextClick,
}: ExpandableNavigationHeaderProps) => {
// By using `disableExpandChangeOnHeaderTextClick`, clicking the header text will not toggle the expandable section.
// We use this for the "expandable-link-group" in the side navigation.
return (
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<ExpandableNavigationHeader /> is rendered conditionally only for the navigation variant, so the change below is only applied to this variant.

if (variant === 'navigation') {
return (
<ExpandableNavigationHeader
className={clsx(className, wrapperClassName)}
ariaLabelledBy={ariaLabelledBy}
{...defaultHeaderProps}
>
{headerText ?? header}
</ExpandableNavigationHeader>
);
}

<div id={id} className={clsx(className, styles['click-target'])} onClick={onClick}>
<div id={id} className={clsx(className, styles['click-target'])}>
<button
className={clsx(styles['icon-container'], styles['expand-button'])}
aria-labelledby={ariaLabelledBy}
aria-label={ariaLabel}
aria-controls={ariaControls}
aria-expanded={expanded}
type="button"
onClick={onClick}
>
{icon}
</button>
{children}
<span
className={styles['click-target-content']}
onClick={disableExpandChangeOnHeaderTextClick ? () => {} : onClick}
>
{children}
</span>
</div>
);
};
Expand Down Expand Up @@ -221,6 +232,7 @@ export const ExpandableSectionHeader = ({
onKeyUp,
onKeyDown,
onClick,
disableExpandChangeOnHeaderTextClick,
}: ExpandableSectionHeaderProps) => {
const icon = (
<InternalIcon
Expand Down Expand Up @@ -256,6 +268,7 @@ export const ExpandableSectionHeader = ({
<ExpandableNavigationHeader
className={clsx(className, wrapperClassName)}
ariaLabelledBy={ariaLabelledBy}
disableExpandChangeOnHeaderTextClick={disableExpandChangeOnHeaderTextClick}
{...defaultHeaderProps}
>
{headerText ?? header}
Expand Down
5 changes: 4 additions & 1 deletion src/expandable-section/internal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import { ExpandableSectionHeader } from './expandable-section-header';
import { InternalBaseComponentProps } from '../internal/hooks/use-base-component';
import { variantSupportsDescription } from './utils';

type InternalExpandableSectionProps = ExpandableSectionProps & InternalBaseComponentProps;
type InternalExpandableSectionProps = ExpandableSectionProps &
InternalBaseComponentProps & { __disableExpandChangeOnHeaderTextClick?: boolean };

export default function InternalExpandableSection({
expanded: controlledExpanded,
Expand All @@ -35,6 +36,7 @@ export default function InternalExpandableSection({
headingTagOverride,
disableContentPaddings,
headerAriaLabel,
__disableExpandChangeOnHeaderTextClick = false,
__internalRootRef,
...props
}: InternalExpandableSectionProps) {
Expand Down Expand Up @@ -113,6 +115,7 @@ export default function InternalExpandableSection({
headerInfo={headerInfo}
headerActions={headerActions}
headingTagOverride={headingTagOverride}
disableExpandChangeOnHeaderTextClick={__disableExpandChangeOnHeaderTextClick}
{...triggerProps}
/>
}
Expand Down
3 changes: 3 additions & 0 deletions src/expandable-section/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ $icon-total-space-medium: calc(#{$icon-width-medium} + #{$icon-margin-left} + #{

.click-target {
cursor: pointer;
&-content {
display: inherit;
}
&:not(.wrapper-container):not(.header-container-button):hover {
color: awsui.$color-text-expandable-section-hover;
}
Expand Down
Loading
Loading