From ddda92a95cab6de39da269b903a20d7d22a70a25 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Mon, 30 Nov 2026 19:22:11 +0000 Subject: [PATCH 1/4] feat(docs-next): send docs search and product-switch events to the data layer The docs sent no custom events, so Marketing could not report on search or product use. A docs_search event now fires once per search session, when the dialog closes after a query of two or more characters, and docs_product_switch fires when a reader picks another product. trackDocsEvent pushes only once the Tag Manager container is on the page and otherwise drops the event, because the container replays whatever is queued when it loads, which would send an event from before consent. The search term is whitespace-collapsed, trimmed and capped at 100 characters, and no result URL is sent. Assisted-by: AI --- ARCHITECTURE.md | 3 + apps/docs/README.md | 18 ++ packages/docs-config/src/client.ts | 4 + packages/docs-config/src/track.test.ts | 66 +++++ packages/docs-config/src/track.ts | 13 + packages/docs-next/src/hybrid-search.tsx | 4 +- .../docs-next/src/product-switcher.test.tsx | 62 ++++- packages/docs-next/src/product-switcher.tsx | 11 +- packages/docs-next/src/search-dialog.tsx | 20 +- packages/docs-next/src/search-events.test.tsx | 235 ++++++++++++++++++ packages/docs-next/src/search-events.ts | 62 +++++ 11 files changed, 484 insertions(+), 14 deletions(-) create mode 100644 packages/docs-config/src/track.test.ts create mode 100644 packages/docs-config/src/track.ts create mode 100644 packages/docs-next/src/search-events.test.tsx create mode 100644 packages/docs-next/src/search-events.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b23cd8e8..ae4ce420 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -242,6 +242,9 @@ Each vendor is named by origin except jsDelivr, a public CDN for any npm package The router applies that policy to archive responses when its own `DOCS_ANALYTICS` is on; `apps/docs/vercel.json`, which cannot vary by environment, keeps the policy above. Widening `script-src` this way is a security decision and needs sign-off before the flag is turned on anywhere. +The search dialog and the product switcher also push `docs_search` and `docs_product_switch` to the container's `dataLayer` through `trackDocsEvent`, which pushes only once the GTM container is on the page and otherwise drops the event, so nothing is sent before consent or without the flag (`apps/docs/README.md` "Analytics"). +It adds no origin, so it needs no change to the policy. + Hardening path, not yet taken: the inline scripts in a static export are fixed at build time, so `csp:check` could emit their SHA-256 hashes and the policy could name them in place of `'unsafe-inline'`. That makes the policy a real barrier to injected inline scripts at the cost of regenerating the header on every build and keeping the router's archive headers in step per version. It is the next step if the sanitizer ever has to be weakened, and otherwise a later improvement. diff --git a/apps/docs/README.md b/apps/docs/README.md index be4b5ed1..f44804d8 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -659,6 +659,24 @@ This has no effect on the public site, which the router serves and gates separat coder.com's `next.config.js` restates the `/docs` policy (step 4 of "Serving through coder.com" below, and the [cutover runbook](https://app.notion.com/p/3f8d579be59281a691f1e6146c2fc1a9), internal, on Notion) and must carry the same origins. Only `script-src` needs them: the policy has no `default-src`, so Osano's and the tags' requests, images, frames, and styles are not restricted. +#### Events + +The docs push two custom events to the Tag Manager `dataLayer` through `trackDocsEvent` in `@coder/docs-config/client`, so any tag Marketing adds to the container (Segment, GA4) can read them. +The helper pushes only once `window.google_tag_manager["GTM-NLLNT3K"]` exists, that is, after a reader accepted marketing consent and GTM loaded. +Before that it drops the event instead of queueing it, because GTM replays everything already in `dataLayer` when it loads, which would send an event from before consent. +With the flag off, on previews, in the offline export, for a reader who denied, or before GTM has loaded, nothing is pushed. +A reader who withdraws marketing consent gets a page reload, so no event can follow the withdrawal. + +| Event | Fires | Fields | +| ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `docs_search` | Once per search session, when the search dialog closes after the reader typed a query of 2 or more characters. | `search_term` (whitespace collapsed, trimmed, at most 100 characters), `results_count` (0 if the results had not arrived), `product` (`coder` or `code-server`), `result_opened` (true when a result was chosen). | +| `docs_product_switch` | When a reader picks a different product in the sidebar switcher. | `from_product`, `to_product` (`coder` or `code-server`). | + +Search queries can hold pasted text such as error messages, so `search_term` is capped and Security and Privacy should review it before Marketing sends it on to Segment. +The event carries no result URL. +Page views are not sent by the docs: the container needs a history-change trigger, since the docs navigate on the client. +Marketing needs a Custom Event trigger for each event name above in `GTM-NLLNT3K`, and a tag per destination that reads the fields as Data Layer Variables; until then the events are inert. + The offline export never loads any of this: `turbo.json` does not pass `DOCS_ANALYTICS` to its build, its source names none of the analytics exports, and `pnpm --filter @coder/offlinedocs analytics:check`, run in CI after the build, fails if any page in `out/` carries Osano, GTM, the bootstrap, or the footer control. Turning the tags on for the public site takes four switches, in this order, because a page that loads the tags under a policy without their origins gets its scripts blocked: diff --git a/packages/docs-config/src/client.ts b/packages/docs-config/src/client.ts index dc40c325..fcb992b8 100644 --- a/packages/docs-config/src/client.ts +++ b/packages/docs-config/src/client.ts @@ -63,3 +63,7 @@ export type { OpenApiSchemas, } from "./openapi.js"; export { isObject, type JsonObject } from "./json.js"; + +export { trackDocsEvent } from "./track.js"; +export type { DocsEventData } from "./track.js"; +export { GTM_CONTAINER_ID } from "./analytics.js"; diff --git a/packages/docs-config/src/track.test.ts b/packages/docs-config/src/track.test.ts new file mode 100644 index 00000000..6fd448de --- /dev/null +++ b/packages/docs-config/src/track.test.ts @@ -0,0 +1,66 @@ +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { GTM_CONTAINER_ID } from "./analytics.js"; +import { trackDocsEvent } from "./track.js"; + +const realWindow = Object.getOwnPropertyDescriptor(globalThis, "window"); + +type FakeWindow = Record; + +function useWindow(setup: (window: FakeWindow) => void): FakeWindow { + const window: FakeWindow = {}; + setup(window); + Object.defineProperty(globalThis, "window", { value: window, configurable: true }); + return window; +} + +function layerOf(window: FakeWindow): unknown[] { + const layer = window.dataLayer; + assert.ok(Array.isArray(layer)); + return layer; +} + +afterEach(() => { + if (realWindow) Object.defineProperty(globalThis, "window", realWindow); + else Reflect.deleteProperty(globalThis, "window"); +}); + +test("trackDocsEvent pushes nothing while the container is absent, and queues nothing", () => { + const window = useWindow((w) => (w.dataLayer = [])); + trackDocsEvent("docs_search", { search_term: "token" }); + assert.equal(layerOf(window).length, 0); + window.google_tag_manager = { [GTM_CONTAINER_ID]: {} }; + assert.equal(layerOf(window).length, 0); +}); + +test("trackDocsEvent pushes nothing for another container or without a data layer", () => { + const other = useWindow((w) => { + w.dataLayer = []; + w.google_tag_manager = { "GTM-OTHER": {} }; + }); + trackDocsEvent("docs_search"); + assert.equal(layerOf(other).length, 0); + const bare = useWindow((w) => (w.google_tag_manager = { [GTM_CONTAINER_ID]: {} })); + trackDocsEvent("docs_search"); + assert.equal(bare.dataLayer, undefined); +}); + +test("trackDocsEvent pushes the event and its fields once the container is present", () => { + const window = useWindow((w) => { + w.dataLayer = []; + w.google_tag_manager = { [GTM_CONTAINER_ID]: {} }; + }); + trackDocsEvent("docs_product_switch", { from_product: "coder", to_product: "code-server" }); + const layer = layerOf(window); + assert.equal(layer.length, 1); + assert.deepEqual(layer[0], { + event: "docs_product_switch", + from_product: "coder", + to_product: "code-server", + }); +}); + +test("trackDocsEvent does nothing outside a browser", () => { + Reflect.deleteProperty(globalThis, "window"); + trackDocsEvent("docs_search"); +}); diff --git a/packages/docs-config/src/track.ts b/packages/docs-config/src/track.ts new file mode 100644 index 00000000..f12964a1 --- /dev/null +++ b/packages/docs-config/src/track.ts @@ -0,0 +1,13 @@ +import { GTM_CONTAINER_ID } from "./analytics.js"; +import { isObject } from "./json.js"; + +export type DocsEventData = Record; + +/** Pushes `event` to the Tag Manager data layer once the container has loaded, and otherwise drops it, since the container replays anything queued before consent. */ +export function trackDocsEvent(event: `docs_${string}`, data: DocsEventData = {}): void { + if (typeof window === "undefined") return; + const containers: unknown = Reflect.get(window, "google_tag_manager"); + if (!isObject(containers) || !(GTM_CONTAINER_ID in containers)) return; + const layer: unknown = Reflect.get(window, "dataLayer"); + if (Array.isArray(layer)) layer.push({ event, ...data }); +} diff --git a/packages/docs-next/src/hybrid-search.tsx b/packages/docs-next/src/hybrid-search.tsx index 87c88909..6375cea6 100644 --- a/packages/docs-next/src/hybrid-search.tsx +++ b/packages/docs-next/src/hybrid-search.tsx @@ -14,6 +14,7 @@ import { } from "fumadocs-ui/components/dialog/search"; import type { SharedProps } from "fumadocs-ui/contexts/search"; import { useCallback, useEffect, useMemo, useState } from "react"; +import { useSearchEvent } from "./search-events.js"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; import { type SemanticIndex, @@ -113,8 +114,9 @@ export default function HybridSearchDialog({ // oxlint-disable-next-line react-hooks/exhaustive-deps -- `loaded` re-runs the current query once the semantic index arrives. const run = useCallback((query: string) => client.search(query), [client, loaded]); const search = experimental_useSearch(run); + const { onSelect } = useSearchEvent({ open: props.open, ...search, product }); return ( - + diff --git a/packages/docs-next/src/product-switcher.test.tsx b/packages/docs-next/src/product-switcher.test.tsx index e068860f..55916730 100644 --- a/packages/docs-next/src/product-switcher.test.tsx +++ b/packages/docs-next/src/product-switcher.test.tsx @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { afterEach, beforeEach, test } from "node:test"; -import { CODE_SERVER_PRODUCT, CODER_PRODUCT } from "@coder/docs-config/client"; +import { CODE_SERVER_PRODUCT, CODER_PRODUCT, GTM_CONTAINER_ID } from "@coder/docs-config/client"; import { loader } from "fumadocs-core/source"; import { act } from "react"; import { type Root, createRoot } from "react-dom/client"; @@ -208,3 +208,63 @@ test("choosing an option closes the list", async () => { }); assert.equal(document.querySelectorAll("[data-product-item]").length, 0); }); + +function docsEvents(): Record[] { + const layer: unknown[] = Reflect.get(window, "dataLayer"); + return layer.flatMap((entry) => + typeof entry === "object" && entry !== null && "event" in entry + ? [Object.fromEntries(Object.entries(entry))] + : [], + ); +} + +async function choose(index: number) { + const { items } = await openFirst(); + document.addEventListener("click", (event) => event.preventDefault(), { once: true }); + await act(async () => { + items[index]?.dispatchEvent( + new window.MouseEvent("click", { bubbles: true, cancelable: true }), + ); + }); +} + +test("choosing another product sends docs_product_switch with both product ids", async () => { + Reflect.set(window, "dataLayer", []); + Reflect.set(window, "google_tag_manager", { [GTM_CONTAINER_ID]: {} }); + try { + await renderPage("/admin/users", corpus(true)); + await choose(1); + const events = docsEvents(); + assert.equal(events.length, 1); + assert.equal(events[0]?.event, "docs_product_switch"); + assert.equal(events[0]?.from_product, "coder"); + assert.equal(events[0]?.to_product, "code-server"); + } finally { + Reflect.deleteProperty(window, "google_tag_manager"); + Reflect.deleteProperty(window, "dataLayer"); + } +}); + +test("choosing the current product sends no event", async () => { + Reflect.set(window, "dataLayer", []); + Reflect.set(window, "google_tag_manager", { [GTM_CONTAINER_ID]: {} }); + try { + await renderPage("/code-server/install", corpus(true)); + await choose(1); + assert.equal(docsEvents().length, 0); + } finally { + Reflect.deleteProperty(window, "google_tag_manager"); + Reflect.deleteProperty(window, "dataLayer"); + } +}); + +test("switching product sends nothing while the container has not loaded", async () => { + Reflect.set(window, "dataLayer", []); + try { + await renderPage("/admin/users", corpus(true)); + await choose(1); + assert.equal(docsEvents().length, 0); + } finally { + Reflect.deleteProperty(window, "dataLayer"); + } +}); diff --git a/packages/docs-next/src/product-switcher.tsx b/packages/docs-next/src/product-switcher.tsx index 60a545fe..895e0264 100644 --- a/packages/docs-next/src/product-switcher.tsx +++ b/packages/docs-next/src/product-switcher.tsx @@ -5,7 +5,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "fumadocs-ui/components/ import { useTreeContext } from "fumadocs-ui/contexts/tree"; import { Check, ChevronsUpDown } from "lucide-react"; import { type KeyboardEvent, useState } from "react"; -import type { DocsProduct } from "@coder/docs-config/client"; +import { type DocsProduct, productForUrl, trackDocsEvent } from "@coder/docs-config/client"; import { productHome, productRoots, treeHome } from "./product-roots.js"; interface Choice { @@ -91,7 +91,14 @@ export function ProductSwitcher({ primary }: { primary: DocsProduct }) { href={choice.href} data-product-item="" aria-current={choice.current ? "true" : undefined} - onClick={() => setOpen(false)} + onClick={() => { + setOpen(false); + if (choice === current) return; + trackDocsEvent("docs_product_switch", { + from_product: productForUrl(current.href).id, + to_product: productForUrl(choice.href).id, + }); + }} className="flex items-center gap-2 rounded-lg p-1.5 hover:bg-fd-accent hover:text-fd-accent-foreground" > diff --git a/packages/docs-next/src/search-dialog.tsx b/packages/docs-next/src/search-dialog.tsx index 2c940745..40566e67 100644 --- a/packages/docs-next/src/search-dialog.tsx +++ b/packages/docs-next/src/search-dialog.tsx @@ -18,6 +18,7 @@ import { useI18n } from "fumadocs-ui/contexts/i18n"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { focusAfterNavigation, returnFocusTo } from "./return-focus.js"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; +import { countResults, useSearchEvent } from "./search-events.js"; function renderItem(props: Parameters[0] & { onClick: () => void }) { return ; @@ -29,15 +30,6 @@ function NoResults() { return
No results found
; } -/** The number of results a search found, counting each row of a table. */ -export function countResults(data: SearchResult | undefined): number | null { - if (!data) return null; - return data.items.reduce( - (count, item) => count + (item.type === "table" ? item.rows.length : 1), - 0, - ); -} - export function searchStatus(search: string, isLoading: boolean, count: number | null): string { if (search.trim() === "") return ""; if (isLoading) return "Searching"; @@ -145,6 +137,7 @@ export function SearchDialogView({ defaultItems, footer, announceDelayMs = 500, + onSelect: onSelectItem, }: { open: boolean; onOpenChange: (open: boolean) => void; @@ -156,8 +149,13 @@ export function SearchDialogView({ defaultItems?: SearchItemType[] | null; footer?: DefaultSearchDialogProps["footer"]; announceDelayMs?: number; + onSelect?: () => void; }) { - const { onSelect, ...contentProps } = useReturnFocus(); + const { onSelect: returnFocusOnSelect, ...contentProps } = useReturnFocus(); + const onSelect = (item: SearchItemType) => { + returnFocusOnSelect(item); + onSelectItem?.(); + }; return ( ( () => links.length === 0 @@ -233,6 +232,7 @@ export default function DocsSearchDialog({ error={error} defaultItems={defaultItems} footer={footer} + onSelect={onSelect} /> ); } diff --git a/packages/docs-next/src/search-events.test.tsx b/packages/docs-next/src/search-events.test.tsx new file mode 100644 index 00000000..7b24ec74 --- /dev/null +++ b/packages/docs-next/src/search-events.test.tsx @@ -0,0 +1,235 @@ +import assert from "node:assert/strict"; +import { afterEach, beforeEach, test } from "node:test"; +import { GTM_CONTAINER_ID } from "@coder/docs-config/client"; +import { FrameworkProvider } from "fumadocs-core/framework"; +import { type MetaData, type VirtualFile, loader } from "fumadocs-core/source"; +import { type ComponentType, act, createElement, useState } from "react"; +import { type Root, createRoot } from "react-dom/client"; +import HybridSearchDialog from "./hybrid-search.js"; +import DocsSearchDialog from "./search-dialog.js"; +import { createDocsSearchRoute } from "./search.js"; +import type { DocsPageData } from "./types.js"; + +const API = "/events/api/search"; +const dialogs: [ + string, + ComponentType<{ api: string; open: boolean; onOpenChange: (open: boolean) => void }>, +][] = [ + ["hybrid dialog", HybridSearchDialog], + ["keyword dialog", DocsSearchDialog], +]; + +async function index(): Promise { + const files: VirtualFile<{ + pageData: DocsPageData & { structuredData: unknown }; + metaData: MetaData; + }>[] = [ + { + type: "page", + path: "install.md", + data: { + title: "Install Coder", + body: () => createElement("p"), + toc: [], + structuredData: { headings: [], contents: [{ heading: undefined, content: "install" }] }, + }, + }, + ]; + const route = createDocsSearchRoute(loader({ baseUrl: "/", source: { files } }) as never); + return await (await route.GET()).text(); +} + +const realFetch = globalThis.fetch; +const warn = console.warn; +let container: HTMLElement; +let root: Root; +let body: string; + +beforeEach(async () => { + body = await index(); + globalThis.fetch = (async (input: URL | RequestInfo) => { + const { pathname } = new URL(String(input), document.baseURI); + return pathname === API ? new Response(body) : new Response(null, { status: 404 }); + }) as typeof fetch; + console.warn = () => {}; + Reflect.set(window, "dataLayer", []); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(async () => { + globalThis.fetch = realFetch; + console.warn = warn; + Reflect.deleteProperty(window, "google_tag_manager"); + Reflect.deleteProperty(window, "dataLayer"); + await act(async () => root.unmount()); + container.remove(); +}); + +function loadContainer() { + Reflect.set(window, "google_tag_manager", { [GTM_CONTAINER_ID]: {} }); +} + +function docsEvents(): Record[] { + const layer: unknown[] = Reflect.get(window, "dataLayer"); + return layer.flatMap((entry) => + typeof entry === "object" && entry !== null && "event" in entry + ? [Object.fromEntries(Object.entries(entry))] + : [], + ); +} + +async function mount(Dialog: (typeof dialogs)[number][1], pathname = "/") { + function Harness() { + const [open, setOpen] = useState(true); + return ( + <> +