6 Commits

Author SHA1 Message Date
Carl-Gerhard Lindesvärd
7a96e7b038 sign cooies 2026-03-09 18:29:15 +01:00
Carl-Gerhard Lindesvärd
fc256124b5 comments 2026-03-09 17:21:27 +01:00
Carl-Gerhard Lindesvärd
df0258f532 comments 2026-03-09 14:20:15 +01:00
Carl-Gerhard Lindesvärd
0f9e5f6e93 fix timepicker 2026-03-09 13:48:02 +01:00
Carl-Gerhard Lindesvärd
c9cf7901ad wip 2026-03-09 12:30:28 +01:00
Carl-Gerhard Lindesvärd
2981638893 wip 2026-03-06 13:59:03 +01:00
178 changed files with 3786 additions and 9418 deletions

View File

@@ -30,6 +30,7 @@
"@openpanel/logger": "workspace:*",
"@openpanel/payments": "workspace:*",
"@openpanel/queue": "workspace:*",
"groupmq": "catalog:",
"@openpanel/redis": "workspace:*",
"@openpanel/trpc": "workspace:*",
"@openpanel/validation": "workspace:*",
@@ -39,7 +40,6 @@
"fastify": "^5.6.1",
"fastify-metrics": "^12.1.0",
"fastify-raw-body": "^5.0.0",
"groupmq": "catalog:",
"jsonwebtoken": "^9.0.2",
"ramda": "^0.29.1",
"sharp": "^0.33.5",

View File

@@ -63,7 +63,6 @@ async function main() {
imported_at: null,
sdk_name: 'test-script',
sdk_version: '1.0.0',
groups: [],
});
}

View File

@@ -1,4 +1,4 @@
import { cacheable } from '@openpanel/redis';
import { cacheable, cacheableLru } from '@openpanel/redis';
import bots from './bots';
// Pre-compile regex patterns at module load time
@@ -15,7 +15,7 @@ const compiledBots = bots.map((bot) => {
const regexBots = compiledBots.filter((bot) => 'compiledRegex' in bot);
const includesBots = compiledBots.filter((bot) => 'includes' in bot);
export const isBot = cacheable(
export const isBot = cacheableLru(
'is-bot',
(ua: string) => {
// Check simple string patterns first (fast)
@@ -40,5 +40,8 @@ export const isBot = cacheable(
return null;
},
60 * 5
{
maxSize: 1000,
ttl: 60 * 5,
},
);

View File

@@ -1,12 +1,12 @@
import { isShuttingDown } from '@/utils/graceful-shutdown';
import { chQuery, db } from '@openpanel/db';
import { getRedisCache } from '@openpanel/redis';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { isShuttingDown } from '@/utils/graceful-shutdown';
// For docker compose healthcheck
export async function healthcheck(
request: FastifyRequest,
reply: FastifyReply
reply: FastifyReply,
) {
try {
const redisRes = await getRedisCache().ping();
@@ -21,7 +21,6 @@ export async function healthcheck(
ch: chRes && chRes.length > 0,
});
} catch (error) {
request.log.warn('healthcheck failed', { error });
return reply.status(503).send({
ready: false,
reason: 'dependencies not ready',
@@ -42,22 +41,18 @@ export async function readiness(request: FastifyRequest, reply: FastifyReply) {
// Perform lightweight dependency checks for readiness
const redisRes = await getRedisCache().ping();
const dbRes = await db.$executeRaw`SELECT 1`;
const dbRes = await db.project.findFirst();
const chRes = await chQuery('SELECT 1');
const isReady = redisRes;
const isReady = redisRes && dbRes && chRes;
if (!isReady) {
const res = {
redis: redisRes === 'PONG',
db: !!dbRes,
ch: chRes && chRes.length > 0,
};
request.log.warn('dependencies not ready', res);
return reply.status(503).send({
ready: false,
reason: 'dependencies not ready',
...res,
redis: redisRes === 'PONG',
db: !!dbRes,
ch: chRes && chRes.length > 0,
});
}

View File

@@ -1,5 +1,12 @@
import type { FastifyRequest } from 'fastify';
import superjson from 'superjson';
import type { WebSocket } from '@fastify/websocket';
import { eventBuffer } from '@openpanel/db';
import {
eventBuffer,
getProfileById,
transformMinimalEvent,
} from '@openpanel/db';
import { setSuperJson } from '@openpanel/json';
import {
psubscribeToPublishedEvent,
@@ -7,7 +14,10 @@ import {
} from '@openpanel/redis';
import { getProjectAccess } from '@openpanel/trpc';
import { getOrganizationAccess } from '@openpanel/trpc/src/access';
import type { FastifyRequest } from 'fastify';
export function getLiveEventInfo(key: string) {
return key.split(':').slice(2) as [string, string];
}
export function wsVisitors(
socket: WebSocket,
@@ -15,38 +25,27 @@ export function wsVisitors(
Params: {
projectId: string;
};
}>
}>,
) {
const { params } = req;
const sendCount = () => {
eventBuffer
.getActiveVisitorCount(params.projectId)
.then((count) => {
const unsubscribe = subscribeToPublishedEvent('events', 'saved', (event) => {
if (event?.projectId === params.projectId) {
eventBuffer.getActiveVisitorCount(params.projectId).then((count) => {
socket.send(String(count));
})
.catch(() => {
socket.send('0');
});
};
const unsubscribe = subscribeToPublishedEvent(
'events',
'batch',
({ projectId }) => {
if (projectId === params.projectId) {
sendCount();
}
}
);
});
const punsubscribe = psubscribeToPublishedEvent(
'__keyevent@0__:expired',
(key) => {
const [, , projectId] = key.split(':');
if (projectId === params.projectId) {
sendCount();
const [projectId] = getLiveEventInfo(key);
if (projectId && projectId === params.projectId) {
eventBuffer.getActiveVisitorCount(params.projectId).then((count) => {
socket.send(String(count));
});
}
}
},
);
socket.on('close', () => {
@@ -63,10 +62,18 @@ export async function wsProjectEvents(
};
Querystring: {
token?: string;
type?: 'saved' | 'received';
};
}>
}>,
) {
const { params } = req;
const { params, query } = req;
const type = query.type || 'saved';
if (!['saved', 'received'].includes(type)) {
socket.send('Invalid type');
socket.close();
return;
}
const userId = req.session?.userId;
if (!userId) {
@@ -80,20 +87,24 @@ export async function wsProjectEvents(
projectId: params.projectId,
});
if (!access) {
socket.send('No access');
socket.close();
return;
}
const unsubscribe = subscribeToPublishedEvent(
'events',
'batch',
({ projectId, count }) => {
if (projectId === params.projectId) {
socket.send(setSuperJson({ count }));
type,
async (event) => {
if (event.projectId === params.projectId) {
const profile = await getProfileById(event.profileId, event.projectId);
socket.send(
superjson.stringify(
access
? {
...event,
profile,
}
: transformMinimalEvent(event),
),
);
}
}
},
);
socket.on('close', () => unsubscribe());
@@ -105,7 +116,7 @@ export async function wsProjectNotifications(
Params: {
projectId: string;
};
}>
}>,
) {
const { params } = req;
const userId = req.session?.userId;
@@ -132,9 +143,9 @@ export async function wsProjectNotifications(
'created',
(notification) => {
if (notification.projectId === params.projectId) {
socket.send(setSuperJson(notification));
socket.send(superjson.stringify(notification));
}
}
},
);
socket.on('close', () => unsubscribe());
@@ -146,7 +157,7 @@ export async function wsOrganizationEvents(
Params: {
organizationId: string;
};
}>
}>,
) {
const { params } = req;
const userId = req.session?.userId;
@@ -173,7 +184,7 @@ export async function wsOrganizationEvents(
'subscription_updated',
(message) => {
socket.send(setSuperJson(message));
}
},
);
socket.on('close', () => unsubscribe());

View File

@@ -1,4 +1,5 @@
import crypto from 'node:crypto';
import { HttpError } from '@/utils/errors';
import { stripTrailingSlash } from '@openpanel/common';
import { hashPassword } from '@openpanel/common/server';
import {
@@ -9,7 +10,6 @@ import {
} from '@openpanel/db';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { z } from 'zod';
import { HttpError } from '@/utils/errors';
// Validation schemas
const zCreateProject = z.object({
@@ -57,7 +57,7 @@ const zUpdateReference = z.object({
// Projects CRUD
export async function listProjects(
request: FastifyRequest,
reply: FastifyReply
reply: FastifyReply,
) {
const projects = await db.project.findMany({
where: {
@@ -74,7 +74,7 @@ export async function listProjects(
export async function getProject(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const project = await db.project.findFirst({
where: {
@@ -92,7 +92,7 @@ export async function getProject(
export async function createProject(
request: FastifyRequest<{ Body: z.infer<typeof zCreateProject> }>,
reply: FastifyReply
reply: FastifyReply,
) {
const parsed = zCreateProject.safeParse(request.body);
@@ -139,9 +139,12 @@ export async function createProject(
},
});
// Clear cache
await Promise.all([
getProjectByIdCached.clear(project.id),
...project.clients.map((client) => getClientByIdCached.clear(client.id)),
project.clients.map((client) => {
getClientByIdCached.clear(client.id);
}),
]);
reply.send({
@@ -162,7 +165,7 @@ export async function updateProject(
Params: { id: string };
Body: z.infer<typeof zUpdateProject>;
}>,
reply: FastifyReply
reply: FastifyReply,
) {
const parsed = zUpdateProject.safeParse(request.body);
@@ -220,9 +223,12 @@ export async function updateProject(
data: updateData,
});
// Clear cache
await Promise.all([
getProjectByIdCached.clear(project.id),
...existing.clients.map((client) => getClientByIdCached.clear(client.id)),
existing.clients.map((client) => {
getClientByIdCached.clear(client.id);
}),
]);
reply.send({ data: project });
@@ -230,7 +236,7 @@ export async function updateProject(
export async function deleteProject(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const project = await db.project.findFirst({
where: {
@@ -260,7 +266,7 @@ export async function deleteProject(
// Clients CRUD
export async function listClients(
request: FastifyRequest<{ Querystring: { projectId?: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const where: any = {
organizationId: request.client!.organizationId,
@@ -294,7 +300,7 @@ export async function listClients(
export async function getClient(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const client = await db.client.findFirst({
where: {
@@ -312,7 +318,7 @@ export async function getClient(
export async function createClient(
request: FastifyRequest<{ Body: z.infer<typeof zCreateClient> }>,
reply: FastifyReply
reply: FastifyReply,
) {
const parsed = zCreateClient.safeParse(request.body);
@@ -368,7 +374,7 @@ export async function updateClient(
Params: { id: string };
Body: z.infer<typeof zUpdateClient>;
}>,
reply: FastifyReply
reply: FastifyReply,
) {
const parsed = zUpdateClient.safeParse(request.body);
@@ -411,7 +417,7 @@ export async function updateClient(
export async function deleteClient(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const client = await db.client.findFirst({
where: {
@@ -438,7 +444,7 @@ export async function deleteClient(
// References CRUD
export async function listReferences(
request: FastifyRequest<{ Querystring: { projectId?: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const where: any = {};
@@ -482,7 +488,7 @@ export async function listReferences(
export async function getReference(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const reference = await db.reference.findUnique({
where: {
@@ -510,7 +516,7 @@ export async function getReference(
export async function createReference(
request: FastifyRequest<{ Body: z.infer<typeof zCreateReference> }>,
reply: FastifyReply
reply: FastifyReply,
) {
const parsed = zCreateReference.safeParse(request.body);
@@ -553,7 +559,7 @@ export async function updateReference(
Params: { id: string };
Body: z.infer<typeof zUpdateReference>;
}>,
reply: FastifyReply
reply: FastifyReply,
) {
const parsed = zUpdateReference.safeParse(request.body);
@@ -610,7 +616,7 @@ export async function updateReference(
export async function deleteReference(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
reply: FastifyReply,
) {
const reference = await db.reference.findUnique({
where: {

View File

@@ -3,20 +3,14 @@ import { generateDeviceId, parseUserAgent } from '@openpanel/common/server';
import {
getProfileById,
getSalts,
groupBuffer,
replayBuffer,
upsertProfile,
} from '@openpanel/db';
import { type GeoLocation, getGeoLocation } from '@openpanel/geo';
import {
type EventsQueuePayloadIncomingEvent,
getEventsGroupQueueShard,
} from '@openpanel/queue';
import { getEventsGroupQueueShard } from '@openpanel/queue';
import { getRedisCache } from '@openpanel/redis';
import {
type IAssignGroupPayload,
type IDecrementPayload,
type IGroupPayload,
type IIdentifyPayload,
type IIncrementPayload,
type IReplayPayload,
@@ -118,7 +112,6 @@ interface TrackContext {
identity?: IIdentifyPayload;
deviceId: string;
sessionId: string;
session?: EventsQueuePayloadIncomingEvent['payload']['session'];
geo: GeoLocation;
}
@@ -148,21 +141,19 @@ async function buildContext(
validatedBody.payload.profileId = profileId;
}
const overrideDeviceId =
validatedBody.type === 'track' &&
typeof validatedBody.payload?.properties?.__deviceId === 'string'
? validatedBody.payload?.properties.__deviceId
: undefined;
// Get geo location (needed for track and identify)
const [geo, salts] = await Promise.all([getGeoLocation(ip), getSalts()]);
const deviceIdResult = await getDeviceId({
const { deviceId, sessionId } = await getDeviceId({
projectId,
ip,
ua,
salts,
overrideDeviceId,
overrideDeviceId:
validatedBody.type === 'track' &&
typeof validatedBody.payload?.properties?.__deviceId === 'string'
? validatedBody.payload?.properties.__deviceId
: undefined,
});
return {
@@ -175,9 +166,8 @@ async function buildContext(
isFromPast: timestamp.isTimestampFromThePast,
},
identity,
deviceId: deviceIdResult.deviceId,
sessionId: deviceIdResult.sessionId,
session: deviceIdResult.session,
deviceId,
sessionId,
geo,
};
}
@@ -186,14 +176,13 @@ async function handleTrack(
payload: ITrackPayload,
context: TrackContext
): Promise<void> {
const { projectId, deviceId, geo, headers, timestamp, sessionId, session } =
context;
const { projectId, deviceId, geo, headers, timestamp, sessionId } = context;
const uaInfo = parseUserAgent(headers['user-agent'], payload.properties);
const groupId = uaInfo.isServer
? payload.profileId
? `${projectId}:${payload.profileId}`
: undefined
: `${projectId}:${generateId()}`
: deviceId;
const jobId = [
slug(payload.name),
@@ -214,14 +203,13 @@ async function handleTrack(
}
promises.push(
getEventsGroupQueueShard(groupId || generateId()).add({
getEventsGroupQueueShard(groupId).add({
orderMs: timestamp.value,
data: {
projectId,
headers,
event: {
...payload,
groups: payload.groups ?? [],
timestamp: timestamp.value,
isTimestampFromThePast: timestamp.isFromPast,
},
@@ -229,7 +217,6 @@ async function handleTrack(
geo,
deviceId,
sessionId,
session,
},
groupId,
jobId,
@@ -337,36 +324,6 @@ async function handleReplay(
await replayBuffer.add(row);
}
async function handleGroup(
payload: IGroupPayload,
context: TrackContext
): Promise<void> {
const { id, type, name, properties = {} } = payload;
await groupBuffer.add({
id,
projectId: context.projectId,
type,
name,
properties,
});
}
async function handleAssignGroup(
payload: IAssignGroupPayload,
context: TrackContext
): Promise<void> {
const profileId = payload.profileId ?? context.deviceId;
if (!profileId) {
return;
}
await upsertProfile({
id: String(profileId),
projectId: context.projectId,
isExternal: !!payload.profileId,
groups: payload.groupIds,
});
}
export async function handler(
request: FastifyRequest<{
Body: ITrackHandlerPayload;
@@ -415,12 +372,6 @@ export async function handler(
case 'replay':
await handleReplay(validatedBody.payload, context);
break;
case 'group':
await handleGroup(validatedBody.payload, context);
break;
case 'assign_group':
await handleAssignGroup(validatedBody.payload, context);
break;
default:
return reply.status(400).send({
status: 400,

View File

@@ -1,19 +1,20 @@
import { isBot } from '@/bots';
import { createBotEvent } from '@openpanel/db';
import type {
DeprecatedPostEventPayload,
ITrackHandlerPayload,
} from '@openpanel/validation';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { isBot } from '@/bots';
export async function isBotHook(
req: FastifyRequest<{
Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
}>,
reply: FastifyReply
reply: FastifyReply,
) {
const bot = req.headers['user-agent']
? await isBot(req.headers['user-agent'])
? isBot(req.headers['user-agent'])
: null;
if (bot && req.client?.projectId) {
@@ -43,6 +44,6 @@ export async function isBotHook(
}
}
return reply.status(202).send({ bot });
return reply.status(202).send();
}
}

View File

@@ -1,5 +1,6 @@
import type { FastifyPluginCallback } from 'fastify';
import { fetchDeviceId, handler } from '@/controllers/track.controller';
import type { FastifyPluginCallback } from 'fastify';
import { clientHook } from '@/hooks/client.hook';
import { duplicateHook } from '@/hooks/duplicate.hook';
import { isBotHook } from '@/hooks/is-bot.hook';
@@ -12,7 +13,7 @@ const trackRouter: FastifyPluginCallback = async (fastify) => {
fastify.route({
method: 'POST',
url: '/',
handler,
handler: handler,
});
fastify.route({

View File

@@ -1,12 +1,7 @@
import crypto from 'node:crypto';
import { generateDeviceId } from '@openpanel/common/server';
import { getSafeJson } from '@openpanel/json';
import type {
EventsQueuePayloadCreateSessionEnd,
EventsQueuePayloadIncomingEvent,
} from '@openpanel/queue';
import { getRedisCache } from '@openpanel/redis';
import { pick } from 'ramda';
export async function getDeviceId({
projectId,
@@ -42,20 +37,14 @@ export async function getDeviceId({
ua,
});
return await getInfoFromSession({
return await getDeviceIdFromSession({
projectId,
currentDeviceId,
previousDeviceId,
});
}
interface DeviceIdResult {
deviceId: string;
sessionId: string;
session?: EventsQueuePayloadIncomingEvent['payload']['session'];
}
async function getInfoFromSession({
async function getDeviceIdFromSession({
projectId,
currentDeviceId,
previousDeviceId,
@@ -63,7 +52,7 @@ async function getInfoFromSession({
projectId: string;
currentDeviceId: string;
previousDeviceId: string;
}): Promise<DeviceIdResult> {
}) {
try {
const multi = getRedisCache().multi();
multi.hget(
@@ -76,33 +65,21 @@ async function getInfoFromSession({
);
const res = await multi.exec();
if (res?.[0]?.[1]) {
const data = getSafeJson<EventsQueuePayloadCreateSessionEnd>(
const data = getSafeJson<{ payload: { sessionId: string } }>(
(res?.[0]?.[1] as string) ?? ''
);
if (data) {
return {
deviceId: currentDeviceId,
sessionId: data.payload.sessionId,
session: pick(
['referrer', 'referrerName', 'referrerType'],
data.payload
),
};
const sessionId = data.payload.sessionId;
return { deviceId: currentDeviceId, sessionId };
}
}
if (res?.[1]?.[1]) {
const data = getSafeJson<EventsQueuePayloadCreateSessionEnd>(
const data = getSafeJson<{ payload: { sessionId: string } }>(
(res?.[1]?.[1] as string) ?? ''
);
if (data) {
return {
deviceId: previousDeviceId,
sessionId: data.payload.sessionId,
session: pick(
['referrer', 'referrerName', 'referrerType'],
data.payload
),
};
const sessionId = data.payload.sessionId;
return { deviceId: previousDeviceId, sessionId };
}
}
} catch (error) {

View File

@@ -1,7 +1,7 @@
---
date: 2025-07-18
title: "13 Best Product Analytics Tools in 2026 (Ranked & Compared)"
description: "Compare the best product analytics tools in 2026. Side-by-side pricing, features, and privacy comparison of 13 platforms — including open source, self-hosted, and free options for every team size."
title: "13 Best Mixpanel Alternatives & Competitors in 2026"
description: "Compare the best Mixpanel alternatives for product analytics in 2026. Side-by-side pricing, features, and privacy comparison of 7 top tools plus 6 honorable mentions — including open source and free options."
updated: 2026-02-16
tag: Comparison
team: OpenPanel Team

View File

@@ -3,7 +3,7 @@
"page_type": "alternative",
"seo": {
"title": "Best Amplitude Alternatives 2026 - Open Source, Free & Paid",
"description": "Compare the best Amplitude alternatives in 2026: OpenPanel, PostHog, Heap, and Plausible. Open source, privacy-first, and affordable options for every team size. See which fits you best.",
"description": "Compare the best Amplitude alternatives in 2026: OpenPanel, PostHog, Mixpanel, Heap, and Plausible. Open source, privacy-first, and affordable options for every team size. See which fits you best.",
"noindex": false
},
"hero": {

View File

@@ -2,8 +2,8 @@
"slug": "fullstory-alternative",
"page_type": "alternative",
"seo": {
"title": "Best FullStory Alternatives 2026 — Cheaper & Privacy-First",
"description": "FullStory pricing starts at $300/month. OpenPanel delivers product analytics — events, funnels, and retention — at $2.50/month or free to self-host. No enterprise contract required.",
"title": "Best FullStory Alternative 2026 - Open Source & Free",
"description": "Looking for a FullStory alternative? OpenPanel offers product analytics with transparent pricing, self-hosting, and privacy-first tracking \u2014 no expensive session replay costs. Free to start.",
"noindex": false
},
"hero": {

View File

@@ -2,8 +2,8 @@
"slug": "heap-alternative",
"page_type": "alternative",
"seo": {
"title": "Best Heap Alternatives 2026 — After the Contentsquare Acquisition",
"description": "Heap was acquired by Contentsquare in 2023. If you're re-evaluating, OpenPanel is an open-source alternative with transparent pricing from $2.50/month, full self-hosting, and no sales call required.",
"title": "Best Heap Alternative 2026 - Open Source & Free",
"description": "Looking for a Heap alternative? OpenPanel offers transparent pricing, lightweight analytics, and self-hosting without autocapture complexity. Open source and free to get started.",
"noindex": false
},
"hero": {
@@ -27,8 +27,8 @@
"overview": {
"title": "Why consider OpenPanel over Heap?",
"paragraphs": [
"Heap was acquired by Contentsquare in September 2023. For many teams, that acquisition raised real questions: Will pricing change? Will the product roadmap shift to serve Contentsquare's enterprise customers? Will independent support continue? These concerns, combined with Heap's opaque pricing model and cloud-only architecture, have driven a wave of teams to evaluate alternatives.",
"OpenPanel takes a different approach with explicit event tracking, giving you precise control over what you measure and how. While you lose Heap's retroactive analysis capability, you gain transparency \u2014 both in your data collection and your costs. OpenPanel's pricing is publicly listed and event-based, starting at just $2.50 per month, compared to Heap's sales-required pricing that reportedly starts at $3,600 per year. And unlike Heap, OpenPanel is fully self-hostable and open source \u2014 no acquisition can change that.",
"Heap made its name with autocapture \u2014 the ability to automatically record every user interaction and analyze it retroactively. It's a compelling feature for teams that want to ask questions about user behavior without planning instrumentation in advance. But Heap's acquisition by Contentsquare, opaque enterprise pricing, and cloud-only architecture have many teams looking for alternatives.",
"OpenPanel takes a different approach with explicit event tracking, giving you precise control over what you measure and how. While you lose Heap's retroactive analysis capability, you gain transparency \u2014 both in your data collection and your costs. OpenPanel's pricing is publicly listed and event-based, starting at just $2.50 per month, compared to Heap's sales-required pricing that reportedly starts at $3,600 per year.",
"For teams that value data sovereignty, OpenPanel offers full self-hosting via a simple Docker deployment \u2014 something Heap doesn't provide at all. Being open source under the MIT license means you can inspect every line of code, contribute improvements, and avoid the vendor lock-in risk that comes with Heap's proprietary, now-Contentsquare-owned platform.",
"If you prefer intentional, controlled analytics over autocapture-everything, want transparent pricing without sales calls, and need the option to self-host \u2014 OpenPanel gives you solid product analytics with full ownership of your data."
]
@@ -443,8 +443,8 @@
],
"articles": [
{
"title": "Best product analytics tools in 2026",
"url": "/articles/mixpanel-alternatives"
"title": "Find an alternative to Mixpanel",
"url": "/articles/alternatives-to-mixpanel"
},
{
"title": "9 best open source web analytics tools",

View File

@@ -2,13 +2,13 @@
"slug": "mixpanel-alternative",
"page_type": "alternative",
"seo": {
"title": "OpenPanel vs Mixpanel (2026): Full Feature & Pricing Comparison",
"description": "Side-by-side comparison of OpenPanel and Mixpanel: pricing, features, self-hosting, privacy, and migration guide. See which product analytics platform is right for your team.",
"title": "Best Mixpanel Alternative 2026 - Open Source & Free",
"description": "Looking for a Mixpanel alternative? OpenPanel offers powerful product analytics at a fraction of the cost \u2014 with EU-only hosting, self-hosting, and full data ownership. Try free today.",
"noindex": false
},
"hero": {
"heading": "OpenPanel vs Mixpanel",
"subheading": "A complete side-by-side comparison of OpenPanel and Mixpanel \u2014 pricing, features, self-hosting, privacy, and what it takes to switch. Make an informed decision before you migrate.",
"heading": "Best Mixpanel Alternative",
"subheading": "OpenPanel is an open-source, privacy-first alternative to Mixpanel. Get powerful product analytics\u2014events, funnels, retention, and user profiles\u2014without event-based pricing that scales to thousands per month or sending your data to US servers.",
"badges": [
"Open-source",
"EU-only hosting",

View File

@@ -2,8 +2,8 @@
"slug": "posthog-alternative",
"page_type": "alternative",
"seo": {
"title": "Best PostHog Alternatives in 2026 — Simpler, Free & Self-Hosted",
"description": "Looking for a simpler PostHog alternative? OpenPanel is free, open-source, and self-hostable — 2.3 KB SDK, cookie-free tracking, and no complex feature flags or session replay you don't need.",
"title": "Best PostHog Alternative 2026 - Open Source & Free",
"description": "Looking for a PostHog alternative? OpenPanel offers simpler analytics with better privacy, a lighter SDK, and transparent pricing \u2014 no complex tiers. Open source and free to self-host.",
"noindex": false
},
"hero": {

View File

@@ -2,8 +2,8 @@
"slug": "smartlook-alternative",
"page_type": "alternative",
"seo": {
"title": "5 Best Smartlook Alternatives in 2026 (Free & Open Source)",
"description": "Replace Smartlook's session recording with OpenPanel — cookie-free product analytics with events, funnels, and retention. Open source, self-hostable, and no consent banners required.",
"title": "Best Smartlook Alternative 2026 - Open Source & Free",
"description": "Looking for a Smartlook alternative? OpenPanel offers product analytics with self-hosting, transparent pricing, and mobile SDKs \u2014 without session replay costs. Open source and free to start.",
"noindex": false
},
"hero": {

View File

@@ -68,34 +68,6 @@ app.listen(3000, () => {
- `trackRequest` - A function that returns `true` if the request should be tracked.
- `getProfileId` - A function that returns the profile ID of the user making the request.
## Working with Groups
Groups let you track analytics at the account or company level. Since Express is a backend SDK, you can upsert groups and assign users from your route handlers.
See the [Groups guide](/docs/get-started/groups) for the full walkthrough.
```ts
app.post('/login', async (req, res) => {
const user = await loginUser(req.body);
// Identify the user
req.op.identify({ profileId: user.id, email: user.email });
// Create/update the group entity
req.op.upsertGroup({
id: user.organizationId,
type: 'company',
name: user.organizationName,
properties: { plan: user.plan },
});
// Assign the user to the group
req.op.setGroup(user.organizationId);
res.json({ ok: true });
});
```
## Typescript
If `req.op` is not typed you can extend the `Request` interface.

View File

@@ -116,38 +116,9 @@ op.decrement({
});
```
### Working with Groups
Groups let you track analytics at the account or company level. See the [Groups guide](/docs/get-started/groups) for the full walkthrough.
**Create or update a group:**
```js title="index.js"
import { op } from './op.ts'
op.upsertGroup({
id: 'org_acme',
type: 'company',
name: 'Acme Inc',
properties: { plan: 'enterprise' },
});
```
**Assign the current user to a group** (call after `identify`):
```js title="index.js"
import { op } from './op.ts'
op.setGroup('org_acme');
// or multiple groups:
op.setGroups(['org_acme', 'team_eng']);
```
Once set, all subsequent `track()` calls will automatically include the group IDs.
### Clearing User Data
To clear the current user's data (including groups):
To clear the current user's data:
```js title="index.js"
import { op } from './op.ts'

View File

@@ -227,32 +227,9 @@ useOpenPanel().decrement({
});
```
### Working with Groups
Groups let you track analytics at the account or company level. See the [Groups guide](/docs/get-started/groups) for the full walkthrough.
**Create or update a group:**
```tsx title="app/login/page.tsx"
useOpenPanel().upsertGroup({
id: 'org_acme',
type: 'company',
name: 'Acme Inc',
properties: { plan: 'enterprise' },
});
```
**Assign the current user to a group** (call after `identify`):
```tsx title="app/login/page.tsx"
useOpenPanel().setGroup('org_acme');
```
Once set, all subsequent `track()` calls will automatically include the group IDs.
### Clearing User Data
To clear the current user's data (including groups):
To clear the current user's data:
```js title="index.js"
useOpenPanel().clear()

View File

@@ -174,37 +174,9 @@ function MyComponent() {
}
```
### Working with Groups
Groups let you track analytics at the account or company level. See the [Groups guide](/docs/get-started/groups) for the full walkthrough.
```tsx
import { op } from '@/openpanel';
function LoginComponent() {
const handleLogin = async (user: User) => {
// 1. Identify the user
op.identify({ profileId: user.id, email: user.email });
// 2. Create/update the group entity (only when data changes)
op.upsertGroup({
id: user.organizationId,
type: 'company',
name: user.organizationName,
properties: { plan: user.plan },
});
// 3. Link the user to their group — tags all future events
op.setGroup(user.organizationId);
};
return <button onClick={() => handleLogin(user)}>Login</button>;
}
```
### Clearing User Data
To clear the current user's data (including groups):
To clear the current user's data:
```tsx
import { op } from '@/openpanel';

View File

@@ -59,16 +59,7 @@ The trailing edge of the line (the current, incomplete interval) is shown as a d
## Insights
A scrollable row of insight cards appears below the chart once your project has at least 30 days of data. OpenPanel automatically detects significant trends across pageviews, entry pages, referrers, and countries—no configuration needed.
Each card shows:
- **Share**: The percentage of total traffic that property represents (e.g., "United States: 42% of all sessions")
- **Absolute change**: The raw increase or decrease in sessions compared to the previous period
- **Percentage change**: How much that property grew or declined relative to its own previous value
For example, if the US had 1,000 sessions last week and 1,200 this week, the card shows "+200 sessions (+20%)".
Clicking any insight card filters the entire overview page to show only data matching that property—letting you drill into what's driving the trend.
If you have configured [Insights](/features/insights) for your project, a scrollable row of insight cards appears below the chart. Each card shows a pre-configured metric with its current value and trend. Clicking a card applies that insight's filter to the entire overview page. Insights are optional—this section is hidden when none have been configured.
---

View File

@@ -1,208 +0,0 @@
---
title: Groups
description: Track analytics at the account, company, or team level — not just individual users.
---
import { Callout } from 'fumadocs-ui/components/callout';
Groups let you associate users with a shared entity — like a company, workspace, or team — and analyze behavior at that level. Instead of asking "what did Jane do?", you can ask "what is Acme Inc doing?"
This is especially useful for B2B SaaS products where a single paying account has many users.
## How Groups work
There are two separate concepts:
1. **The group entity** — created/updated with `upsertGroup()`. Stores metadata about the group (name, plan, etc.).
2. **Group membership** — set with `setGroup()` / `setGroups()`. Links a user profile to one or more groups, and automatically attaches those group IDs to every subsequent `track()` call.
## Creating or updating a group
Call `upsertGroup()` to create a group or update its properties. The group is identified by its `id` and `type`.
```typescript
op.upsertGroup({
id: 'org_acme', // Your group's unique ID
type: 'company', // Group type (company, workspace, team, etc.)
name: 'Acme Inc', // Display name
properties: {
plan: 'enterprise',
seats: 25,
industry: 'logistics',
},
});
```
### Group payload
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | Yes | Unique identifier for the group |
| `type` | `string` | Yes | Category of group (e.g. `"company"`, `"workspace"`) |
| `name` | `string` | Yes | Human-readable display name |
| `properties` | `object` | No | Custom metadata about the group |
## Managing groups in the dashboard
The easiest way to create, edit, and delete groups is directly in the OpenPanel dashboard. Navigate to your project and open the **Groups** section — from there you can manage group names, types, and properties without touching any code.
`upsertGroup()` is the right tool when your group properties are **dynamic and driven by your own data** — for example, syncing a customer's current plan, seat count, or MRR from your backend at login time.
<Callout>
A good rule of thumb: call `upsertGroup()` on login or when group properties change — not on every request or page view. If you find yourself calling it frequently with the same data, the dashboard is probably the better place to manage that group.
</Callout>
## Assigning a user to a group
After identifying a user, call `setGroup()` to link them to a group. This also attaches the group ID to all future `track()` calls for the current session.
```typescript
// After login
op.identify({ profileId: 'user_123' });
// Link the user to their organization
op.setGroup('org_acme');
```
For users that belong to multiple groups:
```typescript
op.setGroups(['org_acme', 'team_engineering']);
```
<Callout>
`setGroup()` and `setGroups()` persist group IDs on the SDK instance. All subsequent `track()` calls will automatically include these group IDs until `clear()` is called.
</Callout>
## Full login flow example
`setGroup()` doesn't require the group to exist first. You can call it with just an ID — events will be tagged with that group ID, and you can create the group later in the dashboard or via `upsertGroup()`.
```typescript
// 1. Identify the user
op.identify({
profileId: 'user_123',
firstName: 'Jane',
email: 'jane@acme.com',
});
// 2. Assign the user to the group — the group doesn't need to exist yet
op.setGroup('org_acme');
// 3. All subsequent events are now tagged with the group
op.track('dashboard_viewed'); // → includes groups: ['org_acme']
op.track('report_exported'); // → includes groups: ['org_acme']
```
If you want to sync dynamic group properties from your own data (plan, seats, MRR), add `upsertGroup()` to the flow:
```typescript
op.identify({ profileId: 'user_123', email: 'jane@acme.com' });
// Sync group metadata from your backend
op.upsertGroup({
id: 'org_acme',
type: 'company',
name: 'Acme Inc',
properties: { plan: 'pro' },
});
op.setGroup('org_acme');
```
## Per-event group override
You can attach group IDs to a specific event without affecting the SDK's persistent group state:
```typescript
op.track('file_shared', {
filename: 'q4-report.pdf',
groups: ['org_acme', 'org_partner'], // Only applies to this event
});
```
Groups passed in `track()` are **merged** with any groups already set on the SDK instance.
## Clearing groups on logout
`clear()` resets the profile, device, session, and all groups. Always call it on logout.
```typescript
function handleLogout() {
op.clear();
// redirect to login...
}
```
## Common patterns
### B2B SaaS — company accounts
```typescript
// On login
op.identify({ profileId: user.id, email: user.email });
op.upsertGroup({
id: user.organizationId,
type: 'company',
name: user.organizationName,
properties: { plan: user.plan, mrr: user.mrr },
});
op.setGroup(user.organizationId);
```
### Multi-tenant — workspaces
```typescript
// When user switches workspace
op.upsertGroup({
id: workspace.id,
type: 'workspace',
name: workspace.name,
});
op.setGroup(workspace.id);
```
### Teams within a company
```typescript
// User belongs to a company and a specific team
op.setGroups([user.organizationId, user.teamId]);
```
## API reference
### `upsertGroup(payload)`
Creates the group if it doesn't exist, or merges properties into the existing group.
```typescript
op.upsertGroup({
id: string; // Required
type: string; // Required
name: string; // Required
properties?: Record<string, unknown>;
});
```
### `setGroup(groupId)`
Adds a single group ID to the SDK's internal group list and sends an `assign_group` event to link the current profile to that group.
```typescript
op.setGroup('org_acme');
```
### `setGroups(groupIds)`
Same as `setGroup()` but for multiple group IDs at once.
```typescript
op.setGroups(['org_acme', 'team_engineering']);
```
## What to avoid
- **Calling `upsertGroup()` on every event or page view** — call it on login or when group properties actually change. For static group management, use the dashboard instead.
- **Not calling `setGroup()` after `identify()`** — without it, events won't be tagged with the group and you won't see group-level data in the dashboard.
- **Forgetting `clear()` on logout** — groups persist on the SDK instance, so a new user logging in on the same session could inherit the previous user's groups.
- **Using `upsertGroup()` to link a user to a group** — `upsertGroup()` manages the group entity only. Use `setGroup()` to link a user profile to it.

View File

@@ -3,7 +3,6 @@
"install-openpanel",
"track-events",
"identify-users",
"groups",
"revenue-tracking"
]
}

View File

@@ -1,155 +0,0 @@
{
"slug": "nextjs",
"audience": "nextjs",
"seo": {
"title": "Next.js Analytics — OpenPanel SDK for App Router & Pages Router",
"description": "Add analytics to your Next.js app in minutes. OpenPanel's Next.js SDK supports App Router, Pages Router, server-side events, and automatic route change tracking. Open source, cookieless, from $2.50/month.",
"noindex": false
},
"hero": {
"heading": "Analytics Built for Next.js",
"subheading": "Most analytics tools treat Next.js like a static site. OpenPanel was built for how Next.js actually works — App Router, server components, API routes, and route changes all tracked correctly. Install in 5 minutes, get events, funnels, and user profiles that work with SSR.",
"badges": [
"App Router support",
"Server-side events",
"Auto route tracking",
"2.3 KB client bundle"
]
},
"problem": {
"title": "Why standard analytics breaks in Next.js",
"intro": "Next.js is not a traditional website. Most analytics tools were built before App Router existed and show it.",
"items": [
{
"title": "GA4 breaks with App Router route changes",
"description": "Google Analytics was designed for traditional page loads. In Next.js App Router, client-side navigation doesn't trigger GA4's page view events unless you add custom workarounds. Your analytics misses a significant portion of page views."
},
{
"title": "Cookie consent is painful in Next.js",
"description": "Implementing a GDPR-compliant cookie consent flow in a Next.js app requires next/script, consent state management, and conditional script loading. It's a non-trivial engineering task just to run analytics."
},
{
"title": "No server-side tracking",
"description": "Most analytics SDKs are client-only. Server-side events — API route completions, background jobs, server actions — are invisible. You're missing half the picture."
},
{
"title": "Analytics libraries bloat your bundle",
"description": "Many analytics SDKs add 2050 KB to your JavaScript bundle. In a performance-conscious Next.js app, that overhead matters for Core Web Vitals."
}
]
},
"features": {
"title": "Analytics that works the way Next.js works",
"intro": "OpenPanel's Next.js SDK was designed for modern Next.js patterns — not adapted from a legacy client-only library.",
"items": [
{
"title": "Next.js SDK with App Router support",
"description": "Install @openpanel/nextjs, add the <OpenPanelComponent> to your root layout, and automatic route change tracking works immediately across App Router and Pages Router."
},
{
"title": "Automatic route change tracking",
"description": "Every router.push(), <Link> navigation, and back/forward browser action is captured as a page view. No custom useEffect or router event listeners needed."
},
{
"title": "Server-side event tracking",
"description": "Import openPanel in any server component, API route, or server action to track events server-side. Track form submissions, payment completions, and background jobs without any client involvement."
},
{
"title": "Cookieless by default",
"description": "The OpenPanel SDK uses no cookies. No consent management library, no conditional script loading, no GDPR consent modal needed — just install and track."
},
{
"title": "Identify users across sessions",
"description": "Call op.identify({ profileId, name, email }) after authentication to tie anonymous events to known users. Works with any auth solution including NextAuth.js, Clerk, and custom implementations."
},
{
"title": "TypeScript-first SDK",
"description": "Full TypeScript types for all methods. Autocomplete for event names and properties. Zero runtime errors from mistyped event calls."
},
{
"title": "2.3 KB gzipped client bundle",
"description": "The smallest full-featured analytics SDK for Next.js. No impact on Lighthouse scores or Core Web Vitals."
}
]
},
"benefits": {
"title": "Why Next.js developers choose OpenPanel",
"intro": "OpenPanel fits naturally into a modern Next.js codebase — not as an afterthought.",
"items": [
{
"title": "Works exactly how Next.js works",
"description": "Built for App Router, server components, and modern Next.js patterns. Not bolted onto a client-only library."
},
{
"title": "No consent infrastructure needed",
"description": "Cookieless tracking means no consent modal, no next/script loading gymnastics, no conditional initialization. Install once, works everywhere."
},
{
"title": "Track server and client events in the same dashboard",
"description": "Server actions, API endpoints, and client interactions all show up together. Full picture of what your app is doing."
},
{
"title": "Open source and self-hostable",
"description": "Run OpenPanel on your own infrastructure. Your Next.js app's analytics data never leaves your servers."
},
{
"title": "From $2.50/month",
"description": "No enterprise contract, no per-seat fees. Pay for events, get all features. Start free with 30-day trial."
}
]
},
"faqs": {
"title": "Frequently asked questions",
"intro": "Common questions from Next.js developers evaluating OpenPanel.",
"items": [
{
"question": "How do I install OpenPanel in a Next.js app?",
"answer": "Install @openpanel/nextjs, add <OpenPanelComponent clientId=\"...\" /> to your root layout.tsx, and you're tracking page views. For custom events, import and call op.track('event_name', { properties }) anywhere. See the full step-by-step guide at /guides/nextjs-analytics."
},
{
"question": "Does OpenPanel support Next.js App Router?",
"answer": "Yes. The <OpenPanelComponent> handles App Router route changes automatically using the usePathname hook internally. No custom setup is needed for client-side navigation tracking."
},
{
"question": "Can I track events in Server Components and API Routes?",
"answer": "Yes. Import { openPanel } from @openpanel/nextjs/server and call openPanel.track() in any server context including Server Components, Route Handlers, and Server Actions."
},
{
"question": "Does OpenPanel work with NextAuth.js or Clerk?",
"answer": "Yes. Call op.identify({ profileId: session.user.id, ... }) after authentication to link events to user identities. Works with any auth solution that gives you a user ID."
},
{
"question": "Does OpenPanel add significant bundle size to my Next.js app?",
"answer": "No. The client-side SDK is 2.3 KB gzipped. For reference, GA4 adds 50+ KB. OpenPanel has negligible impact on your bundle size or Core Web Vitals."
},
{
"question": "Can I self-host OpenPanel for my Next.js app?",
"answer": "Yes. OpenPanel is fully open source and can be self-hosted with Docker. Your Next.js app sends events to your own server. The self-hosted version has no event limits and is free to run."
}
]
},
"related_links": {
"guides": [
{ "title": "Next.js analytics setup", "url": "/guides/nextjs-analytics" },
{ "title": "React analytics setup", "url": "/guides/react-analytics" },
{ "title": "Track custom events", "url": "/guides/track-custom-events" }
],
"articles": [
{ "title": "Self-hosted web analytics", "url": "/articles/self-hosted-web-analytics" }
],
"comparisons": [
{ "title": "OpenPanel vs Google Analytics", "url": "/compare/google-analytics-alternative" },
{ "title": "OpenPanel vs PostHog", "url": "/compare/posthog-alternative" }
]
},
"ctas": {
"primary": {
"label": "Try OpenPanel Free",
"href": "https://dashboard.openpanel.dev/onboarding"
},
"secondary": {
"label": "View Source on GitHub",
"href": "https://github.com/Openpanel-dev/openpanel"
}
}
}

View File

@@ -1,165 +0,0 @@
{
"slug": "saas",
"audience": "saas",
"seo": {
"title": "SaaS Analytics — Track Events, Funnels & Retention Without Enterprise Pricing",
"description": "OpenPanel gives SaaS teams the product analytics they need to reduce churn and grow — events, funnels, retention, cohorts, and user profiles. Open source, from $2.50/month.",
"noindex": false
},
"hero": {
"heading": "Product Analytics for SaaS Teams",
"subheading": "Understanding why users churn, where trials drop off, and which features drive retention is the difference between a SaaS that grows and one that plateaus. OpenPanel gives you events, funnels, retention analysis, and user profiles — the core analytics stack for SaaS — without Mixpanel or Amplitude's enterprise pricing.",
"badges": [
"Funnel analysis",
"Retention tracking",
"User profiles",
"From $2.50/month"
]
},
"problem": {
"title": "Why SaaS teams outgrow their analytics tools",
"intro": "The analytics tools most SaaS teams start with either can't answer the right questions or become unaffordable as you grow.",
"items": [
{
"title": "Mixpanel and Amplitude become unaffordable at scale",
"description": "Event-based pricing sounds cheap at 10K events, but SaaS products are event-heavy. At 1M events/month you're paying $300800/month. At 10M, it's thousands. Your analytics bill grows faster than your revenue."
},
{
"title": "GA4 doesn't answer SaaS questions",
"description": "Google Analytics tells you pageviews. It can't tell you which users completed your onboarding flow, how feature adoption correlates with retention, or why your trial-to-paid conversion dropped last month."
},
{
"title": "Complex tools slow down your team",
"description": "Mixpanel's interface is powerful but has a steep learning curve. When it takes 30 minutes to build a simple funnel, your team stops using analytics to make decisions."
},
{
"title": "Cloud-only means full vendor dependence",
"description": "If Mixpanel raises prices, your data is hostage. No export path, no self-hosting option, and a pricing model that punishes growth."
}
]
},
"features": {
"title": "The full product analytics stack for SaaS",
"intro": "Everything your team needs to understand users, reduce churn, and grow — without the enterprise pricing.",
"items": [
{
"title": "Event tracking",
"description": "Track any user action — feature used, button clicked, settings changed, plan upgraded. One line of code. Works across web, mobile, and your backend."
},
{
"title": "Funnel analysis",
"description": "Build conversion funnels for trial signup, onboarding, activation, and upgrade flows. See the exact step losing you the most conversions and fix it."
},
{
"title": "Retention analysis",
"description": "Cohort-based retention charts show you whether users activated in week 1 are still active in week 8. Identify which actions predict long-term retention."
},
{
"title": "User profiles",
"description": "See every event a specific user triggered since they signed up. Walk through their session to diagnose support issues or understand power user behavior."
},
{
"title": "Cohort analysis",
"description": "Group users by signup date, plan, or any property and compare their behavior over time. Understand how product changes affect different user segments."
},
{
"title": "Real-time dashboard",
"description": "See new signups, trial activations, and feature usage as they happen. Know immediately when a new deployment changes user behavior."
},
{
"title": "Revenue tracking",
"description": "Send MRR, payment events, and plan upgrade data to OpenPanel. Correlate feature usage with revenue without a separate BI tool."
},
{
"title": "Multi-platform SDKs",
"description": "Track across web app, marketing site, iOS, Android, and backend in one unified analytics view. Events from all platforms share the same user profiles."
}
]
},
"benefits": {
"title": "Why SaaS teams choose OpenPanel",
"intro": "OpenPanel gives you the analytics depth of Mixpanel at a price that makes sense for growing SaaS products.",
"items": [
{
"title": "Predictable pricing as you scale",
"description": "Flat event tiers from $2.50 to $900/month. No per-seat fees, no MTU limits. Know exactly what you'll pay as your user base grows."
},
{
"title": "Answer the questions SaaS teams actually ask",
"description": "Which onboarding step has the highest drop-off? Which features are used by retained users vs churned users? OpenPanel is built for these questions."
},
{
"title": "Self-host to eliminate per-event costs",
"description": "Large SaaS products generate millions of events. Self-hosting eliminates the cost entirely — pay only for your server infrastructure."
},
{
"title": "All features from day one",
"description": "Funnels, retention, cohorts, user profiles, and dashboards are available at every pricing tier. No feature gating that forces upgrades."
},
{
"title": "Open source and auditable",
"description": "Your product data is sensitive. OpenPanel's open source codebase means you can audit exactly what's tracked and how it's stored."
}
]
},
"faqs": {
"title": "Frequently asked questions",
"intro": "Common questions from SaaS founders and product teams evaluating OpenPanel.",
"items": [
{
"question": "How is OpenPanel different from Mixpanel for SaaS?",
"answer": "OpenPanel covers the same core analytics (events, funnels, retention, cohorts, user profiles) at a fraction of the cost. Mixpanel adds features like Metric Trees and advanced experimentation, but most SaaS teams don't use them. OpenPanel focuses on the analytics that actually drive decisions."
},
{
"question": "Can OpenPanel replace both GA4 and Mixpanel?",
"answer": "Yes. OpenPanel includes web analytics (pageviews, referrers, UTM campaigns) alongside product analytics. Most SaaS teams can replace both tools with one OpenPanel deployment."
},
{
"question": "How do I track trial-to-paid conversions?",
"answer": "Track a trial_started event on signup and a plan_upgraded event on conversion. Build a funnel in OpenPanel between those two events. See conversion rate by cohort, traffic source, or any user property."
},
{
"question": "Does OpenPanel support multi-product or multi-tenant SaaS?",
"answer": "Yes. Use the profileId to identify individual users and pass organization or workspace IDs as properties. You can filter analytics by any property you send."
},
{
"question": "What happens to my data if I stop paying for OpenPanel cloud?",
"answer": "You can export all your event data via the API at any time. Alternatively, migrate to self-hosting — OpenPanel has no lock-in and no proprietary data format."
},
{
"question": "Can I track backend events from my SaaS API?",
"answer": "Yes. OpenPanel has server-side SDKs for Node.js, Python, and a REST API. Track subscription webhooks, background jobs, and server-side logic alongside client events."
},
{
"question": "Is OpenPanel GDPR compliant for SaaS?",
"answer": "Yes. Cookieless tracking by default, EU-only cloud hosting, and the option to self-host for complete data sovereignty. No consent banner required for product analytics."
}
]
},
"related_links": {
"guides": [
{ "title": "Track custom events", "url": "/guides/track-custom-events" },
{ "title": "Next.js analytics setup", "url": "/guides/nextjs-analytics" },
{ "title": "React analytics setup", "url": "/guides/react-analytics" }
],
"articles": [
{ "title": "How to create a funnel", "url": "/articles/how-to-create-a-funnel" },
{ "title": "Self-hosted web analytics", "url": "/articles/self-hosted-web-analytics" }
],
"comparisons": [
{ "title": "OpenPanel vs Mixpanel", "url": "/compare/mixpanel-alternative" },
{ "title": "OpenPanel vs PostHog", "url": "/compare/posthog-alternative" },
{ "title": "OpenPanel vs Amplitude", "url": "/compare/amplitude-alternative" }
]
},
"ctas": {
"primary": {
"label": "Try OpenPanel Free",
"href": "https://dashboard.openpanel.dev/onboarding"
},
"secondary": {
"label": "View Source on GitHub",
"href": "https://github.com/Openpanel-dev/openpanel"
}
}
}

View File

@@ -1,158 +0,0 @@
{
"slug": "shopify",
"audience": "shopify",
"seo": {
"title": "Shopify Analytics — Cookie-Free Tracking Without Consent Banners",
"description": "Add product analytics to your Shopify store without GDPR consent banners. OpenPanel is cookieless by default — track events, funnels, and revenue from $2.50/month or free to self-host.",
"noindex": false
},
"hero": {
"heading": "Shopify Analytics That Actually Works",
"subheading": "Most analytics tools break on Shopify — cookie consent blocks tracking, GA4 loses attribution, and Shopify's built-in reports can't answer the questions that matter. OpenPanel tracks every event without cookies, so your data is complete and your checkout conversion doesn't suffer from a consent banner.",
"badges": [
"Cookie-free tracking",
"No consent banner needed",
"Revenue tracking",
"From $2.50/month"
]
},
"problem": {
"title": "Why analytics breaks on Shopify",
"intro": "Every major analytics tool creates a different problem for Shopify stores. Here's what you're actually dealing with.",
"items": [
{
"title": "GA4 consent mode destroys your data",
"description": "Cookie consent requirements mean 30-50% of visitors opt out. GA4's \"consent mode\" fills gaps with modeled data — you're making decisions on estimates, not reality."
},
{
"title": "Shopify's built-in analytics is shallow",
"description": "Pageviews and sales are there, but you can't build funnels, analyze drop-off by product page, or see which acquisition channel retains customers best."
},
{
"title": "Event tracking requires a developer",
"description": "Installing GA4 on Shopify correctly, with purchase events, add-to-cart, and checkout steps, requires custom code or expensive third-party apps."
},
{
"title": "Cookie banners hurt conversion",
"description": "A consent popup before checkout is a conversion killer. Every analytics tool that uses cookies forces you to choose between data and revenue."
}
]
},
"features": {
"title": "Everything you need to understand your Shopify store",
"intro": "OpenPanel is designed to give you complete visibility into your store's performance — without the privacy headaches.",
"items": [
{
"title": "Script tag install — no developer needed",
"description": "Add one script tag in Shopify's theme settings. Automatic page view tracking starts immediately. No Shopify app or coding required."
},
{
"title": "Cookieless tracking by default",
"description": "No cookies means no consent banner. Your analytics data is 100% complete — not modeled, not estimated, not filtered by opt-outs."
},
{
"title": "Purchase and revenue tracking",
"description": "Track add-to-cart, checkout started, and purchase events with revenue values. See exactly which campaigns and pages drive revenue, not just clicks."
},
{
"title": "Funnel analysis",
"description": "Build funnels from product page → add to cart → checkout → purchase. See exactly where you're losing customers and fix it."
},
{
"title": "UTM campaign attribution",
"description": "Track every paid ad, email campaign, and influencer link. See which traffic source actually converts to buyers, not just visitors."
},
{
"title": "User profiles",
"description": "See the complete journey of any customer — pages visited, products viewed, purchase history. Identify high-value customer behavior patterns."
},
{
"title": "Real-time dashboard",
"description": "Watch your store live. Launch a sale or send an email and see the traffic surge in real time."
},
{
"title": "EU data residency",
"description": "All data stored in the EU. No transfers to US servers. GDPR compliance without the legal complexity."
}
]
},
"benefits": {
"title": "Why Shopify store owners choose OpenPanel",
"intro": "OpenPanel was built to solve the exact problems that plague analytics on Shopify.",
"items": [
{
"title": "Complete data, no consent required",
"description": "Cookieless tracking means every visitor is counted. No consent mode models, no sampling, no gaps from opt-outs."
},
{
"title": "Cheaper than Shopify analytics apps",
"description": "Most Shopify analytics apps charge $50200/month. OpenPanel starts at $2.50/month with all features included."
},
{
"title": "Replace GA4 and your analytics app",
"description": "One tool covers web analytics (traffic, referrers, UTM) and product analytics (funnels, retention, revenue). Cancel two subscriptions."
},
{
"title": "Privacy-first out of the box",
"description": "EU hosting, no cookies, no fingerprinting. No compliance team required to use OpenPanel on your store."
},
{
"title": "Self-host for free",
"description": "For high-volume stores, self-hosting eliminates per-event costs entirely. One Docker deployment, unlimited events."
}
]
},
"faqs": {
"title": "Frequently asked questions",
"intro": "Common questions from Shopify store owners evaluating OpenPanel.",
"items": [
{
"question": "How do I install OpenPanel on Shopify?",
"answer": "Add the OpenPanel script tag via Shopify Admin → Online Store → Themes → Edit Code → theme.liquid. Paste the snippet before </head>. Automatic page views track immediately. For purchase events, add a few lines to your order confirmation page."
},
{
"question": "Does OpenPanel work without a cookie consent banner?",
"answer": "Yes. OpenPanel is cookieless by default and doesn't collect personal data. No consent banner is required under GDPR or CCPA for analytics-only use."
},
{
"question": "Can I track Shopify purchase events?",
"answer": "Yes. Use a simple script on your order confirmation page to send purchase amount, order ID, and product data to OpenPanel. No Shopify app required."
},
{
"question": "How does OpenPanel compare to Lucky Orange or Hotjar for Shopify?",
"answer": "Lucky Orange and Hotjar focus on heatmaps and session replay. OpenPanel focuses on event analytics, funnels, and retention — understanding what users do, not watching recordings. If you need both, they complement each other."
},
{
"question": "Will OpenPanel affect my Shopify store's page speed?",
"answer": "OpenPanel's JavaScript SDK is 2.3 KB gzipped — one of the lightest analytics trackers available. GA4 is 50+ KB. The performance impact is negligible."
},
{
"question": "Does OpenPanel work with Shopify Plus?",
"answer": "Yes. OpenPanel works on any Shopify plan including Plus. The script tag installation method works identically across all plans."
}
]
},
"related_links": {
"guides": [
{ "title": "Ecommerce tracking setup", "url": "/guides/ecommerce-tracking" }
],
"articles": [
{ "title": "Cookieless analytics explained", "url": "/articles/cookieless-analytics" },
{ "title": "Best open source analytics tools", "url": "/articles/open-source-web-analytics" }
],
"comparisons": [
{ "title": "OpenPanel vs Google Analytics", "url": "/compare/google-analytics-alternative" },
{ "title": "OpenPanel vs Plausible", "url": "/compare/plausible-alternative" }
]
},
"ctas": {
"primary": {
"label": "Try OpenPanel Free",
"href": "https://dashboard.openpanel.dev/onboarding"
},
"secondary": {
"label": "View Source on GitHub",
"href": "https://github.com/Openpanel-dev/openpanel"
}
}
}

View File

@@ -1,157 +0,0 @@
{
"slug": "wordpress",
"audience": "wordpress",
"seo": {
"title": "WordPress Analytics Without Cookies — A Google Analytics Alternative",
"description": "Add privacy-first analytics to your WordPress site without cookie consent banners. OpenPanel is cookieless, open source, and starts at $2.50/month — a better alternative to GA4 for WordPress.",
"noindex": false
},
"hero": {
"heading": "WordPress Analytics Without the Cookie Banner",
"subheading": "Google Analytics on WordPress means cookie consent popups, GDPR complexity, and sending your visitors' data to US servers. OpenPanel is a cookieless WordPress analytics plugin that gives you pageviews, events, and user behavior — with full GDPR compliance out of the box and none of the privacy headaches.",
"badges": [
"No cookie banner needed",
"GDPR compliant",
"Open source",
"Lightweight — 2.3 KB"
]
},
"problem": {
"title": "Why Google Analytics on WordPress creates problems",
"intro": "WordPress powers 40% of the web, but GA4 was not designed with WordPress privacy requirements in mind.",
"items": [
{
"title": "Google Analytics requires cookie consent on WordPress",
"description": "Installing GA4 on a WordPress site means a consent popup for every visitor. Under GDPR, you can't set GA4 cookies without explicit opt-in. That banner costs you conversions and corrupts your data."
},
{
"title": "GA4 sends data to US servers",
"description": "Google Analytics transfers visitor data to US servers. For European sites, this creates legal exposure under SCHREMS II — a risk WordPress site owners increasingly can't ignore."
},
{
"title": "WordPress analytics plugins are bloated",
"description": "Most GA4 WordPress plugins add significant weight to your site. Page speed suffers, Core Web Vitals scores drop, and you're still dealing with cookies."
},
{
"title": "You can't see user behavior, only pageviews",
"description": "GA4 tells you how many people visited. OpenPanel tells you what they did: which CTAs they clicked, where they dropped off, which blog posts convert to signups."
}
]
},
"features": {
"title": "Privacy-first analytics for WordPress",
"intro": "OpenPanel gives WordPress site owners complete visibility without the cookie compliance headaches.",
"items": [
{
"title": "Official WordPress plugin",
"description": "Install the OpenPanel WordPress plugin directly from the WordPress plugin directory. Activate it, paste your Client ID, and page view tracking starts immediately — no code required."
},
{
"title": "Automatic page view tracking",
"description": "Every WordPress page, post, and custom post type is tracked automatically. No configuration needed for standard pageview analytics."
},
{
"title": "Cookie-free by default",
"description": "No cookies means no consent banner. Compliant with GDPR, CCPA, and ePrivacy without any configuration."
},
{
"title": "Custom event tracking",
"description": "Track clicks, form submissions, and conversions with a one-line JavaScript call. Know which CTAs and forms drive the most leads."
},
{
"title": "UTM campaign tracking",
"description": "See exactly which emails, ads, and social posts drive traffic to your WordPress site — and which ones actually convert."
},
{
"title": "Lightweight script — 2.3 KB",
"description": "OpenPanel's tracker is 20x smaller than GA4. No impact on Core Web Vitals or PageSpeed scores."
},
{
"title": "Self-hostable on your own server",
"description": "Run OpenPanel on your own infrastructure. Your WordPress visitor data never leaves your servers."
}
]
},
"benefits": {
"title": "Why WordPress site owners switch to OpenPanel",
"intro": "OpenPanel replaces Google Analytics without sacrificing features — and fixes the privacy problems GA4 created.",
"items": [
{
"title": "No consent banner required",
"description": "Cookieless tracking means you're GDPR-compliant without a popup. No lost conversions, no fragmented data from opt-outs."
},
{
"title": "Replace Google Analytics without losing features",
"description": "Pageviews, referrers, countries, devices, UTM campaigns — all there. Plus events and funnels that GA4 requires complex configuration to support."
},
{
"title": "Your data stays out of Google's hands",
"description": "OpenPanel is EU-hosted with no data sharing. Ideal for European sites, publishers, and anyone avoiding Google's data monopoly."
},
{
"title": "Open source and auditable",
"description": "Unlike GA4, OpenPanel's code is public. You can see exactly what data is collected and how it's processed."
},
{
"title": "Affordable pricing",
"description": "From $2.50/month for small WordPress sites. Self-host for free if you prefer — full feature parity, no event limits."
}
]
},
"faqs": {
"title": "Frequently asked questions",
"intro": "Common questions from WordPress site owners evaluating OpenPanel.",
"items": [
{
"question": "How do I install OpenPanel on WordPress?",
"answer": "Add the OpenPanel script tag to your WordPress site via your theme's header.php, a child theme, or any \"header scripts\" plugin. Paste the snippet before </head>. Automatic page view tracking starts immediately — no additional configuration needed."
},
{
"question": "Do I need a cookie consent banner with OpenPanel?",
"answer": "No. OpenPanel uses cookieless tracking and doesn't collect personal data by default. Under GDPR, cookie consent is only required when you actually use cookies. OpenPanel doesn't, so no banner is needed."
},
{
"question": "Is there an OpenPanel WordPress plugin?",
"answer": "Yes. The official OpenPanel plugin is available in the WordPress plugin directory. Search for \"OpenPanel\" in Plugins → Add New, install it, and paste your Client ID. You can also add the script tag manually via your theme's header.php or any \"add code to header\" plugin if you prefer."
},
{
"question": "How does OpenPanel compare to MonsterInsights or Analytify?",
"answer": "Those plugins are wrappers around Google Analytics — they still send data to Google and still require cookies. OpenPanel is an independent analytics platform that's cookieless by default and stores data in the EU."
},
{
"question": "Can I track WooCommerce events?",
"answer": "Yes. You can track add-to-cart, checkout, and purchase events by adding a few lines of JavaScript to your WooCommerce templates or using WordPress hooks. No dedicated WooCommerce plugin required."
},
{
"question": "Does OpenPanel affect WordPress site speed?",
"answer": "OpenPanel's script is 2.3 KB gzipped. By comparison, GA4 adds 50+ KB. Switching from GA4 to OpenPanel will likely improve your Core Web Vitals scores."
}
]
},
"related_links": {
"guides": [
{ "title": "Ecommerce tracking setup", "url": "/guides/ecommerce-tracking" },
{ "title": "Website analytics setup", "url": "/guides/website-analytics-setup" },
{ "title": "OpenPanel WordPress plugin", "url": "https://sv.wordpress.org/plugins/openpanel/" }
],
"articles": [
{ "title": "Cookieless analytics explained", "url": "/articles/cookieless-analytics" },
{ "title": "How to self-host OpenPanel", "url": "/articles/self-hosted-web-analytics" }
],
"comparisons": [
{ "title": "OpenPanel vs Google Analytics", "url": "/compare/google-analytics-alternative" },
{ "title": "OpenPanel vs Plausible", "url": "/compare/plausible-alternative" },
{ "title": "OpenPanel vs Matomo", "url": "/compare/matomo-alternative" }
]
},
"ctas": {
"primary": {
"label": "Try OpenPanel Free",
"href": "https://dashboard.openpanel.dev/onboarding"
},
"secondary": {
"label": "View Source on GitHub",
"href": "https://github.com/Openpanel-dev/openpanel"
}
}
}

View File

@@ -1,38 +1,56 @@
import { ChevronRightIcon } from 'lucide-react';
import {
BarChart3Icon,
ChevronRightIcon,
DollarSignIcon,
GlobeIcon,
PlayCircleIcon,
} from 'lucide-react';
import Link from 'next/link';
import { FeatureCard } from '@/components/feature-card';
import { NotificationsIllustration } from '@/components/illustrations/notifications';
import { ProductAnalyticsIllustration } from '@/components/illustrations/product-analytics';
import { RetentionIllustration } from '@/components/illustrations/retention';
import { SessionReplayIllustration } from '@/components/illustrations/session-replay';
import { WebAnalyticsIllustration } from '@/components/illustrations/web-analytics';
import { Section, SectionHeader } from '@/components/section';
function wrap(child: React.ReactNode) {
return <div className="h-48 overflow-hidden">{child}</div>;
}
const mediumFeatures = [
const features = [
{
title: 'Retention',
title: 'Revenue tracking',
description:
'Know how many users come back after day 1, day 7, day 30. Identify which behaviors predict long-term retention.',
illustration: wrap(<RetentionIllustration />),
link: { href: '/features/retention', children: 'View retention' },
'Track revenue from your payments and get insights into your revenue sources.',
icon: DollarSignIcon,
link: {
href: '/features/revenue-tracking',
children: 'More about revenue',
},
},
{
title: 'Profiles & Sessions',
description:
'Track individual users and their complete journey across your platform.',
icon: GlobeIcon,
link: {
href: '/features/identify-users',
children: 'Identify your users',
},
},
{
title: 'Event Tracking',
description:
'Capture every important interaction with flexible event tracking.',
icon: BarChart3Icon,
link: {
href: '/features/event-tracking',
children: 'All about tracking',
},
},
{
title: 'Session Replay',
description:
'Watch real user sessions to see exactly what happened — clicks, scrolls, rage clicks. Privacy controls built in.',
illustration: wrap(<SessionReplayIllustration />),
link: { href: '/features/session-replay', children: 'See session replay' },
},
{
title: 'Notifications',
description:
'Get notified when a funnel is completed. Stay on top of key moments in your product without watching dashboards all day.',
illustration: wrap(<NotificationsIllustration />),
link: { href: '/features/notifications', children: 'Set up notifications' },
'Watch real user sessions to see exactly what happened. Privacy controls built in, loads async.',
icon: PlayCircleIcon,
link: {
href: '/features/session-replay',
children: 'See session replay',
},
},
];
@@ -41,39 +59,37 @@ export function AnalyticsInsights() {
<Section className="container">
<SectionHeader
className="mb-16"
description="From first page view to long-term retention — every touchpoint in one platform. No sampling, no data limits, no guesswork."
description="Combine web and product analytics in one platform. Track visitors, events, revenue, and user journeys, all with privacy-first tracking."
label="ANALYTICS & INSIGHTS"
title="Everything you need to understand your users"
title="See the full picture of your users and product performance"
/>
<div className="mb-6 grid grid-cols-1 gap-6 md:grid-cols-2">
<FeatureCard
className="px-0 **:data-content:px-6"
description="Understand your website performance with privacy-first analytics. Track visitors, referrers, and page views without touching user cookies."
description="Understand your website performance with privacy-first analytics and clear, actionable insights."
illustration={<WebAnalyticsIllustration />}
title="Web Analytics"
variant="large"
/>
<FeatureCard
className="px-0 **:data-content:px-6"
description="Go beyond page views. Track custom events, understand user flows, and explore exactly how people use your product."
description="Turn raw data into clarity with real-time visualization of performance, behavior, and trends."
illustration={<ProductAnalyticsIllustration />}
title="Product Analytics"
variant="large"
/>
</div>
<div className="grid grid-cols-1 gap-6 md:grid-cols-3">
{mediumFeatures.map((feature) => (
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-4">
{features.map((feature) => (
<FeatureCard
className="px-0 pt-0 **:data-content:px-6"
description={feature.description}
illustration={feature.illustration}
icon={feature.icon}
key={feature.title}
link={feature.link}
title={feature.title}
/>
))}
</div>
<p className="mt-8 text-center">
<Link
className="inline-flex items-center gap-1 text-muted-foreground text-sm transition-colors hover:text-foreground"

View File

@@ -15,23 +15,23 @@ import { CollaborationChart } from './collaboration-chart';
const features = [
{
title: 'Flexible data visualization',
title: 'Visualize your data',
description:
'Build line charts, bar charts, sankey flows, and custom dashboards. Combine metrics from any event into a single view.',
'See your data in a visual way. You can create advanced reports and more to understand',
icon: ChartBarIcon,
slug: 'data-visualization',
},
{
title: 'Share & Collaborate',
description:
'Invite unlimited team members with org-wide or project-level access. Share dashboards publicly or lock them behind a password.',
'Invite unlimited members with org-wide or project-level access. Share full dashboards or individual reports—publicly or behind a password.',
icon: LayoutDashboardIcon,
slug: 'share-and-collaborate',
},
{
title: 'Integrations & Webhooks',
title: 'Integrations',
description:
'Forward events to your own systems or third-party tools. Connect OpenPanel to Slack, your data warehouse, or any webhook endpoint.',
'Get notified when new events are created, or forward specific events to your own systems with our easy-to-use integrations.',
icon: WorkflowIcon,
slug: 'integrations',
},

View File

@@ -43,9 +43,9 @@ export function DataPrivacy() {
/>
<div className="mt-16 mb-6 grid grid-cols-1 gap-6 md:grid-cols-2">
<FeatureCard
description="GDPR compliant and privacy-friendly analytics without cookies or invasive tracking. Data is EU hosted, and a Data Processing Agreement (DPA) is available to sign."
description="Privacy-first analytics without cookies, fingerprinting, or invasive tracking. Built for compliance and user trust."
illustration={<PrivacyIllustration />}
title="GDPR compliant"
title="Privacy-first"
variant="large"
/>
<FeatureCard

View File

@@ -34,9 +34,9 @@ const faqData = [
'We have a dedicated compare page where you can see how OpenPanel compares to other analytics tools. You can find it [here](/compare). You can also read our comprehensive guide on the [best open source web analytics tools](/articles/open-source-web-analytics).',
},
{
question: 'Is OpenPanel a good Mixpanel alternative?',
question: 'How does OpenPanel compare to Mixpanel?',
answer:
"Yes — OpenPanel covers the core features most teams use in Mixpanel: event tracking, funnels, retention, cohorts, and user profiles. The key differences are pricing, privacy, and self-hosting.\n\nOpenPanel starts at $2.50/month and can be self-hosted for free, while Mixpanel is cloud-only and scales to hundreds or thousands per month. OpenPanel is also cookie-free by default with EU-only hosting, so no consent banners required — something Mixpanel can't offer.\n\nSee the full [OpenPanel vs Mixpanel comparison](/compare/mixpanel-alternative) for a side-by-side breakdown.",
"OpenPanel offers similar powerful product analytics features as Mixpanel, but with the added benefits of being open-source, more affordable, and including web analytics capabilities.\n\nYou get Mixpanel's power with Plausible's simplicity.",
},
{
question: 'How does OpenPanel compare to Plausible?',

View File

@@ -1,68 +0,0 @@
import { FeatureCard } from '@/components/feature-card';
import { ConversionsIllustration } from '@/components/illustrations/conversions';
import { GoogleSearchConsoleIllustration } from '@/components/illustrations/google-search-console';
import { RevenueIllustration } from '@/components/illustrations/revenue';
import { Section, SectionHeader } from '@/components/section';
function wrap(child: React.ReactNode) {
return <div className="h-48 overflow-hidden">{child}</div>;
}
const features = [
{
title: 'Revenue Tracking',
description:
'Connect payment events to track MRR and see which referrers drive the most revenue.',
illustration: wrap(<RevenueIllustration />),
link: {
href: '/features/revenue-tracking',
children: 'Track revenue',
},
},
{
title: 'Conversion Tracking',
description:
'Monitor conversion rates over time and break down by A/B variant, country, or device. Catch regressions before they cost you.',
illustration: wrap(<ConversionsIllustration />),
link: {
href: '/features/conversion',
children: 'Track conversions',
},
},
{
title: 'Google Search Console',
description:
'See which search queries bring organic traffic and how visitors convert after landing. Your SEO and product data, in one place.',
illustration: wrap(<GoogleSearchConsoleIllustration />),
link: {
href: '/features/integrations',
children: 'View integrations',
},
},
];
export function FeatureSpotlight() {
return (
<Section className="container">
<SectionHeader
className="mb-16"
description="OpenPanel goes beyond page views. Track revenue, monitor conversions, and connect your SEO data — all without switching tools."
label="GROWTH TOOLS"
title="Built for teams who ship and measure"
/>
<div className="grid grid-cols-1 gap-6 md:grid-cols-3">
{features.map((feature) => (
<FeatureCard
className="px-0 pt-0 **:data-content:px-6"
description={feature.description}
illustration={feature.illustration}
key={feature.title}
link={feature.link}
title={feature.title}
/>
))}
</div>
</Section>
);
}

View File

@@ -5,14 +5,14 @@ import {
CalendarIcon,
CookieIcon,
CreditCardIcon,
DatabaseIcon,
GithubIcon,
ShieldCheckIcon,
ServerIcon,
} from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useState } from 'react';
import { Competition } from '@/components/competition';
import { EuFlag } from '@/components/eu-flag';
import { GetStartedButton } from '@/components/get-started-button';
import { Perks } from '@/components/perks';
import { Button } from '@/components/ui/button';
@@ -21,10 +21,10 @@ import { cn } from '@/lib/utils';
const perks = [
{ text: 'Free trial 30 days', icon: CalendarIcon },
{ text: 'No credit card required', icon: CreditCardIcon },
{ text: 'GDPR compliant', icon: ShieldCheckIcon },
{ text: 'EU hosted', icon: EuFlag },
{ text: 'Cookie-less tracking', icon: CookieIcon },
{ text: 'Open-source', icon: GithubIcon },
{ text: 'Your data, your rules', icon: DatabaseIcon },
{ text: 'Self-hostable', icon: ServerIcon },
];
const aspectRatio = 2946 / 1329;
@@ -90,7 +90,7 @@ export function Hero() {
TRUSTED BY 1,000+ PROJECTS
</div>
<h1 className="font-semibold text-4xl leading-[1.1] md:text-5xl">
The open-source alternative to <Competition />
OpenPanel - The open-source alternative to <Competition />
</h1>
<p className="text-lg text-muted-foreground">
An open-source web and product analytics platform that combines the

View File

@@ -1,63 +0,0 @@
import { BarChart2Icon, CoinsIcon, GithubIcon, ServerIcon } from 'lucide-react';
import Link from 'next/link';
import { FeatureCard } from '@/components/feature-card';
import { GetStartedButton } from '@/components/get-started-button';
import { Section, SectionHeader } from '@/components/section';
import { Button } from '@/components/ui/button';
const reasons = [
{
icon: CoinsIcon,
title: 'Fraction of the cost',
description:
"Mixpanel's pricing scales to hundreds or thousands per month as your event volume grows. OpenPanel starts at $2.50/month — or self-host for free with no event limits.",
},
{
icon: BarChart2Icon,
title: 'The features you actually use',
description:
'Events, funnels, retention, cohorts, user profiles, custom dashboards, and A/B testing — all there. OpenPanel covers every core analytics workflow from Mixpanel without the learning curve.',
},
{
icon: ServerIcon,
title: 'Actually self-hostable',
description:
'Mixpanel is cloud-only. OpenPanel runs on your own infrastructure with a simple Docker setup. Full data ownership, zero vendor lock-in.',
},
{
icon: GithubIcon,
title: 'Open source & transparent',
description:
"Mixpanel is a black box. OpenPanel's code is public on GitHub — audit it, contribute to it, or fork it. No surprises, no hidden data processing.",
},
];
export function MixpanelAlternative() {
return (
<Section className="container">
<SectionHeader
description="OpenPanel covers the product analytics features teams actually use — events, funnels, retention, cohorts, and user profiles — without Mixpanel's pricing, privacy trade-offs, or vendor lock-in."
label="Mixpanel Alternative"
title="Why teams switch from Mixpanel to OpenPanel"
/>
<div className="mt-8 grid grid-cols-1 gap-4 md:grid-cols-2">
{reasons.map((reason) => (
<FeatureCard
description={reason.description}
icon={reason.icon}
key={reason.title}
title={reason.title}
/>
))}
</div>
<div className="row mt-8 gap-4">
<GetStartedButton />
<Button asChild className="px-6" size="lg" variant="outline">
<Link href="/compare/mixpanel-alternative">
OpenPanel vs Mixpanel
</Link>
</Button>
</div>
</Section>
);
}

View File

@@ -55,9 +55,6 @@ export function Pricing() {
<div className="col mt-8 w-full items-baseline md:mt-auto">
{selected ? (
<>
<span className="mb-2 rounded-full bg-primary/10 px-2.5 py-0.5 font-medium text-primary text-xs">
30-day free trial
</span>
<div className="row items-end gap-3">
<NumberFlow
className="font-bold text-5xl"
@@ -70,6 +67,9 @@ export function Pricing() {
locales={'en-US'}
value={selected.price}
/>
<span className="mb-2 rounded-full bg-primary/10 px-2.5 py-0.5 font-medium text-primary text-xs">
30-day free trial
</span>
</div>
<div className="row w-full justify-between">
<span className="-mt-2 text-muted-foreground/80 text-sm">

View File

@@ -1,6 +1,6 @@
'use client';
import { QuoteIcon, StarIcon } from 'lucide-react';
import { QuoteIcon } from 'lucide-react';
import Image from 'next/image';
import Markdown from 'react-markdown';
import { FeatureCardBackground } from '@/components/feature-card';
@@ -94,22 +94,13 @@ export function WhyOpenPanel() {
))}
</div>
<div className="-mx-4 grid grid-cols-1 border-y py-4 md:grid-cols-2">
{quotes.slice(0, 2).map((quote) => (
{quotes.map((quote) => (
<figure
className="group px-4 py-4 md:odd:border-r"
key={quote.author}
>
<div className="row items-center justify-between">
<QuoteIcon className="mb-2 size-10 stroke-1 text-muted-foreground/50 transition-all group-hover:rotate-6 group-hover:text-foreground" />
<div className="row gap-1">
<StarIcon className="size-4 fill-yellow-500 stroke-0 text-yellow-500" />
<StarIcon className="size-4 fill-yellow-500 stroke-0 text-yellow-500" />
<StarIcon className="size-4 fill-yellow-500 stroke-0 text-yellow-500" />
<StarIcon className="size-4 fill-yellow-500 stroke-0 text-yellow-500" />
<StarIcon className="size-4 fill-yellow-500 stroke-0 text-yellow-500" />
</div>
</div>
<blockquote className="prose text-justify text-xl">
<QuoteIcon className="mb-2 size-10 stroke-1 text-muted-foreground/50 transition-all group-hover:rotate-6 group-hover:text-foreground" />
<blockquote className="prose text-xl">
<Markdown>{quote.quote}</Markdown>
</blockquote>
<figcaption className="row mt-4 justify-between text-muted-foreground text-sm">

View File

@@ -1,10 +1,8 @@
import { AnalyticsInsights } from './_sections/analytics-insights';
import { Collaboration } from './_sections/collaboration';
import { FeatureSpotlight } from './_sections/feature-spotlight';
import { CtaBanner } from './_sections/cta-banner';
import { DataPrivacy } from './_sections/data-privacy';
import { Faq } from './_sections/faq';
import { MixpanelAlternative } from './_sections/mixpanel-alternative';
import { Hero } from './_sections/hero';
import { Pricing } from './_sections/pricing';
import { Sdks } from './_sections/sdks';
@@ -59,12 +57,10 @@ export default function HomePage() {
<Hero />
<WhyOpenPanel />
<AnalyticsInsights />
<FeatureSpotlight />
<Collaboration />
<Testimonials />
<Pricing />
<DataPrivacy />
<MixpanelAlternative />
<Sdks />
<Faq />
<CtaBanner />

View File

@@ -3,9 +3,9 @@ import type { Metadata } from 'next';
export const metadata: Metadata = getPageMetadata({
url: '/tools/ip-lookup',
title: 'Free IP Address Lookup — Geolocation, ISP & ASN',
title: 'IP Lookup - Free IP Address Geolocation Tool',
description:
'Instantly look up any IP address. Get country, city, region, ISP, ASN, and coordinates in seconds. Free tool, no signup required, powered by MaxMind GeoLite2.',
'Find your IP address and get detailed geolocation information including country, city, ISP, ASN, and coordinates. Free IP lookup tool with map preview.',
});
export default function IPLookupLayout({

View File

@@ -1,37 +0,0 @@
function star(cx: number, cy: number, outerR: number, innerR: number) {
const pts: string[] = [];
for (let i = 0; i < 10; i++) {
const r = i % 2 === 0 ? outerR : innerR;
const angle = (i * Math.PI) / 5 - Math.PI / 2;
pts.push(`${cx + r * Math.cos(angle)},${cy + r * Math.sin(angle)}`);
}
return pts.join(' ');
}
const STARS = Array.from({ length: 12 }, (_, i) => {
const angle = (i * 30 - 90) * (Math.PI / 180);
return {
x: 12 + 5 * Math.cos(angle),
y: 8 + 5 * Math.sin(angle),
};
});
export function EuFlag({ className }: { className?: string }) {
return (
<svg
className={className}
viewBox="0 0 24 16"
xmlns="http://www.w3.org/2000/svg"
>
<rect fill="#003399" height="16" rx="1.5" width="24" />
{STARS.map((s, i) => (
<polygon
// biome-ignore lint/suspicious/noArrayIndexKey: static data
key={i}
fill="#FFCC00"
points={star(s.x, s.y, 1.1, 0.45)}
/>
))}
</svg>
);
}

View File

@@ -1,71 +0,0 @@
'use client';
import { SimpleChart } from '@/components/simple-chart';
const variantA = [28, 31, 29, 34, 32, 36, 35, 38, 37, 40, 39, 42];
const variantB = [28, 30, 32, 35, 38, 37, 40, 42, 44, 43, 47, 50];
export function ConversionsIllustration() {
return (
<div className="h-full col gap-3 px-4 pb-3 pt-5">
{/* A/B variant cards */}
<div className="row gap-3">
<div className="col flex-1 gap-1 rounded-xl border bg-card p-3 transition-all duration-300 group-hover:-translate-y-0.5">
<div className="row items-center gap-1.5">
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[9px]">
Variant A
</span>
</div>
<span className="font-bold font-mono text-xl">28.4%</span>
<SimpleChart
height={24}
points={variantA}
strokeColor="var(--foreground)"
width={200}
/>
</div>
<div className="col flex-1 gap-1 rounded-xl border border-emerald-500/30 bg-card p-3 transition-all delay-75 duration-300 group-hover:-translate-y-0.5">
<div className="row items-center gap-1.5">
<span className="rounded bg-emerald-500/10 px-1.5 py-0.5 font-mono text-[9px] text-emerald-600 dark:text-emerald-400">
Variant B
</span>
</div>
<span className="font-bold font-mono text-xl text-emerald-500">
41.2%
</span>
<SimpleChart
height={24}
points={variantB}
strokeColor="rgb(34, 197, 94)"
width={200}
/>
</div>
</div>
{/* Breakdown label */}
<div className="col gap-1 rounded-xl border bg-card/60 px-3 py-2.5">
<span className="text-[9px] uppercase tracking-wider text-muted-foreground">
Breakdown by experiment variant
</span>
<div className="row items-center gap-2">
<div className="h-1 flex-1 rounded-full bg-muted">
<div
className="h-1 rounded-full bg-foreground/50"
style={{ width: '57%' }}
/>
</div>
<span className="text-[9px] text-muted-foreground">A: 57%</span>
</div>
<div className="row items-center gap-2">
<div className="h-1 flex-1 rounded-full bg-muted">
<div
className="h-1 rounded-full bg-emerald-500"
style={{ width: '82%' }}
/>
</div>
<span className="text-[9px] text-muted-foreground">B: 82%</span>
</div>
</div>
</div>
);
}

View File

@@ -1,78 +0,0 @@
const queries = [
{
query: 'openpanel analytics',
clicks: 312,
impressions: '4.1k',
pos: 1.2,
},
{
query: 'open source mixpanel alternative',
clicks: 187,
impressions: '3.8k',
pos: 2.4,
},
{
query: 'web analytics without cookies',
clicks: 98,
impressions: '2.2k',
pos: 4.7,
},
];
export function GoogleSearchConsoleIllustration() {
return (
<div className="col h-full gap-2 px-4 pt-5 pb-3">
{/* Top stats */}
<div className="row mb-1 gap-2">
<div className="col flex-1 gap-0.5 rounded-lg border bg-card px-2.5 py-2">
<span className="text-[8px] text-muted-foreground uppercase tracking-wider">
Clicks
</span>
<span className="font-bold font-mono text-sm">740</span>
</div>
<div className="col flex-1 gap-0.5 rounded-lg border bg-card px-2.5 py-2">
<span className="text-[8px] text-muted-foreground uppercase tracking-wider">
Impr.
</span>
<span className="font-bold font-mono text-sm">13k</span>
</div>
<div className="col flex-1 gap-0.5 rounded-lg border bg-card px-2.5 py-2">
<span className="text-[8px] text-muted-foreground uppercase tracking-wider">
Avg. CTR
</span>
<span className="font-bold font-mono text-sm">5.7%</span>
</div>
<div className="col flex-1 gap-0.5 rounded-lg border bg-card px-2.5 py-2">
<span className="text-[8px] text-muted-foreground uppercase tracking-wider">
Avg. Pos
</span>
<span className="font-bold font-mono text-sm">2.8</span>
</div>
</div>
{/* Query table */}
<div className="flex-1 overflow-hidden rounded-xl border border-border bg-card">
<div className="row border-border border-b px-3 py-1.5">
<span className="flex-1 text-[8px] text-muted-foreground uppercase tracking-wider">
Query
</span>
<span className="w-10 text-right text-[8px] text-muted-foreground uppercase tracking-wider">
Pos
</span>
</div>
{queries.map((q, i) => (
<div
className="row items-center border-border/50 border-b px-3 py-1.5 last:border-0"
key={q.query}
style={{ opacity: 1 - i * 0.18 }}
>
<span className="flex-1 truncate text-[9px]">{q.query}</span>
<span className="w-10 text-right font-mono text-[9px] text-muted-foreground">
{q.pos}
</span>
</div>
))}
</div>
</div>
);
}

View File

@@ -1,47 +0,0 @@
import { CheckCircleIcon } from 'lucide-react';
export function NotificationsIllustration() {
return (
<div className="col h-full justify-center gap-3 px-6 py-4">
{/* Funnel completion notification */}
<div className="col gap-2 rounded-xl border border-border bg-card p-4 shadow-lg transition-transform duration-300 group-hover:-translate-y-0.5">
<div className="row items-center gap-2">
<CheckCircleIcon className="size-4 shrink-0 text-emerald-500" />
<span className="font-semibold text-xs">Funnel completed</span>
<span className="ml-auto text-[9px] text-muted-foreground">
just now
</span>
</div>
<p className="font-medium text-sm">Signup Flow 142 today</p>
<div className="row items-center gap-2">
<div className="h-1.5 flex-1 rounded-full bg-muted">
<div
className="h-1.5 rounded-full bg-emerald-500"
style={{ width: '71%' }}
/>
</div>
<span className="text-[9px] text-muted-foreground">
71% conversion
</span>
</div>
</div>
{/* Notification rule */}
<div className="col gap-1.5 px-3 opacity-80">
<span className="text-[9px] text-muted-foreground uppercase tracking-wider">
Notification rule
</span>
<div className="row flex-wrap items-center gap-1.5">
<span className="text-[9px] text-muted-foreground">When</span>
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[9px]">
Signup Flow
</span>
<span className="text-[9px] text-muted-foreground">completes </span>
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[9px]">
#growth
</span>
</div>
</div>
</div>
);
}

View File

@@ -1,63 +0,0 @@
'use client';
const cohorts = [
{ label: 'Week 1', values: [100, 68, 45, 38, 31] },
{ label: 'Week 2', values: [100, 72, 51, 42, 35] },
{ label: 'Week 3', values: [100, 65, 48, 39, null] },
{ label: 'Week 4', values: [100, 70, null, null, null] },
];
const headers = ['Day 0', 'Day 1', 'Day 7', 'Day 14', 'Day 30'];
function cellStyle(v: number | null) {
if (v === null) {
return {
backgroundColor: 'transparent',
borderColor: 'var(--border)',
color: 'var(--muted-foreground)',
};
}
const opacity = 0.12 + (v / 100) * 0.7;
return {
backgroundColor: `rgba(34, 197, 94, ${opacity})`,
borderColor: `rgba(34, 197, 94, 0.3)`,
color: v > 55 ? 'rgba(0,0,0,0.75)' : 'var(--foreground)',
};
}
export function RetentionIllustration() {
return (
<div className="h-full px-4 pb-3 pt-5">
<div className="col h-full gap-1.5">
<div className="row gap-1">
<div className="w-12 shrink-0" />
{headers.map((h) => (
<div
key={h}
className="flex-1 text-center text-[9px] text-muted-foreground"
>
{h}
</div>
))}
</div>
{cohorts.map(({ label, values }) => (
<div key={label} className="row flex-1 gap-1">
<div className="flex w-12 shrink-0 items-center text-[9px] text-muted-foreground">
{label}
</div>
{values.map((v, i) => (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: static data
key={i}
className="flex flex-1 items-center justify-center rounded border text-[9px] font-medium transition-all duration-300 group-hover:scale-[1.03]"
style={cellStyle(v)}
>
{v !== null ? `${v}%` : '—'}
</div>
))}
</div>
))}
</div>
</div>
);
}

View File

@@ -1,72 +0,0 @@
'use client';
import { SimpleChart } from '@/components/simple-chart';
const revenuePoints = [28, 34, 31, 40, 37, 44, 41, 50, 47, 56, 59, 65];
const referrers = [
{ name: 'google.com', amount: '$3,840', pct: 46 },
{ name: 'twitter.com', amount: '$1,920', pct: 23 },
{ name: 'github.com', amount: '$1,260', pct: 15 },
{ name: 'direct', amount: '$1,400', pct: 16 },
];
export function RevenueIllustration() {
return (
<div className="h-full col gap-3 px-4 pb-3 pt-5">
{/* MRR stat + chart */}
<div className="row gap-3">
<div className="col gap-1 rounded-xl border bg-card p-3 transition-all duration-300 group-hover:-translate-y-0.5">
<span className="text-[9px] uppercase tracking-wider text-muted-foreground">
MRR
</span>
<span className="font-bold font-mono text-xl text-emerald-500">
$8,420
</span>
<span className="text-[9px] text-emerald-500"> 12% this month</span>
</div>
<div className="col flex-1 gap-1 rounded-xl border bg-card px-3 py-2">
<span className="text-[9px] text-muted-foreground">MRR over time</span>
<SimpleChart
className="mt-1 flex-1"
height={36}
points={revenuePoints}
strokeColor="rgb(34, 197, 94)"
width={400}
/>
</div>
</div>
{/* Revenue by referrer */}
<div className="flex-1 overflow-hidden rounded-xl border bg-card">
<div className="row border-b border-border px-3 py-1.5">
<span className="flex-1 text-[8px] uppercase tracking-wider text-muted-foreground">
Referrer
</span>
<span className="text-[8px] uppercase tracking-wider text-muted-foreground">
Revenue
</span>
</div>
{referrers.map((r) => (
<div
className="row items-center gap-2 border-b border-border/50 px-3 py-1.5 last:border-0"
key={r.name}
>
<span className="text-[9px] text-muted-foreground flex-none w-20 truncate">
{r.name}
</span>
<div className="flex-1 h-1 rounded-full bg-muted overflow-hidden">
<div
className="h-1 rounded-full bg-emerald-500/70"
style={{ width: `${r.pct}%` }}
/>
</div>
<span className="font-mono text-[9px] text-emerald-500 flex-none">
{r.amount}
</span>
</div>
))}
</div>
</div>
);
}

View File

@@ -1,89 +0,0 @@
import { PlayIcon } from 'lucide-react';
export function SessionReplayIllustration() {
return (
<div className="h-full px-6 pb-3 pt-4">
<div className="col h-full overflow-hidden rounded-xl border border-border bg-background shadow-lg transition-transform duration-300 group-hover:-translate-y-0.5">
{/* Browser chrome */}
<div className="row shrink-0 items-center gap-1.5 border-b border-border bg-muted/30 px-3 py-2">
<div className="h-2 w-2 rounded-full bg-red-400" />
<div className="h-2 w-2 rounded-full bg-yellow-400" />
<div className="h-2 w-2 rounded-full bg-green-400" />
<div className="mx-2 flex-1 rounded bg-background/80 px-2 py-0.5 text-[8px] text-muted-foreground">
app.example.com/pricing
</div>
</div>
{/* Page content */}
<div className="relative flex-1 overflow-hidden p-3">
<div className="mb-2 h-2 w-20 rounded-full bg-muted/60" />
<div className="mb-4 h-2 w-32 rounded-full bg-muted/40" />
<div className="row mb-3 gap-2">
<div className="h-10 flex-1 rounded-lg border border-border bg-muted/20" />
<div className="h-10 flex-1 rounded-lg border border-border bg-muted/20" />
</div>
<div className="mb-2 h-2 w-28 rounded-full bg-muted/30" />
<div className="h-2 w-24 rounded-full bg-muted/20" />
{/* Click heatspot */}
<div
className="absolute"
style={{ left: '62%', top: '48%' }}
>
<div className="h-4 w-4 animate-pulse rounded-full border-2 border-blue-500/70 bg-blue-500/20" />
</div>
<div
className="absolute"
style={{ left: '25%', top: '32%' }}
>
<div className="h-2.5 w-2.5 rounded-full border border-blue-500/40 bg-blue-500/25" />
</div>
{/* Cursor trail */}
<svg
className="pointer-events-none absolute inset-0 h-full w-full"
style={{ overflow: 'visible' }}
>
<path
d="M 18% 22% Q 42% 28% 62% 48%"
fill="none"
stroke="rgb(59 130 246 / 0.35)"
strokeDasharray="3 2"
strokeWidth="1"
/>
</svg>
{/* Cursor */}
<div
className="absolute"
style={{
left: 'calc(62% + 8px)',
top: 'calc(48% + 6px)',
}}
>
<svg fill="none" height="12" viewBox="0 0 10 12" width="10">
<path
d="M0 0L0 10L3 7L5 11L6.5 10.5L4.5 6.5L8 6L0 0Z"
fill="var(--foreground)"
/>
</svg>
</div>
</div>
{/* Playback bar */}
<div className="row shrink-0 items-center gap-2 border-t border-border bg-muted/20 px-3 py-2">
<PlayIcon className="size-3 shrink-0 text-muted-foreground" />
<div className="relative flex-1 h-1 overflow-hidden rounded-full bg-muted">
<div
className="absolute left-0 top-0 h-1 rounded-full bg-blue-500"
style={{ width: '42%' }}
/>
</div>
<span className="font-mono text-[8px] text-muted-foreground">
0:52 / 2:05
</span>
</div>
</div>
</div>
);
}

View File

@@ -1,165 +1,188 @@
'use client';
import { SimpleChart } from '@/components/simple-chart';
import { cn } from '@/lib/utils';
import NumberFlow from '@number-flow/react';
import { AnimatePresence, motion } from 'framer-motion';
import { ArrowUpIcon } from 'lucide-react';
import Image from 'next/image';
import { useEffect, useState } from 'react';
const VISITOR_DATA = [1840, 2100, 1950, 2400, 2250, 2650, 2980];
const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const STATS = [
{ label: 'Visitors', value: 4128, formatted: null, change: 12, up: true },
{ label: 'Page views', value: 12438, formatted: '12.4k', change: 8, up: true },
{ label: 'Bounce rate', value: null, formatted: '42%', change: 3, up: false },
{ label: 'Avg. session', value: null, formatted: '3m 23s', change: 5, up: true },
];
const SOURCES = [
const TRAFFIC_SOURCES = [
{
icon: 'https://api.openpanel.dev/misc/favicon?url=https%3A%2F%2Fgoogle.com',
name: 'google.com',
pct: 49,
name: 'Google',
percentage: 49,
value: 2039,
},
{
icon: 'https://api.openpanel.dev/misc/favicon?url=https%3A%2F%2Finstagram.com',
name: 'Instagram',
percentage: 23,
value: 920,
},
{
icon: 'https://api.openpanel.dev/misc/favicon?url=https%3A%2F%2Ffacebook.com',
name: 'Facebook',
percentage: 18,
value: 750,
},
{
icon: 'https://api.openpanel.dev/misc/favicon?url=https%3A%2F%2Ftwitter.com',
name: 'twitter.com',
pct: 21,
},
{
icon: 'https://api.openpanel.dev/misc/favicon?url=https%3A%2F%2Fgithub.com',
name: 'github.com',
pct: 14,
name: 'Twitter',
percentage: 10,
value: 412,
},
];
function AreaChart({ data }: { data: number[] }) {
const max = Math.max(...data);
const w = 400;
const h = 64;
const xStep = w / (data.length - 1);
const pts = data.map((v, i) => ({ x: i * xStep, y: h - (v / max) * h }));
const line = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x},${p.y}`).join(' ');
const area = `${line} L ${w},${h} L 0,${h} Z`;
const last = pts[pts.length - 1];
return (
<svg className="w-full" viewBox={`0 0 ${w} ${h + 4}`}>
<defs>
<linearGradient id="wa-fill" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stopColor="rgb(59 130 246)" stopOpacity="0.25" />
<stop offset="100%" stopColor="rgb(59 130 246)" stopOpacity="0" />
</linearGradient>
</defs>
<path d={area} fill="url(#wa-fill)" />
<path
d={line}
fill="none"
stroke="rgb(59 130 246)"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
/>
<circle cx={last.x} cy={last.y} fill="rgb(59 130 246)" r="3" />
<circle
cx={last.x}
cy={last.y}
fill="none"
r="6"
stroke="rgb(59 130 246)"
strokeOpacity="0.3"
strokeWidth="1.5"
/>
</svg>
);
}
const COUNTRIES = [
{ icon: '🇺🇸', name: 'United States', percentage: 37, value: 1842 },
{ icon: '🇩🇪', name: 'Germany', percentage: 28, value: 1391 },
{ icon: '🇬🇧', name: 'United Kingdom', percentage: 20, value: 982 },
{ icon: '🇯🇵', name: 'Japan', percentage: 15, value: 751 },
];
export function WebAnalyticsIllustration() {
const [liveVisitors, setLiveVisitors] = useState(47);
const [currentSourceIndex, setCurrentSourceIndex] = useState(0);
useEffect(() => {
const values = [47, 51, 44, 53, 49, 56];
let i = 0;
const id = setInterval(() => {
i = (i + 1) % values.length;
setLiveVisitors(values[i]);
}, 2500);
return () => clearInterval(id);
const interval = setInterval(() => {
setCurrentSourceIndex((prev) => (prev + 1) % TRAFFIC_SOURCES.length);
}, 3000);
return () => clearInterval(interval);
}, []);
return (
<div className="aspect-video col gap-2.5 p-5">
{/* Header */}
<div className="row items-center justify-between">
<div className="row items-center gap-1.5">
<span className="relative flex h-1.5 w-1.5">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
<span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-500" />
</span>
<span className="text-[10px] font-medium text-muted-foreground">
<NumberFlow value={liveVisitors} /> online now
</span>
<div className="px-12 group aspect-video">
<div className="relative h-full col">
<MetricCard
title="Session duration"
value="3m 23s"
change="3%"
chartPoints={[40, 10, 20, 43, 20, 40, 30, 37, 40, 34, 50, 31]}
color="var(--foreground)"
className="absolute w-full rotate-0 top-2 left-2 group-hover:-translate-y-1 group-hover:-rotate-2 transition-all duration-300"
/>
<MetricCard
title="Bounce rate"
value="46%"
change="3%"
chartPoints={[10, 46, 20, 43, 20, 40, 30, 37, 40, 34, 50, 31]}
color="var(--foreground)"
className="absolute w-full -rotate-2 -left-2 top-12 group-hover:-translate-y-1 group-hover:rotate-0 transition-all duration-300"
/>
<div className="col gap-4 w-[80%] md:w-[70%] ml-auto mt-auto">
<BarCell
{...TRAFFIC_SOURCES[currentSourceIndex]}
className="group-hover:scale-105 transition-all duration-300"
/>
<BarCell
{...TRAFFIC_SOURCES[
(currentSourceIndex + 1) % TRAFFIC_SOURCES.length
]}
className="group-hover:scale-105 transition-all duration-300"
/>
</div>
</div>
</div>
);
}
function MetricCard({
title,
value,
change,
chartPoints,
color,
className,
}: {
title: string;
value: string;
change: string;
chartPoints: number[];
color: string;
className?: string;
}) {
return (
<div className={cn('col bg-card rounded-lg p-4 pb-6 border', className)}>
<div className="row items-end justify-between">
<div>
<div className="text-muted-foreground text-sm">{title}</div>
<div className="text-2xl font-semibold font-mono">{value}</div>
</div>
<div className="row gap-2 items-center font-mono font-medium">
<ArrowUpIcon className="size-3" strokeWidth={3} />
<div>{change}</div>
</div>
</div>
<SimpleChart
width={400}
height={30}
points={chartPoints}
strokeColor={color}
className="mt-4"
/>
</div>
);
}
function BarCell({
icon,
name,
percentage,
value,
className,
}: {
icon: string;
name: string;
percentage: number;
value: number;
className?: string;
}) {
return (
<div
className={cn(
'relative p-4 py-2 bg-card rounded-lg shadow-[0_10px_30px_rgba(0,0,0,0.3)] border',
className,
)}
>
<div
className="absolute bg-background bottom-0 top-0 left-0 rounded-lg transition-all duration-500"
style={{
width: `${percentage}%`,
}}
/>
<div className="relative row justify-between ">
<div className="row gap-2 items-center font-medium text-sm">
{icon.startsWith('http') ? (
<Image
alt="serie icon"
className="max-h-4 rounded-[2px] object-contain"
src={icon}
width={16}
height={16}
/>
) : (
<div className="text-2xl">{icon}</div>
)}
<AnimatePresence mode="popLayout">
<motion.div
key={name}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 10 }}
transition={{ duration: 0.3 }}
>
{name}
</motion.div>
</AnimatePresence>
</div>
<div className="row gap-3 font-mono text-sm">
<span className="text-muted-foreground">
<NumberFlow value={percentage} />%
</span>
<NumberFlow value={value} locales={'en-US'} />
</div>
<span className="rounded bg-muted px-1.5 py-0.5 text-[9px] text-muted-foreground">
Last 7 days
</span>
</div>
{/* KPI tiles */}
<div className="grid grid-cols-4 gap-1.5">
{STATS.map((stat) => (
<div
className="col gap-0.5 rounded-lg border bg-card px-2 py-1.5"
key={stat.label}
>
<span className="text-[8px] text-muted-foreground">{stat.label}</span>
<span className="font-mono font-semibold text-xs leading-tight">
{stat.formatted ??
(stat.value !== null ? (
<NumberFlow locales="en-US" value={stat.value} />
) : null)}
</span>
<span
className={`text-[8px] ${stat.up ? 'text-emerald-500' : 'text-red-400'}`}
>
{stat.up ? '↑' : '↓'} {stat.change}%
</span>
</div>
))}
</div>
{/* Area chart */}
<div className="flex-1 col gap-1 overflow-hidden rounded-xl border bg-card px-3 pt-2 pb-1">
<span className="text-[8px] text-muted-foreground">Unique visitors</span>
<AreaChart data={VISITOR_DATA} />
<div className="row justify-between px-0.5">
{DAYS.map((d) => (
<span className="text-[7px] text-muted-foreground" key={d}>
{d}
</span>
))}
</div>
</div>
{/* Traffic sources */}
<div className="row gap-1.5">
{SOURCES.map((src) => (
<div
className="row flex-1 items-center gap-1.5 overflow-hidden rounded-lg border bg-card px-2 py-1.5"
key={src.name}
>
<Image
alt={src.name}
className="rounded-[2px] object-contain"
height={10}
src={src.icon}
width={10}
/>
<span className="flex-1 truncate text-[9px]">{src.name}</span>
<span className="font-mono text-[9px] text-muted-foreground">
{src.pct}%
</span>
</div>
))}
</div>
</div>
);

View File

@@ -1,13 +1,10 @@
import type React from 'react';
import { cn } from '@/lib/utils';
import type { LucideIcon } from 'lucide-react';
type PerkIcon = LucideIcon | React.ComponentType<{ className?: string }>;
export function Perks({
perks,
className,
}: { perks: { text: string; icon: PerkIcon }[]; className?: string }) {
}: { perks: { text: string; icon: LucideIcon }[]; className?: string }) {
return (
<ul className={cn('grid grid-cols-2 gap-2', className)}>
{perks.map((perk) => (

View File

@@ -1,20 +1,25 @@
import type { IServiceEvent, IServiceEventMinimal } from '@openpanel/db';
import { Link } from '@tanstack/react-router';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { EventIcon } from './event-icon';
import { Tooltiper } from '@/components/ui/tooltip';
import { useAppParams } from '@/hooks/use-app-params';
import { useNumber } from '@/hooks/use-numer-formatter';
import { pushModal } from '@/modals';
import { cn } from '@/utils/cn';
import { getProfileName } from '@/utils/getters';
import { Link } from '@tanstack/react-router';
import type { IServiceEvent, IServiceEventMinimal } from '@openpanel/db';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { EventIcon } from './event-icon';
type EventListItemProps = IServiceEventMinimal | IServiceEvent;
export function EventListItem(props: EventListItemProps) {
const { organizationId, projectId } = useAppParams();
const { createdAt, name, path, meta } = props;
const { createdAt, name, path, duration, meta } = props;
const profile = 'profile' in props ? props.profile : null;
const number = useNumber();
const renderName = () => {
if (name === 'screen_view') {
if (path.includes('/')) {
@@ -27,65 +32,83 @@ export function EventListItem(props: EventListItemProps) {
return name.replace(/_/g, ' ');
};
const renderDuration = () => {
if (name === 'screen_view') {
return (
<span className="text-muted-foreground">
{number.shortWithUnit(duration / 1000, 'min')}
</span>
);
}
return null;
};
const isMinimal = 'minimal' in props;
return (
<button
className={cn(
'card flex w-full items-center justify-between rounded-lg p-4 transition-colors hover:bg-light-background',
meta?.conversion &&
`bg-${meta.color}-50 dark:bg-${meta.color}-900 hover:bg-${meta.color}-100 dark:hover:bg-${meta.color}-700`
)}
onClick={() => {
if (!isMinimal) {
pushModal('EventDetails', {
id: props.id,
projectId,
createdAt,
});
}
}}
type="button"
>
<div>
<div className="flex items-center gap-4 text-left">
<EventIcon meta={meta} name={name} size="sm" />
<span className="font-medium">{renderName()}</span>
</div>
<div className="pl-10">
<div className="flex origin-left scale-75 gap-1">
<SerieIcon name={props.country} />
<SerieIcon name={props.os} />
<SerieIcon name={props.browser} />
</div>
</div>
</div>
<div className="flex gap-4">
{profile && (
<Tooltiper asChild content={getProfileName(profile)}>
<Link
className="max-w-[80px] overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground hover:underline"
onClick={(e) => {
e.stopPropagation();
}}
params={{
organizationId,
projectId,
profileId: profile.id,
}}
to={'/$organizationId/$projectId/profiles/$profileId'}
>
{getProfileName(profile)}
</Link>
</Tooltiper>
<>
<button
type="button"
onClick={() => {
if (!isMinimal) {
pushModal('EventDetails', {
id: props.id,
projectId,
createdAt,
});
}
}}
className={cn(
'card hover:bg-light-background flex w-full items-center justify-between rounded-lg p-4 transition-colors',
meta?.conversion &&
`bg-${meta.color}-50 dark:bg-${meta.color}-900 hover:bg-${meta.color}-100 dark:hover:bg-${meta.color}-700`,
)}
<Tooltiper asChild content={createdAt.toLocaleString()}>
<div className="text-muted-foreground">
{createdAt.toLocaleTimeString()}
>
<div>
<div className="flex items-center gap-4 text-left ">
<EventIcon size="sm" name={name} meta={meta} />
<span>
<span className="font-medium">{renderName()}</span>
{' '}
{renderDuration()}
</span>
</div>
</Tooltiper>
</div>
</button>
<div className="pl-10">
<div className="flex origin-left scale-75 gap-1">
<SerieIcon name={props.country} />
<SerieIcon name={props.os} />
<SerieIcon name={props.browser} />
</div>
</div>
</div>
<div className="flex gap-4">
{profile && (
<Tooltiper asChild content={getProfileName(profile)}>
<Link
onClick={(e) => {
e.stopPropagation();
}}
to={'/$organizationId/$projectId/profiles/$profileId'}
params={{
organizationId,
projectId,
profileId: profile.id,
}}
className="max-w-[80px] overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground hover:underline"
>
{getProfileName(profile)}
</Link>
</Tooltiper>
)}
<Tooltiper asChild content={createdAt.toLocaleString()}>
<div className=" text-muted-foreground">
{createdAt.toLocaleTimeString()}
</div>
</Tooltiper>
</div>
</button>
</>
);
}

View File

@@ -1,4 +1,3 @@
import { AnimatedNumber } from '../animated-number';
import {
Tooltip,
TooltipContent,
@@ -9,53 +8,71 @@ import { useDebounceState } from '@/hooks/use-debounce-state';
import useWS from '@/hooks/use-ws';
import { cn } from '@/utils/cn';
import type { IServiceEvent, IServiceEventMinimal } from '@openpanel/db';
import { useParams } from '@tanstack/react-router';
import { AnimatedNumber } from '../animated-number';
export default function EventListener({
onRefresh,
}: {
onRefresh: () => void;
}) {
const params = useParams({
strict: false,
});
const { projectId } = useAppParams();
const counter = useDebounceState(0, 1000);
useWS<{ count: number }>(
useWS<IServiceEventMinimal | IServiceEvent>(
`/live/events/${projectId}`,
({ count }) => {
counter.set((prev) => prev + count);
(event) => {
if (event) {
const isProfilePage = !!params?.profileId;
if (isProfilePage) {
const profile = 'profile' in event ? event.profile : null;
if (profile?.id === params?.profileId) {
counter.set((prev) => prev + 1);
}
return;
}
counter.set((prev) => prev + 1);
}
},
{
debounce: {
delay: 1000,
maxWait: 5000,
},
}
},
);
return (
<Tooltip>
<TooltipTrigger asChild>
<button
className="flex h-8 items-center gap-2 rounded-md border border-border bg-card px-3 font-medium leading-none"
type="button"
onClick={() => {
counter.set(0);
onRefresh();
}}
type="button"
className="flex h-8 items-center gap-2 rounded-md border border-border bg-card px-3 font-medium leading-none"
>
<div className="relative">
<div
className={cn(
'h-3 w-3 animate-ping rounded-full bg-emerald-500 opacity-100 transition-all'
'h-3 w-3 animate-ping rounded-full bg-emerald-500 opacity-100 transition-all',
)}
/>
<div
className={cn(
'absolute top-0 left-0 h-3 w-3 rounded-full bg-emerald-500 transition-all'
'absolute left-0 top-0 h-3 w-3 rounded-full bg-emerald-500 transition-all',
)}
/>
</div>
{counter.debounced === 0 ? (
'Listening'
) : (
<AnimatedNumber suffix=" new events" value={counter.debounced} />
<AnimatedNumber value={counter.debounced} suffix=" new events" />
)}
</button>
</TooltipTrigger>

View File

@@ -1,14 +1,15 @@
import type { IServiceEvent } from '@openpanel/db';
import type { ColumnDef } from '@tanstack/react-table';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { EventIcon } from '@/components/events/event-icon';
import { ProjectLink } from '@/components/links';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { KeyValueGrid } from '@/components/ui/key-value-grid';
import { useNumber } from '@/hooks/use-numer-formatter';
import { pushModal } from '@/modals';
import { getProfileName } from '@/utils/getters';
import type { ColumnDef } from '@tanstack/react-table';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { KeyValueGrid } from '@/components/ui/key-value-grid';
import type { IServiceEvent } from '@openpanel/db';
export function useColumns() {
const number = useNumber();
@@ -27,24 +28,17 @@ export function useColumns() {
accessorKey: 'name',
header: 'Name',
cell({ row }) {
const { name, path, revenue } = row.original;
const fullTitle =
name === 'screen_view'
? path
: name === 'revenue' && revenue
? `${name} (${number.currency(revenue / 100)})`
: name.replace(/_/g, ' ');
const { name, path, duration, properties, revenue } = row.original;
const renderName = () => {
if (name === 'screen_view') {
if (path.includes('/')) {
return path;
return <span className="max-w-md truncate">{path}</span>;
}
return (
<>
<span className="text-muted-foreground">Screen: </span>
{path}
<span className="max-w-md truncate">{path}</span>
</>
);
}
@@ -56,26 +50,38 @@ export function useColumns() {
return name.replace(/_/g, ' ');
};
const renderDuration = () => {
if (name === 'screen_view') {
return (
<span className="text-muted-foreground">
{number.shortWithUnit(duration / 1000, 'min')}
</span>
);
}
return null;
};
return (
<div className="flex min-w-0 items-center gap-2">
<div className="flex items-center gap-2">
<button
className="shrink-0 transition-transform hover:scale-105"
type="button"
className="transition-transform hover:scale-105"
onClick={() => {
pushModal('EditEvent', {
id: row.original.id,
});
}}
type="button"
>
<EventIcon
meta={row.original.meta}
name={row.original.name}
size="sm"
name={row.original.name}
meta={row.original.meta}
/>
</button>
<span className="flex min-w-0 flex-1 gap-2">
<span className="flex gap-2">
<button
className="min-w-0 max-w-full truncate text-left font-medium hover:underline"
type="button"
onClick={() => {
pushModal('EventDetails', {
id: row.original.id,
@@ -83,11 +89,11 @@ export function useColumns() {
projectId: row.original.projectId,
});
}}
title={fullTitle}
type="button"
className="font-medium hover:underline"
>
<span className="block truncate">{renderName()}</span>
{renderName()}
</button>
{renderDuration()}
</span>
</div>
);
@@ -101,8 +107,8 @@ export function useColumns() {
if (profile) {
return (
<ProjectLink
className="group row items-center gap-2 whitespace-nowrap font-medium hover:underline"
href={`/profiles/${encodeURIComponent(profile.id)}`}
className="group whitespace-nowrap font-medium hover:underline row items-center gap-2"
>
<ProfileAvatar size="sm" {...profile} />
{getProfileName(profile)}
@@ -113,8 +119,8 @@ export function useColumns() {
if (profileId && profileId !== deviceId) {
return (
<ProjectLink
className="whitespace-nowrap font-medium hover:underline"
href={`/profiles/${encodeURIComponent(profileId)}`}
className="whitespace-nowrap font-medium hover:underline"
>
Unknown
</ProjectLink>
@@ -124,8 +130,8 @@ export function useColumns() {
if (deviceId) {
return (
<ProjectLink
className="whitespace-nowrap font-medium hover:underline"
href={`/profiles/${encodeURIComponent(deviceId)}`}
className="whitespace-nowrap font-medium hover:underline"
>
Anonymous
</ProjectLink>
@@ -146,10 +152,10 @@ export function useColumns() {
const { sessionId } = row.original;
return (
<ProjectLink
className="whitespace-nowrap font-medium hover:underline"
href={`/sessions/${encodeURIComponent(sessionId)}`}
className="whitespace-nowrap font-medium hover:underline"
>
{sessionId.slice(0, 6)}
{sessionId.slice(0,6)}
</ProjectLink>
);
},
@@ -169,7 +175,7 @@ export function useColumns() {
cell({ row }) {
const { country, city } = row.original;
return (
<div className="row min-w-0 items-center gap-2">
<div className="row items-center gap-2 min-w-0">
<SerieIcon name={country} />
<span className="truncate">{city}</span>
</div>
@@ -183,7 +189,7 @@ export function useColumns() {
cell({ row }) {
const { os } = row.original;
return (
<div className="row min-w-0 items-center gap-2">
<div className="row items-center gap-2 min-w-0">
<SerieIcon name={os} />
<span className="truncate">{os}</span>
</div>
@@ -197,39 +203,13 @@ export function useColumns() {
cell({ row }) {
const { browser } = row.original;
return (
<div className="row min-w-0 items-center gap-2">
<div className="row items-center gap-2 min-w-0">
<SerieIcon name={browser} />
<span className="truncate">{browser}</span>
</div>
);
},
},
{
accessorKey: 'groups',
header: 'Groups',
size: 200,
meta: {
hidden: true,
},
cell({ row }) {
const { groups } = row.original;
if (!groups?.length) {
return null;
}
return (
<div className="flex flex-wrap gap-1">
{groups.map((g) => (
<span
className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs"
key={g}
>
{g}
</span>
))}
</div>
);
},
},
{
accessorKey: 'properties',
header: 'Properties',
@@ -241,14 +221,14 @@ export function useColumns() {
const { properties } = row.original;
const filteredProperties = Object.fromEntries(
Object.entries(properties || {}).filter(
([key]) => !key.startsWith('__')
)
([key]) => !key.startsWith('__'),
),
);
const items = Object.entries(filteredProperties);
const limit = 2;
const data = items.slice(0, limit).map(([key, value]) => ({
name: key,
value,
value: value,
}));
if (items.length > limit) {
data.push({

View File

@@ -1,17 +1,3 @@
import type { IServiceEvent } from '@openpanel/db';
import type { UseInfiniteQueryResult } from '@tanstack/react-query';
import type { Table } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { useWindowVirtualizer } from '@tanstack/react-virtual';
import type { TRPCInfiniteData } from '@trpc/tanstack-react-query';
import { format } from 'date-fns';
import { CalendarIcon, Loader2Icon } from 'lucide-react';
import { parseAsIsoDateTime, useQueryState } from 'nuqs';
import { last } from 'ramda';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useInViewport } from 'react-in-viewport';
import EventListener from '../event-listener';
import { useColumns } from './columns';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import {
OverviewFilterButton,
@@ -26,6 +12,20 @@ import { useAppParams } from '@/hooks/use-app-params';
import { pushModal } from '@/modals';
import type { RouterInputs, RouterOutputs } from '@/trpc/client';
import { cn } from '@/utils/cn';
import type { IServiceEvent } from '@openpanel/db';
import type { UseInfiniteQueryResult } from '@tanstack/react-query';
import type { Table } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { useWindowVirtualizer } from '@tanstack/react-virtual';
import type { TRPCInfiniteData } from '@trpc/tanstack-react-query';
import { format } from 'date-fns';
import { CalendarIcon, FilterIcon, Loader2Icon } from 'lucide-react';
import { parseAsIsoDateTime, useQueryState } from 'nuqs';
import { last } from 'ramda';
import { memo, useEffect, useMemo, useRef } from 'react';
import { useInViewport } from 'react-in-viewport';
import EventListener from '../event-listener';
import { useColumns } from './columns';
type Props = {
query: UseInfiniteQueryResult<
@@ -35,7 +35,6 @@ type Props = {
>,
unknown
>;
showEventListener?: boolean;
};
const LOADING_DATA = [{}, {}, {}, {}, {}, {}, {}, {}, {}] as IServiceEvent[];
@@ -54,7 +53,6 @@ interface VirtualRowProps {
scrollMargin: number;
isLoading: boolean;
headerColumnsHash: string;
onRowClick?: (row: any) => void;
}
const VirtualRow = memo(
@@ -64,26 +62,12 @@ const VirtualRow = memo(
headerColumns,
scrollMargin,
isLoading,
onRowClick,
}: VirtualRowProps) {
return (
<div
className={cn(
'group/row absolute top-0 left-0 w-full border-b transition-colors hover:bg-muted/50',
onRowClick && 'cursor-pointer'
)}
data-index={virtualRow.index}
onClick={
onRowClick
? (e) => {
if ((e.target as HTMLElement).closest('a, button')) {
return;
}
onRowClick(row);
}
: undefined
}
ref={virtualRow.measureElement}
className="absolute top-0 left-0 w-full border-b hover:bg-muted/50 transition-colors group/row"
style={{
transform: `translateY(${virtualRow.start - scrollMargin}px)`,
display: 'grid',
@@ -98,8 +82,8 @@ const VirtualRow = memo(
const width = `${cell.column.getSize()}px`;
return (
<div
className="flex items-center whitespace-nowrap p-2 px-4 align-middle"
key={cell.id}
className="flex items-center p-2 px-4 align-middle whitespace-nowrap"
style={{
width,
overflow: 'hidden',
@@ -129,18 +113,16 @@ const VirtualRow = memo(
prevProps.virtualRow.start === nextProps.virtualRow.start &&
prevProps.virtualRow.size === nextProps.virtualRow.size &&
prevProps.isLoading === nextProps.isLoading &&
prevProps.headerColumnsHash === nextProps.headerColumnsHash &&
prevProps.onRowClick === nextProps.onRowClick
prevProps.headerColumnsHash === nextProps.headerColumnsHash
);
}
},
);
const VirtualizedEventsTable = ({
table,
data,
isLoading,
onRowClick,
}: VirtualizedEventsTableProps & { onRowClick?: (row: any) => void }) => {
}: VirtualizedEventsTableProps) => {
const parentRef = useRef<HTMLDivElement>(null);
const headerColumns = table.getAllLeafColumns().filter((col) => {
@@ -162,12 +144,12 @@ const VirtualizedEventsTable = ({
const headerColumnsHash = headerColumns.map((col) => col.id).join(',');
return (
<div
className="w-full overflow-x-auto rounded-md border bg-card"
ref={parentRef}
className="w-full overflow-x-auto border rounded-md bg-card"
>
{/* Table Header */}
<div
className="sticky top-0 z-10 border-b bg-card"
className="sticky top-0 z-10 bg-card border-b"
style={{
display: 'grid',
gridTemplateColumns: headerColumns
@@ -181,8 +163,8 @@ const VirtualizedEventsTable = ({
const width = `${column.getSize()}px`;
return (
<div
className="flex h-10 items-center whitespace-nowrap px-4 text-left font-semibold text-[10px] text-foreground uppercase"
key={column.id}
className="flex items-center h-10 px-4 text-left text-[10px] uppercase text-foreground font-semibold whitespace-nowrap"
style={{
width,
}}
@@ -195,8 +177,8 @@ const VirtualizedEventsTable = ({
{!isLoading && data.length === 0 && (
<FullPageEmptyState
description={"Start sending events and you'll see them here"}
title="No events"
description={"Start sending events and you'll see them here"}
/>
)}
@@ -211,23 +193,20 @@ const VirtualizedEventsTable = ({
>
{virtualRows.map((virtualRow) => {
const row = table.getRowModel().rows[virtualRow.index];
if (!row) {
return null;
}
if (!row) return null;
return (
<VirtualRow
headerColumns={headerColumns}
headerColumnsHash={headerColumnsHash}
isLoading={isLoading}
key={row.id}
onRowClick={onRowClick}
row={row}
scrollMargin={rowVirtualizer.options.scrollMargin}
virtualRow={{
...virtualRow,
measureElement: rowVirtualizer.measureElement,
}}
headerColumns={headerColumns}
headerColumnsHash={headerColumnsHash}
scrollMargin={rowVirtualizer.options.scrollMargin}
isLoading={isLoading}
/>
);
})}
@@ -236,18 +215,10 @@ const VirtualizedEventsTable = ({
);
};
export const EventsTable = ({ query, showEventListener = false }: Props) => {
export const EventsTable = ({ query }: Props) => {
const { isLoading } = query;
const columns = useColumns();
const handleRowClick = useCallback((row: any) => {
pushModal('EventDetails', {
id: row.original.id,
createdAt: row.original.createdAt,
projectId: row.original.projectId,
});
}, []);
const data = useMemo(() => {
if (isLoading) {
return LOADING_DATA;
@@ -301,22 +272,13 @@ export const EventsTable = ({ query, showEventListener = false }: Props) => {
return (
<>
<EventsTableToolbar
query={query}
showEventListener={showEventListener}
table={table}
/>
<VirtualizedEventsTable
data={data}
isLoading={isLoading}
onRowClick={handleRowClick}
table={table}
/>
<div className="center-center h-10 w-full pt-4" ref={inViewportRef}>
<EventsTableToolbar query={query} table={table} />
<VirtualizedEventsTable table={table} data={data} isLoading={isLoading} />
<div className="w-full h-10 center-center pt-4" ref={inViewportRef}>
<div
className={cn(
'center-center size-8 rounded-full border bg-background opacity-0 transition-opacity',
query.isFetchingNextPage && 'opacity-100'
'size-8 bg-background rounded-full center-center border opacity-0 transition-opacity',
query.isFetchingNextPage && 'opacity-100',
)}
>
<Loader2Icon className="size-4 animate-spin" />
@@ -329,26 +291,24 @@ export const EventsTable = ({ query, showEventListener = false }: Props) => {
function EventsTableToolbar({
query,
table,
showEventListener,
}: {
query: Props['query'];
table: Table<IServiceEvent>;
showEventListener: boolean;
}) {
const { projectId } = useAppParams();
const [startDate, setStartDate] = useQueryState(
'startDate',
parseAsIsoDateTime
parseAsIsoDateTime,
);
const [endDate, setEndDate] = useQueryState('endDate', parseAsIsoDateTime);
return (
<DataTableToolbarContainer>
<div className="flex flex-1 flex-wrap items-center gap-2">
{showEventListener && (
<EventListener onRefresh={() => query.refetch()} />
)}
<EventListener onRefresh={() => query.refetch()} />
<Button
variant="outline"
size="sm"
icon={CalendarIcon}
onClick={() => {
pushModal('DateRangerPicker', {
@@ -360,8 +320,6 @@ function EventsTableToolbar({
endDate: endDate || undefined,
});
}}
size="sm"
variant="outline"
>
{startDate && endDate
? `${format(startDate, 'MMM d')} - ${format(endDate, 'MMM d')}`

View File

@@ -1,130 +0,0 @@
import { TrendingUpIcon } from 'lucide-react';
import {
Area,
AreaChart,
CartesianGrid,
Tooltip as RechartTooltip,
ResponsiveContainer,
XAxis,
YAxis,
} from 'recharts';
import { WidgetHead, WidgetTitle } from '../overview/overview-widget';
import {
useXAxisProps,
useYAxisProps,
} from '@/components/report-chart/common/axis';
import { Widget, WidgetBody } from '@/components/widget';
import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
import { useNumber } from '@/hooks/use-numer-formatter';
import { getChartColor } from '@/utils/theme';
type Props = {
data: { date: string; count: number }[];
};
function Tooltip(props: any) {
const number = useNumber();
const formatDate = useFormatDateInterval({ interval: 'day', short: false });
const payload = props.payload?.[0]?.payload;
if (!payload) {
return null;
}
return (
<div className="flex min-w-[160px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">
<div className="text-muted-foreground text-sm">
{formatDate(new Date(payload.timestamp))}
</div>
<div className="flex items-center gap-2">
<div
className="h-10 w-1 rounded-full"
style={{ background: getChartColor(0) }}
/>
<div className="col gap-1">
<div className="text-muted-foreground text-sm">Total members</div>
<div
className="font-semibold text-lg"
style={{ color: getChartColor(0) }}
>
{number.format(payload.cumulative)}
</div>
</div>
</div>
{payload.count > 0 && (
<div className="text-muted-foreground text-xs">
+{number.format(payload.count)} new
</div>
)}
</div>
);
}
export function GroupMemberGrowth({ data }: Props) {
const xAxisProps = useXAxisProps({ interval: 'day' });
const yAxisProps = useYAxisProps({});
const color = getChartColor(0);
let cumulative = 0;
const chartData = data.map((item) => {
cumulative += item.count;
return {
date: item.date,
timestamp: new Date(item.date).getTime(),
count: item.count,
cumulative,
};
});
const gradientId = 'memberGrowthGradient';
return (
<Widget className="w-full">
<WidgetHead>
<WidgetTitle icon={TrendingUpIcon}>Member growth</WidgetTitle>
</WidgetHead>
<WidgetBody>
{data.length === 0 ? (
<p className="py-4 text-center text-muted-foreground text-sm">
No data yet
</p>
) : (
<div className="h-[200px] w-full">
<ResponsiveContainer>
<AreaChart data={chartData}>
<defs>
<linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
<stop offset="95%" stopColor={color} stopOpacity={0.02} />
</linearGradient>
</defs>
<RechartTooltip
content={<Tooltip />}
cursor={{ stroke: color, strokeOpacity: 0.3 }}
/>
<Area
dataKey="cumulative"
dot={false}
fill={`url(#${gradientId})`}
isAnimationActive={false}
stroke={color}
strokeWidth={2}
type="monotone"
/>
<XAxis {...xAxisProps} />
<YAxis {...yAxisProps} />
<CartesianGrid
className="stroke-border"
horizontal={true}
strokeDasharray="3 3"
strokeOpacity={0.5}
vertical={false}
/>
</AreaChart>
</ResponsiveContainer>
</div>
)}
</WidgetBody>
</Widget>
);
}

View File

@@ -1,76 +0,0 @@
import { useAppParams } from '@/hooks/use-app-params';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { Badge } from '@/components/ui/badge';
import { Link } from '@tanstack/react-router';
import type { ColumnDef } from '@tanstack/react-table';
import type { IServiceGroup } from '@openpanel/db';
export type IServiceGroupWithStats = IServiceGroup & {
memberCount: number;
lastActiveAt: Date | null;
};
export function useGroupColumns(): ColumnDef<IServiceGroupWithStats>[] {
const { organizationId, projectId } = useAppParams();
return [
{
accessorKey: 'name',
header: 'Name',
cell: ({ row }) => {
const group = row.original;
return (
<Link
className="font-medium hover:underline"
params={{ organizationId, projectId, groupId: group.id }}
to="/$organizationId/$projectId/groups/$groupId"
>
{group.name}
</Link>
);
},
},
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="font-mono text-muted-foreground text-xs">
{row.original.id}
</span>
),
},
{
accessorKey: 'type',
header: 'Type',
cell: ({ row }) => (
<Badge variant="outline">{row.original.type}</Badge>
),
},
{
accessorKey: 'memberCount',
header: 'Members',
cell: ({ row }) => (
<span className="tabular-nums">{row.original.memberCount}</span>
),
},
{
accessorKey: 'lastActiveAt',
header: 'Last active',
size: ColumnCreatedAt.size,
cell: ({ row }) =>
row.original.lastActiveAt ? (
<ColumnCreatedAt>{row.original.lastActiveAt}</ColumnCreatedAt>
) : (
<span className="text-muted-foreground"></span>
),
},
{
accessorKey: 'createdAt',
header: 'Created',
size: ColumnCreatedAt.size,
cell: ({ row }) => (
<ColumnCreatedAt>{row.original.createdAt}</ColumnCreatedAt>
),
},
];
}

View File

@@ -1,114 +0,0 @@
import type { IServiceGroup } from '@openpanel/db';
import type { UseQueryResult } from '@tanstack/react-query';
import type { PaginationState, Table, Updater } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { memo } from 'react';
import { type IServiceGroupWithStats, useGroupColumns } from './columns';
import { DataTable } from '@/components/ui/data-table/data-table';
import {
useDataTableColumnVisibility,
useDataTablePagination,
} from '@/components/ui/data-table/data-table-hooks';
import {
AnimatedSearchInput,
DataTableToolbarContainer,
} from '@/components/ui/data-table/data-table-toolbar';
import { DataTableViewOptions } from '@/components/ui/data-table/data-table-view-options';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
import type { RouterOutputs } from '@/trpc/client';
import { arePropsEqual } from '@/utils/are-props-equal';
const PAGE_SIZE = 50;
interface Props {
query: UseQueryResult<RouterOutputs['group']['list'], unknown>;
pageSize?: number;
toolbarLeft?: React.ReactNode;
}
const LOADING_DATA = [{}, {}, {}, {}, {}, {}, {}, {}, {}] as IServiceGroupWithStats[];
export const GroupsTable = memo(
({ query, pageSize = PAGE_SIZE, toolbarLeft }: Props) => {
const { data, isLoading } = query;
const columns = useGroupColumns();
const { setPage, state: pagination } = useDataTablePagination(pageSize);
const {
columnVisibility,
setColumnVisibility,
columnOrder,
setColumnOrder,
} = useDataTableColumnVisibility(columns, 'groups');
const table = useReactTable({
data: isLoading ? LOADING_DATA : (data?.data ?? []),
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
manualFiltering: true,
manualSorting: true,
columns,
rowCount: data?.meta.count,
pageCount: Math.ceil(
(data?.meta.count || 0) / (pagination.pageSize || 1)
),
filterFns: {
isWithinRange: () => true,
},
state: {
pagination,
columnVisibility,
columnOrder,
},
onColumnVisibilityChange: setColumnVisibility,
onColumnOrderChange: setColumnOrder,
onPaginationChange: (updaterOrValue: Updater<PaginationState>) => {
const nextPagination =
typeof updaterOrValue === 'function'
? updaterOrValue(pagination)
: updaterOrValue;
setPage(nextPagination.pageIndex + 1);
},
getRowId: (row, index) => row.id ?? `loading-${index}`,
});
return (
<>
<GroupsTableToolbar table={table} toolbarLeft={toolbarLeft} />
<DataTable
empty={{
title: 'No groups found',
description:
'Groups represent companies, teams, or other entities that events belong to.',
}}
loading={isLoading}
table={table}
/>
</>
);
},
arePropsEqual(['query.isLoading', 'query.data', 'pageSize', 'toolbarLeft'])
);
function GroupsTableToolbar({
table,
toolbarLeft,
}: {
table: Table<IServiceGroupWithStats>;
toolbarLeft?: React.ReactNode;
}) {
const { search, setSearch } = useSearchQueryState();
return (
<DataTableToolbarContainer>
<div className="flex flex-wrap items-center gap-2">
{toolbarLeft}
<AnimatedSearchInput
onChange={setSearch}
placeholder="Search groups..."
value={search}
/>
</div>
<DataTableViewOptions table={table} />
</DataTableToolbarContainer>
);
}

View File

@@ -1,13 +1,31 @@
import type { IServiceEvent } from '@openpanel/db';
import type {
IServiceClient,
IServiceEvent,
IServiceProject,
} from '@openpanel/db';
import { CheckCircle2Icon, CheckIcon, Loader2 } from 'lucide-react';
import { useState } from 'react';
import useWS from '@/hooks/use-ws';
import { cn } from '@/utils/cn';
import { timeAgo } from '@/utils/date';
interface Props {
project: IServiceProject;
client: IServiceClient | null;
events: IServiceEvent[];
onVerified: (verified: boolean) => void;
}
const VerifyListener = ({ events }: Props) => {
const VerifyListener = ({ client, events: _events, onVerified }: Props) => {
const [events, setEvents] = useState<IServiceEvent[]>(_events ?? []);
useWS<IServiceEvent>(
`/live/events/${client?.projectId}?type=received`,
(data) => {
setEvents((prev) => [...prev, data]);
onVerified(true);
}
);
const isConnected = events.length > 0;
const renderIcon = () => {
@@ -31,18 +49,16 @@ const VerifyListener = ({ events }: Props) => {
<div
className={cn(
'flex gap-6 rounded-xl p-4 md:p-6',
isConnected
? 'bg-emerald-100 dark:bg-emerald-700/10'
: 'bg-blue-500/10'
isConnected ? 'bg-emerald-100 dark:bg-emerald-700' : 'bg-blue-500/10'
)}
>
{renderIcon()}
<div className="flex-1">
<div className="font-semibold text-foreground/90 text-lg leading-normal">
{isConnected ? 'Successfully connected' : 'Waiting for events'}
{isConnected ? 'Success' : 'Waiting for events'}
</div>
{isConnected ? (
<div className="mt-2 flex flex-col-reverse gap-1">
<div className="flex flex-col-reverse">
{events.length > 5 && (
<div className="flex items-center gap-2">
<CheckIcon size={14} />{' '}
@@ -53,7 +69,7 @@ const VerifyListener = ({ events }: Props) => {
<div className="flex items-center gap-2" key={event.id}>
<CheckIcon size={14} />{' '}
<span className="font-medium">{event.name}</span>{' '}
<span className="ml-auto text-foreground/50 text-sm">
<span className="ml-auto text-emerald-800">
{timeAgo(event.createdAt, 'round')}
</span>
</div>

View File

@@ -242,7 +242,6 @@ export default function BillingUsage({ organization }: Props) {
<XAxis {...xAxisProps} dataKey="date" />
<YAxis {...yAxisProps} domain={[0, 'dataMax']} />
<CartesianGrid
className="stroke-border"
horizontal={true}
strokeDasharray="3 3"
strokeOpacity={0.5}

View File

@@ -1,9 +1,8 @@
import type { IChartRange, IInterval } from '@openpanel/validation';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { AlertCircleIcon, ChevronsUpDownIcon, SearchIcon } from 'lucide-react';
import { AlertCircleIcon, ChevronsUpDownIcon } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Pagination } from '@/components/pagination';
import { Input } from '@/components/ui/input';
import { useAppContext } from '@/hooks/use-app-context';
import { useTRPC } from '@/integrations/trpc/react';
import { pushModal } from '@/modals';
@@ -28,7 +27,6 @@ export function GscCannibalization({
const { apiUrl } = useAppContext();
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [page, setPage] = useState(0);
const [search, setSearch] = useState('');
const pageSize = 15;
const query = useQuery(
@@ -56,19 +54,7 @@ export function GscCannibalization({
});
};
const allItems = query.data ?? [];
const items = useMemo(() => {
if (!search.trim()) {
return allItems;
}
const q = search.toLowerCase();
return allItems.filter(
(item) =>
item.query.toLowerCase().includes(q) ||
item.pages.some((p) => p.page.toLowerCase().includes(q))
);
}, [allItems, search]);
const items = query.data ?? [];
const pageCount = Math.ceil(items.length / pageSize) || 1;
useEffect(() => {
@@ -81,52 +67,37 @@ export function GscCannibalization({
const rangeStart = items.length ? page * pageSize + 1 : 0;
const rangeEnd = Math.min((page + 1) * pageSize, items.length);
if (!(query.isLoading || allItems.length)) {
if (!(query.isLoading || items.length)) {
return null;
}
return (
<div className="card">
<div className="border-b">
<div className="flex items-center justify-between px-4 py-3">
<div className="flex items-center gap-2">
<h3 className="font-medium text-sm">Keyword Cannibalization</h3>
{items.length > 0 && (
<span className="rounded-full bg-muted px-2 py-0.5 font-medium text-muted-foreground text-xs">
{items.length}
</span>
)}
</div>
<div className="card overflow-hidden">
<div className="flex items-center justify-between border-b px-4 py-3">
<div className="flex items-center gap-2">
<h3 className="font-medium text-sm">Keyword Cannibalization</h3>
{items.length > 0 && (
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-muted-foreground text-xs">
{items.length === 0
? '0 results'
: `${rangeStart}-${rangeEnd} of ${items.length}`}
</span>
<Pagination
canNextPage={page < pageCount - 1}
canPreviousPage={page > 0}
nextPage={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
pageIndex={page}
previousPage={() => setPage((p) => Math.max(0, p - 1))}
/>
</div>
<span className="rounded-full bg-muted px-2 py-0.5 font-medium text-muted-foreground text-xs">
{items.length}
</span>
)}
</div>
<div className="relative">
<SearchIcon className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
className="rounded-none border-0 border-t bg-transparent pl-9 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0"
onChange={(e) => {
setSearch(e.target.value);
setPage(0);
}}
placeholder="Search keywords"
type="search"
value={search}
/>
</div>
{items.length > 0 && (
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-muted-foreground text-xs">
{items.length === 0
? '0 results'
: `${rangeStart}-${rangeEnd} of ${items.length}`}
</span>
<Pagination
canNextPage={page < pageCount - 1}
canPreviousPage={page > 0}
nextPage={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
pageIndex={page}
previousPage={() => setPage((p) => Math.max(0, p - 1))}
/>
</div>
)}
</div>
<div className="divide-y">
{query.isLoading &&

View File

@@ -3,13 +3,11 @@ import {
AlertTriangleIcon,
EyeIcon,
MousePointerClickIcon,
SearchIcon,
TrendingUpIcon,
} from 'lucide-react';
import { useMemo, useState } from 'react';
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { Pagination } from '@/components/pagination';
import { Input } from '@/components/ui/input';
import { useAppContext } from '@/hooks/use-app-context';
import { useTRPC } from '@/integrations/trpc/react';
import { pushModal } from '@/modals';
@@ -71,7 +69,6 @@ export function PagesInsights({ projectId }: PagesInsightsProps) {
const { range, interval, startDate, endDate } = useOverviewOptions();
const { apiUrl } = useAppContext();
const [page, setPage] = useState(0);
const [search, setSearch] = useState('');
const pageSize = 8;
const dateInput = {
@@ -220,71 +217,45 @@ export function PagesInsights({ projectId }: PagesInsightsProps) {
const isLoading = gscPagesQuery.isLoading || analyticsQuery.isLoading;
const filteredInsights = useMemo(() => {
if (!search.trim()) {
return insights;
}
const q = search.toLowerCase();
return insights.filter(
(i) =>
i.path.toLowerCase().includes(q) || i.page.toLowerCase().includes(q)
);
}, [insights, search]);
const pageCount = Math.ceil(filteredInsights.length / pageSize) || 1;
const pageCount = Math.ceil(insights.length / pageSize) || 1;
const paginatedInsights = useMemo(
() => filteredInsights.slice(page * pageSize, (page + 1) * pageSize),
[filteredInsights, page, pageSize]
() => insights.slice(page * pageSize, (page + 1) * pageSize),
[insights, page, pageSize]
);
const rangeStart = filteredInsights.length ? page * pageSize + 1 : 0;
const rangeEnd = Math.min((page + 1) * pageSize, filteredInsights.length);
const rangeStart = insights.length ? page * pageSize + 1 : 0;
const rangeEnd = Math.min((page + 1) * pageSize, insights.length);
if (!(isLoading || insights.length)) {
if (!isLoading && !insights.length) {
return null;
}
return (
<div className="card">
<div className="border-b">
<div className="flex items-center justify-between px-4 py-3">
<div className="flex items-center gap-2">
<h3 className="font-medium text-sm">Opportunities</h3>
{filteredInsights.length > 0 && (
<span className="rounded-full bg-muted px-2 py-0.5 font-medium text-muted-foreground text-xs">
{filteredInsights.length}
</span>
)}
</div>
{filteredInsights.length > 0 && (
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-muted-foreground text-xs">
{filteredInsights.length === 0
? '0 results'
: `${rangeStart}-${rangeEnd} of ${filteredInsights.length}`}
</span>
<Pagination
canNextPage={page < pageCount - 1}
canPreviousPage={page > 0}
nextPage={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
pageIndex={page}
previousPage={() => setPage((p) => Math.max(0, p - 1))}
/>
</div>
<div className="card overflow-hidden">
<div className="flex items-center justify-between border-b px-4 py-3">
<div className="flex items-center gap-2">
<h3 className="font-medium text-sm">Opportunities</h3>
{insights.length > 0 && (
<span className="rounded-full bg-muted px-2 py-0.5 font-medium text-muted-foreground text-xs">
{insights.length}
</span>
)}
</div>
<div className="relative">
<SearchIcon className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
className="rounded-none border-0 border-t bg-transparent pl-9 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0"
onChange={(e) => {
setSearch(e.target.value);
setPage(0);
}}
placeholder="Search pages"
type="search"
value={search}
/>
</div>
{insights.length > 0 && (
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-muted-foreground text-xs">
{insights.length === 0
? '0 results'
: `${rangeStart}-${rangeEnd} of ${insights.length}`}
</span>
<Pagination
canNextPage={page < pageCount - 1}
canPreviousPage={page > 0}
nextPage={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
pageIndex={page}
previousPage={() => setPage((p) => Math.max(0, p - 1))}
/>
</div>
)}
</div>
<div className="divide-y">
{isLoading &&
@@ -316,16 +287,6 @@ export function PagesInsights({ projectId }: PagesInsightsProps) {
type="button"
>
<div className="col min-w-0 flex-1 gap-2">
<span
className={cn(
'row shrink-0 items-center gap-1 self-start rounded-md px-1 py-0.5 font-medium text-xs',
config.color,
config.bg
)}
>
<Icon className="size-3" />
{config.label}
</span>
<div className="flex items-center gap-2">
<img
alt=""
@@ -340,8 +301,15 @@ export function PagesInsights({ projectId }: PagesInsightsProps) {
{insight.path || insight.page}
</span>
<span className="ml-auto shrink-0 whitespace-nowrap font-mono text-muted-foreground text-xs">
{insight.metrics}
<span
className={cn(
'row shrink-0 items-center gap-1 rounded-md px-1 py-0.5 font-medium text-xs',
config.color,
config.bg
)}
>
<Icon className="size-3" />
{config.label}
</span>
</div>
<p className="text-muted-foreground text-xs leading-relaxed">
@@ -351,6 +319,10 @@ export function PagesInsights({ projectId }: PagesInsightsProps) {
{insight.suggestion}
</p>
</div>
<span className="shrink-0 whitespace-nowrap font-mono text-muted-foreground text-xs">
{insight.metrics}
</span>
</button>
);
})}

View File

@@ -1,5 +1,4 @@
import { ZapIcon } from 'lucide-react';
import { Widget, WidgetEmptyState } from '@/components/widget';
import { Widget } from '@/components/widget';
import { WidgetHead, WidgetTitle } from '../overview/overview-widget';
type Props = {
@@ -7,32 +6,28 @@ type Props = {
};
export const MostEvents = ({ data }: Props) => {
const max = data.length > 0 ? Math.max(...data.map((item) => item.count)) : 0;
const max = Math.max(...data.map((item) => item.count));
return (
<Widget className="w-full">
<WidgetHead>
<WidgetTitle>Popular events</WidgetTitle>
</WidgetHead>
{data.length === 0 ? (
<WidgetEmptyState icon={ZapIcon} text="No events yet" />
) : (
<div className="flex flex-col gap-1 p-1">
{data.slice(0, 5).map((item) => (
<div key={item.name} className="relative px-3 py-2">
<div
className="absolute bottom-0 left-0 top-0 rounded bg-def-200"
style={{
width: `${(item.count / max) * 100}%`,
}}
/>
<div className="relative flex justify-between ">
<div>{item.name}</div>
<div>{item.count}</div>
</div>
<div className="flex flex-col gap-1 p-1">
{data.slice(0, 5).map((item) => (
<div key={item.name} className="relative px-3 py-2">
<div
className="absolute bottom-0 left-0 top-0 rounded bg-def-200"
style={{
width: `${(item.count / max) * 100}%`,
}}
/>
<div className="relative flex justify-between ">
<div>{item.name}</div>
<div>{item.count}</div>
</div>
))}
</div>
)}
</div>
))}
</div>
</Widget>
);
};

View File

@@ -1,5 +1,4 @@
import { RouteIcon } from 'lucide-react';
import { Widget, WidgetEmptyState } from '@/components/widget';
import { Widget } from '@/components/widget';
import { WidgetHead, WidgetTitle } from '../overview/overview-widget';
type Props = {
@@ -7,32 +6,28 @@ type Props = {
};
export const PopularRoutes = ({ data }: Props) => {
const max = data.length > 0 ? Math.max(...data.map((item) => item.count)) : 0;
const max = Math.max(...data.map((item) => item.count));
return (
<Widget className="w-full">
<WidgetHead>
<WidgetTitle>Most visted pages</WidgetTitle>
</WidgetHead>
{data.length === 0 ? (
<WidgetEmptyState icon={RouteIcon} text="No pages visited yet" />
) : (
<div className="flex flex-col gap-1 p-1">
{data.slice(0, 5).map((item) => (
<div key={item.path} className="relative px-3 py-2">
<div
className="absolute bottom-0 left-0 top-0 rounded bg-def-200"
style={{
width: `${(item.count / max) * 100}%`,
}}
/>
<div className="relative flex justify-between ">
<div>{item.path}</div>
<div>{item.count}</div>
</div>
<div className="flex flex-col gap-1 p-1">
{data.slice(0, 5).map((item) => (
<div key={item.path} className="relative px-3 py-2">
<div
className="absolute bottom-0 left-0 top-0 rounded bg-def-200"
style={{
width: `${(item.count / max) * 100}%`,
}}
/>
<div className="relative flex justify-between ">
<div>{item.path}</div>
<div>{item.count}</div>
</div>
))}
</div>
)}
</div>
))}
</div>
</Widget>
);
};

View File

@@ -1,43 +0,0 @@
import { ProjectLink } from '@/components/links';
import { useTRPC } from '@/integrations/trpc/react';
import { useQuery } from '@tanstack/react-query';
import { UsersIcon } from 'lucide-react';
interface Props {
profileId: string;
projectId: string;
groups: string[];
}
export const ProfileGroups = ({ projectId, groups }: Props) => {
const trpc = useTRPC();
const query = useQuery(
trpc.group.listByIds.queryOptions({
projectId,
ids: groups,
}),
);
if (groups.length === 0 || !query.data?.length) {
return null;
}
return (
<div className="flex flex-wrap items-center gap-2">
<span className="flex shrink-0 items-center gap-1.5 text-muted-foreground text-xs">
<UsersIcon className="size-3.5" />
Groups
</span>
{query.data.map((group) => (
<ProjectLink
key={group.id}
href={`/groups/${encodeURIComponent(group.id)}`}
className="inline-flex items-center gap-1.5 rounded-full border bg-muted/50 px-2.5 py-1 text-xs transition-colors hover:bg-muted"
>
<span className="font-medium">{group.name}</span>
<span className="text-muted-foreground">{group.type}</span>
</ProjectLink>
))}
</div>
);
};

View File

@@ -1,10 +1,15 @@
import type { IServiceProfile } from '@openpanel/db';
import type { ColumnDef } from '@tanstack/react-table';
import { ProfileAvatar } from '../profile-avatar';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { ProjectLink } from '@/components/links';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { Tooltiper } from '@/components/ui/tooltip';
import { formatDateTime, formatTime } from '@/utils/date';
import { getProfileName } from '@/utils/getters';
import type { ColumnDef } from '@tanstack/react-table';
import { isToday } from 'date-fns';
import type { IServiceProfile } from '@openpanel/db';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { ProfileAvatar } from '../profile-avatar';
export function useColumns(type: 'profiles' | 'power-users') {
const columns: ColumnDef<IServiceProfile>[] = [
@@ -15,8 +20,8 @@ export function useColumns(type: 'profiles' | 'power-users') {
const profile = row.original;
return (
<ProjectLink
className="flex items-center gap-2 font-medium"
href={`/profiles/${encodeURIComponent(profile.id)}`}
className="flex items-center gap-2 font-medium"
title={getProfileName(profile, false)}
>
<ProfileAvatar size="sm" {...profile} />
@@ -95,40 +100,13 @@ export function useColumns(type: 'profiles' | 'power-users') {
},
{
accessorKey: 'createdAt',
header: 'First seen',
header: 'Last seen',
size: ColumnCreatedAt.size,
cell: ({ row }) => {
const item = row.original;
return <ColumnCreatedAt>{item.createdAt}</ColumnCreatedAt>;
},
},
{
accessorKey: 'groups',
header: 'Groups',
size: 200,
meta: {
hidden: true,
},
cell({ row }) {
const { groups } = row.original;
if (!groups?.length) {
return null;
}
return (
<div className="flex flex-wrap gap-1">
{groups.map((g) => (
<ProjectLink
className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs hover:underline"
href={`/groups/${encodeURIComponent(g)}`}
key={g}
>
{g}
</ProjectLink>
))}
</div>
);
},
},
];
if (type === 'power-users') {

View File

@@ -1,24 +1,22 @@
import type { IServiceProfile } from '@openpanel/db';
import type { UseQueryResult } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import type { PaginationState, Table, Updater } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { memo, useCallback } from 'react';
import { useDataTableColumnVisibility } from '@/components/ui/data-table/data-table-hooks';
import type { RouterOutputs } from '@/trpc/client';
import { useColumns } from './columns';
import { DataTable } from '@/components/ui/data-table/data-table';
import {
useDataTableColumnVisibility,
useDataTablePagination,
} from '@/components/ui/data-table/data-table-hooks';
import { useDataTablePagination } from '@/components/ui/data-table/data-table-hooks';
import {
AnimatedSearchInput,
DataTableToolbarContainer,
} from '@/components/ui/data-table/data-table-toolbar';
import { DataTableViewOptions } from '@/components/ui/data-table/data-table-view-options';
import { useAppParams } from '@/hooks/use-app-params';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
import type { RouterOutputs } from '@/trpc/client';
import { arePropsEqual } from '@/utils/are-props-equal';
import type { IServiceProfile } from '@openpanel/db';
import type { PaginationState, Table, Updater } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { memo } from 'react';
const PAGE_SIZE = 50;
@@ -34,22 +32,6 @@ export const ProfilesTable = memo(
({ type, query, pageSize = PAGE_SIZE }: Props) => {
const { data, isLoading } = query;
const columns = useColumns(type);
const navigate = useNavigate();
const { organizationId, projectId } = useAppParams();
const handleRowClick = useCallback(
(row: any) => {
navigate({
to: '/$organizationId/$projectId/profiles/$profileId',
params: {
organizationId,
projectId,
profileId: encodeURIComponent(row.original.id),
},
});
},
[navigate, organizationId, projectId]
);
const { setPage, state: pagination } = useDataTablePagination(pageSize);
const {
@@ -68,7 +50,7 @@ export const ProfilesTable = memo(
columns,
rowCount: data?.meta.count,
pageCount: Math.ceil(
(data?.meta.count || 0) / (pagination.pageSize || 1)
(data?.meta.count || 0) / (pagination.pageSize || 1),
),
filterFns: {
isWithinRange: () => true,
@@ -94,18 +76,17 @@ export const ProfilesTable = memo(
<>
<ProfileTableToolbar table={table} />
<DataTable
table={table}
loading={isLoading}
empty={{
title: 'No profiles',
description: "Looks like you haven't identified any profiles yet.",
}}
loading={isLoading}
onRowClick={handleRowClick}
table={table}
/>
</>
);
},
arePropsEqual(['query.isLoading', 'query.data', 'type', 'pageSize'])
arePropsEqual(['query.isLoading', 'query.data', 'type', 'pageSize']),
);
function ProfileTableToolbar({ table }: { table: Table<IServiceProfile> }) {
@@ -113,9 +94,9 @@ function ProfileTableToolbar({ table }: { table: Table<IServiceProfile> }) {
return (
<DataTableToolbarContainer>
<AnimatedSearchInput
onChange={setSearch}
placeholder="Search profiles"
value={search}
onChange={setSearch}
/>
<DataTableViewOptions table={table} />
</DataTableToolbarContainer>

View File

@@ -1,9 +1,11 @@
import { useTRPC } from '@/integrations/trpc/react';
import { useQuery } from '@tanstack/react-query';
import { AnimatePresence, motion } from 'framer-motion';
import { ProjectLink } from '../links';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { useTRPC } from '@/integrations/trpc/react';
import { formatTimeAgoOrDateTime } from '@/utils/date';
import { useEffect, useState } from 'react';
import useWS from '@/hooks/use-ws';
import type { IServiceEvent } from '@openpanel/db';
import { EventItem } from '../events/table/item';
interface RealtimeActiveSessionsProps {
projectId: string;
@@ -15,52 +17,64 @@ export function RealtimeActiveSessions({
limit = 10,
}: RealtimeActiveSessionsProps) {
const trpc = useTRPC();
const { data: sessions = [] } = useQuery(
trpc.realtime.activeSessions.queryOptions(
{ projectId },
{ refetchInterval: 5000 }
)
const activeSessionsQuery = useQuery(
trpc.realtime.activeSessions.queryOptions({
projectId,
}),
);
const [state, setState] = useState<IServiceEvent[]>([]);
// Update state when initial data loads
useEffect(() => {
if (activeSessionsQuery.data && state.length === 0) {
setState(activeSessionsQuery.data);
}
}, [activeSessionsQuery.data, state]);
// Set up WebSocket connection for real-time updates
useWS<IServiceEvent>(
`/live/events/${projectId}`,
(session) => {
setState((prev) => {
// Add new session and remove duplicates, keeping most recent
const filtered = prev.filter((s) => s.id !== session.id);
return [session, ...filtered].slice(0, limit);
});
},
{
debounce: {
delay: 1000,
maxWait: 5000,
},
},
);
const sessions = state.length > 0 ? state : (activeSessionsQuery.data ?? []);
return (
<div className="col card h-full max-md:hidden">
<div className="hide-scrollbar h-full overflow-y-auto">
<AnimatePresence initial={false} mode="popLayout">
<div className="col divide-y">
{sessions.slice(0, limit).map((session) => (
<div className="col h-full max-md:hidden">
<div className="hide-scrollbar h-full overflow-y-auto pb-10">
<AnimatePresence mode="popLayout" initial={false}>
<div className="col gap-4">
{sessions.map((session) => (
<motion.div
animate={{ opacity: 1, x: 0, scale: 1 }}
exit={{ opacity: 0, x: 200, scale: 0.8 }}
key={session.id}
layout
// initial={{ opacity: 0, x: -200, scale: 0.8 }}
animate={{ opacity: 1, x: 0, scale: 1 }}
exit={{ opacity: 0, x: 200, scale: 0.8 }}
transition={{ duration: 0.4, type: 'spring', stiffness: 300 }}
>
<ProjectLink
className="relative block p-4 py-3 pr-14"
href={`/sessions/${session.sessionId}`}
>
<div className="col flex-1 gap-1">
{session.name === 'screen_view' && (
<span className="text-muted-foreground text-xs leading-normal/80">
{session.origin}
</span>
)}
<span className="font-medium text-sm leading-normal">
{session.name === 'screen_view'
? session.path
: session.name}
</span>
<span className="text-muted-foreground text-xs">
{formatTimeAgoOrDateTime(session.createdAt)}
</span>
</div>
<div className="row absolute top-1/2 right-4 origin-right -translate-y-1/2 scale-50 gap-2">
<SerieIcon name={session.referrerName} />
<SerieIcon name={session.os} />
<SerieIcon name={session.browser} />
<SerieIcon name={session.device} />
</div>
</ProjectLink>
<EventItem
event={session}
viewOptions={{
properties: false,
origin: false,
queryString: false,
}}
className="w-full"
/>
</motion.div>
))}
</div>

View File

@@ -166,8 +166,7 @@ export function Tables({
metric: 'sum',
options: funnelOptions,
},
stepIndex,
breakdownValues: breakdowns,
stepIndex, // Pass the step index for funnel queries
});
};
return (

View File

@@ -1,8 +1,5 @@
import { chartSegments } from '@openpanel/constants';
import { type IChartEventSegment, mapKeys } from '@openpanel/validation';
import {
ActivityIcon,
Building2Icon,
ClockIcon,
EqualApproximatelyIcon,
type LucideIcon,
@@ -13,7 +10,10 @@ import {
UserCheckIcon,
UsersIcon,
} from 'lucide-react';
import { Button } from '../ui/button';
import { chartSegments } from '@openpanel/constants';
import { type IChartEventSegment, mapKeys } from '@openpanel/validation';
import {
DropdownMenu,
DropdownMenuContent,
@@ -25,6 +25,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
import { Button } from '../ui/button';
interface ReportChartTypeProps {
className?: string;
@@ -45,7 +46,6 @@ export function ReportSegment({
event: ActivityIcon,
user: UsersIcon,
session: ClockIcon,
group: Building2Icon,
user_average: UserCheck2Icon,
one_event_per_user: UserCheckIcon,
property_sum: SigmaIcon,
@@ -58,9 +58,9 @@ export function ReportSegment({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
className={cn('justify-start text-sm', className)}
icon={Icons[value]}
variant="outline"
icon={Icons[value]}
className={cn('justify-start text-sm', className)}
>
{items.find((item) => item.value === value)?.label}
</Button>
@@ -74,13 +74,13 @@ export function ReportSegment({
const Icon = Icons[item.value];
return (
<DropdownMenuItem
className="group"
key={item.value}
onClick={() => onChange(item.value)}
className="group"
>
{item.label}
<DropdownMenuShortcut>
<Icon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
<Icon className="size-4 group-hover:text-blue-500 group-hover:scale-125 transition-all group-hover:rotate-12" />
</DropdownMenuShortcut>
</DropdownMenuItem>
);

View File

@@ -1,14 +1,3 @@
import type { IChartEvent } from '@openpanel/validation';
import { useQuery } from '@tanstack/react-query';
import { AnimatePresence, motion } from 'framer-motion';
import {
ArrowLeftIcon,
Building2Icon,
DatabaseIcon,
UserIcon,
} from 'lucide-react';
import VirtualList from 'rc-virtual-list';
import { type Dispatch, type SetStateAction, useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
@@ -21,7 +10,11 @@ import {
import { Input } from '@/components/ui/input';
import { useAppParams } from '@/hooks/use-app-params';
import { useEventProperties } from '@/hooks/use-event-properties';
import { useTRPC } from '@/integrations/trpc/react';
import type { IChartEvent } from '@openpanel/validation';
import { AnimatePresence, motion } from 'framer-motion';
import { ArrowLeftIcon, DatabaseIcon, UserIcon } from 'lucide-react';
import VirtualList from 'rc-virtual-list';
import { type Dispatch, type SetStateAction, useEffect, useState } from 'react';
interface PropertiesComboboxProps {
event?: IChartEvent;
@@ -47,15 +40,15 @@ function SearchHeader({
return (
<div className="row items-center gap-1">
{!!onBack && (
<Button onClick={onBack} size="icon" variant="ghost">
<Button variant="ghost" size="icon" onClick={onBack}>
<ArrowLeftIcon className="size-4" />
</Button>
)}
<Input
autoFocus
onChange={(e) => onSearch(e.target.value)}
placeholder="Search"
value={value}
onChange={(e) => onSearch(e.target.value)}
autoFocus
/>
</div>
);
@@ -69,24 +62,18 @@ export function PropertiesCombobox({
exclude = [],
}: PropertiesComboboxProps) {
const { projectId } = useAppParams();
const trpc = useTRPC();
const [open, setOpen] = useState(false);
const properties = useEventProperties({
event: event?.name,
projectId,
});
const groupPropertiesQuery = useQuery(
trpc.group.properties.queryOptions({ projectId })
);
const [state, setState] = useState<'index' | 'event' | 'profile' | 'group'>(
'index'
);
const [state, setState] = useState<'index' | 'event' | 'profile'>('index');
const [search, setSearch] = useState('');
const [direction, setDirection] = useState<'forward' | 'backward'>('forward');
useEffect(() => {
if (!open) {
setState(mode ? (mode === 'events' ? 'event' : 'profile') : 'index');
setState(!mode ? 'index' : mode === 'events' ? 'event' : 'profile');
}
}, [open, mode]);
@@ -99,21 +86,11 @@ export function PropertiesCombobox({
});
};
// Fixed group properties: name, type, plus dynamic property keys
const groupActions = [
{ value: 'group.name', label: 'name', description: 'group' },
{ value: 'group.type', label: 'type', description: 'group' },
...(groupPropertiesQuery.data ?? []).map((key) => ({
value: `group.properties.${key}`,
label: key,
description: 'group.properties',
})),
].filter((a) => shouldShowProperty(a.value));
// Mock data for the lists
const profileActions = properties
.filter(
(property) =>
property.startsWith('profile') && shouldShowProperty(property)
property.startsWith('profile') && shouldShowProperty(property),
)
.map((property) => ({
value: property,
@@ -123,7 +100,7 @@ export function PropertiesCombobox({
const eventActions = properties
.filter(
(property) =>
!property.startsWith('profile') && shouldShowProperty(property)
!property.startsWith('profile') && shouldShowProperty(property),
)
.map((property) => ({
value: property,
@@ -131,9 +108,7 @@ export function PropertiesCombobox({
description: property.split('.').slice(0, -1).join('.'),
}));
const handleStateChange = (
newState: 'index' | 'event' | 'profile' | 'group'
) => {
const handleStateChange = (newState: 'index' | 'event' | 'profile') => {
setDirection(newState === 'index' ? 'backward' : 'forward');
setState(newState);
};
@@ -160,7 +135,7 @@ export function PropertiesCombobox({
}}
>
Event properties
<DatabaseIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
<DatabaseIcon className="size-4 group-hover:text-blue-500 group-hover:scale-125 transition-all group-hover:rotate-12" />
</DropdownMenuItem>
<DropdownMenuItem
className="group justify-between gap-2"
@@ -170,17 +145,7 @@ export function PropertiesCombobox({
}}
>
Profile properties
<UserIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
</DropdownMenuItem>
<DropdownMenuItem
className="group justify-between gap-2"
onClick={(e) => {
e.preventDefault();
handleStateChange('group');
}}
>
Group properties
<Building2Icon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
<UserIcon className="size-4 group-hover:text-blue-500 group-hover:scale-125 transition-all group-hover:rotate-12" />
</DropdownMenuItem>
</DropdownMenuGroup>
);
@@ -190,7 +155,7 @@ export function PropertiesCombobox({
const filteredActions = eventActions.filter(
(action) =>
action.label.toLowerCase().includes(search.toLowerCase()) ||
action.description.toLowerCase().includes(search.toLowerCase())
action.description.toLowerCase().includes(search.toLowerCase()),
);
return (
@@ -204,20 +169,20 @@ export function PropertiesCombobox({
/>
<DropdownMenuSeparator />
<VirtualList
data={filteredActions}
height={300}
data={filteredActions}
itemHeight={40}
itemKey="id"
>
{(action) => (
<motion.div
animate={{ opacity: 1, y: 0 }}
className="col cursor-pointer gap-px rounded-md p-2 hover:bg-accent"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="p-2 hover:bg-accent cursor-pointer rounded-md col gap-px"
onClick={() => handleSelect(action)}
>
<div className="font-medium">{action.label}</div>
<div className="text-muted-foreground text-sm">
<div className="text-sm text-muted-foreground">
{action.description}
</div>
</motion.div>
@@ -231,7 +196,7 @@ export function PropertiesCombobox({
const filteredActions = profileActions.filter(
(action) =>
action.label.toLowerCase().includes(search.toLowerCase()) ||
action.description.toLowerCase().includes(search.toLowerCase())
action.description.toLowerCase().includes(search.toLowerCase()),
);
return (
@@ -243,59 +208,20 @@ export function PropertiesCombobox({
/>
<DropdownMenuSeparator />
<VirtualList
data={filteredActions}
height={300}
data={filteredActions}
itemHeight={40}
itemKey="id"
>
{(action) => (
<motion.div
animate={{ opacity: 1, y: 0 }}
className="col cursor-pointer gap-px rounded-md p-2 hover:bg-accent"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="p-2 hover:bg-accent cursor-pointer rounded-md col gap-px"
onClick={() => handleSelect(action)}
>
<div className="font-medium">{action.label}</div>
<div className="text-muted-foreground text-sm">
{action.description}
</div>
</motion.div>
)}
</VirtualList>
</div>
);
};
const renderGroup = () => {
const filteredActions = groupActions.filter(
(action) =>
action.label.toLowerCase().includes(search.toLowerCase()) ||
action.description.toLowerCase().includes(search.toLowerCase())
);
return (
<div className="flex flex-col">
<SearchHeader
onBack={() => handleStateChange('index')}
onSearch={setSearch}
value={search}
/>
<DropdownMenuSeparator />
<VirtualList
data={filteredActions}
height={Math.min(300, filteredActions.length * 40 + 8)}
itemHeight={40}
itemKey="value"
>
{(action) => (
<motion.div
animate={{ opacity: 1, y: 0 }}
className="col cursor-pointer gap-px rounded-md p-2 hover:bg-accent"
initial={{ opacity: 0, y: 10 }}
onClick={() => handleSelect(action)}
>
<div className="font-medium">{action.label}</div>
<div className="text-muted-foreground text-sm">
<div className="text-sm text-muted-foreground">
{action.description}
</div>
</motion.div>
@@ -307,20 +233,20 @@ export function PropertiesCombobox({
return (
<DropdownMenu
open={open}
onOpenChange={(open) => {
setOpen(open);
}}
open={open}
>
<DropdownMenuTrigger asChild>{children(setOpen)}</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-w-80">
<AnimatePresence initial={false} mode="wait">
<DropdownMenuContent className="max-w-80" align="start">
<AnimatePresence mode="wait" initial={false}>
{state === 'index' && (
<motion.div
key="index"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
key="index"
transition={{ duration: 0.05 }}
>
{renderIndex()}
@@ -328,10 +254,10 @@ export function PropertiesCombobox({
)}
{state === 'event' && (
<motion.div
key="event"
initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}
initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
key="event"
transition={{ duration: 0.05 }}
>
{renderEvent()}
@@ -339,26 +265,15 @@ export function PropertiesCombobox({
)}
{state === 'profile' && (
<motion.div
key="profile"
initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}
initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
key="profile"
transition={{ duration: 0.05 }}
>
{renderProfile()}
</motion.div>
)}
{state === 'group' && (
<motion.div
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}
initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
key="group"
transition={{ duration: 0.05 }}
>
{renderGroup()}
</motion.div>
)}
</AnimatePresence>
</DropdownMenuContent>
</DropdownMenu>

View File

@@ -74,7 +74,7 @@ export function useColumns() {
if (session.profile) {
return (
<ProjectLink
className="row items-center gap-2 font-medium hover:underline"
className="row items-center gap-2 font-medium"
href={`/profiles/${encodeURIComponent(session.profile.id)}`}
>
<ProfileAvatar size="sm" {...session.profile} />
@@ -270,27 +270,6 @@ export function useColumns() {
header: 'Device ID',
size: 120,
},
{
accessorKey: 'groups',
header: 'Groups',
size: 200,
cell: ({ row }) => {
const { groups } = row.original;
if (!groups?.length) return null;
return (
<div className="flex flex-wrap gap-1">
{groups.map((g) => (
<span
key={g}
className="rounded bg-muted px-1.5 py-0.5 text-xs font-mono"
>
{g}
</span>
))}
</div>
);
},
},
];
return columns;

View File

@@ -1,7 +1,9 @@
import type { UseInfiniteQueryResult } from '@tanstack/react-query';
import { useDataTableColumnVisibility } from '@/components/ui/data-table/data-table-hooks';
import type { RouterInputs, RouterOutputs } from '@/trpc/client';
import { useLocalStorage } from 'usehooks-ts';
import { useColumns } from './columns';
import type { RouterInputs, RouterOutputs } from '@/trpc/client';
// Custom hook for persistent column visibility
const usePersistentColumnVisibility = (columns: any[]) => {
@@ -19,7 +21,7 @@ const usePersistentColumnVisibility = (columns: any[]) => {
}
return acc;
},
{} as Record<string, boolean>
{} as Record<string, boolean>,
);
}, [columns, savedVisibility]);
@@ -35,33 +37,25 @@ const usePersistentColumnVisibility = (columns: any[]) => {
};
};
import type { IServiceSession } from '@openpanel/db';
import { useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import type { Table } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { useWindowVirtualizer } from '@tanstack/react-virtual';
import type { TRPCInfiniteData } from '@trpc/tanstack-react-query';
import { Loader2Icon, SlidersHorizontalIcon } from 'lucide-react';
import { last } from 'ramda';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useInViewport } from 'react-in-viewport';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import { Skeleton } from '@/components/skeleton';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
AnimatedSearchInput,
DataTableToolbarContainer,
} from '@/components/ui/data-table/data-table-toolbar';
import { DataTableViewOptions } from '@/components/ui/data-table/data-table-view-options';
import type { FilterDefinition } from '@/components/ui/filter-dropdown';
import { FilterDropdown } from '@/components/ui/filter-dropdown';
import { useAppParams } from '@/hooks/use-app-params';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
import { useSessionFilters } from '@/hooks/use-session-filters';
import { useTRPC } from '@/integrations/trpc/react';
import { arePropsEqual } from '@/utils/are-props-equal';
import { cn } from '@/utils/cn';
import type { IServiceSession } from '@openpanel/db';
import type { Table } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { useWindowVirtualizer } from '@tanstack/react-virtual';
import type { TRPCInfiniteData } from '@trpc/tanstack-react-query';
import { Loader2Icon } from 'lucide-react';
import { last } from 'ramda';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useInViewport } from 'react-in-viewport';
type Props = {
query: UseInfiniteQueryResult<
@@ -89,7 +83,6 @@ interface VirtualRowProps {
scrollMargin: number;
isLoading: boolean;
headerColumnsHash: string;
onRowClick?: (row: any) => void;
}
const VirtualRow = memo(
@@ -99,26 +92,12 @@ const VirtualRow = memo(
headerColumns,
scrollMargin,
isLoading,
onRowClick,
}: VirtualRowProps) {
return (
<div
className={cn(
'group/row absolute top-0 left-0 w-full border-b transition-colors hover:bg-muted/50',
onRowClick && 'cursor-pointer'
)}
data-index={virtualRow.index}
onClick={
onRowClick
? (e) => {
if ((e.target as HTMLElement).closest('a, button')) {
return;
}
onRowClick(row);
}
: undefined
}
ref={virtualRow.measureElement}
className="absolute top-0 left-0 w-full border-b hover:bg-muted/50 transition-colors group/row"
style={{
transform: `translateY(${virtualRow.start - scrollMargin}px)`,
display: 'grid',
@@ -133,8 +112,8 @@ const VirtualRow = memo(
const width = `${cell.column.getSize()}px`;
return (
<div
className="flex items-center whitespace-nowrap p-2 px-4 align-middle"
key={cell.id}
className="flex items-center p-2 px-4 align-middle whitespace-nowrap"
style={{
width,
overflow: 'hidden',
@@ -164,18 +143,16 @@ const VirtualRow = memo(
prevProps.virtualRow.start === nextProps.virtualRow.start &&
prevProps.virtualRow.size === nextProps.virtualRow.size &&
prevProps.isLoading === nextProps.isLoading &&
prevProps.headerColumnsHash === nextProps.headerColumnsHash &&
prevProps.onRowClick === nextProps.onRowClick
prevProps.headerColumnsHash === nextProps.headerColumnsHash
);
}
},
);
const VirtualizedSessionsTable = ({
table,
data,
isLoading,
onRowClick,
}: VirtualizedSessionsTableProps & { onRowClick?: (row: any) => void }) => {
}: VirtualizedSessionsTableProps) => {
const parentRef = useRef<HTMLDivElement>(null);
const headerColumns = table.getAllLeafColumns().filter((col) => {
@@ -194,12 +171,12 @@ const VirtualizedSessionsTable = ({
return (
<div
className="w-full overflow-x-auto rounded-md border bg-card"
ref={parentRef}
className="w-full overflow-x-auto border rounded-md bg-card"
>
{/* Table Header */}
<div
className="sticky top-0 z-10 border-b bg-card"
className="sticky top-0 z-10 bg-card border-b"
style={{
display: 'grid',
gridTemplateColumns: headerColumns
@@ -213,8 +190,8 @@ const VirtualizedSessionsTable = ({
const width = `${column.getSize()}px`;
return (
<div
className="flex h-10 items-center whitespace-nowrap px-4 text-left font-semibold text-[10px] text-foreground uppercase"
key={column.id}
className="flex items-center h-10 px-4 text-left text-[10px] uppercase text-foreground font-semibold whitespace-nowrap"
style={{
width,
}}
@@ -227,8 +204,8 @@ const VirtualizedSessionsTable = ({
{!isLoading && data.length === 0 && (
<FullPageEmptyState
description="Looks like you haven't inserted any events yet."
title="No sessions found"
description="Looks like you haven't inserted any events yet."
/>
)}
@@ -243,23 +220,20 @@ const VirtualizedSessionsTable = ({
>
{virtualRows.map((virtualRow) => {
const row = table.getRowModel().rows[virtualRow.index];
if (!row) {
return null;
}
if (!row) return null;
return (
<VirtualRow
headerColumns={headerColumns}
headerColumnsHash={headerColumnsHash}
isLoading={isLoading}
key={row.id}
onRowClick={onRowClick}
row={row}
scrollMargin={rowVirtualizer.options.scrollMargin}
virtualRow={{
...virtualRow,
measureElement: rowVirtualizer.measureElement,
}}
headerColumns={headerColumns}
headerColumnsHash={headerColumnsHash}
scrollMargin={rowVirtualizer.options.scrollMargin}
isLoading={isLoading}
/>
);
})}
@@ -271,25 +245,13 @@ const VirtualizedSessionsTable = ({
export const SessionsTable = ({ query }: Props) => {
const { isLoading } = query;
const columns = useColumns();
const navigate = useNavigate();
const { organizationId, projectId } = useAppParams();
const handleRowClick = useCallback(
(row: any) => {
navigate({
to: '/$organizationId/$projectId/sessions/$sessionId',
params: { organizationId, projectId, sessionId: row.original.id },
});
},
[navigate, organizationId, projectId]
);
const data = useMemo(() => {
if (isLoading) {
return LOADING_DATA;
}
return query.data?.pages?.flatMap((p) => p.items) ?? [];
return query.data?.pages?.flatMap((p) => p.data) ?? [];
}, [query.data]);
// const { setPage, state: pagination } = useDataTablePagination();
@@ -330,6 +292,7 @@ export const SessionsTable = ({ query }: Props) => {
enterCount > 0 &&
query.isFetchingNextPage === false
) {
console.log('fetching next page');
query.fetchNextPage();
}
}, [inViewport, enterCount, hasNextPage]);
@@ -338,16 +301,15 @@ export const SessionsTable = ({ query }: Props) => {
<>
<SessionTableToolbar table={table} />
<VirtualizedSessionsTable
table={table}
data={data}
isLoading={isLoading}
onRowClick={handleRowClick}
table={table}
/>
<div className="center-center h-10 w-full pt-4" ref={inViewportRef}>
<div className="w-full h-10 center-center pt-4" ref={inViewportRef}>
<div
className={cn(
'center-center size-8 rounded-full border bg-background opacity-0 transition-opacity',
query.isFetchingNextPage && 'opacity-100'
'size-8 bg-background rounded-full center-center border opacity-0 transition-opacity',
query.isFetchingNextPage && 'opacity-100',
)}
>
<Loader2Icon className="size-4 animate-spin" />
@@ -357,88 +319,15 @@ export const SessionsTable = ({ query }: Props) => {
);
};
const SESSION_FILTER_KEY_TO_FIELD: Record<string, string> = {
referrer: 'referrer_name',
country: 'country',
os: 'os',
browser: 'browser',
device: 'device',
};
const SESSION_FILTER_DEFINITIONS: FilterDefinition[] = [
{ key: 'referrer', label: 'Referrer', type: 'select' },
{ key: 'country', label: 'Country', type: 'select' },
{ key: 'os', label: 'OS', type: 'select' },
{ key: 'browser', label: 'Browser', type: 'select' },
{ key: 'device', label: 'Device', type: 'select' },
{ key: 'entryPage', label: 'Entry page', type: 'string' },
{ key: 'exitPage', label: 'Exit page', type: 'string' },
{ key: 'minPageViews', label: 'Min page views', type: 'number' },
{ key: 'maxPageViews', label: 'Max page views', type: 'number' },
{ key: 'minEvents', label: 'Min events', type: 'number' },
{ key: 'maxEvents', label: 'Max events', type: 'number' },
];
function SessionTableToolbar({ table }: { table: Table<IServiceSession> }) {
const { projectId } = useAppParams();
const trpc = useTRPC();
const queryClient = useQueryClient();
const { search, setSearch } = useSearchQueryState();
const { values, setValue, activeCount } = useSessionFilters();
const loadOptions = useCallback(
(key: string) => {
const field = SESSION_FILTER_KEY_TO_FIELD[key];
if (!field) {
return Promise.resolve([]);
}
return queryClient.fetchQuery(
trpc.session.distinctValues.queryOptions({
projectId,
field: field as
| 'referrer_name'
| 'country'
| 'os'
| 'browser'
| 'device',
})
);
},
[trpc, queryClient, projectId]
);
return (
<DataTableToolbarContainer>
<div className="flex flex-1 flex-wrap items-center gap-2">
<AnimatedSearchInput
onChange={setSearch}
placeholder="Search sessions by path, referrer..."
value={search}
/>
<FilterDropdown
definitions={SESSION_FILTER_DEFINITIONS}
loadOptions={loadOptions}
onChange={setValue}
values={values}
>
<Button
className={cn(
'border-dashed',
activeCount > 0 && 'border-primary border-solid'
)}
size="sm"
variant="outline"
>
<SlidersHorizontalIcon className="mr-2 size-4" />
Filters
{activeCount > 0 && (
<Badge className="ml-2 rounded-full px-1.5 py-0 text-xs">
{activeCount}
</Badge>
)}
</Button>
</FilterDropdown>
</div>
<AnimatedSearchInput
placeholder="Search sessions by path, referrer..."
value={search}
onChange={setSearch}
/>
<DataTableViewOptions table={table} />
</DataTableToolbarContainer>
);

View File

@@ -4,7 +4,6 @@ import { AnimatePresence, motion } from 'framer-motion';
import {
BellIcon,
BookOpenIcon,
Building2Icon,
ChartLineIcon,
ChevronDownIcon,
CogIcon,
@@ -63,7 +62,6 @@ export default function SidebarProjectMenu({
<SidebarLink href={'/events'} icon={GanttChartIcon} label="Events" />
<SidebarLink href={'/sessions'} icon={UsersIcon} label="Sessions" />
<SidebarLink href={'/profiles'} icon={UserCircleIcon} label="Profiles" />
<SidebarLink href={'/groups'} icon={Building2Icon} label="Groups" />
<div className="mt-4 mb-2 font-medium text-muted-foreground text-sm">
Manage
</div>

View File

@@ -1,6 +1,7 @@
import type { Column, Table } from '@tanstack/react-table';
import { SearchIcon, X, XIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import { DataTableDateFilter } from '@/components/ui/data-table/data-table-date-filter';
import { DataTableFacetedFilter } from '@/components/ui/data-table/data-table-faceted-filter';
@@ -22,12 +23,12 @@ export function DataTableToolbarContainer({
}: React.ComponentProps<'div'>) {
return (
<div
role="toolbar"
aria-orientation="horizontal"
className={cn(
'mb-2 flex flex-1 items-start justify-between gap-2',
className
'flex flex-1 items-start justify-between gap-2 mb-2',
className,
)}
role="toolbar"
{...props}
/>
);
@@ -46,12 +47,12 @@ export function DataTableToolbar<TData>({
});
const isFiltered = table.getState().columnFilters.length > 0;
const columns = useMemo(
const columns = React.useMemo(
() => table.getAllColumns().filter((column) => column.getCanFilter()),
[table]
[table],
);
const onReset = useCallback(() => {
const onReset = React.useCallback(() => {
table.resetColumnFilters();
}, [table]);
@@ -60,23 +61,23 @@ export function DataTableToolbar<TData>({
<div className="flex flex-1 flex-wrap items-center gap-2">
{globalSearchKey && (
<AnimatedSearchInput
onChange={setSearch}
placeholder={globalSearchPlaceholder ?? 'Search'}
value={search}
onChange={setSearch}
/>
)}
{columns.map((column) => (
<DataTableToolbarFilter column={column} key={column.id} />
<DataTableToolbarFilter key={column.id} column={column} />
))}
{isFiltered && (
<Button
aria-label="Reset filters"
variant="outline"
size="sm"
className="border-dashed"
onClick={onReset}
size="sm"
variant="outline"
>
<XIcon className="mr-2 size-4" />
<XIcon className="size-4 mr-2" />
Reset
</Button>
)}
@@ -98,22 +99,20 @@ function DataTableToolbarFilter<TData>({
{
const columnMeta = column.columnDef.meta;
const getTitle = useCallback(() => {
const getTitle = React.useCallback(() => {
return columnMeta?.label ?? columnMeta?.placeholder ?? column.id;
}, [columnMeta, column]);
const onFilterRender = useCallback(() => {
if (!columnMeta?.variant) {
return null;
}
const onFilterRender = React.useCallback(() => {
if (!columnMeta?.variant) return null;
switch (columnMeta.variant) {
case 'text':
return (
<AnimatedSearchInput
onChange={(value) => column.setFilterValue(value)}
placeholder={columnMeta.placeholder ?? columnMeta.label}
value={(column.getFilterValue() as string) ?? ''}
onChange={(value) => column.setFilterValue(value)}
/>
);
@@ -121,12 +120,12 @@ function DataTableToolbarFilter<TData>({
return (
<div className="relative">
<Input
className={cn('h-8 w-[120px]', columnMeta.unit && 'pr-8')}
inputMode="numeric"
onChange={(event) => column.setFilterValue(event.target.value)}
placeholder={getTitle()}
type="number"
inputMode="numeric"
placeholder={getTitle()}
value={(column.getFilterValue() as string) ?? ''}
onChange={(event) => column.setFilterValue(event.target.value)}
className={cn('h-8 w-[120px]', columnMeta.unit && 'pr-8')}
/>
{columnMeta.unit && (
<span className="absolute top-0 right-0 bottom-0 flex items-center rounded-r-md bg-accent px-2 text-muted-foreground text-sm">
@@ -144,8 +143,8 @@ function DataTableToolbarFilter<TData>({
return (
<DataTableDateFilter
column={column}
multiple={columnMeta.variant === 'dateRange'}
title={getTitle()}
multiple={columnMeta.variant === 'dateRange'}
/>
);
@@ -154,9 +153,9 @@ function DataTableToolbarFilter<TData>({
return (
<DataTableFacetedFilter
column={column}
multiple={columnMeta.variant === 'multiSelect'}
options={columnMeta.options ?? []}
title={getTitle()}
options={columnMeta.options ?? []}
multiple={columnMeta.variant === 'multiSelect'}
/>
);
@@ -180,11 +179,11 @@ export function AnimatedSearchInput({
value,
onChange,
}: AnimatedSearchInputProps) {
const [isFocused, setIsFocused] = useState(false);
const inputRef = useRef<HTMLInputElement | null>(null);
const [isFocused, setIsFocused] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement | null>(null);
const isExpanded = isFocused || (value?.length ?? 0) > 0;
const handleClear = useCallback(() => {
const handleClear = React.useCallback(() => {
onChange('');
// Re-focus after clearing
requestAnimationFrame(() => inputRef.current?.focus());
@@ -192,35 +191,34 @@ export function AnimatedSearchInput({
return (
<div
aria-label={placeholder ?? 'Search'}
className={cn(
'relative flex items-center rounded-md border border-input bg-background text-sm transition-[width] duration-300 ease-out',
'relative flex h-8 items-center rounded-md border border-input bg-background text-sm transition-[width] duration-300 ease-out',
'focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background',
'h-8 min-h-8',
isExpanded ? 'w-56 lg:w-72' : 'w-32'
isExpanded ? 'w-56 lg:w-72' : 'w-32',
)}
role="search"
aria-label={placeholder ?? 'Search'}
>
<SearchIcon className="ml-2 size-4 shrink-0" />
<SearchIcon className="size-4 ml-2 shrink-0" />
<Input
ref={inputRef}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
className={cn(
'absolute inset-0 h-full w-full rounded-md border-0 bg-transparent py-2 pr-7 pl-7 shadow-none',
'absolute inset-0 -top-px h-8 w-full rounded-md border-0 bg-transparent pl-7 pr-7 shadow-none',
'focus-visible:ring-0 focus-visible:ring-offset-0',
'transition-opacity duration-200',
'truncate align-baseline font-medium text-[14px]'
'font-medium text-[14px] truncate align-baseline',
)}
onBlur={() => setIsFocused(false)}
onChange={(e) => onChange(e.target.value)}
onFocus={() => setIsFocused(true)}
placeholder={placeholder}
ref={inputRef}
size="sm"
value={value}
onBlur={() => setIsFocused(false)}
/>
{isExpanded && value && (
<button
type="button"
aria-label="Clear search"
className="absolute right-1 flex size-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
onClick={(e) => {
@@ -228,7 +226,6 @@ export function AnimatedSearchInput({
e.stopPropagation();
handleClear();
}}
type="button"
>
<X className="size-4" />
</button>

View File

@@ -1,328 +0,0 @@
import { AnimatePresence, motion } from 'framer-motion';
import {
ArrowLeftIcon,
CheckIcon,
ChevronRightIcon,
Loader2Icon,
XIcon,
} from 'lucide-react';
import VirtualList from 'rc-virtual-list';
import { useEffect, useState } from 'react';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/utils/cn';
export type FilterType = 'select' | 'string' | 'number';
export interface FilterDefinition {
key: string;
label: string;
type: FilterType;
/** For 'select' type: show SerieIcon next to options (default true) */
showIcon?: boolean;
}
interface FilterDropdownProps {
definitions: FilterDefinition[];
values: Record<string, string | number | null | undefined>;
onChange: (key: string, value: string | number | null) => void;
loadOptions: (key: string) => Promise<string[]>;
children: React.ReactNode;
}
export function FilterDropdown({
definitions,
values,
onChange,
loadOptions,
children,
}: FilterDropdownProps) {
const [open, setOpen] = useState(false);
const [activeKey, setActiveKey] = useState<string | null>(null);
const [direction, setDirection] = useState<'forward' | 'backward'>('forward');
const [search, setSearch] = useState('');
const [options, setOptions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
if (!open) {
setActiveKey(null);
setSearch('');
setOptions([]);
setInputValue('');
}
}, [open]);
useEffect(() => {
if (!activeKey) {
return;
}
const def = definitions.find((d) => d.key === activeKey);
if (!def || def.type !== 'select') {
return;
}
setIsLoading(true);
loadOptions(activeKey)
.then((opts) => {
setOptions(opts);
setIsLoading(false);
})
.catch(() => setIsLoading(false));
}, [activeKey]);
const currentDef = activeKey
? definitions.find((d) => d.key === activeKey)
: null;
const goToFilter = (key: string) => {
setDirection('forward');
setSearch('');
setOptions([]);
const current = values[key];
setInputValue(current != null ? String(current) : '');
setActiveKey(key);
};
const goBack = () => {
setDirection('backward');
setActiveKey(null);
setSearch('');
};
const applyValue = (key: string, value: string | number | null) => {
onChange(key, value);
goBack();
};
const renderIndex = () => (
<div className="min-w-52">
{definitions.map((def) => {
const currentValue = values[def.key];
const isActive = currentValue != null && currentValue !== '';
return (
<button
className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 hover:bg-accent"
key={def.key}
onClick={() => goToFilter(def.key)}
type="button"
>
<span className="font-medium text-sm">{def.label}</span>
<div className="flex shrink-0 items-center gap-1">
{isActive && (
<>
<span className="max-w-24 truncate text-muted-foreground text-xs">
{String(currentValue)}
</span>
<button
className="rounded-sm p-0.5 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation();
onChange(def.key, null);
}}
type="button"
>
<XIcon className="size-3" />
</button>
</>
)}
<ChevronRightIcon className="size-4 text-muted-foreground" />
</div>
</button>
);
})}
</div>
);
const renderSelectFilter = () => {
const showIcon = currentDef?.showIcon !== false;
const filteredOptions = options.filter((opt) =>
opt.toLowerCase().includes(search.toLowerCase())
);
const currentValue = activeKey ? values[activeKey] : undefined;
return (
<div className="min-w-52">
<div className="flex items-center gap-1 p-1">
<Button
className="size-7 shrink-0"
onClick={goBack}
size="icon"
variant="ghost"
>
<ArrowLeftIcon className="size-4" />
</Button>
<Input
autoFocus
className="h-7 text-sm"
onChange={(e) => setSearch(e.target.value)}
placeholder="Search..."
value={search}
/>
</div>
<Separator />
{isLoading ? (
<div className="flex items-center justify-center p-6 text-muted-foreground">
<Loader2Icon className="size-4 animate-spin" />
</div>
) : filteredOptions.length === 0 ? (
<div className="p-4 text-center text-muted-foreground text-sm">
No options found
</div>
) : (
<VirtualList
data={filteredOptions}
height={Math.min(filteredOptions.length * 36, 250)}
itemHeight={36}
itemKey={(item) => item}
>
{(option) => (
<button
className="flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 hover:bg-accent"
onClick={() => applyValue(activeKey!, option)}
type="button"
>
{showIcon && <SerieIcon name={option} />}
<span className="truncate text-sm">{option || 'Direct'}</span>
<CheckIcon
className={cn(
'ml-auto size-4 shrink-0',
currentValue === option ? 'opacity-100' : 'opacity-0'
)}
/>
</button>
)}
</VirtualList>
)}
</div>
);
};
const renderStringFilter = () => (
<div className="min-w-52">
<div className="flex items-center gap-1 p-1">
<Button
className="size-7 shrink-0"
onClick={goBack}
size="icon"
variant="ghost"
>
<ArrowLeftIcon className="size-4" />
</Button>
<span className="px-1 font-medium text-sm">{currentDef?.label}</span>
</div>
<Separator />
<div className="flex flex-col gap-2 p-2">
<Input
autoFocus
className="h-8 text-sm"
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
applyValue(activeKey!, inputValue || null);
}
}}
placeholder={`Filter by ${currentDef?.label.toLowerCase()}...`}
value={inputValue}
/>
<Button
className="w-full"
onClick={() => applyValue(activeKey!, inputValue || null)}
size="sm"
>
Apply
</Button>
</div>
</div>
);
const renderNumberFilter = () => (
<div className="min-w-52">
<div className="flex items-center gap-1 p-1">
<Button
className="size-7 shrink-0"
onClick={goBack}
size="icon"
variant="ghost"
>
<ArrowLeftIcon className="size-4" />
</Button>
<span className="px-1 font-medium text-sm">{currentDef?.label}</span>
</div>
<Separator />
<div className="flex flex-col gap-2 p-2">
<Input
autoFocus
className="h-8 text-sm"
inputMode="numeric"
min={0}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
applyValue(
activeKey!,
inputValue === '' ? null : Number(inputValue)
);
}
}}
placeholder="Enter value..."
type="number"
value={inputValue}
/>
<Button
className="w-full"
onClick={() =>
applyValue(
activeKey!,
inputValue === '' ? null : Number(inputValue)
)
}
size="sm"
>
Apply
</Button>
</div>
</div>
);
const renderContent = () => {
if (!(activeKey && currentDef)) {
return renderIndex();
}
switch (currentDef.type) {
case 'select':
return renderSelectFilter();
case 'string':
return renderStringFilter();
case 'number':
return renderNumberFilter();
}
};
return (
<Popover onOpenChange={setOpen} open={open}>
<PopoverTrigger asChild>{children}</PopoverTrigger>
<PopoverContent align="start" className="w-auto p-1">
<AnimatePresence initial={false} mode="wait">
<motion.div
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}
initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
key={activeKey ?? 'index'}
transition={{ duration: 0.1 }}
>
{renderContent()}
</motion.div>
</AnimatePresence>
</PopoverContent>
</Popover>
);
}

View File

@@ -1,6 +1,7 @@
import * as SelectPrimitive from '@radix-ui/react-select';
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
import type * as React from 'react';
import { cn } from '@/lib/utils';
function Select({
@@ -31,12 +32,12 @@ function SelectTrigger({
}) {
return (
<SelectPrimitive.Trigger
className={cn(
"flex w-fit items-center justify-between gap-2 whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[size=default]:h-8 data-[size=sm]:h-8 data-[placeholder]:text-muted-foreground *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:hover:bg-input/50 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0",
className
)}
data-size={size}
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
@@ -56,13 +57,13 @@ function SelectContent({
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
className={cn(
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=open]:animate-in',
position === 'popper' &&
'data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1',
className
)}
data-slot="select-content"
className={cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
)}
position={position}
{...props}
>
@@ -71,7 +72,7 @@ function SelectContent({
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1'
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',
)}
>
{children}
@@ -88,8 +89,8 @@ function SelectLabel({
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
className={cn('px-2 py-1.5 text-muted-foreground text-xs', className)}
data-slot="select-label"
className={cn('text-muted-foreground px-2 py-1.5 text-xs', className)}
{...props}
/>
);
@@ -102,11 +103,11 @@ function SelectItem({
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
className={cn(
"relative flex w-full cursor-default select-none items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
@@ -125,8 +126,8 @@ function SelectSeparator({
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
className={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}
data-slot="select-separator"
className={cn('bg-border pointer-events-none -mx-1 my-1 h-px', className)}
{...props}
/>
);
@@ -138,11 +139,11 @@ function SelectScrollUpButton({
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
'flex cursor-default items-center justify-center py-1',
className
className,
)}
data-slot="select-scroll-up-button"
{...props}
>
<ChevronUpIcon className="size-4" />
@@ -156,11 +157,11 @@ function SelectScrollDownButton({
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
'flex cursor-default items-center justify-center py-1',
className
className,
)}
data-slot="select-scroll-down-button"
{...props}
>
<ChevronDownIcon className="size-4" />

View File

@@ -54,19 +54,6 @@ export function WidgetBody({ children, className }: WidgetBodyProps) {
return <div className={cn('p-4', className)}>{children}</div>;
}
export interface WidgetEmptyStateProps {
icon: LucideIcon;
text: string;
}
export function WidgetEmptyState({ icon: Icon, text }: WidgetEmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center gap-2 py-8 text-muted-foreground">
<Icon size={28} strokeWidth={1.5} />
<p className="text-sm">{text}</p>
</div>
);
}
export interface WidgetProps {
children: React.ReactNode;
className?: string;

View File

@@ -1,229 +0,0 @@
import type { IChartEventFilter } from '@openpanel/validation';
import { parseAsInteger, parseAsString, useQueryState } from 'nuqs';
import { useCallback, useMemo } from 'react';
const DEBOUNCE_MS = 500;
const debounceOpts = {
clearOnDefault: true,
limitUrlUpdates: { method: 'debounce' as const, timeMs: DEBOUNCE_MS },
};
export function useSessionFilters() {
const [referrer, setReferrer] = useQueryState(
'referrer',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [country, setCountry] = useQueryState(
'country',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [os, setOs] = useQueryState(
'os',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [browser, setBrowser] = useQueryState(
'browser',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [device, setDevice] = useQueryState(
'device',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [entryPage, setEntryPage] = useQueryState(
'entryPage',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [exitPage, setExitPage] = useQueryState(
'exitPage',
parseAsString.withDefault('').withOptions(debounceOpts),
);
const [minPageViews, setMinPageViews] = useQueryState(
'minPageViews',
parseAsInteger,
);
const [maxPageViews, setMaxPageViews] = useQueryState(
'maxPageViews',
parseAsInteger,
);
const [minEvents, setMinEvents] = useQueryState('minEvents', parseAsInteger);
const [maxEvents, setMaxEvents] = useQueryState('maxEvents', parseAsInteger);
const filters = useMemo<IChartEventFilter[]>(() => {
const result: IChartEventFilter[] = [];
if (referrer) {
result.push({ name: 'referrer_name', operator: 'is', value: [referrer] });
}
if (country) {
result.push({ name: 'country', operator: 'is', value: [country] });
}
if (os) {
result.push({ name: 'os', operator: 'is', value: [os] });
}
if (browser) {
result.push({ name: 'browser', operator: 'is', value: [browser] });
}
if (device) {
result.push({ name: 'device', operator: 'is', value: [device] });
}
if (entryPage) {
result.push({
name: 'entry_path',
operator: 'contains',
value: [entryPage],
});
}
if (exitPage) {
result.push({
name: 'exit_path',
operator: 'contains',
value: [exitPage],
});
}
return result;
}, [referrer, country, os, browser, device, entryPage, exitPage]);
const values = useMemo(
() => ({
referrer,
country,
os,
browser,
device,
entryPage,
exitPage,
minPageViews,
maxPageViews,
minEvents,
maxEvents,
}),
[
referrer,
country,
os,
browser,
device,
entryPage,
exitPage,
minPageViews,
maxPageViews,
minEvents,
maxEvents,
],
);
const setValue = useCallback(
(key: string, value: string | number | null) => {
switch (key) {
case 'referrer':
setReferrer(String(value ?? ''));
break;
case 'country':
setCountry(String(value ?? ''));
break;
case 'os':
setOs(String(value ?? ''));
break;
case 'browser':
setBrowser(String(value ?? ''));
break;
case 'device':
setDevice(String(value ?? ''));
break;
case 'entryPage':
setEntryPage(String(value ?? ''));
break;
case 'exitPage':
setExitPage(String(value ?? ''));
break;
case 'minPageViews':
setMinPageViews(value != null ? Number(value) : null);
break;
case 'maxPageViews':
setMaxPageViews(value != null ? Number(value) : null);
break;
case 'minEvents':
setMinEvents(value != null ? Number(value) : null);
break;
case 'maxEvents':
setMaxEvents(value != null ? Number(value) : null);
break;
}
},
[
setReferrer,
setCountry,
setOs,
setBrowser,
setDevice,
setEntryPage,
setExitPage,
setMinPageViews,
setMaxPageViews,
setMinEvents,
setMaxEvents,
],
);
const activeCount =
filters.length +
(minPageViews != null ? 1 : 0) +
(maxPageViews != null ? 1 : 0) +
(minEvents != null ? 1 : 0) +
(maxEvents != null ? 1 : 0);
const clearAll = useCallback(() => {
setReferrer('');
setCountry('');
setOs('');
setBrowser('');
setDevice('');
setEntryPage('');
setExitPage('');
setMinPageViews(null);
setMaxPageViews(null);
setMinEvents(null);
setMaxEvents(null);
}, [
setReferrer,
setCountry,
setOs,
setBrowser,
setDevice,
setEntryPage,
setExitPage,
setMinPageViews,
setMaxPageViews,
setMinEvents,
setMaxEvents,
]);
return {
referrer,
setReferrer,
country,
setCountry,
os,
setOs,
browser,
setBrowser,
device,
setDevice,
entryPage,
setEntryPage,
exitPage,
setExitPage,
minPageViews,
setMinPageViews,
maxPageViews,
setMaxPageViews,
minEvents,
setMinEvents,
maxEvents,
setMaxEvents,
filters,
values,
setValue,
activeCount,
clearAll,
};
}

View File

@@ -1,139 +0,0 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { zCreateGroup } from '@openpanel/validation';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, Trash2Icon } from 'lucide-react';
import { useFieldArray, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
import { ButtonContainer } from '@/components/button-container';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/use-app-params';
import { handleError, useTRPC } from '@/integrations/trpc/react';
const zForm = zCreateGroup.omit({ projectId: true, properties: true }).extend({
properties: z.array(z.object({ key: z.string(), value: z.string() })),
});
type IForm = z.infer<typeof zForm>;
export default function AddGroup() {
const { projectId } = useAppParams();
const queryClient = useQueryClient();
const trpc = useTRPC();
const { register, handleSubmit, control, formState } = useForm<IForm>({
resolver: zodResolver(zForm),
defaultValues: {
id: '',
type: '',
name: '',
properties: [],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: 'properties',
});
const mutation = useMutation(
trpc.group.create.mutationOptions({
onSuccess() {
queryClient.invalidateQueries(trpc.group.list.pathFilter());
queryClient.invalidateQueries(trpc.group.types.pathFilter());
toast('Success', { description: 'Group created.' });
popModal();
},
onError: handleError,
})
);
return (
<ModalContent>
<ModalHeader title="Add group" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit(({ properties, ...values }) => {
const props = Object.fromEntries(
properties
.filter((p) => p.key.trim() !== '')
.map((p) => [p.key.trim(), String(p.value)])
);
mutation.mutate({ projectId, ...values, properties: props });
})}
>
<InputWithLabel
label="ID"
placeholder="acme-corp"
{...register('id')}
autoFocus
error={formState.errors.id?.message}
/>
<InputWithLabel
label="Name"
placeholder="Acme Corp"
{...register('name')}
error={formState.errors.name?.message}
/>
<InputWithLabel
label="Type"
placeholder="company"
{...register('type')}
error={formState.errors.type?.message}
/>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="font-medium text-sm">Properties</span>
<Button
onClick={() => append({ key: '', value: '' })}
size="sm"
type="button"
variant="outline"
>
<PlusIcon className="mr-1 size-3" />
Add
</Button>
</div>
{fields.map((field, index) => (
<div className="flex gap-2" key={field.id}>
<input
className="h-9 flex-1 rounded-md border bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
placeholder="key"
{...register(`properties.${index}.key`)}
/>
<input
className="h-9 flex-1 rounded-md border bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
placeholder="value"
{...register(`properties.${index}.value`)}
/>
<Button
className="shrink-0"
onClick={() => remove(index)}
size="icon"
type="button"
variant="ghost"
>
<Trash2Icon className="size-4" />
</Button>
</div>
))}
</div>
<ButtonContainer>
<Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
<Button
disabled={!formState.isDirty || mutation.isPending}
type="submit"
>
Create
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -1,147 +0,0 @@
import { zodResolver } from '@hookform/resolvers/zod';
import type { IServiceGroup } from '@openpanel/db';
import { zUpdateGroup } from '@openpanel/validation';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, Trash2Icon } from 'lucide-react';
import { useFieldArray, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
import { ButtonContainer } from '@/components/button-container';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { handleError, useTRPC } from '@/integrations/trpc/react';
const zForm = zUpdateGroup
.omit({ id: true, projectId: true, properties: true })
.extend({
properties: z.array(z.object({ key: z.string(), value: z.string() })),
});
type IForm = z.infer<typeof zForm>;
type EditGroupProps = Pick<
IServiceGroup,
'id' | 'projectId' | 'name' | 'type' | 'properties'
>;
export default function EditGroup({
id,
projectId,
name,
type,
properties,
}: EditGroupProps) {
const queryClient = useQueryClient();
const trpc = useTRPC();
const { register, handleSubmit, control, formState } = useForm<IForm>({
resolver: zodResolver(zForm),
defaultValues: {
type,
name,
properties: Object.entries(properties as Record<string, string>).map(
([key, value]) => ({
key,
value: String(value),
})
),
},
});
const { fields, append, remove } = useFieldArray({
control,
name: 'properties',
});
const mutation = useMutation(
trpc.group.update.mutationOptions({
onSuccess() {
queryClient.invalidateQueries(trpc.group.list.pathFilter());
queryClient.invalidateQueries(trpc.group.byId.pathFilter());
queryClient.invalidateQueries(trpc.group.types.pathFilter());
toast('Success', { description: 'Group updated.' });
popModal();
},
onError: handleError,
})
);
return (
<ModalContent>
<ModalHeader title="Edit group" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit(({ properties: formProps, ...values }) => {
const props = Object.fromEntries(
formProps
.filter((p) => p.key.trim() !== '')
.map((p) => [p.key.trim(), String(p.value)])
);
mutation.mutate({ id, projectId, ...values, properties: props });
})}
>
<InputWithLabel
label="Name"
{...register('name')}
error={formState.errors.name?.message}
/>
<InputWithLabel
label="Type"
{...register('type')}
error={formState.errors.type?.message}
/>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="font-medium text-sm">Properties</span>
<Button
onClick={() => append({ key: '', value: '' })}
size="sm"
type="button"
variant="outline"
>
<PlusIcon className="mr-1 size-3" />
Add
</Button>
</div>
{fields.map((field, index) => (
<div className="flex gap-2" key={field.id}>
<input
className="h-9 flex-1 rounded-md border bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
placeholder="key"
{...register(`properties.${index}.key`)}
/>
<input
className="h-9 flex-1 rounded-md border bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
placeholder="value"
{...register(`properties.${index}.value`)}
/>
<Button
className="shrink-0"
onClick={() => remove(index)}
size="icon"
type="button"
variant="ghost"
>
<Trash2Icon className="size-4" />
</Button>
</div>
))}
</div>
<ButtonContainer>
<Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
<Button
disabled={!formState.isDirty || mutation.isPending}
type="submit"
>
Update
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -1,7 +1,7 @@
import PageDetails from './page-details';
import { createPushModal } from 'pushmodal';
import AddClient from './add-client';
import AddDashboard from './add-dashboard';
import AddGroup from './add-group';
import AddImport from './add-import';
import AddIntegration from './add-integration';
import AddNotificationRule from './add-notification-rule';
@@ -16,7 +16,6 @@ import DateTimePicker from './date-time-picker';
import EditClient from './edit-client';
import EditDashboard from './edit-dashboard';
import EditEvent from './edit-event';
import EditGroup from './edit-group';
import EditMember from './edit-member';
import EditReference from './edit-reference';
import EditReport from './edit-report';
@@ -24,7 +23,6 @@ import EventDetails from './event-details';
import Instructions from './Instructions';
import OverviewChartDetails from './overview-chart-details';
import OverviewFilters from './overview-filters';
import PageDetails from './page-details';
import RequestPasswordReset from './request-reset-password';
import SaveReport from './save-report';
import SelectBillingPlan from './select-billing-plan';
@@ -38,8 +36,6 @@ import { op } from '@/utils/op';
const modals = {
PageDetails,
AddGroup,
EditGroup,
OverviewTopPagesModal,
OverviewTopGenericModal,
RequestPasswordReset,

View File

@@ -281,10 +281,9 @@ function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
interface FunnelUsersViewProps {
report: IReportInput;
stepIndex: number;
breakdownValues?: string[];
}
function FunnelUsersView({ report, stepIndex, breakdownValues }: FunnelUsersViewProps) {
function FunnelUsersView({ report, stepIndex }: FunnelUsersViewProps) {
const trpc = useTRPC();
const [showDropoffs, setShowDropoffs] = useState(false);
@@ -307,7 +306,6 @@ function FunnelUsersView({ report, stepIndex, breakdownValues }: FunnelUsersView
? report.options.funnelGroup
: undefined,
breakdowns: report.breakdowns,
breakdownValues: breakdownValues,
},
{
enabled: stepIndex !== undefined,
@@ -386,14 +384,13 @@ type ViewChartUsersProps =
type: 'funnel';
report: IReportInput;
stepIndex: number;
breakdownValues?: string[];
};
// Main component that routes to the appropriate view
export default function ViewChartUsers(props: ViewChartUsersProps) {
if (props.type === 'funnel') {
return (
<FunnelUsersView report={props.report} stepIndex={props.stepIndex} breakdownValues={props.breakdownValues} />
<FunnelUsersView report={props.report} stepIndex={props.stepIndex} />
);
}

View File

@@ -48,7 +48,6 @@ import { Route as AppOrganizationIdProjectIdReferencesRouteImport } from './rout
import { Route as AppOrganizationIdProjectIdRealtimeRouteImport } from './routes/_app.$organizationId.$projectId.realtime'
import { Route as AppOrganizationIdProjectIdPagesRouteImport } from './routes/_app.$organizationId.$projectId.pages'
import { Route as AppOrganizationIdProjectIdInsightsRouteImport } from './routes/_app.$organizationId.$projectId.insights'
import { Route as AppOrganizationIdProjectIdGroupsRouteImport } from './routes/_app.$organizationId.$projectId.groups'
import { Route as AppOrganizationIdProjectIdDashboardsRouteImport } from './routes/_app.$organizationId.$projectId.dashboards'
import { Route as AppOrganizationIdProjectIdChatRouteImport } from './routes/_app.$organizationId.$projectId.chat'
import { Route as AppOrganizationIdProfileTabsIndexRouteImport } from './routes/_app.$organizationId.profile._tabs.index'
@@ -83,16 +82,12 @@ import { Route as AppOrganizationIdProjectIdProfilesTabsAnonymousRouteImport } f
import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs'
import { Route as AppOrganizationIdProjectIdNotificationsTabsRulesRouteImport } from './routes/_app.$organizationId.$projectId.notifications._tabs.rules'
import { Route as AppOrganizationIdProjectIdNotificationsTabsNotificationsRouteImport } from './routes/_app.$organizationId.$projectId.notifications._tabs.notifications'
import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs'
import { Route as AppOrganizationIdProjectIdEventsTabsStatsRouteImport } from './routes/_app.$organizationId.$projectId.events._tabs.stats'
import { Route as AppOrganizationIdProjectIdEventsTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.events._tabs.events'
import { Route as AppOrganizationIdProjectIdEventsTabsConversionsRouteImport } from './routes/_app.$organizationId.$projectId.events._tabs.conversions'
import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.index'
import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.index'
import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.sessions'
import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.events'
import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.members'
import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.events'
const AppOrganizationIdProfileRouteImport = createFileRoute(
'/_app/$organizationId/profile',
@@ -118,9 +113,6 @@ const AppOrganizationIdProjectIdEventsRouteImport = createFileRoute(
const AppOrganizationIdProjectIdProfilesProfileIdRouteImport = createFileRoute(
'/_app/$organizationId/$projectId/profiles/$profileId',
)()
const AppOrganizationIdProjectIdGroupsGroupIdRouteImport = createFileRoute(
'/_app/$organizationId/$projectId/groups_/$groupId',
)()
const UnsubscribeRoute = UnsubscribeRouteImport.update({
id: '/unsubscribe',
@@ -358,12 +350,6 @@ const AppOrganizationIdProjectIdInsightsRoute =
path: '/insights',
getParentRoute: () => AppOrganizationIdProjectIdRoute,
} as any)
const AppOrganizationIdProjectIdGroupsRoute =
AppOrganizationIdProjectIdGroupsRouteImport.update({
id: '/groups',
path: '/groups',
getParentRoute: () => AppOrganizationIdProjectIdRoute,
} as any)
const AppOrganizationIdProjectIdDashboardsRoute =
AppOrganizationIdProjectIdDashboardsRouteImport.update({
id: '/dashboards',
@@ -382,12 +368,6 @@ const AppOrganizationIdProjectIdProfilesProfileIdRoute =
path: '/$profileId',
getParentRoute: () => AppOrganizationIdProjectIdProfilesRoute,
} as any)
const AppOrganizationIdProjectIdGroupsGroupIdRoute =
AppOrganizationIdProjectIdGroupsGroupIdRouteImport.update({
id: '/groups_/$groupId',
path: '/groups/$groupId',
getParentRoute: () => AppOrganizationIdProjectIdRoute,
} as any)
const AppOrganizationIdProfileTabsIndexRoute =
AppOrganizationIdProfileTabsIndexRouteImport.update({
id: '/',
@@ -575,11 +555,6 @@ const AppOrganizationIdProjectIdNotificationsTabsNotificationsRoute =
path: '/notifications',
getParentRoute: () => AppOrganizationIdProjectIdNotificationsTabsRoute,
} as any)
const AppOrganizationIdProjectIdGroupsGroupIdTabsRoute =
AppOrganizationIdProjectIdGroupsGroupIdTabsRouteImport.update({
id: '/_tabs',
getParentRoute: () => AppOrganizationIdProjectIdGroupsGroupIdRoute,
} as any)
const AppOrganizationIdProjectIdEventsTabsStatsRoute =
AppOrganizationIdProjectIdEventsTabsStatsRouteImport.update({
id: '/stats',
@@ -604,12 +579,6 @@ const AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute =
path: '/',
getParentRoute: () => AppOrganizationIdProjectIdProfilesProfileIdTabsRoute,
} as any)
const AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute =
AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => AppOrganizationIdProjectIdGroupsGroupIdTabsRoute,
} as any)
const AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute =
AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRouteImport.update({
id: '/sessions',
@@ -622,18 +591,6 @@ const AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute =
path: '/events',
getParentRoute: () => AppOrganizationIdProjectIdProfilesProfileIdTabsRoute,
} as any)
const AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute =
AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRouteImport.update({
id: '/members',
path: '/members',
getParentRoute: () => AppOrganizationIdProjectIdGroupsGroupIdTabsRoute,
} as any)
const AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute =
AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRouteImport.update({
id: '/events',
path: '/events',
getParentRoute: () => AppOrganizationIdProjectIdGroupsGroupIdTabsRoute,
} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
@@ -658,7 +615,6 @@ export interface FileRoutesByFullPath {
'/$organizationId/': typeof AppOrganizationIdIndexRoute
'/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute
'/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute
'/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute
'/$organizationId/$projectId/insights': typeof AppOrganizationIdProjectIdInsightsRoute
'/$organizationId/$projectId/pages': typeof AppOrganizationIdProjectIdPagesRoute
'/$organizationId/$projectId/realtime': typeof AppOrganizationIdProjectIdRealtimeRoute
@@ -690,7 +646,6 @@ export interface FileRoutesByFullPath {
'/$organizationId/$projectId/events/conversions': typeof AppOrganizationIdProjectIdEventsTabsConversionsRoute
'/$organizationId/$projectId/events/events': typeof AppOrganizationIdProjectIdEventsTabsEventsRoute
'/$organizationId/$projectId/events/stats': typeof AppOrganizationIdProjectIdEventsTabsStatsRoute
'/$organizationId/$projectId/groups/$groupId': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRouteWithChildren
'/$organizationId/$projectId/notifications/notifications': typeof AppOrganizationIdProjectIdNotificationsTabsNotificationsRoute
'/$organizationId/$projectId/notifications/rules': typeof AppOrganizationIdProjectIdNotificationsTabsRulesRoute
'/$organizationId/$projectId/profiles/$profileId': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsRouteWithChildren
@@ -708,11 +663,8 @@ export interface FileRoutesByFullPath {
'/$organizationId/$projectId/notifications/': typeof AppOrganizationIdProjectIdNotificationsTabsIndexRoute
'/$organizationId/$projectId/profiles/': typeof AppOrganizationIdProjectIdProfilesTabsIndexRoute
'/$organizationId/$projectId/settings/': typeof AppOrganizationIdProjectIdSettingsTabsIndexRoute
'/$organizationId/$projectId/groups/$groupId/events': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute
'/$organizationId/$projectId/groups/$groupId/members': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute
'/$organizationId/$projectId/profiles/$profileId/events': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute
'/$organizationId/$projectId/profiles/$profileId/sessions': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute
'/$organizationId/$projectId/groups/$groupId/': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute
'/$organizationId/$projectId/profiles/$profileId/': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute
}
export interface FileRoutesByTo {
@@ -736,7 +688,6 @@ export interface FileRoutesByTo {
'/$organizationId': typeof AppOrganizationIdIndexRoute
'/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute
'/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute
'/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute
'/$organizationId/$projectId/insights': typeof AppOrganizationIdProjectIdInsightsRoute
'/$organizationId/$projectId/pages': typeof AppOrganizationIdProjectIdPagesRoute
'/$organizationId/$projectId/realtime': typeof AppOrganizationIdProjectIdRealtimeRoute
@@ -765,7 +716,6 @@ export interface FileRoutesByTo {
'/$organizationId/$projectId/events/conversions': typeof AppOrganizationIdProjectIdEventsTabsConversionsRoute
'/$organizationId/$projectId/events/events': typeof AppOrganizationIdProjectIdEventsTabsEventsRoute
'/$organizationId/$projectId/events/stats': typeof AppOrganizationIdProjectIdEventsTabsStatsRoute
'/$organizationId/$projectId/groups/$groupId': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute
'/$organizationId/$projectId/notifications/notifications': typeof AppOrganizationIdProjectIdNotificationsTabsNotificationsRoute
'/$organizationId/$projectId/notifications/rules': typeof AppOrganizationIdProjectIdNotificationsTabsRulesRoute
'/$organizationId/$projectId/profiles/$profileId': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute
@@ -779,8 +729,6 @@ export interface FileRoutesByTo {
'/$organizationId/$projectId/settings/imports': typeof AppOrganizationIdProjectIdSettingsTabsImportsRoute
'/$organizationId/$projectId/settings/tracking': typeof AppOrganizationIdProjectIdSettingsTabsTrackingRoute
'/$organizationId/$projectId/settings/widgets': typeof AppOrganizationIdProjectIdSettingsTabsWidgetsRoute
'/$organizationId/$projectId/groups/$groupId/events': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute
'/$organizationId/$projectId/groups/$groupId/members': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute
'/$organizationId/$projectId/profiles/$profileId/events': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute
'/$organizationId/$projectId/profiles/$profileId/sessions': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute
}
@@ -812,7 +760,6 @@ export interface FileRoutesById {
'/_app/$organizationId/': typeof AppOrganizationIdIndexRoute
'/_app/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute
'/_app/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute
'/_app/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute
'/_app/$organizationId/$projectId/insights': typeof AppOrganizationIdProjectIdInsightsRoute
'/_app/$organizationId/$projectId/pages': typeof AppOrganizationIdProjectIdPagesRoute
'/_app/$organizationId/$projectId/realtime': typeof AppOrganizationIdProjectIdRealtimeRoute
@@ -851,8 +798,6 @@ export interface FileRoutesById {
'/_app/$organizationId/$projectId/events/_tabs/conversions': typeof AppOrganizationIdProjectIdEventsTabsConversionsRoute
'/_app/$organizationId/$projectId/events/_tabs/events': typeof AppOrganizationIdProjectIdEventsTabsEventsRoute
'/_app/$organizationId/$projectId/events/_tabs/stats': typeof AppOrganizationIdProjectIdEventsTabsStatsRoute
'/_app/$organizationId/$projectId/groups_/$groupId': typeof AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRouteWithChildren
'/_app/$organizationId/$projectId/notifications/_tabs/notifications': typeof AppOrganizationIdProjectIdNotificationsTabsNotificationsRoute
'/_app/$organizationId/$projectId/notifications/_tabs/rules': typeof AppOrganizationIdProjectIdNotificationsTabsRulesRoute
'/_app/$organizationId/$projectId/profiles/$profileId': typeof AppOrganizationIdProjectIdProfilesProfileIdRouteWithChildren
@@ -871,11 +816,8 @@ export interface FileRoutesById {
'/_app/$organizationId/$projectId/notifications/_tabs/': typeof AppOrganizationIdProjectIdNotificationsTabsIndexRoute
'/_app/$organizationId/$projectId/profiles/_tabs/': typeof AppOrganizationIdProjectIdProfilesTabsIndexRoute
'/_app/$organizationId/$projectId/settings/_tabs/': typeof AppOrganizationIdProjectIdSettingsTabsIndexRoute
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute
'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/events': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute
'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute
'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute
}
export interface FileRouteTypes {
@@ -903,7 +845,6 @@ export interface FileRouteTypes {
| '/$organizationId/'
| '/$organizationId/$projectId/chat'
| '/$organizationId/$projectId/dashboards'
| '/$organizationId/$projectId/groups'
| '/$organizationId/$projectId/insights'
| '/$organizationId/$projectId/pages'
| '/$organizationId/$projectId/realtime'
@@ -935,7 +876,6 @@ export interface FileRouteTypes {
| '/$organizationId/$projectId/events/conversions'
| '/$organizationId/$projectId/events/events'
| '/$organizationId/$projectId/events/stats'
| '/$organizationId/$projectId/groups/$groupId'
| '/$organizationId/$projectId/notifications/notifications'
| '/$organizationId/$projectId/notifications/rules'
| '/$organizationId/$projectId/profiles/$profileId'
@@ -953,11 +893,8 @@ export interface FileRouteTypes {
| '/$organizationId/$projectId/notifications/'
| '/$organizationId/$projectId/profiles/'
| '/$organizationId/$projectId/settings/'
| '/$organizationId/$projectId/groups/$groupId/events'
| '/$organizationId/$projectId/groups/$groupId/members'
| '/$organizationId/$projectId/profiles/$profileId/events'
| '/$organizationId/$projectId/profiles/$profileId/sessions'
| '/$organizationId/$projectId/groups/$groupId/'
| '/$organizationId/$projectId/profiles/$profileId/'
fileRoutesByTo: FileRoutesByTo
to:
@@ -981,7 +918,6 @@ export interface FileRouteTypes {
| '/$organizationId'
| '/$organizationId/$projectId/chat'
| '/$organizationId/$projectId/dashboards'
| '/$organizationId/$projectId/groups'
| '/$organizationId/$projectId/insights'
| '/$organizationId/$projectId/pages'
| '/$organizationId/$projectId/realtime'
@@ -1010,7 +946,6 @@ export interface FileRouteTypes {
| '/$organizationId/$projectId/events/conversions'
| '/$organizationId/$projectId/events/events'
| '/$organizationId/$projectId/events/stats'
| '/$organizationId/$projectId/groups/$groupId'
| '/$organizationId/$projectId/notifications/notifications'
| '/$organizationId/$projectId/notifications/rules'
| '/$organizationId/$projectId/profiles/$profileId'
@@ -1024,8 +959,6 @@ export interface FileRouteTypes {
| '/$organizationId/$projectId/settings/imports'
| '/$organizationId/$projectId/settings/tracking'
| '/$organizationId/$projectId/settings/widgets'
| '/$organizationId/$projectId/groups/$groupId/events'
| '/$organizationId/$projectId/groups/$groupId/members'
| '/$organizationId/$projectId/profiles/$profileId/events'
| '/$organizationId/$projectId/profiles/$profileId/sessions'
id:
@@ -1056,7 +989,6 @@ export interface FileRouteTypes {
| '/_app/$organizationId/'
| '/_app/$organizationId/$projectId/chat'
| '/_app/$organizationId/$projectId/dashboards'
| '/_app/$organizationId/$projectId/groups'
| '/_app/$organizationId/$projectId/insights'
| '/_app/$organizationId/$projectId/pages'
| '/_app/$organizationId/$projectId/realtime'
@@ -1095,8 +1027,6 @@ export interface FileRouteTypes {
| '/_app/$organizationId/$projectId/events/_tabs/conversions'
| '/_app/$organizationId/$projectId/events/_tabs/events'
| '/_app/$organizationId/$projectId/events/_tabs/stats'
| '/_app/$organizationId/$projectId/groups_/$groupId'
| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs'
| '/_app/$organizationId/$projectId/notifications/_tabs/notifications'
| '/_app/$organizationId/$projectId/notifications/_tabs/rules'
| '/_app/$organizationId/$projectId/profiles/$profileId'
@@ -1115,11 +1045,8 @@ export interface FileRouteTypes {
| '/_app/$organizationId/$projectId/notifications/_tabs/'
| '/_app/$organizationId/$projectId/profiles/_tabs/'
| '/_app/$organizationId/$projectId/settings/_tabs/'
| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events'
| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members'
| '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/events'
| '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions'
| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/'
| '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/'
fileRoutesById: FileRoutesById
}
@@ -1451,13 +1378,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppOrganizationIdProjectIdInsightsRouteImport
parentRoute: typeof AppOrganizationIdProjectIdRoute
}
'/_app/$organizationId/$projectId/groups': {
id: '/_app/$organizationId/$projectId/groups'
path: '/groups'
fullPath: '/$organizationId/$projectId/groups'
preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsRouteImport
parentRoute: typeof AppOrganizationIdProjectIdRoute
}
'/_app/$organizationId/$projectId/dashboards': {
id: '/_app/$organizationId/$projectId/dashboards'
path: '/dashboards'
@@ -1479,13 +1399,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppOrganizationIdProjectIdProfilesProfileIdRouteImport
parentRoute: typeof AppOrganizationIdProjectIdProfilesRoute
}
'/_app/$organizationId/$projectId/groups_/$groupId': {
id: '/_app/$organizationId/$projectId/groups_/$groupId'
path: '/groups/$groupId'
fullPath: '/$organizationId/$projectId/groups/$groupId'
preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdRouteImport
parentRoute: typeof AppOrganizationIdProjectIdRoute
}
'/_app/$organizationId/profile/_tabs/': {
id: '/_app/$organizationId/profile/_tabs/'
path: '/'
@@ -1710,13 +1623,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppOrganizationIdProjectIdNotificationsTabsNotificationsRouteImport
parentRoute: typeof AppOrganizationIdProjectIdNotificationsTabsRoute
}
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs': {
id: '/_app/$organizationId/$projectId/groups_/$groupId/_tabs'
path: '/groups/$groupId'
fullPath: '/$organizationId/$projectId/groups/$groupId'
preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRouteImport
parentRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdRoute
}
'/_app/$organizationId/$projectId/events/_tabs/stats': {
id: '/_app/$organizationId/$projectId/events/_tabs/stats'
path: '/stats'
@@ -1745,13 +1651,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRouteImport
parentRoute: typeof AppOrganizationIdProjectIdProfilesProfileIdTabsRoute
}
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/': {
id: '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/'
path: '/'
fullPath: '/$organizationId/$projectId/groups/$groupId/'
preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRouteImport
parentRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRoute
}
'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions': {
id: '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions'
path: '/sessions'
@@ -1766,20 +1665,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRouteImport
parentRoute: typeof AppOrganizationIdProjectIdProfilesProfileIdTabsRoute
}
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members': {
id: '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members'
path: '/members'
fullPath: '/$organizationId/$projectId/groups/$groupId/members'
preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRouteImport
parentRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRoute
}
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events': {
id: '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events'
path: '/events'
fullPath: '/$organizationId/$projectId/groups/$groupId/events'
preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRouteImport
parentRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRoute
}
}
}
@@ -1987,46 +1872,9 @@ const AppOrganizationIdProjectIdSettingsRouteWithChildren =
AppOrganizationIdProjectIdSettingsRouteChildren,
)
interface AppOrganizationIdProjectIdGroupsGroupIdTabsRouteChildren {
AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute
AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute
AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute
}
const AppOrganizationIdProjectIdGroupsGroupIdTabsRouteChildren: AppOrganizationIdProjectIdGroupsGroupIdTabsRouteChildren =
{
AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute:
AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute,
AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute:
AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute,
AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute:
AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute,
}
const AppOrganizationIdProjectIdGroupsGroupIdTabsRouteWithChildren =
AppOrganizationIdProjectIdGroupsGroupIdTabsRoute._addFileChildren(
AppOrganizationIdProjectIdGroupsGroupIdTabsRouteChildren,
)
interface AppOrganizationIdProjectIdGroupsGroupIdRouteChildren {
AppOrganizationIdProjectIdGroupsGroupIdTabsRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRouteWithChildren
}
const AppOrganizationIdProjectIdGroupsGroupIdRouteChildren: AppOrganizationIdProjectIdGroupsGroupIdRouteChildren =
{
AppOrganizationIdProjectIdGroupsGroupIdTabsRoute:
AppOrganizationIdProjectIdGroupsGroupIdTabsRouteWithChildren,
}
const AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren =
AppOrganizationIdProjectIdGroupsGroupIdRoute._addFileChildren(
AppOrganizationIdProjectIdGroupsGroupIdRouteChildren,
)
interface AppOrganizationIdProjectIdRouteChildren {
AppOrganizationIdProjectIdChatRoute: typeof AppOrganizationIdProjectIdChatRoute
AppOrganizationIdProjectIdDashboardsRoute: typeof AppOrganizationIdProjectIdDashboardsRoute
AppOrganizationIdProjectIdGroupsRoute: typeof AppOrganizationIdProjectIdGroupsRoute
AppOrganizationIdProjectIdInsightsRoute: typeof AppOrganizationIdProjectIdInsightsRoute
AppOrganizationIdProjectIdPagesRoute: typeof AppOrganizationIdProjectIdPagesRoute
AppOrganizationIdProjectIdRealtimeRoute: typeof AppOrganizationIdProjectIdRealtimeRoute
@@ -2042,7 +1890,6 @@ interface AppOrganizationIdProjectIdRouteChildren {
AppOrganizationIdProjectIdReportsReportIdRoute: typeof AppOrganizationIdProjectIdReportsReportIdRoute
AppOrganizationIdProjectIdSessionsSessionIdRoute: typeof AppOrganizationIdProjectIdSessionsSessionIdRoute
AppOrganizationIdProjectIdSettingsRoute: typeof AppOrganizationIdProjectIdSettingsRouteWithChildren
AppOrganizationIdProjectIdGroupsGroupIdRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren
}
const AppOrganizationIdProjectIdRouteChildren: AppOrganizationIdProjectIdRouteChildren =
@@ -2050,8 +1897,6 @@ const AppOrganizationIdProjectIdRouteChildren: AppOrganizationIdProjectIdRouteCh
AppOrganizationIdProjectIdChatRoute: AppOrganizationIdProjectIdChatRoute,
AppOrganizationIdProjectIdDashboardsRoute:
AppOrganizationIdProjectIdDashboardsRoute,
AppOrganizationIdProjectIdGroupsRoute:
AppOrganizationIdProjectIdGroupsRoute,
AppOrganizationIdProjectIdInsightsRoute:
AppOrganizationIdProjectIdInsightsRoute,
AppOrganizationIdProjectIdPagesRoute: AppOrganizationIdProjectIdPagesRoute,
@@ -2079,8 +1924,6 @@ const AppOrganizationIdProjectIdRouteChildren: AppOrganizationIdProjectIdRouteCh
AppOrganizationIdProjectIdSessionsSessionIdRoute,
AppOrganizationIdProjectIdSettingsRoute:
AppOrganizationIdProjectIdSettingsRouteWithChildren,
AppOrganizationIdProjectIdGroupsGroupIdRoute:
AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren,
}
const AppOrganizationIdProjectIdRouteWithChildren =

View File

@@ -42,5 +42,5 @@ function Component() {
),
);
return <EventsTable query={query} showEventListener />;
return <EventsTable query={query} />;
}

View File

@@ -1,100 +0,0 @@
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { PlusIcon } from 'lucide-react';
import { parseAsString, useQueryState } from 'nuqs';
import { GroupsTable } from '@/components/groups/table';
import { PageContainer } from '@/components/page-container';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { useDataTablePagination } from '@/components/ui/data-table/data-table-hooks';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
import { useTRPC } from '@/integrations/trpc/react';
import { pushModal } from '@/modals';
import { createProjectTitle } from '@/utils/title';
const PAGE_SIZE = 50;
export const Route = createFileRoute('/_app/$organizationId/$projectId/groups')(
{
component: Component,
head: () => ({
meta: [{ title: createProjectTitle('Groups') }],
}),
}
);
function Component() {
const { projectId } = Route.useParams();
const trpc = useTRPC();
const { debouncedSearch } = useSearchQueryState();
const [typeFilter, setTypeFilter] = useQueryState(
'type',
parseAsString.withDefault('')
);
const { page } = useDataTablePagination(PAGE_SIZE);
const typesQuery = useQuery(trpc.group.types.queryOptions({ projectId }));
const groupsQuery = useQuery(
trpc.group.list.queryOptions(
{
projectId,
search: debouncedSearch || undefined,
type: typeFilter || undefined,
take: PAGE_SIZE,
cursor: (page - 1) * PAGE_SIZE,
},
{ placeholderData: keepPreviousData }
)
);
const types = typesQuery.data ?? [];
return (
<PageContainer>
<PageHeader
actions={
<Button onClick={() => pushModal('AddGroup')}>
<PlusIcon className="mr-2 size-4" />
Add group
</Button>
}
className="mb-8"
description="Groups represent companies, teams, or other entities that events belong to."
title="Groups"
/>
<GroupsTable
pageSize={PAGE_SIZE}
query={groupsQuery}
toolbarLeft={
types.length > 0 ? (
<Select
onValueChange={(v) => setTypeFilter(v === 'all' ? '' : v)}
value={typeFilter || 'all'}
>
<SelectTrigger className="w-40">
<SelectValue placeholder="All types" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All types</SelectItem>
{types.map((t) => (
<SelectItem key={t} value={t}>
{t}
</SelectItem>
))}
</SelectContent>
</Select>
) : null
}
/>
</PageContainer>
);
}

View File

@@ -1,46 +0,0 @@
import { EventsTable } from '@/components/events/table';
import { useReadColumnVisibility } from '@/components/ui/data-table/data-table-hooks';
import { useEventQueryNamesFilter } from '@/hooks/use-event-query-filters';
import { useTRPC } from '@/integrations/trpc/react';
import { createProjectTitle } from '@/utils/title';
import { useInfiniteQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { parseAsIsoDateTime, useQueryState } from 'nuqs';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events'
)({
component: Component,
head: () => ({
meta: [{ title: createProjectTitle('Group events') }],
}),
});
function Component() {
const { projectId, groupId } = Route.useParams();
const trpc = useTRPC();
const [startDate] = useQueryState('startDate', parseAsIsoDateTime);
const [endDate] = useQueryState('endDate', parseAsIsoDateTime);
const [eventNames] = useEventQueryNamesFilter();
const columnVisibility = useReadColumnVisibility('events');
const query = useInfiniteQuery(
trpc.event.events.infiniteQueryOptions(
{
projectId,
groupId,
filters: [], // Always scope to group only; date + event names from toolbar still apply
startDate: startDate || undefined,
endDate: endDate || undefined,
events: eventNames,
columnVisibility: columnVisibility ?? {},
},
{
enabled: columnVisibility !== null,
getNextPageParam: (lastPage) => lastPage.meta.next,
}
)
);
return <EventsTable query={query} />;
}

View File

@@ -1,233 +0,0 @@
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, Link } from '@tanstack/react-router';
import { UsersIcon } from 'lucide-react';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { GroupMemberGrowth } from '@/components/groups/group-member-growth';
import { OverviewMetricCard } from '@/components/overview/overview-metric-card';
import { WidgetHead, WidgetTitle } from '@/components/overview/overview-widget';
import { MostEvents } from '@/components/profiles/most-events';
import { PopularRoutes } from '@/components/profiles/popular-routes';
import { ProfileActivity } from '@/components/profiles/profile-activity';
import { KeyValueGrid } from '@/components/ui/key-value-grid';
import { Widget, WidgetBody, WidgetEmptyState } from '@/components/widget';
import { WidgetTable } from '@/components/widget-table';
import { useTRPC } from '@/integrations/trpc/react';
import { formatDateTime, formatTimeAgoOrDateTime } from '@/utils/date';
import { createProjectTitle } from '@/utils/title';
const MEMBERS_PREVIEW_LIMIT = 13;
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/'
)({
component: Component,
loader: async ({ context, params }) => {
await Promise.all([
context.queryClient.prefetchQuery(
context.trpc.group.activity.queryOptions({
id: params.groupId,
projectId: params.projectId,
})
),
]);
},
pendingComponent: FullPageLoadingState,
head: () => ({
meta: [{ title: createProjectTitle('Group') }],
}),
});
function Component() {
const { projectId, organizationId, groupId } = Route.useParams();
const trpc = useTRPC();
const group = useSuspenseQuery(
trpc.group.byId.queryOptions({ id: groupId, projectId })
);
const metrics = useSuspenseQuery(
trpc.group.metrics.queryOptions({ id: groupId, projectId })
);
const activity = useSuspenseQuery(
trpc.group.activity.queryOptions({ id: groupId, projectId })
);
const members = useSuspenseQuery(
trpc.group.members.queryOptions({ id: groupId, projectId })
);
const mostEvents = useSuspenseQuery(
trpc.group.mostEvents.queryOptions({ id: groupId, projectId })
);
const popularRoutes = useSuspenseQuery(
trpc.group.popularRoutes.queryOptions({ id: groupId, projectId })
);
const memberGrowth = useSuspenseQuery(
trpc.group.memberGrowth.queryOptions({ id: groupId, projectId })
);
const g = group.data;
const m = metrics.data;
if (!g) {
return null;
}
const properties = g.properties as Record<string, unknown>;
return (
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
{/* Metrics */}
{m && (
<div className="col-span-1 md:col-span-2">
<div className="card grid grid-cols-2 overflow-hidden rounded-md md:grid-cols-4">
<OverviewMetricCard
data={[]}
id="totalEvents"
isLoading={false}
label="Total Events"
metric={{ current: m.totalEvents, previous: null }}
unit=""
/>
<OverviewMetricCard
data={[]}
id="uniqueMembers"
isLoading={false}
label="Unique Members"
metric={{ current: m.uniqueProfiles, previous: null }}
unit=""
/>
<OverviewMetricCard
data={[]}
id="firstSeen"
isLoading={false}
label="First Seen"
metric={{
current: m.firstSeen ? new Date(m.firstSeen).getTime() : 0,
previous: null,
}}
unit="timeAgo"
/>
<OverviewMetricCard
data={[]}
id="lastSeen"
isLoading={false}
label="Last Seen"
metric={{
current: m.lastSeen ? new Date(m.lastSeen).getTime() : 0,
previous: null,
}}
unit="timeAgo"
/>
</div>
</div>
)}
{/* Properties */}
<div className="col-span-1 md:col-span-2">
<Widget className="w-full">
<WidgetHead>
<div className="title">Group Information</div>
</WidgetHead>
<KeyValueGrid
className="border-0"
columns={3}
copyable
data={[
{ name: 'id', value: g.id },
{ name: 'name', value: g.name },
{ name: 'type', value: g.type },
{
name: 'createdAt',
value: formatDateTime(new Date(g.createdAt)),
},
...Object.entries(properties)
.filter(([, v]) => v !== undefined && v !== '')
.map(([k, v]) => ({
name: k,
value: String(v),
})),
]}
/>
</Widget>
</div>
{/* Activity heatmap */}
<div className="col-span-1">
<ProfileActivity data={activity.data} />
</div>
{/* Member growth */}
<div className="col-span-1">
<GroupMemberGrowth data={memberGrowth.data} />
</div>
{/* Top events */}
<div className="col-span-1">
<MostEvents data={mostEvents.data} />
</div>
{/* Popular routes */}
<div className="col-span-1">
<PopularRoutes data={popularRoutes.data} />
</div>
{/* Members preview */}
<div className="col-span-1 md:col-span-2">
<Widget className="w-full">
<WidgetHead>
<WidgetTitle icon={UsersIcon}>Members</WidgetTitle>
</WidgetHead>
<WidgetBody className="p-0">
{members.data.length === 0 ? (
<WidgetEmptyState icon={UsersIcon} text="No members yet" />
) : (
<WidgetTable
columnClassName="px-2"
columns={[
{
key: 'profile',
name: 'Profile',
width: 'w-full',
render: (member) => (
<Link
className="font-mono text-xs hover:underline"
params={{
organizationId,
projectId,
profileId: member.profileId,
}}
to="/$organizationId/$projectId/profiles/$profileId"
>
{member.profileId}
</Link>
),
},
{
key: 'events',
name: 'Events',
width: '60px',
className: 'text-muted-foreground',
render: (member) => member.eventCount,
},
{
key: 'lastSeen',
name: 'Last Seen',
width: '150px',
className: 'text-muted-foreground',
render: (member) =>
formatTimeAgoOrDateTime(new Date(member.lastSeen)),
},
]}
data={members.data.slice(0, MEMBERS_PREVIEW_LIMIT)}
keyExtractor={(member) => member.profileId}
/>
)}
{members.data.length > MEMBERS_PREVIEW_LIMIT && (
<p className="border-t py-2 text-center text-muted-foreground text-xs">
{`${members.data.length} members found. View all in Members tab`}
</p>
)}
</WidgetBody>
</Widget>
</div>
</div>
);
}

View File

@@ -1,42 +0,0 @@
import { ProfilesTable } from '@/components/profiles/table';
import { useDataTablePagination } from '@/components/ui/data-table/data-table-hooks';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
import { useTRPC } from '@/integrations/trpc/react';
import { createProjectTitle } from '@/utils/title';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members'
)({
component: Component,
head: () => ({
meta: [{ title: createProjectTitle('Group members') }],
}),
});
function Component() {
const { projectId, groupId } = Route.useParams();
const trpc = useTRPC();
const { debouncedSearch } = useSearchQueryState();
const { page } = useDataTablePagination(50);
const query = useQuery({
...trpc.group.listProfiles.queryOptions({
projectId,
groupId,
cursor: (page - 1) * 50,
take: 50,
search: debouncedSearch || undefined,
}),
placeholderData: keepPreviousData,
});
return (
<ProfilesTable
pageSize={50}
query={query as Parameters<typeof ProfilesTable>[0]['query']}
type="profiles"
/>
);
}

View File

@@ -1,161 +0,0 @@
import {
useMutation,
useQueryClient,
useSuspenseQuery,
} from '@tanstack/react-query';
import {
createFileRoute,
Outlet,
useNavigate,
useRouter,
} from '@tanstack/react-router';
import { Building2Icon, PencilIcon, Trash2Icon } from 'lucide-react';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { PageContainer } from '@/components/page-container';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { usePageTabs } from '@/hooks/use-page-tabs';
import { handleError, useTRPC } from '@/integrations/trpc/react';
import { pushModal, showConfirm } from '@/modals';
import { createProjectTitle } from '@/utils/title';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/groups_/$groupId/_tabs'
)({
component: Component,
loader: async ({ context, params }) => {
await Promise.all([
context.queryClient.prefetchQuery(
context.trpc.group.byId.queryOptions({
id: params.groupId,
projectId: params.projectId,
})
),
context.queryClient.prefetchQuery(
context.trpc.group.metrics.queryOptions({
id: params.groupId,
projectId: params.projectId,
})
),
]);
},
pendingComponent: FullPageLoadingState,
head: () => ({
meta: [{ title: createProjectTitle('Group') }],
}),
});
function Component() {
const router = useRouter();
const { projectId, organizationId, groupId } = Route.useParams();
const trpc = useTRPC();
const queryClient = useQueryClient();
const navigate = useNavigate();
const group = useSuspenseQuery(
trpc.group.byId.queryOptions({ id: groupId, projectId })
);
const deleteMutation = useMutation(
trpc.group.delete.mutationOptions({
onSuccess() {
queryClient.invalidateQueries(trpc.group.list.pathFilter());
navigate({
to: '/$organizationId/$projectId/groups',
params: { organizationId, projectId },
});
},
onError: handleError,
})
);
const { activeTab, tabs } = usePageTabs([
{ id: '/$organizationId/$projectId/groups/$groupId', label: 'Overview' },
{ id: 'members', label: 'Members' },
{ id: 'events', label: 'Events' },
]);
const handleTabChange = (tabId: string) => {
router.navigate({
from: Route.fullPath,
to: tabId,
});
};
const g = group.data;
if (!g) {
return (
<PageContainer>
<div className="flex flex-col items-center justify-center gap-3 py-24 text-muted-foreground">
<Building2Icon className="size-10 opacity-30" />
<p className="text-sm">Group not found</p>
</div>
</PageContainer>
);
}
return (
<PageContainer className="col">
<PageHeader
actions={
<div className="row gap-2">
<Button
onClick={() =>
pushModal('EditGroup', {
id: g.id,
projectId: g.projectId,
name: g.name,
type: g.type,
properties: g.properties,
})
}
size="sm"
variant="outline"
>
<PencilIcon className="mr-2 size-4" />
Edit
</Button>
<Button
onClick={() =>
showConfirm({
title: 'Delete group',
text: `Are you sure you want to delete "${g.name}"? This action cannot be undone.`,
onConfirm: () =>
deleteMutation.mutate({ id: g.id, projectId }),
})
}
size="sm"
variant="outline"
>
<Trash2Icon className="mr-2 size-4" />
Delete
</Button>
</div>
}
title={
<div className="row min-w-0 items-center gap-3">
<Building2Icon className="size-6 shrink-0" />
<span className="truncate">{g.name}</span>
</div>
}
/>
<Tabs
className="mt-2 mb-8"
onValueChange={handleTabChange}
value={activeTab}
>
<TabsList>
{tabs.map((tab) => (
<TabsTrigger key={tab.id} value={tab.id}>
{tab.label}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<Outlet />
</PageContainer>
);
}

View File

@@ -4,7 +4,6 @@ import { MostEvents } from '@/components/profiles/most-events';
import { PopularRoutes } from '@/components/profiles/popular-routes';
import { ProfileActivity } from '@/components/profiles/profile-activity';
import { ProfileCharts } from '@/components/profiles/profile-charts';
import { ProfileGroups } from '@/components/profiles/profile-groups';
import { ProfileMetrics } from '@/components/profiles/profile-metrics';
import { ProfileProperties } from '@/components/profiles/profile-properties';
import { useTRPC } from '@/integrations/trpc/react';
@@ -104,15 +103,8 @@ function Component() {
<ProfileMetrics data={metrics.data} />
</div>
{/* Profile properties - full width */}
<div className="col-span-1 flex flex-col gap-3 md:col-span-2">
<div className="col-span-1 md:col-span-2">
<ProfileProperties profile={profile.data!} />
{profile.data?.groups?.length ? (
<ProfileGroups
profileId={profileId}
projectId={projectId}
groups={profile.data.groups}
/>
) : null}
</div>
{/* Heatmap / Activity */}

View File

@@ -1,5 +1,3 @@
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { Fullscreen, FullscreenClose } from '@/components/fullscreen-toggle';
import RealtimeMap from '@/components/realtime/map';
import { RealtimeActiveSessions } from '@/components/realtime/realtime-active-sessions';
@@ -9,10 +7,12 @@ import { RealtimePaths } from '@/components/realtime/realtime-paths';
import { RealtimeReferrals } from '@/components/realtime/realtime-referrals';
import RealtimeReloader from '@/components/realtime/realtime-reloader';
import { useTRPC } from '@/integrations/trpc/react';
import { createProjectTitle, PAGE_TITLES } from '@/utils/title';
import { PAGE_TITLES, createProjectTitle } from '@/utils/title';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/realtime'
'/_app/$organizationId/$projectId/realtime',
)({
component: Component,
head: () => {
@@ -36,8 +36,8 @@ function Component() {
},
{
placeholderData: keepPreviousData,
}
)
},
),
);
return (
@@ -47,7 +47,7 @@ function Component() {
<RealtimeReloader projectId={projectId} />
<div className="row relative">
<div className="aspect-[4/2] w-full overflow-hidden">
<div className="overflow-hidden aspect-[4/2] w-full">
<RealtimeMap
markers={coordinatesQuery.data ?? []}
sidebarConfig={{
@@ -56,17 +56,18 @@ function Component() {
}}
/>
</div>
<div className="col absolute top-8 bottom-4 left-8 gap-4">
<div className="card w-72 bg-background/90 p-4">
<div className="absolute top-8 left-8 bottom-0 col gap-4">
<div className="card p-4 w-72 bg-background/90">
<RealtimeLiveHistogram projectId={projectId} />
</div>
<div className="relative min-h-0 w-72 flex-1">
<div className="w-72 flex-1 min-h-0 relative">
<RealtimeActiveSessions projectId={projectId} />
<div className="absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-def-100 to-transparent" />
</div>
</div>
</div>
<div className="grid grid-cols-1 gap-4 p-4 pt-4 md:grid-cols-2 md:p-8 md:pt-0 xl:grid-cols-3">
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 p-4 pt-4 md:p-8 md:pt-0">
<div>
<RealtimeGeo projectId={projectId} />
</div>

View File

@@ -732,10 +732,10 @@ function GscTable({
)}
</div>
{onSearchChange != null && (
<div className="relative">
<div className="relative border-t">
<SearchIcon className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
className="rounded-none border-0 border-t bg-transparent pl-9 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0"
className="rounded-none border-0 border-y bg-transparent pl-9 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0"
onChange={(e) => onSearchChange(e.target.value)}
placeholder={searchPlaceholder ?? 'Search'}
type="search"

View File

@@ -1,15 +1,19 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { PageContainer } from '@/components/page-container';
import { PageHeader } from '@/components/page-header';
import { SessionsTable } from '@/components/sessions/table';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
import { useSessionFilters } from '@/hooks/use-session-filters';
import { useTRPC } from '@/integrations/trpc/react';
import { createProjectTitle, PAGE_TITLES } from '@/utils/title';
import { PAGE_TITLES, createProjectTitle } from '@/utils/title';
import {
keepPreviousData,
useInfiniteQuery,
useQuery,
} from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { parseAsString, parseAsStringEnum, useQueryState } from 'nuqs';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/sessions'
'/_app/$organizationId/$projectId/sessions',
)({
component: Component,
head: () => {
@@ -27,8 +31,6 @@ function Component() {
const { projectId } = Route.useParams();
const trpc = useTRPC();
const { debouncedSearch } = useSearchQueryState();
const { filters, minPageViews, maxPageViews, minEvents, maxEvents } =
useSessionFilters();
const query = useInfiniteQuery(
trpc.session.list.infiniteQueryOptions(
@@ -36,24 +38,19 @@ function Component() {
projectId,
take: 50,
search: debouncedSearch,
filters,
minPageViews,
maxPageViews,
minEvents,
maxEvents,
},
{
getNextPageParam: (lastPage) => lastPage.meta.next,
}
)
},
),
);
return (
<PageContainer>
<PageHeader
className="mb-8"
description="Access all your sessions here"
title="Sessions"
description="Access all your sessions here"
className="mb-8"
/>
<SessionsTable query={query} />
</PageContainer>

View File

@@ -1,5 +1,5 @@
import type { IServiceEvent, IServiceSession } from '@openpanel/db';
import { useSuspenseQuery, useQuery } from '@tanstack/react-query';
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, Link } from '@tanstack/react-router';
import { EventIcon } from '@/components/events/event-icon';
import FullPageLoadingState from '@/components/full-page-loading-state';
@@ -165,14 +165,6 @@ function Component() {
})
);
const { data: sessionGroups } = useQuery({
...trpc.group.listByIds.queryOptions({
projectId,
ids: session.groups ?? [],
}),
enabled: (session.groups?.length ?? 0) > 0,
});
const fakeEvent = sessionToFakeEvent(session);
return (
@@ -332,35 +324,6 @@ function Component() {
</Widget>
)}
{/* Group cards */}
{sessionGroups && sessionGroups.length > 0 && (
<Widget className="w-full">
<WidgetHead>
<WidgetTitle>Groups</WidgetTitle>
</WidgetHead>
<WidgetBody className="p-0">
{sessionGroups.map((group) => (
<Link
key={group.id}
className="row items-center gap-3 p-4 transition-colors hover:bg-accent"
params={{ organizationId, projectId, groupId: group.id }}
to="/$organizationId/$projectId/groups/$groupId"
>
<div className="col min-w-0 flex-1 gap-0.5">
<span className="truncate font-medium">{group.name}</span>
<span className="truncate text-muted-foreground text-sm font-mono">
{group.id}
</span>
</div>
<span className="shrink-0 rounded border px-1.5 py-0.5 text-muted-foreground text-xs">
{group.type}
</span>
</Link>
))}
</WidgetBody>
</Widget>
)}
{/* Visited pages */}
<VisitedRoutes
paths={events

View File

@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { createFileRoute, Link, redirect } from '@tanstack/react-router';
import { BoxSelectIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { ButtonContainer } from '@/components/button-container';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
@@ -32,21 +33,22 @@ export const Route = createFileRoute('/_steps/onboarding/$projectId/verify')({
});
function Component() {
const [isVerified, setIsVerified] = useState(false);
const { projectId } = Route.useParams();
const trpc = useTRPC();
const { data: events } = useQuery(
trpc.event.events.queryOptions(
{ projectId },
{
refetchInterval: 2500,
}
)
const { data: events, refetch } = useQuery(
trpc.event.events.queryOptions({ projectId })
);
const isVerified = events?.data && events.data.length > 0;
const { data: project } = useQuery(
trpc.project.getProjectWithClients.queryOptions({ projectId })
);
useEffect(() => {
if (events && events.data.length > 0) {
setIsVerified(true);
}
}, [events]);
if (!project) {
return (
<FullPageEmptyState icon={BoxSelectIcon} title="Project not found" />
@@ -62,7 +64,15 @@ function Component() {
<div className="flex min-h-0 flex-1 flex-col">
<div className="scrollbar-thin flex-1 overflow-y-auto">
<div className="col gap-8 p-4">
<VerifyListener events={events?.data ?? []} />
<VerifyListener
client={client}
events={events?.data ?? []}
onVerified={() => {
refetch();
setIsVerified(true);
}}
project={project}
/>
<VerifyFaq project={project} />
</div>

View File

@@ -10,7 +10,7 @@ const BASE_TITLE = 'OpenPanel.dev';
export function createTitle(
pageTitle: string,
section?: string,
baseTitle = BASE_TITLE
baseTitle = BASE_TITLE,
): string {
const parts = [pageTitle];
if (section) {
@@ -25,7 +25,7 @@ export function createTitle(
*/
export function createOrganizationTitle(
pageTitle: string,
organizationName?: string
organizationName?: string,
): string {
if (organizationName) {
return createTitle(pageTitle, organizationName);
@@ -39,7 +39,7 @@ export function createOrganizationTitle(
export function createProjectTitle(
pageTitle: string,
projectName?: string,
organizationName?: string
organizationName?: string,
): string {
const parts = [pageTitle];
if (projectName) {
@@ -59,7 +59,7 @@ export function createEntityTitle(
entityName: string,
entityType: string,
projectName?: string,
organizationName?: string
organizationName?: string,
): string {
const parts = [entityName, entityType];
if (projectName) {
@@ -95,9 +95,6 @@ export const PAGE_TITLES = {
PROFILES: 'Profiles',
PROFILE_EVENTS: 'Profile events',
PROFILE_DETAILS: 'Profile details',
// Groups
GROUPS: 'Groups',
GROUP_DETAILS: 'Group details',
// Sub-sections
CONVERSIONS: 'Conversions',

View File

@@ -1,4 +0,0 @@
node_modules
dist
public/op1.js
.env

View File

@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Testbed | OpenPanel SDK</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -1,24 +0,0 @@
{
"name": "@openpanel/testbed",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port 3100",
"build": "tsc && vite build",
"postinstall": "node scripts/copy-op1.mjs"
},
"dependencies": {
"@openpanel/web": "workspace:*",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.13.1"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "catalog:",
"vite": "^6.0.0"
}
}

View File

@@ -1,16 +0,0 @@
import { copyFileSync, mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const src = join(__dirname, '../../public/public/op1.js');
const dest = join(__dirname, '../public/op1.js');
mkdirSync(join(__dirname, '../public'), { recursive: true });
try {
copyFileSync(src, dest);
console.log('✓ Copied op1.js to public/');
} catch (e) {
console.warn('⚠ Could not copy op1.js:', e.message);
}

View File

@@ -1,217 +0,0 @@
import { useEffect, useState } from 'react';
import { Link, Route, Routes, useNavigate } from 'react-router-dom';
import { op } from './analytics';
import { CartPage } from './pages/Cart';
import { CheckoutPage } from './pages/Checkout';
import { LoginPage, PRESET_GROUPS } from './pages/Login';
import { ProductPage } from './pages/Product';
import { ShopPage } from './pages/Shop';
import type { CartItem, Product, User } from './types';
const PRODUCTS: Product[] = [
{ id: 'p1', name: 'Classic T-Shirt', price: 25, category: 'clothing' },
{ id: 'p2', name: 'Coffee Mug', price: 15, category: 'accessories' },
{ id: 'p3', name: 'Hoodie', price: 60, category: 'clothing' },
{ id: 'p4', name: 'Sticker Pack', price: 10, category: 'accessories' },
{ id: 'p5', name: 'Cap', price: 35, category: 'clothing' },
];
export default function App() {
const navigate = useNavigate();
const [cart, setCart] = useState<CartItem[]>([]);
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
const stored = localStorage.getItem('op_testbed_user');
if (stored) {
const u = JSON.parse(stored) as User;
setUser(u);
op.identify({
profileId: u.id,
firstName: u.firstName,
lastName: u.lastName,
email: u.email,
});
applyGroups(u);
}
op.ready();
}, []);
function applyGroups(u: User) {
op.setGroups(u.groupIds);
for (const id of u.groupIds) {
const meta = PRESET_GROUPS.find((g) => g.id === id);
if (meta) {
op.upsertGroup({ id, ...meta });
}
}
}
function login(u: User) {
localStorage.setItem('op_testbed_user', JSON.stringify(u));
setUser(u);
op.identify({
profileId: u.id,
firstName: u.firstName,
lastName: u.lastName,
email: u.email,
});
applyGroups(u);
op.track('user_login', { method: 'form', group_count: u.groupIds.length });
navigate('/');
}
function logout() {
localStorage.removeItem('op_testbed_user');
op.clear();
setUser(null);
}
function addToCart(product: Product) {
setCart((prev) => {
const existing = prev.find((i) => i.id === product.id);
if (existing) {
return prev.map((i) =>
i.id === product.id ? { ...i, qty: i.qty + 1 } : i
);
}
return [...prev, { ...product, qty: 1 }];
});
op.track('add_to_cart', {
product_id: product.id,
product_name: product.name,
price: product.price,
category: product.category,
});
}
function removeFromCart(id: string) {
const item = cart.find((i) => i.id === id);
if (item) {
op.track('remove_from_cart', {
product_id: item.id,
product_name: item.name,
});
}
setCart((prev) => prev.filter((i) => i.id !== id));
}
function startCheckout() {
const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);
op.track('checkout_started', {
total,
item_count: cart.reduce((sum, i) => sum + i.qty, 0),
items: cart.map((i) => i.id),
});
navigate('/checkout');
}
function pay(succeed: boolean) {
const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);
op.track('payment_attempted', { total, success: succeed });
if (succeed) {
op.revenue(total, {
items: cart.map((i) => i.id),
item_count: cart.reduce((sum, i) => sum + i.qty, 0),
});
op.track('purchase_completed', { total });
setCart([]);
navigate('/success');
} else {
op.track('purchase_failed', { total, reason: 'declined' });
navigate('/error');
}
}
const cartCount = cart.reduce((sum, i) => sum + i.qty, 0);
return (
<div className="app">
<nav className="nav">
<Link className="nav-brand" to="/">
TESTSTORE
</Link>
<div className="nav-links">
<Link to="/">Shop</Link>
<Link to="/cart">Cart ({cartCount})</Link>
{user ? (
<>
<span className="nav-user">{user.firstName}</span>
<button onClick={logout} type="button">
Logout
</button>
</>
) : (
<Link to="/login">Login</Link>
)}
</div>
</nav>
<main className="main">
<Routes>
<Route
element={<ShopPage onAddToCart={addToCart} products={PRODUCTS} />}
path="/"
/>
<Route
element={
<ProductPage onAddToCart={addToCart} products={PRODUCTS} />
}
path="/product/:id"
/>
<Route element={<LoginPage onLogin={login} />} path="/login" />
<Route
element={
<CartPage
cart={cart}
onCheckout={startCheckout}
onRemove={removeFromCart}
/>
}
path="/cart"
/>
<Route
element={<CheckoutPage cart={cart} onPay={pay} />}
path="/checkout"
/>
<Route
element={
<div className="result-page">
<div className="result-icon">[OK]</div>
<div className="result-title">Payment successful</div>
<p>Your order has been placed. Thanks for testing!</p>
<div className="result-actions">
<Link to="/">
<button className="primary" type="button">
Continue shopping
</button>
</Link>
</div>
</div>
}
path="/success"
/>
<Route
element={
<div className="result-page">
<div className="result-icon">[ERR]</div>
<div className="result-title">Payment failed</div>
<p>Card declined. Try again or go back to cart.</p>
<div className="result-actions">
<Link to="/checkout">
<button type="button">Retry</button>
</Link>
<Link to="/cart">
<button type="button">Back to cart</button>
</Link>
</div>
</div>
}
path="/error"
/>
</Routes>
</main>
</div>
);
}

View File

@@ -1,10 +0,0 @@
import { OpenPanel } from '@openpanel/web';
export const op = new OpenPanel({
clientId: import.meta.env.VITE_OPENPANEL_CLIENT_ID ?? 'testbed-client',
apiUrl: import.meta.env.VITE_OPENPANEL_API_URL ?? 'http://localhost:3333',
trackScreenViews: true,
trackOutgoingLinks: true,
trackAttributes: true,
disabled: true,
});

Some files were not shown because too many files have changed in this diff Show More