Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/chronicle/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"@radix-ui/react-icons": "^1.3.2",
"@raystack/apsara": "1.0.0-rc.7",
"@shikijs/rehype": "^4.0.2",
"@tanstack/react-query": "5.100.10",
"@vitejs/plugin-react": "^6.0.1",
"chalk": "^5.6.2",
"class-variance-authority": "^0.7.1",
Expand Down
70 changes: 70 additions & 0 deletions packages/chronicle/src/components/ui/PrefetchProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { useEffect } from 'react';
import { prefetchPageData } from '@/lib/preload';

function resolvePathname(href: string | null): string | null {
if (!href) return null;
try {
const url = new URL(href, location.href);
if (url.origin !== location.origin) return null;
return url.pathname;
} catch {
return null;
}
}

export function PrefetchProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
const handleMouseOver = (e: MouseEvent) => {
const anchor = (e.target as HTMLElement).closest?.('a[href]');
if (!anchor) return;
const pathname = resolvePathname(anchor.getAttribute('href'));
if (pathname) prefetchPageData(pathname);
};

const handleFocusIn = (e: FocusEvent) => {
const anchor = (e.target as HTMLElement).closest?.('a[href]');
if (!anchor) return;
const pathname = resolvePathname(anchor.getAttribute('href'));
if (pathname) prefetchPageData(pathname);
};

document.addEventListener('mouseover', handleMouseOver);
document.addEventListener('focusin', handleFocusIn);

const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
const pathname = resolvePathname((entry.target as HTMLAnchorElement).getAttribute('href'));
if (pathname) prefetchPageData(pathname);
observer.unobserve(entry.target);
}
}
},
{ rootMargin: '200px' },
);

const observeLinks = () => {
document.querySelectorAll('a[href]:not([data-prefetch-observed])').forEach((link) => {
const pathname = resolvePathname(link.getAttribute('href'));
if (pathname) {
link.setAttribute('data-prefetch-observed', '');
observer.observe(link);
}
});
};

const mutationObserver = new MutationObserver(observeLinks);
mutationObserver.observe(document.body, { childList: true, subtree: true });
observeLinks();

return () => {
document.removeEventListener('mouseover', handleMouseOver);
document.removeEventListener('focusin', handleFocusIn);
observer.disconnect();
mutationObserver.disconnect();
};
}, []);

return children;
}
17 changes: 11 additions & 6 deletions packages/chronicle/src/lib/page-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { resolveRoute, RouteType } from '@/lib/route-resolver';
import type { VersionContext } from '@/lib/version-source';
import { LATEST_CONTEXT } from '@/lib/version-source';
import type { ChronicleConfig, Frontmatter, Page, PageNavLink, Root, TableOfContents } from '@/types';
import { queryClient } from '@/lib/preload';

export type MdxLoader = (relativePath: string) => Promise<{ content: ReactNode; toc: TableOfContents }>;

Expand Down Expand Up @@ -114,12 +115,16 @@ export function PageProvider({
}

const fetchPageData = useCallback(async (slug: string[]): Promise<PageData> => {
const apiPath = slug.length === 0
? '/api/page'
: `/api/page?slug=${slug.map(s => encodeURIComponent(s)).join(',')}`;
const res = await fetch(apiPath);
if (!res.ok) throw new Error(String(res.status));
return res.json();
const key = slug.length === 0 ? '' : slug.map(s => encodeURIComponent(s)).join(',');
const apiPath = key ? `/api/page?slug=${key}` : '/api/page';
return queryClient.fetchQuery({
queryKey: ['pageData', key],
queryFn: async () => {
const res = await fetch(apiPath);
if (!res.ok) throw new Error(String(res.status));
return res.json();
},
});
}, []);

const loadDocsPage = useCallback(async (slug: string[], cancelled: { current: boolean }) => {
Expand Down
37 changes: 37 additions & 0 deletions packages/chronicle/src/lib/preload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { QueryClient } from '@tanstack/react-query';

export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: Infinity,
refetchOnWindowFocus: false,
},
},
});

export function pageDataQueryKey(pathname: string) {
const slug = pathname.split('/').filter(Boolean);
const key = slug.length === 0 ? '' : slug.map(s => encodeURIComponent(s)).join(',');
return ['pageData', key] as const;
}

async function fetchPageDataByPathname(pathname: string) {
const slug = pathname.split('/').filter(Boolean);
const key = slug.length === 0 ? '' : slug.map(s => encodeURIComponent(s)).join(',');
const apiPath = key ? `/api/page?slug=${key}` : '/api/page';
const res = await fetch(apiPath);
if (!res.ok) throw new Error(String(res.status));
return res.json();
}

function isApisRoute(pathname: string): boolean {
return pathname === '/apis' || pathname.startsWith('/apis/');
}

export function prefetchPageData(pathname: string) {
if (isApisRoute(pathname)) return;
queryClient.prefetchQuery({
queryKey: pageDataQueryKey(pathname),
queryFn: () => fetchPageDataByPathname(pathname),
});
}
19 changes: 11 additions & 8 deletions packages/chronicle/src/pages/DocsLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react';
import { useLocation } from 'react-router';
import { PrefetchProvider } from '@/components/ui/PrefetchProvider';
import { usePageContext } from '@/lib/page-context';
import { getActiveContentDir } from '@/lib/navigation';
import {
Expand Down Expand Up @@ -27,13 +28,15 @@ export function DocsLayout({ children, hideSidebar }: DocsLayoutProps) {
);

return (
<Layout
config={config}
tree={scopedTree}
hideSidebar={hideSidebar}
classNames={{ layout: className }}
>
{children}
</Layout>
<PrefetchProvider>
<Layout
config={config}
tree={scopedTree}
hideSidebar={hideSidebar}
classNames={{ layout: className }}
>
{children}
</Layout>
</PrefetchProvider>
);
}
32 changes: 18 additions & 14 deletions packages/chronicle/src/server/entry-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import React from 'react';
import { hydrateRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router';
import { ReactRouterProvider } from 'fumadocs-core/framework/react-router';
import { QueryClientProvider } from '@tanstack/react-query';
import { mdxComponents } from '@/components/mdx';
import { getApiConfigsForVersion } from '@/lib/config';
import { PageProvider } from '@/lib/page-context';
import { queryClient } from '@/lib/preload';
import { resolveRoute, RouteType } from '@/lib/route-resolver';
import { resolveVersionFromUrl, type VersionContext } from '@/lib/version-source';
import type { ChronicleConfig, Frontmatter, PageNavLink, Root, TableOfContents } from '@/types';
Expand Down Expand Up @@ -93,20 +95,22 @@ async function hydrate() {

hydrateRoot(
document.getElementById('root') as HTMLElement,
<BrowserRouter>
<ReactRouterProvider>
<PageProvider
initialConfig={config}
initialTree={tree}
initialPage={page}
initialApiSpecs={apiSpecs}
initialVersion={version}
loadMdx={loadMdxModule}
>
<App />
</PageProvider>
</ReactRouterProvider>
</BrowserRouter>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<ReactRouterProvider>
<PageProvider
initialConfig={config}
initialTree={tree}
initialPage={page}
initialApiSpecs={apiSpecs}
initialVersion={version}
loadMdx={loadMdxModule}
>
<App />
</PageProvider>
</ReactRouterProvider>
</BrowserRouter>
</QueryClientProvider>
);
} catch (err) {
console.error('Hydration failed:', err);
Expand Down
Loading