Skip to content

Commit 118096e

Browse files
committed
Close ToC when it sticks
1 parent 6379525 commit 118096e

1 file changed

Lines changed: 19 additions & 2 deletions

File tree

dotcom-rendering/src/components/TableOfContents.importable.tsx

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
SvgChevronDownSingle,
1010
SvgChevronUpSingle,
1111
} from '@guardian/source/react-components';
12-
import { useState } from 'react';
12+
import { useEffect, useState } from 'react';
1313
import { ArticleDisplay, type ArticleFormat } from '../lib/articleFormat';
1414
import { getZIndex } from '../lib/getZIndex';
1515
import type { TableOfContentsItem } from '../model/enhanceTableOfContents';
@@ -75,7 +75,7 @@ const detailsStyles = css`
7575
`;
7676
const stickyStyles = css`
7777
position: sticky;
78-
top: 0;
78+
top: -1px;
7979
background: ${palette('--article-background')};
8080
z-index: ${getZIndex('tableOfContents')};
8181
summary {
@@ -138,6 +138,23 @@ const verticalStyle = css`
138138
export const TableOfContents = ({ tableOfContents, format }: Props) => {
139139
const [open, setOpen] = useState(tableOfContents.length < 5);
140140

141+
useEffect(() => {
142+
const tocElement = document.querySelector(
143+
'[data-component="table-of-contents"]',
144+
) as HTMLElement;
145+
146+
const observer = new IntersectionObserver(
147+
([e]) => {
148+
if (e && e.intersectionRatio < 1) {
149+
setOpen(false);
150+
}
151+
},
152+
{ threshold: [1] },
153+
);
154+
155+
observer.observe(tocElement);
156+
}, []);
157+
141158
return (
142159
<details
143160
open={open}

0 commit comments

Comments
 (0)