:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(heatmaps): page history strip (#117200)
Jordan Mryyan3e6ed85983af
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 286b465bc4dd..4c7b631f29f4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10966,6 +10966,14 @@ snapshots:hash: v1.k794b7964.9d4260c0f995e7dab1dce843dea2bb4d65cde7985de37c3d9c22bc1076e99222.0K0DVWC3ZQ2Azz6yFsqNOS-6TDOAzN1irTWpegrFNksscenes-app-heatmap--generating--light:hash: v1.k794b7964.3bb8caf591d48254690d88d7fd91f56d37f174fd436856e05068fc48b6447c8c.sj0fwc61KHPb3o_hlXH-J5n47Aa8TVTmCRmQvWWcaDM+ scenes-app-heatmap--historical-day--dark:+ hash: v1.k794b7964.2e4ffd7d5626936008038af691026115e73084a3b60fc1566b7b3b853c951c22.J5o3V5sje7hrWnHfIxFv8CZ-js6Gmm59OjPIGRDvdDQ+ scenes-app-heatmap--historical-day--light:+ hash: v1.k794b7964.50014e66961df3b9b4ff6ae15fb699dce99914b489144448ecce5c20c2cad474.imke0qNh5hu3gsKYEfmjLnOHqnzP5FJ_8mF1eFBPYq8+ scenes-app-heatmap--historical-day-narrow--dark:+ hash: v1.k794b7964.975049d7b4e3f60a43f8bf05ff6156372e84bc02ed4220d435aeddd6bd9710ea.OJF7JsONehAysRwV14mVAZjQmVP2Fu3V5DZ6GDtM2pI+ scenes-app-heatmap--historical-day-narrow--light:+ hash: v1.k794b7964.6b2487ec31c787c26982f8860229a20d407d5b4313aa8f11da9a7afdca7bf9e8.g-rTb-3eQKxQayKSRoAgci6m9YYHwPCNT_Tz_whTHi0scenes-app-heatmap--iframe-example--dark:hash: v1.k794b7964.edc8641f41da1365aaa55e532b36b6fe272234b86f6ce1ef317d0d3d586eac79.kgs_gmdNN7IN2c8RZPsQrShFeZ8ChwmTy0atI73o1wsscenes-app-heatmap--iframe-example--light:@@ -10978,6 +10986,10 @@ snapshots:hash: v1.k794b7964.cfd075c10189496c867372e36391cf5985948fe5a8137c434545f5825b15ac7e.IUvQTi7vHNPSGeWj-q6upJsHMLU3UpumxHwGBndOhYEscenes-app-heatmap--new--light:hash: v1.k794b7964.ec5a5410104285363cbd9367af0620e4e9674399712a898f32cc400fa7a993e7.I9v4DCi_Vj_NoXXOcFYninqMnCS3vrIk9uN6cBPEBtk+ scenes-app-heatmap--page-history--dark:+ hash: v1.k794b7964.f76d7aa4688924fb38b129a7ef371bf056f45dfa662823cd394a5e29f2039015.V5cgLSSLk_vGCvcoN7TPnKbbn-VYRno8f0AefSYbqJg+ scenes-app-heatmap--page-history--light:+ hash: v1.k794b7964.aa5526deff5fbfd96d91993227dd123a7fb6edcb2b3702f5b0e2ea0295969de2.xZfKHj2RTpsL-AJZ5bmN9iTqdigEP94NtDKmIwRLUUIscenes-app-heatmap--page-settings-dialog--dark:hash: v1.k794b7964.4ec34661c29e460870e68fb4e5c372b3df3dd26c62289881c2636aa9018e8fb7.wA3prs5fChc4NeAfoN2lJS1iM0HN5Wrp0s0-r9B0jzAscenes-app-heatmap--page-settings-dialog--light:diff --git a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsxindex 057d316ba715..5ecc17d88477 100644--- a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx+++ b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx@@ -74,7 +74,7 @@ export function ViewportChooser({ lockedWidth }: { lockedWidth?: number }): JSX.size="small"onChange={setWindowWidthOverride}value={lockedWidth ?? widthOverride}- disabledReason={lockedWidth ? 'Toolbar captures are saved at a single width' : undefined}+ disabledReason={lockedWidth ? 'This capture is saved at a fixed viewport width' : undefined}data-attr="viewport-chooser"options={allOptions.map(({ value, icon }) => ({value,@@ -101,10 +101,12 @@ export function FilterPanel({clickmapSettings,lockedWidth,previewUnavailable = false,+ dateControl,}: {previewUnavailable?: booleanclickmapSettings?: JSX.ElementlockedWidth?: number+ dateControl?: JSX.Element}): JSX.Element {const [isSettingsOpen, setIsSettingsOpen] = useState(false)const [isEventFilterOpen, setIsEventFilterOpen] = useState(false)@@ -141,14 +143,16 @@ export function FilterPanel({)}<div className="flex flex-wrap justify-between items-center gap-2 my-2"><div className="flex flex-wrap items-center gap-2 min-w-0">- <DateFilter- dateFrom={commonFilters?.date_from}- dateTo={commonFilters?.date_to}- onChange={(fromDate, toDate) => {- setCommonFilters?.({ ...commonFilters, date_from: fromDate, date_to: toDate })- }}- dateOptions={heatmapDateOptions}- />+ {dateControl ?? (+ <DateFilter+ dateFrom={commonFilters?.date_from}+ dateTo={commonFilters?.date_to}+ onChange={(fromDate, toDate) => {+ setCommonFilters?.({ ...commonFilters, date_from: fromDate, date_to: toDate })+ }}+ dateOptions={heatmapDateOptions}+ />+ )}{cohortFilterEnabled && (<div className="min-w-0"><PropertyFiltersdiff --git a/products/web_analytics/frontend/heatmaps/history/PageHistoryDateControls.tsx b/products/web_analytics/frontend/heatmaps/history/PageHistoryDateControls.tsxnew file mode 100644index 000000000000..d2cbfc4e474b--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/history/PageHistoryDateControls.tsx@@ -0,0 +1,62 @@+import { useActions, useValues } from 'kea'++import { IconChevronLeft, IconChevronRight } from '@posthog/icons'+import { LemonButton, LemonSelect } from '@posthog/lemon-ui'++import { isUsableCapture, pageHistoryLogic } from './pageHistoryLogic'+import { formatCaptureDay } from './pageHistoryUtils'++export function PageHistoryDateControls({ id }: { id: string }): JSX.Element {+ const logic = pageHistoryLogic({ id })+ const { captures, selectedBackground, previousCapture, nextCapture, historyBrowseDisabledReason } = useValues(logic)+ const { browseCapture, navigateCapture } = useActions(logic)++ return (+ <div className="flex flex-wrap items-center gap-1" aria-label="Historical interaction dates">+ <LemonButton+ size="small"+ icon={<IconChevronLeft />}+ onClick={() => navigateCapture('previous')}+ aria-label={+ previousCapture+ ? `Previous available capture: ${formatCaptureDay(previousCapture.captured_on, 'long')}`+ : 'Previous available capture'+ }+ disabledReason={+ historyBrowseDisabledReason ||+ (!previousCapture ? 'This is the oldest available screenshot.' : undefined)+ }+ tooltip={previousCapture ? `Inspect ${formatCaptureDay(previousCapture.captured_on)}` : undefined}+ data-attr="heatmap-page-history-previous-day"+ />+ <LemonSelect+ size="small"+ value={selectedBackground?.id}+ onSelect={browseCapture}+ aria-label="Historical interaction day"+ disabledReason={historyBrowseDisabledReason}+ options={[...captures].reverse().map((capture) => ({+ value: capture.id,+ label: `${formatCaptureDay(capture.captured_on)}${isUsableCapture(capture) ? '' : ' (no screenshot)'}`,+ }))}+ data-attr="heatmap-page-history-dates"+ />+ <LemonButton+ size="small"+ icon={<IconChevronRight />}+ onClick={() => navigateCapture('next')}+ aria-label={+ nextCapture+ ? `Next available capture: ${formatCaptureDay(nextCapture.captured_on, 'long')}`+ : 'Next available capture'+ }+ disabledReason={+ historyBrowseDisabledReason ||+ (!nextCapture ? 'This is the newest available screenshot.' : undefined)+ }+ tooltip={nextCapture ? `Inspect ${formatCaptureDay(nextCapture.captured_on)}` : undefined}+ data-attr="heatmap-page-history-next-day"+ />+ </div>+ )+}diff --git a/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsx b/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsxnew file mode 100644index 000000000000..b834c4209ad7--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsx@@ -0,0 +1,324 @@+import { useActions, useValues } from 'kea'+import { useCallback, useLayoutEffect, useRef, useState } from 'react'+import useResizeObserver from 'use-resize-observer'++import { IconChevronLeft, IconChevronRight, IconEllipsis, IconRefresh } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonCard, LemonMenu, Tooltip } from '@posthog/lemon-ui'++import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'+import { dayjs } from 'lib/dayjs'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { dateFilterToText } from 'lib/utils/dateFilters'++import { pageHistoryLogic } from './pageHistoryLogic'+import { PageHistoryTile } from './PageHistoryTile'+import { formatCaptureDay, formatCaptureTimestamp, formatHistoryDateRange } from './pageHistoryUtils'++export function PageHistoryStrip({ id }: { id: string }): JSX.Element {+ const logic = pageHistoryLogic({ id })+ const {+ history,+ historyLoading,+ historyLoadFailed,+ captures,+ usableCaptures,+ visibleCaptures,+ historyPage,+ historyPageCount,+ historyExpanded,+ selectedDateRange,+ selectedBackground,+ historyBrowseDisabledReason,+ missingCaptureDate,+ missingDateAlternatives,+ navigationNotice,+ } = useValues(logic)+ const { browseCapture, clearSelection, loadHistory, setHistoryPage, setHistoryExpanded, setMissingCaptureDate } =+ useActions(logic)+ const { effectiveCommonFilters } = useValues(heatmapDataLogic({ context: 'in-app' }))+ const contextRef = useRef<HTMLElement | null>(null)+ const [browserMaxHeight, setBrowserMaxHeight] = useState(640)+ const measureBrowserSpace = useCallback((): void => {+ const top = contextRef.current?.getBoundingClientRect().top+ if (top !== undefined) {+ setBrowserMaxHeight(Math.max(280, window.innerHeight - Math.max(0, top) - 16))+ }+ }, [])+ const { ref: observeContext } = useResizeObserver<HTMLElement>({ onResize: measureBrowserSpace })+ const setContextRef = useCallback(+ (node: HTMLElement | null): void => {+ contextRef.current = node+ observeContext(node)+ },+ [observeContext]+ )+ useLayoutEffect(() => {+ if (!historyExpanded) {+ return+ }+ measureBrowserSpace()+ window.addEventListener('resize', measureBrowserSpace)+ return () => window.removeEventListener('resize', measureBrowserSpace)+ }, [measureBrowserSpace, historyExpanded])+ const browseRef = useRef<HTMLButtonElement | null>(null)+ const focusCloseButton = useCallback((node: HTMLButtonElement | null): void => {+ node?.focus({ preventScroll: true })+ }, [])+ const closeBrowser = (): void => {+ setHistoryExpanded(false)+ browseRef.current?.focus({ preventScroll: true })+ }++ return (+ <section+ ref={setContextRef}+ className="@container/history p-3 border-b"+ aria-label="Page history"+ data-attr="heatmap-page-history"+ onKeyDown={(event) => {+ if (event.key === 'Escape' && historyExpanded) {+ event.preventDefault()+ closeBrowser()+ }+ }}+ >+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="min-w-0">+ <div+ className="text-sm font-semibold"+ aria-live="polite"+ data-attr="heatmap-page-history-selection"+ >+ <span>+ {selectedDateRange+ ? `Interactions: ${formatHistoryDateRange(selectedDateRange)}`+ : `Interactions: ${dateFilterToText(effectiveCommonFilters?.date_from, effectiveCommonFilters?.date_to, 'Current date filters')}`}+ </span>+ {selectedBackground ? (+ <span className="sr-only">{`. Screenshot captured ${formatCaptureTimestamp(selectedBackground)}.`}</span>+ ) : null}+ </div>+ <div className="text-xs text-muted mt-1">+ <Tooltip+ title={+ selectedBackground+ ? 'Daily screenshots show the page at capture time. They may not reflect later changes or personalized versions.'+ : 'This saved screenshot may differ from the pages seen during your interaction dates. Browse screenshots to inspect a past day.'+ }+ >+ <span className="cursor-help border-b border-dashed">+ {selectedBackground+ ? `Screenshot captured ${formatCaptureTimestamp(selectedBackground)} · ${selectedBackground.width}px`+ : 'Current saved screenshot'}+ </span>+ </Tooltip>+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-1">+ <LemonButton+ ref={browseRef}+ size="small"+ type="secondary"+ onClick={() => {+ if (historyExpanded) {+ closeBrowser()+ } else {+ setHistoryExpanded(true)+ }+ }}+ aria-expanded={historyExpanded}+ aria-controls="heatmap-history-browser"+ disabledReason={historyBrowseDisabledReason}+ data-attr="heatmap-page-history-toggle"+ >+ Browse screenshots+ </LemonButton>+ {selectedDateRange ? (+ <LemonButton+ size="small"+ type="secondary"+ onClick={clearSelection}+ data-attr="heatmap-page-history-current"+ aria-label="Current view"+ tooltip="Restore your current screenshot, date filters, and screen width"+ >+ Current view+ </LemonButton>+ ) : null}+ {captures.length > 0 ? (+ <LemonMenu+ items={[+ {+ label: 'Refresh screenshots',+ icon: <IconRefresh />,+ onClick: () => loadHistory(),+ disabledReason: historyLoading ? 'Refreshing screenshots' : undefined,+ 'data-attr': 'heatmap-page-history-refresh',+ },+ ]}+ >+ <LemonButton+ size="small"+ icon={<IconEllipsis />}+ aria-label="Screenshot actions"+ data-attr="heatmap-page-history-actions"+ />+ </LemonMenu>+ ) : null}+ </div>+ </div>+ {historyLoadFailed ? (+ <LemonBanner+ type="error"+ className="mt-2"+ action={{+ children: 'Try again',+ onClick: () => loadHistory(),+ loading: historyLoading,+ 'data-attr': 'heatmap-page-history-retry',+ }}+ >+ {history+ ? "Couldn't refresh screenshots. The available captures may be out of date."+ : "Couldn't load page history. Try again."}+ </LemonBanner>+ ) : null}+ <div role="status" aria-live="polite">+ {navigationNotice ? <p className="text-xs text-muted mt-2 mb-0">{navigationNotice}</p> : null}+ </div>+ {missingCaptureDate ? (+ <LemonBanner type="info" className="mt-2" onClose={() => setMissingCaptureDate(null)}>+ <p className="mb-1">+ <span>{`No screenshot was saved for ${formatCaptureDay(missingCaptureDate)}. ${selectedBackground ? `Still viewing the ${dayjs(selectedBackground.captured_on).format('MMM D')} screenshot and its interaction day.` : 'Your current view is unchanged.'}`}</span>+ </p>+ <p className="text-xs mb-2">A missing screenshot does not indicate whether interactions exist.</p>+ <div className="flex flex-wrap gap-2">+ {missingDateAlternatives.map((capture) => (+ <LemonButton+ key={capture.id}+ size="small"+ type="secondary"+ onClick={() => browseCapture(capture.id)}+ >+ <span>{`Inspect ${formatCaptureDay(capture.captured_on)}`}</span>+ </LemonButton>+ ))}+ </div>+ </LemonBanner>+ ) : null}+ {historyBrowseDisabledReason ? (+ <LemonBanner type="info" className="mt-2">+ {historyBrowseDisabledReason}+ </LemonBanner>+ ) : null}+ {!history && !historyLoadFailed ? (+ <LemonSkeleton className="h-8 mt-2" />+ ) : history && captures.length === 0 ? (+ <div className="mt-3" data-attr="heatmap-page-history-empty">+ <p className="text-sm mb-2">+ {history.storage_available+ ? "Automatic captures build history for recently viewed pages. Earlier page designs can't be recovered."+ : 'Screenshot storage is unavailable on this installation. Ask your administrator to configure it.'}+ </p>+ <p className="text-xs text-muted mb-0 mt-2">+ <span>{`Saved screenshots are kept for ${history.retention_days} days. Some days may be missing.`}</span>+ </p>+ </div>+ ) : null}+ {selectedDateRange ? (+ <p className="text-xs text-muted mt-2 mb-0">+ This history view is temporary. The heatmap link opens the current view; historical export is+ unavailable.+ </p>+ ) : null}+ {historyExpanded ? (+ <div+ className="absolute top-0 inset-x-3 h-full pointer-events-none z-20"+ style={{ maxHeight: browserMaxHeight }}+ >+ <div+ className="absolute bottom-3 inset-x-0 max-w-lg ml-auto pointer-events-auto"+ id="heatmap-history-browser"+ role="dialog"+ aria-labelledby="heatmap-history-browser-title"+ >+ <LemonCard hoverEffect={false} className="p-3 shadow-lg">+ <div className="flex justify-between items-center gap-2">+ <h3 id="heatmap-history-browser-title" className="text-sm mb-0">+ Browse screenshots+ </h3>+ <LemonButton+ ref={focusCloseButton}+ size="small"+ onClick={closeBrowser}+ aria-label="Close screenshot browser"+ >+ Close+ </LemonButton>+ </div>+ <p className="text-xs text-muted mt-2 mb-2">+ Choose a day to inspect its interactions and captured screenshot.+ </p>+ {visibleCaptures.length > 0 ? (+ <div className="grid grid-cols-4 gap-2" aria-label="Available screenshot dates">+ {visibleCaptures.map((capture) => (+ <PageHistoryTile+ key={capture.id}+ capture={capture}+ selected={selectedBackground?.id === capture.id}+ disabledReason={historyBrowseDisabledReason}+ onSelect={() => browseCapture(capture.id)}+ />+ ))}+ </div>+ ) : (+ <p className="text-sm">+ {historyLoadFailed+ ? "Couldn't load screenshots. Use Try again above."+ : historyLoading+ ? 'Loading screenshots…'+ : 'No screenshots are available yet.'}+ </p>+ )}+ {historyPageCount > 1 ? (+ <div className="flex justify-between gap-2 mt-2">+ <LemonButton+ size="small"+ icon={<IconChevronLeft />}+ onClick={() => setHistoryPage(historyPage + 1)}+ disabledReason={+ historyPage >= historyPageCount - 1+ ? 'These are the oldest captures.'+ : undefined+ }+ data-attr="heatmap-page-history-older"+ >+ Older+ </LemonButton>+ <LemonButton+ size="small"+ sideIcon={<IconChevronRight />}+ onClick={() => setHistoryPage(historyPage - 1)}+ disabledReason={+ historyPage === 0 ? 'These are the newest captures.' : undefined+ }+ data-attr="heatmap-page-history-newer"+ >+ Newer+ </LemonButton>+ </div>+ ) : null}+ <p className="text-xs text-muted mb-0 mt-2">+ <span>+ {usableCaptures.length+ ? `${usableCaptures.length} captured ${usableCaptures.length === 1 ? 'day' : 'days'} between ${dayjs(usableCaptures[0].captured_on).format('MMM D')} and ${formatCaptureDay(usableCaptures.at(-1)!.captured_on)}. Kept for ${history?.retention_days} days; some days may be missing.`+ : 'Earlier page designs cannot be recovered.'}+ </span>+ </p>+ </LemonCard>+ </div>+ </div>+ ) : null}+ </section>+ )+}diff --git a/products/web_analytics/frontend/heatmaps/history/PageHistoryTile.tsx b/products/web_analytics/frontend/heatmaps/history/PageHistoryTile.tsxnew file mode 100644index 000000000000..e4d196383101--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/history/PageHistoryTile.tsx@@ -0,0 +1,127 @@+import { useState } from 'react'++import { IconCamera, IconCheck, IconClock, IconWarning } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { cn } from 'lib/utils/css-classes'++import type { HeatmapScreenshotHistoryItemApi } from 'products/web_analytics/frontend/generated/api.schemas'++import { isUsableCapture } from './pageHistoryLogic'+import { formatCaptureDay, formatCaptureTime } from './pageHistoryUtils'++function describeCaptureFailure(capture: HeatmapScreenshotHistoryItemApi): string {+ const cause = capture.latest_request?.failure_cause ?? capture.failure_cause+ const pageStatus = capture.latest_request?.page_status ?? capture.page_status+ const reason =+ cause === 'page_http_status'+ ? `The page returned ${pageStatus ?? 'an error'} when we loaded it.`+ : cause === 'browserless_timeout'+ ? 'The page took too long to load.'+ : cause === 'ssrf_blocked'+ ? "This page URL can't be rendered."+ : cause === 'not_configured'+ ? "Screenshot rendering isn't set up on this installation."+ : cause === 'storage_write_failed'+ ? "The capture couldn't be stored."+ : "The latest capture couldn't be completed."+ return `${reason} ${isUsableCapture(capture) ? 'The previous capture is still available.' : 'There is no image for this day.'}`+}++export function PageHistoryTile({+ capture,+ selected,+ disabledReason,+ onSelect,+}: {+ capture: HeatmapScreenshotHistoryItemApi+ selected: boolean+ disabledReason?: string | null+ onSelect: () => void+}): JSX.Element {+ const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null)+ const pending = !!capture.latest_request && ['queued', 'running'].includes(capture.latest_request.state)+ const failed = capture.latest_request?.state === 'failed' || capture.status === 'failed'+ const usable = isUsableCapture(capture)+ const day = dayjs(capture.captured_on)+ const capturedTime = formatCaptureTime(capture)+ const status = pending+ ? usable+ ? 'Updating'+ : 'Capturing'+ : failed+ ? usable+ ? 'Previous image kept'+ : 'Failed'+ : !usable+ ? 'Unavailable'+ : selected+ ? 'Displayed'+ : (capturedTime ?? 'Captured')+ const details = pending+ ? usable+ ? 'A new capture is in progress. You can view the previous screenshot.'+ : 'A capture is in progress for this day.'+ : failed+ ? describeCaptureFailure(capture)+ : !usable+ ? 'This screenshot is unavailable. Choose another capture.'+ : `${capturedTime ? `Captured at ${capturedTime} in ${capture.timezone}. ` : ''}${capture.width}px screen width.${capture.trigger === 'manual' ? ' Requested capture.' : ''}`++ return (+ <LemonButton+ type="secondary"+ fullWidth+ noPadding+ aria-pressed={selected}+ aria-label={`Inspect ${formatCaptureDay(capture.captured_on, 'long')}${selected ? ', displayed screenshot' : ''}${failed && usable ? ', previous screenshot kept' : !usable ? ', no screenshot' : ''}`}+ disabledReason={disabledReason}+ tooltip={+ <>+ <strong>{day.format('dddd, MMMM D, YYYY')}</strong>+ <div className="mt-1">{details}</div>+ </>+ }+ onClick={onSelect}+ data-attr="heatmap-page-history-capture"+ className={cn('min-w-0 overflow-hidden rounded', selected && 'ring-2 ring-accent')}+ >+ <div className="w-full min-w-0 font-normal">+ <div className="h-16 overflow-hidden bg-surface-secondary flex items-center justify-center">+ {usable && capture.thumbnail_url && capture.thumbnail_url !== failedThumbnailUrl ? (+ <img+ src={capture.thumbnail_url}+ onError={() => setFailedThumbnailUrl(capture.thumbnail_url)}+ alt=""+ loading="lazy"+ className="w-full h-full object-cover object-top"+ />+ ) : pending ? (+ <IconClock className="text-xl text-muted" />+ ) : usable ? (+ <IconCamera className="text-xl text-muted" />+ ) : (+ <IconWarning className="text-xl text-muted" />+ )}+ </div>+ <div className="p-2 text-xs text-left">+ <div className="flex items-center justify-between gap-1">+ <span className="font-semibold truncate" translate="no">+ {day.format('MMM D')}+ </span>+ {selected ? <IconCheck className="text-accent shrink-0" /> : null}+ </div>+ <div className={cn('flex items-center gap-1 mt-1', failed ? 'text-warning' : 'text-muted')}>+ {pending ? (+ <IconClock className="shrink-0" />+ ) : failed ? (+ <IconWarning className="shrink-0" />+ ) : null}+ <span className="truncate">{status}</span>+ </div>+ </div>+ </div>+ </LemonButton>+ )+}diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.tsindex e02a40bc5b0b..3e9923c0e267 100644--- a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts@@ -273,6 +273,20 @@ describe('pageHistoryLogic', () => {expect(dataLogic.values.dateRangeOverride).toBeNull()})+ it('loads history once the page history flag turns on after mount', async () => {+ const late = pageHistoryLogic({ id: 'hm_test', teamId: 998 })+ late.mount()+ await expectLogic(late).toFinishAllListeners()+ expect(late.values.history).toBeNull()++ await expectLogic(late, () =>+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.HEATMAPS_PAGE_HISTORY]: true })+ ).toFinishAllListeners()++ expect(late.values.history).toEqual(historyResponse(captures))+ late.unmount()+ })+it('drops the previous page history when the saved page changes', async () => {featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.HEATMAPS_PAGE_HISTORY]: true })await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.tsindex dae42e56747f..ddc2c6c5c0a5 100644--- a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.ts+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.ts@@ -107,6 +107,13 @@ export interface pageHistoryLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface pageHistoryLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogicsetHistoryView: (view: HeatmapHistoryView | null) => {view: HeatmapHistoryView | null} // heatmapDataLogic@@ -231,6 +238,8 @@ export const pageHistoryLogic = kea<pageHistoryLogicType>([['setSavedSettings', 'setPageUrlDraft', 'setType', 'setDataUrl'],heatmapDataLogic({ context: 'in-app' }),['setHistoryView'],+ featureFlagLogic,+ ['setFeatureFlags'],],})),actions({@@ -416,6 +425,11 @@ export const pageHistoryLogic = kea<pageHistoryLogicType>([actions.loadHistory()}},+ setFeatureFlags: () => {+ if (values.pageHistoryEnabled && props.id !== 'new' && !values.history && !values.historyLoading) {+ actions.loadHistory()+ }+ },setPageUrlDraft: clearSelectionOnUnsavedChange,setDataUrl: clearSelectionOnUnsavedChange,setType: ({ type }) => {diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsxindex 65c1696b2452..149f0599e30c 100644--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx@@ -9,6 +9,7 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import type { MockSignature, Mocks } from '~/mocks/utils'+import { pageHistoryLogic } from '../../history/pageHistoryLogic'import { heatmapLogic } from './heatmapLogic'const generatingSaved = {@@ -382,3 +383,117 @@ export const EmptyWithSimilarUrls: Story = {),],}++const historyScreenshot = (label: string): string => {+ const newer = label.includes('Current') || Number(label.slice(-2)) >= 19+ const title = newer ? 'New collection' : 'Weekly offers'+ const textX = newer ? 540 : 90+ const circleX = newer ? 240 : 780+ return `data:image/svg+xml;utf8,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1000"><rect width="1024" height="1000" fill="white"/><text x="50" y="55" font-family="sans-serif" font-size="24" fill="#252525">MarketDemo</text><text x="780" y="55" font-family="sans-serif" font-size="16" fill="#555">Shop · Offers</text><rect x="50" y="105" width="924" height="260" rx="8" fill="${newer ? '#efdfc8' : '#e0eedc'}"/><text x="${textX}" y="185" font-family="sans-serif" font-size="38" fill="#252525">${title}</text><text x="${textX}" y="225" font-family="sans-serif" font-size="18" fill="#555">${label}</text><rect x="${textX}" y="265" width="190" height="48" rx="4" fill="${newer ? '#734821' : '#245b32'}"/><text x="${textX + 18}" y="295" font-family="sans-serif" font-size="17" fill="white">Explore collection</text><circle cx="${circleX}" cy="235" r="80" fill="${newer ? '#ae997b' : '#86a870'}"/><rect x="50" y="400" width="290" height="280" rx="8" fill="#eeeDE5"/><rect x="367" y="400" width="290" height="280" rx="8" fill="#eeeDE5"/><rect x="684" y="400" width="290" height="280" rx="8" fill="#eeeDE5"/><text x="70" y="640" font-family="sans-serif" font-size="20" fill="#252525">Seasonal favourites</text><text x="385" y="640" font-family="sans-serif" font-size="20" fill="#252525">Everyday essentials</text><text x="703" y="640" font-family="sans-serif" font-size="20" fill="#252525">Something different</text></svg>`)}`+}+const historySaved = {+ ...generatingSaved,+ id: 102,+ short_id: 'hm_history',+ name: 'Home page',+ source: 'server',+ status: 'completed',+ has_content: true,+ target_widths: [1024],+ snapshots: [{ width: 1024, has_content: true }],+}+const historyCaptures = Array.from({ length: 21 }, (_, index) => {+ const date = `2024-01-${String(index + 1).padStart(2, '0')}`+ const failed = index === 17+ return {+ id: `cap-${index + 1}`,+ captured_on: date,+ captured_at: `${date}T02:40:00Z`,+ width: 1024,+ timezone: 'UTC',+ day_start: `${date}T00:00:00Z`,+ day_end: `2024-01-${String(index + 2).padStart(2, '0')}T00:00:00Z`,+ expires_at: '2024-04-01T00:00:00Z',+ revision: `capture-${index}`,+ latest_request: null,+ thumbnail_url: failed ? null : historyScreenshot(date),+ trigger: index === 19 ? 'manual' : 'scheduled',+ status: failed ? 'failed' : 'ok',+ failure_cause: failed ? 'page_http_status' : null,+ page_status: failed ? 503 : 200,+ content_url: failed ? null : historyScreenshot(date),+ }+})+const pageHistoryDecorators = [+ mswDecorator({+ get: {+ '/api/projects/:team_id/saved': { results: [historySaved], count: 1 },+ '/api/projects/:team_id/saved/hm_history/': historySaved,+ '/api/projects/:team_id/saved/hm_history/screenshot_history/': {+ width: 1024,+ retention_days: 90,+ storage_available: true,+ results: historyCaptures,+ },+ '/api/projects/:team_id/heatmaps/': {+ results: [+ { pointer_relative_x: 0.2, pointer_target_fixed: false, pointer_y: 380, count: 64 },+ { pointer_relative_x: 0.5, pointer_target_fixed: false, pointer_y: 380, count: 41 },+ { pointer_relative_x: 0.8, pointer_target_fixed: false, pointer_y: 380, count: 27 },+ ],+ count: 3,+ next: null,+ previous: null,+ },+ },+ }),+]+export const PageHistory: Story = {+ parameters: {+ pageUrl: urls.heatmap('hm_history'),+ featureFlags: [FEATURE_FLAGS.HEATMAPS_PAGE_HISTORY],+ mockDate: '2024-01-21T12:00:00Z',+ testOptions: { waitForLoadersToDisappear: false },+ },+ decorators: pageHistoryDecorators,+ render: () => <HistoryAfterLoad />,+}++function HistoryAfterLoad({ initialCapture }: { initialCapture?: string }): JSX.Element {+ const scene = heatmapLogic({ id: 'hm_history' })+ const { savedSettings, loading } = useValues(scene)+ const historyLogic = pageHistoryLogic({ id: 'hm_history' })+ const { history } = useValues(historyLogic)+ const configured = useRef(false)+ useEffect(() => {+ if (savedSettings && !loading && !configured.current) {+ configured.current = true+ scene.actions.setScreenshotUrl(historyScreenshot('Current view'))+ }+ }, [savedSettings, loading, scene])+ const selected = useRef(false)+ useEffect(() => {+ if (history && !selected.current && initialCapture) {+ selected.current = true+ historyLogic.actions.selectCapture(initialCapture)+ }+ }, [history, historyLogic, initialCapture])+ return <App />+}++export const HistoricalDay: Story = { ...PageHistory, render: () => <HistoryAfterLoad initialCapture="cap-17" /> }+export const HistoricalDayNarrow: Story = {+ ...HistoricalDay,+ decorators: [+ ...pageHistoryDecorators,+ (Story) => (+ <Narrow>+ <Story />+ </Narrow>+ ),+ ],+ parameters: {+ ...PageHistory.parameters,+ testOptions: { waitForLoadersToDisappear: true, viewport: loadedNarrowViewport },+ },+}diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsx b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsxindex f292a5725063..e30ec50d8686 100644--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsx+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsx@@ -25,6 +25,10 @@ import { FilterPanel } from '../../components/FilterPanel'import { HeatmapHeader } from '../../components/HeatmapHeader'import { HeatmapRecordingFallback } from '../../components/HeatmapRecordingFallback'import { HeatmapsPricingNotice } from '../../components/HeatmapsPricingNotice'+import { PageHistoryDateControls } from '../../history/PageHistoryDateControls'+import { pageHistoryLogic } from '../../history/pageHistoryLogic'+import { PageHistoryStrip } from '../../history/PageHistoryStrip'+import { formatCaptureDay } from '../../history/pageHistoryUtils'import { heatmapLogic } from './heatmapLogic'const HedgehogDirector = pngHoggie(directorPng)@@ -65,8 +69,20 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {regenerateDisabledReason,switchToScreenshotDisabledReason,displayUrlIsPattern,+ source,+ heatmapId,historyView,} = useValues(logic)+ const {+ pageHistoryEnabled,+ isSelectionActive: historySelectionActive,+ selectedBackground,+ } = useValues(pageHistoryLogic(logicProps))+ const {+ clearSelection: clearHistorySelection,+ setHistoryExpanded,+ loadHistory,+ } = useActions(pageHistoryLogic(logicProps))const {setName,onIframeLoad,@@ -185,10 +201,12 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {tooltip="Export heatmap as PNG"tooltipPlacement="bottom"disabledReason={- previewType === 'screenshot' &&- (!screenshotUrl || !screenshotLoaded || generatingScreenshot)- ? 'Screenshot is not ready'- : undefined+ historySelectionActive+ ? 'Exit history to export your current view.'+ : previewType === 'screenshot' &&+ (!screenshotUrl || !screenshotLoaded || generatingScreenshot)+ ? 'Screenshot is not ready'+ : undefined}>Export@@ -198,7 +216,11 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {/><HeatmapsPricingNotice /><HeatmapHeader />- <FilterPanel lockedWidth={lockedWidth ?? undefined} previewUnavailable={previewUnavailable} />+ <FilterPanel+ lockedWidth={lockedWidth ?? undefined}+ previewUnavailable={previewUnavailable}+ dateControl={historySelectionActive ? <PageHistoryDateControls id={id} /> : undefined}+ />{isHeightCapped && (<LemonBanner type="info" className="mb-2">This heatmap is capped at {MAX_HEATMAP_HEIGHT.toLocaleString()}px tall to keep rendering fast,@@ -207,9 +229,12 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {)}<div ref={measureRef} className="w-full"><div- className="border mx-auto bg-surface-primary rounded-lg"+ className="relative border mx-auto bg-surface-primary rounded-lg"style={{ width: effectiveWidth ?? '100%' }}>+ {pageHistoryEnabled && heatmapId && previewType === 'screenshot' && source === 'server' ? (+ <PageHistoryStrip id={id} />+ ) : null}<div className="p-2 border-b text-muted-foreground gap-2 flex flex-wrap items-center"><IconBrowser />{' '}<span className="min-w-0 flex-1 truncate" title={displayUrl ?? undefined}>@@ -229,22 +254,42 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {data-attr="heatmap-preview-error"><IconBrowser className="text-3xl text-muted" />- <h3 className="mb-0">{previewRecovery.title}</h3>- <p className="text-muted max-w-lg mb-0">{previewError}</p>+ <h3 className="mb-0">+ {historySelectionActive+ ? 'Historical screenshot unavailable'+ : previewRecovery.title}+ </h3>+ <p className="text-muted max-w-lg mb-0">+ {historySelectionActive+ ? 'This screenshot may have expired or become unavailable. Choose another saved date, or return to your current view.'+ : previewError}+ </p><LemonButtontype="primary"- onClick={previewRecovery.onClick}- loading={generatingScreenshot || saving}- disabledReason={previewRecovery.disabledReason}+ onClick={+ historySelectionActive+ ? () => {+ setHistoryExpanded(true)+ loadHistory()+ }+ : previewRecovery.onClick+ }+ loading={(!historySelectionActive && generatingScreenshot) || saving}+ disabledReason={historySelectionActive ? undefined : previewRecovery.disabledReason}data-attr="heatmap-preview-recovery">- {previewRecovery.label}+ {historySelectionActive ? 'Choose another date' : previewRecovery.label}</LemonButton>+ {historySelectionActive ? (+ <LemonButton type="secondary" size="small" onClick={clearHistorySelection}>+ Current view+ </LemonButton>+ ) : null}{displayUrl && !displayUrlIsPattern && <HeatmapRecordingFallback url={displayUrl} />}</div>) : previewType === 'screenshot' ? (<div className="relative flex w-full justify-center flex-1" style={{ width: '100%' }}>- {generatingScreenshot ? (+ {generatingScreenshot && !historySelectionActive ? (<divclassName="flex-1 flex items-center justify-center min-h-96"data-attr="heatmap-generating-screenshot"@@ -278,7 +323,11 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {<imgid="heatmap-screenshot"src={screenshotUrl}- alt="Website screenshot for heatmap analysis"+ alt={+ selectedBackground+ ? `Website screenshot from ${formatCaptureDay(selectedBackground.captured_on, 'long')}`+ : 'Website screenshot for heatmap analysis'+ }style={{width: '100%',height: 'auto',