@open-press/core
useSource
A React hook to read a registered MDX source from the Press tree's resolved source map. It is synchronous and safe to call anywhere inside <Press>.
useSource is a synchronous React Hook designed to safely retrieve resolved MDX source data structures within the <Press> render tree.
Extracts parsed MDX AST and metadata based on a source ID. The engine guarantees data is populated before the render cycle, so this method never returns null.
import { useSource } from "@open-press/core"; function useSource<T = ResolvedSource>(id: string): T Parameters
| Name | Type | Default | Description |
|---|---|---|---|
id required | string | The source `id` declared in ` |
Returns
| Name | Type | Default | Description |
|---|---|---|---|
ResolvedSource | object | The engine-parsed source object, encompassing blocks, block source maps, and custom metadata. Supports forced type casting using the TypeScript generic ` |
Throws
| Name | Type | Default | Description |
|---|---|---|---|
Outside Press Boundary | Error | Thrown when the call site lacks `PressContext` (not within the ` | |
Unknown Source ID | Error | Thrown when the passed `id` has not been registered, accompanied by a hint listing registered sources. |
Example: Accessing Source Metadata
import { useSource } from "@open-press/core";
function CustomTableOfContents() {
const story = useSource("story");
return (
<ul>
{story.sections.map((s) => (
<li key={s.id}>{s.title}</li>
))}
</ul>
);
}Example: Type Casting with Generics
import { useSource, type ResolvedSource } from "@open-press/core";
interface StorySource extends ResolvedSource {
sections: Array<{ id: string; title: string; chapterCount: number }>;
}
function ChapterCounts() {
const story = useSource<StorySource>("story");
return story.sections.map((s) => (
<div key={s.id}>{s.title}: {s.chapterCount} chapters</div>
));
} Applicable Scenarios and Limitations
Applicable Contexts:
- Developing Low-level Utilities: Writing custom manuscript allocators as an alternative to
<Sections>. - Advanced Layout Components: Building a Table of Contents (
TOC) with a non-standard tree structure. - Global Information Interfaces: Custom headers, footers, or statistic dashboards needing access to aggregated source data.
Forbidden Patterns:
- Inside MDX Blocks: MDX nodes are already situated within the compilation pipeline; they should rely on Prop drilling and should not inversely re-fetch data via the Hook.
- Non-React Runtimes: Attempting to call this in server-side scripts or outside the
<Press>boundary. For external scripts, you should directly analyze thedocument.jsonartifact.