Skip to content

Commit 3bf388c

Browse files
authored
Merge pull request #188 from carbonplan/Shane98c/scroll-to-figs
use figure/table caption numbers for anchoring
2 parents 4ee9ab0 + 9e34d12 commit 3bf388c

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

src/figure-caption.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,6 @@ const FigureCaption = ({ as = 'figcaption', number, children }) => {
99
)
1010
}
1111

12+
FigureCaption.displayName = 'FigureCaption'
13+
1214
export default FigureCaption

src/figure.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,28 @@ import { Box } from 'theme-ui'
44
import Group from './group'
55

66
const Figure = ({ as = 'figure', children, sx }) => {
7+
// try to use figure/table number as id for anchoring
8+
const childrenArray = React.Children.toArray(children)
9+
const captionElement = childrenArray.find(
10+
(child) =>
11+
React.isValidElement(child) &&
12+
child.type?.displayName &&
13+
(child.type.displayName === 'FigureCaption' ||
14+
child.type.displayName === 'TableCaption')
15+
)
16+
17+
const elementNumber = captionElement?.props?.number
18+
const elementType =
19+
captionElement?.type?.displayName === 'TableCaption' ? 'table' : 'figure'
20+
const id = elementNumber ? `${elementType}-${elementNumber}` : undefined
21+
722
return (
823
<Box
924
as={as}
25+
id={id}
1026
sx={{
1127
my: [6, 6, 6, 7],
28+
scrollMarginTop: '60px', // account for header height
1229
'@media print': {
1330
breakInside: 'avoid',
1431
},

src/table-caption.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,6 @@ const TableCaption = ({ as = 'figcaption', number, children }) => {
99
)
1010
}
1111

12+
TableCaption.displayName = 'TableCaption'
13+
1214
export default TableCaption

0 commit comments

Comments
 (0)