@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 73 lines 2.61 KB
Raw
1 'use client';
2
3 import { useEffect } from 'react';
4 import { usePostHog } from 'posthog-js/react';
5 import type { SidebarNavIndex } from '@/lib/sidebar-nav-index';
6
7 /**
8 * Emits `docs_sidebar_click` for sidebar navigation.
9 *
10 * One delegated listener rather than per-link handlers, and the group/folder/
11 * depth come from `index` (built from the page tree) rather than from walking
12 * the rendered DOM. An href that is not in the index emits nothing — a guessed
13 * group is worse than a missing event.
14 */
15 export function SidebarAnalytics({ index }: { index: SidebarNavIndex }) {
16 const posthog = usePostHog();
17
18 useEffect(() => {
19 // `usePostHog()` falls back to the module singleton when no provider is
20 // mounted, so it is truthy even with no key — capturing on it would only
21 // log "You must initialize PostHog before calling posthog.capture". Gate on
22 // the same env var `components/posthog-provider.tsx` gates on; Next inlines it.
23 if (!posthog || !process.env.NEXT_PUBLIC_POSTHOG_KEY) return;
24
25 function handleClick(event: MouseEvent) {
26 // `click` skips middle-click, which would drop every sidebar link opened
27 // in a new tab while keeping the Cmd/Ctrl+click ones.
28 if (event.type === 'auxclick' && event.button !== 1) return;
29
30 const target = event.target;
31 if (!(target instanceof Element)) return;
32
33 const anchor = target.closest('a[href]');
34 // The desktop and mobile sidebar containers. Matching `aside` instead
35 // would also catch the Ask AI panel, whose answers link to docs pages.
36 // These two ids are the same hooks `app/global.css` styles against.
37 if (!anchor || !anchor.closest('#nd-sidebar, #nd-sidebar-mobile')) return;
38
39 const href = anchor.getAttribute('href');
40 if (!href) return;
41
42 let url: URL;
43 try {
44 url = new URL(href, window.location.href);
45 } catch {
46 return;
47 }
48 if (url.origin !== window.location.origin) return;
49
50 const pathname = url.pathname.replace(/\/$/, '') || '/';
51 const entry = index[pathname];
52 if (!entry) return;
53
54 posthog.capture('docs_sidebar_click', {
55 href: pathname,
56 group: entry.group,
57 folder: entry.folder,
58 depth: entry.depth,
59 position: entry.position,
60 from_path: window.location.pathname,
61 });
62 }
63
64 document.addEventListener('click', handleClick, true);
65 document.addEventListener('auxclick', handleClick, true);
66 return () => {
67 document.removeEventListener('click', handleClick, true);
68 document.removeEventListener('auxclick', handleClick, true);
69 };
70 }, [index, posthog]);
71
72 return null;
73 }