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.

fix(heatmaps): match heatmap data urls literally unless they contain a wildcard (#103147)

Jordan Mryyan6a89ec4578a0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f62aa746ae09..3e444081624f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8881,9 +8881,9 @@ snapshots:
scenes-app-heatmap-new--unauthorized-iframe--light:
hash: v1.k794b7964.8e355023754bf9c2c1dc31cbadba79e6b524ad9a66528c649ab150f7eaf0cc05.yqUC0NlgolBVjXQsucJcRfdlu5npQvynKZSy7oAnd_8
scenes-app-heatmap-recording--recording-mode-with-clickmap--dark:
- hash: v1.k794b7964.9369ded2efa326a9d9adaec0de1efb86baa001b7ee4dca6e5fa2446379413c9d.nxftFTmTFr1jVHJQssBp-fdpgkojfMux1YVzeJVtSfk
+ hash: v1.k794b7964.5391a9fc4891c9c7ae154895493807ff0e569a5a1d7bdef43ca0f48b878a59cc.JaAh4Zz4E8c0ompabfRmWhcN-VsLNhZd3607c4RPJAw
scenes-app-heatmap-recording--recording-mode-with-clickmap--light:
- hash: v1.k794b7964.966fa455f5651c32d6e6b0cf7092325c4ebb917a8c67eb372598c3bab977e5de.TE80vbs-abW4Nu6I2L_Uw-MHMs5w5xESaNBqrCXiorQ
+ hash: v1.k794b7964.b971c6a8c3c44007c4b2de5797ac84541c34cef1ec16e0b6d760908b4d804302.DIupEQcozzEHDmS1urKBQx7LPhToY6N0FGgL2osOcUw
scenes-app-heatmaps-saved--list--dark:
hash: v1.k794b7964.8368377e136c567c3c500c97924486837234c230858baf0eb14678b6900d68c6.qpjMZIE3Ii8vpyLrfaKjCdym7waJtp38DGez1iugMMo
scenes-app-heatmaps-saved--list--light:
diff --git a/frontend/src/exporter/exporterViewLogic.ts b/frontend/src/exporter/exporterViewLogic.ts
index 9b42721780bd..870d3e7f9d3a 100644
--- a/frontend/src/exporter/exporterViewLogic.ts
+++ b/frontend/src/exporter/exporterViewLogic.ts
@@ -1,15 +1,12 @@
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'
-const isUrlPattern = (url: string): boolean => {
- return /[*+?^${}()|[\]\\]/.test(url)
-}
-
export const heatmapScreenshotFetchOptions = (heatmapUrl: string, exportToken?: string): RequestInit => {
const requestUrl = new URL(heatmapUrl, window.location.origin)
if (!exportToken || requestUrl.origin !== window.location.origin) {
@@ -136,12 +133,10 @@ export const exporterViewLogic = kea<exporterViewLogicType>([
actions.setIsLoading(false)
}
if (props.heatmap_context?.heatmap_data_url) {
- actions.setHref(props.heatmap_context?.heatmap_data_url)
- if (isUrlPattern(props.heatmap_context?.heatmap_data_url)) {
- actions.setHrefMatchType('pattern')
- } else {
- actions.setHrefMatchType('exact')
- }
+ 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) {
diff --git a/frontend/src/lib/components/heatmaps/heatmapUrlMatch.ts b/frontend/src/lib/components/heatmaps/heatmapUrlMatch.ts
new file mode 100644
index 000000000000..bc4f8e5d1481
--- /dev/null
+++ b/frontend/src/lib/components/heatmaps/heatmapUrlMatch.ts
@@ -0,0 +1,76 @@
+import type { HrefMatchType } from './heatmapDataLogic'
+
+export type HeatmapUrlMatchMode = 'page' | 'exact'
+
+export interface HeatmapUrlFilter {
+ href: string
+ matchType: HrefMatchType
+ regex: string | null
+}
+
+export const escapeUnescapedRegex = (str: string): string =>
+ str.replace(/\\.|([.*+?^=!:${}()|[\]/\\])/g, (match, group1) => (group1 ? `\\${group1}` : match))
+
+export const hasWildcard = (url: string): boolean => url.includes('*')
+
+const parseUrl = (url: string): URL | null => {
+ try {
+ return new URL(url)
+ } catch {
+ return null
+ }
+}
+
+const normalizeUrlPath = (urlObj: URL): string => {
+ if (urlObj.pathname === '') {
+ urlObj.pathname = '/'
+ }
+ return urlObj.toString()
+}
+
+export const heatmapPageUrl = (url: string): string | null => {
+ const parsed = parseUrl(url.trim())
+ return parsed ? `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}` : null
+}
+
+export const resolveHeatmapUrlFilter = (
+ url: string | null | undefined,
+ mode: HeatmapUrlMatchMode = 'exact'
+): HeatmapUrlFilter | null => {
+ const trimmed = url?.trim()
+ if (!trimmed) {
+ return null
+ }
+ if (hasWildcard(trimmed)) {
+ const segments = trimmed
+ .replace(/^\^|\$$/g, '')
+ .replace(/\.\*/g, '*')
+ .split('*')
+ .map(escapeUnescapedRegex)
+ const href = segments.join('*')
+ return { href, matchType: 'pattern', regex: heatmapUrlPatternToRegex(href) }
+ }
+ const parsed = parseUrl(trimmed)
+ const page = heatmapPageUrl(trimmed)
+ if (!parsed || !page) {
+ return null
+ }
+ if (mode === 'page') {
+ const regex = `^${escapeUnescapedRegex(page)}\\/?(\\?.*)?(#.*)?$`
+ return { href: regex, matchType: 'pattern', regex }
+ }
+ return { href: normalizeUrlPath(parsed), matchType: 'exact', regex: null }
+}
+
+export function heatmapUrlPatternToRegex(value: string): string {
+ let normalized = value
+ if (!normalized.startsWith('^')) {
+ normalized = `^${normalized}`
+ }
+ if (!normalized.endsWith('$')) {
+ normalized = `${normalized}$`
+ }
+ return Array.from(normalized)
+ .map((character, index) => (character === '*' && index > 0 && normalized[index - 1] !== '.' ? '.+' : character))
+ .join('')
+}
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
index 9d2f653e6d54..be3d25010002 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
@@ -94,7 +94,7 @@ describe('heatmapToolbarMenuLogic', () => {
[
{
key: '$current_url',
- value: '^https\\:\\/\\/example\\.com\\/page\\/.*$',
+ value: '^https\\:\\/\\/example\\.com\\/page\\/.+$',
operator: 'regex',
type: 'event',
},
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index 9a8cad8cf65e..5652a61a89d8 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -18,6 +18,7 @@ import { collectAllElementsDeep } from 'query-selector-shadow-dom'
import type { PaginatedResponse } from 'lib/api'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { escapeUnescapedRegex, heatmapUrlPatternToRegex } from 'lib/components/heatmaps/heatmapUrlMatch'
import { HeatmapBoundsFilter } from 'lib/components/heatmaps/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { createSliceYielder } from 'lib/utils/async'
@@ -180,7 +181,7 @@ export function buildElementStatsProperties(
}
: {
key: '$current_url',
- value: `^${wildcardHref.split('*').map(escapeUnescapedRegex).join('.*')}$`,
+ value: heatmapUrlPatternToRegex(wildcardHref.split('*').map(escapeUnescapedRegex).join('*')),
operator: PropertyOperator.Regex,
type: PropertyFilterType.Event,
},
@@ -1654,6 +1655,3 @@ function aggregateAndSortElements(elements: CountedHTMLElement[]): CountedHTMLEl
return sorted.map((e, i) => ({ ...e, position: i + 1 }))
}
-
-export const escapeUnescapedRegex = (str: string): string =>
- str.replace(/\\.|([.*+?^=!:${}()|[\]/\\])/g, (match, group1) => (group1 ? `\\${group1}` : match))
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index ebb6a850411f..f46d7a51fdc0 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -1699,11 +1699,30 @@ class TestExportRendererTokenFlow(APIBaseTest):
encoded_data = json.loads(html[start:end])
return json.loads(encoded_data) if isinstance(encoded_data, str) else encoded_data
+ @parameterized.expand(
+ [
+ ("exact", "https://example.com", "url_exact", "https://example.com"),
+ (
+ "query_string_stays_exact",
+ "https://example.com/p?a=1+2&b=(x)",
+ "url_exact",
+ "https://example.com/p?a=1+2&b=(x)",
+ ),
+ (
+ "wildcard_escapes_the_rest",
+ "https://example.com/users/*?tab=1",
+ "url_pattern",
+ "https\\:\\/\\/example\\.com\\/users\\/*\\?tab\\=1",
+ ),
+ ]
+ )
@mock_exporter_template
- def test_exporter_page_mints_token_that_only_serves_its_heatmap_query(self) -> None:
+ def test_exporter_page_mints_token_that_only_serves_its_heatmap_query(
+ self, _name: str, heatmap_data_url: str, url_param: str, url_value: str
+ ) -> None:
export_context = {
"heatmap_url": "https://example.com",
- "heatmap_data_url": "https://example.com",
+ "heatmap_data_url": heatmap_data_url,
"heatmap_type": "click",
"width": 1400,
"common_filters": {"date_from": "-7d"},
@@ -1732,7 +1751,7 @@ class TestExportRendererTokenFlow(APIBaseTest):
{
"type": "click",
"date_from": "-7d",
- "url_exact": "https://example.com",
+ url_param: url_value,
"viewport_width_min": "1260",
"viewport_width_max": "1540",
"aggregation": "total_count",
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index 5a4c02d05a23..2b64aa6d7242 100644
--- a/products/web_analytics/backend/api/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -248,6 +248,17 @@ def parse_fold_summary_row(row: Any) -> dict[str, Any]:
}
+_UNESCAPED_REGEX_CHARS = re.compile(r"\\.|([.*+?^=!:${}()|\[\]/\\])")
+
+
+def literal_wildcard_url_pattern(value: str) -> str:
+ trimmed = re.sub(r"^\^|\$$", "", value.strip()).replace(".*", "*")
+ return "*".join(
+ _UNESCAPED_REGEX_CHARS.sub(lambda m: f"\\{m.group(1)}" if m.group(1) else m.group(0), segment)
+ for segment in trimmed.split("*")
+ )
+
+
def capture_allowlist_pattern_to_regex(pattern: str) -> str:
return "^" + re.escape(pattern).replace("\\*", ".*") + "$"
@@ -691,8 +702,8 @@ def _renderer_heatmap_query(export_context: dict[str, object]) -> dict[str, obje
"viewport_width_max": int((width + extra_pixels) + 0.5),
"limit": 0,
}
- if any(character in heatmap_data_url for character in "*+?^${}()|[]\\"):
- query["url_pattern"] = heatmap_data_url
+ if "*" in heatmap_data_url:
+ query["url_pattern"] = literal_wildcard_url_pattern(heatmap_data_url)
else:
query["url_exact"] = heatmap_data_url
@@ -1358,11 +1369,8 @@ class HeatmapScreenshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
-_URL_PATTERN_CHARS = set("*+?^${}()|[]\\")
-
-
def _reject_url_wildcards(value: str) -> None:
- if any(c in _URL_PATTERN_CHARS for c in value):
+ if "*" in value:
raise serializers.ValidationError("Wildcards are not allowed in the page URL.")
diff --git a/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr
index 4ea633a7ce19..44b17a4d6818 100644
--- a/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr
+++ b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr
@@ -233,6 +233,116 @@
use_hive_partitioning=0
'''
# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_^http\:\/\/example\.com\/?(\?.*)?(#.*)?$
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT pointer_target_fixed AS pointer_target_fixed,
+ pointer_relative_x AS pointer_relative_x,
+ client_y AS client_y,
+ count(*) AS cnt
+ FROM
+ (SELECT heatmaps.distinct_id AS distinct_id,
+ heatmaps.pointer_target_fixed AS pointer_target_fixed,
+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,
+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0)))))
+ GROUP BY pointer_target_fixed,
+ pointer_relative_x,
+ client_y
+ ORDER BY cnt DESC
+ LIMIT 501
+ OFFSET 0 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_^http\:\/\/example\.com\/?(\?.*)?(#.*)?$.1
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,
+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,
+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))
+ LIMIT 1000000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_^http\:\/\/example\.com\/?(\?.*)?(#.*)?$.2
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT pointer_target_fixed AS pointer_target_fixed,
+ pointer_relative_x AS pointer_relative_x,
+ client_y AS client_y,
+ count(*) AS cnt
+ FROM
+ (SELECT heatmaps.distinct_id AS distinct_id,
+ heatmaps.pointer_target_fixed AS pointer_target_fixed,
+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,
+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http\\:\\/\\/example\\.com\\/?(\\?.*)?(#.*)?$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0)))))
+ GROUP BY pointer_target_fixed,
+ pointer_relative_x,
+ client_y
+ ORDER BY cnt DESC
+ LIMIT 501
+ OFFSET 0 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_^http\:\/\/example\.com\/?(\?.*)?(#.*)?$.3
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,
+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,
+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http\\:\\/\\/example\\.com\\/?(\\?.*)?(#.*)?$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))
+ LIMIT 1000000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com*
'''
/* user_id:0 request:_snapshot_ */
@@ -893,6 +1003,116 @@
use_hive_partitioning=0
'''
# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http\:\/\/example\.com\/products\/*\/parts\/*
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT pointer_target_fixed AS pointer_target_fixed,
+ pointer_relative_x AS pointer_relative_x,
+ client_y AS client_y,
+ count(*) AS cnt
+ FROM
+ (SELECT heatmaps.distinct_id AS distinct_id,
+ heatmaps.pointer_target_fixed AS pointer_target_fixed,
+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,
+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0)))))
+ GROUP BY pointer_target_fixed,
+ pointer_relative_x,
+ client_y
+ ORDER BY cnt DESC
+ LIMIT 501
+ OFFSET 0 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http\:\/\/example\.com\/products\/*\/parts\/*.1
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,
+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,
+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))
+ LIMIT 1000000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http\:\/\/example\.com\/products\/*\/parts\/*.2
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT pointer_target_fixed AS pointer_target_fixed,
+ pointer_relative_x AS pointer_relative_x,
+ client_y AS client_y,
+ count(*) AS cnt
+ FROM
+ (SELECT heatmaps.distinct_id AS distinct_id,
+ heatmaps.pointer_target_fixed AS pointer_target_fixed,
+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,
+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http\\:\\/\\/example\\.com\\/products\\/.+\\/parts\\/.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0)))))
+ GROUP BY pointer_target_fixed,
+ pointer_relative_x,
+ client_y
+ ORDER BY cnt DESC
+ LIMIT 501
+ OFFSET 0 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http\:\/\/example\.com\/products\/*\/parts\/*.3
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,
+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,
+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height
+ FROM heatmaps
+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http\\:\\/\\/example\\.com\\/products\\/.+\\/parts\\/.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))
+ LIMIT 1000000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestSessionRecordings.test_can_filter_by_url_pattern_where_end_is_anchored
'''
/* user_id:0 request:_snapshot_ */
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.py
index 31c422451157..c2c4c6ba0c4f 100644
--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py
@@ -726,6 +726,13 @@ class TestSavedHeatmapCaptureRequestSerializer(SimpleTestCase):
self.assertFalse(serializer.is_valid())
self.assertIn("url", serializer.errors)
+ def test_accepts_a_query_string_url(self) -> None:
+ serializer = SavedHeatmapCaptureRequestSerializer(
+ data={"url": "https://app.example.com/dashboard?tab=(1)&q=a+b"}
+ )
+ serializer.is_valid()
+ self.assertNotIn("url", serializer.errors)
+
@parameterized.expand(
[
("mismatched_lengths", [320, 768, 1440], 2, False),
diff --git a/products/web_analytics/backend/test/test_heatmaps_api.py b/products/web_analytics/backend/test/test_heatmaps_api.py
index 9bc729e690be..32722ea96348 100644
--- a/products/web_analytics/backend/test/test_heatmaps_api.py
+++ b/products/web_analytics/backend/test/test_heatmaps_api.py
@@ -419,6 +419,8 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
["http://example.com/products/*/reviews/*", 2],
["http://example.com/products/*/parts/*", 2],
["http://example.com/products/1*/parts/*", 1],
+ ["http\\:\\/\\/example\\.com\\/products\\/*\\/parts\\/*", 2],
+ ["^http\\:\\/\\/example\\.com\\/?(\\?.*)?(#.*)?$", 1],
],
name_func=lambda f, n, p: f"{f.__name__}_{p.args[0]}",
)
@@ -462,7 +464,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
)
self._assert_heatmap_single_result_count(
- {"date_from": "2023-03-08", "url_pattern": pattern, "type": "rageclick"},
+ {"date_from": "2023-03-08", "url_pattern": quote(pattern), "type": "rageclick"},
expected_matches,
)
diff --git a/products/web_analytics/frontend/heatmaps/components/HeatmapRecording.tsx b/products/web_analytics/frontend/heatmaps/components/HeatmapRecording.tsx
index b9319676c33f..bb264c4301ac 100644
--- a/products/web_analytics/frontend/heatmaps/components/HeatmapRecording.tsx
+++ b/products/web_analytics/frontend/heatmaps/components/HeatmapRecording.tsx
@@ -1,8 +1,10 @@
import { BindLogic, useActions, useValues } from 'kea'
import { useRef } from 'react'
-import { LemonBanner, LemonDivider, LemonInput, LemonLabel } from '@posthog/lemon-ui'
+import { LemonBanner, LemonDivider, LemonInput, LemonLabel, LemonSegmentedButton } from '@posthog/lemon-ui'
+import { hasWildcard, heatmapPageUrl } from 'lib/components/heatmaps/heatmapUrlMatch'
+import type { HeatmapUrlFilter, HeatmapUrlMatchMode } from 'lib/components/heatmaps/heatmapUrlMatch'
import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -13,32 +15,60 @@ import { FixedReplayHeatmapBrowser } from './FixedReplayHeatmapBrowser'
import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'
import { HeatmapsWarnings } from './HeatmapsWarnings'
+function urlMatchSummary(
+ url: string | undefined,
+ urlFilter: HeatmapUrlFilter | null,
+ mode: HeatmapUrlMatchMode
+): string {
+ if (!url?.trim()) {
+ return 'Enter the URL of the page to show data for.'
+ }
+ if (!urlFilter) {
+ return 'Enter a full URL, starting with https://'
+ }
+ if (hasWildcard(url)) {
+ return 'Shows every URL that fits this pattern. * stands for any text, everything else is matched as written.'
+ }
+ if (mode === 'page') {
+ return `Shows every visit to ${heatmapPageUrl(url) ?? 'this page'}, whatever the query string.`
+ }
+ return 'Shows only visits to this exact URL, including its query string.'
+}
+
function UrlSearchHeader(): JSX.Element {
const logic = heatmapsBrowserLogic()
- const { replayIframeData } = useValues(logic)
- const { setReplayIframeDataURL } = useActions(logic)
+ const { replayIframeData, recordingUrlFilter, recordingUrlMatchMode } = useValues(logic)
+ const { setReplayIframeDataURL, setRecordingUrlMatchMode } = useActions(logic)
+ const isWildcard = hasWildcard(replayIframeData?.url ?? '')
return (
- <>
- <div className="flex-none md:flex justify-between items-end gap-2 w-full">
- <div className="flex gap-2 flex-1 min-w-0">
- <div className="flex-1">
- <div className="mt-2">
- <LemonLabel>Heatmap data URL</LemonLabel>
- <div className="text-xs text-muted mb-1">
- Add * for wildcards to aggregate data from multiple pages
- </div>
- <LemonInput
- value={replayIframeData?.url}
- onChange={(s) => setReplayIframeDataURL(s)}
- className="truncate"
- size="small"
- />
- </div>
- </div>
- </div>
+ <div className="mt-2 w-full">
+ <LemonLabel htmlFor="heatmap-recording-data-url">Heatmap data URL</LemonLabel>
+ <div className="text-xs text-muted mb-1">Add * for wildcards to aggregate data from multiple pages</div>
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ id="heatmap-recording-data-url"
+ value={replayIframeData?.url}
+ onChange={(s) => setReplayIframeDataURL(s)}
+ className="truncate flex-1 min-w-60"
+ size="small"
+ data-attr="heatmap-recording-data-url"
+ />
+ <LemonSegmentedButton
+ size="small"
+ value={recordingUrlMatchMode}
+ onChange={(mode) => setRecordingUrlMatchMode(mode)}
+ disabledReason={isWildcard ? 'A URL with * is always matched as a pattern' : undefined}
+ options={[
+ { value: 'page', label: 'This page', 'data-attr': 'heatmap-recording-match-page' },
+ { value: 'exact', label: 'Exact URL', 'data-attr': 'heatmap-recording-match-exact' },
+ ]}
+ />
</div>
- </>
+ <div className="text-xs text-muted mt-1">
+ {urlMatchSummary(replayIframeData?.url, recordingUrlFilter, recordingUrlMatchMode)}
+ </div>
+ </div>
)
}
diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts
index 7ab7672030b4..5b1c613b3db6 100644
--- a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts
+++ b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts
@@ -3,18 +3,14 @@ import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { resolveHeatmapUrlFilter } from 'lib/components/heatmaps/heatmapUrlMatch'
import { initKeaTests } from '~/test/init'
-import {
- PagePreflight,
- heatmapsBrowserLogic,
- normalizeHeatmapDataUrl,
- preflightBannerMessage,
-} from './heatmapsBrowserLogic'
+import { PagePreflight, heatmapsBrowserLogic, preflightBannerMessage } from './heatmapsBrowserLogic'
describe('heatmapsBrowserLogic', () => {
- describe('normalizeHeatmapDataUrl', () => {
+ describe('resolveHeatmapUrlFilter', () => {
it.each([
['example.com', null],
[' ', null],
@@ -25,9 +21,18 @@ describe('heatmapsBrowserLogic', () => {
['https://example.com', { href: 'https://example.com/', matchType: 'exact' }],
['https://example.com/pricing', { href: 'https://example.com/pricing', matchType: 'exact' }],
[' https://example.com/pricing ', { href: 'https://example.com/pricing', matchType: 'exact' }],
- ['https://example.com/users/*', { href: 'https://example.com/users/*', matchType: 'pattern' }],
- ] as const)('normalizeHeatmapDataUrl(%s) → %s', (input, expected) => {
- expect(normalizeHeatmapDataUrl(input)).toEqual(expected)
+ [
+ 'https://example.com/pricing?plan=a+b&ref=(x)',
+ { href: 'https://example.com/pricing?plan=a+b&ref=(x)', matchType: 'exact' },
+ ],
+ ['https://example.com/users/*', { href: 'https\\:\\/\\/example\\.com\\/users\\/*', matchType: 'pattern' }],
+ [
+ 'https://example.com/users/*?tab=1',
+ { href: 'https\\:\\/\\/example\\.com\\/users\\/*\\?tab\\=1', matchType: 'pattern' },
+ ],
+ ] as const)('resolveHeatmapUrlFilter(%s) → %s', (input, expected) => {
+ const filter = resolveHeatmapUrlFilter(input)
+ expect(filter && { href: filter.href, matchType: filter.matchType }).toEqual(expected)
})
})
@@ -131,14 +136,26 @@ describe('heatmapsBrowserLogic', () => {
width: 100,
height: 100,
startDateTime: undefined,
- url: 'https://example.com/pricing',
+ url: 'https://example.com/pricing?plan=a',
})
await expectLogic(logic).toFinishAllListeners()
- expect(dataLogic.values.href).toBe('https://example.com/pricing')
+ const pageRegex = '^https\\:\\/\\/example\\.com\\/pricing\\/?(\\?.*)?(#.*)?$'
+ expect(dataLogic.values.href).toBe(pageRegex)
+ expect(dataLogic.values.hrefMatchType).toBe('pattern')
logic.actions.onIframeLoad()
await expectLogic(logic).toFinishAllListeners()
- expect(dataLogic.values.href).toBe('https://example.com/pricing')
+ expect(dataLogic.values.href).toBe(pageRegex)
+
+ logic.actions.setRecordingUrlMatchMode('exact')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(dataLogic.values.href).toBe('https://example.com/pricing?plan=a')
+ expect(dataLogic.values.hrefMatchType).toBe('exact')
+
+ logic.actions.setReplayIframeDataURL('https://')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(dataLogic.values.href).toBe('')
+ expect(dataLogic.values.hrefMatchType).toBe('exact')
})
// The snapshot is a DOM captured at one width, so that width is the only one the overlay can
diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts
index 6cb7fcd4bf5e..24973a2e8165 100644
--- a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts
+++ b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts
@@ -25,6 +25,8 @@ import {
import type { KeyedAppUrl } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import type { HrefMatchType } from 'lib/components/heatmaps/heatmapDataLogic'
+import { hasWildcard, resolveHeatmapUrlFilter } from 'lib/components/heatmaps/heatmapUrlMatch'
+import type { HeatmapUrlFilter, HeatmapUrlMatchMode } from 'lib/components/heatmaps/heatmapUrlMatch'
import { CommonFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'
import type { HeatmapFilters } from 'lib/components/heatmaps/types'
import { PostHogAppToolbarEvent, calculateViewportRange } from 'lib/components/IframedToolbarBrowser/utils'
@@ -98,35 +100,6 @@ export function preflightBannerMessage(preflight: PagePreflight | null): string
return null
}
-// Helper function to detect if a URL contains regex pattern characters
-export const isUrlPattern = (url: string): boolean => {
- return /[*+?^${}()|[\]\\]/.test(url)
-}
-
-const normalizeUrlPath = (urlObj: URL): string => {
- if (urlObj.pathname === '') {
- urlObj.pathname = '/'
- }
- return urlObj.toString()
-}
-
-export const normalizeHeatmapDataUrl = (
- url: string | null
-): { href: string; matchType: 'pattern' | 'exact' } | null => {
- const trimmed = url?.trim()
- if (!trimmed) {
- return null
- }
- if (isUrlPattern(trimmed)) {
- return { href: trimmed, matchType: 'pattern' }
- }
- try {
- return { href: normalizeUrlPath(new URL(trimmed)), matchType: 'exact' }
- } catch {
- return null
- }
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface heatmapsBrowserLogicValues {
checkUrlIsAuthorized: (url: string) => boolean // authorizedUrlListLogic
@@ -160,6 +133,8 @@ export interface heatmapsBrowserLogicValues {
pagePreflight: PagePreflight | null
pagePreflightLoading: boolean
preflightMessage: string | null
+ recordingUrlFilter: HeatmapUrlFilter | null
+ recordingUrlMatchMode: HeatmapUrlMatchMode
replayIframeData: ReplayIframeData | null
topUrls:
| {
@@ -201,6 +176,9 @@ export interface heatmapsBrowserLogicActions {
setWindowWidthOverride: (widthOverride: number | null) => {
widthOverride: number | null
} // heatmapDataLogic
+ applyRecordingUrlFilter: () => {
+ value: true
+ }
checkPagePreflight: (url: string | null) => {
url: string | null
}
@@ -298,6 +276,9 @@ export interface heatmapsBrowserLogicActions {
setIframeBanner: (banner: IFrameBanner | null) => {
banner: IFrameBanner | null
}
+ setRecordingUrlMatchMode: (mode: HeatmapUrlMatchMode) => {
+ mode: HeatmapUrlMatchMode
+ }
setReplayIframeData: (replayIframeData: ReplayIframeData | null) => {
replayIframeData: ReplayIframeData | null
}
@@ -321,6 +302,10 @@ export interface heatmapsBrowserLogicMeta {
currentPagePreflight: (pagePreflight: PagePreflight | null, displayUrl: string | null) => PagePreflight | null
preflightMessage: (currentPagePreflight: PagePreflight | null) => string | null
iframeBanner: (preflightMessage: string | null, loadTimeoutBanner: IFrameBanner | null) => IFrameBanner | null
+ recordingUrlFilter: (
+ replayIframeData: ReplayIframeData | null,
+ recordingUrlMatchMode: HeatmapUrlMatchMode
+ ) => HeatmapUrlFilter | null
browserUrlSearchOptions: (
browserSearchResults: string[] | null,
topUrls:
@@ -331,10 +316,7 @@ export interface heatmapsBrowserLogicMeta {
| null,
browserSearchTerm: string
) => string[] | null
- isBrowserUrlAuthorized: (
- dataUrl: string | null,
- checkUrlIsAuthorized: (url: string) => boolean // authorizedUrlListLogic
- ) => boolean
+ isBrowserUrlAuthorized: (dataUrl: string | null, checkUrlIsAuthorized: (url: string) => boolean) => boolean
isBrowserUrlValid: (dataUrl: string | null) => boolean
viewportRange: (
heatmapFilters: HeatmapFilters,
@@ -424,6 +406,8 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
stopTrackingLoading: true,
setReplayIframeData: (replayIframeData: ReplayIframeData | null) => ({ replayIframeData }),
setReplayIframeDataURL: (url: string | null) => ({ url }),
+ setRecordingUrlMatchMode: (mode: HeatmapUrlMatchMode) => ({ mode }),
+ applyRecordingUrlFilter: true,
checkPagePreflight: (url: string | null) => ({ url }),
}),
@@ -518,6 +502,12 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
},
},
],
+ recordingUrlMatchMode: [
+ 'page' as HeatmapUrlMatchMode,
+ {
+ setRecordingUrlMatchMode: (_, { mode }) => mode,
+ },
+ ],
filterPanelCollapsed: [
false as boolean,
{ persist: true },
@@ -585,6 +575,11 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
(preflightMessage: string | null, loadTimeoutBanner: IFrameBanner | null): IFrameBanner | null =>
preflightMessage ? { level: 'error', message: preflightMessage } : loadTimeoutBanner,
],
+ recordingUrlFilter: [
+ (s) => [s.replayIframeData, s.recordingUrlMatchMode],
+ (replayIframeData: ReplayIframeData | null, mode: HeatmapUrlMatchMode): HeatmapUrlFilter | null =>
+ isUsableHeatmapUrl(replayIframeData?.url) ? resolveHeatmapUrlFilter(replayIframeData.url, mode) : null,
+ ],
browserUrlSearchOptions: [
(s) => [s.browserSearchResults, s.topUrls, s.browserSearchTerm],
(
@@ -667,10 +662,7 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
},
setReplayIframeData: ({ replayIframeData }) => {
if (isUsableHeatmapUrl(replayIframeData?.url)) {
- actions.setHref(replayIframeData.url)
- // Auto-detect match type for replay data URLs too
- const isPattern = isUrlPattern(replayIframeData.url)
- actions.setHrefMatchType(isPattern ? 'pattern' : 'exact')
+ actions.applyRecordingUrlFilter()
// The snapshot is a DOM captured at one width, and that width is the only one the
// overlay can line up with. Without this the width falls back to the generic default,
// so the query asks for viewports the recorded visitor never had and the heatmap
@@ -687,10 +679,10 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
await breakpoint(200)
actions.loadBrowserSearchResults()
- // Also update match type based on search term if it has regex patterns
- if (searchTerm && isUrlPattern(searchTerm)) {
- actions.setHrefMatchType('pattern')
- actions.setHref(searchTerm)
+ const filter = searchTerm && hasWildcard(searchTerm) ? resolveHeatmapUrlFilter(searchTerm) : null
+ if (filter) {
+ actions.setHrefMatchType(filter.matchType)
+ actions.setHref(filter.href)
}
},
@@ -711,10 +703,10 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
// The recording background path has no dataUrl; its href comes from the snapshot. Setting
// href to an empty string here would blank the query and leave the heatmap loading forever.
- const url = values.dataUrl?.trim()
- if (url) {
- actions.setHref(url)
- actions.setHrefMatchType(isUrlPattern(url) ? 'pattern' : 'exact')
+ const dataUrlFilter = resolveHeatmapUrlFilter(values.dataUrl)
+ if (dataUrlFilter) {
+ actions.setHref(dataUrlFilter.href)
+ actions.setHrefMatchType(dataUrlFilter.matchType)
} else if (!values.hasValidReplayIframeData) {
// No page URL and no recording snapshot: clear the stale href so a previous page's
// heatmap does not repaint over the page now in the frame.
@@ -737,14 +729,19 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
}
},
- setReplayIframeDataURL: async ({ url }, breakpoint) => {
+ setReplayIframeDataURL: async (_, breakpoint) => {
await breakpoint(150)
- if (url?.trim().length) {
- actions.setHref(url)
- // Auto-detect match type for replay URLs too
- const isPattern = isUrlPattern(url)
- actions.setHrefMatchType(isPattern ? 'pattern' : 'exact')
- }
+ actions.applyRecordingUrlFilter()
+ },
+
+ setRecordingUrlMatchMode: () => {
+ actions.applyRecordingUrlFilter()
+ },
+
+ applyRecordingUrlFilter: () => {
+ const filter = values.recordingUrlFilter
+ actions.setHref(filter?.href ?? '')
+ actions.setHrefMatchType(filter?.matchType ?? 'exact')
},
setDataUrl: ({ url }) => {
@@ -756,10 +753,10 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
) {
return
}
- const normalized = normalizeHeatmapDataUrl(url)
- if (normalized) {
- actions.setHref(normalized.href)
- actions.setHrefMatchType(normalized.matchType)
+ const filter = resolveHeatmapUrlFilter(url)
+ if (filter) {
+ actions.setHref(filter.href)
+ actions.setHrefMatchType(filter.matchType)
}
},
diff --git a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts
index 484970187a05..7a14a5fd3213 100644
--- a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts
+++ b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts
@@ -1,3 +1,5 @@
+import { resolveHeatmapUrlFilter } from 'lib/components/heatmaps/heatmapUrlMatch'
+
import type { ElementStatsApi } from 'products/product_analytics/frontend/generated/api.schemas'
import { buildElementStatsParams, computeClickmapBoxes } from './recordingClickmapLogic'
@@ -18,7 +20,7 @@ describe('recordingClickmapLogic', () => {
{
name: 'filters stats to the exact page URL',
href: 'https://example.com/pricing',
- isPattern: false,
+ mode: 'exact' as const,
expectedProperty: {
key: '$current_url',
value: 'https://example.com/pricing',
@@ -29,16 +31,40 @@ describe('recordingClickmapLogic', () => {
{
name: 'converts * wildcards to an anchored regex',
href: 'https://example.com/blog/*',
- isPattern: true,
+ mode: 'exact' as const,
+ expectedProperty: {
+ key: '$current_url',
+ value: '^https\\:\\/\\/example\\.com\\/blog\\/.+$',
+ operator: 'regex',
+ type: 'event',
+ },
+ },
+ {
+ name: 'keeps a query string literal instead of reading it as a regex',
+ href: 'https://example.com/pricing?plan=a+b',
+ mode: 'exact' as const,
+ expectedProperty: {
+ key: '$current_url',
+ value: 'https://example.com/pricing?plan=a+b',
+ operator: 'exact',
+ type: 'event',
+ },
+ },
+ {
+ name: 'matches the page with any query string in page mode',
+ href: 'https://example.com/pricing?plan=a',
+ mode: 'page' as const,
expectedProperty: {
key: '$current_url',
- value: '^https\\:\\/\\/example\\.com\\/blog\\/.*$',
+ value: '^https\\:\\/\\/example\\.com\\/pricing\\/?(\\?.*)?(#.*)?$',
operator: 'regex',
type: 'event',
},
},
- ])('$name', ({ href, isPattern, expectedProperty }) => {
- const params = buildElementStatsParams(href, isPattern, { date_from: '-7d' }, ['data-attr'])
+ ])('$name', ({ href, mode, expectedProperty }) => {
+ const params = buildElementStatsParams(resolveHeatmapUrlFilter(href, mode)!, { date_from: '-7d' }, [
+ 'data-attr',
+ ])
expect(JSON.parse((params as { properties?: string }).properties ?? '[]')).toEqual([expectedProperty])
})
})
diff --git a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts
index f94694917185..03f1b0d4228c 100644
--- a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts
+++ b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts
@@ -6,6 +6,7 @@ import { collectAllElementsDeep } from 'query-selector-shadow-dom'
import { RefObject } from 'react'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import type { HeatmapUrlFilter } from 'lib/components/heatmaps/heatmapUrlMatch'
import type { CommonFilters } from 'lib/components/heatmaps/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -21,7 +22,6 @@ import {
matchIsChainConsistent,
} from '~/toolbar/elements/domElementIndex'
import type { ElementMatchOptions } from '~/toolbar/elements/domElementIndex'
-import { escapeUnescapedRegex } from '~/toolbar/elements/heatmapToolbarMenuLogic'
import { ElementsEventType } from '~/toolbar/types'
import { PropertyFilterType, PropertyOperator } from '~/types'
import type { TeamPublicType, TeamType } from '~/types'
@@ -33,7 +33,7 @@ import type {
} from 'products/product_analytics/frontend/generated/api.schemas'
import type { ReplayIframeData } from '../replayIframeData'
-import { heatmapsBrowserLogic, isUrlPattern } from './heatmapsBrowserLogic'
+import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'
export interface ClickmapBox {
top: number
@@ -55,11 +55,11 @@ export type RecordingClickmapLogicProps = {
const CLICKMAP_STATS_LIMIT = 500
const CLICKMAP_STATS_AUTO_LOAD_LIMIT = 10000
-function currentUrlProperty(href: string, isPattern: boolean): Record<string, unknown> {
- return isPattern
+function currentUrlProperty({ href, regex }: HeatmapUrlFilter): Record<string, unknown> {
+ return regex
? {
key: '$current_url',
- value: `^${href.split('*').map(escapeUnescapedRegex).join('.*')}$`,
+ value: regex,
operator: PropertyOperator.Regex,
type: PropertyFilterType.Event,
}
@@ -72,8 +72,7 @@ function currentUrlProperty(href: string, isPattern: boolean): Record<string, un
}
export function buildElementStatsParams(
- href: string,
- isPattern: boolean,
+ urlFilter: HeatmapUrlFilter,
commonFilters: {
date_from?: string | null
date_to?: string | null
@@ -83,7 +82,7 @@ export function buildElementStatsParams(
dataAttributes: string[],
limit: number = CLICKMAP_STATS_LIMIT
): ElementsStatsRetrieveParams {
- const properties: Record<string, unknown>[] = [currentUrlProperty(href, isPattern)]
+ const properties: Record<string, unknown>[] = [currentUrlProperty(urlFilter)]
for (const cohortId of commonFilters.cohort_ids ?? []) {
properties.push({
type: PropertyFilterType.Cohort,
@@ -203,6 +202,7 @@ export async function computeClickmapBoxes(
export interface recordingClickmapLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
commonFilters: CommonFilters // heatmapDataLogic
+ recordingUrlFilter: HeatmapUrlFilter | null // heatmapsBrowserLogic
replayIframeData: ReplayIframeData | null // heatmapsBrowserLogic
currentProjectId: number | null // projectLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
@@ -234,6 +234,9 @@ export interface recordingClickmapLogicActions {
onIframeLoad: () => {
value: true
} // heatmapsBrowserLogic
+ setRecordingUrlMatchMode: (mode: import('lib/components/heatmaps/heatmapUrlMatch').HeatmapUrlMatchMode) => {
+ mode: import('lib/components/heatmaps/heatmapUrlMatch').HeatmapUrlMatchMode
+ } // heatmapsBrowserLogic
setReplayIframeData: (replayIframeData: ReplayIframeData | null) => {
replayIframeData: ReplayIframeData | null
} // heatmapsBrowserLogic
@@ -310,7 +313,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
heatmapDataLogic({ context: 'in-app' }),
['commonFilters'],
heatmapsBrowserLogic,
- ['replayIframeData'],
+ ['replayIframeData', 'recordingUrlFilter'],
teamLogic,
['currentTeam'],
projectLogic,
@@ -320,7 +323,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
],
actions: [
heatmapsBrowserLogic,
- ['onIframeLoad', 'setReplayIframeData', 'setReplayIframeDataURL'],
+ ['onIframeLoad', 'setReplayIframeData', 'setReplayIframeDataURL', 'setRecordingUrlMatchMode'],
heatmapDataLogic({ context: 'in-app' }),
['setCommonFilters', 'setWindowWidthOverride', 'setHeatmapTooltipSuppressed'],
],
@@ -355,6 +358,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
setClickmapEnabled: (state, { enabled }) => (enabled ? state : []),
setReplayIframeData: () => [],
setReplayIframeDataURL: () => [],
+ setRecordingUrlMatchMode: () => [],
},
],
selectedBoxKey: [
@@ -365,6 +369,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
setClickmapEnabled: () => null,
setReplayIframeData: () => null,
setReplayIframeDataURL: () => null,
+ setRecordingUrlMatchMode: () => null,
},
],
hoveredBoxKey: [
@@ -375,6 +380,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
setClickmapEnabled: () => null,
setReplayIframeData: () => null,
setReplayIframeDataURL: () => null,
+ setRecordingUrlMatchMode: () => null,
},
],
// the loader keeps stale stats across recording changes otherwise, and
@@ -382,6 +388,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
elementStats: {
setReplayIframeData: () => null,
setReplayIframeDataURL: () => null,
+ setRecordingUrlMatchMode: () => null,
},
}),
loaders(({ values }) => ({
@@ -392,13 +399,12 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
await breakpoint(150)
// heatmapDataLogic's href is shared and driven by the browser data-URL flow,
// so the replay payload's URL is the stable source of truth here
- const url = values.replayIframeData?.url?.trim()
- if (!url) {
+ const urlFilter = values.recordingUrlFilter
+ if (!urlFilter) {
return null
}
const params = buildElementStatsParams(
- url,
- isUrlPattern(url),
+ urlFilter,
values.commonFilters,
values.wantedDataAttributes,
limit
@@ -457,6 +463,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
},
setReplayIframeData: () => actions.maybeLoadElementStats(),
setReplayIframeDataURL: () => actions.maybeLoadElementStats(),
+ setRecordingUrlMatchMode: () => actions.maybeLoadElementStats(),
setCommonFilters: () => actions.maybeLoadElementStats(),
setMatchLinksByHref: () => actions.recomputeClickmap(),
setWindowWidthOverride: () => actions.recomputeClickmap(),
diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapNewScene.tsx b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapNewScene.tsx
index 532d7d34c09f..ce40cf78ebb8 100644
--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapNewScene.tsx
+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapNewScene.tsx
@@ -6,6 +6,7 @@ import { LemonBanner, LemonButton, LemonCard, LemonLabel, Spinner } from '@posth
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { appEditorUrl } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'
+import { hasWildcard } from 'lib/components/heatmaps/heatmapUrlMatch'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
@@ -21,7 +22,7 @@ import { AccessControlLevel, AccessControlResourceType, HeatmapType } from '~/ty
import { HeatmapAdvancedSettings } from '../../components/HeatmapAdvancedSettings'
import { HeatmapRecording } from '../../components/HeatmapRecording'
import { HeatmapRecordingFallback } from '../../components/HeatmapRecordingFallback'
-import { heatmapsBrowserLogic, isUrlPattern } from '../../components/heatmapsBrowserLogic'
+import { heatmapsBrowserLogic } from '../../components/heatmapsBrowserLogic'
import { HeatmapScreenshotAccessNotice } from '../../components/HeatmapScreenshotAccessNotice'
import { HeatmapsEnableCapture } from '../../components/HeatmapsEnableCapture'
import { HeatmapsInvalidURL } from '../../components/HeatmapsInvalidURL'
@@ -526,7 +527,7 @@ function ReviewStep(): JSX.Element {
<dt className="font-semibold">Matching rule</dt>
<dd>
<span className="font-medium">
- {isUrlPattern(effectiveDataUrl ?? '') ? 'Pattern' : 'Exact URL'}:
+ {hasWildcard(effectiveDataUrl ?? '') ? 'Pattern' : 'Exact URL'}:
</span>{' '}
<span className="ph-no-capture break-all">{effectiveDataUrl}</span>
</dd>
diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapCreationLogic.ts b/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapCreationLogic.ts
index 513fc57af8a1..6421b91e8455 100644
--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapCreationLogic.ts
+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapCreationLogic.ts
@@ -20,6 +20,7 @@ import {
authorizedUrlListLogic,
defaultAuthorizedUrlProperties,
} from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'
+import { hasWildcard, heatmapUrlPatternToRegex, resolveHeatmapUrlFilter } from 'lib/components/heatmaps/heatmapUrlMatch'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
@@ -35,7 +36,7 @@ import type { TeamPublicType, TeamType } from '~/types'
import { savedPrewarmCreate } from 'products/web_analytics/frontend/generated/api'
-import { heatmapsBrowserLogic, isUrlPattern } from '../../components/heatmapsBrowserLogic'
+import { heatmapsBrowserLogic } from '../../components/heatmapsBrowserLogic'
import type { PagePreflight } from '../../components/heatmapsBrowserLogic'
import { ReplayIframeData, getStoredRecordingBackground } from '../../replayIframeData'
import { HeatmapCreationContext, heatmapLogic } from './heatmapLogic'
@@ -71,19 +72,6 @@ const authorizedUrlsLogic = authorizedUrlListLogic({
type: AuthorizedUrlListType.TOOLBAR_URLS,
})
-export function heatmapUrlPatternToRegex(value: string): string {
- let normalized = value
- if (!normalized.startsWith('^')) {
- normalized = `^${normalized}`
- }
- if (!normalized.endsWith('$')) {
- normalized = `${normalized}$`
- }
- return Array.from(normalized)
- .map((character, index) => (character === '*' && index > 0 && normalized[index - 1] !== '.' ? '.+' : character))
- .join('')
-}
-
export function getPageStepBlockReason({
displayUrl,
isDisplayUrlValid,
@@ -443,7 +431,7 @@ export const heatmapCreationLogic = kea<heatmapCreationLogicType>([
const query =
matchType === 'pattern'
? hogql`SELECT count() FROM heatmaps WHERE match(current_url, ${heatmapUrlPatternToRegex(
- url
+ resolveHeatmapUrlFilter(url)?.href ?? url
)}) AND timestamp >= now() - INTERVAL 30 DAY`
: hogql`SELECT count() FROM heatmaps WHERE trimRight(current_url, '/') = trimRight(${url}, '/') AND timestamp >= now() - INTERVAL 30 DAY`
let response: Awaited<ReturnType<typeof api.queryHogQL>> | null = null
@@ -697,7 +685,7 @@ export const heatmapCreationLogic = kea<heatmapCreationLogicType>([
}
actions.checkPageData({
url: values.effectiveDataUrl,
- matchType: isUrlPattern(values.effectiveDataUrl) ? 'pattern' : 'exact',
+ matchType: hasWildcard(values.effectiveDataUrl) ? 'pattern' : 'exact',
trigger,
})
},
diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts b/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts
index eccc45c7e769..8ff1d92b7bea 100644
--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts
+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts
@@ -6,6 +6,7 @@ import type { JSX } from 'react'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { hasWildcard } from 'lib/components/heatmaps/heatmapUrlMatch'
import type { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'
import { DEFAULT_HEATMAP_WIDTH } from 'lib/components/IframedToolbarBrowser/utils'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -40,7 +41,7 @@ import type {
SavedHeatmapRequestApi,
} from 'products/web_analytics/frontend/generated/api.schemas'
-import { IFrameBanner, PagePreflight, heatmapsBrowserLogic, isUrlPattern } from '../../components/heatmapsBrowserLogic'
+import { IFrameBanner, PagePreflight, heatmapsBrowserLogic } from '../../components/heatmapsBrowserLogic'
import { heatmapsSceneLogic } from '../heatmaps/heatmapsSceneLogic'
import { DEFAULT_HEATMAP_NAME, HeatmapSettings, normalizeHeatmapSettings } from './heatmapSettings'
@@ -91,7 +92,7 @@ function isValidPageUrl(url: string | null): boolean {
if (!url) {
return true
}
- if (isUrlPattern(url)) {
+ if (hasWildcard(url)) {
return false
}
try {
@@ -906,12 +907,12 @@ export const heatmapLogic = kea<heatmapLogicType>([
(error: string | JSX.Element | null, generating: boolean): boolean => !!error || generating,
],
isDisplayUrlValid: [(s) => [s.displayUrl], (displayUrl: string | null) => isValidPageUrl(displayUrl)],
- displayUrlIsPattern: [(s) => [s.displayUrl], (displayUrl: string | null) => isUrlPattern(displayUrl ?? '')],
+ displayUrlIsPattern: [(s) => [s.displayUrl], (displayUrl: string | null) => hasWildcard(displayUrl ?? '')],
isPageUrlDraftValid: [
(s) => [s.pageUrlDraft],
(pageUrlDraft: string) => isValidPageUrl(pageUrlDraft.trim() || null),
],
- pageUrlDraftIsPattern: [(s) => [s.pageUrlDraft], (pageUrlDraft: string) => isUrlPattern(pageUrlDraft)],
+ pageUrlDraftIsPattern: [(s) => [s.pageUrlDraft], (pageUrlDraft: string) => hasWildcard(pageUrlDraft)],
desiredNumericWidth: [
(s) => [s.widthOverride, s.containerWidth],
(widthOverride: number, containerWidth: number | null) => {