Skip to content
Closed
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
60 changes: 37 additions & 23 deletions src/components/Layout/context.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { createContext, useEffect, useMemo, useState } from 'react'
import React, { createContext, useEffect, useRef, useState } from 'react'
import menu, { docsMenu } from '../../navs'
import { IMenu } from 'components/PostLayout/types'
import { useLocation } from '@reach/router'
Expand Down Expand Up @@ -36,25 +36,15 @@ export interface IProps {
export const LayoutProvider = ({ children, ...other }: IProps) => {
const { pathname, search } = useLocation()
const { setWebsiteTheme } = useActions(layoutLogic)
const compact = typeof window !== 'undefined' && window !== window.parent
const [fullWidthContent, setFullWidthContent] = useState<boolean>(
compact || (typeof window !== 'undefined' && localStorage.getItem('full-width-content') === 'true')
)

const hedgehogModeLocalStorage = useMemo(() => {
// Only default it to be on if it's April 1st but still respect if they turned it off
const today = new Date()
const isAprilFirst = today.getMonth() === 3 && today.getDate() === 1
let hedgehogModeLocalStorage = typeof window !== 'undefined' && localStorage.getItem('hedgehog-mode-enabled')

if (isAprilFirst && typeof hedgehogModeLocalStorage !== 'string') {
hedgehogModeLocalStorage = 'true'
}

return hedgehogModeLocalStorage
}, [])

const [hedgehogModeEnabled, _setHedgehogModeEnabled] = useState<boolean>(hedgehogModeLocalStorage === 'true')
// `mounted` is false during SSR and the first client render. We gate browser-only reads
// (iframe detection, localStorage) on it so the first client render matches the
// server-rendered HTML and we don't trigger hydration mismatches (React error #418).
const [mounted, setMounted] = useState(false)
const isInIframe = typeof window !== 'undefined' && window !== window.parent
const compact = mounted && isInIframe
const [fullWidthContent, setFullWidthContent] = useState<boolean>(false)
const [hedgehogModeEnabled, _setHedgehogModeEnabled] = useState<boolean>(false)
const fullWidthContentInitialized = useRef(false)
const [enterpriseMode, setEnterpriseMode] = useState(false)
const [theoMode, setTheoMode] = useState(false)
const [post, setPost] = useState<boolean>(false)
Expand All @@ -74,7 +64,29 @@ export const LayoutProvider = ({ children, ...other }: IProps) => {
return currentURL === menuItem.url?.split('?')[0] || recursiveSearch(menuItem.children, currentURL)
})

// Read the real (browser-only) initial values after mount. Kept out of the useState
// initializers above so the first client render matches SSR (avoids React #418).
useEffect(() => {
setMounted(true)

setFullWidthContent(isInIframe || localStorage.getItem('full-width-content') === 'true')

// Only default hedgehog mode on if it's April 1st, but still respect an explicit opt-out
const today = new Date()
const isAprilFirst = today.getMonth() === 3 && today.getDate() === 1
const storedHedgehogMode = localStorage.getItem('hedgehog-mode-enabled')
_setHedgehogModeEnabled(
storedHedgehogMode === 'true' || (isAprilFirst && typeof storedHedgehogMode !== 'string')
)
}, [])

useEffect(() => {
// Skip the first run so we don't overwrite the stored value before the mount effect
// above has loaded it.
if (!fullWidthContentInitialized.current) {
fullWidthContentInitialized.current = true
return
}
localStorage.setItem('full-width-content', fullWidthContent + '')
}, [fullWidthContent])

Expand All @@ -84,7 +96,9 @@ export const LayoutProvider = ({ children, ...other }: IProps) => {
}

useEffect(() => {
if (compact) {
// Read iframe state directly rather than the render-gated `compact`, which is
// intentionally `false` on the first render (pre-mount) for hydration.
if (isInIframe) {
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration - intentional for docs embedding, parent origin unknown, non-sensitive navigation data
window.parent.postMessage(
{
Expand All @@ -97,7 +111,7 @@ export const LayoutProvider = ({ children, ...other }: IProps) => {
}, [pathname])

useEffect(() => {
if (compact) {
if (isInIframe) {
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration - intentional for docs embedding, parent origin unknown, non-sensitive menu data
window.parent.postMessage(
{
Expand All @@ -116,7 +130,7 @@ export const LayoutProvider = ({ children, ...other }: IProps) => {
setWebsiteTheme(window.__theme)
}
}
if (compact) {
if (isInIframe) {
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration - intentional for docs embedding, parent origin unknown, non-sensitive ready signal
window.parent.postMessage(
{
Expand Down
21 changes: 13 additions & 8 deletions src/components/ReaderView/context/ReaderViewContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,28 @@ export function ReaderViewProvider({ children }: { children: React.ReactNode })
const { appWindow } = useWindow()
// @2xl breakpoint for sidebar visibility (equivalent to @2xl/app-reader used in CSS)
const isWideEnoughForSidebar = appWindow?.size?.width && appWindow?.size?.width >= 672 // 42rem = 672px
const [isNavVisible, setIsNavVisible] = useState(isWideEnoughForSidebar)
// Nav/ToC visibility and the saved background depend on the window size and
// localStorage, neither of which is available during SSR. Initialize to the
// SSR-equivalent values (hidden / no background) and reconcile after mount via the
// effects below, so the first client render matches the server (avoids React #418).
const [isNavVisible, setIsNavVisible] = useState(false)
const [navUserToggled, setNavUserToggled] = useState(false)
// @6xl breakpoint is 72rem = 1152px
const isLarge = appWindow?.size?.width && appWindow?.size?.width >= 1152
const [isTocVisible, setIsTocVisible] = useState(isLarge)
const [isTocVisible, setIsTocVisible] = useState(false)
const [tocUserToggled, setTocUserToggled] = useState(false)
const [fullWidthContent, setFullWidthContent] = useState(false)
const [lineHeightMultiplier, setLineHeightMultiplier] = useState<number>(1)
const [lineHeightP, setLineHeightP] = useState<number | null>(null)
const [lineHeightLi, setLineHeightLi] = useState<number | null>(null)
const [backgroundImage, setBackgroundImage] = useState<string | null>(() => {
if (typeof window !== 'undefined') {
const savedBackground = localStorage.getItem('background-image')
return savedBackground
const [backgroundImage, setBackgroundImage] = useState<string | null>(null)

useEffect(() => {
const savedBackground = localStorage.getItem('background-image')
if (savedBackground) {
setBackgroundImage(savedBackground)
}
return null
})
}, [])

const toggleNav = useCallback(() => {
setNavUserToggled(true)
Expand Down
142 changes: 101 additions & 41 deletions src/context/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1390,6 +1390,22 @@ export interface SiteSettings {

const isLabel = (item: any) => !item?.url && item?.name

// SSR-equivalent defaults. The server has no access to `window`/`localStorage`, so it
// always renders with these values. The client must use the exact same values on its
// first render (before mount) to avoid a hydration mismatch (React error #418); the real
// browser-derived settings are read in an effect after mount.
const DEFAULT_SITE_SETTINGS: SiteSettings = {
experience: 'posthog',
colorMode: 'light',
theme: 'light',
skinMode: 'modern',
cursor: 'default',
wallpaper: 'keyboard-garden',
clickBehavior: 'double',
performanceBoost: false,
screensaverDisabled: true,
}

const getInitialSiteSettings = (isMobile: boolean, compact: boolean) => {
const lastReset = typeof window !== 'undefined' ? localStorage.getItem('lastReset') : null
const siteSettings = {
Expand Down Expand Up @@ -1419,11 +1435,16 @@ const getInitialSiteSettings = (isMobile: boolean, compact: boolean) => {

export const Provider = ({ children, element, location }: AppProviderProps) => {
const isSSR = typeof window === 'undefined'
const compact = typeof window !== 'undefined' && window !== window.parent
// `mounted` is false during SSR and the first client render, then flips to true in an
// effect after mount. We gate browser-only reads (window size, iframe detection,
// localStorage, feature flags) on it so the first client render matches the
// server-rendered HTML, avoiding hydration mismatches (React error #418).
const [mounted, setMounted] = useState(false)
const compact = mounted && typeof window !== 'undefined' && window !== window.parent
const constraintsRef = useRef<HTMLDivElement>(null)
const taskbarRef = useRef<HTMLDivElement>(null)
const [isMobile, setIsMobile] = useState(!isSSR && window.innerWidth < 768)
const [siteSettings, setSiteSettings] = useState<SiteSettings>(getInitialSiteSettings(isMobile, compact))
const [isMobile, setIsMobile] = useState(false)
const [siteSettings, setSiteSettings] = useState<SiteSettings>(DEFAULT_SITE_SETTINGS)
const websiteMode = siteSettings.experience === 'boring'
const [taskbarHeight, setTaskbarHeight] = useState(38)
const [lastClickedElementRect, setLastClickedElementRect] = useState<{ x: number; y: number } | null>(null)
Expand All @@ -1436,11 +1457,11 @@ export const Provider = ({ children, element, location }: AppProviderProps) => {
const stateWindows = element.props?.location?.state?.savedWindows
const posthog = usePostHog()

const [windows, setWindows] = useState<AppWindow[]>(
(location.key === 'initial' && location.pathname === '/' && isMobile) || !!paramsWindows
? []
: getInitialWindows(element)
)
// Always start with the SSR-equivalent single window so the first client render
// matches the server. Browser-only initial layouts (shared `?windows=` links, the
// `?contact=` two-window layout, and the empty mobile homepage) are applied after
// mount in effects below to avoid a hydration mismatch (React error #418).
const [windows, setWindows] = useState<AppWindow[]>(getInitialWindows(element))
const windowsRef = useRef(windows)
useEffect(() => {
windowsRef.current = windows
Expand Down Expand Up @@ -1720,47 +1741,53 @@ export const Provider = ({ children, element, location }: AppProviderProps) => {
return lastClickedElementRect || undefined
}

// Returns the SSR-equivalent single window. This must not read any browser-only state
// (window size, query string) so the first client render matches the server. The
// `?contact=` two-window layout is applied after mount in the post-mount effect below.
function getInitialWindows(element: any) {
if (isSSR) return [createNewWindow(element, [], location, isSSR, taskbarHeight)]
const urlObj = new URL(location.href)
const contact = urlObj.searchParams.get('contact')
if (contact) {
const initialWindowSize = { width: window.innerWidth * 0.58, height: window.innerHeight * 0.8 }
const formWindowWidth = window.innerWidth * 0.4
const formWindowSize = {
width: formWindowWidth,
height: formWindowWidth <= 545 ? 732 : 568,
}
const padding = [65, 20]
return [createNewWindow(element, [], location, isSSR, taskbarHeight)]
}

const initialWindow = createNewWindow(element, [], location, isSSR, taskbarHeight, {
size: initialWindowSize,
position: { x: padding[0], y: padding[1] },
zIndex: 2,
})
const formWindow = createNewWindow(
<ContactSales location={{ pathname: `/talk-to-a-human` }} key="/talk-to-a-human" />,
[],
{ pathname: `talk-to-a-human` },
isSSR,
taskbarHeight,
{
size: formWindowSize,
position: {
x: window.innerWidth - formWindowSize.width - padding[0],
y: window.innerHeight - formWindowSize.height - padding[1] - taskbarHeight,
},
zIndex: 0,
}
)
return [initialWindow, formWindow]
// Builds the two-window `?contact=` layout (page + contact form). Runs only on the
// client, after mount.
function getContactWindows(element: any) {
const initialWindowSize = { width: window.innerWidth * 0.58, height: window.innerHeight * 0.8 }
const formWindowWidth = window.innerWidth * 0.4
const formWindowSize = {
width: formWindowWidth,
height: formWindowWidth <= 545 ? 732 : 568,
}
return [createNewWindow(element, [], location, isSSR, taskbarHeight)]
const padding = [65, 20]

const initialWindow = createNewWindow(element, [], location, isSSR, taskbarHeight, {
size: initialWindowSize,
position: { x: padding[0], y: padding[1] },
zIndex: 2,
})
const formWindow = createNewWindow(
<ContactSales location={{ pathname: `/talk-to-a-human` }} key="/talk-to-a-human" />,
[],
{ pathname: `talk-to-a-human` },
isSSR,
taskbarHeight,
{
size: formWindowSize,
position: {
x: window.innerWidth - formWindowSize.width - padding[0],
y: window.innerHeight - formWindowSize.height - padding[1] - taskbarHeight,
},
zIndex: 0,
}
)
return [initialWindow, formWindow]
}

function getKey(key: string) {
const experiment = appSettings[key]?.experiment
if (!experiment?.flag) return key
// Don't branch on feature flags until after mount — flags may be bootstrapped
// synchronously on the client and would otherwise diverge from SSR (error #418).
if (!mounted) return key
const assignedVariant = posthog?.getFeatureFlag?.(experiment?.flag)
if (!assignedVariant) return key
const keyToUse = Object.keys(appSettings).find(
Expand Down Expand Up @@ -2064,6 +2091,32 @@ export const Provider = ({ children, element, location }: AppProviderProps) => {
}
}

// After mount, switch from SSR-equivalent defaults to the real browser-derived state.
// Reading these here (rather than in the useState initializers) keeps the first client
// render identical to the server and avoids hydration mismatches (React error #418).
useEffect(() => {
setMounted(true)

const clientCompact = typeof window !== 'undefined' && window !== window.parent
const clientIsMobile = window.innerWidth < 768
setSiteSettings(getInitialSiteSettings(clientIsMobile, clientCompact))

// Apply the browser-only initial window layout that was deferred from the
// `windows` useState initializer.
if (paramsWindows) {
// Shared `?windows=` links are reconstructed by the dedicated effect below.
return
}
if (location.key === 'initial' && location.pathname === '/' && clientIsMobile) {
setWindows([])
return
}
const contact = new URL(location.href).searchParams.get('contact')
if (contact) {
setWindows(getContactWindows(element))
}
}, [])

useEffect(() => {
if (
(location.key === 'initial' && location.pathname === '/' && isMobile) ||
Expand Down Expand Up @@ -2351,6 +2404,8 @@ export const Provider = ({ children, element, location }: AppProviderProps) => {
setIsMobile(typeof window !== 'undefined' && window.innerWidth < 768)
}

// Set the real value on mount (initial state is `false` to match SSR).
handleResize()
window.addEventListener('resize', handleResize)

return () => window.removeEventListener('resize', handleResize)
Expand Down Expand Up @@ -2387,6 +2442,9 @@ export const Provider = ({ children, element, location }: AppProviderProps) => {
}, [websiteMode, taskbarHeight, isSSR])

useEffect(() => {
// Read iframe state directly here rather than the render-gated `compact` value,
// which is intentionally `false` on the first render (pre-mount) for hydration.
const compact = typeof window !== 'undefined' && window !== window.parent
if (compact) {
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration - intentional for docs embedding, parent origin unknown, non-sensitive ready signal
window.parent.postMessage(
Expand Down Expand Up @@ -2425,6 +2483,8 @@ export const Provider = ({ children, element, location }: AppProviderProps) => {
}, [])

useEffect(() => {
// Read iframe state directly (see note on the docs-ready effect above).
const compact = typeof window !== 'undefined' && window !== window.parent
if (compact) {
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration - intentional for docs embedding, parent origin unknown, non-sensitive navigation data
window.parent.postMessage(
Expand Down
11 changes: 10 additions & 1 deletion src/pages/product-toolkit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,13 @@ export default function ProductToolkit() {
const { appWindow } = useWindow()
const { setWindowTitle } = useApp()
const posthog = usePostHog()
// Don't branch the CTA URL on a feature flag until after mount — flags can be
// bootstrapped synchronously and would otherwise diverge from SSR (React error #418).
const [mounted, setMounted] = useState(false)

useEffect(() => {
setMounted(true)
}, [])

useEffect(() => {
if (appWindow) {
Expand All @@ -370,7 +377,9 @@ export default function ProductToolkit() {
mdxBody={mdxBody}
cta={{
url: `https://${
posthog?.isFeatureEnabled && posthog.isFeatureEnabled('direct-to-eu-cloud') ? 'eu' : 'app'
mounted && posthog?.isFeatureEnabled && posthog.isFeatureEnabled('direct-to-eu-cloud')
? 'eu'
: 'app'
}.posthog.com/signup`,
label: 'Get started - free',
}}
Expand Down
Loading