This commit is contained in:
Mike Cao committed 2026-08-04 21:21:17 -07:00
commit aab5462e38
20 files changed
+807 -121

No files matched your search

+13
View File
@@ -7,6 +7,7 @@ export const config = {
};
const TRACKER_PATH = '/script.js';
const RECORDER_PATH = '/recorder.js';
const COLLECT_PATH = '/api/send';
const LOGIN_PATH = '/login';
const BASE_PATH = process.env.BASE_PATH || '';
@@ -62,6 +63,17 @@ function customScriptUrl(request: NextRequest) {
}
}
function applyStaticScriptHeaders(request: NextRequest, response: NextResponse) {
if (
matchesConfiguredPath(request.nextUrl.pathname, TRACKER_PATH, BASE_PATH) ||
matchesConfiguredPath(request.nextUrl.pathname, RECORDER_PATH, BASE_PATH)
) {
Object.entries(trackerHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
}
}
function disableLogin(request: NextRequest) {
const loginDisabled = process.env.DISABLE_LOGIN;
@@ -83,6 +95,7 @@ export default function middleware(req: NextRequest) {
}
res ??= NextResponse.next();
applyStaticScriptHeaders(req, res);
// Set the CSP here, not only at build time in next.config.ts, so
// ALLOWED_FRAME_URLS is resolved from the runtime environment.
+5
View File
@@ -6,6 +6,7 @@ import { getContentSecurityPolicy } from './src/lib/csp';
const withNextIntl = createNextIntlPlugin('./src/i18n/request.ts');
const TRACKER_SCRIPT = '/script.js';
const RECORDER_SCRIPT = '/recorder.js';
const isProd = process.env.NODE_ENV === 'production';
@@ -99,6 +100,10 @@ if (isProd) {
source: TRACKER_SCRIPT,
headers: trackerHeaders,
});
headers.push({
source: RECORDER_SCRIPT,
headers: trackerHeaders,
});
}
const rewrites = [];
@@ -58,6 +58,35 @@
font-weight: 600;
}
.mobilePageHeader {
min-width: 0;
}
.mobilePageSection {
padding: 4px 0 2px;
}
.mobileSectionLabel {
font-size: 12px;
font-weight: 600;
}
.mobileSelectedPageButton {
width: 100%;
text-align: left;
border: 1px solid var(--border-base);
background: var(--surface-raised);
border-radius: 8px;
padding: 10px 12px;
cursor: pointer;
font: inherit;
color: inherit;
}
.mobileSelectedPageButton:hover {
background: var(--surface-sunken);
}
.summaryHeader {
min-width: 0;
}
@@ -98,6 +127,10 @@
min-width: 0;
}
.mobileSummaryControls {
width: 100%;
}
.screenWidthCount {
margin-left: auto;
font-variant-numeric: tabular-nums;
@@ -228,3 +261,38 @@
pointer-events: auto;
mix-blend-mode: multiply;
}
@media (max-width: 640px) {
.summaryStats,
.summaryHeader {
width: 100%;
align-items: stretch;
}
.summaryStats {
gap: 8px;
}
.summaryStat {
width: 100%;
justify-content: flex-start;
}
.screenWidthControl {
width: 100%;
margin-left: 0;
justify-content: space-between;
}
.screenWidthLabel {
font-size: 12px;
}
.canvasWrapper {
max-height: 70vh;
}
.scrollBandLabel {
display: none;
}
}
@@ -1,19 +1,25 @@
'use client';
import {
Button,
Column,
Dialog,
Grid,
Heading,
Icon,
ListItem,
Loading,
Modal,
Row,
Select,
Text,
} from '@umami/react-zen';
import { Laptop, Monitor, Smartphone, Tablet } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ControlledDialog } from '@/components/common/ControlledDialog';
import { IconLabel } from '@/components/common/IconLabel';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { useResultQuery } from '@/components/hooks';
import { useMobile, useResultQuery } from '@/components/hooks';
import { ListCheck } from '@/components/icons';
import { formatLongNumber } from '@/lib/format';
import type { HeatmapMode, HeatmapPoint, HeatmapResult, HeatmapSnapshot } from '@/queries/sql';
import styles from './Heatmap.module.css';
@@ -53,6 +59,8 @@ interface HeatmapProps {
}
export function Heatmap({ websiteId, urlPath, onUrlPathChange, mode, search }: HeatmapProps) {
const { isPhone } = useMobile();
const [isPagePickerOpen, setIsPagePickerOpen] = useState(false);
const {
data: pagesData,
error,
@@ -88,6 +96,7 @@ export function Heatmap({ websiteId, urlPath, onUrlPathChange, mode, search }: H
return pages.filter(page => page.urlPath.toLowerCase().includes(value));
}, [pages, search]);
const selectedPage = filteredPages.find(page => page.urlPath === urlPath) ?? null;
const points = detailData?.points ?? [];
const scroll = detailData?.scroll;
const snapshot = detailData?.snapshot ?? null;
@@ -122,16 +131,33 @@ export function Heatmap({ websiteId, urlPath, onUrlPathChange, mode, search }: H
return (
<LoadingPanel data={pagesData} isLoading={isLoading} error={error} minHeight="900px">
<Grid columns="320px 12px 1fr" minHeight="900px" className={styles.layoutGrid}>
<PageList
pages={filteredPages}
selected={urlPath}
onSelect={onUrlPathChange}
mode={mode}
hasSearch={Boolean(search)}
/>
<div className={styles.railDivider} aria-hidden="true" />
<Column className={styles.contentColumn} gap>
{isPhone ? (
<Column gap="4" minHeight="900px">
<Column gap="2" className={styles.mobilePageSection}>
<Row alignItems="center" justifyContent="space-between" gap className={styles.mobilePageHeader}>
<Text color="muted" className={styles.mobileSectionLabel}>
Selected page
</Text>
<Button variant="outline" onPress={() => setIsPagePickerOpen(true)}>
<IconLabel icon={<ListCheck />} label="Pages" />
</Button>
</Row>
{selectedPage && (
<button
type="button"
className={styles.mobileSelectedPageButton}
onClick={() => setIsPagePickerOpen(true)}
>
<Row alignItems="center" justifyContent="space-between" gap="3">
<Text truncate>{selectedPage.urlPath}</Text>
<Text color="muted" className={styles.pageMetric}>
{formatLongNumber(selectedPage.sessions)}
</Text>
</Row>
</button>
)}
</Column>
{urlPath ? (
mode === 'scroll' ? (
<ScrollHeatmapView
@@ -151,8 +177,74 @@ export function Heatmap({ websiteId, urlPath, onUrlPathChange, mode, search }: H
) : (
<EmptyState />
)}
<ControlledDialog>
<Modal
isOpen={isPagePickerOpen}
onOpenChange={isOpen => setIsPagePickerOpen(isOpen)}
placement="fullscreen"
>
<Dialog
title="Pages"
style={{
width: '100%',
height: '100%',
maxHeight: '100%',
overflowY: 'auto',
padding: '24px',
}}
>
{({ close }) => (
<PageList
pages={filteredPages}
selected={urlPath}
onSelect={nextUrlPath => {
onUrlPathChange(nextUrlPath);
setIsPagePickerOpen(false);
close();
}}
mode={mode}
hasSearch={Boolean(search)}
showHeading={false}
/>
)}
</Dialog>
</Modal>
</ControlledDialog>
</Column>
</Grid>
) : (
<Grid columns="320px 12px 1fr" minHeight="900px" className={styles.layoutGrid}>
<PageList
pages={filteredPages}
selected={urlPath}
onSelect={onUrlPathChange}
mode={mode}
hasSearch={Boolean(search)}
/>
<div className={styles.railDivider} aria-hidden="true" />
<Column className={styles.contentColumn} gap>
{urlPath ? (
mode === 'scroll' ? (
<ScrollHeatmapView
urlPath={urlPath}
scroll={scroll}
snapshot={snapshot}
isLoading={detailLoading}
/>
) : (
<ClickHeatmapView
urlPath={urlPath}
points={points}
snapshot={snapshot}
isLoading={detailLoading}
/>
)
) : (
<EmptyState />
)}
</Column>
</Grid>
)}
</LoadingPanel>
);
}
@@ -163,12 +255,14 @@ function PageList({
onSelect,
mode,
hasSearch,
showHeading = true,
}: {
pages: HeatmapResult['pages'];
selected: string;
onSelect: (urlPath: string) => void;
mode: HeatmapMode;
hasSearch: boolean;
showHeading?: boolean;
}) {
const getPageMetricTitle = (page: HeatmapResult['pages'][number]) => {
const metricLabel = mode === 'scroll' ? 'scroll events' : 'clicks';
@@ -178,7 +272,7 @@ function PageList({
return (
<Column className={styles.pageList} gap="1">
<Heading size="lg">Pages</Heading>
{showHeading && <Heading size="lg">Pages</Heading>}
<Column className={styles.pageListItems} gap="2">
{pages.length === 0 && hasSearch && <Text color="muted">No matching pages</Text>}
{pages.map(page => (
@@ -546,6 +640,7 @@ function ClickHeatmapView({
snapshot: HeatmapSnapshot | null;
isLoading: boolean;
}) {
const { isPhone } = useMobile();
const [snapshotReady, setSnapshotReady] = useState(false);
const screenWidthBuckets = useMemo(() => getScreenWidthBuckets(points), [points]);
const { viewport, setSelectedScreenWidth } = useSelectedScreenWidthBucket(screenWidthBuckets);
@@ -596,17 +691,27 @@ function ClickHeatmapView({
return (
<Column gap>
<Column gap="2" className={styles.summaryHeader}>
<Row alignItems="center" justifyContent="space-between" gap>
<Text color="muted" title={urlPath} className={styles.summaryPath}>
{urlPath}
</Text>
</Row>
{!isPhone && (
<Row alignItems="center" justifyContent="space-between" gap>
<Text color="muted" title={urlPath} className={styles.summaryPath}>
{urlPath}
</Text>
</Row>
)}
{showLoading ? (
<Row alignItems="center" gap className={styles.summaryStats}>
<Text color="muted" className={styles.summaryStat}>
Loading Heatmap...
</Text>
</Row>
) : isPhone ? (
<Column gap="2" className={styles.mobileSummaryControls}>
<ScreenWidthSelect
buckets={screenWidthBuckets}
value={viewport?.width ?? null}
onChange={setSelectedScreenWidth}
/>
</Column>
) : (
<Row
alignItems="center"
@@ -705,6 +810,7 @@ function ScrollHeatmapView({
snapshot: HeatmapSnapshot | null;
isLoading: boolean;
}) {
const { isPhone } = useMobile();
const [snapshotReady, setSnapshotReady] = useState(false);
const handleSnapshotReady = useCallback(() => setSnapshotReady(true), []);
const hasSnapshot = Boolean(snapshot);
@@ -771,15 +877,25 @@ function ScrollHeatmapView({
return (
<Column gap>
<Text color="muted" title={urlPath} className={styles.summaryPath}>
{urlPath}
</Text>
{!isPhone && (
<Text color="muted" title={urlPath} className={styles.summaryPath}>
{urlPath}
</Text>
)}
{showLoading ? (
<Row alignItems="center" gap className={styles.summaryStats}>
<Text color="muted" className={styles.summaryStat}>
Loading Heatmap...
</Text>
</Row>
) : isPhone ? (
<Column gap="2" className={styles.mobileSummaryControls}>
<ScreenWidthSelect
buckets={screenWidthBuckets}
value={viewport?.width ?? null}
onChange={setSelectedScreenWidth}
/>
</Column>
) : (
<Row
alignItems="center"
@@ -67,7 +67,12 @@ export function HeatmapsPage({ websiteId }: { websiteId: string }) {
{isPhone ? (
<Column gap="3">
<Row>
<SearchField value={search} onSearch={setSearch} placeholder="Search" />
<SearchField
value={search}
onSearch={setSearch}
placeholder="Search"
className="w-full max-w-md"
/>
</Row>
<Row justifyContent="flex-end">
<FilterButtons
@@ -79,7 +84,12 @@ export function HeatmapsPage({ websiteId }: { websiteId: string }) {
</Column>
) : (
<Row alignItems="center" justifyContent="space-between" gap="4">
<SearchField value={search} onSearch={setSearch} placeholder="Search" />
<SearchField
value={search}
onSearch={setSearch}
placeholder="Search"
className="w-full max-w-md"
/>
<FilterButtons
items={buttons}
value={mode}
@@ -5,5 +5,10 @@
.modal {
width: min(calc(100dvw - 48px), 1320px);
height: calc(100dvh - 80px);
overflow: hidden;
}
.portrait {
width: min(calc(100dvw - 48px), 900px);
}
@@ -1,12 +1,13 @@
'use client';
import { Column, Dialog, Sheet, type SheetProps } from '@umami/react-zen';
import { Column, Dialog, Modal, type ModalProps } from '@umami/react-zen';
import { useEffect, useState } from 'react';
import { ReplayPlayback } from '@/app/(main)/websites/[websiteId]/replays/[replayId]/ReplayPlayback';
import { ControlledDialog } from '@/components/common/ControlledDialog';
import { useNavigation } from '@/components/hooks';
import { buildPath } from '@/lib/url';
import styles from './ReplayModal.module.css';
export interface ReplayModalProps extends SheetProps {
export interface ReplayModalProps extends ModalProps {
websiteId: string;
replayId?: string;
}
@@ -19,7 +20,21 @@ export function ReplayModal({ websiteId, replayId, className, ...props }: Replay
updateParams,
} = useNavigation();
const activeReplayId = replayId || replay;
const modalClassName = [styles.modal, className].filter(Boolean).join(' ');
const [replayOrientation, setReplayOrientation] = useState<'portrait' | 'landscape' | null>(null);
useEffect(() => {
if (activeReplayId) {
setReplayOrientation(null);
}
}, [activeReplayId]);
const modalClassName = [
styles.modal,
replayOrientation === 'portrait' ? styles.portrait : null,
className,
]
.filter(Boolean)
.join(' ');
const handleOpenChange = (isOpen: boolean) => {
if (!isOpen) {
@@ -36,26 +51,29 @@ export function ReplayModal({ websiteId, replayId, className, ...props }: Replay
return (
<ControlledDialog>
<Sheet
<Modal
{...props}
side="bottom"
size="calc(100dvh - 80px)"
className={modalClassName}
isOpen={!!activeReplayId}
onOpenChange={handleOpenChange}
>
<Column height="100%">
<Dialog className={styles.sheet}>
<Dialog className="h-full rounded-lg">
{({ close }) => (
<Column padding="6">
{activeReplayId && (
<ReplayPlayback websiteId={websiteId} replayId={activeReplayId} onClose={close} />
<ReplayPlayback
websiteId={websiteId}
replayId={activeReplayId}
onClose={close}
onReplayStateChange={setReplayOrientation}
/>
)}
</Column>
)}
</Dialog>
</Column>
</Sheet>
</Modal>
</ControlledDialog>
);
}
@@ -1,41 +1,60 @@
'use client';
import { Button, Column, Dialog, DialogTrigger, Icon, Popover, Row, Text } from '@umami/react-zen';
import { Bookmark, X } from 'lucide-react';
import { useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { SessionInfo } from '@/app/(main)/websites/[websiteId]/sessions/SessionInfo';
import { Avatar } from '@/components/common/Avatar';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useMessages,
useMobile,
useReplayQuery,
useReplaySavedQuery,
useUpdateQuery,
useWebsiteSessionQuery,
} from '@/components/hooks';
import { touch } from '@/components/hooks/useModified';
import { getReplayViewport } from '@/lib/replay';
import { ReplayPlayer } from './ReplayPlayer';
import { ReplaySaveForm } from './ReplaySaveForm';
type ReplayOrientation = 'portrait' | 'landscape';
export function ReplayPlayback({
websiteId,
replayId,
showSessionInfo = true,
onClose,
onReplayStateChange,
}: {
websiteId: string;
replayId: string;
showSessionInfo?: boolean;
onClose?: () => void;
onReplayStateChange?: (orientation: ReplayOrientation | null) => void;
}) {
const { data: replay, isLoading, error } = useReplayQuery(websiteId, replayId);
const { data: replaySaved } = useReplaySavedQuery(websiteId, replayId);
const { data: session } = useWebsiteSessionQuery(websiteId, replay?.sessionId);
const { t, labels } = useMessages();
const { isMobile } = useMobile();
const [isSaved, setIsSaved] = useState<boolean | null>(null);
const { mutate } = useUpdateQuery(`/websites/${websiteId}/replays/saved/${replayId}`);
const replayViewport = useMemo(() => getReplayViewport(replay?.events), [replay?.events]);
const replayOrientation: ReplayOrientation | null = replayViewport
? replayViewport.height > replayViewport.width
? 'portrait'
: 'landscape'
: replay
? 'landscape'
: null;
const saved = isSaved ?? replaySaved?.isSaved ?? false;
useEffect(() => {
onReplayStateChange?.(replayOrientation);
}, [replayOrientation, onReplayStateChange]);
const handleUnsave = () => {
setIsSaved(false);
mutate({ isSaved: false }, { onSuccess: () => touch('replays') });
@@ -50,19 +69,24 @@ export function ReplayPlayback({
style={{ minHeight: '400px' }}
>
{replay && (
<Column gap="6">
<Column gap="6" width="100%" minWidth="0">
{session && (
<Row justifyContent="space-between" alignItems="flex-start">
<Row alignItems="center" gap="4">
<Row
justifyContent="space-between"
alignItems="flex-start"
gap="3"
style={{ flexWrap: isMobile ? 'wrap' : 'nowrap' }}
>
<Row alignItems="center" gap="4" minWidth="0" style={{ flex: '1 1 240px' }}>
<Avatar seed={replay.sessionId} size={48} />
<Column>
<Column minWidth="0">
<Text weight="bold">{t(labels.replay)}</Text>
<Text color="muted">
{replay.eventCount} {t(labels.actions).toLowerCase()}
</Text>
</Column>
</Row>
<Row gap="2">
<Row gap="2" style={{ flex: '0 0 auto' }}>
{saved ? (
<Button onPress={handleUnsave} variant="quiet">
<Icon>
@@ -24,24 +24,71 @@ function destroyReplayPlayer(player: { $destroy?: () => void } | null) {
}
export function ReplayPlayer({ events }: { events: any[] }) {
const playerWrapperRef = useRef<HTMLDivElement>(null);
const playerRootRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<any>(null);
const [playerError, setPlayerError] = useState(false);
const [availableWidth, setAvailableWidth] = useState(0);
const [viewportHeight, setViewportHeight] = useState(
() => (typeof window !== 'undefined' ? window.innerHeight : 0),
);
const { isMobile, isPhone } = useMobile();
const replayEvents = useMemo(() => getReplayPlayerEvents(events), [events]);
const replayViewport = useMemo(() => getReplayViewport(replayEvents), [replayEvents]);
const canReplay = replayEvents.length >= 2;
const showUnavailable = !events?.length || !canReplay || playerError;
const playerWidth = isPhone ? 360 : isMobile ? 640 : 1024;
const preferredPlayerWidth = isPhone ? 360 : isMobile ? 640 : 1024;
const replayAspectRatio = replayViewport
? replayViewport.height / replayViewport.width
: DEFAULT_REPLAY_ASPECT_RATIO;
const playerHeight = Math.round(
playerWidth * Math.min(Math.max(replayAspectRatio, DEFAULT_REPLAY_ASPECT_RATIO), 1.5),
const isPortraitReplay = replayViewport
? replayViewport.height > replayViewport.width
: false;
const fittedAspectRatio = isPortraitReplay
? Math.min(Math.max(replayAspectRatio, DEFAULT_REPLAY_ASPECT_RATIO), 2.25)
: Math.min(Math.max(replayAspectRatio, DEFAULT_REPLAY_ASPECT_RATIO), 1.5);
const maxPortraitPlayerHeight = Math.max(
240,
Math.round((viewportHeight || 900) * (isMobile ? (isPhone ? 0.55 : 0.6) : 0.88)),
);
let playerWidth = Math.min(preferredPlayerWidth, availableWidth || preferredPlayerWidth);
let playerHeight = Math.round(playerWidth * fittedAspectRatio);
// Portrait/mobile-recorded replays need to shrink to the visible viewport,
// otherwise the player keeps a large desktop frame with a tiny phone replay inside it.
if (isPortraitReplay && playerHeight > maxPortraitPlayerHeight) {
playerHeight = maxPortraitPlayerHeight;
playerWidth = Math.max(1, Math.round(playerHeight / fittedAspectRatio));
}
const playerOuterHeight = playerHeight + 80;
useEffect(() => {
const updateAvailableSize = () => {
const width = playerWrapperRef.current?.clientWidth ?? 0;
setAvailableWidth(current => (current === width ? current : width));
setViewportHeight(current => (current === window.innerHeight ? current : window.innerHeight));
};
updateAvailableSize();
const resizeObserver =
typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateAvailableSize) : null;
if (playerWrapperRef.current && resizeObserver) {
resizeObserver.observe(playerWrapperRef.current);
}
window.addEventListener('resize', updateAvailableSize);
return () => {
resizeObserver?.disconnect();
window.removeEventListener('resize', updateAvailableSize);
};
}, []);
useEffect(() => {
let cancelled = false;
const playerRoot = playerRootRef.current;
@@ -114,27 +161,28 @@ export function ReplayPlayer({ events }: { events: any[] }) {
return (
<Column alignItems="center" width="100%">
<div
style={{
width: '100%',
maxWidth: playerWidth,
height: showUnavailable ? playerHeight : playerOuterHeight,
overflowX: showUnavailable ? 'hidden' : 'auto',
overflowY: 'hidden',
borderRadius: '8px',
border: '1px solid var(--base300)',
background: 'var(--base75)',
}}
>
<div ref={playerWrapperRef} style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
<div
ref={playerRootRef}
style={{
display: showUnavailable ? 'none' : 'block',
width: playerWidth,
height: playerOuterHeight,
maxWidth: '100%',
height: showUnavailable ? playerHeight : playerOuterHeight,
overflow: 'hidden',
borderRadius: '8px',
border: '1px solid var(--base300)',
background: 'var(--base75)',
}}
/>
{showUnavailable && <Empty message="Replay unavailable." />}
>
<div
ref={playerRootRef}
style={{
display: showUnavailable ? 'none' : 'block',
width: playerWidth,
height: playerOuterHeight,
}}
/>
{showUnavailable && <Empty message="Replay unavailable." />}
</div>
</div>
</Column>
);
@@ -2,7 +2,7 @@
import { Column, Dialog, Modal, type ModalProps } from '@umami/react-zen';
import { SessionProfile } from '@/app/(main)/websites/[websiteId]/sessions/SessionProfile';
import { ControlledDialog } from '@/components/common/ControlledDialog';
import { useNavigation } from '@/components/hooks';
import { useMobile, useNavigation } from '@/components/hooks';
import styles from './SessionModal.module.css';
export interface SessionModalProps extends ModalProps {
@@ -16,6 +16,7 @@ export function SessionModal({ websiteId, className, ...props }: SessionModalPro
query: { session },
updateParams,
} = useNavigation();
const { isMobile } = useMobile();
const isSharePage = pathname.includes('/share/');
const handleOpenChange = (isOpen: boolean) => {
if (!isOpen) {
@@ -34,7 +35,7 @@ export function SessionModal({ websiteId, className, ...props }: SessionModalPro
<Column height="100%">
<Dialog className="h-full rounded-lg">
{({ close }) => (
<Column padding="10">
<Column padding={isMobile ? '6' : '10'} minWidth="0" width="100%">
<SessionProfile
websiteId={websiteId}
sessionId={session}
@@ -57,7 +57,7 @@ export function SessionProfile({
loadingPlacement="absolute"
>
{data && (
<Column gap>
<Column gap width="100%" minWidth="0">
{onClose && (
<Row justifyContent="flex-end" gap="1">
{showDeleteButton && (
@@ -74,7 +74,7 @@ export function SessionProfile({
</Button>
</Row>
)}
<Column gap="6">
<Column gap="6" width="100%" minWidth="0">
<Row
justifyContent="center"
alignItems="center"
@@ -108,7 +108,7 @@ export function SessionProfile({
<SessionData sessionId={sessionId} websiteId={websiteId} />
</TabPanel>
{showReplays && (
<TabPanel id="replays">
<TabPanel id="replays" style={{ width: '100%', minWidth: 0, overflowX: 'hidden' }}>
<SessionReplaysDataTable websiteId={websiteId} sessionId={sessionId} />
</TabPanel>
)}
@@ -2,7 +2,7 @@
import { Column } from '@umami/react-zen';
import { useState } from 'react';
import { DataGrid } from '@/components/common/DataGrid';
import { useSessionReplaysQuery } from '@/components/hooks';
import { useMobile, useSessionReplaysQuery } from '@/components/hooks';
import { ReplayPlayback } from '../replays/[replayId]/ReplayPlayback';
import { SessionReplaysTable } from './SessionReplaysTable';
@@ -10,13 +10,22 @@ function InlinePlayer({
websiteId,
replayId,
onClose,
isMobile,
}: {
websiteId: string;
replayId: string;
onClose: () => void;
isMobile: boolean;
}) {
return (
<div style={{ padding: '1.5rem 0' }}>
<div
style={{
padding: isMobile ? '0.75rem 0' : '1.5rem 0',
width: '100%',
maxWidth: '100%',
overflowX: 'hidden',
}}
>
<ReplayPlayback
websiteId={websiteId}
replayId={replayId}
@@ -34,6 +43,7 @@ export function SessionReplaysDataTable({
websiteId: string;
sessionId: string;
}) {
const { isMobile } = useMobile();
const queryResult = useSessionReplaysQuery(websiteId, sessionId);
const [selectedId, setSelectedId] = useState<string | undefined>();
@@ -42,12 +52,13 @@ export function SessionReplaysDataTable({
};
return (
<Column>
<Column width="100%" minWidth="0">
{selectedId && (
<InlinePlayer
websiteId={websiteId}
replayId={selectedId}
onClose={() => setSelectedId(undefined)}
isMobile={isMobile}
/>
)}
<DataGrid query={queryResult} allowPaging>
@@ -9,7 +9,6 @@ import {
Select,
Text,
} from '@umami/react-zen';
import { useState } from 'react';
import {
useLoginQuery,
useMessages,
@@ -30,7 +29,6 @@ export function WebsiteTransferForm({
}) {
const { user } = useLoginQuery();
const website = useWebsite();
const [teamId, setTeamId] = useState<string>(null);
const { t, labels, messages, getErrorMessage } = useMessages();
const { mutateAsync, error, isPending } = useUpdateQuery(`/websites/${websiteId}/transfer`);
const { data: teams, isLoading } = useUserTeamsQuery(user.id);
@@ -44,11 +42,11 @@ export function WebsiteTransferForm({
),
) || [];
const handleSubmit = async () => {
const handleSubmit = async (data: { teamId?: string }) => {
await mutateAsync(
{
userId: website.teamId ? user.id : undefined,
teamId: website.userId ? teamId : undefined,
teamId: website.userId ? data.teamId : undefined,
},
{
onSuccess: async () => {
@@ -59,42 +57,50 @@ export function WebsiteTransferForm({
);
};
const handleChange = (key: string | number | null) => {
setTeamId(key as string);
};
if (isLoading) {
return <Loading icon="dots" placement="center" />;
}
return (
<Form onSubmit={handleSubmit} error={getErrorMessage(error)} values={{ teamId }}>
<Text>
{t(isTeamWebsite ? messages.transferTeamWebsiteToUser : messages.transferUserWebsiteToTeam)}
</Text>
<FormField name="teamId">
{!isTeamWebsite && (
<Select onChange={handleChange} value={teamId}>
{items.map(({ id, name }) => {
return (
<ListItem key={`${id}`} id={`${id}`}>
{name}
</ListItem>
);
})}
</Select>
)}
</FormField>
<FormButtons>
<Button onPress={onClose}>{t(labels.cancel)}</Button>
<FormSubmitButton
variant="primary"
isLoading={isPending}
isDisabled={!isTeamWebsite && !teamId}
>
{t(labels.transfer)}
</FormSubmitButton>
</FormButtons>
<Form onSubmit={handleSubmit} error={getErrorMessage(error)} defaultValues={{ teamId: '' }}>
{({ watch }) => {
const selectedTeamId = watch('teamId');
return (
<>
<Text>
{t(
isTeamWebsite
? messages.transferTeamWebsiteToUser
: messages.transferUserWebsiteToTeam,
)}
</Text>
<FormField name="teamId">
{!isTeamWebsite && (
<Select>
{items.map(({ id, name }) => {
return (
<ListItem key={`${id}`} id={`${id}`}>
{name}
</ListItem>
);
})}
</Select>
)}
</FormField>
<FormButtons>
<Button onPress={onClose}>{t(labels.cancel)}</Button>
<FormSubmitButton
variant="primary"
isLoading={isPending}
isDisabled={!isTeamWebsite && !selectedTeamId}
>
{t(labels.transfer)}
</FormSubmitButton>
</FormButtons>
</>
);
}}
</Form>
);
}
+67
View File
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { parseRequest } from '@/lib/request';
import { OPTIONS, POST } from './route';
vi.mock('@/lib/detect', () => ({
getClientInfo: vi.fn(),
hasBlockedIp: vi.fn(),
}));
vi.mock('@/lib/jwt', () => ({
parseToken: vi.fn(),
}));
vi.mock('@/lib/request', () => ({
parseRequest: vi.fn(),
}));
vi.mock('@/queries/prisma', () => ({
getWebsite: vi.fn(),
}));
vi.mock('@/queries/sql', () => ({
saveRecording: vi.fn(),
}));
vi.mock('@/queries/sql/heatmap/saveHeatmapEvents', () => ({
saveHeatmapEvents: vi.fn(),
}));
const parseRequestMock = vi.mocked(parseRequest);
beforeEach(() => {
vi.clearAllMocks();
});
describe('record route CORS', () => {
test('handles preflight requests', async () => {
const response = OPTIONS();
expect(response.status).toBe(204);
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
expect(response.headers.get('Access-Control-Allow-Headers')).toContain('x-umami-cache');
expect(response.headers.get('Access-Control-Allow-Methods')).toContain('POST');
});
test('includes CORS headers on post responses', async () => {
parseRequestMock.mockResolvedValue({
body: {
type: 'record',
payload: {
website: '11111111-1111-4111-8111-111111111111',
events: [],
},
},
error: undefined,
});
const response = await POST(
new Request('http://localhost/api/record', {
method: 'POST',
}),
);
expect(response.status).toBe(200);
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
});
});
+26 -19
View File
@@ -2,6 +2,7 @@ import { isbot } from 'isbot';
import { serializeError } from 'serialize-error';
import { z } from 'zod';
import { HEATMAP_EVENT_TYPE } from '@/lib/constants';
import { corsPreflight, withCorsHeaders } from '@/lib/cors';
import { secret } from '@/lib/crypto';
import { getClientInfo, hasBlockedIp } from '@/lib/detect';
import { parseToken } from '@/lib/jwt';
@@ -96,22 +97,28 @@ async function getRequestBodySize(request: Request): Promise<number | null> {
}
}
export function OPTIONS() {
return corsPreflight();
}
export async function POST(request: Request) {
try {
const requestBodySize = await getRequestBodySize(request);
if (requestBodySize && requestBodySize > MAX_RECORD_REQUEST_BYTES) {
return payloadTooLarge({
reason: 'payload_too_large',
maxBytes: MAX_RECORD_REQUEST_BYTES,
size: requestBodySize,
});
return withCorsHeaders(
payloadTooLarge({
reason: 'payload_too_large',
maxBytes: MAX_RECORD_REQUEST_BYTES,
size: requestBodySize,
}),
);
}
const { body, error } = await parseRequest(request, schema, { skipAuth: true });
if (error) {
return error();
return withCorsHeaders(error());
}
const { website: websiteId } = body.payload;
@@ -119,20 +126,20 @@ export async function POST(request: Request) {
const timestamp = body.payload.timestamp;
if (!events?.length) {
return json({ ok: true });
return withCorsHeaders(json({ ok: true }));
}
// Parse cache token to get session info
const cacheHeader = request.headers.get('x-umami-cache');
if (!cacheHeader) {
return badRequest({ message: 'Missing session token.' });
return withCorsHeaders(badRequest({ message: 'Missing session token.' }));
}
const cache = (await parseToken(cacheHeader, secret())) as Cache | null;
if (!cache?.sessionId || !cache?.visitId) {
return badRequest({ message: 'Invalid session token.' });
return withCorsHeaders(badRequest({ message: 'Invalid session token.' }));
}
const { sessionId, visitId } = cache;
@@ -141,7 +148,7 @@ export async function POST(request: Request) {
const website = await getWebsite(websiteId);
if (!website) {
return badRequest({ message: 'Website not found.' });
return withCorsHeaders(badRequest({ message: 'Website not found.' }));
}
const recorderConfig = getRecorderConfig(website.replayConfig);
@@ -149,7 +156,7 @@ export async function POST(request: Request) {
const heatmapEnabled = recorderConfig.heatmapEnabled === true;
if (!website.recorderEnabled) {
return json({ ok: false, reason: 'recorder_disabled' });
return withCorsHeaders(json({ ok: false, reason: 'recorder_disabled' }));
}
if (process.env.CLOUD_MODE) {
@@ -160,7 +167,7 @@ export async function POST(request: Request) {
: null;
if (!account?.isBusiness && !account?.isNoBilling) {
return forbidden({ message: 'Business subscription required.' });
return withCorsHeaders(forbidden({ message: 'Business subscription required.' }));
}
}
@@ -168,16 +175,16 @@ export async function POST(request: Request) {
const { ip, userAgent } = await getClientInfo(request, {});
if (!process.env.DISABLE_BOT_CHECK && isbot(userAgent)) {
return json({ beep: 'boop' });
return withCorsHeaders(json({ beep: 'boop' }));
}
if (hasBlockedIp(ip)) {
return forbidden();
return withCorsHeaders(forbidden());
}
if (body.type === 'record') {
if (!replayEnabled) {
return json({ ok: false, reason: 'replay_disabled' });
return withCorsHeaders(json({ ok: false, reason: 'replay_disabled' }));
}
const eventTimestamps = events
@@ -203,11 +210,11 @@ export async function POST(request: Request) {
endedAt,
});
return json({ ok: true });
return withCorsHeaders(json({ ok: true }));
}
if (!heatmapEnabled) {
return json({ ok: false, reason: 'heatmap_disabled' });
return withCorsHeaders(json({ ok: false, reason: 'heatmap_disabled' }));
}
try {
@@ -238,8 +245,8 @@ export async function POST(request: Request) {
console.log('heatmap save failed', serializeError(e));
}
return json({ ok: true });
return withCorsHeaders(json({ ok: true }));
} catch (e) {
return serverError(e);
return withCorsHeaders(serverError(e));
}
}
@@ -0,0 +1,42 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { parseRequest } from '@/lib/request';
import { getWebsite } from '@/queries/prisma';
import { GET, OPTIONS } from './route';
vi.mock('@/lib/request', () => ({
parseRequest: vi.fn(),
}));
vi.mock('@/queries/prisma', () => ({
getWebsite: vi.fn(),
}));
const parseRequestMock = vi.mocked(parseRequest);
const getWebsiteMock = vi.mocked(getWebsite);
beforeEach(() => {
vi.clearAllMocks();
parseRequestMock.mockResolvedValue({ error: undefined });
});
describe('recorder config route CORS', () => {
test('handles preflight requests', async () => {
const response = OPTIONS();
expect(response.status).toBe(204);
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
expect(response.headers.get('Access-Control-Allow-Headers')).toContain('x-umami-cache');
});
test('includes CORS headers on config responses', async () => {
getWebsiteMock.mockResolvedValue(null as any);
const response = await GET(new Request('http://localhost/api/websites/test/recorder'), {
params: Promise.resolve({ websiteId: '11111111-1111-4111-8111-111111111111' }),
});
expect(response.status).toBe(200);
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
expect(response.headers.get('Cache-Control')).toContain('max-age=60');
});
});
@@ -1,7 +1,12 @@
import { corsPreflight, getApiCorsHeaders, withCorsHeaders } from '@/lib/cors';
import { getRecorderConfig } from '@/lib/recorder';
import { parseRequest } from '@/lib/request';
import { getWebsite } from '@/queries/prisma';
export function OPTIONS() {
return corsPreflight();
}
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
@@ -9,13 +14,14 @@ export async function GET(
const { error } = await parseRequest(request, null, { skipAuth: true });
if (error) {
return error();
return withCorsHeaders(error());
}
const { websiteId } = await params;
const website = await getWebsite(websiteId);
const headers = {
...getApiCorsHeaders(),
'Cache-Control': 'public, max-age=60, stale-while-revalidate=300',
};
+46
View File
@@ -80,3 +80,49 @@ select:is(:-webkit-autofill, :autofill):focus {
[data-theme="dark"] .rr-controller__btns .label {
color: black;
}
@media (max-width: 640px) {
.rr-controller {
height: auto !important;
padding: 8px 0 10px;
gap: 8px;
overflow: hidden;
}
.rr-timeline {
width: calc(100% - 24px) !important;
gap: 4px;
}
.rr-timeline__time {
width: auto !important;
min-width: 44px;
font-size: 12px;
}
.rr-progress {
margin: 0 2px;
}
.rr-controller__btns {
width: calc(100% - 24px);
box-sizing: border-box;
flex-wrap: wrap;
justify-content: center;
column-gap: 6px;
row-gap: 8px;
font-size: 12px;
overflow: hidden;
}
.rr-controller__btns button {
width: 28px;
height: 28px;
flex: 0 0 28px;
}
.rr-controller__btns .label {
margin: 0 4px;
font-size: 12px;
}
}
@@ -0,0 +1,161 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { ReactNode } from 'react';
import { render, screen } from '@/test/render';
import { resetTestNavigation } from '@/test/navigation';
import { setShareData } from '@/store/app';
import { ShareProvider } from '@/app/share/ShareProvider';
import { SharePage } from './SharePage';
const mockShare = vi.hoisted(() => ({
slug: 'slug',
shareId: 'share-1',
shareType: 1,
websiteId: 'website-1',
token: 'share-token',
parameters: {
events: true,
},
}));
const initTheme = vi.fn();
vi.mock('@umami/react-zen', async importOriginal => {
const actual = await importOriginal<typeof import('@umami/react-zen')>();
return {
...actual,
useTheme: () => ({
initTheme,
}),
};
});
vi.mock('@/components/hooks', async importOriginal => {
const actual = await importOriginal<typeof import('@/components/hooks')>();
return {
...actual,
useShareTokenQuery: () => ({
share: mockShare,
data: mockShare,
isLoading: false,
isFetching: false,
}),
};
});
vi.mock('@/app/(main)/boards/[boardId]/BoardViewPage', () => ({
BoardViewPage: () => <div>board view page</div>,
}));
vi.mock('@/app/(main)/links/[linkId]/LinkPage', () => ({
LinkPage: () => <div>link page</div>,
}));
vi.mock('@/app/(main)/pixels/[pixelId]/PixelPage', () => ({
PixelPage: () => <div>pixel page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/attribution/AttributionPage', () => ({
AttributionPage: () => <div>attribution page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/breakdown/BreakdownPage', () => ({
BreakdownPage: () => <div>breakdown page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelsPage', () => ({
FunnelsPage: () => <div>funnels page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/goals/GoalsPage', () => ({
GoalsPage: () => <div>goals page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/journeys/JourneysPage', () => ({
JourneysPage: () => <div>journeys page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/performance/PerformancePage', () => ({
PerformancePage: () => <div>performance page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/retention/RetentionPage', () => ({
RetentionPage: () => <div>retention page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/revenue/RevenuePage', () => ({
RevenuePage: () => <div>revenue page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/(reports)/utm/UTMPage', () => ({
UTMPage: () => <div>utm page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/compare/ComparePage', () => ({
ComparePage: () => <div>compare page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/events/EventsPage', () => ({
EventsPage: () => <div>events page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/realtime/RealtimePage', () => ({
RealtimePage: () => <div>realtime page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/sessions/SessionsPage', () => ({
SessionsPage: () => <div>sessions page</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/WebsiteHeader', () => ({
WebsiteHeader: () => <div>website header</div>,
}));
vi.mock('@/app/(main)/websites/[websiteId]/WebsitePage', () => ({
WebsitePage: () => <div>website page</div>,
}));
vi.mock('@/app/(main)/websites/WebsiteProvider', () => ({
WebsiteProvider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
vi.mock('@/components/common/PageBody', () => ({
PageBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
vi.mock('@/components/input/MobileMenuButton', () => ({
MobileMenuButton: ({ children }: { children: ReactNode | ((props: { close: () => void }) => ReactNode) }) => (
<div>{typeof children === 'function' ? children({ close: () => {} }) : children}</div>
),
}));
vi.mock('./ShareFooter', () => ({
ShareFooter: () => <div>share footer</div>,
}));
vi.mock('./ShareNav', () => ({
ShareNav: () => <div>share nav</div>,
}));
describe('SharePage', () => {
beforeEach(() => {
resetTestNavigation();
initTheme.mockReset();
setShareData(mockShare, { token: mockShare.token });
});
test('renders an allowed website share route', () => {
render(
<ShareProvider slug="slug">
<SharePage />
</ShareProvider>,
{ route: '/share/slug/events' },
);
expect(screen.getAllByText('share nav')).toHaveLength(2);
expect(screen.getByText('website header')).toBeInTheDocument();
expect(screen.getByText('events page')).toBeInTheDocument();
expect(initTheme).toHaveBeenCalled();
});
});
+32
View File
@@ -0,0 +1,32 @@
const DEFAULT_CORS_MAX_AGE = process.env.CORS_MAX_AGE || '86400';
export function getApiCorsHeaders(headers: HeadersInit = {}) {
return {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, x-umami-cache',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Max-Age': DEFAULT_CORS_MAX_AGE,
...headers,
};
}
export function withCorsHeaders(response: Response, headers: HeadersInit = {}) {
const nextHeaders = new Headers(response.headers);
Object.entries(getApiCorsHeaders(headers)).forEach(([key, value]) => {
nextHeaders.set(key, value);
});
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: nextHeaders,
});
}
export function corsPreflight(headers: HeadersInit = {}) {
return new Response(null, {
status: 204,
headers: getApiCorsHeaders(headers),
});
}