54 lines
1.1 KiB
TypeScript
54 lines
1.1 KiB
TypeScript
'use client';
|
|
|
|
/**
|
|
* Table of Contents Context
|
|
*
|
|
* Allows documentation pages to pass their TOC items up to the layout
|
|
* so the layout can render the TOC in the right sidebar.
|
|
*
|
|
* Usage in pages:
|
|
* ```tsx
|
|
* <TocProvider tocItems={[...]}>
|
|
* <page content>
|
|
* </TocProvider>
|
|
* ```
|
|
*
|
|
* Usage in layout:
|
|
* ```tsx
|
|
* const { tocItems } = useToc();
|
|
* return <DocsTOC items={tocItems} />;
|
|
* ```
|
|
*/
|
|
|
|
import { createContext, useContext, ReactNode } from 'react';
|
|
|
|
export interface TocItem {
|
|
id: string;
|
|
text: string;
|
|
level: number;
|
|
}
|
|
|
|
interface TocContextValue {
|
|
tocItems: TocItem[];
|
|
}
|
|
|
|
const TocContext = createContext<TocContextValue | undefined>(undefined);
|
|
|
|
interface TocProviderProps {
|
|
tocItems: TocItem[];
|
|
children: ReactNode;
|
|
}
|
|
|
|
export const TocProvider = ({ tocItems, children }: TocProviderProps) => {
|
|
return <TocContext.Provider value={{ tocItems }}>{children}</TocContext.Provider>;
|
|
};
|
|
|
|
export const useToc = (): TocContextValue => {
|
|
const context = useContext(TocContext);
|
|
if (!context) {
|
|
// Return empty array if no provider (allows layout to work without TOC)
|
|
return { tocItems: [] };
|
|
}
|
|
return context;
|
|
};
|