|
| 1 | +import { useEffect, useRef } from 'react' |
| 2 | +import { useTranslation } from 'react-i18next' |
| 3 | +import TableOfContents from './TableOfContents' |
| 4 | + |
| 5 | +/** |
| 6 | + * Mobile-only TOC: a fixed FAB at bottom-right that slides up a bottom sheet. |
| 7 | + * Hidden on lg+ (desktop shows the right-rail TOC instead). |
| 8 | + */ |
| 9 | +export default function TocDrawer({ headings, open, onOpen, onClose }) { |
| 10 | + const { t } = useTranslation() |
| 11 | + const sheetRef = useRef(null) |
| 12 | + |
| 13 | + // Close on backdrop click |
| 14 | + const handleBackdrop = (e) => { |
| 15 | + if (e.target === e.currentTarget) onClose() |
| 16 | + } |
| 17 | + |
| 18 | + // Close on Escape |
| 19 | + useEffect(() => { |
| 20 | + if (!open) return |
| 21 | + const handler = (e) => { if (e.key === 'Escape') onClose() } |
| 22 | + document.addEventListener('keydown', handler) |
| 23 | + return () => document.removeEventListener('keydown', handler) |
| 24 | + }, [open, onClose]) |
| 25 | + |
| 26 | + // Trap body scroll while drawer is open |
| 27 | + useEffect(() => { |
| 28 | + if (open) { |
| 29 | + document.body.style.overflow = 'hidden' |
| 30 | + } else { |
| 31 | + document.body.style.overflow = '' |
| 32 | + } |
| 33 | + return () => { document.body.style.overflow = '' } |
| 34 | + }, [open]) |
| 35 | + |
| 36 | + if (!headings || headings.length === 0) return null |
| 37 | + |
| 38 | + return ( |
| 39 | + <> |
| 40 | + {/* FAB — only visible on mobile */} |
| 41 | + <button |
| 42 | + className="toc-fab lg:hidden no-print" |
| 43 | + onClick={onOpen} |
| 44 | + aria-label={t('toc.label')} |
| 45 | + title={t('toc.label')} |
| 46 | + > |
| 47 | + <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"> |
| 48 | + <line x1="3" y1="5" x2="17" y2="5" /> |
| 49 | + <line x1="3" y1="10" x2="13" y2="10" /> |
| 50 | + <line x1="3" y1="15" x2="10" y2="15" /> |
| 51 | + </svg> |
| 52 | + </button> |
| 53 | + |
| 54 | + {/* Backdrop + bottom sheet */} |
| 55 | + {open && ( |
| 56 | + <div |
| 57 | + className="toc-drawer-backdrop lg:hidden" |
| 58 | + onClick={handleBackdrop} |
| 59 | + aria-hidden="true" |
| 60 | + > |
| 61 | + <div |
| 62 | + ref={sheetRef} |
| 63 | + className="toc-drawer-sheet" |
| 64 | + role="dialog" |
| 65 | + aria-label={t('toc.label')} |
| 66 | + aria-modal="true" |
| 67 | + > |
| 68 | + <div className="toc-drawer-handle" /> |
| 69 | + <div |
| 70 | + className="toc-drawer-body" |
| 71 | + onClick={(e) => { |
| 72 | + // Close after a heading is clicked (user wants to navigate) |
| 73 | + if (e.target.closest('a')) onClose() |
| 74 | + }} |
| 75 | + > |
| 76 | + <TableOfContents headings={headings} /> |
| 77 | + </div> |
| 78 | + </div> |
| 79 | + </div> |
| 80 | + )} |
| 81 | + </> |
| 82 | + ) |
| 83 | +} |
0 commit comments