Skip to content

Commit

Permalink
when clicking on toc entry, focus on respective heading in content (#…
Browse files Browse the repository at this point in the history
…7845)

Co-authored-by: katiegoines <katiegoines@gmail.com>
  • Loading branch information
katiegoines and katiegoines authored Jul 23, 2024
1 parent d24c120 commit 383ee7c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/components/MDXComponents/MDXHeading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const MDXHeading = (props) => {
const { level, children, id } = props;

return (
<Heading level={level} id={id}>
<Heading level={level} id={id} tabIndex={-1}>
{/* Only output heading links for h2 and h3 \ */}
{level == 2 || level == 3 ? (
<Link href={`#${id}`}>{children}</Link>
Expand Down
26 changes: 26 additions & 0 deletions src/components/MDXComponents/__tests__/MDXHeading.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { render, screen } from '@testing-library/react';
import { MDXHeading } from '../MDXHeading';
import { TableOfContents } from '../../TableOfContents/index';
import userEvent from '@testing-library/user-event';

describe('MDXHeading', () => {
it('should render H2 with string and anchor link', () => {
Expand Down Expand Up @@ -53,4 +55,28 @@ describe('MDXHeading', () => {
expect(heading).toHaveTextContent(props.children);
expect(link).not.toBeInTheDocument();
});

it('should shift focus to in-content heading on TOC click', async () => {
const props = {
level: 2,
children: 'Test heading',
id: 'test-heading'
};
render(<MDXHeading {...props} />);

const heading = screen.queryByRole('heading', { level: 2 });
const tocHeadings = [
{ linkText: 'Test heading', hash: 'test-heading', level: 'h2' }
];

const tableOfContents = <TableOfContents headers={tocHeadings} />;
render(tableOfContents);

const tocEntry = await screen.findByRole('heading', {
name: 'Test heading'
});

userEvent.click(tocEntry);
expect(heading).toHaveFocus();
});
});
6 changes: 6 additions & 0 deletions src/styles/base.scss
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,12 @@ ol:not([class]) {
.amplify-heading--2,
.amplify-heading--3 {
scroll-margin-top: 9rem;

&:focus-visible {
transition: none;
outline: 2px solid var(--amplify-colors-border-focus);
outline-offset: 2px;
}
}
}

Expand Down

0 comments on commit 383ee7c

Please sign in to comment.