: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
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import { resolveHeatmapUrlFilter } from 'lib/components/heatmaps/heatmapUrlMatch'
import type { HrefMatchType } from '../lib/components/heatmaps/heatmapDataLogic'
import type { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from '../lib/components/heatmaps/types'
import { ExportType, ExportedData } from './types'
export const heatmapScreenshotFetchOptions = (heatmapUrl: string, exportToken?: string): RequestInit => {
const requestUrl = new URL(heatmapUrl, window.location.origin)
if (!exportToken || requestUrl.origin !== window.location.origin) {
return {}
}
return { headers: { Authorization: `Bearer ${exportToken}` } }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface exporterViewLogicValues {
exportedData: ExportedData
isLoading: boolean
screenshotUrl: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface exporterViewLogicActions {
setCommonFilters: (filters: CommonFilters) => {
filters: CommonFilters
} // heatmapDataLogic
setHeatmapColorPalette: (palette: string | null) => {
palette: string | null
} // heatmapDataLogic
setHeatmapFilters: (filters: HeatmapFilters) => {
filters: HeatmapFilters
} // heatmapDataLogic
setHeatmapFixedPositionMode: (mode: HeatmapFixedPositionMode) => {
mode: HeatmapFixedPositionMode
} // heatmapDataLogic
setHref: (href: string) => {
href: string
} // heatmapDataLogic
setHrefMatchType: (matchType: HrefMatchType) => {
matchType: HrefMatchType
} // heatmapDataLogic
setWindowWidthOverride: (widthOverride: number | null) => {
widthOverride: number | null
} // heatmapDataLogic
fetchScreenshotUrl: () => {
value: true
}
setIsLoading: (isLoading: boolean) => {
isLoading: boolean
}
setScreenshotUrl: (screenshotUrl: string) => {
screenshotUrl: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface exporterViewLogicMeta {
__keaTypeGenInternalSelectorTypes: {
exportedData: (arg: ExportedData) => ExportedData
}
}
export type exporterViewLogicType = MakeLogicType<
exporterViewLogicValues,
exporterViewLogicActions,
ExportedData,
exporterViewLogicMeta
>
// This is a simple logic that is mounted by the Exporter view and then can be found by any nested callers
// This simplifies passing props everywhere.
// E.g. api.ts uses this to add the sharing_access_token
export const exporterViewLogic = kea<exporterViewLogicType>([
path(['exporter', 'exporterViewLogic']),
props({} as ExportedData),
connect((props: ExportedData) => ({
actions: [
heatmapDataLogic({ context: 'in-app', exportToken: props.exportToken }),
[
'setHref',
'setHrefMatchType',
'setHeatmapFilters',
'setHeatmapFixedPositionMode',
'setHeatmapColorPalette',
'setCommonFilters',
'setWindowWidthOverride',
],
],
})),
actions({
setIsLoading: (isLoading: boolean) => ({ isLoading }),
setScreenshotUrl: (screenshotUrl: string) => ({ screenshotUrl }),
fetchScreenshotUrl: true,
}),
reducers({
isLoading: [false, { setIsLoading: (_, { isLoading }) => isLoading }],
screenshotUrl: [null as string | null, { setScreenshotUrl: (_, { screenshotUrl }) => screenshotUrl }],
}),
selectors({
exportedData: [() => [(_, props: ExportedData) => props], (props: ExportedData) => props],
}),
listeners(({ actions, props }) => ({
fetchScreenshotUrl: async () => {
if (props.heatmap_context?.heatmap_type !== 'screenshot') {
return
}
actions.setIsLoading(true)
try {
const heatmapUrl = props.heatmap_url ?? ''
const response = await fetch(heatmapUrl, heatmapScreenshotFetchOptions(heatmapUrl, props.exportToken))
if (response.ok) {
const blob = await response.blob()
const objectUrl = URL.createObjectURL(blob)
actions.setScreenshotUrl(objectUrl)
} else {
console.error('Failed to fetch screenshot:', response.status)
}
} catch (error) {
console.error('Failed to fetch screenshot:', error)
} finally {
actions.setIsLoading(false)
}
},
})),
afterMount(({ actions, props }) => {
if (props.type === ExportType.Heatmap && props.heatmap_url) {
if (props.heatmap_context?.heatmap_type === 'screenshot') {
actions.fetchScreenshotUrl()
} else {
actions.setIsLoading(false)
}
if (props.heatmap_context?.heatmap_data_url) {
const dataUrl = props.heatmap_context.heatmap_data_url
const urlFilter = resolveHeatmapUrlFilter(dataUrl)
actions.setHref(urlFilter?.href ?? dataUrl)
actions.setHrefMatchType(urlFilter?.matchType ?? 'exact')
}
if (props.heatmap_context?.heatmap_filters) {
actions.setHeatmapFilters(props.heatmap_context.heatmap_filters)
}
if (props.heatmap_context?.heatmap_fixed_position_mode) {
actions.setHeatmapFixedPositionMode(props.heatmap_context.heatmap_fixed_position_mode)
}
if (props.heatmap_context?.heatmap_color_palette) {
actions.setHeatmapColorPalette(props.heatmap_context.heatmap_color_palette)
}
if (props.heatmap_context?.common_filters) {
actions.setCommonFilters(props.heatmap_context.common_filters)
}
if (props.heatmap_context?.width) {
actions.setWindowWidthOverride(props.heatmap_context.width)
}
}
}),
])
export const getCurrentExporterData = (): ExportedData | undefined => {
return exporterViewLogic.findMounted()?.values.exportedData
}
/**
* Synchronous check for "this bundle is rendering a shared/exported view".
*
* Reads `window.POSTHOG_EXPORTED_DATA` directly because that global is set by
* Django before any React code runs. Going through the kea logic (via
* `getCurrentExporterData`) is unreliable from inside a leaf component's
* `useEffect` — React fires child effects before parent ones, so the
* `BindLogic` wrapping `<Exporter>` may not have mounted `exporterViewLogic`
* yet by the time a deeply-nested gate checks. Direct global access is
* synchronous and there's no mount-order risk.
*
* Falls back to the kea check for non-exporter contexts (Storybook, jest)
* where `POSTHOG_EXPORTED_DATA` isn't injected.
*/
export const isSharedView = (): boolean => {
if (typeof window !== 'undefined' && window.POSTHOG_EXPORTED_DATA) {
return true
}
return !!getCurrentExporterData()
}