Skip to content

: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.

feat(heatmaps): page history logic (#117198)

Jordan Mryyand980905087a0
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 97be953b9e45..cc20e968e2d7 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -231,6 +231,7 @@ export const FEATURE_FLAGS = {
HEATMAPS_COHORT_FILTER: 'heatmaps-cohort-filter', // owner: #team-web-analytics
HEATMAPS_CREATION_FLOW: 'heatmaps-creation-flow', // owner: #team-web-analytics, gates the guided heatmap creation wizard at /heatmaps/new
HEATMAPS_EVENT_FILTER: 'heatmaps-event-filter', // owner: #team-web-analytics
+ HEATMAPS_PAGE_HISTORY: 'heatmaps-page-history', // owner: @jordanm-posthog #team-web-analytics, keeps a daily screenshot history per saved heatmap
HEATMAPS_PRICING_NOTICE: 'heatmaps-capture-allowlist-notice', // owner: #team-web-analytics, gates the heatmaps pricing change notice
HEATMAPS_SCREENSHOT_PREWARM: 'heatmaps-screenshot-prewarm', // owner: #team-web-analytics, pre-renders the screenshot while entering a URL in the wizard
IMPROVED_COOKIELESS_MODE: 'improved-cookieless-mode', // owner: #team-web-analytics
diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts
new file mode 100644
index 000000000000..e02a40bc5b0b
--- /dev/null
+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts
@@ -0,0 +1,346 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel } from '~/types'
+
+import * as heatmapApi from 'products/web_analytics/frontend/generated/api'
+import type {
+ HeatmapScreenshotHistoryItemApi,
+ HeatmapScreenshotHistoryResponseApi,
+ HeatmapScreenshotResponseApi,
+} from 'products/web_analytics/frontend/generated/api.schemas'
+
+import { heatmapLogic } from '../scenes/heatmap/heatmapLogic'
+import { pageHistoryLogic, selectCapturesBetween } from './pageHistoryLogic'
+
+const saved: HeatmapScreenshotResponseApi = {
+ id: 'heatmap-1',
+ short_id: 'hm_test',
+ name: 'Home page',
+ url: 'https://example.com',
+ data_url: null,
+ type: 'screenshot',
+ source: 'server',
+ status: 'completed',
+ has_content: true,
+ target_widths: [1024],
+ snapshots: [{ width: 1024, has_content: true }],
+ block_consent_modals: false,
+ created_by: {
+ id: MOCK_DEFAULT_USER.id,
+ uuid: MOCK_DEFAULT_USER.uuid,
+ email: '[email protected]',
+ hedgehog_config: null,
+ },
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ exception: null,
+ user_access_level: 'editor',
+}
+
+const capture = (
+ id: string,
+ capturedOn: string,
+ overrides: Partial<HeatmapScreenshotHistoryItemApi> = {}
+): HeatmapScreenshotHistoryItemApi => ({
+ id,
+ captured_on: capturedOn,
+ captured_at: `${capturedOn}T02:40:00Z`,
+ width: 1024,
+ timezone: 'UTC',
+ day_start: `${capturedOn}T00:00:00Z`,
+ day_end: dayjs.utc(capturedOn).add(1, 'day').format('YYYY-MM-DD[T]HH:mm:ss[Z]'),
+ expires_at: dayjs().add(30, 'day').toISOString(),
+ revision: id,
+ latest_request: null,
+ thumbnail_url: null,
+ trigger: 'scheduled',
+ status: 'ok',
+ failure_cause: null,
+ page_status: 200,
+ content_url: `/api/projects/997/saved/hm_test/screenshot_history/${id}/content/`,
+ ...overrides,
+})
+
+const historyResponse = (results: HeatmapScreenshotHistoryItemApi[]): HeatmapScreenshotHistoryResponseApi => ({
+ width: 1024,
+ retention_days: 90,
+ storage_available: true,
+ results,
+})
+
+const captures = [
+ capture('cap-3', '2024-05-03'),
+ capture('cap-2', '2024-05-02', {
+ status: 'failed',
+ failure_cause: 'browserless_timeout',
+ content_url: null,
+ revision: null,
+ }),
+ capture('cap-1', '2024-05-01'),
+]
+
+describe('pageHistoryLogic', () => {
+ describe('selectCapturesBetween', () => {
+ it.each([
+ ['a single day', 'cap-1', 'cap-1', ['cap-1']],
+ ['a range in either direction', 'cap-3', 'cap-1', ['cap-1', 'cap-3']],
+ ['a failed day on its own', 'cap-2', 'cap-2', []],
+ ['no anchor', null, null, []],
+ ['an expired endpoint', 'cap-1', 'expired', []],
+ ['a failed endpoint', 'cap-1', 'cap-2', []],
+ ])('selects %s', (_label, anchorId, extentId, expected) => {
+ expect(selectCapturesBetween(captures, anchorId, extentId).map((c) => c.id)).toEqual(expected)
+ })
+
+ it.each([{ width: 1440 }, { timezone: 'America/New_York' }])('rejects incompatible ranges %s', (difference) => {
+ const mixed = [capture('a', '2024-05-01'), capture('b', '2024-05-02', difference)]
+ expect(selectCapturesBetween(mixed, 'a', 'b').map((c) => c.id)).toEqual([])
+ })
+ })
+
+ describe('selecting history', () => {
+ let logic: ReturnType<typeof pageHistoryLogic>
+ const dataLogic = heatmapDataLogic({ context: 'in-app' })
+
+ beforeEach(async () => {
+ initKeaTests()
+ window.POSTHOG_APP_CONTEXT!.resource_access_control = {
+ ...window.POSTHOG_APP_CONTEXT!.resource_access_control!,
+ heatmap: AccessControlLevel.Editor,
+ }
+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api.savedHeatmaps, 'list').mockImplementation(
+ async () => ({ results: [saved], count: 1 }) as any
+ )
+ jest.spyOn(heatmapApi, 'savedRetrieve').mockImplementation(async () => saved)
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryRetrieve').mockImplementation(async () =>
+ historyResponse(captures)
+ )
+ router.actions.push('/heatmaps/hm_test')
+ const sceneLogic = heatmapLogic({ id: 'hm_test' })
+ sceneLogic.mount()
+ await expectLogic(sceneLogic).toFinishAllListeners()
+ dataLogic.actions.setCommonFilters({ date_from: '-7d' })
+ dataLogic.actions.setWindowWidthOverride(1440)
+ logic = pageHistoryLogic({ id: 'hm_test' })
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.loadHistory()).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ jest.restoreAllMocks()
+ })
+
+ it('scopes the overlay to the day, shows that day on its screenshot and locks the width', async () => {
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-3')).toFinishAllListeners()
+
+ expect(dataLogic.values.effectiveCommonFilters).toMatchObject({
+ date_from: '2024-05-03',
+ date_to: '2024-05-03',
+ })
+ expect(dataLogic.values.commonFilters).toEqual({ date_from: '-7d' })
+ expect(dataLogic.values.dateRangeOverride).toMatchObject({ timestamp_from: '2024-05-03T00:00:00Z' })
+ expect(dataLogic.values.widthOverride).toBe(1024)
+ expect(heatmapLogic({ id: 'hm_test' }).values.lockedWidth).toBe(1024)
+ const scene = heatmapLogic({ id: 'hm_test' })
+ expect(scene.values.screenshotUrl).toBe(captures[0].content_url)
+ scene.actions.setGeneratingScreenshot(true)
+ scene.actions.setHistoryScreenshotStatus(captures[0].content_url!, true)
+ scene.actions.setScreenshotLoaded(false)
+ scene.actions.setScreenshotError('Current capture failed')
+ expect(scene.values.previewUnavailable).toBe(false)
+ expect(scene.values.previewError).toBeNull()
+ expect(scene.values.screenshotLoaded).toBe(true)
+ await expectLogic(logic, () => logic.actions.clearSelection()).toFinishAllListeners()
+ expect(scene.values.previewError).toBe('Current capture failed')
+ expect(scene.values.previewUnavailable).toBe(true)
+ })
+
+ it('preserves the shown day when a missing date is requested and explicitly identifies navigation gaps', async () => {
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.browseCapture('cap-2')).toFinishAllListeners()
+ expect(logic.values.missingCaptureDate).toBe('2024-05-02')
+ expect(logic.values.missingDateAlternatives.map((capture) => capture.id)).toEqual(['cap-1', 'cap-3'])
+ expect(logic.values.selectedBackground?.id).toBe('cap-1')
+ await expectLogic(logic, () => logic.actions.navigateCapture('next')).toFinishAllListeners()
+ expect(logic.values.selectedBackground?.id).toBe('cap-3')
+ expect(logic.values.navigationNotice).toContain('Skipped 1 day')
+ expect(logic.values.missingCaptureDate).toBeNull()
+ })
+
+ it.each(['unchanged metadata', 'failed replacement'])(
+ 'keeps an active area during %s refresh',
+ async (state) => {
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ const area = {
+ points: [{ x: 10, y: 20, target_fixed: false }],
+ expectedCount: 1,
+ clickX: 10,
+ clickY: 20,
+ }
+ await expectLogic(dataLogic, () => dataLogic.actions.setSelectedArea(area)).toFinishAllListeners()
+ const scene = heatmapLogic({ id: 'hm_test' })
+ scene.actions.setHistoryScreenshotStatus(scene.values.screenshotUrl!, true)
+ const refreshed = capture(
+ 'cap-1',
+ '2024-05-01',
+ state === 'failed replacement'
+ ? {
+ latest_request: {
+ request_id: 'failed',
+ state: 'failed',
+ failure_cause: 'browserless_timeout',
+ page_status: null,
+ deadline: '2024-05-01T12:30:00Z',
+ completed_at: '2024-05-01T12:05:00Z',
+ },
+ }
+ : {}
+ )
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(historyResponse([refreshed]))
+ ).toFinishAllListeners()
+ expect(dataLogic.values.selectedArea).toEqual(area)
+ expect(dataLogic.values.showEventsPanel).toBe(true)
+ expect(scene.values.screenshotLoaded).toBe(true)
+ }
+ )
+
+ it('opens with recent captures and brings a chosen older date into view', async () => {
+ const month = Array.from({ length: 21 }, (_, index) =>
+ capture(`day-${index + 1}`, `2024-05-${String(index + 1).padStart(2, '0')}`)
+ )
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(historyResponse(month))
+ ).toFinishAllListeners()
+ expect(logic.values.visibleCaptures.map((c) => c.id)).toEqual(month.slice(17).map((c) => c.id))
+ await expectLogic(logic, () => logic.actions.selectCapture('day-1')).toFinishAllListeners()
+ expect(logic.values.visibleCaptures.map((c) => c.id)).toEqual(month.slice(0, 1).map((c) => c.id))
+ expect(logic.values.selectedBackground?.id).toBe('day-1')
+ })
+
+ it('refreshes the selected image after successful replacement', async () => {
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ const area = { points: [{ x: 10, y: 20, target_fixed: false }], expectedCount: 1, clickX: 10, clickY: 20 }
+ await expectLogic(dataLogic, () => dataLogic.actions.setSelectedArea(area)).toFinishAllListeners()
+ const replacement = capture('cap-1', '2024-05-01', {
+ content_url: '/replacement.jpg',
+ revision: 'request-new',
+ })
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(historyResponse([replacement]))
+ ).toFinishAllListeners()
+ expect(heatmapLogic({ id: 'hm_test' }).values.screenshotUrl).toBe('/replacement.jpg')
+ expect(dataLogic.values.selectedArea).toBeNull()
+ expect(dataLogic.values.showEventsPanel).toBe(false)
+ })
+
+ it('does not export a selected historical image through the action', async () => {
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ const scene = heatmapLogic({ id: 'hm_test' })
+ const exportAction = jest.spyOn(scene.actions, 'startHeatmapExport')
+ scene.actions.exportHeatmap()
+ expect(exportAction).not.toHaveBeenCalled()
+ })
+
+ it('keeps history selections separate between projects', async () => {
+ const other = pageHistoryLogic({ id: 'hm_test', teamId: 998 })
+ other.mount()
+ await expectLogic(other, () => other.actions.loadHistory()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ expect(other.values.anchorId).toBeNull()
+ await expectLogic(other, () => other.actions.selectCapture('cap-3')).toFinishAllListeners()
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(historyResponse(captures))
+ ).toFinishAllListeners()
+ expect(dataLogic.values.historyView?.owner).toBe('998:hm_test')
+ expect(logic.values.anchorId).toBeNull()
+ logic.unmount()
+ expect(dataLogic.values.dateRangeOverride?.date_from).toBe('2024-05-03')
+ expect(dataLogic.values.historyView?.owner).toBe('998:hm_test')
+ other.unmount()
+ expect(dataLogic.values.dateRangeOverride).toBeNull()
+ })
+
+ 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()
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryRetrieve').mockRejectedValue(new Error('unavailable'))
+ const scene = heatmapLogic({ id: 'hm_test' })
+ await expectLogic(logic, () =>
+ scene.actions.setSavedSettings({ ...scene.values.savedSettings!, url: 'https://example.com/new-page' })
+ ).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.browseCapture('cap-3')).toFinishAllListeners()
+
+ expect(logic.values.historyLoadFailed).toBe(true)
+ expect(logic.values.captures).toEqual([])
+ expect(logic.values.isSelectionActive).toBe(false)
+ expect(dataLogic.values.historyView).toBeNull()
+ })
+
+ it('restores the current view and reloads history when a cached day has expired', async () => {
+ const expired = capture('cap-1', '2024-05-01', { expires_at: dayjs().subtract(1, 'minute').toISOString() })
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(historyResponse([captures[0], expired]))
+ ).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.browseCapture('cap-1')).toFinishAllListeners()
+
+ expect(logic.values.isSelectionActive).toBe(false)
+ expect(dataLogic.values.historyView).toBeNull()
+ expect(logic.values.navigationNotice).toContain('no longer available')
+ expect(logic.values.history).toEqual(historyResponse(captures))
+ })
+
+ it.each(['cap-1', 'cap-3'])('explains recovery when the selected day expires: %s', async (expiredId) => {
+ await expectLogic(logic, () => logic.actions.selectCapture(expiredId)).toFinishAllListeners()
+ dataLogic.actions.setCommonFilters({ date_from: '-30d', filter_test_accounts: true })
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(
+ historyResponse(captures.filter((capture) => capture.id !== expiredId))
+ )
+ ).toFinishAllListeners()
+ expect(logic.values.isSelectionActive).toBe(false)
+ expect(logic.values.navigationNotice).toContain('no longer available')
+ expect(logic.values.historyExpanded).toBe(true)
+ expect(dataLogic.values.dateRangeOverride).toBeNull()
+ expect(dataLogic.values.commonFilters).toEqual({ date_from: '-30d', filter_test_accounts: true })
+ })
+
+ it.each(['exit history', 'edit the page URL', 'switch to an iframe'])(
+ 'restores current filters and width when users %s',
+ async (action) => {
+ const sceneLogic = heatmapLogic({ id: 'hm_test' })
+ const currentScreenshotUrl = sceneLogic.values.screenshotUrl
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ dataLogic.actions.setCommonFilters({ date_from: '-30d', filter_test_accounts: true })
+ await expectLogic(logic, () => {
+ if (action === 'edit the page URL') {
+ sceneLogic.actions.setPageUrlDraft('https://example.com/new-page')
+ } else if (action === 'switch to an iframe') {
+ sceneLogic.actions.setType('iframe')
+ } else {
+ logic.actions.clearSelection()
+ }
+ }).toFinishAllListeners()
+
+ expect(logic.values.isSelectionActive).toBe(false)
+ expect(dataLogic.values.commonFilters).toEqual({ date_from: '-30d', filter_test_accounts: true })
+ expect(dataLogic.values.dateRangeOverride).toBeNull()
+ expect(dataLogic.values.widthOverride).toBe(1440)
+ expect(sceneLogic.values.lockedWidth).toBeNull()
+ expect(sceneLogic.values.screenshotUrl).toBe(currentScreenshotUrl)
+ }
+ )
+ })
+})
diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.ts
new file mode 100644
index 000000000000..dae42e56747f
--- /dev/null
+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.ts
@@ -0,0 +1,518 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ beforeUnmount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+
+import {
+ HeatmapDateRangeOverride,
+ HeatmapHistoryView,
+ heatmapDataLogic,
+} from 'lib/components/heatmaps/heatmapDataLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { HeatmapType } from '~/types'
+
+import { savedScreenshotHistoryRetrieve } from 'products/web_analytics/frontend/generated/api'
+import type {
+ HeatmapScreenshotHistoryItemApi,
+ HeatmapScreenshotHistoryResponseApi,
+} from 'products/web_analytics/frontend/generated/api.schemas'
+
+import { heatmapLogic } from '../scenes/heatmap/heatmapLogic'
+import type { HeatmapSettings } from '../scenes/heatmap/heatmapSettings'
+import { formatCaptureDay } from './pageHistoryUtils'
+
+export interface PageHistoryLogicProps {
+ id: string
+ teamId?: number
+}
+const CAPTURES_PER_PAGE = 4
+
+export function isUsableCapture(capture: HeatmapScreenshotHistoryItemApi): boolean {
+ return capture.status === 'ok' && !!capture.content_url
+}
+function isExpiredCapture(capture: HeatmapScreenshotHistoryItemApi): boolean {
+ return dayjs(capture.expires_at).isBefore(dayjs())
+}
+function sortCapturesOldestFirst(captures: HeatmapScreenshotHistoryItemApi[]): HeatmapScreenshotHistoryItemApi[] {
+ return [...captures].sort((a, b) => a.captured_on.localeCompare(b.captured_on))
+}
+export function selectCapturesBetween(
+ captures: HeatmapScreenshotHistoryItemApi[],
+ anchorId: string | null,
+ extentId: string | null
+): HeatmapScreenshotHistoryItemApi[] {
+ const anchor = captures.find((capture) => capture.id === anchorId)
+ if (!anchor || !isUsableCapture(anchor)) {
+ return []
+ }
+ const extent = extentId ? captures.find((capture) => capture.id === extentId) : anchor
+ if (!extent || !isUsableCapture(extent)) {
+ return []
+ }
+ const [from, to] = [anchor.captured_on, extent.captured_on].sort()
+ const selected = sortCapturesOldestFirst(
+ captures.filter(
+ (capture) => isUsableCapture(capture) && capture.captured_on >= from && capture.captured_on <= to
+ )
+ )
+ return selected.every((capture) => capture.width === anchor.width && capture.timezone === anchor.timezone)
+ ? selected
+ : []
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pageHistoryLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ hasUnsavedChanges: boolean // heatmapLogic
+ savedSettings: HeatmapSettings | null // heatmapLogic
+ anchorId: string | null
+ captures: HeatmapScreenshotHistoryItemApi[]
+ extentId: string | null
+ history: HeatmapScreenshotHistoryResponseApi | null
+ historyBrowseDisabledReason: string | null
+ historyExpanded: boolean
+ historyLoadFailed: boolean
+ historyLoading: boolean
+ historyPage: number
+ historyPageCount: number
+ isSelectionActive: boolean
+ missingCaptureDate: string | null
+ missingDateAlternatives: HeatmapScreenshotHistoryItemApi[]
+ navigationNotice: string | null
+ nextCapture: HeatmapScreenshotHistoryItemApi | null
+ pageHistoryEnabled: boolean
+ previousCapture: HeatmapScreenshotHistoryItemApi | null
+ selectedBackground: HeatmapScreenshotHistoryItemApi | null
+ selectedCaptures: HeatmapScreenshotHistoryItemApi[]
+ selectedDateRange: HeatmapDateRangeOverride | null
+ usableCaptures: HeatmapScreenshotHistoryItemApi[]
+ visibleCaptures: HeatmapScreenshotHistoryItemApi[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pageHistoryLogicActions {
+ setHistoryView: (view: HeatmapHistoryView | null) => {
+ view: HeatmapHistoryView | null
+ } // heatmapDataLogic
+ setDataUrl: (url: string | null) => {
+ url: string | null
+ } // heatmapLogic
+ setPageUrlDraft: (value: string) => {
+ value: string
+ } // heatmapLogic
+ setSavedSettings: (settings: HeatmapSettings) => {
+ settings: HeatmapSettings
+ } // heatmapLogic
+ setType: (type: HeatmapType) => {
+ type: HeatmapType
+ } // heatmapLogic
+ applySelection: () => {
+ value: true
+ }
+ browseCapture: (id: string) => {
+ id: string
+ }
+ clearSelection: () => {
+ value: true
+ }
+ loadHistory: (_: void) => void
+ loadHistoryFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadHistorySuccess: (
+ history: HeatmapScreenshotHistoryResponseApi,
+ payload?: void
+ ) => {
+ history: HeatmapScreenshotHistoryResponseApi
+ payload?: void
+ }
+ navigateCapture: (direction: 'next' | 'previous') => {
+ direction: 'next' | 'previous'
+ }
+ pageChanged: () => {
+ value: true
+ }
+ selectCapture: (id: string) => {
+ id: string
+ }
+ setHistoryExpanded: (expanded: boolean) => {
+ expanded: boolean
+ }
+ setHistoryPage: (page: number) => {
+ page: number
+ }
+ setMissingCaptureDate: (date: string | null) => {
+ date: string | null
+ }
+ setNavigationNotice: (notice: string | null) => {
+ notice: string | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pageHistoryLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ pageHistoryEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ captures: (history: HeatmapScreenshotHistoryResponseApi | null) => HeatmapScreenshotHistoryItemApi[]
+ historyPageCount: (captures: HeatmapScreenshotHistoryItemApi[]) => number
+ visibleCaptures: (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ historyPage: number,
+ historyPageCount: number
+ ) => HeatmapScreenshotHistoryItemApi[]
+ usableCaptures: (captures: HeatmapScreenshotHistoryItemApi[]) => HeatmapScreenshotHistoryItemApi[]
+ previousCapture: (
+ usableCaptures: HeatmapScreenshotHistoryItemApi[],
+ selectedBackground: HeatmapScreenshotHistoryItemApi | null
+ ) => HeatmapScreenshotHistoryItemApi | null
+ nextCapture: (
+ usableCaptures: HeatmapScreenshotHistoryItemApi[],
+ selectedBackground: HeatmapScreenshotHistoryItemApi | null
+ ) => HeatmapScreenshotHistoryItemApi | null
+ missingDateAlternatives: (
+ usableCaptures: HeatmapScreenshotHistoryItemApi[],
+ missingCaptureDate: string | null
+ ) => HeatmapScreenshotHistoryItemApi[]
+ historyBrowseDisabledReason: (hasUnsavedChanges: boolean) => string | null
+ selectedCaptures: (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ anchorId: string | null,
+ extentId: string | null
+ ) => HeatmapScreenshotHistoryItemApi[]
+ selectedDateRange: (selectedCaptures: HeatmapScreenshotHistoryItemApi[]) => HeatmapDateRangeOverride | null
+ selectedBackground: (
+ selectedCaptures: HeatmapScreenshotHistoryItemApi[]
+ ) => HeatmapScreenshotHistoryItemApi | null
+ isSelectionActive: (selectedCaptures: HeatmapScreenshotHistoryItemApi[]) => boolean
+ }
+}
+
+export type pageHistoryLogicType = MakeLogicType<
+ pageHistoryLogicValues,
+ pageHistoryLogicActions,
+ PageHistoryLogicProps,
+ pageHistoryLogicMeta
+>
+
+export const pageHistoryLogic = kea<pageHistoryLogicType>([
+ path((key) => ['products', 'web_analytics', 'heatmaps', 'history', 'pageHistoryLogic', key]),
+ props({} as PageHistoryLogicProps),
+ key((props) => `${props.teamId ?? teamLogic.values.currentTeamIdStrict}:${props.id}`),
+ connect((props: PageHistoryLogicProps) => ({
+ values: [
+ heatmapLogic({ id: props.id }),
+ ['savedSettings', 'hasUnsavedChanges'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
+ actions: [
+ heatmapLogic({ id: props.id }),
+ ['setSavedSettings', 'setPageUrlDraft', 'setType', 'setDataUrl'],
+ heatmapDataLogic({ context: 'in-app' }),
+ ['setHistoryView'],
+ ],
+ })),
+ actions({
+ pageChanged: true,
+ selectCapture: (id: string) => ({ id }),
+ browseCapture: (id: string) => ({ id }),
+ navigateCapture: (direction: 'previous' | 'next') => ({ direction }),
+ setMissingCaptureDate: (date: string | null) => ({ date }),
+ setNavigationNotice: (notice: string | null) => ({ notice }),
+ setHistoryPage: (page: number) => ({ page }),
+ setHistoryExpanded: (expanded: boolean) => ({ expanded }),
+ clearSelection: true,
+ applySelection: true,
+ }),
+ loaders(({ props, cache }) => ({
+ history: [
+ null as HeatmapScreenshotHistoryResponseApi | null,
+ {
+ loadHistory: async (_: void, breakpoint) => {
+ const history = await savedScreenshotHistoryRetrieve(String(cache.teamId), props.id)
+ breakpoint()
+ return history
+ },
+ },
+ ],
+ })),
+ reducers({
+ anchorId: [
+ null as string | null,
+ {
+ selectCapture: (_, { id }) => id,
+ clearSelection: () => null,
+ },
+ ],
+ extentId: [
+ null as string | null,
+ {
+ selectCapture: (_, { id }) => id,
+ clearSelection: () => null,
+ },
+ ],
+ historyExpanded: [
+ false,
+ {
+ setHistoryExpanded: (_, { expanded }) => expanded,
+ clearSelection: () => false,
+ },
+ ],
+ missingCaptureDate: [
+ null as string | null,
+ { setMissingCaptureDate: (_, { date }) => date, selectCapture: () => null, clearSelection: () => null },
+ ],
+ navigationNotice: [
+ null as string | null,
+ { setNavigationNotice: (_, { notice }) => notice, selectCapture: () => null, clearSelection: () => null },
+ ],
+ history: { pageChanged: () => null },
+ historyPage: [0, { setHistoryPage: (_, { page }) => Math.max(0, page), pageChanged: () => 0 }],
+ historyLoadFailed: [false, { loadHistory: () => false, loadHistoryFailure: () => true }],
+ }),
+ selectors({
+ pageHistoryEnabled: [
+ (s) => [s.featureFlags],
+ (flags: FeatureFlagsSet): boolean => !!flags[FEATURE_FLAGS.HEATMAPS_PAGE_HISTORY],
+ ],
+ captures: [
+ (s) => [s.history],
+ (history: HeatmapScreenshotHistoryResponseApi | null): HeatmapScreenshotHistoryItemApi[] =>
+ sortCapturesOldestFirst(history?.results ?? []),
+ ],
+ historyPageCount: [
+ (s) => [s.captures],
+ (captures: HeatmapScreenshotHistoryItemApi[]): number =>
+ Math.max(1, Math.ceil(captures.length / CAPTURES_PER_PAGE)),
+ ],
+ visibleCaptures: [
+ (s) => [s.captures, s.historyPage, s.historyPageCount],
+ (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ page: number,
+ count: number
+ ): HeatmapScreenshotHistoryItemApi[] => {
+ const end = captures.length - Math.min(page, count - 1) * CAPTURES_PER_PAGE
+ return captures.slice(Math.max(0, end - CAPTURES_PER_PAGE), end)
+ },
+ ],
+ usableCaptures: [
+ (s) => [s.captures],
+ (captures: HeatmapScreenshotHistoryItemApi[]): HeatmapScreenshotHistoryItemApi[] =>
+ captures.filter(isUsableCapture),
+ ],
+ previousCapture: [
+ (s) => [s.usableCaptures, s.selectedBackground],
+ (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ background: HeatmapScreenshotHistoryItemApi | null
+ ): HeatmapScreenshotHistoryItemApi | null =>
+ background
+ ? (captures[captures.findIndex((capture) => capture.id === background.id) - 1] ?? null)
+ : null,
+ ],
+ nextCapture: [
+ (s) => [s.usableCaptures, s.selectedBackground],
+ (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ background: HeatmapScreenshotHistoryItemApi | null
+ ): HeatmapScreenshotHistoryItemApi | null =>
+ background
+ ? (captures[captures.findIndex((capture) => capture.id === background.id) + 1] ?? null)
+ : null,
+ ],
+ missingDateAlternatives: [
+ (s) => [s.usableCaptures, s.missingCaptureDate],
+ (captures: HeatmapScreenshotHistoryItemApi[], date: string | null): HeatmapScreenshotHistoryItemApi[] => {
+ if (!date) {
+ return []
+ }
+ return [
+ captures.filter((capture) => capture.captured_on < date).at(-1),
+ captures.find((capture) => capture.captured_on > date),
+ ].filter((capture): capture is HeatmapScreenshotHistoryItemApi => !!capture)
+ },
+ ],
+ historyBrowseDisabledReason: [
+ (s) => [s.hasUnsavedChanges],
+ (hasUnsavedChanges: boolean): string | null =>
+ hasUnsavedChanges ? 'Save or discard your page changes to explore history.' : null,
+ ],
+ selectedCaptures: [
+ (s) => [s.captures, s.anchorId, s.extentId],
+ (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ anchorId: string | null,
+ extentId: string | null
+ ): HeatmapScreenshotHistoryItemApi[] => selectCapturesBetween(captures, anchorId, extentId),
+ ],
+ selectedDateRange: [
+ (s) => [s.selectedCaptures],
+ (captures: HeatmapScreenshotHistoryItemApi[]): HeatmapDateRangeOverride | null =>
+ captures.length
+ ? {
+ date_from: captures[0].captured_on,
+ date_to: captures[captures.length - 1].captured_on,
+ timestamp_from: captures[0].day_start,
+ timestamp_to: captures[captures.length - 1].day_end,
+ }
+ : null,
+ ],
+ selectedBackground: [
+ (s) => [s.selectedCaptures],
+ (captures: HeatmapScreenshotHistoryItemApi[]): HeatmapScreenshotHistoryItemApi | null =>
+ captures[captures.length - 1] ?? null,
+ ],
+ isSelectionActive: [
+ (s) => [s.selectedCaptures],
+ (captures: HeatmapScreenshotHistoryItemApi[]): boolean => captures.length > 0,
+ ],
+ }),
+ listeners(({ actions, values, cache, key, props }) => {
+ const clearSelectionOnUnsavedChange = (): void => {
+ if (values.hasUnsavedChanges && values.isSelectionActive) {
+ actions.clearSelection()
+ }
+ }
+ const restoreCurrentView = (): void => {
+ actions.clearSelection()
+ actions.setNavigationNotice(
+ 'A selected screenshot is no longer available. Your current view has been restored. Choose another date to continue.'
+ )
+ actions.setHistoryExpanded(true)
+ }
+ return {
+ setSavedSettings: ({ settings }) => {
+ const urlKey = JSON.stringify([settings.url, settings.data_url])
+ if (cache.urlKey && cache.urlKey !== urlKey) {
+ actions.pageChanged()
+ }
+ cache.urlKey = urlKey
+ },
+ pageChanged: () => {
+ actions.clearSelection()
+ if (values.pageHistoryEnabled && props.id !== 'new') {
+ actions.loadHistory()
+ }
+ },
+ setPageUrlDraft: clearSelectionOnUnsavedChange,
+ setDataUrl: clearSelectionOnUnsavedChange,
+ setType: ({ type }) => {
+ if (type !== 'screenshot' && values.isSelectionActive) {
+ actions.clearSelection()
+ }
+ },
+ browseCapture: ({ id }) => {
+ if (values.historyBrowseDisabledReason) {
+ return
+ }
+ const capture = values.captures.find((capture) => capture.id === id)
+ if (!capture) {
+ return
+ }
+ if (!isUsableCapture(capture)) {
+ actions.setMissingCaptureDate(capture.captured_on)
+ return
+ }
+ actions.selectCapture(id)
+ },
+ navigateCapture: ({ direction }) => {
+ const from = values.selectedBackground
+ const to = direction === 'previous' ? values.previousCapture : values.nextCapture
+ if (!from || !to || values.historyBrowseDisabledReason) {
+ return
+ }
+ actions.selectCapture(to.id)
+ const missingDays = Math.abs(dayjs(to.captured_on).diff(dayjs(from.captured_on), 'day')) - 1
+ if (missingDays > 0) {
+ actions.setNavigationNotice(
+ `Moved to ${formatCaptureDay(to.captured_on)}. Skipped ${missingDays} ${missingDays === 1 ? 'day' : 'days'} with no saved screenshot.`
+ )
+ }
+ },
+ selectCapture: ({ id }) => {
+ const index = values.captures.findIndex((capture) => capture.id === id)
+ if (index >= 0) {
+ actions.setHistoryPage(Math.floor((values.captures.length - index - 1) / CAPTURES_PER_PAGE))
+ }
+ actions.applySelection()
+ },
+ applySelection: () => {
+ const background = values.selectedBackground
+ const range = values.selectedDateRange
+ if (!background?.content_url || !range) {
+ actions.clearSelection()
+ return
+ }
+ if (values.selectedCaptures.some(isExpiredCapture)) {
+ restoreCurrentView()
+ actions.loadHistory()
+ return
+ }
+ const view: HeatmapHistoryView = {
+ owner: key,
+ dateRange: range,
+ width: background.width,
+ imageUrl: background.content_url,
+ }
+ if (!objectsEqual(heatmapDataLogic({ context: 'in-app' }).values.historyView, view)) {
+ actions.setHistoryView(view)
+ }
+ },
+ clearSelection: () => {
+ const data = heatmapDataLogic({ context: 'in-app' })
+ if (data.values.historyView?.owner === key) {
+ actions.setHistoryView(null)
+ }
+ },
+ loadHistorySuccess: () => {
+ actions.setHistoryPage(Math.min(values.historyPage, values.historyPageCount - 1))
+ if (values.anchorId) {
+ if (heatmapDataLogic({ context: 'in-app' }).values.historyView?.owner !== key) {
+ actions.clearSelection()
+ } else if (values.selectedCaptures.length > 0) {
+ actions.applySelection()
+ } else {
+ restoreCurrentView()
+ }
+ }
+ },
+ }
+ }),
+ afterMount(({ actions, props, values, cache }) => {
+ cache.teamId = props.teamId ?? teamLogic.values.currentTeamIdStrict
+ if (values.savedSettings) {
+ cache.urlKey = JSON.stringify([values.savedSettings.url, values.savedSettings.data_url])
+ }
+ if (values.pageHistoryEnabled && props.id !== 'new') {
+ actions.loadHistory()
+ }
+ }),
+ beforeUnmount(({ key }) => {
+ const data = heatmapDataLogic({ context: 'in-app' })
+ if (data.values.historyView?.owner === key) {
+ data.actions.setHistoryView(null)
+ }
+ }),
+])
diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryUtils.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryUtils.ts
new file mode 100644
index 000000000000..0505820c1ac2
--- /dev/null
+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryUtils.ts
@@ -0,0 +1,25 @@
+import type { HeatmapDateRangeOverride } from 'lib/components/heatmaps/heatmapDataLogic'
+import { dayjs } from 'lib/dayjs'
+
+import type { HeatmapScreenshotHistoryItemApi } from 'products/web_analytics/frontend/generated/api.schemas'
+
+export function formatCaptureDay(day: string, style: 'short' | 'long' = 'short'): string {
+ return dayjs(day).format(style === 'long' ? 'MMMM D, YYYY' : 'MMM D, YYYY')
+}
+
+export function formatCaptureTime(capture: HeatmapScreenshotHistoryItemApi): string | null {
+ return capture.captured_at ? dayjs(capture.captured_at).tz(capture.timezone).format('HH:mm') : null
+}
+
+export function formatHistoryDateRange(range: Pick<HeatmapDateRangeOverride, 'date_from' | 'date_to'>): string {
+ const from = dayjs(range.date_from)
+ const to = dayjs(range.date_to)
+ return from.isSame(to, 'day')
+ ? formatCaptureDay(range.date_from)
+ : `${from.format(from.year() === to.year() ? 'MMM D' : 'MMM D, YYYY')} to ${formatCaptureDay(range.date_to)}`
+}
+
+export function formatCaptureTimestamp(capture: HeatmapScreenshotHistoryItemApi): string {
+ const time = formatCaptureTime(capture)
+ return `${formatCaptureDay(capture.captured_on)}${time ? ` at ${time}` : ''} ${capture.timezone}`
+}