@devries-cameron20 / composio Mirror · read-only / commits / fe623da43
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, 16:00 UTC

docs: emit docs_sidebar_click with sidebar group and depth

The docs app had exactly one posthog.capture call ($pageview), so any question about how people move through the sidebar had to be answered by reverse-engineering pageview ordering within a session. $referring_domain is no help either: pageviews are captured manually on client-side route change, so document.referrer never updates on internal navigation. Adds a docs_sidebar_click event carrying href, group, folder, depth, position and from_path. Group/folder/depth are derived from the fumadocs page tree at build time and the click handler only does an href lookup — reading them off the rendered sidebar would mean depending on separators being <p> and folder triggers being <button>, which is fumadocs-internal and breaks on upgrade. Mounted on the docs, examples and both reference sidebars. Nothing fires when PostHog is unconfigured, for non-sidebar links, or for an href that is not in the index. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

Kshitij Jhunjhunwala committed Aug 14, 2026 at 15:37 UTC fe623da4348a0fee251c752ddd2d906e9e34e77c
7 files changed +241
docs/app/(home)/docs/layout.tsx
+4
@@ -1,6 +1,8 @@
1 import { source } from '@/lib/source';
2 import { DocsLayout } from 'fumadocs-ui/layouts/docs';
3 import { decorateSidebarBadges } from '@/lib/decorate-sidebar-badges';
4 +import { buildSidebarNavIndex } from '@/lib/sidebar-nav-index';
5 +import { SidebarAnalytics } from '@/components/sidebar-analytics';
6
7 interface BadgeFrontmatter {
8 experimental?: boolean;
@@ -16,6 +18,7 @@ const newUrls = new Set(
18 );
19
20 const tree = decorateSidebarBadges(source.pageTree, experimentalUrls, newUrls);
21 +const navIndex = buildSidebarNavIndex(tree);
22
23 export default function Layout({ children }: LayoutProps<'/docs'>) {
24 return (
@@ -26,6 +29,7 @@ export default function Layout({ children }: LayoutProps<'/docs'>) {
29 themeSwitch={{ enabled: false }}
30 searchToggle={{ enabled: false }}
31 >
32 + <SidebarAnalytics index={navIndex} />
33 {children}
34 </DocsLayout>
35 );
docs/app/(home)/reference/(v31)/layout.tsx
+3
@@ -2,6 +2,8 @@ import { getReferenceSource } from '@/lib/source';
2 import { DocsLayout } from 'fumadocs-ui/layouts/docs';
3 import type { ReactNode } from 'react';
4 import { prepareTree } from '@/lib/filter-api-version';
5 +import { buildSidebarNavIndex } from '@/lib/sidebar-nav-index';
6 +import { SidebarAnalytics } from '@/components/sidebar-analytics';
7
8 export default async function Layout({ children }: { children: ReactNode }) {
9 const source = await getReferenceSource();
@@ -29,6 +31,7 @@ export default async function Layout({ children }: { children: ReactNode }) {
31 sidebar={{ collapsible: false, footer: null, tabs: false }}
32 themeSwitch={{ enabled: false }}
33 >
34 + <SidebarAnalytics index={buildSidebarNavIndex(pageTree)} />
35 {children}
36 </DocsLayout>
37 );
docs/app/(home)/reference/v3/layout.tsx
+3
@@ -2,6 +2,8 @@ import { getReferenceSource } from '@/lib/source';
2 import { DocsLayout } from 'fumadocs-ui/layouts/docs';
3 import type { ReactNode } from 'react';
4 import { prepareTree } from '@/lib/filter-api-version';
5 +import { buildSidebarNavIndex } from '@/lib/sidebar-nav-index';
6 +import { SidebarAnalytics } from '@/components/sidebar-analytics';
7
8 export default async function Layout({ children }: { children: ReactNode }) {
9 const source = await getReferenceSource();
@@ -15,6 +17,7 @@ export default async function Layout({ children }: { children: ReactNode }) {
17 sidebar={{ collapsible: false, footer: null, tabs: false }}
18 themeSwitch={{ enabled: false }}
19 >
20 + <SidebarAnalytics index={buildSidebarNavIndex(tree)} />
21 {children}
22 </DocsLayout>
23 );
docs/components/sidebar-analytics.tsx new
+61
@@ -0,0 +1,61 @@
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 + if (!posthog) return;
20 +
21 + function handleClick(event: MouseEvent) {
22 + const target = event.target;
23 + if (!(target instanceof Element)) return;
24 +
25 + const anchor = target.closest('a[href]');
26 + // The desktop and mobile sidebar containers. Matching `aside` instead
27 + // would also catch the Ask AI panel, whose answers link to docs pages.
28 + // These two ids are the same hooks `app/global.css` styles against.
29 + if (!anchor || !anchor.closest('#nd-sidebar, #nd-sidebar-mobile')) return;
30 +
31 + const href = anchor.getAttribute('href');
32 + if (!href) return;
33 +
34 + let url: URL;
35 + try {
36 + url = new URL(href, window.location.href);
37 + } catch {
38 + return;
39 + }
40 + if (url.origin !== window.location.origin) return;
41 +
42 + const pathname = url.pathname.replace(/\/$/, '') || '/';
43 + const entry = index[pathname];
44 + if (!entry) return;
45 +
46 + posthog.capture('docs_sidebar_click', {
47 + href: pathname,
48 + group: entry.group,
49 + folder: entry.folder,
50 + depth: entry.depth,
51 + position: entry.position,
52 + from_path: window.location.pathname,
53 + });
54 + }
55 +
56 + document.addEventListener('click', handleClick, true);
57 + return () => document.removeEventListener('click', handleClick, true);
58 + }, [index, posthog]);
59 +
60 + return null;
61 +}
docs/lib/create-docs-layout.tsx
+5
@@ -1,9 +1,13 @@
1 import { DocsLayout } from 'fumadocs-ui/layouts/docs';
2 import type { ReactNode } from 'react';
3 +import { buildSidebarNavIndex } from './sidebar-nav-index';
4 +import { SidebarAnalytics } from '@/components/sidebar-analytics';
5
6 type Source = typeof import('./source').examplesSource;
7
8 export function createDocsLayout(source: Source) {
9 + const navIndex = buildSidebarNavIndex(source.pageTree);
10 +
11 return function Layout({ children }: { children: ReactNode }) {
12 return (
13 <DocsLayout
@@ -13,6 +17,7 @@ export function createDocsLayout(source: Source) {
17 sidebar={{ collapsible: false, footer: null, tabs: false }}
18 themeSwitch={{ enabled: false }}
19 >
20 + <SidebarAnalytics index={navIndex} />
21 {children}
22 </DocsLayout>
23 );
docs/lib/sidebar-nav-index.ts new
+84
@@ -0,0 +1,84 @@
1 +/**
2 + * Flattens a fumadocs page tree into a url -> sidebar-position lookup.
3 + *
4 + * Analytics needs to know which sidebar group a click came from, and the
5 + * rendered sidebar cannot answer that: separators render as `<p>` and folders
6 + * as `<button>`, both fumadocs-internal details that change on upgrade. The
7 + * tree is the stable source, so the mapping is derived here at build time and
8 + * the click handler only does an href lookup.
9 + *
10 + * Mirrors the traversal in `app/llms.txt/route.ts`.
11 + */
12 +import type { ReactNode } from 'react';
13 +import type { Root, Node } from 'fumadocs-core/page-tree';
14 +
15 +export interface SidebarNavEntry {
16 + /** Enclosing separator heading, e.g. "Core concepts". */
17 + group: string | null;
18 + /** Enclosing folder title, e.g. "Authentication"; null at the top level. */
19 + folder: string | null;
20 + /** 1 = top-level row, 2 = folder child, 3 = nested. */
21 + depth: number;
22 + /** 1-based position within the group, in top-to-bottom sidebar order. */
23 + position: number;
24 +}
25 +
26 +export type SidebarNavIndex = Record<string, SidebarNavEntry>;
27 +
28 +/** Sidebar badges wrap names in elements, so only plain names yield text. */
29 +function nodeText(name: ReactNode): string | null {
30 + if (typeof name === 'string') return name;
31 + if (typeof name === 'number') return String(name);
32 + return null;
33 +}
34 +
35 +interface WalkState {
36 + group: string | null;
37 + position: number;
38 +}
39 +
40 +function walkNodes(
41 + nodes: Node[],
42 + folder: string | null,
43 + depth: number,
44 + state: WalkState,
45 + index: SidebarNavIndex
46 +): void {
47 + for (const node of nodes) {
48 + if (node.type === 'separator') {
49 + state.group = nodeText(node.name);
50 + state.position = 0;
51 + continue;
52 + }
53 +
54 + if (node.type === 'page') {
55 + state.position += 1;
56 + index[node.url] = { group: state.group, folder, depth, position: state.position };
57 + continue;
58 + }
59 +
60 + const folderName = nodeText(node.name) ?? folder;
61 +
62 + // A folder's index page is the folder's own row, so it keeps the folder's depth.
63 + if (node.index) {
64 + state.position += 1;
65 + index[node.index.url] = {
66 + group: state.group,
67 + folder: folderName,
68 + depth,
69 + position: state.position,
70 + };
71 + }
72 +
73 + // A separator nested in a folder must not leak into the folder's siblings.
74 + const outerGroup = state.group;
75 + walkNodes(node.children, folderName, depth + 1, state, index);
76 + state.group = outerGroup;
77 + }
78 +}
79 +
80 +export function buildSidebarNavIndex(tree: Root): SidebarNavIndex {
81 + const index: SidebarNavIndex = {};
82 + walkNodes(tree.children, null, 1, { group: null, position: 0 }, index);
83 + return index;
84 +}
docs/tests/static/sidebar-nav-index.test.ts new
+81
@@ -0,0 +1,81 @@
1 +/**
2 + * Sidebar nav index tests.
3 + *
4 + * Exercises the real docs page tree: `docs_sidebar_click` reports the group,
5 + * folder and depth from this index, so a traversal bug silently drops pages
6 + * from analytics rather than breaking the site.
7 + */
8 +import { describe, expect, test } from 'bun:test';
9 +import { readFile } from 'node:fs/promises';
10 +import { join } from 'node:path';
11 +import { flattenTree } from 'fumadocs-core/page-tree';
12 +
13 +import { buildSidebarNavIndex } from '../../lib/sidebar-nav-index';
14 +import { source } from '../../lib/source';
15 +
16 +const index = buildSidebarNavIndex(source.pageTree);
17 +
18 +describe('buildSidebarNavIndex', () => {
19 + test('folder children carry their group, folder and depth', () => {
20 + expect(index['/docs/authentication/white-labeling-authentication']).toEqual({
21 + group: 'Core concepts',
22 + folder: 'Authentication',
23 + depth: 2,
24 + position: expect.any(Number),
25 + });
26 +
27 + expect(index['/docs/extending-sessions/shared-connections']).toEqual({
28 + group: 'Guides',
29 + folder: 'Extend sessions',
30 + depth: 2,
31 + position: expect.any(Number),
32 + });
33 + });
34 +
35 + test('top-level pages have no folder', () => {
36 + expect(index['/docs/quickstart']).toEqual({
37 + group: 'Get Started',
38 + folder: null,
39 + depth: 1,
40 + position: expect.any(Number),
41 + });
42 + });
43 +
44 + test('folder index pages resolve to the folder row', () => {
45 + expect(index['/docs/authentication']).toEqual({
46 + group: 'Core concepts',
47 + folder: 'Authentication',
48 + depth: 1,
49 + position: expect.any(Number),
50 + });
51 + });
52 +
53 + test('position increases down a group and resets at the next separator', () => {
54 + expect(index['/docs/quickstart'].position).toBeGreaterThan(index['/docs'].position);
55 + expect(index['/docs/how-composio-works'].position).toBe(1);
56 + });
57 +
58 + test('every page in the sidebar tree resolves to a non-null group', () => {
59 + const missing = flattenTree(source.pageTree.children)
60 + .map(page => page.url)
61 + .filter(url => index[url]?.group == null);
62 +
63 + expect(missing).toEqual([]);
64 + });
65 +
66 + test('every root meta.json entry that is a page is indexed', async () => {
67 + const meta = JSON.parse(
68 + await readFile(join(import.meta.dir, '../../content/docs/meta.json'), 'utf-8')
69 + ) as { pages: string[] };
70 +
71 + const indexed = meta.pages
72 + .filter(entry => !entry.startsWith('---') && entry !== '...')
73 + .map(entry => (entry === 'index' ? '/docs' : `/docs/${entry}`))
74 + .filter(url => index[url] != null);
75 +
76 + // Entries that are folders without an index page have no url of their own.
77 + expect(indexed).toContain('/docs/quickstart');
78 + expect(indexed).toContain('/docs/authentication');
79 + expect(indexed).toContain('/docs/providers');
80 + });
81 +});