feat(docs): layout toggle (#53688)

## Problem

- docs layout v2 (variant `option-1` of the `docs-ia-mvp-v1` flag) is
about to roll out and a reader in the rollout has no way back to the
classic layout

## Solution

- adds a toggle button bottom of the guide right column so user in the
rollout can switch back
- adds a dialog that asks for an optional reason when a reader switches
back to classic, and stores the reason in `feedback_comments` with
`metadata.source = 'docs_layout_switch'` so we relying on existing
- adds the `docs_layout_updated` event and stops new experiment
exposures for readers who picked a layout

| toggle | survey |
| -------|------|
| <img width="654" height="312" alt="image"
src="https://github.com/user-attachments/assets/69bcd4b8-7dd2-4fd3-9045-e3246625ccf9"
/> | <img width="654" height="312" alt="image"
src="https://github.com/user-attachments/assets/4b18eb76-b9f1-4d96-be25-14a960b11475"
/> |

<!--
## Preview links

If relevant, include links to changed pages for easy review access.

Copy the preview base URL from the Vercel bot comment on this PR. Use
the following table as an example template.

| Site | Live | Preview | Search for |
| -------------- |
-------------------------------------------------------------------------
|
------------------------------------------------------------------------------------------------------------
| ----------------------------- |
| WWW | [/blog/your-post](https://supabase.com/blog/your-post) |
[/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post)
| unique phrase from the change |
| Docs |
[/docs/guides/your-page](https://supabase.com/docs/guides/your-page) |
[/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page)
| unique phrase from the change |
| Studio | [/dashboard](https://supabase.com/dashboard) |
[/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard)
| unique phrase from the change |
| Design system | [/design-system](https://supabase.com/design-system) |
[/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system)
| unique phrase from the change |
| UI library | [/library](https://supabase.com/library) |
[/library](https://ui-library-git-branch-name-supabase.vercel.app/library)
| unique phrase from the change |
| Knowledge base |
[/kb/guides/your-page](https://supabase.com/kb/guides/your-page) |
[/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page)
| unique phrase from the change |
-->

<!-- ## Additional context

Optionally add any other context or screenshots.

-->

## Review instructions

1. open
[/docs/guides/database/prisma?docs-ia-mvp-v1=option-1](https://docs-git-antlio-feat-docs-layout-switch-v2-supabase.vercel.app/docs/guides/database/prisma?docs-ia-mvp-v1=option-1)
2. click "Switch to classic layout" in the notice and make sure that a
dialog asks "What made you switch back?"

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
This commit is contained in:
anthony lio authored and GitHub committed 2026-12-01 11:43:40 +02:00
1 parent 680633ee4f
commit 6bd006dc08
15 files changed
+592 -60

No files matched your search

+4 -2
View File
@@ -8,6 +8,7 @@ import { Bug, Check, MessageSquareQuote, ThumbsDown, ThumbsUp, X } from 'lucide-
import { usePathname } from 'next/navigation'
import {
forwardRef,
useId,
useReducer,
useRef,
useState,
@@ -95,6 +96,7 @@ function Feedback({ className, variant = 'default' }: FeedbackProps) {
const pathname = usePathname() ?? ''
const sendTelemetryEvent = useSendTelemetryEvent()
const isRail = variant === 'rail'
const titleId = useId()
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
const supabase = useConstant(() =>
@@ -157,9 +159,9 @@ function Feedback({ className, variant = 'default' }: FeedbackProps) {
}
return (
<section className={cn('@container', className)} aria-labelledby="feedback-title">
<section className={cn('@container', className)} aria-labelledby={titleId}>
<h2
id="feedback-title"
id={titleId}
className={cn('block font-mono text-xs text-foreground-light mb-3', isRail && 'sr-only')}
>
Is this helpful?
@@ -4,6 +4,7 @@
import { AiTools } from '~/components/AiTools'
import { Feedback } from '~/components/Feedback'
import { VideoPreview } from '~/components/VideoPreview'
import { LayoutSwitchButton } from '~/features/DocsLayout/LayoutSwitchButton'
import { isFeatureEnabled } from 'common'
import { usePathname } from 'next/navigation'
import { cn } from 'ui'
@@ -59,6 +60,7 @@ const GuidesSidebar = ({
{!hideToc && toc.length !== 0 && (
<TocSection items={toc} scrollAreaClassName="-me-8.75 pe-8.75" />
)}
<LayoutSwitchButton className="ml-5 shrink-0" />
</div>
</div>
)
+60 -44
View File
@@ -3,6 +3,7 @@
import { Feedback } from '~/components/Feedback'
import { LegacyGuidesSidebar } from '~/components/GuidesSidebar.legacy'
import { VideoPreview } from '~/components/VideoPreview'
import { LayoutSwitchButton } from '~/features/DocsLayout/LayoutSwitchButton'
import { useDocsLayoutV2 } from '~/features/DocsLayout/useDocsLayoutV2'
import { HeadingSlotCrumb } from '~/layouts/HeadingSlot'
import { RightRailPortal } from '~/layouts/RightRail'
@@ -37,6 +38,11 @@ interface GuidesSidebarProps extends GuidesRightRailProps {
className?: string
}
interface GuidePageLinksProps {
editHref?: string
className?: string
}
interface GuideTocProps {
toc: TOCItemType[]
activeUrl: string | undefined
@@ -58,15 +64,10 @@ const GuidesSidebar = ({ className, ...props }: GuidesSidebarProps) =>
const GuidesRightRail = ({ video, videoTitle, hideToc, editHref }: GuidesRightRailProps) => {
const pathname = usePathname()
const sendTelemetryEvent = useSendTelemetryEvent()
const { toc } = useTocAnchors()
const activeIndex = Math.max(TocPrimitive.useTopActiveIndex(toc), 0)
const showFeedback = isFeatureEnabled('feedback:docs')
const tocVideoPreview = `https://img.youtube.com/vi/${video}/0.jpg`
const handlePreferredSourceClick = () =>
sendTelemetryEvent({ action: 'preferred_source_clicked', properties: { pageType: 'guide' } })
return (
<RightRailPortal>
<div className="flex min-h-0 flex-1 flex-col gap-8 px-6 pt-6">
@@ -83,51 +84,66 @@ const GuidesRightRail = ({ video, videoTitle, hideToc, editHref }: GuidesRightRa
<GuideToc toc={toc} activeUrl={toc[activeIndex]?.url} />
)}
</div>
<LayoutSwitchButton className="mx-3 mb-3 shrink-0 pl-2.5" />
<footer className="shrink-0 border-t py-2 pl-6 pr-4">
<ul className="flex flex-col">
{showFeedback ? (
<li className="-ml-2.5 flex h-8 items-center">
<Feedback key={pathname} variant="rail" className="w-full" />
</li>
) : null}
<li>
<a
href={PREFERRED_SOURCE_URL}
target="_blank"
rel="noreferrer noopener"
onClick={handlePreferredSourceClick}
className="group -mr-0.5 -ml-2.5 flex h-8 items-center gap-2 rounded-md py-2 pr-2.5 pl-2 text-sm text-foreground-light hover:text-foreground focus-inset focus-visible:text-foreground"
>
<Google
aria-hidden
className="size-4 text-foreground-lighter group-hover:text-foreground group-focus-visible:text-foreground"
/>
Prefer on Google
</a>
</li>
{editHref ? (
<li>
<a
href={editHref}
target="_blank"
rel="noreferrer noopener edit"
className="group -mr-0.5 -ml-2.5 flex h-8 items-center gap-2 rounded-md py-2 pr-2.5 pl-2 text-sm text-foreground-light hover:text-foreground focus-inset focus-visible:text-foreground"
>
<IconGitHubSolid
aria-hidden
className="size-4 text-foreground-lighter group-hover:text-foreground group-focus-visible:text-foreground"
/>
Edit this page
</a>
</li>
) : null}
</ul>
<GuidePageLinks editHref={editHref} />
</footer>
<HeadingSlotCrumb key={pathname} heading={toc[activeIndex]} index={activeIndex} />
</RightRailPortal>
)
}
const GuidePageLinks = ({ editHref, className }: GuidePageLinksProps) => {
const pathname = usePathname()
const sendTelemetryEvent = useSendTelemetryEvent()
const showFeedback = isFeatureEnabled('feedback:docs')
const handlePreferredSourceClick = () =>
sendTelemetryEvent({ action: 'preferred_source_clicked', properties: { pageType: 'guide' } })
return (
<ul className={cn('flex flex-col', className)}>
{showFeedback ? (
<li className="-ml-2.5 flex h-8 items-center">
<Feedback key={pathname} variant="rail" className="w-full" />
</li>
) : null}
<li>
<a
href={PREFERRED_SOURCE_URL}
target="_blank"
rel="noreferrer noopener"
onClick={handlePreferredSourceClick}
className="group -mr-0.5 -ml-2.5 flex h-8 items-center gap-2 rounded-md py-2 pr-2.5 pl-2 text-sm text-foreground-light hover:text-foreground focus-inset focus-visible:text-foreground"
>
<Google
aria-hidden
className="size-4 text-foreground-lighter group-hover:text-foreground group-focus-visible:text-foreground"
/>
Prefer on Google
</a>
</li>
{editHref ? (
<li>
<a
href={editHref}
target="_blank"
rel="noreferrer noopener edit"
className="group -mr-0.5 -ml-2.5 flex h-8 items-center gap-2 rounded-md py-2 pr-2.5 pl-2 text-sm text-foreground-light hover:text-foreground focus-inset focus-visible:text-foreground"
>
<IconGitHubSolid
aria-hidden
size={16}
className="text-foreground-lighter group-hover:text-foreground group-focus-visible:text-foreground"
/>
Edit this page
</a>
</li>
) : null}
</ul>
)
}
const GuideToc = ({ toc, activeUrl }: GuideTocProps) => (
<nav aria-label="On this page" className="flex min-h-0 flex-1 flex-col">
<TOCScrollArea className="-ms-2 -me-4 pe-4">
@@ -165,5 +181,5 @@ const GuideTocLink = ({ item, isActive, hasActiveBar = false, className }: Guide
</TocPrimitive.TOCItem>
)
export { GuidesSidebar, GuideToc }
export { GuidePageLinks, GuidesSidebar, GuideToc }
export type { TOCHeader }
@@ -0,0 +1,100 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { useIaNavVariant } from '~/features/IaNav/useIaNavVariant'
import { LOCAL_STORAGE_KEYS } from 'common/constants/local-storage'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { LayoutSwitchButton } from './LayoutSwitchButton'
const { sendTelemetryEvent, insert } = vi.hoisted(() => ({
sendTelemetryEvent: vi.fn(),
insert: vi.fn((_row: unknown) => ({ abortSignal: async () => ({ error: null }) })),
}))
vi.mock('~/features/IaNav/useIaNavVariant', () => ({ useIaNavVariant: vi.fn() }))
vi.mock('~/features/IaNav/useIaNavReady', () => ({ useIaNavReady: () => true }))
vi.mock('~/features/IaNav/IaNavRouteProvider', () => ({
useIaNavRouteVariant: () => null,
useDocsPathname: () => '/guides/database/prisma',
}))
vi.mock('~/lib/telemetry', () => ({ useSendTelemetryEvent: () => sendTelemetryEvent }))
vi.mock('~/lib/constants', () => ({ IS_PLATFORM: true }))
vi.mock('~/lib/supabase', () => ({ supabase: () => ({ from: () => ({ insert }) }) }))
vi.mock('next/navigation', () => ({ usePathname: () => '/guides/database/prisma' }))
vi.mock('common', () => ({ useFeatureFlags: () => ({ posthog: { 'docs-ia-mvp-v1': 'control' } }) }))
const readLayoutChoice = () => localStorage.getItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE)
beforeEach(() => {
vi.mocked(useIaNavVariant).mockReturnValue('option-1')
})
afterEach(() => {
cleanup()
localStorage.clear()
vi.clearAllMocks()
})
it('asks for a reason before it switches back to classic', () => {
render(<LayoutSwitchButton />)
expect(screen.queryByRole('dialog')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Switch to classic layout' }))
expect(screen.getByRole('dialog')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(screen.queryByRole('dialog')).toBeNull()
expect(readLayoutChoice()).toBeNull()
})
it('switches to the new layout in one click and records the switch', () => {
vi.mocked(useIaNavVariant).mockReturnValue('control')
render(<LayoutSwitchButton />)
fireEvent.click(screen.getByRole('button', { name: 'Switch to new layout' }))
expect(readLayoutChoice()).toBe('option-1')
expect(sendTelemetryEvent).toHaveBeenCalledWith({
action: 'docs_layout_updated',
properties: { layoutVariant: 'option-1', assignedVariant: 'control' },
})
})
it('stores the reason as a layout switch comment, then switches to classic', async () => {
render(<LayoutSwitchButton />)
fireEvent.click(screen.getByRole('button', { name: 'Switch to classic layout' }))
const dialog = screen.getByRole('dialog')
fireEvent.change(within(dialog).getByRole('textbox'), {
target: { value: 'I miss the product list' },
})
fireEvent.click(within(dialog).getByRole('button', { name: 'Switch to classic layout' }))
await waitFor(() => expect(readLayoutChoice()).toBe('control'))
expect(insert.mock.calls[0]?.[0]).toMatchObject({
comment: 'I miss the product list',
metadata: { source: 'docs_layout_switch' },
})
expect(screen.queryByRole('dialog')).toBeNull()
})
it('switches to classic without a stored row when the reason is empty', async () => {
render(<LayoutSwitchButton />)
fireEvent.click(screen.getByRole('button', { name: 'Switch to classic layout' }))
const dialog = screen.getByRole('dialog')
fireEvent.click(within(dialog).getByRole('button', { name: 'Switch to classic layout' }))
await waitFor(() => expect(readLayoutChoice()).toBe('control'))
expect(insert).not.toHaveBeenCalled()
})
it('returns keyboard focus to the switch button when the dialog closes', async () => {
render(<LayoutSwitchButton />)
const button = screen.getByRole('button', { name: 'Switch to classic layout' })
fireEvent.click(button)
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(document.activeElement).toBe(button))
})
@@ -0,0 +1,99 @@
'use client'
import { IA_NAV_FLAG, isIaNavVariant, type IaNavVariant } from '~/features/IaNav/constants'
import { useDocsPathname, useIaNavRouteVariant } from '~/features/IaNav/IaNavRouteProvider'
import { setLayoutChoice } from '~/features/IaNav/layoutChoice'
import { useIaNavReady } from '~/features/IaNav/useIaNavReady'
import { useIaNavVariant } from '~/features/IaNav/useIaNavVariant'
import { BASE_PATH, IS_PLATFORM } from '~/lib/constants'
import { supabase } from '~/lib/supabase'
import { useSendTelemetryEvent } from '~/lib/telemetry'
import { useFeatureFlags } from 'common'
import { PanelsTopLeft } from 'lucide-react'
import { usePathname } from 'next/navigation'
import { useRef, useState } from 'react'
import { Button, cn } from 'ui'
import { LayoutSwitchFeedbackDialog } from './LayoutSwitchFeedbackDialog'
interface LayoutSwitchButtonProps {
className?: string
}
export const LayoutSwitchButton = ({ className }: LayoutSwitchButtonProps) => {
const variant = useIaNavVariant()
const isNavReady = useIaNavReady()
const sendTelemetryEvent = useSendTelemetryEvent()
const assignedVariant = useFeatureFlags().posthog[IA_NAV_FLAG]
const pathname = usePathname() ?? ''
const routeVariant = useIaNavRouteVariant()
const docsPathname = useDocsPathname()
const [isFeedbackOpen, setIsFeedbackOpen] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
const switchLayout = (nextVariant: IaNavVariant) => {
setLayoutChoice(nextVariant)
sendTelemetryEvent({
action: 'docs_layout_updated',
properties: {
layoutVariant: nextVariant,
...(isIaNavVariant(assignedVariant) && { assignedVariant }),
},
})
// a forced url or route keeps its variant over the choice, so only a load of the public page switches
const url = new URL(window.location.href)
const isForcedUrl = url.searchParams.has(IA_NAV_FLAG)
if (!isForcedUrl && !routeVariant) return
url.searchParams.delete(IA_NAV_FLAG)
if (routeVariant) url.pathname = `${BASE_PATH}${docsPathname}`
window.location.replace(url)
}
// a switch back asks why first, so the rollout gets a reason for each opt-out
const handleClick = () =>
variant === 'option-1' ? setIsFeedbackOpen(true) : switchLayout('option-1')
const handleFeedbackCancel = () => setIsFeedbackOpen(false)
const handleFeedbackSubmit = async (comment: string) => {
if (comment && IS_PLATFORM) {
// the vote and title columns are for page feedback, so the source lives in metadata
const { error } = await supabase()
.from('feedback_comments')
.insert({
page: pathname,
comment,
metadata: { source: 'docs_layout_switch', layoutVariant: 'control' },
})
// the reason is optional, so a hung request must not block the switch
.abortSignal(AbortSignal.timeout(5000))
if (error) console.error(error)
}
setIsFeedbackOpen(false)
switchLayout('control')
}
// the server renders control, so the button waits for the known variant
if (!isNavReady) return null
return (
<>
<Button
ref={buttonRef}
size="small"
icon={<PanelsTopLeft className="size-4!" />}
className={cn('justify-start self-stretch pl-1.5', className)}
onClick={handleClick}
>
{variant === 'option-1' ? 'Switch to classic layout' : 'Switch to new layout'}
</Button>
<LayoutSwitchFeedbackDialog
isOpen={isFeedbackOpen}
returnFocusRef={buttonRef}
onCancel={handleFeedbackCancel}
onSubmit={handleFeedbackSubmit}
/>
</>
)
}
@@ -0,0 +1,112 @@
'use client'
import { zodResolver } from '@hookform/resolvers/zod'
import { useId, type RefObject } from 'react'
import { useForm, type SubmitHandler } from 'react-hook-form'
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
Form,
FormControl,
FormField,
Textarea,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import * as z from 'zod'
interface LayoutSwitchFeedbackDialogProps {
isOpen: boolean
returnFocusRef: RefObject<HTMLButtonElement | null>
onCancel: () => void
onSubmit: (comment: string) => Promise<void>
}
const formSchema = z.object({
comment: z.string().trim(),
})
type LayoutSwitchFeedbackFields = z.infer<typeof formSchema>
const DEFAULT_VALUES: LayoutSwitchFeedbackFields = { comment: '' }
export const LayoutSwitchFeedbackDialog = ({
isOpen,
returnFocusRef,
onCancel,
onSubmit,
}: LayoutSwitchFeedbackDialogProps) => {
const form = useForm<LayoutSwitchFeedbackFields>({
defaultValues: DEFAULT_VALUES,
resolver: zodResolver(formSchema),
})
const { isSubmitting } = form.formState
const formId = useId()
const handleOpenChange = (isNextOpen: boolean) => {
if (isNextOpen || isSubmitting) return
form.reset()
onCancel()
}
const handleCancel = () => handleOpenChange(false)
// the dialog has no trigger, so radix has no element to return focus to
const handleCloseAutoFocus = (event: Event) => {
event.preventDefault()
returnFocusRef.current?.focus()
}
const handleSubmit: SubmitHandler<LayoutSwitchFeedbackFields> = ({ comment }) => onSubmit(comment)
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent onCloseAutoFocus={handleCloseAutoFocus}>
<DialogHeader>
<DialogTitle>Switch to classic layout</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
<Form {...form}>
<form id={formId} onSubmit={form.handleSubmit(handleSubmit)}>
<DialogSection>
<FormField
control={form.control}
name="comment"
render={({ field }) => (
<FormItemLayout
layout="vertical"
label="What made you switch back?"
labelOptional="Optional"
>
<FormControl>
<Textarea {...field} rows={4} className="resize-none" />
</FormControl>
</FormItemLayout>
)}
/>
</DialogSection>
</form>
</Form>
<DialogFooter>
<Button disabled={isSubmitting} onClick={handleCancel}>
Cancel
</Button>
<Button
variant="primary"
type="submit"
form={formId}
loading={isSubmitting}
disabled={isSubmitting}
>
Switch to classic layout
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+28 -1
View File
@@ -2,7 +2,7 @@
import { LOCAL_STORAGE_KEYS } from 'common/constants/local-storage'
import { afterEach, describe, expect, it } from 'vitest'
import { IA_NAV_CACHE_SCRIPT, IA_NAV_FLAG, IA_NAV_OVERRIDE_KEY } from './constants'
import { IA_NAV_CACHE_SCRIPT, IA_NAV_FLAG, IA_NAV_FLAG_OFF, IA_NAV_OVERRIDE_KEY } from './constants'
// the layout inlines this string in <head>, so the test runs it the same way the browser does
const runCacheScript = () => new Function(IA_NAV_CACHE_SCRIPT)()
@@ -57,6 +57,33 @@ describe('IA_NAV_CACHE_SCRIPT', () => {
expect(document.documentElement.dataset.iaNav).toBeUndefined()
})
it('marks the page from the picked layout over a cached control', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, 'control')
localStorage.setItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE, 'option-1')
runCacheScript()
expect(document.documentElement.dataset.iaNav).toBe('option-1')
})
it('leaves the page unmarked when the picked layout is control over a cached option-1', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, 'option-1')
localStorage.setItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE, 'control')
runCacheScript()
expect(document.documentElement.dataset.iaNav).toBeUndefined()
})
it('leaves the page unmarked when the flag is off over a picked option-1', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, IA_NAV_FLAG_OFF)
localStorage.setItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE, 'option-1')
runCacheScript()
expect(document.documentElement.dataset.iaNav).toBeUndefined()
})
it('leaves the page unmarked when the url forces control over a cached option-1', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, 'option-1')
window.history.replaceState(null, '', `/?${IA_NAV_FLAG}=control`)
+6 -2
View File
@@ -13,9 +13,13 @@ export const isIaNavVariant = (value: unknown): value is IaNavVariant =>
// A forced variant is kept for the browser session, because links don't carry the query parameter.
export const IA_NAV_OVERRIDE_KEY = 'docs-ia-mvp-v1-override'
// a disabled flag leaves the posthog response, and this cached value marks it as off
export const IA_NAV_FLAG_OFF = 'off'
// runs before paint, so a visitor on option-1 never sees the control nav the server renders.
// the url override wins over the session override, which wins over the value from the last visit
export const IA_NAV_CACHE_SCRIPT = `try{var V=${JSON.stringify(VARIANTS)};var o=new URLSearchParams(location.search).get('${IA_NAV_FLAG}');var s=V.indexOf(o)>-1?o:sessionStorage.getItem('${IA_NAV_OVERRIDE_KEY}');var v=V.indexOf(s)>-1?s:localStorage.getItem('${LOCAL_STORAGE_KEYS.IA_NAV_FLAG}');if(v==='option-1')document.documentElement.dataset.iaNav='option-1'}catch(e){}`
// the url override wins over the session override, then the layout the user picked, then the value from the last visit
// a flag that is off ignores the picked layout, so the flag stays the kill switch
export const IA_NAV_CACHE_SCRIPT = `try{var V=${JSON.stringify(VARIANTS)};var o=new URLSearchParams(location.search).get('${IA_NAV_FLAG}');var s=V.indexOf(o)>-1?o:sessionStorage.getItem('${IA_NAV_OVERRIDE_KEY}');if(V.indexOf(s)<0&&localStorage.getItem('${LOCAL_STORAGE_KEYS.IA_NAV_FLAG}')!=='${IA_NAV_FLAG_OFF}')s=localStorage.getItem('${LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE}');var v=V.indexOf(s)>-1?s:localStorage.getItem('${LOCAL_STORAGE_KEYS.IA_NAV_FLAG}');if(v==='option-1')document.documentElement.dataset.iaNav='option-1'}catch(e){}`
export const IA_NAV_PENDING_CLASS = 'in-data-[ia-nav=option-1]:invisible'
+40
View File
@@ -0,0 +1,40 @@
'use client'
import { LOCAL_STORAGE_KEYS } from 'common/constants/local-storage'
import { safeLocalStorage, safeSessionStorage } from 'common/safe-storage'
import { useSyncExternalStore } from 'react'
import { IA_NAV_OVERRIDE_KEY, isIaNavVariant, type IaNavVariant } from './constants'
const listeners = new Set<() => void>()
// blocked or full storage drops the write, so the pick stays in memory until the next load
let unsavedChoice: IaNavVariant | null = null
export const subscribeToLayoutChoice = (listener: () => void) => {
listeners.add(listener)
// a change in another tab must switch this tab too
window.addEventListener('storage', listener)
return () => {
listeners.delete(listener)
window.removeEventListener('storage', listener)
}
}
export const useLayoutChoice = (): IaNavVariant | null =>
useSyncExternalStore(
subscribeToLayoutChoice,
() => {
const stored = safeLocalStorage.getItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE)
return unsavedChoice ?? (isIaNavVariant(stored) ? stored : null)
},
() => null
)
export const setLayoutChoice = (variant: IaNavVariant): void => {
// the session override wins over the choice, so a forced link must not keep the old layout
safeSessionStorage.removeItem(IA_NAV_OVERRIDE_KEY)
safeLocalStorage.setItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE, variant)
const isSaved = safeLocalStorage.getItem(LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE) === variant
unsavedChoice = isSaved ? null : variant
listeners.forEach((listener) => listener())
}
@@ -1,11 +1,12 @@
// @vitest-environment jsdom
import { renderHook } from '@testing-library/react'
import { act, renderHook } from '@testing-library/react'
import { posthogClient, useFeatureFlags, useSearchParamsShallow } from 'common'
import { LOCAL_STORAGE_KEYS } from 'common/constants/local-storage'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { IA_NAV_FLAG, IA_NAV_OVERRIDE_KEY } from './constants'
import { IA_NAV_FLAG, IA_NAV_FLAG_OFF, IA_NAV_OVERRIDE_KEY } from './constants'
import { IaNavRouteProvider } from './IaNavRouteProvider'
import { setLayoutChoice } from './layoutChoice'
import { useIaNavVariant } from './useIaNavVariant'
vi.mock('common', () => ({
@@ -58,6 +59,7 @@ describe('useIaNavVariant', () => {
afterEach(() => {
localStorage.clear()
sessionStorage.clear()
vi.restoreAllMocks()
})
it('keeps a forced option-1 on later pages without the query param, with no exposure', () => {
@@ -163,7 +165,78 @@ describe('useIaNavVariant', () => {
const { result } = renderVariant({ otherFlags: { 'another-flag': true } })
expect(result.current).toBe('control')
expect(localStorage.getItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG)).toBe('false')
expect(localStorage.getItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG)).toBe(IA_NAV_FLAG_OFF)
})
it('ignores the picked layout once the flag is off', () => {
setLayoutChoice('option-1')
const { result } = renderVariant({ otherFlags: { 'another-flag': true } })
expect(result.current).toBe('control')
})
it('keeps the picked layout when the posthog request fails', () => {
setLayoutChoice('option-1')
const { result } = renderVariant({})
expect(result.current).toBe('option-1')
})
it('keeps the layout the user picked over the flag, with no exposure', () => {
setLayoutChoice('control')
const { result } = renderVariant({ flagValue: 'option-1' })
expect(result.current).toBe('control')
expect(captureExposure).not.toHaveBeenCalled()
})
it('switches every reader when the user picks a layout', () => {
const { result } = renderVariant({ flagValue: 'control' })
act(() => setLayoutChoice('option-1'))
expect(result.current).toBe('option-1')
})
it('lets a picked layout replace a forced session variant', () => {
sessionStorage.setItem(IA_NAV_OVERRIDE_KEY, 'option-1')
setLayoutChoice('control')
const { result } = renderVariant({ flagValue: 'option-1' })
expect(result.current).toBe('control')
})
it('drops a session override when the user picks the layout already saved', () => {
setLayoutChoice('control')
sessionStorage.setItem(IA_NAV_OVERRIDE_KEY, 'option-1')
const { result } = renderVariant({ flagValue: 'control' })
act(() => setLayoutChoice('control'))
expect(result.current).toBe('control')
})
it('applies the picked layout when storage rejects the write', () => {
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('QuotaExceededError')
})
const { result } = renderVariant({ flagValue: 'option-1' })
act(() => setLayoutChoice('control'))
expect(result.current).toBe('control')
})
it('lets the url override win over the picked layout', () => {
setLayoutChoice('control')
const { result } = renderVariant({ flagValue: 'control', override: 'option-1' })
expect(result.current).toBe('option-1')
})
})
+31 -6
View File
@@ -7,11 +7,13 @@ import { useEffect, useSyncExternalStore } from 'react'
import {
IA_NAV_FLAG,
IA_NAV_FLAG_OFF,
IA_NAV_OVERRIDE_KEY,
isIaNavVariant as isVariant,
type IaNavVariant,
} from './constants'
import { useIaNavRouteVariant } from './IaNavRouteProvider'
import { subscribeToLayoutChoice, useLayoutChoice } from './layoutChoice'
const subscribeToNothing = () => () => {}
@@ -29,7 +31,7 @@ const readKnownFlag = () => {
}
/**
* Reads the `docs-ia-mvp-v1` PostHog experiment flag.
* Reads the `docs-ia-mvp-v1` PostHog experiment flag. A layout the user picked wins over the flag, unless the flag is off.
* While the flags load, or when the posthog request fails, it uses the value from the last visit.
* If neither is known, it returns `'control'`, the current navigation.
*/
@@ -38,9 +40,14 @@ export function useIaNavVariant(): IaNavVariant {
const { hasAccepted } = useConsentState()
const searchParams = useSearchParamsShallow()
const routeVariant = useIaNavRouteVariant()
const sessionOverride = useSyncExternalStore(subscribeToNothing, readSessionOverride, () => null)
// a layout pick clears the session override, so the override reads again on each pick
const sessionOverride = useSyncExternalStore(
subscribeToLayoutChoice,
readSessionOverride,
() => null
)
const layoutChoice = useLayoutChoice()
const urlOverride = searchParams.get(IA_NAV_FLAG)
const override = routeVariant ?? (isVariant(urlOverride) ? urlOverride : sessionOverride)
// the value known before the flags load. it is null on the server and on a first visit
const knownFlag = useSyncExternalStore(subscribeToNothing, readKnownFlag, () => null)
@@ -56,23 +63,41 @@ export function useIaNavVariant(): IaNavVariant {
// `false` means the visitor is outside the rollout, not assigned to control.
const isAssigned = isVariant(flagValue)
const flagVariant: IaNavVariant = flagValue === 'option-1' ? 'option-1' : 'control'
// a disabled flag ignores the picked layout, so the flag stays the kill switch
const isFlagOff = hasPosthogFlags ? !(IA_NAV_FLAG in posthog) : knownFlag === IA_NAV_FLAG_OFF
const override =
routeVariant ??
(isVariant(urlOverride) ? urlOverride : sessionOverride) ??
(isFlagOff ? null : layoutChoice)
// exception: the flags arrive through context, with no event to hook
useEffect(() => {
if (!hasPosthogFlags) return
// a missing key means the flag is gone, so the cache drops the old assignment
safeLocalStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, String(posthog[IA_NAV_FLAG] ?? false))
safeLocalStorage.setItem(
LOCAL_STORAGE_KEYS.IA_NAV_FLAG,
IA_NAV_FLAG in posthog ? String(posthog[IA_NAV_FLAG]) : IA_NAV_FLAG_OFF
)
}, [hasPosthogFlags, posthog])
useEffect(() => {
// the cached flag can be stale, so only the loaded flag records an exposure
if (!hasPosthogFlags || !isAssigned || routeVariant) return
// a layout the user picked is not the flag assignment, so it records no exposure
if (!hasPosthogFlags || !isAssigned || routeVariant || layoutChoice) return
// useSearchParamsShallow is empty until its own effect runs, so read the URL directly.
const urlOverride = new URLSearchParams(window.location.search).get(IA_NAV_FLAG)
if (isVariant(urlOverride) || sessionOverride) return
posthogClient.captureExperimentExposure(IA_NAV_FLAG, { variant: flagVariant }, hasAccepted)
}, [hasPosthogFlags, isAssigned, routeVariant, sessionOverride, flagVariant, hasAccepted])
}, [
hasPosthogFlags,
isAssigned,
routeVariant,
layoutChoice,
sessionOverride,
flagVariant,
hasAccepted,
])
return isVariant(override) ? override : flagVariant
}
@@ -1,5 +1,6 @@
import Breadcrumbs from '~/components/Breadcrumbs'
import { GuidesSidebar } from '~/components/GuidesSidebar'
import { GuidePageLinks, GuidesSidebar } from '~/components/GuidesSidebar'
import { LayoutSwitchButton } from '~/features/DocsLayout/LayoutSwitchButton'
import { GuideTocMenu, TocAnchorsProvider } from '~/features/docs/GuidesMdx.client'
import { MDXRemoteBase } from '~/features/docs/MdxBase'
import type { WithRequired } from '~/features/helpers.types'
@@ -170,8 +171,9 @@ const GuideTemplate = ({
<a
href={editHref}
className={cn(
'hidden md:flex layout-v2:hidden',
'relative w-fit',
'flex items-center gap-1.5',
'items-center gap-1.5',
'text-sm text-tertiary-foreground hover:text-foreground',
'transition-colors',
'after:absolute after:-inset-y-3 after:inset-x-0'
@@ -182,6 +184,10 @@ const GuideTemplate = ({
<IconGitHubSolid size={14} aria-hidden />
Edit this page
</a>
<div className="flex flex-col md:hidden layout-v2:md:flex">
<LayoutSwitchButton className="mb-3 pl-2.5 md:self-start" />
<GuidePageLinks editHref={editHref} className="border-t py-2 pl-3" />
</div>
</footer>
</article>
</div>
@@ -148,6 +148,7 @@ export const LOCAL_STORAGE_KEYS = {
SAVED_BRANCH: 'docs.ui.user.selected.branch',
IA_NAV_FLAG: 'docs-ia-mvp-v1',
DOCS_PAGE_ACTION: 'docs.ui.page-action',
DOCS_LAYOUT_CHOICE: 'docs.ui.layout-choice',
/**
* WWW
@@ -177,6 +178,7 @@ const LOCAL_STORAGE_KEYS_ALLOWLIST = [
LOCAL_STORAGE_KEYS.LAST_SIGN_IN_METHOD,
LOCAL_STORAGE_KEYS.BLOG_VIEW,
LOCAL_STORAGE_KEYS.DOCS_PAGE_ACTION,
LOCAL_STORAGE_KEYS.DOCS_LAYOUT_CHOICE,
LOCAL_STORAGE_KEYS.AI_ASSISTANT_MCP_OPT_IN,
LOCAL_STORAGE_KEYS.LINTER_SHOW_FOOTER,
LOCAL_STORAGE_KEYS.SIDEBAR_BEHAVIOR,
+23
View File
@@ -1477,6 +1477,28 @@ export interface DocsGettingStartedOptionClickedEvent {
}
}
/**
* User switched the docs layout with the layout switch button on a guide page. A switch keeps the
* layout over the docs-ia-mvp-v1 flag assignment.
*
* @group Events
* @source docs
*/
export interface DocsLayoutUpdatedEvent {
action: 'docs_layout_updated'
properties: {
/**
* Layout the user switched to. option-1 is the new layout, control is the previous layout.
*/
layoutVariant: 'control' | 'option-1'
/**
* docs-ia-mvp-v1 variant the user is assigned to. Absent when the user is outside the
* experiment or the flags have not loaded.
*/
assignedVariant?: 'control' | 'option-1'
}
}
/**
* User opened the Search V2 dialog.
*
@@ -5504,6 +5526,7 @@ export type TelemetryEvent =
| ExampleLinkClickedEvent
| DocsCodeCopiedEvent
| DocsGettingStartedOptionClickedEvent
| DocsLayoutUpdatedEvent
| DocsSearchV2OpenedEvent
| DocsSearchV2SearchSubmittedEvent
| DocsSearchV2ResultClickedEvent
+1
View File
@@ -18,6 +18,7 @@ const KEEPALIVE_ACTIONS = new Set<TelemetryEvent['action']>([
'kb_search_closed',
'agent_setup_clicked',
'view_as_markdown_clicked',
'docs_layout_updated',
])
let featureFlagProperties: Record<string, unknown> = {}