Skip to content
Open
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
INDEXSUPPLY_API_KEY=
SLACK_FEEDBACK_WEBHOOK= # e.g. https://hooks.slack.com/services/...
VITE_BASE_URL= # e.g. https://docs.tempo.xyz
VITE_ANALYTICS_RELEASE= # e.g. docs_growth_v1
VITE_GA_MEASUREMENT_ID=
VITE_POSTHOG_HOST=
VITE_POSTHOG_KEY=
Expand Down
1 change: 1 addition & 0 deletions env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ interface EnvironmentVariables {
readonly NODE_ENV: 'development' | 'production' | 'test'

readonly VITE_BASE_URL: string
readonly VITE_ANALYTICS_RELEASE: string
readonly VITE_POSTHOG_KEY: string
readonly VITE_POSTHOG_HOST: string
readonly VITE_TEMPO_ENV: 'localnet' | 'devnet' | 'moderato'
Expand Down
15 changes: 15 additions & 0 deletions src/components/DocsHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from 're
import { useConfig } from 'vocs'
import { useRouter } from 'waku'
import { DOCS_SEARCH_PARAM } from '../lib/docs-search'
import { trackDocsSearchOpened } from '../lib/posthog'
import { AmpLogo, ClaudeLogo, CodexLogo } from './AgentLogos'

type MegaLink = {
Expand Down Expand Up @@ -1098,13 +1099,26 @@ export default function DocsHeader() {
cancelClose()
setActiveMenu(null)
close()
trackDocsSearchOpened('header')
openDocsSearch()
}

useEffect(() => {
warmMarketingApp()
}, [])

useEffect(() => {
const trackKeyboardSearch = (event: KeyboardEvent) => {
if (!event.isTrusted) return
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
trackDocsSearchOpened('keyboard')
}
}

document.addEventListener('keydown', trackKeyboardSearch)
return () => document.removeEventListener('keydown', trackKeyboardSearch)
}, [])

// Open the search dialog when arriving from the marketing site's search CTA
// (which navigates to `/docs?search=1`). Strip the param so refresh/back
// doesn't reopen it.
Expand All @@ -1119,6 +1133,7 @@ export default function DocsHeader() {
'',
`${window.location.pathname}${query ? `?${query}` : ''}${window.location.hash}`,
)
trackDocsSearchOpened('marketing')
openDocsSearchWhenReady()
}, [])

Expand Down
247 changes: 226 additions & 21 deletions src/components/PostHogSetup.tsx
Original file line number Diff line number Diff line change
@@ -1,50 +1,255 @@
'use client'

import { useEffect } from 'react'
import {
markPostHogReady,
trackDocsCopyCode,
trackDocsCtaClick,
trackDocsSearchResultClick,
} from '../lib/posthog'
import {
classifyStrategicCta,
DEFAULT_ANALYTICS_RELEASE,
enrichPostHogCapture,
getAnalyticsRuntimeProperties,
hasUnsafeAnalyticsQuery,
isProductionAnalyticsHost,
sanitizeAnalyticsUrl,
sanitizePostHogCapture,
} from '../lib/posthog-analytics'

const POSTHOG_UI_HOST = 'https://us.posthog.com'

function eventTargetElement(event: Event) {
return event.target instanceof Element ? event.target : null
}

function ctaLocation(anchor: HTMLAnchorElement) {
if (anchor.closest('header, nav')) return 'nav'
if (anchor.closest('footer')) return 'footer'
if (anchor.closest('aside')) return 'sidebar'
return 'content'
}

function codeLanguage(button: HTMLButtonElement) {
const container = button.closest('pre') ?? button.parentElement
const code = container?.querySelector('code')
const explicit = code?.getAttribute('data-language') ?? container?.getAttribute('data-language')
if (explicit) return explicit.toLowerCase().slice(0, 32)

const languageClass = [...(code?.classList ?? [])].find((name) => name.startsWith('language-'))
return languageClass?.slice('language-'.length, 32).toLowerCase()
}

function copyMetadata(button: HTMLButtonElement) {
const label = button.getAttribute('aria-label')?.toLowerCase() ?? ''
const isAgentInstall = label.startsWith('copy tempo')
const isShell = button.hasAttribute('data-v-shell-copy') || label.includes('command')
const isOpenApiCopy =
button.hasAttribute('data-v-openapi-action') &&
(label.includes('copy') || button.textContent?.trim().toLowerCase() === 'copy')
const isCodeCopy = label === 'copy code'

if (!isAgentInstall && !isShell && !isOpenApiCopy && !isCodeCopy) return null

return {
copyType: isAgentInstall || isShell ? ('command' as const) : ('code' as const),
copySource: isAgentInstall
? 'agent_install'
: isShell
? 'shell'
: isOpenApiCopy
? 'openapi'
: 'code_block',
language: codeLanguage(button),
}
}

function findVocsSearchInput() {
return document.querySelector<HTMLInputElement>(
'[role="combobox"][aria-controls="search-results"]',
)
}

function vocsSearchResultMetadata(anchor: HTMLAnchorElement) {
const results = anchor.closest('#search-results')
if (!results) return null

const options = [...results.querySelectorAll<HTMLElement>('[role="option"]')]
const option = anchor.closest<HTMLElement>('[role="option"]')
const rank = option ? options.indexOf(option) + 1 : 0
const url = new URL(anchor.href, window.location.origin)
return {
queryLength: findVocsSearchInput()?.value.trim().length ?? 0,
resultPath: url.pathname,
resultRank: Math.max(rank, 0),
resultType: url.hash ? 'section' : 'page',
}
}

function PostHogInitializer({ site }: { site: string }) {
useEffect(() => {
const posthogKey = import.meta.env.VITE_POSTHOG_KEY
const posthogHost = import.meta.env.VITE_POSTHOG_HOST
if (!posthogKey) return
if (!isProductionAnalyticsHost(window.location.hostname)) return

if (!posthogKey || !posthogHost) return
const analyticsRelease =
import.meta.env.VITE_ANALYTICS_RELEASE?.trim() || DEFAULT_ANALYTICS_RELEASE

const init = async () => {
let cancelled = false
const initializePostHog = async () => {
const { default: posthog } = await import('posthog-js')
if (cancelled) return

const registerBrowserContext = () => {
posthog.register(getAnalyticsRuntimeProperties(site, analyticsRelease))
markPostHogReady(posthog)
}

if (posthog.__loaded) {
registerBrowserContext()
return
}

posthog.init(posthogKey, {
api_host: '/ingest',
ui_host: posthogHost,
defaults: '2025-11-30',
capture_exceptions: true,
debug: import.meta.env.MODE === 'development',
ui_host: POSTHOG_UI_HOST,
defaults: '2026-05-30',
capture_pageview: 'history_change',
capture_pageleave: 'if_capture_pageview',
enable_heatmaps: true,
capture_dead_clicks: true,
cross_subdomain_cookie: true,
secure_cookie: true,
person_profiles: 'identified_only',
autocapture: {
dom_event_allowlist: ['click', 'submit'],
element_allowlist: ['a', 'button', 'form'],
css_selector_ignorelist: [
'.ph-no-capture',
'[data-ph-no-autocapture]',
'[data-ph-sensitive]',
'input',
'textarea',
'select',
'[contenteditable="true"]',
],
element_attribute_ignorelist: [
'value',
'data-value',
'data-secret',
'data-private',
'aria-valuetext',
],
capture_copied_text: false,
},
mask_all_text: true,
mask_all_element_attributes: true,
session_recording: {
maskAllInputs: false,
maskInputOptions: {
password: true,
maskAllInputs: true,
maskTextSelector:
'input, textarea, select, [contenteditable="true"], [data-ph-sensitive]',
blockSelector: '[data-ph-sensitive]',
recordHeaders: false,
recordBody: false,
captureCanvas: { recordCanvas: false },
collectFonts: false,
maskCapturedNetworkRequestFn: (request) => {
const name = sanitizeAnalyticsUrl(request.name)
if (!name) return undefined
return {
...request,
name,
requestHeaders: undefined,
requestBody: undefined,
responseHeaders: undefined,
responseBody: undefined,
}
},
},
disable_session_recording: hasUnsafeAnalyticsQuery(window.location.href),
enable_recording_console_log: false,
before_send: (capture) =>
sanitizePostHogCapture(
enrichPostHogCapture(capture, window.location.pathname, document.title),
),
capture_exceptions: true,
debug: import.meta.env.MODE === 'development',
loaded: registerBrowserContext,
})
posthog.register({ site })
}
void initializePostHog()

if ('requestIdleCallback' in window) {
const idleId = window.requestIdleCallback(init, { timeout: 2_000 })
return () => window.cancelIdleCallback(idleId)
let lastSearchSelection = ''
let lastSearchSelectionAt = 0

const captureSearchResult = (anchor: HTMLAnchorElement) => {
const metadata = vocsSearchResultMetadata(anchor)
if (!metadata) return false

const selectionKey = `${metadata.resultPath}:${metadata.resultRank}`
const now = Date.now()
if (selectionKey === lastSearchSelection && now - lastSearchSelectionAt < 500) return true

lastSearchSelection = selectionKey
lastSearchSelectionAt = now
trackDocsSearchResultClick(metadata)
return true
}

const timeoutId = globalThis.setTimeout(init, 1)
return () => globalThis.clearTimeout(timeoutId)
const handleClick = (event: MouseEvent) => {
const target = eventTargetElement(event)
if (!target) return

const anchor = target.closest<HTMLAnchorElement>('a[href]')
if (anchor) {
if (captureSearchResult(anchor)) return

const cta = classifyStrategicCta(anchor.href, window.location.pathname)
if (cta)
trackDocsCtaClick({
...cta,
ctaText: anchor.textContent ?? undefined,
location: ctaLocation(anchor),
})
}

const button = target.closest<HTMLButtonElement>('button')
if (!button) return
const metadata = copyMetadata(button)
if (metadata) trackDocsCopyCode(metadata)
}

const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Enter') return
const target = eventTargetElement(event)
if (!(target instanceof HTMLInputElement)) return
if (target.getAttribute('aria-controls') !== 'search-results') return

const results = document.getElementById('search-results')
const option = results?.querySelector<HTMLElement>(
'[role="option"][aria-selected="true"], [role="option"][data-selected="true"], [role="option"]',
)
const anchor =
option instanceof HTMLAnchorElement
? option
: option?.querySelector<HTMLAnchorElement>('a[href]')
if (anchor) captureSearchResult(anchor)
}

window.addEventListener('click', handleClick, true)
window.addEventListener('keydown', handleKeyDown, true)
return () => {
cancelled = true
window.removeEventListener('click', handleClick, true)
window.removeEventListener('keydown', handleKeyDown, true)
}
}, [site])

return null
}

export default function PostHogSetup({ site = 'docs' }: { site?: string }) {
const posthogKey = import.meta.env.VITE_POSTHOG_KEY
const posthogHost = import.meta.env.VITE_POSTHOG_HOST

if (!posthogKey || !posthogHost) return null

if (!import.meta.env.VITE_POSTHOG_KEY) return null
return <PostHogInitializer site={site} />
}
Loading
Loading