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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@ NEXT_PUBLIC_SHOWCASES_ORIGIN=https://office.univer.ai
# Client license for the site's built-in editors; included in the browser bundle.
CLIENT_LICENSE_TEXT=

# Optional server-side analytics sent to PostHog US; disabled when empty.
# Page views include path, language, referrer, browser, OS, and device type.
# Enabling page-view analytics renders tracked pages per request.
NEXT_POSTHOG_APIKEY=

# Override in .env.local when running the sibling Showcase project locally.
# NEXT_PUBLIC_SHOWCASES_ORIGIN=http://localhost:5180
2 changes: 2 additions & 0 deletions app/[lang]/(home)/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { getGuidesMDXComponents } from '@/components/mdx/components'
import { Button } from '@/components/ui/button'
import { formatLocalDate } from '@/lib/dayjs'
import { createDocsRelativeLink } from '@/lib/docs/links'
import { trackDocsPageView } from '@/lib/docs/page-view'
import { getContentLocale, stripLocalePrefix, withLocale } from '@/lib/locale-path'
import { blog, getActiveBlogPage, getActiveBlogParams } from '@/lib/source'

Expand Down Expand Up @@ -71,6 +72,7 @@ export default async function Page({ params }: IProps) {
}

const { default: MDXContent, toc } = await page.data.load()
await trackDocsPageView({ lang, url: stripLocalePrefix(page.url) })
const BlogLink = createDocsRelativeLink(blog, page)
const contentLocale = getContentLocale(page.path)
const pageUrl = `${BLOG_ORIGIN}${withLocale(contentLocale, stripLocalePrefix(page.url))}`
Expand Down
2 changes: 2 additions & 0 deletions app/[lang]/(home)/blog/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Link from 'next/link'
import type { Locale } from '@/i18n/routing'
import { Footer } from '@/components/footer'
import { formatLocalDate } from '@/lib/dayjs'
import { trackDocsPageView } from '@/lib/docs/page-view'
import { stripLocalePrefix, withLocale } from '@/lib/locale-path'
import { getActiveBlogPages } from '@/lib/source'

Expand Down Expand Up @@ -39,6 +40,7 @@ export default async function Page({ params }: IProps) {
const posts = getActiveBlogPages(lang).toSorted((a, b) => {
return new Date(b.data.date).getTime() - new Date(a.data.date).getTime()
})
await trackDocsPageView({ lang, url: '/blog' })
const postsByYear = new Map<number, typeof posts>()

for (const post of posts) {
Expand Down
37 changes: 2 additions & 35 deletions components/docs-feedback.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,15 @@
import process from 'node:process'
import { headers } from 'next/headers'
import { after, userAgent } from 'next/server'
import { PostHog } from 'posthog-node'
import { Rate } from '@/components/rate'
import { withLocale } from '@/lib/locale-path'
import { trackDocsPageView } from '@/lib/docs/page-view'

interface IDocsFeedbackProps {
lang: string
url: string
}

export async function DocsFeedback({ lang, url }: IDocsFeedbackProps) {
const pathname = withLocale(lang, url)
const apiKey = process.env.NEXT_POSTHOG_APIKEY

if (process.env.NODE_ENV === 'production' && apiKey) {
// Read during render so visits run per request instead of during static generation.
const requestHeaders = await headers()
const agent = userAgent({ headers: requestHeaders })
const referrer = requestHeaders.get('referer')
const isPrefetch =
requestHeaders.get('purpose')?.includes('prefetch') || requestHeaders.get('sec-purpose')?.includes('prefetch')

if (!agent.isBot && !isPrefetch && !requestHeaders.has('next-action')) {
after(async () => {
const posthog = new PostHog(apiKey, { host: 'https://us.i.posthog.com', flushInterval: 0 })
posthog.capture({
event: 'on_view_docs',
distinctId: 'anonymous',
properties: {
url: pathname,
lang,
referrer,
$browser: agent.browser.name,
$os: agent.os.name,
$device_type:
agent.device.type === 'mobile' ? 'Mobile' : agent.device.type === 'tablet' ? 'Tablet' : 'Desktop',
$process_person_profile: false,
},
})
await posthog.shutdown()
})
}
}
await trackDocsPageView({ lang, url })

return (
<Rate
Expand Down
136 changes: 136 additions & 0 deletions lib/docs/__tests__/page-view.spec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import process from 'node:process'
import { after, beforeEach, mock, test } from 'node:test'

// Run with node --experimental-test-module-mocks --test lib/docs/__tests__/page-view.spec.mjs.
const originalEnv = { NODE_ENV: process.env.NODE_ENV, NEXT_POSTHOG_APIKEY: process.env.NEXT_POSTHOG_APIKEY }
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier === 'server-only') return { url: 'data:text/javascript,', shortCircuit: true }
if (specifier === 'next/headers' || specifier === 'next/server') return nextResolve(`${specifier}.js`, context)
if (specifier.startsWith('@/'))
return nextResolve(new URL(`../../../${specifier.slice(2)}.ts`, import.meta.url).href, context)
return nextResolve(specifier, context)
},
})

let requestHeaders
let agent
let pending
let events
let clients
let headerReads
let shutdowns

mock.module('next/headers.js', {
namedExports: {
headers: async () => {
headerReads++
return { get: (name) => requestHeaders[name] ?? null, has: (name) => name in requestHeaders }
},
},
})
mock.module('next/server.js', {
namedExports: { after: (callback) => pending.push(callback), userAgent: () => agent },
})
mock.module('posthog-node', {
namedExports: {
PostHog: function (apiKey, options) {
clients.push({ apiKey, options })
return { capture: (event) => events.push(event), shutdown: async () => shutdowns++ }
},
},
})

const { trackDocsPageView } = await import('../page-view.ts')

beforeEach(() => {
process.env.NODE_ENV = 'production'
process.env.NEXT_POSTHOG_APIKEY = 'test-server-key'
requestHeaders = { referer: 'https://docs.univer.ai/blog' }
agent = { isBot: false, browser: { name: 'Chrome' }, os: { name: 'Windows' }, device: {} }
pending = []
events = []
clients = []
headerReads = 0
shutdowns = 0
})

after(() => {
hooks.deregister()
mock.restoreAll()
for (const [key, value] of Object.entries(originalEnv)) {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
})

for (const [lang, url, expected] of [
['en-US', '/blog', '/blog'],
['zh-CN', '/blog/univer-1.0', '/zh-CN/blog/univer-1.0'],
['ja-JP', '/guides/sheets', '/ja-JP/guides/sheets'],
]) {
test(`defers and flushes the existing visit event for ${expected}`, async () => {
assert.equal(await trackDocsPageView({ lang, url }), undefined)
assert.equal(headerReads, 1)
assert.equal(pending.length, 1)
assert.deepEqual(events, [])
assert.deepEqual(clients, [])
await pending[0]()
assert.deepEqual(clients, [
{ apiKey: 'test-server-key', options: { host: 'https://us.i.posthog.com', flushInterval: 0 } },
])
assert.deepEqual(events, [
{
event: 'on_view_docs',
distinctId: 'anonymous',
properties: {
url: expected,
lang,
referrer: requestHeaders.referer,
$browser: 'Chrome',
$os: 'Windows',
$device_type: 'Desktop',
$process_person_profile: false,
},
},
])
assert.equal(shutdowns, 1)
})
}

for (const excluded of ['bot', 'purpose', 'sec-purpose', 'next-action']) {
test(`does not report ${excluded} requests`, async () => {
if (excluded === 'bot') agent.isBot = true
else requestHeaders[excluded] = excluded === 'next-action' ? 'action-id' : 'prefetch'
await trackDocsPageView({ lang: 'en-US', url: '/blog' })
assert.equal(headerReads, 1)
assert.deepEqual(pending, [])
assert.deepEqual(clients, [])
})
}

for (const env of ['development', 'test', 'missing-key']) {
test(`avoids request-time work with ${env}`, async () => {
if (env === 'missing-key') delete process.env.NEXT_POSTHOG_APIKEY
else process.env.NODE_ENV = env
await trackDocsPageView({ lang: 'en-US', url: '/blog' })
assert.equal(headerReads, 0)
assert.deepEqual(pending, [])
})
}

for (const [type, expected] of [
['mobile', 'Mobile'],
['tablet', 'Tablet'],
]) {
test(`preserves the ${expected} device property`, async () => {
agent.device.type = type
delete requestHeaders.referer
await trackDocsPageView({ lang: 'en-US', url: '/blog' })
await pending[0]()
assert.equal(events[0].properties.$device_type, expected)
assert.equal(events[0].properties.referrer, null)
})
}
46 changes: 46 additions & 0 deletions lib/docs/page-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import process from 'node:process'
import { headers } from 'next/headers'
import { after, userAgent } from 'next/server'
import { PostHog } from 'posthog-node'
import { withLocale } from '@/lib/locale-path'
import 'server-only'

interface IDocsPageViewParams {
lang: string
url: string
}

export async function trackDocsPageView({ lang, url }: IDocsPageViewParams) {
const pathname = withLocale(lang, url)
const apiKey = process.env.NEXT_POSTHOG_APIKEY

if (process.env.NODE_ENV === 'production' && apiKey) {
// Read during render so visits run per request instead of during static generation.
const requestHeaders = await headers()
const agent = userAgent({ headers: requestHeaders })
const referrer = requestHeaders.get('referer')
const isPrefetch =
requestHeaders.get('purpose')?.includes('prefetch') || requestHeaders.get('sec-purpose')?.includes('prefetch')

if (!agent.isBot && !isPrefetch && !requestHeaders.has('next-action')) {
after(async () => {
const posthog = new PostHog(apiKey, { host: 'https://us.i.posthog.com', flushInterval: 0 })
posthog.capture({
event: 'on_view_docs',
distinctId: 'anonymous',
properties: {
url: pathname,
lang,
referrer,
$browser: agent.browser.name,
$os: agent.os.name,
$device_type:
agent.device.type === 'mobile' ? 'Mobile' : agent.device.type === 'tablet' ? 'Tablet' : 'Desktop',
$process_person_profile: false,
},
})
await posthog.shutdown()
})
}
}
}
Loading