@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 03:37 UTC

next
tsx 200 lines 5.89 KB
Raw
1 'use client';
2
3 import {
4 createContext,
5 useCallback,
6 useContext,
7 useEffect,
8 useMemo,
9 useRef,
10 useState,
11 type ReactNode,
12 } from 'react';
13 import { flushSync } from 'react-dom';
14 import { usePathname, useRouter } from 'next/navigation';
15 import {
16 classifyDocsProduct,
17 DOCS_PRODUCTS,
18 serializeDocsProductCookie,
19 shouldAnimateDocsProductSwitch,
20 type DocsProduct,
21 } from '@/lib/home-navigation';
22
23 interface DocsProductContextValue {
24 product: DocsProduct;
25 navigateToProduct: (
26 product: DocsProduct,
27 href: string,
28 origin?: HTMLElement | null,
29 ) => void;
30 persistProduct: (product: DocsProduct) => void;
31 }
32
33 interface ViewTransitionHandle {
34 finished: Promise<void>;
35 }
36
37 type ViewTransitionDocument = Document & {
38 startViewTransition?: (
39 update: () => void | Promise<void>,
40 ) => ViewTransitionHandle;
41 };
42
43 const DocsProductContext = createContext<DocsProductContextValue | null>(null);
44
45 function writeProductCookie(product: DocsProduct): void {
46 document.cookie = serializeDocsProductCookie(product);
47 }
48
49 /**
50 * The product theme is derived state, not a user preference: apply it directly
51 * to the document element instead of routing it through next-themes' shared
52 * `theme` localStorage key, whose cross-tab storage events would repaint other
53 * tabs that are viewing the other product.
54 */
55 function applyProductTheme(product: DocsProduct): void {
56 const { theme, themeColor } = DOCS_PRODUCTS[product];
57 const root = document.documentElement;
58 root.classList.remove('light', 'dark');
59 root.classList.add(theme);
60 root.style.colorScheme = theme;
61 document
62 .querySelector('meta[name="theme-color"]')
63 ?.setAttribute('content', themeColor);
64 }
65
66 export function DocsProductProvider({
67 initialProduct,
68 children,
69 }: {
70 initialProduct: DocsProduct;
71 children: ReactNode;
72 }) {
73 const pathname = usePathname();
74 const router = useRouter();
75 const [persistedProduct, setPersistedProduct] = useState(initialProduct);
76 const [pendingProduct, setPendingProduct] = useState<DocsProduct | null>(null);
77 const pendingNavigation = useRef<{
78 from: string;
79 resolve: () => void;
80 } | null>(null);
81
82 const inferredProduct = classifyDocsProduct(pathname);
83 const product = pendingProduct ?? inferredProduct ?? persistedProduct;
84
85 useEffect(() => {
86 applyProductTheme(product);
87 }, [product]);
88
89 const persistProduct = useCallback((nextProduct: DocsProduct) => {
90 writeProductCookie(nextProduct);
91 setPersistedProduct(nextProduct);
92 }, []);
93
94 useEffect(() => {
95 if (inferredProduct) {
96 writeProductCookie(inferredProduct);
97 }
98
99 if (pendingNavigation.current && pendingNavigation.current.from !== pathname) {
100 pendingNavigation.current.resolve();
101 pendingNavigation.current = null;
102 }
103
104 const frame = window.requestAnimationFrame(() => {
105 if (inferredProduct) setPersistedProduct(inferredProduct);
106 setPendingProduct(null);
107 });
108 return () => window.cancelAnimationFrame(frame);
109 }, [inferredProduct, pathname]);
110
111 useEffect(() => {
112 return () => {
113 pendingNavigation.current?.resolve();
114 pendingNavigation.current = null;
115 document.documentElement.classList.remove('docs-product-transition');
116 };
117 }, []);
118
119 const navigateToProduct = useCallback(
120 (nextProduct: DocsProduct, href: string, origin?: HTMLElement | null) => {
121 const commitNavigation = () => {
122 writeProductCookie(nextProduct);
123 flushSync(() => {
124 setPersistedProduct(nextProduct);
125 setPendingProduct(nextProduct);
126 applyProductTheme(nextProduct);
127 });
128 if (href !== pathname) router.push(href);
129 };
130
131 const viewTransitionDocument = document as ViewTransitionDocument;
132 const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
133 const startViewTransition =
134 viewTransitionDocument.startViewTransition?.bind(viewTransitionDocument);
135 const shouldAnimate = shouldAnimateDocsProductSwitch(
136 typeof startViewTransition === 'function',
137 reduceMotion,
138 );
139
140 if (!shouldAnimate || !startViewTransition) {
141 commitNavigation();
142 return;
143 }
144
145 const root = document.documentElement;
146 const rect = origin?.getBoundingClientRect();
147 root.style.setProperty('--docs-reveal-x', `${rect ? rect.left + rect.width / 2 : 32}px`);
148 root.style.setProperty('--docs-reveal-y', `${rect ? rect.top + rect.height / 2 : 32}px`);
149 root.classList.add('docs-product-transition');
150
151 let cleaned = false;
152 const cleanup = () => {
153 if (cleaned) return;
154 cleaned = true;
155 root.classList.remove('docs-product-transition');
156 root.style.removeProperty('--docs-reveal-x');
157 root.style.removeProperty('--docs-reveal-y');
158 };
159 window.setTimeout(cleanup, 2500);
160
161 try {
162 const transition = startViewTransition(() => {
163 if (href === pathname) {
164 commitNavigation();
165 return;
166 }
167
168 return new Promise<void>(resolve => {
169 pendingNavigation.current?.resolve();
170 const finish = () => resolve();
171 window.setTimeout(finish, 1500);
172 pendingNavigation.current = {
173 from: pathname,
174 resolve: finish,
175 };
176 commitNavigation();
177 });
178 });
179 void transition.finished.catch(() => undefined).finally(cleanup);
180 } catch {
181 cleanup();
182 commitNavigation();
183 }
184 },
185 [pathname, router],
186 );
187
188 const value = useMemo(
189 () => ({ product, navigateToProduct, persistProduct }),
190 [navigateToProduct, persistProduct, product],
191 );
192
193 return <DocsProductContext.Provider value={value}>{children}</DocsProductContext.Provider>;
194 }
195
196 export function useDocsProduct(): DocsProductContextValue {
197 const value = useContext(DocsProductContext);
198 if (!value) throw new Error('useDocsProduct must be used inside DocsProductProvider');
199 return value;
200 }