Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

implement sepearte replay/heatmap enabled routes and collection

Francis Cao5bd92ce95042
diff --git a/prisma/migrations/20_add_heatmap/migration.sql b/prisma/migrations/20_add_heatmap/migration.sql
index e5d5dface..f3e3d30f5 100644
--- a/prisma/migrations/20_add_heatmap/migration.sql
+++ b/prisma/migrations/20_add_heatmap/migration.sql
@@ -1,3 +1,9 @@
+ALTER TABLE "website" RENAME COLUMN "replay_enabled" TO "recorder_enabled";
+
+UPDATE "website"
+SET "replay_config" = COALESCE("replay_config", '{}'::jsonb) || '{"replayEnabled": true}'::jsonb
+WHERE "recorder_enabled" = true;
+
-- CreateTable
CREATE TABLE "heatmap_event" (
"heatmap_event_id" UUID NOT NULL,
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 23d29c964..16993f067 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -75,8 +75,8 @@ model Website {
updatedAt DateTime? @updatedAt @map("updated_at") @db.Timestamptz(6)
deletedAt DateTime? @map("deleted_at") @db.Timestamptz(6)
- replayEnabled Boolean @default(false) @map("replay_enabled")
- replayConfig Json? @map("replay_config")
+ recorderEnabled Boolean @default(false) @map("recorder_enabled")
+ replayConfig Json? @map("replay_config")
user User? @relation("user", fields: [userId], references: [id])
createUser User? @relation("createUser", fields: [createdBy], references: [id])
diff --git a/public/intl/messages/bs-BA.json b/public/intl/messages/bs-BA.json
index 931956515..30abc781a 100644
--- a/public/intl/messages/bs-BA.json
+++ b/public/intl/messages/bs-BA.json
@@ -256,7 +256,7 @@
"play": "Reprodukuj",
"replay": "Ponovna reprodukcija",
"replay-id": "Replay ID",
- "replay-code": "Kod ponavljanja sesije",
+ "recorder-code": "Kod ponavljanja sesije",
"replay-enabled": "Ponovna reprodukcija omogućena",
"replays": "Ponovne reprodukcije",
"reports": "Izvještaji",
diff --git a/public/intl/messages/ca-ES.json b/public/intl/messages/ca-ES.json
index 5c7b62b47..f141503b3 100644
--- a/public/intl/messages/ca-ES.json
+++ b/public/intl/messages/ca-ES.json
@@ -256,7 +256,7 @@
"play": "Reprodueix",
"replay": "Repetició",
"replay-id": "Replay ID",
- "replay-code": "Codi de repetició de sessió",
+ "recorder-code": "Codi de repetició de sessió",
"replay-enabled": "Repetició activada",
"replays": "Repeticions",
"reports": "Informes",
diff --git a/public/intl/messages/cs-CZ.json b/public/intl/messages/cs-CZ.json
index e3789ff28..bac565d41 100644
--- a/public/intl/messages/cs-CZ.json
+++ b/public/intl/messages/cs-CZ.json
@@ -256,7 +256,7 @@
"play": "Přehrát",
"replay": "Přehrávání",
"replay-id": "Replay ID",
- "replay-code": "Kód přehrání relace",
+ "recorder-code": "Kód přehrání relace",
"replay-enabled": "Přehrávání povoleno",
"replays": "Přehrávání",
"reports": "Hlášení",
diff --git a/public/intl/messages/da-DK.json b/public/intl/messages/da-DK.json
index 8d3ed3cda..f214774df 100644
--- a/public/intl/messages/da-DK.json
+++ b/public/intl/messages/da-DK.json
@@ -256,7 +256,7 @@
"play": "Afspil",
"replay": "Afspilning",
"replay-id": "Replay ID",
- "replay-code": "Kode til sessionsgengivelse",
+ "recorder-code": "Kode til sessionsgengivelse",
"replay-enabled": "Afspilning aktiveret",
"replays": "Afspilninger",
"reports": "Rapporter",
diff --git a/public/intl/messages/de-CH.json b/public/intl/messages/de-CH.json
index 71cce4823..5fbca2798 100644
--- a/public/intl/messages/de-CH.json
+++ b/public/intl/messages/de-CH.json
@@ -256,7 +256,7 @@
"play": "Abspielen",
"replay": "Wiedergabe",
"replay-id": "Replay ID",
- "replay-code": "Session-Replay-Code",
+ "recorder-code": "Session-Replay-Code",
"replay-enabled": "Wiedergabe aktiviert",
"replays": "Wiedergaben",
"reports": "Brichte",
diff --git a/public/intl/messages/de-DE.json b/public/intl/messages/de-DE.json
index 907d3768c..7c0afe6f7 100644
--- a/public/intl/messages/de-DE.json
+++ b/public/intl/messages/de-DE.json
@@ -256,7 +256,7 @@
"play": "Abspielen",
"replay": "Wiedergabe",
"replay-id": "Replay ID",
- "replay-code": "Session-Replay-Code",
+ "recorder-code": "Session-Replay-Code",
"replay-enabled": "Wiedergabe aktiviert",
"replays": "Wiedergaben",
"reports": "Berichte",
diff --git a/public/intl/messages/en-GB.json b/public/intl/messages/en-GB.json
index 243b6e9a5..9c54feb16 100644
--- a/public/intl/messages/en-GB.json
+++ b/public/intl/messages/en-GB.json
@@ -256,7 +256,7 @@
"play": "Play",
"replay": "Replay",
"replay-id": "Replay ID",
- "replay-code": "Session replay code",
+ "recorder-code": "Recorder code",
"replay-enabled": "Replay enabled",
"replays": "Replays",
"reports": "Reports",
diff --git a/public/intl/messages/en-US.json b/public/intl/messages/en-US.json
index b62ed30a0..d1fdfd2ca 100644
--- a/public/intl/messages/en-US.json
+++ b/public/intl/messages/en-US.json
@@ -264,7 +264,7 @@
"play": "Play",
"replay": "Replay",
"replay-id": "Replay ID",
- "replay-code": "Session replay code",
+ "recorder-code": "Recorder code",
"replay-enabled": "Replay enabled",
"replays": "Replays",
"reports": "Reports",
diff --git a/public/intl/messages/es-ES.json b/public/intl/messages/es-ES.json
index 33dbcea29..5efbe9c15 100644
--- a/public/intl/messages/es-ES.json
+++ b/public/intl/messages/es-ES.json
@@ -256,7 +256,7 @@
"play": "Reproducir",
"replay": "Repetición",
"replay-id": "Replay ID",
- "replay-code": "Código de repetición de sesión",
+ "recorder-code": "Código de repetición de sesión",
"replay-enabled": "Repetición activada",
"replays": "Repeticiones",
"reports": "Informes",
diff --git a/public/intl/messages/fi-FI.json b/public/intl/messages/fi-FI.json
index 2fa0135e8..2c0971ffe 100644
--- a/public/intl/messages/fi-FI.json
+++ b/public/intl/messages/fi-FI.json
@@ -256,7 +256,7 @@
"play": "Toista",
"replay": "Toisto",
"replay-id": "Replay ID",
- "replay-code": "Istunnon toistokoodi",
+ "recorder-code": "Istunnon toistokoodi",
"replay-enabled": "Toisto käytössä",
"replays": "Toistot",
"reports": "Raportit",
diff --git a/public/intl/messages/fo-FO.json b/public/intl/messages/fo-FO.json
index 758148dee..14a884e04 100644
--- a/public/intl/messages/fo-FO.json
+++ b/public/intl/messages/fo-FO.json
@@ -256,7 +256,7 @@
"play": "Spæla",
"replay": "Uppspæling",
"replay-id": "Replay ID",
- "replay-code": "Kodi fyri endurspæling av setuni",
+ "recorder-code": "Kodi fyri endurspæling av setuni",
"replay-enabled": "Uppspæling virkjað",
"replays": "Uppspælingar",
"reports": "Frágreiðingar",
diff --git a/public/intl/messages/fr-FR.json b/public/intl/messages/fr-FR.json
index a02786858..b4521bd9a 100644
--- a/public/intl/messages/fr-FR.json
+++ b/public/intl/messages/fr-FR.json
@@ -259,7 +259,7 @@
"remove": "Retirer",
"remove-member": "Retirer le membre",
"replay": "Relecture",
- "replay-code": "Code de relecture de session",
+ "recorder-code": "Code de relecture de session",
"replay-enabled": "Relecture activée",
"replay-id": "Replay ID",
"replays": "Relectures",
diff --git a/public/intl/messages/ga-ES.json b/public/intl/messages/ga-ES.json
index 0ac9bdf82..7088a5204 100644
--- a/public/intl/messages/ga-ES.json
+++ b/public/intl/messages/ga-ES.json
@@ -256,7 +256,7 @@
"play": "Reproducir",
"replay": "Reprodución",
"replay-id": "Replay ID",
- "replay-code": "Código de repetición da sesión",
+ "recorder-code": "Código de repetición da sesión",
"replay-enabled": "Reprodución activada",
"replays": "Reproducións",
"reports": "Reportes",
diff --git a/public/intl/messages/hr-HR.json b/public/intl/messages/hr-HR.json
index a5c022162..4e7d10889 100644
--- a/public/intl/messages/hr-HR.json
+++ b/public/intl/messages/hr-HR.json
@@ -256,7 +256,7 @@
"play": "Reproduciraj",
"replay": "Ponovna reprodukcija",
"replay-id": "Replay ID",
- "replay-code": "Kôd ponavljanja sesije",
+ "recorder-code": "Kôd ponavljanja sesije",
"replay-enabled": "Ponovna reprodukcija omogućena",
"replays": "Ponovne reprodukcije",
"reports": "Izvješća",
diff --git a/public/intl/messages/hu-HU.json b/public/intl/messages/hu-HU.json
index d72587e01..181c3e53a 100644
--- a/public/intl/messages/hu-HU.json
+++ b/public/intl/messages/hu-HU.json
@@ -256,7 +256,7 @@
"play": "Lejátszás",
"replay": "Visszajátszás",
"replay-id": "Replay ID",
- "replay-code": "Munkamenet-újrajátszási kód",
+ "recorder-code": "Munkamenet-újrajátszási kód",
"replay-enabled": "Visszajátszás engedélyezve",
"replays": "Visszajátszások",
"reports": "Jelentések",
diff --git a/public/intl/messages/id-ID.json b/public/intl/messages/id-ID.json
index 64e68bbbe..a609fe768 100644
--- a/public/intl/messages/id-ID.json
+++ b/public/intl/messages/id-ID.json
@@ -256,7 +256,7 @@
"play": "Putar",
"replay": "Pemutaran ulang",
"replay-id": "Replay ID",
- "replay-code": "Kode putar ulang sesi",
+ "recorder-code": "Kode putar ulang sesi",
"replay-enabled": "Pemutaran ulang diaktifkan",
"replays": "Pemutaran ulang",
"reports": "Laporan",
diff --git a/public/intl/messages/it-IT.json b/public/intl/messages/it-IT.json
index 0ad631dcd..4f460295c 100644
--- a/public/intl/messages/it-IT.json
+++ b/public/intl/messages/it-IT.json
@@ -256,7 +256,7 @@
"play": "Riproduci",
"replay": "Replay",
"replay-id": "Replay ID",
- "replay-code": "Codice replay sessione",
+ "recorder-code": "Codice replay sessione",
"replay-enabled": "Replay abilitato",
"replays": "Replay",
"reports": "Report",
diff --git a/public/intl/messages/lt-LT.json b/public/intl/messages/lt-LT.json
index cdb4c8191..4e6e8e078 100644
--- a/public/intl/messages/lt-LT.json
+++ b/public/intl/messages/lt-LT.json
@@ -256,7 +256,7 @@
"play": "Leisti",
"replay": "Pakartojimas",
"replay-id": "Replay ID",
- "replay-code": "Sesijos pakartojimo kodas",
+ "recorder-code": "Sesijos pakartojimo kodas",
"replay-enabled": "Pakartojimas įjungtas",
"replays": "Pakartojimai",
"reports": "Ataskaitos",
diff --git a/public/intl/messages/ms-MY.json b/public/intl/messages/ms-MY.json
index 56ed4f7ac..aa81cb9ef 100644
--- a/public/intl/messages/ms-MY.json
+++ b/public/intl/messages/ms-MY.json
@@ -256,7 +256,7 @@
"play": "Main",
"replay": "Main semula",
"replay-id": "Replay ID",
- "replay-code": "Kod main semula sesi",
+ "recorder-code": "Kod main semula sesi",
"replay-enabled": "Main semula diaktifkan",
"replays": "Main semula",
"reports": "Laporan",
diff --git a/public/intl/messages/nb-NO.json b/public/intl/messages/nb-NO.json
index 279336971..552fcf4df 100644
--- a/public/intl/messages/nb-NO.json
+++ b/public/intl/messages/nb-NO.json
@@ -256,7 +256,7 @@
"play": "Spill av",
"replay": "Avspilling",
"replay-id": "Replay ID",
- "replay-code": "Kode for øktavspilling",
+ "recorder-code": "Kode for øktavspilling",
"replay-enabled": "Avspilling aktivert",
"replays": "Avspillinger",
"reports": "Rapporter",
diff --git a/public/intl/messages/nl-NL.json b/public/intl/messages/nl-NL.json
index 446f84ff4..e4f0df26b 100644
--- a/public/intl/messages/nl-NL.json
+++ b/public/intl/messages/nl-NL.json
@@ -256,7 +256,7 @@
"play": "Afspelen",
"replay": "Herhaling",
"replay-id": "Replay ID",
- "replay-code": "Sessieherhalingscode",
+ "recorder-code": "Sessieherhalingscode",
"replay-enabled": "Herhaling ingeschakeld",
"replays": "Herhalingen",
"reports": "Rapporten",
diff --git a/public/intl/messages/pl-PL.json b/public/intl/messages/pl-PL.json
index aff7aa1da..b6a5ed716 100644
--- a/public/intl/messages/pl-PL.json
+++ b/public/intl/messages/pl-PL.json
@@ -256,7 +256,7 @@
"play": "Odtwórz",
"replay": "Odtwarzanie",
"replay-id": "Replay ID",
- "replay-code": "Kod odtworzenia sesji",
+ "recorder-code": "Kod odtworzenia sesji",
"replay-enabled": "Odtwarzanie włączone",
"replays": "Odtwarzania",
"reports": "Raporty",
diff --git a/public/intl/messages/pt-BR.json b/public/intl/messages/pt-BR.json
index 698c190fd..3b4fce82c 100644
--- a/public/intl/messages/pt-BR.json
+++ b/public/intl/messages/pt-BR.json
@@ -256,7 +256,7 @@
"play": "Reproduzir",
"replay": "Reprodução",
"replay-id": "Replay ID",
- "replay-code": "Código de replay da sessão",
+ "recorder-code": "Código de replay da sessão",
"replay-enabled": "Reprodução habilitada",
"replays": "Reproduções",
"reports": "Relatórios",
diff --git a/public/intl/messages/pt-PT.json b/public/intl/messages/pt-PT.json
index 7e24883cf..ddc8fef52 100644
--- a/public/intl/messages/pt-PT.json
+++ b/public/intl/messages/pt-PT.json
@@ -256,7 +256,7 @@
"play": "Reproduzir",
"replay": "Reprodução",
"replay-id": "Replay ID",
- "replay-code": "Código de repetição de sessão",
+ "recorder-code": "Código de repetição de sessão",
"replay-enabled": "Reprodução ativada",
"replays": "Reproduções",
"reports": "Relatórios",
diff --git a/public/intl/messages/ro-RO.json b/public/intl/messages/ro-RO.json
index 84ee2bc69..43e1ab49c 100644
--- a/public/intl/messages/ro-RO.json
+++ b/public/intl/messages/ro-RO.json
@@ -256,7 +256,7 @@
"play": "Redă",
"replay": "Reluare",
"replay-id": "Replay ID",
- "replay-code": "Cod de reluare sesiune",
+ "recorder-code": "Cod de reluare sesiune",
"replay-enabled": "Reluare activată",
"replays": "Reluări",
"reports": "Rapoarte",
diff --git a/public/intl/messages/sk-SK.json b/public/intl/messages/sk-SK.json
index 1f429dfa2..fcfc46ed6 100644
--- a/public/intl/messages/sk-SK.json
+++ b/public/intl/messages/sk-SK.json
@@ -256,7 +256,7 @@
"play": "Prehrať",
"replay": "Prehrávanie",
"replay-id": "Replay ID",
- "replay-code": "Kód prehrania relácie",
+ "recorder-code": "Kód prehrania relácie",
"replay-enabled": "Prehrávanie povolené",
"replays": "Prehrávanie",
"reports": "Správy",
diff --git a/public/intl/messages/sl-SI.json b/public/intl/messages/sl-SI.json
index f8fc8407f..6f9c7e2de 100644
--- a/public/intl/messages/sl-SI.json
+++ b/public/intl/messages/sl-SI.json
@@ -256,7 +256,7 @@
"play": "Predvajaj",
"replay": "Predvajanje",
"replay-id": "Replay ID",
- "replay-code": "Koda ponovitve seje",
+ "recorder-code": "Koda ponovitve seje",
"replay-enabled": "Predvajanje omogočeno",
"replays": "Predvajanja",
"reports": "Poročila",
diff --git a/public/intl/messages/sv-SE.json b/public/intl/messages/sv-SE.json
index b600465ff..322fb70d6 100644
--- a/public/intl/messages/sv-SE.json
+++ b/public/intl/messages/sv-SE.json
@@ -256,7 +256,7 @@
"play": "Spela upp",
"replay": "Uppspelning",
"replay-id": "Replay ID",
- "replay-code": "Kod för sessionsuppspelning",
+ "recorder-code": "Kod för sessionsuppspelning",
"replay-enabled": "Uppspelning aktiverad",
"replays": "Uppspelningar",
"reports": "Rapporter",
diff --git a/public/intl/messages/tr-TR.json b/public/intl/messages/tr-TR.json
index 0725081cb..a795f4ef2 100644
--- a/public/intl/messages/tr-TR.json
+++ b/public/intl/messages/tr-TR.json
@@ -256,7 +256,7 @@
"play": "Oynat",
"replay": "Tekrar oynatma",
"replay-id": "Replay ID",
- "replay-code": "Oturum tekrar oynatma kodu",
+ "recorder-code": "Oturum tekrar oynatma kodu",
"replay-enabled": "Tekrar oynatma etkin",
"replays": "Tekrar oynatmalar",
"reports": "Raporlar",
diff --git a/public/intl/messages/uz-UZ.json b/public/intl/messages/uz-UZ.json
index 9b54f139c..78b1412d8 100644
--- a/public/intl/messages/uz-UZ.json
+++ b/public/intl/messages/uz-UZ.json
@@ -256,7 +256,7 @@
"play": "Ijro etish",
"replay": "Qayta ijro",
"replay-id": "Replay ID",
- "replay-code": "Sessiya takrorlash kodi",
+ "recorder-code": "Sessiya takrorlash kodi",
"replay-enabled": "Qayta ijro yoqilgan",
"replays": "Qayta ijrolar",
"reports": "Hisobotlar",
diff --git a/src/app/(main)/websites/[websiteId]/settings/WebsiteReplaySettings.tsx b/src/app/(main)/websites/[websiteId]/settings/WebsiteReplaySettings.tsx
index 39cd4e816..d7309affe 100644
--- a/src/app/(main)/websites/[websiteId]/settings/WebsiteReplaySettings.tsx
+++ b/src/app/(main)/websites/[websiteId]/settings/WebsiteReplaySettings.tsx
@@ -10,48 +10,59 @@ import {
Text,
TextField,
} from '@umami/react-zen';
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { EmptyPlaceholder } from '@/components/common/EmptyPlaceholder';
import { useMessages, useSubscription, useUpdateQuery, useWebsite } from '@/components/hooks';
import { Video } from '@/components/icons';
+import { getRecorderConfig, type RecorderConfig } from '@/lib/recorder';
const RECORDER_NAME = 'recorder.js';
-interface ReplayConfig {
- sampleRate?: number;
- maskLevel?: string;
- maxDuration?: number;
- blockSelector?: string;
-}
-
export function WebsiteReplaySettings({ websiteId }: { websiteId: string }) {
const website = useWebsite();
const { t, labels, messages } = useMessages();
const { hasFeature, cloudMode } = useSubscription(website?.teamId);
const { mutateAsync, touch, toast, isPending } = useUpdateQuery(`/websites/${websiteId}`);
- const [enabled, setEnabled] = useState(website?.replayEnabled ?? false);
-
- const config = (website?.replayConfig as ReplayConfig) || {};
+ const config = getRecorderConfig(website?.replayConfig);
+ const [replayEnabled, setReplayEnabled] = useState(config.replayEnabled === true);
+ const [heatmapEnabled, setHeatmapEnabled] = useState(config.heatmapEnabled === true);
const [sampleRate, setSampleRate] = useState(config.sampleRate ?? 0.15);
+ const [heatmapSampleRate, setHeatmapSampleRate] = useState(config.heatmapSampleRate ?? 0.15);
const [maskLevel, setMaskLevel] = useState(config.maskLevel ?? 'moderate');
const [maxDuration, setMaxDuration] = useState(String(config.maxDuration ?? 300000));
const [blockSelector, setBlockSelector] = useState(config.blockSelector ?? '');
+ useEffect(() => {
+ setReplayEnabled(config.replayEnabled === true);
+ setHeatmapEnabled(config.heatmapEnabled === true);
+ setSampleRate(config.sampleRate ?? 0.15);
+ setHeatmapSampleRate(config.heatmapSampleRate ?? 0.15);
+ setMaskLevel(config.maskLevel ?? 'moderate');
+ setMaxDuration(String(config.maxDuration ?? 300000));
+ setBlockSelector(config.blockSelector ?? '');
+ }, [
+ config.blockSelector,
+ config.heatmapEnabled,
+ config.heatmapSampleRate,
+ config.maskLevel,
+ config.maxDuration,
+ config.replayEnabled,
+ config.sampleRate,
+ ]);
+
const recorderUrl = cloudMode
? `${process.env.cloudUrl}/${RECORDER_NAME}`
: `${window?.location?.origin || ''}${process.env.basePath || ''}/${RECORDER_NAME}`;
const recorderCode = `<script defer src="${recorderUrl}" data-website-id="${websiteId}"></script>`;
+ const sectionLabel = `${t(labels.replays)} & ${t(labels.heatmaps)}`;
- const handleToggle = async (value: boolean) => {
- const previous = enabled;
- setEnabled(value);
-
+ const saveRecorderConfig = async (nextConfig: RecorderConfig, rollback?: () => void) => {
try {
await mutateAsync(
{
- replayEnabled: value,
+ replayConfig: nextConfig,
},
{
onSuccess: async () => {
@@ -62,39 +73,48 @@ export function WebsiteReplaySettings({ websiteId }: { websiteId: string }) {
},
);
} catch {
- setEnabled(previous);
+ rollback?.();
}
};
+ const getNextConfig = (overrides: Partial<RecorderConfig> = {}): RecorderConfig => ({
+ ...config,
+ replayEnabled,
+ heatmapEnabled,
+ sampleRate,
+ heatmapSampleRate,
+ maskLevel,
+ maxDuration: parseInt(maxDuration, 10) || 300000,
+ blockSelector,
+ ...overrides,
+ });
+
+ const handleReplayToggle = async (value: boolean) => {
+ const previous = replayEnabled;
+
+ setReplayEnabled(value);
+ await saveRecorderConfig(getNextConfig({ replayEnabled: value }), () => setReplayEnabled(previous));
+ };
+
+ const handleHeatmapToggle = async (value: boolean) => {
+ const previous = heatmapEnabled;
+
+ setHeatmapEnabled(value);
+ await saveRecorderConfig(getNextConfig({ heatmapEnabled: value }), () => setHeatmapEnabled(previous));
+ };
+
const handleSave = async () => {
- await mutateAsync(
- {
- replayEnabled: enabled,
- replayConfig: {
- sampleRate,
- maskLevel,
- maxDuration: parseInt(maxDuration, 10) || 300000,
- ...(blockSelector && { blockSelector }),
- },
- },
- {
- onSuccess: async () => {
- toast(t(messages.saved));
- touch('websites');
- touch(`website:${websiteId}`);
- },
- },
- );
+ await saveRecorderConfig(getNextConfig());
};
if (cloudMode && !hasFeature('replays')) {
return (
<Column gap="4">
- <Label>{t(labels.replays)}</Label>
+ <Label>{sectionLabel}</Label>
<EmptyPlaceholder
icon={<Video />}
title={t(messages.upgradeRequired, { plan: 'Business' })}
- description="Watch real user sessions to see exactly how visitors interact with your site."
+ description="Watch real user sessions and build heatmaps from real visitor behavior."
>
<Button
variant="primary"
@@ -109,46 +129,73 @@ export function WebsiteReplaySettings({ websiteId }: { websiteId: string }) {
return (
<Column gap="4">
- <Label>{t(labels.replays)}</Label>
- <Switch isSelected={enabled} onChange={handleToggle} isDisabled={isPending}>
- {t(labels.replayEnabled)}
+ <Label>{sectionLabel}</Label>
+ <Switch isSelected={replayEnabled} onChange={handleReplayToggle} isDisabled={isPending}>
+ {t(labels.replays)}
+ </Switch>
+ <Switch isSelected={heatmapEnabled} onChange={handleHeatmapToggle} isDisabled={isPending}>
+ {t(labels.heatmaps)}
</Switch>
- {enabled && (
+ {(replayEnabled || heatmapEnabled) && (
<>
- <Label>{t(labels.replayCode)}</Label>
+ <Label>{t(labels.recorderCode)}</Label>
<Text color="muted">{t(messages.trackingCode)}</Text>
- <TextField value={recorderCode} isReadOnly allowCopy asTextArea resize="none" className="code-textarea" />
- <Slider
- label={t(labels.sampleRate)}
- minValue={0.05}
- maxValue={1}
- step={0.05}
- value={sampleRate}
- onChange={v => setSampleRate(Array.isArray(v) ? v[0] : v)}
- showValue
- formatOptions={{ style: 'percent', maximumFractionDigits: 0 }}
- style={{ maxWidth: '360px' }}
+ <TextField
+ value={recorderCode}
+ isReadOnly
+ allowCopy
+ asTextArea
+ resize="none"
+ className="code-textarea"
/>
- <Column gap="1">
- <Label>{t(labels.maskLevel)}</Label>
- <Select value={maskLevel} onChange={setMaskLevel} style={{ maxWidth: '360px' }}>
- <ListItem id="strict">strict</ListItem>
- <ListItem id="moderate">moderate</ListItem>
- </Select>
- </Column>
- <Column gap="1">
- <Label>{t(labels.maxDuration)}</Label>
- <Select value={maxDuration} onChange={setMaxDuration} style={{ maxWidth: '360px' }}>
- <ListItem id="300000">5 minutes</ListItem>
- <ListItem id="600000">10 minutes</ListItem>
- <ListItem id="900000">15 minutes</ListItem>
- <ListItem id="1200000">20 minutes</ListItem>
- </Select>
- </Column>
- <Column gap="1">
- <Label>{t(labels.blockSelector)}</Label>
- <TextField value={blockSelector} onChange={setBlockSelector} />
- </Column>
+ {heatmapEnabled && (
+ <Slider
+ label={`Heatmap ${t(labels.sampleRate).toLowerCase()}`}
+ minValue={0.05}
+ maxValue={1}
+ step={0.05}
+ value={heatmapSampleRate}
+ onChange={v => setHeatmapSampleRate(Array.isArray(v) ? v[0] : v)}
+ showValue
+ formatOptions={{ style: 'percent', maximumFractionDigits: 0 }}
+ style={{ maxWidth: '360px' }}
+ />
+ )}
+ {replayEnabled && (
+ <>
+ <Slider
+ label={`Replay ${t(labels.sampleRate).toLowerCase()}`}
+ minValue={0.05}
+ maxValue={1}
+ step={0.05}
+ value={sampleRate}
+ onChange={v => setSampleRate(Array.isArray(v) ? v[0] : v)}
+ showValue
+ formatOptions={{ style: 'percent', maximumFractionDigits: 0 }}
+ style={{ maxWidth: '360px' }}
+ />
+ <Column gap="1">
+ <Label>{t(labels.maskLevel)}</Label>
+ <Select value={maskLevel} onChange={setMaskLevel} style={{ maxWidth: '360px' }}>
+ <ListItem id="strict">strict</ListItem>
+ <ListItem id="moderate">moderate</ListItem>
+ </Select>
+ </Column>
+ <Column gap="1">
+ <Label>{t(labels.maxDuration)}</Label>
+ <Select value={maxDuration} onChange={setMaxDuration} style={{ maxWidth: '360px' }}>
+ <ListItem id="300000">5 minutes</ListItem>
+ <ListItem id="600000">10 minutes</ListItem>
+ <ListItem id="900000">15 minutes</ListItem>
+ <ListItem id="1200000">20 minutes</ListItem>
+ </Select>
+ </Column>
+ <Column gap="1">
+ <Label>{t(labels.blockSelector)}</Label>
+ <TextField value={blockSelector} onChange={setBlockSelector} />
+ </Column>
+ </>
+ )}
<Row>
<Button variant="primary" onPress={handleSave} isDisabled={isPending}>
{t(labels.save)}
diff --git a/src/app/api/record/route.ts b/src/app/api/record/route.ts
index 396f0b22c..91c2282dc 100644
--- a/src/app/api/record/route.ts
+++ b/src/app/api/record/route.ts
@@ -5,11 +5,12 @@ import { secret } from '@/lib/crypto';
import { getClientInfo, hasBlockedIp } from '@/lib/detect';
import { parseToken } from '@/lib/jwt';
import { fetchAccount, fetchTeam } from '@/lib/load';
+import { HEATMAP_EVENT_TYPE } from '@/lib/constants';
+import { getRecorderConfig } from '@/lib/recorder';
import { parseRequest } from '@/lib/request';
import { badRequest, forbidden, json, serverError } from '@/lib/response';
import { getWebsite } from '@/queries/prisma';
import { saveRecording } from '@/queries/sql';
-import { extractHeatmapEvents } from '@/queries/sql/heatmap/extractHeatmapEvents';
import { saveHeatmapEvents } from '@/queries/sql/heatmap/saveHeatmapEvents';
interface Cache {
@@ -17,14 +18,60 @@ interface Cache {
visitId: string;
}
-const schema = z.object({
- type: z.literal('record'),
- payload: z.object({
- website: z.uuid(),
- events: z.array(z.any()).max(200),
- timestamp: z.coerce.number().int().optional(),
+const schema = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('record'),
+ payload: z.object({
+ website: z.uuid(),
+ events: z.array(z.any()).max(200),
+ timestamp: z.coerce.number().int().optional(),
+ }),
}),
-});
+ z.object({
+ type: z.literal('heatmap'),
+ payload: z.object({
+ website: z.uuid(),
+ events: z
+ .array(
+ z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('click'),
+ url: z.string(),
+ x: z.coerce.number().optional(),
+ y: z.coerce.number().optional(),
+ pageX: z.coerce.number().optional(),
+ pageY: z.coerce.number().optional(),
+ pageW: z.coerce.number().optional(),
+ pageH: z.coerce.number().optional(),
+ viewportW: z.coerce.number().optional(),
+ viewportH: z.coerce.number().optional(),
+ timestamp: z.coerce.number().int().optional(),
+ }),
+ z.object({
+ type: z.literal('scroll'),
+ url: z.string(),
+ scrollPct: z.coerce.number().optional(),
+ pageW: z.coerce.number().optional(),
+ pageH: z.coerce.number().optional(),
+ viewportW: z.coerce.number().optional(),
+ viewportH: z.coerce.number().optional(),
+ timestamp: z.coerce.number().int().optional(),
+ }),
+ ]),
+ )
+ .max(200),
+ timestamp: z.coerce.number().int().optional(),
+ }),
+ }),
+]);
+
+function getUrlPath(url: string) {
+ try {
+ return new URL(url).pathname || '/';
+ } catch {
+ return url.startsWith('/') ? url.split(/[?#]/)[0] || '/' : '/';
+ }
+}
export async function POST(request: Request) {
try {
@@ -34,7 +81,9 @@ export async function POST(request: Request) {
return error();
}
- const { website: websiteId, events, timestamp } = body.payload;
+ const { website: websiteId } = body.payload;
+ const events = body.payload.events;
+ const timestamp = body.payload.timestamp;
if (!events?.length) {
return json({ ok: true });
@@ -55,15 +104,19 @@ export async function POST(request: Request) {
const { sessionId, visitId } = cache;
- // Query directly to avoid stale Redis cache for recordingEnabled
+ // Query directly to avoid stale Redis cache for recorderEnabled
const website = await getWebsite(websiteId);
if (!website) {
return badRequest({ message: 'Website not found.' });
}
- if (!website.replayEnabled) {
- return json({ ok: false, reason: 'replay_disabled' });
+ const recorderConfig = getRecorderConfig(website.replayConfig);
+ const replayEnabled = recorderConfig.replayEnabled === true;
+ const heatmapEnabled = recorderConfig.heatmapEnabled === true;
+
+ if (!website.recorderEnabled) {
+ return json({ ok: false, reason: 'recorder_disabled' });
}
if (process.env.CLOUD_MODE) {
@@ -89,38 +142,63 @@ export async function POST(request: Request) {
return forbidden();
}
- // Compute timestamps from events
- const eventTimestamps = events
- .map((e: any) => Number(e?.timestamp))
- .filter((t: number) => Number.isFinite(t) && t > 0);
+ if (body.type === 'record') {
+ if (!replayEnabled) {
+ return json({ ok: false, reason: 'replay_disabled' });
+ }
- const fallbackMs = (timestamp || Math.floor(Date.now() / 1000)) * 1000;
- const minTimestamp = eventTimestamps.length ? Math.min(...eventTimestamps) : fallbackMs;
- const maxTimestamp = eventTimestamps.length ? Math.max(...eventTimestamps) : fallbackMs;
+ const eventTimestamps = events
+ .map((e: any) => Number(e?.timestamp))
+ .filter((t: number) => Number.isFinite(t) && t > 0);
- const startedAt = new Date(minTimestamp);
- const endedAt = new Date(maxTimestamp);
+ const fallbackMs = (timestamp || Math.floor(Date.now() / 1000)) * 1000;
+ const minTimestamp = eventTimestamps.length ? Math.min(...eventTimestamps) : fallbackMs;
+ const maxTimestamp = eventTimestamps.length ? Math.max(...eventTimestamps) : fallbackMs;
- // Use timestamp-based chunk index for ordering
- const chunkIndex = timestamp || Math.floor(Date.now() / 1000);
+ const startedAt = new Date(minTimestamp);
+ const endedAt = new Date(maxTimestamp);
+ const chunkIndex = timestamp || Math.floor(Date.now() / 1000);
- await saveRecording({
- websiteId,
- sessionId,
- visitId,
- chunkIndex,
- events,
- eventCount: events.length,
- startedAt,
- endedAt,
- });
+ await saveRecording({
+ websiteId,
+ sessionId,
+ visitId,
+ chunkIndex,
+ events,
+ eventCount: events.length,
+ startedAt,
+ endedAt,
+ });
+
+ return json({ ok: true });
+ }
+
+ if (!heatmapEnabled) {
+ return json({ ok: false, reason: 'heatmap_disabled' });
+ }
try {
- const heatmapRows = extractHeatmapEvents(events, { chunkIndex }).map(e => ({
+ const fallbackMs = (timestamp || Math.floor(Date.now() / 1000)) * 1000;
+ const heatmapRows = events.map(event => ({
websiteId,
sessionId,
visitId,
- ...e,
+ eventType: event.type === 'click' ? HEATMAP_EVENT_TYPE.click : HEATMAP_EVENT_TYPE.scroll,
+ nodeId: null,
+ x: event.type === 'click' ? event.x ?? null : null,
+ y: event.type === 'click' ? event.y ?? null : null,
+ pageX: event.type === 'click' ? event.pageX ?? null : null,
+ pageY: event.type === 'click' ? event.pageY ?? null : null,
+ pageW: event.pageW ?? null,
+ viewportW: event.viewportW ?? null,
+ viewportH: event.viewportH ?? null,
+ pageH: event.pageH ?? null,
+ scrollPct: event.type === 'scroll' ? event.scrollPct ?? null : null,
+ urlPath: getUrlPath(event.url),
+ createdAt: new Date(event.timestamp ?? fallbackMs),
+ replayChunkIndex: null,
+ replayEventIndex: null,
+ replayTimeMs: null,
}));
if (heatmapRows.length) {
@@ -128,7 +206,7 @@ export async function POST(request: Request) {
}
} catch (e) {
// eslint-disable-next-line no-console
- console.log('heatmap extraction failed', serializeError(e));
+ console.log('heatmap save failed', serializeError(e));
}
return json({ ok: true });
diff --git a/src/app/api/websites/[websiteId]/recorder/route.ts b/src/app/api/websites/[websiteId]/recorder/route.ts
index bec989c6d..ef6307055 100644
--- a/src/app/api/websites/[websiteId]/recorder/route.ts
+++ b/src/app/api/websites/[websiteId]/recorder/route.ts
@@ -1,14 +1,7 @@
import { parseRequest } from '@/lib/request';
-import { json } from '@/lib/response';
+import { getRecorderConfig } from '@/lib/recorder';
import { getWebsite } from '@/queries/prisma';
-interface ReplayConfig {
- sampleRate?: number;
- maskLevel?: string;
- maxDuration?: number;
- blockSelector?: string;
-}
-
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
@@ -26,16 +19,19 @@ export async function GET(
'Cache-Control': 'public, max-age=60, stale-while-revalidate=300',
};
- if (!website || !website.replayEnabled) {
+ if (!website || !website.recorderEnabled) {
return Response.json({ enabled: false }, { headers });
}
- const config = (website.replayConfig as ReplayConfig) || {};
+ const config = getRecorderConfig(website.replayConfig);
return Response.json(
{
enabled: true,
+ replayEnabled: config.replayEnabled === true,
+ heatmapEnabled: config.heatmapEnabled === true,
sampleRate: config.sampleRate ?? 0.15,
+ heatmapSampleRate: config.heatmapSampleRate ?? 0.15,
maskLevel: config.maskLevel ?? 'moderate',
maxDuration: config.maxDuration ?? 300000,
blockSelector: config.blockSelector ?? '',
diff --git a/src/app/api/websites/[websiteId]/route.ts b/src/app/api/websites/[websiteId]/route.ts
index c74d018a3..b0897b254 100644
--- a/src/app/api/websites/[websiteId]/route.ts
+++ b/src/app/api/websites/[websiteId]/route.ts
@@ -1,6 +1,8 @@
import { z } from 'zod';
+import type { Prisma } from '@/generated/prisma/client';
import { ENTITY_TYPE } from '@/lib/constants';
import { uuid } from '@/lib/crypto';
+import { getRecorderConfig, getRecorderEnabled } from '@/lib/recorder';
import { parseRequest } from '@/lib/request';
import { badRequest, json, ok, serverError, unauthorized } from '@/lib/response';
import { canDeleteWebsite, canUpdateWebsite, canViewWebsite } from '@/permissions';
@@ -42,10 +44,12 @@ export async function POST(
name: z.string().optional(),
domain: z.string().optional(),
shareId: z.string().max(50).nullable().optional(),
- replayEnabled: z.boolean().optional(),
replayConfig: z
.object({
+ replayEnabled: z.boolean().optional(),
+ heatmapEnabled: z.boolean().optional(),
sampleRate: z.number().min(0).max(1).optional(),
+ heatmapSampleRate: z.number().min(0).max(1).optional(),
maskLevel: z.enum(['strict', 'moderate']).optional(),
maxDuration: z.number().int().positive().optional(),
blockSelector: z.string().optional(),
@@ -61,18 +65,35 @@ export async function POST(
}
const { websiteId } = await params;
- const { name, domain, shareId, replayEnabled, replayConfig } = body;
+ const { name, domain, shareId, replayConfig } = body;
if (!(await canUpdateWebsite(auth, websiteId))) {
return unauthorized();
}
try {
+ const currentWebsite = await getWebsite(websiteId);
+
+ if (!currentWebsite) {
+ return badRequest({ message: 'Website not found.' });
+ }
+
+ const nextReplayConfig = getRecorderConfig(
+ replayConfig === null
+ ? {}
+ : {
+ ...getRecorderConfig(currentWebsite.replayConfig),
+ ...(replayConfig ?? {}),
+ },
+ );
+
const website = await updateWebsite(websiteId, {
name,
domain,
- ...(replayEnabled !== undefined && { replayEnabled }),
- ...(replayConfig !== undefined && { replayConfig }),
+ ...(replayConfig !== undefined && {
+ replayConfig: nextReplayConfig as Prisma.InputJsonObject,
+ recorderEnabled: getRecorderEnabled(nextReplayConfig),
+ }),
});
if (shareId === null) {
diff --git a/src/components/messages.ts b/src/components/messages.ts
index c2d42c890..65c655056 100644
--- a/src/components/messages.ts
+++ b/src/components/messages.ts
@@ -381,7 +381,7 @@ export const labels: Record<string, string> = {
replay: 'label.replay',
replayId: 'label.replay-id',
replayEnabled: 'label.replay-enabled',
- replayCode: 'label.replay-code',
+ recorderCode: 'label.recorder-code',
sampleRate: 'label.sample-rate',
maskLevel: 'label.mask-level',
maxDuration: 'label.max-duration',
diff --git a/src/lib/recorder.ts b/src/lib/recorder.ts
new file mode 100644
index 000000000..53d57f77a
--- /dev/null
+++ b/src/lib/recorder.ts
@@ -0,0 +1,54 @@
+export interface RecorderConfig {
+ replayEnabled?: boolean;
+ heatmapEnabled?: boolean;
+ sampleRate?: number;
+ heatmapSampleRate?: number;
+ maskLevel?: 'strict' | 'moderate';
+ maxDuration?: number;
+ blockSelector?: string;
+}
+
+export function getRecorderConfig(value: unknown): RecorderConfig {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return {};
+ }
+
+ const config = value as Record<string, unknown>;
+ const nextConfig: RecorderConfig = {};
+
+ if (config.replayEnabled === true) {
+ nextConfig.replayEnabled = true;
+ }
+
+ if (config.heatmapEnabled === true) {
+ nextConfig.heatmapEnabled = true;
+ }
+
+ if (typeof config.sampleRate === 'number') {
+ nextConfig.sampleRate = config.sampleRate;
+ }
+
+ if (typeof config.heatmapSampleRate === 'number') {
+ nextConfig.heatmapSampleRate = config.heatmapSampleRate;
+ }
+
+ if (config.maskLevel === 'strict' || config.maskLevel === 'moderate') {
+ nextConfig.maskLevel = config.maskLevel;
+ }
+
+ if (typeof config.maxDuration === 'number' && Number.isFinite(config.maxDuration)) {
+ nextConfig.maxDuration = Math.round(config.maxDuration);
+ }
+
+ if (typeof config.blockSelector === 'string') {
+ nextConfig.blockSelector = config.blockSelector;
+ }
+
+ return nextConfig;
+}
+
+export function getRecorderEnabled(config: unknown) {
+ const { replayEnabled, heatmapEnabled } = getRecorderConfig(config);
+
+ return replayEnabled === true || heatmapEnabled === true;
+}
diff --git a/src/recorder/index.js b/src/recorder/index.js
index 38c27bf41..43a413f15 100644
--- a/src/recorder/index.js
+++ b/src/recorder/index.js
@@ -3,14 +3,15 @@ import { record } from 'rrweb';
(window => {
const { document } = window;
const { currentScript } = document;
+
if (!currentScript) return;
const _data = 'data-';
const attr = currentScript.getAttribute.bind(currentScript);
const config = value => attr(`${_data}${value}`);
- const website = config(`website-id`);
- const hostUrl = config(`host-url`);
+ const website = config('website-id');
+ const hostUrl = config('host-url');
if (!website) return;
@@ -18,41 +19,45 @@ import { record } from 'rrweb';
hostUrl || '__COLLECT_API_HOST__' || currentScript.src.split('/').slice(0, -1).join('/');
const hostBase = host.replace(/\/$/, '');
const endpoint = `${hostBase}__COLLECT_REPLAY_ENDPOINT__`;
- const configEndpoint = `${hostBase}__RECORDER_CONFIG_ENDPOINT__`.replace(
- '{websiteId}',
- website,
- );
+ const configEndpoint = `${hostBase}__RECORDER_CONFIG_ENDPOINT__`.replace('{websiteId}', website);
- const FLUSH_EVENT_COUNT = 100;
- const FLUSH_INTERVAL = 10000;
+ const REPLAY_FLUSH_EVENT_COUNT = 100;
+ const REPLAY_FLUSH_INTERVAL = 10000;
+ const HEATMAP_FLUSH_EVENT_COUNT = 20;
+ const HEATMAP_FLUSH_INTERVAL = 5000;
+ let replayEnabled = false;
+ let heatmapEnabled = false;
let sampleRate = 0.15;
+ let heatmapSampleRate = 0.15;
let maskLevel = 'moderate';
let maxDuration = 300000;
let blockSelector = '';
- let eventBuffer = [];
- let stopFn = null;
- let flushTimer = null;
- let startTime = null;
- let stopped = false;
- let recorderReady = false;
- let customEventBuffer = [];
+ let replayBuffer = [];
+ let heatmapBuffer = [];
+ let replayStopFn = null;
+ let replayFlushTimer = null;
+ let heatmapFlushTimer = null;
+ let replayStartTime = null;
+ let replayStopped = false;
+ let heatmapStarted = false;
+
+ const getSessionCache = () => window.umami?.getSession?.()?.cache;
+
+ const sendPayload = (type, payload, useKeepalive = false) => {
+ const cache = getSessionCache();
- const sendEvents = (events, useKeepalive = false) => {
- const session = window.umami?.getSession?.();
- if (!session?.cache) return;
+ if (!cache) return;
const body = JSON.stringify({
- type: 'record',
+ type,
payload: {
website,
- events,
- timestamp: Math.floor(Date.now() / 1000),
+ ...payload,
},
});
- // keepalive has a 64KB body limit — only use it for small payloads on unload
const keepalive = useKeepalive && body.length < 60000;
return fetch(endpoint, {
@@ -61,67 +66,79 @@ import { record } from 'rrweb';
body,
headers: {
'Content-Type': 'application/json',
- 'x-umami-cache': session.cache,
+ 'x-umami-cache': cache,
},
credentials: 'omit',
}).catch(() => {});
};
- const flush = (useKeepalive = false) => {
- if (!eventBuffer.length) return;
+ const flushReplay = (useKeepalive = false) => {
+ if (!replayBuffer.length) return;
- const events = eventBuffer;
- eventBuffer = [];
+ const events = replayBuffer;
+ replayBuffer = [];
- sendEvents(events, useKeepalive);
+ sendPayload(
+ 'record',
+ {
+ events,
+ timestamp: Math.floor(Date.now() / 1000),
+ },
+ useKeepalive,
+ );
};
- const scheduleFlush = () => {
- if (flushTimer) clearTimeout(flushTimer);
- flushTimer = setTimeout(flush, FLUSH_INTERVAL);
+ const flushHeatmap = (useKeepalive = false) => {
+ if (!heatmapBuffer.length) return;
+
+ const events = heatmapBuffer;
+ heatmapBuffer = [];
+
+ sendPayload(
+ 'heatmap',
+ {
+ events,
+ timestamp: Math.floor(Date.now() / 1000),
+ },
+ useKeepalive,
+ );
};
- const stop = () => {
- if (stopped) return;
- stopped = true;
- if (flushTimer) clearTimeout(flushTimer);
- flush();
- if (stopFn) stopFn();
+ const scheduleReplayFlush = () => {
+ if (replayFlushTimer) clearTimeout(replayFlushTimer);
+ replayFlushTimer = setTimeout(() => flushReplay(), REPLAY_FLUSH_INTERVAL);
};
- const flushCustomEvents = () => {
- if (!recorderReady || !customEventBuffer.length) return;
+ const scheduleHeatmapFlush = () => {
+ if (heatmapFlushTimer) clearTimeout(heatmapFlushTimer);
+ heatmapFlushTimer = setTimeout(() => flushHeatmap(), HEATMAP_FLUSH_INTERVAL);
+ };
- const events = customEventBuffer;
- customEventBuffer = [];
+ const queueHeatmapEvent = event => {
+ heatmapBuffer.push({
+ ...event,
+ timestamp: Date.now(),
+ });
- for (const event of events) {
- addCustomEvent(event.tag, event.payload);
+ if (heatmapBuffer.length >= HEATMAP_FLUSH_EVENT_COUNT) {
+ flushHeatmap();
+ return;
}
+
+ scheduleHeatmapFlush();
};
- const addCustomEvent = (tag, payload) => {
- if (stopped) return;
+ const stopReplay = () => {
+ if (replayStopped) return;
- if (!recorderReady) {
- customEventBuffer.push({ tag, payload });
- return;
- }
+ replayStopped = true;
- try {
- record.addCustomEvent(tag, payload);
- } catch (e) {
- if (e?.message === 'please add custom event after start recording') {
- recorderReady = false;
- customEventBuffer.push({ tag, payload });
- setTimeout(() => {
- recorderReady = true;
- flushCustomEvents();
- }, 0);
- return;
- }
+ if (replayFlushTimer) clearTimeout(replayFlushTimer);
+ flushReplay();
- throw e;
+ if (replayStopFn) {
+ replayStopFn();
+ replayStopFn = null;
}
};
@@ -132,16 +149,25 @@ import { record } from 'rrweb';
maskAllInputs: true,
maskTextSelector: '*',
};
- default: // moderate
+ default:
return {
maskAllInputs: true,
};
}
};
+ const shouldSample = value => {
+ if (value >= 1) return true;
+ if (value <= 0) return false;
+
+ return Math.random() <= value;
+ };
+
const measureElementWidth = element => {
if (!element) return 0;
+
const rect = element.getBoundingClientRect?.();
+
return Math.max(
element.scrollWidth || 0,
element.offsetWidth || 0,
@@ -152,7 +178,9 @@ import { record } from 'rrweb';
const measureElementHeight = element => {
if (!element) return 0;
+
const rect = element.getBoundingClientRect?.();
+
return Math.max(
element.scrollHeight || 0,
element.offsetHeight || 0,
@@ -163,6 +191,7 @@ import { record } from 'rrweb';
const measureDocumentBounds = doc => {
const body = doc?.body;
+
if (!body) {
return { width: 0, height: 0 };
}
@@ -174,10 +203,12 @@ import { record } from 'rrweb';
while (node) {
const rect = node.getBoundingClientRect?.();
+
if (rect && (rect.width > 0 || rect.height > 0)) {
maxRight = Math.max(maxRight, rect.right);
maxBottom = Math.max(maxBottom, rect.bottom);
}
+
node = walker.nextNode();
}
@@ -187,66 +218,7 @@ import { record } from 'rrweb';
};
};
- const waitForSession = (attempts = 0) => {
- if (attempts > 50) return;
-
- const session = window.umami?.getSession?.();
- if (session?.cache) {
- beginRecording();
- } else {
- setTimeout(() => waitForSession(attempts + 1), 100);
- }
- };
-
- const beginRecording = () => {
- startTime = Date.now();
-
- const maskConfig = getMaskConfig(maskLevel);
-
- stopFn = record({
- emit(event) {
- if (stopped) return;
-
- if (Date.now() - startTime > maxDuration) {
- stop();
- return;
- }
-
- eventBuffer.push(event);
- recorderReady = true;
- flushCustomEvents();
-
- if (eventBuffer.length >= FLUSH_EVENT_COUNT) {
- flush();
- }
-
- scheduleFlush();
- },
- ...maskConfig,
- inlineStylesheet: true,
- slimDOMOptions: {
- script: true,
- comment: true,
- headMetaDescKeywords: true,
- headMetaSocial: true,
- headMetaRobots: true,
- headMetaHttpEquiv: true,
- headMetaAuthorship: true,
- headMetaVerification: true,
- },
- recordCanvas: false,
- recordCrossOriginIframes: false,
- checkoutEveryNms: 30000,
- ...(blockSelector && { blockSelector }),
- });
- recorderReady = true;
- flushCustomEvents();
-
- let scrollUrl = location.href;
- let maxScrollPct = 0;
- let lastFlushedScrollPct = 0;
- let scrollTimer = null;
-
+ const createPageMetrics = () => {
const computePageMetrics = ({ includeBounds = false } = {}) => {
const scrollingElement = document.scrollingElement || document.documentElement;
const firstChild = document.body?.firstElementChild;
@@ -286,11 +258,69 @@ import { record } from 'rrweb';
};
};
+ return {
+ computePageMetrics,
+ computeScrollPct,
+ };
+ };
+
+ const beginReplayCapture = () => {
+ replayStartTime = Date.now();
+
+ replayStopFn = record({
+ emit(event) {
+ if (replayStopped) return;
+
+ if (Date.now() - replayStartTime > maxDuration) {
+ stopReplay();
+ return;
+ }
+
+ replayBuffer.push(event);
+
+ if (replayBuffer.length >= REPLAY_FLUSH_EVENT_COUNT) {
+ flushReplay();
+ }
+
+ scheduleReplayFlush();
+ },
+ ...getMaskConfig(maskLevel),
+ inlineStylesheet: true,
+ slimDOMOptions: {
+ script: true,
+ comment: true,
+ headMetaDescKeywords: true,
+ headMetaSocial: true,
+ headMetaRobots: true,
+ headMetaHttpEquiv: true,
+ headMetaAuthorship: true,
+ headMetaVerification: true,
+ },
+ recordCanvas: false,
+ recordCrossOriginIframes: false,
+ checkoutEveryNms: 30000,
+ ...(blockSelector && { blockSelector }),
+ });
+ };
+
+ const beginHeatmapCapture = () => {
+ if (heatmapStarted) return;
+
+ heatmapStarted = true;
+
+ const { computePageMetrics, computeScrollPct } = createPageMetrics();
+ let scrollUrl = location.href;
+ let maxScrollPct = 0;
+ let lastFlushedScrollPct = 0;
+ let scrollTimer = null;
+
const flushScroll = () => {
if (maxScrollPct <= 0 || maxScrollPct <= lastFlushedScrollPct) return;
+
const { pageW, pageH } = computePageMetrics({ includeBounds: true });
- addCustomEvent('scroll-progress', {
+ queueHeatmapEvent({
+ type: 'scroll',
url: scrollUrl,
scrollPct: maxScrollPct,
viewportW: window.innerWidth,
@@ -298,6 +328,7 @@ import { record } from 'rrweb';
pageW,
pageH,
});
+
lastFlushedScrollPct = maxScrollPct;
maxScrollPct = 0;
};
@@ -320,7 +351,8 @@ import { record } from 'rrweb';
const pageW = Math.max(rawPageW, Math.ceil(pageX), Math.ceil(targetRight));
const pageH = Math.max(rawPageH, Math.ceil(pageY), Math.ceil(targetBottom));
- addCustomEvent('heatmap-click', {
+ queueHeatmapEvent({
+ type: 'click',
url: location.href,
x: Math.round(event.clientX),
y: Math.round(event.clientY),
@@ -335,9 +367,14 @@ import { record } from 'rrweb';
const onScroll = () => {
if (scrollTimer) return;
+
scrollTimer = setTimeout(() => {
const { pct } = computeScrollPct();
- if (pct > maxScrollPct) maxScrollPct = pct;
+
+ if (pct > maxScrollPct) {
+ maxScrollPct = pct;
+ }
+
flushScroll();
scrollTimer = null;
}, 400);
@@ -345,16 +382,17 @@ import { record } from 'rrweb';
const onUrlChange = () => {
if (location.href === scrollUrl) return;
+
flushScroll();
scrollUrl = location.href;
lastFlushedScrollPct = 0;
- addCustomEvent('url-change', { url: scrollUrl });
};
const hookHistory = method => {
- const orig = history[method];
+ const original = history[method];
+
history[method] = function (...args) {
- const result = orig.apply(this, args);
+ const result = original.apply(this, args);
onUrlChange();
return result;
};
@@ -368,32 +406,80 @@ import { record } from 'rrweb';
{
const { pct } = computeScrollPct();
- if (pct > maxScrollPct) maxScrollPct = pct;
+
+ if (pct > maxScrollPct) {
+ maxScrollPct = pct;
+ }
+
flushScroll();
}
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
flushScroll();
- flush(true);
+ flushHeatmap(true);
}
});
window.addEventListener('beforeunload', () => {
flushScroll();
- flush(true);
+ flushHeatmap(true);
+ });
+ };
+
+ const waitForSession = (callback, attempts = 0) => {
+ if (attempts > 50) return;
+
+ if (getSessionCache()) {
+ callback();
+ return;
+ }
+
+ setTimeout(() => waitForSession(callback, attempts + 1), 100);
+ };
+
+ const startCaptures = () => {
+ const shouldRecordReplay = replayEnabled && shouldSample(sampleRate);
+ const shouldRecordHeatmap = heatmapEnabled && shouldSample(heatmapSampleRate);
+
+ if (shouldRecordHeatmap) {
+ beginHeatmapCapture();
+ }
+
+ if (shouldRecordReplay) {
+ beginReplayCapture();
+ }
+
+ if (!shouldRecordHeatmap && !shouldRecordReplay) {
+ return;
+ }
+
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') {
+ flushReplay(true);
+ }
+ });
+
+ window.addEventListener('beforeunload', () => {
+ flushReplay(true);
});
};
const bootstrap = async () => {
try {
const response = await fetch(configEndpoint, { credentials: 'omit' });
+
if (!response.ok) return;
const data = await response.json();
+
if (!data?.enabled) return;
+ replayEnabled = data.replayEnabled === true;
+ heatmapEnabled = data.heatmapEnabled === true;
+
if (typeof data.sampleRate === 'number') sampleRate = data.sampleRate;
+ if (typeof data.heatmapSampleRate === 'number') heatmapSampleRate = data.heatmapSampleRate;
if (typeof data.maskLevel === 'string') maskLevel = data.maskLevel;
if (typeof data.maxDuration === 'number') maxDuration = data.maxDuration;
if (typeof data.blockSelector === 'string') blockSelector = data.blockSelector;
@@ -401,14 +487,17 @@ import { record } from 'rrweb';
return;
}
- // Sample rate check
- if (sampleRate < 1 && Math.random() > sampleRate) return;
+ if (!replayEnabled && !heatmapEnabled) {
+ return;
+ }
if (document.readyState === 'complete') {
- waitForSession();
+ waitForSession(startCaptures);
} else {
document.addEventListener('readystatechange', () => {
- if (document.readyState === 'complete') waitForSession();
+ if (document.readyState === 'complete') {
+ waitForSession(startCaptures);
+ }
});
}
};