Compare commits
22 Commits
feature/in
...
feature/sh
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f880b9a697 | ||
|
|
13bd16b207 | ||
|
|
347a01a941 | ||
|
|
ba79ac570c | ||
|
|
ca15717885 | ||
|
|
ba93924d20 | ||
|
|
7b87a57cbe | ||
|
|
39251c8598 | ||
|
|
9a4aa51975 | ||
|
|
f008fb58e5 | ||
|
|
cabfb1f3f0 | ||
|
|
4867260ece | ||
|
|
87c919f700 | ||
|
|
3c085e445d | ||
|
|
6d9e3ce8e5 | ||
|
|
f187065d75 | ||
|
|
d5e4518e32 | ||
|
|
1f088d2208 | ||
|
|
3bd1f99d28 | ||
|
|
9a916f3171 | ||
|
|
34cb186ead | ||
|
|
5f38560373 |
@@ -38,11 +38,9 @@ COPY packages/redis/package.json packages/redis/
|
||||
COPY packages/logger/package.json packages/logger/
|
||||
COPY packages/common/package.json packages/common/
|
||||
COPY packages/payments/package.json packages/payments/
|
||||
COPY packages/sdks/sdk/package.json packages/sdks/sdk/
|
||||
COPY packages/constants/package.json packages/constants/
|
||||
COPY packages/validation/package.json packages/validation/
|
||||
COPY packages/integrations/package.json packages/integrations/
|
||||
COPY packages/sdks/sdk/package.json packages/sdks/sdk/
|
||||
COPY patches ./patches
|
||||
|
||||
# BUILD
|
||||
@@ -107,7 +105,6 @@ COPY --from=build /app/packages/redis ./packages/redis
|
||||
COPY --from=build /app/packages/logger ./packages/logger
|
||||
COPY --from=build /app/packages/common ./packages/common
|
||||
COPY --from=build /app/packages/payments ./packages/payments
|
||||
COPY --from=build /app/packages/sdks/sdk ./packages/sdks/sdk
|
||||
COPY --from=build /app/packages/constants ./packages/constants
|
||||
COPY --from=build /app/packages/validation ./packages/validation
|
||||
COPY --from=build /app/packages/integrations ./packages/integrations
|
||||
|
||||
@@ -52,7 +52,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "^9.0.1",
|
||||
"@openpanel/sdk": "workspace:*",
|
||||
"@openpanel/tsconfig": "workspace:*",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/jsonwebtoken": "^9.0.9",
|
||||
|
||||
@@ -3,15 +3,15 @@ import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { generateDeviceId, parseUserAgent } from '@openpanel/common/server';
|
||||
import { getSalts } from '@openpanel/db';
|
||||
import { getEventsGroupQueueShard } from '@openpanel/queue';
|
||||
import type { PostEventPayload } from '@openpanel/sdk';
|
||||
|
||||
import { generateId, slug } from '@openpanel/common';
|
||||
import { getGeoLocation } from '@openpanel/geo';
|
||||
import type { DeprecatedPostEventPayload } from '@openpanel/validation';
|
||||
import { getStringHeaders, getTimestamp } from './track.controller';
|
||||
|
||||
export async function postEvent(
|
||||
request: FastifyRequest<{
|
||||
Body: PostEventPayload;
|
||||
Body: DeprecatedPostEventPayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
getSettingsForProject,
|
||||
} from '@openpanel/db';
|
||||
import { ChartEngine } from '@openpanel/db';
|
||||
import { zChartEvent, zChartInputBase } from '@openpanel/validation';
|
||||
import { zChartEvent, zReport } from '@openpanel/validation';
|
||||
import { omit } from 'ramda';
|
||||
|
||||
async function getProjectId(
|
||||
@@ -139,7 +139,7 @@ export async function events(
|
||||
});
|
||||
}
|
||||
|
||||
const chartSchemeFull = zChartInputBase
|
||||
const chartSchemeFull = zReport
|
||||
.pick({
|
||||
breakdowns: true,
|
||||
interval: true,
|
||||
|
||||
@@ -96,8 +96,6 @@ export async function getPages(
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
timezone,
|
||||
cursor: parsed.data.cursor,
|
||||
limit: Math.min(parsed.data.limit, 50),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -170,8 +168,6 @@ export function getOverviewGeneric(
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
timezone,
|
||||
cursor: parsed.data.cursor,
|
||||
limit: Math.min(parsed.data.limit, 50),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -118,7 +118,11 @@ async function fetchImage(
|
||||
|
||||
// Check if URL is an ICO file
|
||||
function isIcoFile(url: string, contentType?: string): boolean {
|
||||
return url.toLowerCase().endsWith('.ico') || contentType === 'image/x-icon';
|
||||
return (
|
||||
url.toLowerCase().endsWith('.ico') ||
|
||||
contentType === 'image/x-icon' ||
|
||||
contentType === 'image/vnd.microsoft.icon'
|
||||
);
|
||||
}
|
||||
function isSvgFile(url: string, contentType?: string): boolean {
|
||||
return url.toLowerCase().endsWith('.svg') || contentType === 'image/svg+xml';
|
||||
@@ -239,7 +243,9 @@ export async function getFavicon(
|
||||
try {
|
||||
const url = validateUrl(request.query.url);
|
||||
if (!url) {
|
||||
return createFallbackImage();
|
||||
reply.header('Content-Type', 'image/png');
|
||||
reply.header('Cache-Control', 'public, max-age=3600');
|
||||
return reply.send(createFallbackImage());
|
||||
}
|
||||
|
||||
const cacheKey = createCacheKey(url.toString());
|
||||
@@ -260,21 +266,65 @@ export async function getFavicon(
|
||||
} else {
|
||||
// For website URLs, extract favicon from HTML
|
||||
const meta = await parseUrlMeta(url.toString());
|
||||
logger.info('parseUrlMeta result', {
|
||||
url: url.toString(),
|
||||
favicon: meta?.favicon,
|
||||
});
|
||||
if (meta?.favicon) {
|
||||
imageUrl = new URL(meta.favicon);
|
||||
} else {
|
||||
// Fallback to Google's favicon service
|
||||
const { hostname } = url;
|
||||
imageUrl = new URL(
|
||||
`https://www.google.com/s2/favicons?domain=${hostname}&sz=256`,
|
||||
);
|
||||
// Try standard favicon location first
|
||||
const { origin } = url;
|
||||
imageUrl = new URL(`${origin}/favicon.ico`);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch the image
|
||||
const { buffer, contentType, status } = await fetchImage(imageUrl);
|
||||
logger.info('Fetching favicon', {
|
||||
originalUrl: url.toString(),
|
||||
imageUrl: imageUrl.toString(),
|
||||
});
|
||||
|
||||
if (status !== 200 || buffer.length === 0) {
|
||||
// Fetch the image
|
||||
let { buffer, contentType, status } = await fetchImage(imageUrl);
|
||||
|
||||
logger.info('Favicon fetch result', {
|
||||
originalUrl: url.toString(),
|
||||
imageUrl: imageUrl.toString(),
|
||||
status,
|
||||
bufferLength: buffer.length,
|
||||
contentType,
|
||||
});
|
||||
|
||||
// If the direct favicon fetch failed and it's not from DuckDuckGo's service,
|
||||
// try DuckDuckGo's favicon service as a fallback
|
||||
if (buffer.length === 0 && !imageUrl.hostname.includes('duckduckgo.com')) {
|
||||
const { hostname } = url;
|
||||
const duckduckgoUrl = new URL(
|
||||
`https://icons.duckduckgo.com/ip3/${hostname}.ico`,
|
||||
);
|
||||
|
||||
logger.info('Trying DuckDuckGo favicon service', {
|
||||
originalUrl: url.toString(),
|
||||
duckduckgoUrl: duckduckgoUrl.toString(),
|
||||
});
|
||||
|
||||
const duckduckgoResult = await fetchImage(duckduckgoUrl);
|
||||
buffer = duckduckgoResult.buffer;
|
||||
contentType = duckduckgoResult.contentType;
|
||||
status = duckduckgoResult.status;
|
||||
imageUrl = duckduckgoUrl;
|
||||
|
||||
logger.info('DuckDuckGo favicon result', {
|
||||
status,
|
||||
bufferLength: buffer.length,
|
||||
contentType,
|
||||
});
|
||||
}
|
||||
|
||||
// Accept any response as long as we have valid image data
|
||||
if (buffer.length === 0) {
|
||||
reply.header('Content-Type', 'image/png');
|
||||
reply.header('Cache-Control', 'public, max-age=3600');
|
||||
return reply.send(createFallbackImage());
|
||||
}
|
||||
|
||||
@@ -285,9 +335,31 @@ export async function getFavicon(
|
||||
contentType,
|
||||
);
|
||||
|
||||
logger.info('Favicon processing result', {
|
||||
originalUrl: url.toString(),
|
||||
originalBufferLength: buffer.length,
|
||||
processedBufferLength: processedBuffer.length,
|
||||
});
|
||||
|
||||
// Determine the correct content type for caching and response
|
||||
const isIco = isIcoFile(imageUrl.toString(), contentType);
|
||||
const responseContentType = isIco ? 'image/x-icon' : contentType;
|
||||
const isSvg = isSvgFile(imageUrl.toString(), contentType);
|
||||
let responseContentType = contentType;
|
||||
|
||||
if (isIco) {
|
||||
responseContentType = 'image/x-icon';
|
||||
} else if (isSvg) {
|
||||
responseContentType = 'image/svg+xml';
|
||||
} else if (
|
||||
processedBuffer.length < 5000 &&
|
||||
buffer.length === processedBuffer.length
|
||||
) {
|
||||
// Image was returned as-is, keep original content type
|
||||
responseContentType = contentType;
|
||||
} else {
|
||||
// Image was processed by Sharp, it's now a PNG
|
||||
responseContentType = 'image/png';
|
||||
}
|
||||
|
||||
// Cache the result with correct content type
|
||||
await setToCacheBinary(cacheKey, processedBuffer, responseContentType);
|
||||
|
||||
@@ -5,13 +5,13 @@ import { parseUserAgent } from '@openpanel/common/server';
|
||||
import { getProfileById, upsertProfile } from '@openpanel/db';
|
||||
import { getGeoLocation } from '@openpanel/geo';
|
||||
import type {
|
||||
IncrementProfilePayload,
|
||||
UpdateProfilePayload,
|
||||
} from '@openpanel/sdk';
|
||||
DeprecatedIncrementProfilePayload,
|
||||
DeprecatedUpdateProfilePayload,
|
||||
} from '@openpanel/validation';
|
||||
|
||||
export async function updateProfile(
|
||||
request: FastifyRequest<{
|
||||
Body: UpdateProfilePayload;
|
||||
Body: DeprecatedUpdateProfilePayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
@@ -52,7 +52,7 @@ export async function updateProfile(
|
||||
|
||||
export async function incrementProfileProperty(
|
||||
request: FastifyRequest<{
|
||||
Body: IncrementProfilePayload;
|
||||
Body: DeprecatedIncrementProfilePayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
@@ -94,7 +94,7 @@ export async function incrementProfileProperty(
|
||||
|
||||
export async function decrementProfileProperty(
|
||||
request: FastifyRequest<{
|
||||
Body: IncrementProfilePayload;
|
||||
Body: DeprecatedIncrementProfilePayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
|
||||
@@ -8,13 +8,15 @@ import { getProfileById, getSalts, upsertProfile } from '@openpanel/db';
|
||||
import { type GeoLocation, getGeoLocation } from '@openpanel/geo';
|
||||
import { getEventsGroupQueueShard } from '@openpanel/queue';
|
||||
import { getRedisCache } from '@openpanel/redis';
|
||||
import type {
|
||||
DecrementPayload,
|
||||
IdentifyPayload,
|
||||
IncrementPayload,
|
||||
TrackHandlerPayload,
|
||||
TrackPayload,
|
||||
} from '@openpanel/sdk';
|
||||
|
||||
import {
|
||||
type IDecrementPayload,
|
||||
type IIdentifyPayload,
|
||||
type IIncrementPayload,
|
||||
type ITrackHandlerPayload,
|
||||
type ITrackPayload,
|
||||
zTrackHandlerPayload,
|
||||
} from '@openpanel/validation';
|
||||
|
||||
export function getStringHeaders(headers: FastifyRequest['headers']) {
|
||||
return Object.entries(
|
||||
@@ -37,25 +39,28 @@ export function getStringHeaders(headers: FastifyRequest['headers']) {
|
||||
);
|
||||
}
|
||||
|
||||
function getIdentity(body: TrackHandlerPayload): IdentifyPayload | undefined {
|
||||
const identity =
|
||||
'properties' in body.payload
|
||||
? (body.payload?.properties?.__identify as IdentifyPayload | undefined)
|
||||
: undefined;
|
||||
function getIdentity(body: ITrackHandlerPayload): IIdentifyPayload | undefined {
|
||||
if (body.type === 'track') {
|
||||
const identity = body.payload.properties?.__identify as
|
||||
| IIdentifyPayload
|
||||
| undefined;
|
||||
|
||||
return (
|
||||
identity ||
|
||||
(body?.payload?.profileId
|
||||
? {
|
||||
profileId: body.payload.profileId,
|
||||
}
|
||||
: undefined)
|
||||
);
|
||||
return (
|
||||
identity ||
|
||||
(body.payload.profileId
|
||||
? {
|
||||
profileId: body.payload.profileId,
|
||||
}
|
||||
: undefined)
|
||||
);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getTimestamp(
|
||||
timestamp: FastifyRequest['timestamp'],
|
||||
payload: TrackHandlerPayload['payload'],
|
||||
payload: ITrackHandlerPayload['payload'],
|
||||
) {
|
||||
const safeTimestamp = timestamp || Date.now();
|
||||
const userDefinedTimestamp =
|
||||
@@ -82,7 +87,7 @@ export function getTimestamp(
|
||||
return { timestamp: safeTimestamp, isTimestampFromThePast: false };
|
||||
}
|
||||
|
||||
// isTimestampFromThePast is true only if timestamp is older than 1 hour
|
||||
// isTimestampFromThePast is true only if timestamp is older than 15 minutes
|
||||
const isTimestampFromThePast =
|
||||
clientTimestampNumber < safeTimestamp - FIFTEEN_MINUTES_MS;
|
||||
|
||||
@@ -92,170 +97,113 @@ export function getTimestamp(
|
||||
};
|
||||
}
|
||||
|
||||
export async function handler(
|
||||
request: FastifyRequest<{
|
||||
Body: TrackHandlerPayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
const timestamp = getTimestamp(request.timestamp, request.body.payload);
|
||||
const ip =
|
||||
'properties' in request.body.payload &&
|
||||
request.body.payload.properties?.__ip
|
||||
? (request.body.payload.properties.__ip as string)
|
||||
: request.clientIp;
|
||||
const ua = request.headers['user-agent'];
|
||||
const projectId = request.client?.projectId;
|
||||
interface TrackContext {
|
||||
projectId: string;
|
||||
ip: string;
|
||||
ua?: string;
|
||||
headers: Record<string, string | undefined>;
|
||||
timestamp: { value: number; isFromPast: boolean };
|
||||
identity?: IIdentifyPayload;
|
||||
currentDeviceId?: string;
|
||||
previousDeviceId?: string;
|
||||
geo: GeoLocation;
|
||||
}
|
||||
|
||||
async function buildContext(
|
||||
request: FastifyRequest<{
|
||||
Body: ITrackHandlerPayload;
|
||||
}>,
|
||||
validatedBody: ITrackHandlerPayload,
|
||||
): Promise<TrackContext> {
|
||||
const projectId = request.client?.projectId;
|
||||
if (!projectId) {
|
||||
return reply.status(400).send({
|
||||
status: 400,
|
||||
error: 'Bad Request',
|
||||
message: 'Missing projectId',
|
||||
});
|
||||
throw new HttpError('Missing projectId', { status: 400 });
|
||||
}
|
||||
|
||||
const identity = getIdentity(request.body);
|
||||
const timestamp = getTimestamp(request.timestamp, validatedBody.payload);
|
||||
const ip =
|
||||
validatedBody.type === 'track' && validatedBody.payload.properties?.__ip
|
||||
? (validatedBody.payload.properties.__ip as string)
|
||||
: request.clientIp;
|
||||
const ua = request.headers['user-agent'];
|
||||
const headers = getStringHeaders(request.headers);
|
||||
|
||||
const identity = getIdentity(validatedBody);
|
||||
const profileId = identity?.profileId;
|
||||
const overrideDeviceId = (() => {
|
||||
const deviceId =
|
||||
'properties' in request.body.payload
|
||||
? request.body.payload.properties?.__deviceId
|
||||
: undefined;
|
||||
if (typeof deviceId === 'string') {
|
||||
return deviceId;
|
||||
}
|
||||
return undefined;
|
||||
})();
|
||||
|
||||
// We might get a profileId from the alias table
|
||||
// If we do, we should use that instead of the one from the payload
|
||||
if (profileId) {
|
||||
request.body.payload.profileId = profileId;
|
||||
if (profileId && validatedBody.type === 'track') {
|
||||
validatedBody.payload.profileId = profileId;
|
||||
}
|
||||
|
||||
switch (request.body.type) {
|
||||
case 'track': {
|
||||
const [salts, geo] = await Promise.all([getSalts(), getGeoLocation(ip)]);
|
||||
const currentDeviceId =
|
||||
overrideDeviceId ||
|
||||
(ua
|
||||
? generateDeviceId({
|
||||
salt: salts.current,
|
||||
origin: projectId,
|
||||
ip,
|
||||
ua,
|
||||
})
|
||||
: '');
|
||||
const previousDeviceId = ua
|
||||
// Get geo location (needed for track and identify)
|
||||
const geo = await getGeoLocation(ip);
|
||||
|
||||
// Generate device IDs if needed (for track)
|
||||
let currentDeviceId: string | undefined;
|
||||
let previousDeviceId: string | undefined;
|
||||
|
||||
if (validatedBody.type === 'track') {
|
||||
const overrideDeviceId =
|
||||
typeof validatedBody.payload.properties?.__deviceId === 'string'
|
||||
? validatedBody.payload.properties.__deviceId
|
||||
: undefined;
|
||||
|
||||
const [salts] = await Promise.all([getSalts()]);
|
||||
currentDeviceId =
|
||||
overrideDeviceId ||
|
||||
(ua
|
||||
? generateDeviceId({
|
||||
salt: salts.previous,
|
||||
salt: salts.current,
|
||||
origin: projectId,
|
||||
ip,
|
||||
ua,
|
||||
})
|
||||
: '';
|
||||
|
||||
const promises = [];
|
||||
|
||||
// If we have more than one property in the identity object, we should identify the user
|
||||
// Otherwise its only a profileId and we should not identify the user
|
||||
if (identity && Object.keys(identity).length > 1) {
|
||||
promises.push(
|
||||
identify({
|
||||
payload: identity,
|
||||
projectId,
|
||||
geo,
|
||||
ua,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
promises.push(
|
||||
track({
|
||||
payload: request.body.payload,
|
||||
currentDeviceId,
|
||||
previousDeviceId,
|
||||
projectId,
|
||||
geo,
|
||||
headers: getStringHeaders(request.headers),
|
||||
timestamp: timestamp.timestamp,
|
||||
isTimestampFromThePast: timestamp.isTimestampFromThePast,
|
||||
}),
|
||||
);
|
||||
|
||||
await Promise.all(promises);
|
||||
break;
|
||||
}
|
||||
case 'identify': {
|
||||
const payload = request.body.payload;
|
||||
const geo = await getGeoLocation(ip);
|
||||
if (!payload.profileId) {
|
||||
throw new HttpError('Missing profileId', {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
await identify({
|
||||
payload,
|
||||
projectId,
|
||||
geo,
|
||||
ua,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'alias': {
|
||||
return reply.status(400).send({
|
||||
status: 400,
|
||||
error: 'Bad Request',
|
||||
message: 'Alias is not supported',
|
||||
});
|
||||
}
|
||||
case 'increment': {
|
||||
await increment({
|
||||
payload: request.body.payload,
|
||||
projectId,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'decrement': {
|
||||
await decrement({
|
||||
payload: request.body.payload,
|
||||
projectId,
|
||||
});
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return reply.status(400).send({
|
||||
status: 400,
|
||||
error: 'Bad Request',
|
||||
message: 'Invalid type',
|
||||
});
|
||||
}
|
||||
: '');
|
||||
previousDeviceId = ua
|
||||
? generateDeviceId({
|
||||
salt: salts.previous,
|
||||
origin: projectId,
|
||||
ip,
|
||||
ua,
|
||||
})
|
||||
: '';
|
||||
}
|
||||
|
||||
reply.status(200).send();
|
||||
return {
|
||||
projectId,
|
||||
ip,
|
||||
ua,
|
||||
headers,
|
||||
timestamp: {
|
||||
value: timestamp.timestamp,
|
||||
isFromPast: timestamp.isTimestampFromThePast,
|
||||
},
|
||||
identity,
|
||||
currentDeviceId,
|
||||
previousDeviceId,
|
||||
geo,
|
||||
};
|
||||
}
|
||||
|
||||
async function track({
|
||||
payload,
|
||||
currentDeviceId,
|
||||
previousDeviceId,
|
||||
projectId,
|
||||
geo,
|
||||
headers,
|
||||
timestamp,
|
||||
isTimestampFromThePast,
|
||||
}: {
|
||||
payload: TrackPayload;
|
||||
currentDeviceId: string;
|
||||
previousDeviceId: string;
|
||||
projectId: string;
|
||||
geo: GeoLocation;
|
||||
headers: Record<string, string | undefined>;
|
||||
timestamp: number;
|
||||
isTimestampFromThePast: boolean;
|
||||
}) {
|
||||
async function handleTrack(
|
||||
payload: ITrackPayload,
|
||||
context: TrackContext,
|
||||
): Promise<void> {
|
||||
const {
|
||||
projectId,
|
||||
currentDeviceId,
|
||||
previousDeviceId,
|
||||
geo,
|
||||
headers,
|
||||
timestamp,
|
||||
} = context;
|
||||
|
||||
if (!currentDeviceId || !previousDeviceId) {
|
||||
throw new HttpError('Device ID generation failed', { status: 500 });
|
||||
}
|
||||
|
||||
const uaInfo = parseUserAgent(headers['user-agent'], payload.properties);
|
||||
const groupId = uaInfo.isServer
|
||||
? payload.profileId
|
||||
@@ -264,44 +212,51 @@ async function track({
|
||||
: currentDeviceId;
|
||||
const jobId = [
|
||||
slug(payload.name),
|
||||
timestamp,
|
||||
timestamp.value,
|
||||
projectId,
|
||||
currentDeviceId,
|
||||
groupId,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('-');
|
||||
await getEventsGroupQueueShard(groupId).add({
|
||||
orderMs: timestamp,
|
||||
data: {
|
||||
projectId,
|
||||
headers,
|
||||
event: {
|
||||
...payload,
|
||||
timestamp,
|
||||
isTimestampFromThePast,
|
||||
|
||||
const promises = [];
|
||||
|
||||
// If we have more than one property in the identity object, we should identify the user
|
||||
// Otherwise its only a profileId and we should not identify the user
|
||||
if (context.identity && Object.keys(context.identity).length > 1) {
|
||||
promises.push(handleIdentify(context.identity, context));
|
||||
}
|
||||
|
||||
promises.push(
|
||||
getEventsGroupQueueShard(groupId).add({
|
||||
orderMs: timestamp.value,
|
||||
data: {
|
||||
projectId,
|
||||
headers,
|
||||
event: {
|
||||
...payload,
|
||||
timestamp: timestamp.value,
|
||||
isTimestampFromThePast: timestamp.isFromPast,
|
||||
},
|
||||
uaInfo,
|
||||
geo,
|
||||
currentDeviceId,
|
||||
previousDeviceId,
|
||||
},
|
||||
uaInfo,
|
||||
geo,
|
||||
currentDeviceId,
|
||||
previousDeviceId,
|
||||
},
|
||||
groupId,
|
||||
jobId,
|
||||
});
|
||||
groupId,
|
||||
jobId,
|
||||
}),
|
||||
);
|
||||
|
||||
await Promise.all(promises);
|
||||
}
|
||||
|
||||
async function identify({
|
||||
payload,
|
||||
projectId,
|
||||
geo,
|
||||
ua,
|
||||
}: {
|
||||
payload: IdentifyPayload;
|
||||
projectId: string;
|
||||
geo: GeoLocation;
|
||||
ua?: string;
|
||||
}) {
|
||||
async function handleIdentify(
|
||||
payload: IIdentifyPayload,
|
||||
context: TrackContext,
|
||||
): Promise<void> {
|
||||
const { projectId, geo, ua } = context;
|
||||
const uaInfo = parseUserAgent(ua, payload.properties);
|
||||
await upsertProfile({
|
||||
...payload,
|
||||
@@ -326,17 +281,15 @@ async function identify({
|
||||
});
|
||||
}
|
||||
|
||||
async function increment({
|
||||
payload,
|
||||
projectId,
|
||||
}: {
|
||||
payload: IncrementPayload;
|
||||
projectId: string;
|
||||
}) {
|
||||
async function adjustProfileProperty(
|
||||
payload: IIncrementPayload | IDecrementPayload,
|
||||
projectId: string,
|
||||
direction: 1 | -1,
|
||||
): Promise<void> {
|
||||
const { profileId, property, value } = payload;
|
||||
const profile = await getProfileById(profileId, projectId);
|
||||
if (!profile) {
|
||||
throw new Error('Not found');
|
||||
throw new HttpError('Profile not found', { status: 404 });
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(
|
||||
@@ -345,12 +298,12 @@ async function increment({
|
||||
);
|
||||
|
||||
if (Number.isNaN(parsed)) {
|
||||
throw new Error('Not number');
|
||||
throw new HttpError('Property value is not a number', { status: 400 });
|
||||
}
|
||||
|
||||
profile.properties = assocPath(
|
||||
property.split('.'),
|
||||
parsed + (value || 1),
|
||||
parsed + direction * (value || 1),
|
||||
profile.properties,
|
||||
);
|
||||
|
||||
@@ -362,40 +315,74 @@ async function increment({
|
||||
});
|
||||
}
|
||||
|
||||
async function decrement({
|
||||
payload,
|
||||
projectId,
|
||||
}: {
|
||||
payload: DecrementPayload;
|
||||
projectId: string;
|
||||
}) {
|
||||
const { profileId, property, value } = payload;
|
||||
const profile = await getProfileById(profileId, projectId);
|
||||
if (!profile) {
|
||||
throw new Error('Not found');
|
||||
async function handleIncrement(
|
||||
payload: IIncrementPayload,
|
||||
context: TrackContext,
|
||||
): Promise<void> {
|
||||
await adjustProfileProperty(payload, context.projectId, 1);
|
||||
}
|
||||
|
||||
async function handleDecrement(
|
||||
payload: IDecrementPayload,
|
||||
context: TrackContext,
|
||||
): Promise<void> {
|
||||
await adjustProfileProperty(payload, context.projectId, -1);
|
||||
}
|
||||
|
||||
export async function handler(
|
||||
request: FastifyRequest<{
|
||||
Body: ITrackHandlerPayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
// Validate request body with Zod
|
||||
const validationResult = zTrackHandlerPayload.safeParse(request.body);
|
||||
if (!validationResult.success) {
|
||||
return reply.status(400).send({
|
||||
status: 400,
|
||||
error: 'Bad Request',
|
||||
message: 'Validation failed',
|
||||
errors: validationResult.error.errors,
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(
|
||||
pathOr<string>('0', property.split('.'), profile.properties),
|
||||
10,
|
||||
);
|
||||
const validatedBody = validationResult.data;
|
||||
|
||||
if (Number.isNaN(parsed)) {
|
||||
throw new Error('Not number');
|
||||
// Handle alias (not supported)
|
||||
if (validatedBody.type === 'alias') {
|
||||
return reply.status(400).send({
|
||||
status: 400,
|
||||
error: 'Bad Request',
|
||||
message: 'Alias is not supported',
|
||||
});
|
||||
}
|
||||
|
||||
profile.properties = assocPath(
|
||||
property.split('.'),
|
||||
parsed - (value || 1),
|
||||
profile.properties,
|
||||
);
|
||||
// Build request context
|
||||
const context = await buildContext(request, validatedBody);
|
||||
|
||||
await upsertProfile({
|
||||
id: profile.id,
|
||||
projectId,
|
||||
properties: profile.properties,
|
||||
isExternal: true,
|
||||
});
|
||||
// Dispatch to appropriate handler
|
||||
switch (validatedBody.type) {
|
||||
case 'track':
|
||||
await handleTrack(validatedBody.payload, context);
|
||||
break;
|
||||
case 'identify':
|
||||
await handleIdentify(validatedBody.payload, context);
|
||||
break;
|
||||
case 'increment':
|
||||
await handleIncrement(validatedBody.payload, context);
|
||||
break;
|
||||
case 'decrement':
|
||||
await handleDecrement(validatedBody.payload, context);
|
||||
break;
|
||||
default:
|
||||
return reply.status(400).send({
|
||||
status: 400,
|
||||
error: 'Bad Request',
|
||||
message: 'Invalid type',
|
||||
});
|
||||
}
|
||||
|
||||
reply.status(200).send();
|
||||
}
|
||||
|
||||
export async function fetchDeviceId(
|
||||
|
||||
@@ -191,7 +191,9 @@ export async function polarWebhook(
|
||||
where: {
|
||||
subscriptionCustomerId: event.data.customer.id,
|
||||
subscriptionId: event.data.id,
|
||||
subscriptionStatus: 'active',
|
||||
subscriptionStatus: {
|
||||
in: ['active', 'past_due', 'unpaid'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { SdkAuthError, validateSdkRequest } from '@/utils/auth';
|
||||
import type { PostEventPayload, TrackHandlerPayload } from '@openpanel/sdk';
|
||||
import type {
|
||||
DeprecatedPostEventPayload,
|
||||
ITrackHandlerPayload,
|
||||
} from '@openpanel/validation';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
|
||||
export async function clientHook(
|
||||
req: FastifyRequest<{
|
||||
Body: PostEventPayload | TrackHandlerPayload;
|
||||
Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { isDuplicatedEvent } from '@/utils/deduplicate';
|
||||
import type { PostEventPayload, TrackHandlerPayload } from '@openpanel/sdk';
|
||||
import type {
|
||||
DeprecatedPostEventPayload,
|
||||
ITrackHandlerPayload,
|
||||
} from '@openpanel/validation';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
|
||||
export async function duplicateHook(
|
||||
req: FastifyRequest<{
|
||||
Body: PostEventPayload | TrackHandlerPayload;
|
||||
Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
import { isBot } from '@/bots';
|
||||
import { createBotEvent } from '@openpanel/db';
|
||||
import type { TrackHandlerPayload } from '@openpanel/sdk';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type {
|
||||
DeprecatedPostEventPayload,
|
||||
ITrackHandlerPayload,
|
||||
} from '@openpanel/validation';
|
||||
|
||||
type DeprecatedEventPayload = {
|
||||
name: string;
|
||||
properties: Record<string, unknown>;
|
||||
timestamp: string;
|
||||
};
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
|
||||
export async function isBotHook(
|
||||
req: FastifyRequest<{
|
||||
Body: TrackHandlerPayload | DeprecatedEventPayload;
|
||||
Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
|
||||
@@ -14,22 +14,6 @@ const trackRouter: FastifyPluginCallback = async (fastify) => {
|
||||
method: 'POST',
|
||||
url: '/',
|
||||
handler: handler,
|
||||
schema: {
|
||||
body: {
|
||||
type: 'object',
|
||||
required: ['type', 'payload'],
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['track', 'increment', 'decrement', 'alias', 'identify'],
|
||||
},
|
||||
payload: {
|
||||
type: 'object',
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fastify.route({
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from '@openpanel/db';
|
||||
import { ChartEngine } from '@openpanel/db';
|
||||
import { getCache } from '@openpanel/redis';
|
||||
import { zChartInputAI } from '@openpanel/validation';
|
||||
import { zReportInput } from '@openpanel/validation';
|
||||
import { tool } from 'ai';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -27,7 +27,10 @@ export function getReport({
|
||||
- ${chartTypes.metric}
|
||||
- ${chartTypes.bar}
|
||||
`,
|
||||
parameters: zChartInputAI,
|
||||
parameters: zReportInput.extend({
|
||||
startDate: z.string().describe('The start date for the report'),
|
||||
endDate: z.string().describe('The end date for the report'),
|
||||
}),
|
||||
execute: async (report) => {
|
||||
return {
|
||||
type: 'report',
|
||||
@@ -72,7 +75,10 @@ export function getConversionReport({
|
||||
return tool({
|
||||
description:
|
||||
'Generate a report (a chart) for conversions between two actions a unique user took.',
|
||||
parameters: zChartInputAI,
|
||||
parameters: zReportInput.extend({
|
||||
startDate: z.string().describe('The start date for the report'),
|
||||
endDate: z.string().describe('The end date for the report'),
|
||||
}),
|
||||
execute: async (report) => {
|
||||
return {
|
||||
type: 'report',
|
||||
@@ -94,7 +100,10 @@ export function getFunnelReport({
|
||||
return tool({
|
||||
description:
|
||||
'Generate a report (a chart) for funnel between two or more actions a unique user (session_id or profile_id) took.',
|
||||
parameters: zChartInputAI,
|
||||
parameters: zReportInput.extend({
|
||||
startDate: z.string().describe('The start date for the report'),
|
||||
endDate: z.string().describe('The end date for the report'),
|
||||
}),
|
||||
execute: async (report) => {
|
||||
return {
|
||||
type: 'report',
|
||||
|
||||
@@ -4,10 +4,11 @@ import { verifyPassword } from '@openpanel/common/server';
|
||||
import type { IServiceClientWithProject } from '@openpanel/db';
|
||||
import { ClientType, getClientByIdCached } from '@openpanel/db';
|
||||
import { getCache } from '@openpanel/redis';
|
||||
import type { PostEventPayload, TrackHandlerPayload } from '@openpanel/sdk';
|
||||
import type {
|
||||
DeprecatedPostEventPayload,
|
||||
IProjectFilterIp,
|
||||
IProjectFilterProfileId,
|
||||
ITrackHandlerPayload,
|
||||
} from '@openpanel/validation';
|
||||
import { path } from 'ramda';
|
||||
|
||||
@@ -41,7 +42,7 @@ export class SdkAuthError extends Error {
|
||||
|
||||
export async function validateSdkRequest(
|
||||
req: FastifyRequest<{
|
||||
Body: PostEventPayload | TrackHandlerPayload;
|
||||
Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
|
||||
}>,
|
||||
): Promise<IServiceClientWithProject> {
|
||||
const { headers, clientIp } = req;
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import urlMetadata from 'url-metadata';
|
||||
|
||||
function fallbackFavicon(url: string) {
|
||||
return `https://www.google.com/s2/favicons?domain=${url}&sz=256`;
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return `https://icons.duckduckgo.com/ip3/${hostname}.ico`;
|
||||
} catch {
|
||||
// If URL parsing fails, use the original string
|
||||
return `https://icons.duckduckgo.com/ip3/${url}.ico`;
|
||||
}
|
||||
}
|
||||
|
||||
function findBestFavicon(favicons: UrlMetaData['favicons']) {
|
||||
|
||||
BIN
apps/justfuckinguseopenpanel/favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
505
apps/justfuckinguseopenpanel/index.html
Normal file
@@ -0,0 +1,505 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<!-- Primary Meta Tags -->
|
||||
<title>Just Fucking Use OpenPanel - Stop Overpaying for Analytics</title>
|
||||
<meta name="title" content="Just Fucking Use OpenPanel - Stop Overpaying for Analytics">
|
||||
<meta name="description" content="Mixpanel costs $2,300/month at scale. PostHog costs $1,982/month. Web-only tools tell you nothing about user behavior. OpenPanel gives you full product analytics for a fraction of the cost, or FREE self-hosted.">
|
||||
<meta name="keywords" content="openpanel, analytics, mixpanel alternative, posthog alternative, product analytics, web analytics, open source analytics, self-hosted analytics">
|
||||
<meta name="author" content="OpenPanel">
|
||||
<meta name="robots" content="index, follow">
|
||||
<link rel="canonical" href="https://justfuckinguseopenpanel.dev/">
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico">
|
||||
|
||||
<!-- Open Graph / Facebook -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="https://justfuckinguseopenpanel.dev/">
|
||||
<meta property="og:title" content="Just Fucking Use OpenPanel - Stop Overpaying for Analytics">
|
||||
<meta property="og:description" content="Mixpanel costs $2,300/month at scale. PostHog costs $1,982/month. Web-only tools tell you nothing about user behavior. OpenPanel gives you full product analytics for a fraction of the cost, or FREE self-hosted.">
|
||||
<meta property="og:image" content="/ogimage.png">
|
||||
<meta property="og:image:width" content="1200">
|
||||
<meta property="og:image:height" content="630">
|
||||
<meta property="og:site_name" content="Just Fucking Use OpenPanel">
|
||||
|
||||
<!-- Twitter -->
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:url" content="https://justfuckinguseopenpanel.dev/">
|
||||
<meta name="twitter:title" content="Just Fucking Use OpenPanel - Stop Overpaying for Analytics">
|
||||
<meta name="twitter:description" content="Mixpanel costs $2,300/month at scale. PostHog costs $1,982/month. Web-only tools tell you nothing about user behavior. OpenPanel gives you full product analytics for a fraction of the cost, or FREE self-hosted.">
|
||||
<meta name="twitter:image" content="/ogimage.png">
|
||||
|
||||
<!-- Additional Meta Tags -->
|
||||
<meta name="theme-color" content="#0a0a0a">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
background: #0a0a0a;
|
||||
color: #e5e5e5;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
font-size: 18px;
|
||||
line-height: 1.75;
|
||||
padding: 2rem 1.5rem;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 700px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
margin-bottom: 0.5rem;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.875rem;
|
||||
font-weight: 800;
|
||||
line-height: 1.3;
|
||||
margin-top: 3rem;
|
||||
margin-bottom: 1.5rem;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.4;
|
||||
margin-top: 2rem;
|
||||
margin-bottom: 1rem;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-bottom: 1.25em;
|
||||
}
|
||||
|
||||
strong {
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #3b82f6;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
ul, ol {
|
||||
margin-left: 1.5rem;
|
||||
margin-bottom: 1.25em;
|
||||
}
|
||||
|
||||
li {
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 4px solid #3b82f6;
|
||||
padding-left: 1.5rem;
|
||||
margin: 1.5rem 0;
|
||||
font-style: italic;
|
||||
color: #d1d5db;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 2rem 0;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 0.75rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #374151;
|
||||
}
|
||||
|
||||
th {
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
background: #131313;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background: #131313;
|
||||
}
|
||||
|
||||
.screenshot {
|
||||
margin: 0 -4rem 4rem;
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
@media (max-width: 840px) {
|
||||
.screenshot {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.screenshot-inner {
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
padding: 0.5rem;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #2a2a2a;
|
||||
}
|
||||
|
||||
.window-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
padding: 0 0.25rem;
|
||||
}
|
||||
|
||||
.window-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.window-dot.red {
|
||||
background: #ef4444;
|
||||
}
|
||||
|
||||
.window-dot.yellow {
|
||||
background: #eab308;
|
||||
}
|
||||
|
||||
.window-dot.green {
|
||||
background: #22c55e;
|
||||
}
|
||||
|
||||
.screenshot-image-wrapper {
|
||||
width: 100%;
|
||||
border: 1px solid #2a2a2a;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background: #0a0a0a;
|
||||
}
|
||||
|
||||
.screenshot img {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.cta {
|
||||
background: #131313;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 2rem;
|
||||
margin: 3rem 0;
|
||||
text-align: center;
|
||||
margin: 0 -4rem 4rem;
|
||||
}
|
||||
|
||||
@media (max-width: 840px) {
|
||||
.cta {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.cta h2 {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.cta a {
|
||||
display: inline-block;
|
||||
background: #fff;
|
||||
color: #000;
|
||||
padding: 0.75rem 1.5rem;
|
||||
border-radius: 6px;
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
margin: 0.5rem;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.cta a:hover {
|
||||
background: #fff;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 4rem;
|
||||
padding-top: 2rem;
|
||||
border-top: 1px solid #374151;
|
||||
text-align: center;
|
||||
color: #9ca3af;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.hero {
|
||||
text-align: left;
|
||||
margin-top: 4rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.hero p {
|
||||
font-size: 1.25rem;
|
||||
color: #8f8f8f;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
figcaption {
|
||||
margin-top: 1rem;
|
||||
font-size: 0.875rem;
|
||||
text-align: center;
|
||||
color: #9ca3af;
|
||||
max-width: 100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="hero">
|
||||
<h1>Just Fucking Use OpenPanel</h1>
|
||||
<p>Stop settling for basic metrics. Get real insights that actually help you build a better product.</p>
|
||||
</div>
|
||||
|
||||
<figure class="screenshot">
|
||||
<div class="screenshot-inner">
|
||||
<div class="window-controls">
|
||||
<div class="window-dot red"></div>
|
||||
<div class="window-dot yellow"></div>
|
||||
<div class="window-dot green"></div>
|
||||
</div>
|
||||
<div class="screenshot-image-wrapper">
|
||||
<img src="screenshots/realtime-dark.webp" alt="OpenPanel Real-time Analytics" width="1400" height="800">
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>Real-time analytics - see events as they happen. No waiting, no delays.</figcaption>
|
||||
</figure>
|
||||
|
||||
<h2>The PostHog/Mixpanel Problem (Volume Pricing Hell)</h2>
|
||||
|
||||
<p>Let's talk about what happens when you have a <strong>real product</strong> with <strong>real users</strong>.</p>
|
||||
|
||||
<p><strong>Real pricing at scale (20M+ events/month):</strong></p>
|
||||
<ul>
|
||||
<li><strong>Mixpanel</strong>: $2,300/month (and more with add-ons)</li>
|
||||
<li><strong>PostHog</strong>: $1,982/month (and more with add-ons)</li>
|
||||
</ul>
|
||||
|
||||
<p>"1 million free events!" they scream. Cute. Until you have an actual product with actual users doing actual things. Then suddenly you need to "talk to sales" and your wallet starts bleeding.</p>
|
||||
|
||||
<p>Add-ons, add-ons everywhere. Session replay? +$X. Feature flags? +$X. HIPAA compliance? +$250/month. A/B testing? That'll be extra. You're hemorrhaging money just to understand what your users are doing, you magnificent fool.</p>
|
||||
|
||||
<h2>The Web-Only Analytics Trap</h2>
|
||||
|
||||
<p>You built a great fucking product. You have real traffic. Thousands, tens of thousands of visitors. But you're flying blind.</p>
|
||||
|
||||
<blockquote>
|
||||
"Congrats, 50,000 visitors from France this month. Why didn't a single one buy your baguette?"
|
||||
</blockquote>
|
||||
|
||||
<p>You see the traffic. You see the bounce rate. You see the referrers. You see where they're from. You have <strong>NO FUCKING IDEA</strong> what users actually do.</p>
|
||||
|
||||
<p>Where do they drop off? Do they come back? What features do they use? Why didn't they convert? Who the fuck knows! You're using a glorified hit counter with a pretty dashboard that tells you everything about geography and nothing about behavior.</p>
|
||||
|
||||
<p>Plausible. Umami. Fathom. Simple Analytics. GoatCounter. Cabin. Pirsch. They're all the same story: simple analytics with some goals you can define. Page views, visitors, countries, basic funnels. That's it. No retention analysis. No user profiles. No event tracking. No cohorts. No revenue tracking. Just... basic web analytics.</p>
|
||||
|
||||
<p>And when you finally need to understand your users—when you need to see where they drop off in your signup flow, or which features drive retention, or why your conversion rate is shit—you end up paying for a <strong>SECOND tool</strong> on top. Now you're paying for two subscriptions, managing two dashboards, and your users' data is split across two platforms like a bad divorce.</p>
|
||||
|
||||
<h2>Counter One Dollar Stats</h2>
|
||||
|
||||
<p>"$1/month for page views. Adorable."</p>
|
||||
|
||||
<p>Look, I get it. A dollar is cheap. But you're getting exactly what you pay for: page views. That's it. No funnels. No retention. No user profiles. No event tracking. Just... page views.</p>
|
||||
|
||||
<p>Here's the thing: if you want to make <strong>good decisions</strong> about your product, you need to understand <strong>what your users are actually doing</strong>, not just where the fuck they're from.</p>
|
||||
|
||||
<p>OpenPanel gives you the full product analytics suite. Or self-host for <strong>FREE</strong> with <strong>UNLIMITED events</strong>.</p>
|
||||
|
||||
<p>You get:</p>
|
||||
<ul>
|
||||
<li>Funnels to see where users drop off</li>
|
||||
<li>Retention analysis to see who comes back</li>
|
||||
<li>Cohorts to segment your users</li>
|
||||
<li>User profiles to understand individual behavior</li>
|
||||
<li>Custom dashboards to see what matters to YOU</li>
|
||||
<li>Revenue tracking to see what actually makes money</li>
|
||||
<li>All the web analytics (page views, visitors, referrers) that the other tools give you</li>
|
||||
</ul>
|
||||
|
||||
<p>One Dollar Stats tells you 50,000 people visited from France. OpenPanel tells you why they didn't buy your baguette. That's the difference between vanity metrics and actual insights.</p>
|
||||
|
||||
<h2>Why OpenPanel is the Answer</h2>
|
||||
|
||||
<p>You want analytics that actually help you build a better product. Not vanity metrics. Not enterprise pricing. Not two separate tools.</p>
|
||||
|
||||
<p>To make good decisions, you need to understand <strong>what your users are doing</strong>, not just where they're from. You need to see where they drop off. You need to know which features they use. You need to understand why they convert or why they don't.</p>
|
||||
|
||||
<ul>
|
||||
<li><strong>Open Source & Self-Hostable</strong>: AGPL-3.0 - fork it, audit it, own it. Self-host for FREE with unlimited events, or use our cloud</li>
|
||||
<li><strong>Price</strong>: Affordable pricing that scales, or FREE self-hosted (unlimited events, forever)</li>
|
||||
<li><strong>SDK Size</strong>: 2.3KB (PostHog is 52KB+ - that's 22x bigger, you performance-obsessed maniac)</li>
|
||||
<li><strong>Privacy</strong>: Cookie-free by default, EU-only hosting (or your own servers if you self-host)</li>
|
||||
<li><strong>Full Suite</strong>: Web analytics + product analytics in one tool. No need for two subscriptions.</li>
|
||||
</ul>
|
||||
|
||||
<figure class="screenshot">
|
||||
<div class="screenshot-inner">
|
||||
<div class="window-controls">
|
||||
<div class="window-dot red"></div>
|
||||
<div class="window-dot yellow"></div>
|
||||
<div class="window-dot green"></div>
|
||||
</div>
|
||||
<div class="screenshot-image-wrapper">
|
||||
<img src="screenshots/overview-dark.webp" alt="OpenPanel Overview Dashboard" width="1400" height="800">
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>OpenPanel overview showing web analytics and product analytics in one clean interface</figcaption>
|
||||
</figure>
|
||||
|
||||
<h2>Open Source & Self-Hosting: The Ultimate Fuck You to Pricing Hell</h2>
|
||||
|
||||
<p>Tired of watching your analytics bill grow every month? Tired of "talk to sales" when you hit their arbitrary limits? Tired of paying $2,000+/month just to understand your users?</p>
|
||||
|
||||
<p><strong>OpenPanel is open source.</strong> AGPL-3.0 licensed. You can fork it. You can audit it. You can own it. And you can <strong>self-host it for FREE with UNLIMITED events</strong>.</p>
|
||||
|
||||
<p>That's right. Zero dollars. Unlimited events. All the features. Your data on your servers. No vendor lock-in. No surprise bills. No "enterprise sales" calls.</p>
|
||||
|
||||
<p>Mixpanel at 20M events? $2,300/month. PostHog? $1,982/month. OpenPanel self-hosted? <strong>$0/month</strong>. Forever.</p>
|
||||
|
||||
<p>Don't want to manage infrastructure? That's fine. Use our cloud. But if you want to escape the pricing hell entirely, self-hosting is a Docker command away. Your data, your rules, your wallet.</p>
|
||||
|
||||
<h2>The Comparison Table (The Brutal Truth)</h2>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Tool</th>
|
||||
<th>Price at 20M events</th>
|
||||
<th>What You Get</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>Mixpanel</strong></td>
|
||||
<td>$2,300+/month</td>
|
||||
<td>Not all feautres... since addons are extra</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>PostHog</strong></td>
|
||||
<td>$1,982+/month</td>
|
||||
<td>Not all feautres... since addons are extra</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Plausible</strong></td>
|
||||
<td>Various pricing</td>
|
||||
<td>Simple analytics with basic goals. Page views and visitors. That's it.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>One Dollar Stats</strong></td>
|
||||
<td>$1/month</td>
|
||||
<td>Page views (but cheaper!)</td>
|
||||
</tr>
|
||||
<tr style="background: #131313; border: 2px solid #3b82f6;">
|
||||
<td><strong>OpenPanel</strong></td>
|
||||
<td><strong>~$530/mo or FREE (self-hosted)</strong></td>
|
||||
<td><strong>Web + Product analytics. The full package. Open source. Your data.</strong></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<figure class="screenshot">
|
||||
<div class="screenshot-inner">
|
||||
<div class="window-controls">
|
||||
<div class="window-dot red"></div>
|
||||
<div class="window-dot yellow"></div>
|
||||
<div class="window-dot green"></div>
|
||||
</div>
|
||||
<div class="screenshot-image-wrapper">
|
||||
<img src="screenshots/profile-dark.webp" alt="OpenPanel User Profiles" width="1400" height="800">
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>User profiles - see individual user journeys and behavior. Something web-only tools can't give you.</figcaption>
|
||||
</figure>
|
||||
|
||||
<figure class="screenshot">
|
||||
<div class="screenshot-inner">
|
||||
<div class="window-controls">
|
||||
<div class="window-dot red"></div>
|
||||
<div class="window-dot yellow"></div>
|
||||
<div class="window-dot green"></div>
|
||||
</div>
|
||||
<div class="screenshot-image-wrapper">
|
||||
<img src="screenshots/report-dark.webp" alt="OpenPanel Reports and Funnels" width="1400" height="800">
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>Funnels, retention, and custom reports - the features you CAN'T get with web-only tools</figcaption>
|
||||
</figure>
|
||||
|
||||
<h2>The Bottom Fucking Line</h2>
|
||||
|
||||
<p>If you want to make good decisions about your product, you need to understand what your users are actually doing. Not just where they're from. Not just how many page views you got. You need to see the full picture: funnels, retention, user behavior, conversion paths.</p>
|
||||
|
||||
<p>You have three choices:</p>
|
||||
|
||||
<ol>
|
||||
<li>Keep using Google Analytics like a data-harvesting accomplice, adding cookie banners, annoying your users, and contributing to the dystopian surveillance economy</li>
|
||||
<li>Pay $2,000+/month for Mixpanel or PostHog when you scale, or use simple web-only analytics that tell you nothing about user behavior—just where they're from</li>
|
||||
<li>Use OpenPanel (affordable pricing or FREE self-hosted) and get the full analytics suite: web analytics AND product analytics in one tool, so you can actually understand what your users do</li>
|
||||
</ol>
|
||||
|
||||
<p>If you picked option 1 or 2, I can't help you. You're beyond saving. Go enjoy your complicated, privacy-violating, overpriced analytics life where you know everything about where your users are from but nothing about what they actually do.</p>
|
||||
|
||||
<p>But if you have even one functioning brain cell, you'll realize that OpenPanel gives you everything you need—web analytics AND product analytics—for a fraction of what the enterprise tools cost. You'll finally understand what your users are doing, not just where the fuck they're from.</p>
|
||||
|
||||
<div class="cta">
|
||||
<h2>Ready to understand what your users actually do?</h2>
|
||||
<p>Stop settling for vanity metrics. Get the full analytics suite—web analytics AND product analytics—so you can make better decisions. Or self-host for free.</p>
|
||||
<a href="https://openpanel.dev" target="_blank">Get Started with OpenPanel</a>
|
||||
<a href="https://openpanel.dev/docs/self-hosting/self-hosting" target="_blank">Self-Host Guide</a>
|
||||
</div>
|
||||
|
||||
<figure class="screenshot">
|
||||
<div class="screenshot-inner">
|
||||
<div class="window-controls">
|
||||
<div class="window-dot red"></div>
|
||||
<div class="window-dot yellow"></div>
|
||||
<div class="window-dot green"></div>
|
||||
</div>
|
||||
<div class="screenshot-image-wrapper">
|
||||
<img src="screenshots/dashboard-dark.webp" alt="OpenPanel Custom Dashboards" width="1400" height="800">
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>Custom dashboards - build exactly what you need to understand your product</figcaption>
|
||||
</figure>
|
||||
|
||||
<footer>
|
||||
<p><strong>Just Fucking Use OpenPanel</strong></p>
|
||||
<p>Inspired by <a href="https://justfuckingusereact.com" target="_blank" rel="nofollow">justfuckingusereact.com</a>, <a href="https://justfuckingusehtml.com" target="_blank" rel="nofollow">justfuckingusehtml.com</a>, and <a href="https://justfuckinguseonedollarstats.com" target="_blank" rel="nofollow">justfuckinguseonedollarstats.com</a> and all other just fucking use sites.</p>
|
||||
<p style="margin-top: 1rem;">This is affiliated with <a href="https://openpanel.dev" target="_blank" rel="nofollow">OpenPanel</a>. We still love all products mentioned in this website, and we're grateful for them and what they do 🫶</p>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.op=window.op||function(){var n=[];return new Proxy(function(){arguments.length&&n.push([].slice.call(arguments))},{get:function(t,r){return"q"===r?n:function(){n.push([r].concat([].slice.call(arguments)))}} ,has:function(t,r){return"q"===r}}) }();
|
||||
window.op('init', {
|
||||
clientId: '59d97757-9449-44cf-a8c1-8f213843b4f0',
|
||||
trackScreenViews: true,
|
||||
trackOutgoingLinks: true,
|
||||
trackAttributes: true,
|
||||
});
|
||||
</script>
|
||||
<script src="https://openpanel.dev/op1.js" defer async></script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
apps/justfuckinguseopenpanel/ogimage.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
apps/justfuckinguseopenpanel/screenshots/dashboard-dark.webp
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
apps/justfuckinguseopenpanel/screenshots/overview-dark.webp
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
apps/justfuckinguseopenpanel/screenshots/profile-dark.webp
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
apps/justfuckinguseopenpanel/screenshots/realtime-dark.webp
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
apps/justfuckinguseopenpanel/screenshots/report-dark.webp
Normal file
|
After Width: | Height: | Size: 47 KiB |
7
apps/justfuckinguseopenpanel/wrangler.jsonc
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "justfuckinguseopenpanel",
|
||||
"compatibility_date": "2025-12-19",
|
||||
"assets": {
|
||||
"directory": "."
|
||||
}
|
||||
}
|
||||
256
apps/public/content/docs/(tracking)/sdks/nuxt.mdx
Normal file
@@ -0,0 +1,256 @@
|
||||
---
|
||||
title: Nuxt
|
||||
---
|
||||
|
||||
import Link from 'next/link';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
|
||||
import { DeviceIdWarning } from '@/components/device-id-warning';
|
||||
import { PersonalDataWarning } from '@/components/personal-data-warning';
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import CommonSdkConfig from '@/components/common-sdk-config.mdx';
|
||||
import WebSdkConfig from '@/components/web-sdk-config.mdx';
|
||||
|
||||
<Callout>
|
||||
Looking for a step-by-step tutorial? Check out the [Nuxt analytics guide](/guides/nuxt-analytics).
|
||||
</Callout>
|
||||
|
||||
## Good to know
|
||||
|
||||
Keep in mind that all tracking here happens on the client!
|
||||
|
||||
Read more about server side tracking in the [Server Side Tracking](#track-server-events) section.
|
||||
|
||||
## Installation
|
||||
|
||||
<Steps>
|
||||
### Install dependencies
|
||||
|
||||
```bash
|
||||
pnpm install @openpanel/nuxt
|
||||
```
|
||||
|
||||
### Initialize
|
||||
|
||||
Add the module to your `nuxt.config.ts`:
|
||||
|
||||
```typescript
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@openpanel/nuxt'],
|
||||
openpanel: {
|
||||
clientId: 'your-client-id',
|
||||
trackScreenViews: true,
|
||||
trackOutgoingLinks: true,
|
||||
trackAttributes: true,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Options
|
||||
|
||||
<CommonSdkConfig />
|
||||
<WebSdkConfig />
|
||||
|
||||
##### Nuxt options
|
||||
|
||||
- `clientId` - Your OpenPanel client ID (required)
|
||||
- `apiUrl` - The API URL to send events to (default: `https://api.openpanel.dev`)
|
||||
- `trackScreenViews` - Automatically track screen views (default: `true`)
|
||||
- `trackOutgoingLinks` - Automatically track outgoing links (default: `true`)
|
||||
- `trackAttributes` - Automatically track elements with `data-track` attributes (default: `true`)
|
||||
- `trackHashChanges` - Track hash changes in URL (default: `false`)
|
||||
- `disabled` - Disable tracking (default: `false`)
|
||||
- `proxy` - Enable server-side proxy to avoid adblockers (default: `false`)
|
||||
|
||||
</Steps>
|
||||
|
||||
## Usage
|
||||
|
||||
### Using the composable
|
||||
|
||||
The `useOpenPanel` composable is auto-imported, so you can use it directly in any component:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel(); // Auto-imported!
|
||||
|
||||
function handleClick() {
|
||||
op.track('button_click', { button: 'signup' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleClick">Trigger event</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Accessing via useNuxtApp
|
||||
|
||||
You can also access the OpenPanel instance directly via `useNuxtApp()`:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const { $openpanel } = useNuxtApp();
|
||||
|
||||
$openpanel.track('my_event', { foo: 'bar' });
|
||||
</script>
|
||||
```
|
||||
|
||||
### Tracking Events
|
||||
|
||||
You can track events with two different methods: by calling the `op.track()` method directly or by adding `data-track` attributes to your HTML elements.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
op.track('my_event', { foo: 'bar' });
|
||||
</script>
|
||||
```
|
||||
|
||||
### Identifying Users
|
||||
|
||||
To identify a user, call the `op.identify()` method with a unique identifier.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
op.identify({
|
||||
profileId: '123', // Required
|
||||
firstName: 'Joe',
|
||||
lastName: 'Doe',
|
||||
email: 'joe@doe.com',
|
||||
properties: {
|
||||
tier: 'premium',
|
||||
},
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Setting Global Properties
|
||||
|
||||
To set properties that will be sent with every event:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
op.setGlobalProperties({
|
||||
app_version: '1.0.2',
|
||||
environment: 'production',
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Incrementing Properties
|
||||
|
||||
To increment a numeric property on a user profile.
|
||||
|
||||
- `value` is the amount to increment the property by. If not provided, the property will be incremented by 1.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
op.increment({
|
||||
profileId: '1',
|
||||
property: 'visits',
|
||||
value: 1, // optional
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Decrementing Properties
|
||||
|
||||
To decrement a numeric property on a user profile.
|
||||
|
||||
- `value` is the amount to decrement the property by. If not provided, the property will be decremented by 1.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
op.decrement({
|
||||
profileId: '1',
|
||||
property: 'visits',
|
||||
value: 1, // optional
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Clearing User Data
|
||||
|
||||
To clear the current user's data:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
op.clear();
|
||||
</script>
|
||||
```
|
||||
|
||||
## Server side
|
||||
|
||||
If you want to track server-side events, you should create an instance of our Javascript SDK. Import `OpenPanel` from `@openpanel/sdk`
|
||||
|
||||
<Callout>
|
||||
When using server events it's important that you use a secret to authenticate the request. This is to prevent unauthorized requests since we cannot use cors headers.
|
||||
|
||||
You can use the same clientId but you should pass the associated client secret to the SDK.
|
||||
|
||||
</Callout>
|
||||
|
||||
```typescript
|
||||
import { OpenPanel } from '@openpanel/sdk';
|
||||
|
||||
const opServer = new OpenPanel({
|
||||
clientId: '{YOUR_CLIENT_ID}',
|
||||
clientSecret: '{YOUR_CLIENT_SECRET}',
|
||||
});
|
||||
|
||||
opServer.track('my_server_event', { ok: '✅' });
|
||||
|
||||
// Pass `profileId` to track events for a specific user
|
||||
opServer.track('my_server_event', { profileId: '123', ok: '✅' });
|
||||
```
|
||||
|
||||
### Serverless & Edge Functions
|
||||
|
||||
If you log events in a serverless environment, make sure to await the event call to ensure it completes before the function terminates.
|
||||
|
||||
```typescript
|
||||
import { OpenPanel } from '@openpanel/sdk';
|
||||
|
||||
const opServer = new OpenPanel({
|
||||
clientId: '{YOUR_CLIENT_ID}',
|
||||
clientSecret: '{YOUR_CLIENT_SECRET}',
|
||||
});
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Await to ensure event is logged before function completes
|
||||
await opServer.track('my_server_event', { foo: 'bar' });
|
||||
return { message: 'Event logged!' };
|
||||
});
|
||||
```
|
||||
|
||||
### Proxy events
|
||||
|
||||
With the `proxy` option enabled, you can proxy your events through your server, which ensures all events are tracked since many adblockers block requests to third-party domains.
|
||||
|
||||
```typescript title="nuxt.config.ts"
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@openpanel/nuxt'],
|
||||
openpanel: {
|
||||
clientId: 'your-client-id',
|
||||
proxy: true, // Enables proxy at /api/openpanel/*
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
When `proxy: true` is set:
|
||||
- The module automatically sets `apiUrl` to `/api/openpanel`
|
||||
- A server handler is registered at `/api/openpanel/**`
|
||||
- All tracking requests route through your server
|
||||
|
||||
This helps bypass adblockers that might block requests to `api.openpanel.dev`.
|
||||
@@ -2,4 +2,244 @@
|
||||
title: React
|
||||
---
|
||||
|
||||
Use [script tag](/docs/sdks/script) or [Web SDK](/docs/sdks/web) for now. We'll add a dedicated react sdk soon.
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
|
||||
import { PersonalDataWarning } from '@/components/personal-data-warning';
|
||||
import CommonSdkConfig from '@/components/common-sdk-config.mdx';
|
||||
import WebSdkConfig from '@/components/web-sdk-config.mdx';
|
||||
|
||||
## Good to know
|
||||
|
||||
Keep in mind that all tracking here happens on the client!
|
||||
|
||||
For React SPAs, you can use `@openpanel/web` directly - no need for a separate React SDK. Simply create an OpenPanel instance and use it throughout your application.
|
||||
|
||||
## Installation
|
||||
|
||||
<Steps>
|
||||
### Step 1: Install
|
||||
|
||||
```bash
|
||||
npm install @openpanel/web
|
||||
```
|
||||
|
||||
### Step 2: Initialize
|
||||
|
||||
Create a shared OpenPanel instance in your project:
|
||||
|
||||
```ts title="src/openpanel.ts"
|
||||
import { OpenPanel } from '@openpanel/web';
|
||||
|
||||
export const op = new OpenPanel({
|
||||
clientId: 'YOUR_CLIENT_ID',
|
||||
trackScreenViews: true,
|
||||
trackOutgoingLinks: true,
|
||||
trackAttributes: true,
|
||||
});
|
||||
```
|
||||
|
||||
#### Options
|
||||
|
||||
<CommonSdkConfig />
|
||||
<WebSdkConfig />
|
||||
|
||||
- `clientId` - Your OpenPanel client ID (required)
|
||||
- `apiUrl` - The API URL to send events to (default: `https://api.openpanel.dev`)
|
||||
- `trackScreenViews` - Automatically track screen views (default: `true`)
|
||||
- `trackOutgoingLinks` - Automatically track outgoing links (default: `true`)
|
||||
- `trackAttributes` - Automatically track elements with `data-track` attributes (default: `true`)
|
||||
- `trackHashChanges` - Track hash changes in URL (default: `false`)
|
||||
- `disabled` - Disable tracking (default: `false`)
|
||||
|
||||
### Step 3: Usage
|
||||
|
||||
Import and use the instance in your React components:
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function MyComponent() {
|
||||
const handleClick = () => {
|
||||
op.track('button_click', { button: 'signup' });
|
||||
};
|
||||
|
||||
return <button onClick={handleClick}>Trigger event</button>;
|
||||
}
|
||||
```
|
||||
|
||||
</Steps>
|
||||
|
||||
## Usage
|
||||
|
||||
### Tracking Events
|
||||
|
||||
You can track events with two different methods: by calling the `op.track()` method directly or by adding `data-track` attributes to your HTML elements.
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function MyComponent() {
|
||||
useEffect(() => {
|
||||
op.track('my_event', { foo: 'bar' });
|
||||
}, []);
|
||||
|
||||
return <div>My Component</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### Identifying Users
|
||||
|
||||
To identify a user, call the `op.identify()` method with a unique identifier.
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function LoginComponent() {
|
||||
const handleLogin = (user: User) => {
|
||||
op.identify({
|
||||
profileId: user.id, // Required
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
email: user.email,
|
||||
properties: {
|
||||
tier: 'premium',
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return <button onClick={() => handleLogin(user)}>Login</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Setting Global Properties
|
||||
|
||||
To set properties that will be sent with every event:
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
op.setGlobalProperties({
|
||||
app_version: '1.0.2',
|
||||
environment: 'production',
|
||||
});
|
||||
}, []);
|
||||
|
||||
return <div>App</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### Incrementing Properties
|
||||
|
||||
To increment a numeric property on a user profile.
|
||||
|
||||
- `value` is the amount to increment the property by. If not provided, the property will be incremented by 1.
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function MyComponent() {
|
||||
const handleAction = () => {
|
||||
op.increment({
|
||||
profileId: '1',
|
||||
property: 'visits',
|
||||
value: 1, // optional
|
||||
});
|
||||
};
|
||||
|
||||
return <button onClick={handleAction}>Increment</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Decrementing Properties
|
||||
|
||||
To decrement a numeric property on a user profile.
|
||||
|
||||
- `value` is the amount to decrement the property by. If not provided, the property will be decremented by 1.
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function MyComponent() {
|
||||
const handleAction = () => {
|
||||
op.decrement({
|
||||
profileId: '1',
|
||||
property: 'visits',
|
||||
value: 1, // optional
|
||||
});
|
||||
};
|
||||
|
||||
return <button onClick={handleAction}>Decrement</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Clearing User Data
|
||||
|
||||
To clear the current user's data:
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function LogoutComponent() {
|
||||
const handleLogout = () => {
|
||||
op.clear();
|
||||
// ... logout logic
|
||||
};
|
||||
|
||||
return <button onClick={handleLogout}>Logout</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Revenue Tracking
|
||||
|
||||
Track revenue events:
|
||||
|
||||
```tsx
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function CheckoutComponent() {
|
||||
const handlePurchase = async () => {
|
||||
// Track revenue immediately
|
||||
await op.revenue(29.99, { currency: 'USD' });
|
||||
|
||||
// Or accumulate revenue and flush later
|
||||
op.pendingRevenue(29.99, { currency: 'USD' });
|
||||
op.pendingRevenue(19.99, { currency: 'USD' });
|
||||
await op.flushRevenue(); // Sends both revenue events
|
||||
|
||||
// Clear pending revenue
|
||||
op.clearRevenue();
|
||||
};
|
||||
|
||||
return <button onClick={handlePurchase}>Purchase</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Optional: Create a Hook
|
||||
|
||||
If you prefer using a React hook pattern, you can create your own wrapper:
|
||||
|
||||
```ts title="src/hooks/useOpenPanel.ts"
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
export function useOpenPanel() {
|
||||
return op;
|
||||
}
|
||||
```
|
||||
|
||||
Then use it in your components:
|
||||
|
||||
```tsx
|
||||
import { useOpenPanel } from '@/hooks/useOpenPanel';
|
||||
|
||||
function MyComponent() {
|
||||
const op = useOpenPanel();
|
||||
|
||||
useEffect(() => {
|
||||
op.track('my_event', { foo: 'bar' });
|
||||
}, []);
|
||||
|
||||
return <div>My Component</div>;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -2,4 +2,219 @@
|
||||
title: Vue
|
||||
---
|
||||
|
||||
Use [script tag](/docs/sdks/script) or [Web SDK](/docs/sdks/web) for now. We'll add a dedicated vue sdk soon.
|
||||
import Link from 'next/link';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
|
||||
import { DeviceIdWarning } from '@/components/device-id-warning';
|
||||
import { PersonalDataWarning } from '@/components/personal-data-warning';
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import CommonSdkConfig from '@/components/common-sdk-config.mdx';
|
||||
import WebSdkConfig from '@/components/web-sdk-config.mdx';
|
||||
|
||||
<Callout>
|
||||
Looking for a step-by-step tutorial? Check out the [Vue analytics guide](/guides/vue-analytics).
|
||||
</Callout>
|
||||
|
||||
## Good to know
|
||||
|
||||
Keep in mind that all tracking here happens on the client!
|
||||
|
||||
For Vue SPAs, you can use `@openpanel/web` directly - no need for a separate Vue SDK. Simply create an OpenPanel instance and use it throughout your application.
|
||||
|
||||
## Installation
|
||||
|
||||
<Steps>
|
||||
### Step 1: Install
|
||||
|
||||
```bash
|
||||
pnpm install @openpanel/web
|
||||
```
|
||||
|
||||
### Step 2: Initialize
|
||||
|
||||
Create a shared OpenPanel instance in your project:
|
||||
|
||||
```ts title="src/openpanel.ts"
|
||||
import { OpenPanel } from '@openpanel/web';
|
||||
|
||||
export const op = new OpenPanel({
|
||||
clientId: 'YOUR_CLIENT_ID',
|
||||
trackScreenViews: true,
|
||||
trackOutgoingLinks: true,
|
||||
trackAttributes: true,
|
||||
});
|
||||
```
|
||||
|
||||
#### Options
|
||||
|
||||
<CommonSdkConfig />
|
||||
<WebSdkConfig />
|
||||
|
||||
- `clientId` - Your OpenPanel client ID (required)
|
||||
- `apiUrl` - The API URL to send events to (default: `https://api.openpanel.dev`)
|
||||
- `trackScreenViews` - Automatically track screen views (default: `true`)
|
||||
- `trackOutgoingLinks` - Automatically track outgoing links (default: `true`)
|
||||
- `trackAttributes` - Automatically track elements with `data-track` attributes (default: `true`)
|
||||
- `trackHashChanges` - Track hash changes in URL (default: `false`)
|
||||
- `disabled` - Disable tracking (default: `false`)
|
||||
|
||||
### Step 3: Usage
|
||||
|
||||
Import and use the instance in your Vue components:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
function handleClick() {
|
||||
op.track('button_click', { button: 'signup' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleClick">Trigger event</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
</Steps>
|
||||
|
||||
## Usage
|
||||
|
||||
### Tracking Events
|
||||
|
||||
You can track events with two different methods: by calling the `op.track()` method directly or by adding `data-track` attributes to your HTML elements.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
op.track('my_event', { foo: 'bar' });
|
||||
</script>
|
||||
```
|
||||
|
||||
### Identifying Users
|
||||
|
||||
To identify a user, call the `op.identify()` method with a unique identifier.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
op.identify({
|
||||
profileId: '123', // Required
|
||||
firstName: 'Joe',
|
||||
lastName: 'Doe',
|
||||
email: 'joe@doe.com',
|
||||
properties: {
|
||||
tier: 'premium',
|
||||
},
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Setting Global Properties
|
||||
|
||||
To set properties that will be sent with every event:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
op.setGlobalProperties({
|
||||
app_version: '1.0.2',
|
||||
environment: 'production',
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Incrementing Properties
|
||||
|
||||
To increment a numeric property on a user profile.
|
||||
|
||||
- `value` is the amount to increment the property by. If not provided, the property will be incremented by 1.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
op.increment({
|
||||
profileId: '1',
|
||||
property: 'visits',
|
||||
value: 1, // optional
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Decrementing Properties
|
||||
|
||||
To decrement a numeric property on a user profile.
|
||||
|
||||
- `value` is the amount to decrement the property by. If not provided, the property will be decremented by 1.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
op.decrement({
|
||||
profileId: '1',
|
||||
property: 'visits',
|
||||
value: 1, // optional
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Clearing User Data
|
||||
|
||||
To clear the current user's data:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
op.clear();
|
||||
</script>
|
||||
```
|
||||
|
||||
### Revenue Tracking
|
||||
|
||||
Track revenue events:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
// Track revenue immediately
|
||||
await op.revenue(29.99, { currency: 'USD' });
|
||||
|
||||
// Or accumulate revenue and flush later
|
||||
op.pendingRevenue(29.99, { currency: 'USD' });
|
||||
op.pendingRevenue(19.99, { currency: 'USD' });
|
||||
await op.flushRevenue(); // Sends both revenue events
|
||||
|
||||
// Clear pending revenue
|
||||
op.clearRevenue();
|
||||
</script>
|
||||
```
|
||||
|
||||
### Optional: Create a Composable
|
||||
|
||||
If you prefer using a composable pattern, you can create your own wrapper:
|
||||
|
||||
```ts title="src/composables/useOpenPanel.ts"
|
||||
import { op } from '@/openpanel';
|
||||
|
||||
export function useOpenPanel() {
|
||||
return op;
|
||||
}
|
||||
```
|
||||
|
||||
Then use it in your components:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useOpenPanel } from '@/composables/useOpenPanel';
|
||||
|
||||
const op = useOpenPanel();
|
||||
op.track('my_event', { foo: 'bar' });
|
||||
</script>
|
||||
```
|
||||
|
||||
354
apps/public/content/guides/nuxt-analytics.mdx
Normal file
@@ -0,0 +1,354 @@
|
||||
---
|
||||
title: "How to add analytics to Nuxt"
|
||||
description: "Add privacy-first analytics to your Nuxt app in under 5 minutes with OpenPanel's official Nuxt module."
|
||||
difficulty: beginner
|
||||
timeToComplete: 5
|
||||
date: 2025-01-07
|
||||
cover: /content/cover-default.jpg
|
||||
team: OpenPanel Team
|
||||
steps:
|
||||
- name: "Install the module"
|
||||
anchor: "install"
|
||||
- name: "Configure the module"
|
||||
anchor: "setup"
|
||||
- name: "Track custom events"
|
||||
anchor: "events"
|
||||
- name: "Identify users"
|
||||
anchor: "identify"
|
||||
- name: "Set up server-side tracking"
|
||||
anchor: "server"
|
||||
- name: "Verify your setup"
|
||||
anchor: "verify"
|
||||
---
|
||||
|
||||
# How to add analytics to Nuxt
|
||||
|
||||
This guide walks you through adding OpenPanel to a Nuxt 3 application. The official `@openpanel/nuxt` module makes integration effortless with auto-imported composables, automatic page view tracking, and a built-in proxy option to bypass ad blockers.
|
||||
|
||||
OpenPanel is an open-source alternative to Mixpanel and Google Analytics. It uses cookieless tracking by default, so you won't need cookie consent banners for basic analytics.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A Nuxt 3 project
|
||||
- An OpenPanel account ([sign up free](https://dashboard.openpanel.dev/onboarding))
|
||||
- Your Client ID from the OpenPanel dashboard
|
||||
|
||||
## Install the module [#install]
|
||||
|
||||
Start by installing the OpenPanel Nuxt module. This package includes everything you need for client-side tracking, including the auto-imported `useOpenPanel` composable.
|
||||
|
||||
```bash
|
||||
npm install @openpanel/nuxt
|
||||
```
|
||||
|
||||
If you prefer pnpm or yarn, those work too.
|
||||
|
||||
## Configure the module [#setup]
|
||||
|
||||
Add the module to your `nuxt.config.ts` and configure it with your Client ID. The module automatically sets up page view tracking and makes the `useOpenPanel` composable available throughout your app.
|
||||
|
||||
```ts title="nuxt.config.ts"
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@openpanel/nuxt'],
|
||||
openpanel: {
|
||||
clientId: 'your-client-id',
|
||||
trackScreenViews: true,
|
||||
trackOutgoingLinks: true,
|
||||
trackAttributes: true,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
That's it. Page views are now being tracked automatically as users navigate your app.
|
||||
|
||||
### Configuration options
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `clientId` | — | Your OpenPanel client ID (required) |
|
||||
| `apiUrl` | `https://api.openpanel.dev` | The API URL to send events to |
|
||||
| `trackScreenViews` | `true` | Automatically track page views |
|
||||
| `trackOutgoingLinks` | `true` | Track clicks on external links |
|
||||
| `trackAttributes` | `true` | Track elements with `data-track` attributes |
|
||||
| `trackHashChanges` | `false` | Track hash changes in URL |
|
||||
| `disabled` | `false` | Disable all tracking |
|
||||
| `proxy` | `false` | Route events through your server |
|
||||
|
||||
### Using environment variables
|
||||
|
||||
For production applications, store your Client ID in environment variables.
|
||||
|
||||
```ts title="nuxt.config.ts"
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@openpanel/nuxt'],
|
||||
openpanel: {
|
||||
clientId: process.env.NUXT_PUBLIC_OPENPANEL_CLIENT_ID,
|
||||
trackScreenViews: true,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```bash title=".env"
|
||||
NUXT_PUBLIC_OPENPANEL_CLIENT_ID=your-client-id
|
||||
```
|
||||
|
||||
## Track custom events [#events]
|
||||
|
||||
Page views only tell part of the story. To understand how users interact with your product, track custom events like button clicks, form submissions, or feature usage.
|
||||
|
||||
### Using the composable
|
||||
|
||||
The `useOpenPanel` composable is auto-imported, so you can use it directly in any component without importing anything.
|
||||
|
||||
```vue title="components/SignupButton.vue"
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
function handleClick() {
|
||||
op.track('button_clicked', {
|
||||
button_name: 'signup',
|
||||
button_location: 'hero',
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button type="button" @click="handleClick">Sign Up</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Accessing via useNuxtApp
|
||||
|
||||
You can also access the OpenPanel instance through `useNuxtApp()` if you prefer.
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const { $openpanel } = useNuxtApp();
|
||||
|
||||
$openpanel.track('my_event', { foo: 'bar' });
|
||||
</script>
|
||||
```
|
||||
|
||||
### Track form submissions
|
||||
|
||||
Form tracking helps you understand conversion rates and identify where users drop off.
|
||||
|
||||
```vue title="components/ContactForm.vue"
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
const email = ref('');
|
||||
|
||||
async function handleSubmit() {
|
||||
op.track('form_submitted', {
|
||||
form_name: 'contact',
|
||||
form_location: 'homepage',
|
||||
});
|
||||
|
||||
// Your form submission logic
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form @submit.prevent="handleSubmit">
|
||||
<input v-model="email" type="email" placeholder="Enter your email" />
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Use data attributes for declarative tracking
|
||||
|
||||
The SDK supports declarative tracking using `data-track` attributes. This is useful for simple click tracking without writing JavaScript.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<button
|
||||
data-track="button_clicked"
|
||||
data-track-button_name="signup"
|
||||
data-track-button_location="hero"
|
||||
>
|
||||
Sign Up
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
When a user clicks this button, OpenPanel automatically sends a `button_clicked` event with the specified properties. This requires `trackAttributes: true` in your configuration.
|
||||
|
||||
## Identify users [#identify]
|
||||
|
||||
Anonymous tracking is useful, but identifying users unlocks more valuable insights. You can track behavior across sessions, segment users by properties, and build cohort analyses.
|
||||
|
||||
Call `identify` after a user logs in or when you have their information available.
|
||||
|
||||
```vue title="components/UserProfile.vue"
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
const props = defineProps(['user']);
|
||||
|
||||
watch(() => props.user, (user) => {
|
||||
if (user) {
|
||||
op.identify({
|
||||
profileId: user.id,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
email: user.email,
|
||||
properties: {
|
||||
plan: user.plan,
|
||||
signupDate: user.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
}, { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>Welcome, {{ user?.firstName }}!</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Set global properties
|
||||
|
||||
Properties set with `setGlobalProperties` are included with every event. This is useful for app version tracking, feature flags, or A/B test variants.
|
||||
|
||||
```vue title="app.vue"
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
onMounted(() => {
|
||||
op.setGlobalProperties({
|
||||
app_version: '1.0.0',
|
||||
environment: useRuntimeConfig().public.environment,
|
||||
});
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Clear user data on logout
|
||||
|
||||
When users log out, clear the stored profile data to ensure subsequent events aren't associated with the previous user.
|
||||
|
||||
```vue title="components/LogoutButton.vue"
|
||||
<script setup>
|
||||
const op = useOpenPanel();
|
||||
|
||||
function handleLogout() {
|
||||
op.clear();
|
||||
navigateTo('/login');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="handleLogout">Logout</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Set up server-side tracking [#server]
|
||||
|
||||
For tracking events in server routes, API endpoints, or server middleware, use the `@openpanel/sdk` package. Server-side tracking requires a client secret for authentication.
|
||||
|
||||
### Install the SDK
|
||||
|
||||
```bash
|
||||
npm install @openpanel/sdk
|
||||
```
|
||||
|
||||
### Create a server instance
|
||||
|
||||
```ts title="server/utils/op.ts"
|
||||
import { OpenPanel } from '@openpanel/sdk';
|
||||
|
||||
export const op = new OpenPanel({
|
||||
clientId: process.env.OPENPANEL_CLIENT_ID!,
|
||||
clientSecret: process.env.OPENPANEL_CLIENT_SECRET!,
|
||||
});
|
||||
```
|
||||
|
||||
### Track events in server routes
|
||||
|
||||
```ts title="server/api/webhook.post.ts"
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event);
|
||||
|
||||
await op.track('webhook_received', {
|
||||
source: body.source,
|
||||
event_type: body.type,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
});
|
||||
```
|
||||
|
||||
Never expose your client secret on the client side. Keep it in server-only code.
|
||||
|
||||
### Awaiting in serverless environments
|
||||
|
||||
If you're deploying to a serverless platform like Vercel or Netlify, make sure to await the tracking call to ensure it completes before the function terminates.
|
||||
|
||||
```ts
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Always await in serverless environments
|
||||
await op.track('my_server_event', { foo: 'bar' });
|
||||
return { message: 'Event logged!' };
|
||||
});
|
||||
```
|
||||
|
||||
## Bypass ad blockers with proxy [#proxy]
|
||||
|
||||
Many ad blockers block requests to third-party analytics domains. The Nuxt module includes a built-in proxy that routes events through your own server.
|
||||
|
||||
Enable the proxy option in your configuration:
|
||||
|
||||
```ts title="nuxt.config.ts"
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@openpanel/nuxt'],
|
||||
openpanel: {
|
||||
clientId: 'your-client-id',
|
||||
proxy: true, // Routes events through /api/openpanel/*
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
When `proxy: true` is set:
|
||||
- The module automatically sets `apiUrl` to `/api/openpanel`
|
||||
- A server handler is registered at `/api/openpanel/**`
|
||||
- All tracking requests route through your Nuxt server
|
||||
|
||||
This makes tracking requests invisible to browser extensions that block third-party analytics.
|
||||
|
||||
## Verify your setup [#verify]
|
||||
|
||||
Open your Nuxt app in the browser and navigate between a few pages. Interact with elements that trigger custom events. Then open your [OpenPanel dashboard](https://dashboard.openpanel.dev) and check the Real-time view to see events appearing within seconds.
|
||||
|
||||
If events aren't showing up, check the browser console for errors. The most common issues are:
|
||||
- Incorrect client ID
|
||||
- Ad blockers intercepting requests (enable the proxy option)
|
||||
- Client ID exposed in server-only code
|
||||
|
||||
The Network tab in your browser's developer tools can help you confirm that requests are being sent.
|
||||
|
||||
## Next steps
|
||||
|
||||
The [Nuxt SDK reference](/docs/sdks/nuxt) covers additional features like incrementing user properties and event filtering. If you're interested in understanding how OpenPanel handles privacy, read our article on [cookieless analytics](/articles/cookieless-analytics).
|
||||
|
||||
<Faqs>
|
||||
<FaqItem question="Does OpenPanel work with Nuxt 3 and Nuxt 4?">
|
||||
Yes. The `@openpanel/nuxt` module supports both Nuxt 3 and Nuxt 4. It uses Nuxt's module system and auto-imports, so everything works seamlessly with either version.
|
||||
</FaqItem>
|
||||
|
||||
<FaqItem question="Is the useOpenPanel composable auto-imported?">
|
||||
Yes. The module automatically registers the `useOpenPanel` composable, so you can use it in any component without importing it. You can also access the instance via `useNuxtApp().$openpanel`.
|
||||
</FaqItem>
|
||||
|
||||
<FaqItem question="Does OpenPanel use cookies?">
|
||||
No. OpenPanel uses cookieless tracking by default. This means you don't need cookie consent banners for basic analytics under most privacy regulations, including GDPR and PECR.
|
||||
</FaqItem>
|
||||
|
||||
<FaqItem question="How do I avoid ad blockers?">
|
||||
Enable the `proxy: true` option in your configuration. This routes all tracking requests through your Nuxt server at `/api/openpanel/*`, which ad blockers don't typically block.
|
||||
</FaqItem>
|
||||
|
||||
<FaqItem question="Is OpenPanel GDPR compliant?">
|
||||
Yes. OpenPanel is designed for GDPR compliance with cookieless tracking, data minimization, and full support for data subject rights. With self-hosting, you also eliminate international data transfer concerns entirely.
|
||||
</FaqItem>
|
||||
</Faqs>
|
||||
|
||||
|
Before Width: | Height: | Size: 5.7 KiB |
BIN
apps/public/public/logos/lucide-animated.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
@@ -7,10 +7,9 @@ import Image from 'next/image';
|
||||
|
||||
const images = [
|
||||
{
|
||||
name: 'Helpy UI',
|
||||
url: 'https://helpy-ui.com',
|
||||
logo: '/logos/helpy-ui.png',
|
||||
className: 'size-12',
|
||||
name: 'Lucide Animated',
|
||||
url: 'https://lucide-animated.com',
|
||||
logo: '/logos/lucide-animated.png',
|
||||
},
|
||||
{
|
||||
name: 'KiddoKitchen',
|
||||
@@ -67,10 +66,7 @@ export function WhyOpenPanel() {
|
||||
alt={image.name}
|
||||
width={64}
|
||||
height={64}
|
||||
className={cn(
|
||||
'size-16 object-contain dark:invert',
|
||||
image.className,
|
||||
)}
|
||||
className={cn('size-16 object-contain dark:invert')}
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -34,7 +34,6 @@ COPY packages/payments/package.json packages/payments/
|
||||
COPY packages/constants/package.json packages/constants/
|
||||
COPY packages/validation/package.json packages/validation/
|
||||
COPY packages/integrations/package.json packages/integrations/
|
||||
COPY packages/sdks/sdk/package.json packages/sdks/sdk/
|
||||
COPY packages/sdks/_info/package.json packages/sdks/_info/
|
||||
COPY patches ./patches
|
||||
# Copy tracking script to self-hosting dashboard
|
||||
@@ -93,7 +92,6 @@ COPY --from=build /app/packages/payments/package.json ./packages/payments/
|
||||
COPY --from=build /app/packages/constants/package.json ./packages/constants/
|
||||
COPY --from=build /app/packages/validation/package.json ./packages/validation/
|
||||
COPY --from=build /app/packages/integrations/package.json ./packages/integrations/
|
||||
COPY --from=build /app/packages/sdks/sdk/package.json ./packages/sdks/sdk/
|
||||
COPY --from=build /app/packages/sdks/_info/package.json ./packages/sdks/_info/
|
||||
COPY --from=build /app/patches ./patches
|
||||
|
||||
@@ -132,7 +130,6 @@ COPY --from=build /app/packages/payments ./packages/payments
|
||||
COPY --from=build /app/packages/constants ./packages/constants
|
||||
COPY --from=build /app/packages/validation ./packages/validation
|
||||
COPY --from=build /app/packages/integrations ./packages/integrations
|
||||
COPY --from=build /app/packages/sdks/sdk ./packages/sdks/sdk
|
||||
COPY --from=build /app/packages/sdks/_info ./packages/sdks/_info
|
||||
COPY --from=build /app/tooling/typescript ./tooling/typescript
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
"cf-typegen": "wrangler types",
|
||||
"build": "pnpm with-env vite build",
|
||||
"serve": "vite preview",
|
||||
"test": "vitest run",
|
||||
"format": "biome format",
|
||||
"lint": "biome lint",
|
||||
"check": "biome check",
|
||||
@@ -25,7 +24,8 @@
|
||||
"@faker-js/faker": "^9.6.0",
|
||||
"@hookform/resolvers": "^3.3.4",
|
||||
"@hyperdx/node-opentelemetry": "^0.8.1",
|
||||
"@number-flow/react": "0.3.5",
|
||||
"@nivo/sankey": "^0.99.0",
|
||||
"@number-flow/react": "0.5.10",
|
||||
"@openpanel/common": "workspace:^",
|
||||
"@openpanel/constants": "workspace:^",
|
||||
"@openpanel/integrations": "workspace:^",
|
||||
@@ -149,7 +149,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.9.4",
|
||||
"@cloudflare/vite-plugin": "^1.13.12",
|
||||
"@cloudflare/vite-plugin": "1.20.3",
|
||||
"@openpanel/db": "workspace:*",
|
||||
"@openpanel/trpc": "workspace:*",
|
||||
"@tanstack/devtools-event-client": "^0.3.3",
|
||||
@@ -170,6 +170,6 @@
|
||||
"vite": "^6.3.5",
|
||||
"vitest": "^3.0.5",
|
||||
"web-vitals": "^4.2.4",
|
||||
"wrangler": "^4.42.2"
|
||||
"wrangler": "4.59.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,6 @@
|
||||
import type { NumberFlowProps } from '@number-flow/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import ReactAnimatedNumber from '@number-flow/react';
|
||||
|
||||
// NumberFlow is breaking ssr and forces loaders to fetch twice
|
||||
export function AnimatedNumber(props: NumberFlowProps) {
|
||||
const [Component, setComponent] =
|
||||
useState<React.ComponentType<NumberFlowProps> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
import('@number-flow/react').then(({ default: NumberFlow }) => {
|
||||
setComponent(NumberFlow);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!Component) {
|
||||
return <>{props.value}</>;
|
||||
}
|
||||
|
||||
return <Component {...props} />;
|
||||
return <ReactAnimatedNumber {...props} />;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,13 @@ import { LogoSquare } from '../logo';
|
||||
import { Button } from '../ui/button';
|
||||
import { Input } from '../ui/input';
|
||||
|
||||
export function ShareEnterPassword({ shareId }: { shareId: string }) {
|
||||
export function ShareEnterPassword({
|
||||
shareId,
|
||||
shareType = 'overview',
|
||||
}: {
|
||||
shareId: string;
|
||||
shareType?: 'overview' | 'dashboard' | 'report';
|
||||
}) {
|
||||
const trpc = useTRPC();
|
||||
const mutation = useMutation(
|
||||
trpc.auth.signInShare.mutationOptions({
|
||||
@@ -25,6 +31,7 @@ export function ShareEnterPassword({ shareId }: { shareId: string }) {
|
||||
defaultValues: {
|
||||
password: '',
|
||||
shareId,
|
||||
shareType,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -32,6 +39,7 @@ export function ShareEnterPassword({ shareId }: { shareId: string }) {
|
||||
mutation.mutate({
|
||||
password: data.password,
|
||||
shareId,
|
||||
shareType,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -40,9 +48,20 @@ export function ShareEnterPassword({ shareId }: { shareId: string }) {
|
||||
<div className="bg-background p-6 rounded-lg max-w-md w-full text-left">
|
||||
<div className="col mt-1 flex-1 gap-2">
|
||||
<LogoSquare className="size-12 mb-4" />
|
||||
<div className="text-xl font-semibold">Overview is locked</div>
|
||||
<div className="text-xl font-semibold">
|
||||
{shareType === 'dashboard'
|
||||
? 'Dashboard is locked'
|
||||
: shareType === 'report'
|
||||
? 'Report is locked'
|
||||
: 'Overview is locked'}
|
||||
</div>
|
||||
<div className="text-lg text-muted-foreground leading-normal">
|
||||
Please enter correct password to access this overview
|
||||
Please enter correct password to access this{' '}
|
||||
{shareType === 'dashboard'
|
||||
? 'dashboard'
|
||||
: shareType === 'report'
|
||||
? 'report'
|
||||
: 'overview'}
|
||||
</div>
|
||||
</div>
|
||||
<form onSubmit={onSubmit} className="col gap-4 mt-6">
|
||||
|
||||
@@ -5,9 +5,15 @@ import { Tooltip as RechartsTooltip, type TooltipProps } from 'recharts';
|
||||
|
||||
export const ChartTooltipContainer = ({
|
||||
children,
|
||||
}: { children: React.ReactNode }) => {
|
||||
className,
|
||||
}: { children: React.ReactNode; className?: string }) => {
|
||||
return (
|
||||
<div className="min-w-[180px] col gap-2 rounded-xl border bg-background/80 p-3 shadow-xl backdrop-blur-sm">
|
||||
<div
|
||||
className={cn(
|
||||
'min-w-[180px] col gap-2 rounded-xl border bg-background/80 p-3 shadow-xl backdrop-blur-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Markdown } from '@/components/markdown';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { zChartInputAI } from '@openpanel/validation';
|
||||
import { zReport } from '@openpanel/validation';
|
||||
import { z } from 'zod';
|
||||
import type { UIMessage } from 'ai';
|
||||
import { Loader2Icon, UserIcon } from 'lucide-react';
|
||||
import { Fragment, memo } from 'react';
|
||||
@@ -77,7 +78,10 @@ export const ChatMessage = memo(
|
||||
const { result } = p.toolInvocation;
|
||||
|
||||
if (result.type === 'report') {
|
||||
const report = zChartInputAI.safeParse(result.report);
|
||||
const report = zReport.extend({
|
||||
startDate: z.string(),
|
||||
endDate: z.string(),
|
||||
}).safeParse(result.report);
|
||||
if (report.success) {
|
||||
return (
|
||||
<Fragment key={key}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { pushModal } from '@/modals';
|
||||
import type {
|
||||
IChartInputAi,
|
||||
IReport,
|
||||
IChartRange,
|
||||
IChartType,
|
||||
IInterval,
|
||||
@@ -16,7 +16,7 @@ import { Button } from '../ui/button';
|
||||
export function ChatReport({
|
||||
lazy,
|
||||
...props
|
||||
}: { report: IChartInputAi; lazy: boolean }) {
|
||||
}: { report: IReport & { startDate: string; endDate: string }; lazy: boolean }) {
|
||||
const [chartType, setChartType] = useState<IChartType>(
|
||||
props.report.chartType,
|
||||
);
|
||||
|
||||
65
apps/start/src/components/delta-chip.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { cn } from '@/utils/cn';
|
||||
import { type VariantProps, cva } from 'class-variance-authority';
|
||||
import { ArrowDownIcon, ArrowUpIcon } from 'lucide-react';
|
||||
|
||||
const deltaChipVariants = cva(
|
||||
'flex items-center gap-1 rounded-full px-2 py-1 text-sm font-semibold',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
inc: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
|
||||
dec: 'bg-red-500/10 text-red-600 dark:text-red-400',
|
||||
default: 'bg-muted text-muted-foreground',
|
||||
},
|
||||
size: {
|
||||
sm: 'text-xs',
|
||||
md: 'text-sm',
|
||||
lg: 'text-base',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'md',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
type DeltaChipProps = VariantProps<typeof deltaChipVariants> & {
|
||||
children: React.ReactNode;
|
||||
inverted?: boolean;
|
||||
};
|
||||
|
||||
const iconVariants: Record<NonNullable<DeltaChipProps['size']>, number> = {
|
||||
sm: 12,
|
||||
md: 16,
|
||||
lg: 20,
|
||||
};
|
||||
|
||||
const getVariant = (variant: DeltaChipProps['variant'], inverted?: boolean) => {
|
||||
if (inverted) {
|
||||
return variant === 'inc' ? 'dec' : variant === 'dec' ? 'inc' : variant;
|
||||
}
|
||||
return variant;
|
||||
};
|
||||
|
||||
export function DeltaChip({
|
||||
variant,
|
||||
size,
|
||||
inverted,
|
||||
children,
|
||||
}: DeltaChipProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
deltaChipVariants({ variant: getVariant(variant, inverted), size }),
|
||||
)}
|
||||
>
|
||||
{variant === 'inc' ? (
|
||||
<ArrowUpIcon size={iconVariants[size || 'md']} className="shrink-0" />
|
||||
) : variant === 'dec' ? (
|
||||
<ArrowDownIcon size={iconVariants[size || 'md']} className="shrink-0" />
|
||||
) : null}
|
||||
<span>{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
95
apps/start/src/components/grafana-grid.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { IServiceReport } from '@openpanel/db';
|
||||
import { useMemo } from 'react';
|
||||
import { Responsive, WidthProvider } from 'react-grid-layout';
|
||||
|
||||
const ResponsiveGridLayout = WidthProvider(Responsive);
|
||||
|
||||
export type Layout = ReactGridLayout.Layout;
|
||||
|
||||
export const useReportLayouts = (
|
||||
reports: NonNullable<IServiceReport>[],
|
||||
): ReactGridLayout.Layouts => {
|
||||
return useMemo(() => {
|
||||
const baseLayout = reports.map((report, index) => ({
|
||||
i: report.id,
|
||||
x: report.layout?.x ?? (index % 2) * 6,
|
||||
y: report.layout?.y ?? Math.floor(index / 2) * 4,
|
||||
w: report.layout?.w ?? 6,
|
||||
h: report.layout?.h ?? 4,
|
||||
minW: 3,
|
||||
minH: 3,
|
||||
}));
|
||||
|
||||
return {
|
||||
lg: baseLayout,
|
||||
md: baseLayout,
|
||||
sm: baseLayout.map((item) => ({ ...item, w: Math.min(item.w, 6) })),
|
||||
xs: baseLayout.map((item) => ({ ...item, w: 4, x: 0 })),
|
||||
xxs: baseLayout.map((item) => ({ ...item, w: 2, x: 0 })),
|
||||
};
|
||||
}, [reports]);
|
||||
};
|
||||
|
||||
export function GrafanaGrid({
|
||||
layouts,
|
||||
children,
|
||||
transitions,
|
||||
onLayoutChange,
|
||||
onDragStop,
|
||||
onResizeStop,
|
||||
isDraggable,
|
||||
isResizable,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
transitions?: boolean;
|
||||
} & Pick<
|
||||
ReactGridLayout.ResponsiveProps,
|
||||
| 'layouts'
|
||||
| 'onLayoutChange'
|
||||
| 'onDragStop'
|
||||
| 'onResizeStop'
|
||||
| 'isDraggable'
|
||||
| 'isResizable'
|
||||
>) {
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
.react-grid-item {
|
||||
transition: ${transitions ? 'transform 200ms ease, width 200ms ease, height 200ms ease' : 'none'} !important;
|
||||
}
|
||||
.react-grid-item.react-grid-placeholder {
|
||||
background: none !important;
|
||||
opacity: 0.5;
|
||||
transition-duration: 100ms;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px dashed var(--primary);
|
||||
}
|
||||
.react-grid-item.resizing {
|
||||
transition: none !important;
|
||||
}
|
||||
`}</style>
|
||||
<div className="-m-4">
|
||||
<ResponsiveGridLayout
|
||||
className="layout"
|
||||
layouts={layouts}
|
||||
breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
|
||||
cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
|
||||
rowHeight={100}
|
||||
draggableHandle=".drag-handle"
|
||||
compactType="vertical"
|
||||
preventCollision={false}
|
||||
margin={[16, 16]}
|
||||
transformScale={1}
|
||||
useCSSTransforms={true}
|
||||
onLayoutChange={onLayoutChange}
|
||||
onDragStop={onDragStop}
|
||||
onResizeStop={onResizeStop}
|
||||
isDraggable={isDraggable}
|
||||
isResizable={isResizable}
|
||||
>
|
||||
{children}
|
||||
</ResponsiveGridLayout>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type { InsightPayload } from '@openpanel/validation';
|
||||
import { ArrowDown, ArrowUp, FilterIcon, RotateCcwIcon } from 'lucide-react';
|
||||
import { last } from 'ramda';
|
||||
import { useState } from 'react';
|
||||
import { DeltaChip } from '../delta-chip';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { Badge } from '../ui/badge';
|
||||
|
||||
@@ -188,42 +189,13 @@ export function InsightCard({
|
||||
|
||||
{/* Delta chip */}
|
||||
<DeltaChip
|
||||
isIncrease={isIncrease}
|
||||
isDecrease={isDecrease}
|
||||
deltaText={deltaText}
|
||||
/>
|
||||
variant={isIncrease ? 'inc' : isDecrease ? 'dec' : 'default'}
|
||||
size="sm"
|
||||
>
|
||||
{deltaText}
|
||||
</DeltaChip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DeltaChip({
|
||||
isIncrease,
|
||||
isDecrease,
|
||||
deltaText,
|
||||
}: {
|
||||
isIncrease: boolean;
|
||||
isDecrease: boolean;
|
||||
deltaText: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-1 rounded-full px-2 py-1 text-sm font-semibold',
|
||||
isIncrease
|
||||
? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
|
||||
: isDecrease
|
||||
? 'bg-red-500/10 text-red-600 dark:text-red-400'
|
||||
: 'bg-muted text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{isIncrease ? (
|
||||
<ArrowUp size={16} className="shrink-0" />
|
||||
) : isDecrease ? (
|
||||
<ArrowDown size={16} className="shrink-0" />
|
||||
) : null}
|
||||
<span>{deltaText}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ export function LoginNavbar({ className }: { className?: string }) {
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://openpanel.dev/compare/mixpanel-alternative">
|
||||
<a href="https://openpanel.dev/compare/posthog-alternative">
|
||||
Posthog alternative
|
||||
</a>
|
||||
</li>
|
||||
|
||||
82
apps/start/src/components/organization/feedback-prompt.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { PromptCard } from '@/components/organization/prompt-card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useAppContext } from '@/hooks/use-app-context';
|
||||
import { useCookieStore } from '@/hooks/use-cookie-store';
|
||||
import { op } from '@/utils/op';
|
||||
import { MessageSquareIcon } from 'lucide-react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
|
||||
const THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30;
|
||||
|
||||
export default function FeedbackPrompt() {
|
||||
const { isSelfHosted } = useAppContext();
|
||||
const [feedbackPromptSeen, setFeedbackPromptSeen] = useCookieStore(
|
||||
'feedback-prompt-seen',
|
||||
'',
|
||||
{ maxAge: THIRTY_DAYS_IN_SECONDS },
|
||||
);
|
||||
|
||||
const shouldShow = useMemo(() => {
|
||||
if (isSelfHosted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!feedbackPromptSeen) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const lastSeenDate = new Date(feedbackPromptSeen);
|
||||
const now = new Date();
|
||||
const daysSinceLastSeen =
|
||||
(now.getTime() - lastSeenDate.getTime()) / (1000 * 60 * 60 * 24);
|
||||
|
||||
return daysSinceLastSeen >= 30;
|
||||
} catch {
|
||||
// If date parsing fails, show the prompt
|
||||
return true;
|
||||
}
|
||||
}, [isSelfHosted, feedbackPromptSeen]);
|
||||
|
||||
const handleGiveFeedback = () => {
|
||||
// Open userjot widget
|
||||
if (typeof window !== 'undefined' && 'uj' in window) {
|
||||
(window.uj as any).showWidget();
|
||||
}
|
||||
// Set cookie with current timestamp
|
||||
setFeedbackPromptSeen(new Date().toISOString());
|
||||
op.track('feedback_prompt_button_clicked');
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
// Set cookie with current timestamp when closed
|
||||
setFeedbackPromptSeen(new Date().toISOString());
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldShow) {
|
||||
op.track('feedback_prompt_viewed');
|
||||
}
|
||||
}, [shouldShow]);
|
||||
|
||||
return (
|
||||
<PromptCard
|
||||
title="Share Your Feedback"
|
||||
subtitle="Help us improve OpenPanel with your insights"
|
||||
onClose={handleClose}
|
||||
show={shouldShow}
|
||||
gradientColor="rgb(59 130 246)"
|
||||
>
|
||||
<div className="px-6 col gap-4">
|
||||
<p className="text-sm text-foreground leading-normal">
|
||||
Your feedback helps us build features you actually need. Share your
|
||||
thoughts, report bugs, or suggest improvements
|
||||
</p>
|
||||
|
||||
<Button className="self-start" onClick={handleGiveFeedback}>
|
||||
Give Feedback
|
||||
</Button>
|
||||
</div>
|
||||
</PromptCard>
|
||||
);
|
||||
}
|
||||
66
apps/start/src/components/organization/prompt-card.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { XIcon } from 'lucide-react';
|
||||
|
||||
interface PromptCardProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
gradientColor?: string;
|
||||
show: boolean;
|
||||
}
|
||||
|
||||
export function PromptCard({
|
||||
title,
|
||||
subtitle,
|
||||
onClose,
|
||||
children,
|
||||
gradientColor = 'rgb(16 185 129)',
|
||||
show,
|
||||
}: PromptCardProps) {
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{show && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, x: 100, scale: 0.95 }}
|
||||
animate={{ opacity: 1, x: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, x: 100, scale: 0.95 }}
|
||||
transition={{
|
||||
type: 'spring',
|
||||
stiffness: 300,
|
||||
damping: 30,
|
||||
}}
|
||||
className="fixed bottom-0 right-0 z-50 p-4 max-w-sm"
|
||||
>
|
||||
<div className="bg-card border rounded-lg shadow-[0_0_100px_50px_var(--color-background)] col gap-6 py-6 overflow-hidden">
|
||||
<div className="relative px-6 col gap-1">
|
||||
<div
|
||||
className="absolute -bottom-10 -right-10 h-64 w-64 rounded-full opacity-30 blur-3xl pointer-events-none"
|
||||
style={{
|
||||
background: `radial-gradient(circle, ${gradientColor} 0%, transparent 70%)`,
|
||||
}}
|
||||
/>
|
||||
<div className="row items-center justify-between">
|
||||
<h2 className="text-xl font-semibold max-w-[200px] leading-snug">
|
||||
{title}
|
||||
</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="rounded-full"
|
||||
onClick={onClose}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Button, LinkButton } from '@/components/ui/button';
|
||||
import { PromptCard } from '@/components/organization/prompt-card';
|
||||
import { LinkButton } from '@/components/ui/button';
|
||||
import { useAppContext } from '@/hooks/use-app-context';
|
||||
import { useCookieStore } from '@/hooks/use-cookie-store';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import {
|
||||
AwardIcon,
|
||||
HeartIcon,
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
MessageCircleIcon,
|
||||
RocketIcon,
|
||||
SparklesIcon,
|
||||
XIcon,
|
||||
ZapIcon,
|
||||
} from 'lucide-react';
|
||||
|
||||
@@ -78,70 +77,43 @@ export default function SupporterPrompt() {
|
||||
}
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{!supporterPromptClosed && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, x: 100, scale: 0.95 }}
|
||||
animate={{ opacity: 1, x: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, x: 100, scale: 0.95 }}
|
||||
transition={{
|
||||
type: 'spring',
|
||||
stiffness: 300,
|
||||
damping: 30,
|
||||
}}
|
||||
className="fixed bottom-0 right-0 z-50 p-4 max-w-md"
|
||||
<PromptCard
|
||||
title="Support OpenPanel"
|
||||
subtitle="Help us build the future of open analytics"
|
||||
onClose={() => setSupporterPromptClosed(true)}
|
||||
show={!supporterPromptClosed}
|
||||
gradientColor="rgb(16 185 129)"
|
||||
>
|
||||
<div className="col gap-3 px-6">
|
||||
{PERKS.map((perk) => (
|
||||
<PerkPoint
|
||||
key={perk.text}
|
||||
icon={perk.icon}
|
||||
text={perk.text}
|
||||
description={perk.description}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="px-6">
|
||||
<LinkButton
|
||||
className="w-full"
|
||||
href="https://buy.polar.sh/polar_cl_Az1CruNFzQB2bYdMOZmGHqTevW317knWqV44W1FqZmV"
|
||||
>
|
||||
<div className="bg-card border p-6 rounded-lg shadow-lg col gap-4">
|
||||
<div>
|
||||
<div className="row items-center justify-between">
|
||||
<h2 className="text-xl font-semibold">Support OpenPanel</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="rounded-full"
|
||||
onClick={() => setSupporterPromptClosed(true)}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Help us build the future of open analytics
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="col gap-3">
|
||||
{PERKS.map((perk) => (
|
||||
<PerkPoint
|
||||
key={perk.text}
|
||||
icon={perk.icon}
|
||||
text={perk.text}
|
||||
description={perk.description}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<LinkButton
|
||||
className="w-full"
|
||||
href="https://buy.polar.sh/polar_cl_Az1CruNFzQB2bYdMOZmGHqTevW317knWqV44W1FqZmV"
|
||||
>
|
||||
Become a Supporter
|
||||
</LinkButton>
|
||||
<p className="text-xs text-muted-foreground text-center mt-4">
|
||||
Starting at $20/month • Cancel anytime •{' '}
|
||||
<a
|
||||
href="https://openpanel.dev/supporter"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
Learn more
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
Become a Supporter
|
||||
</LinkButton>
|
||||
<p className="text-xs text-muted-foreground text-center mt-4">
|
||||
Starting at $20/month • Cancel anytime •{' '}
|
||||
<a
|
||||
href="https://openpanel.dev/supporter"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
Learn more
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</PromptCard>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import React from 'react';
|
||||
|
||||
import {
|
||||
ChartTooltipContainer,
|
||||
ChartTooltipHeader,
|
||||
ChartTooltipItem,
|
||||
createChartTooltip,
|
||||
} from '@/components/charts/chart-tooltip';
|
||||
import type { IInterval } from '@openpanel/validation';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
|
||||
type Data = {
|
||||
date: string;
|
||||
timestamp: number;
|
||||
[key: `${string}:sessions`]: number;
|
||||
[key: `${string}:pageviews`]: number;
|
||||
[key: `${string}:revenue`]: number | undefined;
|
||||
[key: `${string}:payload`]: {
|
||||
name: string;
|
||||
prefix?: string;
|
||||
color: string;
|
||||
};
|
||||
};
|
||||
|
||||
type Context = {
|
||||
interval: IInterval;
|
||||
};
|
||||
|
||||
export const OverviewLineChartTooltip = createChartTooltip<Data, Context>(
|
||||
({ context: { interval }, data }) => {
|
||||
const formatDate = useFormatDateInterval({
|
||||
interval,
|
||||
short: false,
|
||||
});
|
||||
const number = useNumber();
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const firstItem = data[0];
|
||||
|
||||
// Get all payload items from the first data point
|
||||
// Keys are in format "prefix:name:payload" or "name:payload"
|
||||
const payloadItems = Object.keys(firstItem)
|
||||
.filter((key) => key.endsWith(':payload'))
|
||||
.map((key) => {
|
||||
const payload = firstItem[key as keyof typeof firstItem] as {
|
||||
name: string;
|
||||
prefix?: string;
|
||||
color: string;
|
||||
};
|
||||
// Extract the base key (without :payload) to access sessions/pageviews/revenue
|
||||
const baseKey = key.replace(':payload', '');
|
||||
return {
|
||||
payload,
|
||||
baseKey,
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(item) =>
|
||||
item.payload &&
|
||||
typeof item.payload === 'object' &&
|
||||
'name' in item.payload,
|
||||
);
|
||||
|
||||
// Sort by sessions (descending)
|
||||
const sorted = payloadItems.sort((a, b) => {
|
||||
const aSessions =
|
||||
(firstItem[
|
||||
`${a.baseKey}:sessions` as keyof typeof firstItem
|
||||
] as number) ?? 0;
|
||||
const bSessions =
|
||||
(firstItem[
|
||||
`${b.baseKey}:sessions` as keyof typeof firstItem
|
||||
] as number) ?? 0;
|
||||
return bSessions - aSessions;
|
||||
});
|
||||
|
||||
const limit = 3;
|
||||
const visible = sorted.slice(0, limit);
|
||||
const hidden = sorted.slice(limit);
|
||||
|
||||
return (
|
||||
<>
|
||||
{visible.map((item, index) => {
|
||||
const sessions =
|
||||
(firstItem[
|
||||
`${item.baseKey}:sessions` as keyof typeof firstItem
|
||||
] as number) ?? 0;
|
||||
const pageviews =
|
||||
(firstItem[
|
||||
`${item.baseKey}:pageviews` as keyof typeof firstItem
|
||||
] as number) ?? 0;
|
||||
const revenue = firstItem[
|
||||
`${item.baseKey}:revenue` as keyof typeof firstItem
|
||||
] as number | undefined;
|
||||
|
||||
return (
|
||||
<React.Fragment key={item.baseKey}>
|
||||
{index === 0 && firstItem.date && (
|
||||
<ChartTooltipHeader>
|
||||
<div>{formatDate(new Date(firstItem.date))}</div>
|
||||
</ChartTooltipHeader>
|
||||
)}
|
||||
<ChartTooltipItem color={item.payload.color}>
|
||||
<div className="flex items-center gap-1">
|
||||
<SerieIcon name={item.payload.prefix || item.payload.name} />
|
||||
<div className="font-medium">
|
||||
{item.payload.prefix && (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
{item.payload.prefix}
|
||||
</span>
|
||||
<span className="mx-1">/</span>
|
||||
</>
|
||||
)}
|
||||
{item.payload.name || 'Not set'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="col gap-1 text-sm">
|
||||
{revenue !== undefined && revenue > 0 && (
|
||||
<div className="flex justify-between gap-8 font-mono font-medium">
|
||||
<span className="text-muted-foreground">Revenue</span>
|
||||
<span style={{ color: '#3ba974' }}>
|
||||
{number.currency(revenue / 100, { short: true })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between gap-8 font-mono font-medium">
|
||||
<span className="text-muted-foreground">Pageviews</span>
|
||||
<span>{number.short(pageviews)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-8 font-mono font-medium">
|
||||
<span className="text-muted-foreground">Sessions</span>
|
||||
<span>{number.short(sessions)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</ChartTooltipItem>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
{hidden.length > 0 && (
|
||||
<div className="text-muted-foreground text-sm">
|
||||
and {hidden.length} more {hidden.length === 1 ? 'item' : 'items'}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
);
|
||||
303
apps/start/src/components/overview/overview-line-chart.tsx
Normal file
@@ -0,0 +1,303 @@
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { getChartColor } from '@/utils/theme';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
CartesianGrid,
|
||||
Line,
|
||||
LineChart,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts';
|
||||
|
||||
import type { RouterOutputs } from '@/trpc/client';
|
||||
import type { IInterval } from '@openpanel/validation';
|
||||
import { useXAxisProps, useYAxisProps } from '../report-chart/common/axis';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { OverviewLineChartTooltip } from './overview-line-chart-tooltip';
|
||||
|
||||
type SeriesData =
|
||||
RouterOutputs['overview']['topGenericSeries']['items'][number];
|
||||
|
||||
interface OverviewLineChartProps {
|
||||
data: RouterOutputs['overview']['topGenericSeries'];
|
||||
interval: IInterval;
|
||||
searchQuery?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function transformDataForRecharts(
|
||||
items: SeriesData[],
|
||||
searchQuery?: string,
|
||||
): Array<{
|
||||
date: string;
|
||||
timestamp: number;
|
||||
[key: `${string}:sessions`]: number;
|
||||
[key: `${string}:pageviews`]: number;
|
||||
[key: `${string}:revenue`]: number | undefined;
|
||||
[key: `${string}:payload`]: {
|
||||
name: string;
|
||||
prefix?: string;
|
||||
color: string;
|
||||
};
|
||||
}> {
|
||||
// Filter items by search query
|
||||
const filteredItems = searchQuery
|
||||
? items.filter((item) => {
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return (
|
||||
(item.name?.toLowerCase().includes(queryLower) ?? false) ||
|
||||
(item.prefix?.toLowerCase().includes(queryLower) ?? false)
|
||||
);
|
||||
})
|
||||
: items;
|
||||
|
||||
// Limit to top 15
|
||||
const topItems = filteredItems.slice(0, 15);
|
||||
|
||||
// Get all unique dates from all items
|
||||
const allDates = new Set<string>();
|
||||
topItems.forEach((item) => {
|
||||
item.data.forEach((d) => allDates.add(d.date));
|
||||
});
|
||||
|
||||
const sortedDates = Array.from(allDates).sort();
|
||||
|
||||
// Transform to recharts format
|
||||
return sortedDates.map((date) => {
|
||||
const timestamp = new Date(date).getTime();
|
||||
const result: Record<string, any> = {
|
||||
date,
|
||||
timestamp,
|
||||
};
|
||||
|
||||
topItems.forEach((item, index) => {
|
||||
const dataPoint = item.data.find((d) => d.date === date);
|
||||
if (dataPoint) {
|
||||
// Use prefix:name as key to avoid collisions when same name exists with different prefixes
|
||||
const key = item.prefix ? `${item.prefix}:${item.name}` : item.name;
|
||||
result[`${key}:sessions`] = dataPoint.sessions;
|
||||
result[`${key}:pageviews`] = dataPoint.pageviews;
|
||||
if (dataPoint.revenue !== undefined) {
|
||||
result[`${key}:revenue`] = dataPoint.revenue;
|
||||
}
|
||||
result[`${key}:payload`] = {
|
||||
name: item.name,
|
||||
prefix: item.prefix,
|
||||
color: getChartColor(index),
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return result as typeof result & {
|
||||
date: string;
|
||||
timestamp: number;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function OverviewLineChart({
|
||||
data,
|
||||
interval,
|
||||
searchQuery,
|
||||
className,
|
||||
}: OverviewLineChartProps) {
|
||||
const number = useNumber();
|
||||
|
||||
const chartData = useMemo(
|
||||
() => transformDataForRecharts(data.items, searchQuery),
|
||||
[data.items, searchQuery],
|
||||
);
|
||||
|
||||
const visibleItems = useMemo(() => {
|
||||
const filtered = searchQuery
|
||||
? data.items.filter((item) => {
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return (
|
||||
(item.name?.toLowerCase().includes(queryLower) ?? false) ||
|
||||
(item.prefix?.toLowerCase().includes(queryLower) ?? false)
|
||||
);
|
||||
})
|
||||
: data.items;
|
||||
return filtered.slice(0, 15);
|
||||
}, [data.items, searchQuery]);
|
||||
|
||||
const xAxisProps = useXAxisProps({ interval, hide: false });
|
||||
const yAxisProps = useYAxisProps({});
|
||||
|
||||
if (visibleItems.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className={cn('flex items-center justify-center h-[358px]', className)}
|
||||
>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{searchQuery ? 'No results found' : 'No data available'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('w-full p-4', className)}>
|
||||
<div className="h-[358px] w-full">
|
||||
<OverviewLineChartTooltip.TooltipProvider interval={interval}>
|
||||
<ResponsiveContainer>
|
||||
<LineChart data={chartData}>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
horizontal={true}
|
||||
vertical={false}
|
||||
className="stroke-border"
|
||||
/>
|
||||
<XAxis {...xAxisProps} />
|
||||
<YAxis {...yAxisProps} />
|
||||
<Tooltip content={<OverviewLineChartTooltip.Tooltip />} />
|
||||
{visibleItems.map((item, index) => {
|
||||
const color = getChartColor(index);
|
||||
// Use prefix:name as key to avoid collisions when same name exists with different prefixes
|
||||
const key = item.prefix
|
||||
? `${item.prefix}:${item.name}`
|
||||
: item.name;
|
||||
return (
|
||||
<Line
|
||||
key={key}
|
||||
type="monotone"
|
||||
dataKey={`${key}:sessions`}
|
||||
stroke={color}
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</OverviewLineChartTooltip.TooltipProvider>
|
||||
</div>
|
||||
|
||||
{/* Legend */}
|
||||
<LegendScrollable items={visibleItems} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LegendScrollable({
|
||||
items,
|
||||
}: {
|
||||
items: SeriesData[];
|
||||
}) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [showLeftGradient, setShowLeftGradient] = useState(false);
|
||||
const [showRightGradient, setShowRightGradient] = useState(false);
|
||||
|
||||
const updateGradients = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const { scrollLeft, scrollWidth, clientWidth } = el;
|
||||
const hasOverflow = scrollWidth > clientWidth;
|
||||
|
||||
setShowLeftGradient(hasOverflow && scrollLeft > 0);
|
||||
setShowRightGradient(
|
||||
hasOverflow && scrollLeft < scrollWidth - clientWidth - 1,
|
||||
);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
|
||||
updateGradients();
|
||||
|
||||
el.addEventListener('scroll', updateGradients);
|
||||
window.addEventListener('resize', updateGradients);
|
||||
|
||||
return () => {
|
||||
el.removeEventListener('scroll', updateGradients);
|
||||
window.removeEventListener('resize', updateGradients);
|
||||
};
|
||||
}, [updateGradients]);
|
||||
|
||||
// Update gradients when items change
|
||||
useEffect(() => {
|
||||
requestAnimationFrame(updateGradients);
|
||||
}, [items, updateGradients]);
|
||||
|
||||
return (
|
||||
<div className="relative mt-4 -mb-2">
|
||||
{/* Left gradient */}
|
||||
<div
|
||||
className={cn(
|
||||
'pointer-events-none absolute left-0 top-0 z-10 h-full w-8 bg-gradient-to-r from-card to-transparent transition-opacity duration-200',
|
||||
showLeftGradient ? 'opacity-100' : 'opacity-0',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Scrollable legend */}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="flex gap-x-4 gap-y-1 overflow-x-auto px-2 py-1 hide-scrollbar text-xs"
|
||||
>
|
||||
{items.map((item, index) => {
|
||||
const color = getChartColor(index);
|
||||
return (
|
||||
<div
|
||||
className="flex shrink-0 items-center gap-1"
|
||||
key={item.prefix ? `${item.prefix}:${item.name}` : item.name}
|
||||
style={{ color }}
|
||||
>
|
||||
<SerieIcon name={item.prefix || item.name} />
|
||||
<span className="font-semibold whitespace-nowrap">
|
||||
{item.prefix && (
|
||||
<>
|
||||
<span className="text-muted-foreground">{item.prefix}</span>
|
||||
<span className="mx-1">/</span>
|
||||
</>
|
||||
)}
|
||||
{item.name || 'Not set'}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Right gradient */}
|
||||
<div
|
||||
className={cn(
|
||||
'pointer-events-none absolute right-0 top-0 z-10 h-full w-8 bg-gradient-to-l from-card to-transparent transition-opacity duration-200',
|
||||
showRightGradient ? 'opacity-100' : 'opacity-0',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function OverviewLineChartLoading({
|
||||
className,
|
||||
}: {
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn('flex items-center justify-center h-[358px]', className)}
|
||||
>
|
||||
<div className="text-muted-foreground text-sm">Loading...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function OverviewLineChartEmpty({
|
||||
className,
|
||||
}: {
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn('flex items-center justify-center h-[358px]', className)}
|
||||
>
|
||||
<div className="text-muted-foreground text-sm">No data available</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
264
apps/start/src/components/overview/overview-list-modal.tsx
Normal file
@@ -0,0 +1,264 @@
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { ModalContent } from '@/modals/Modal/Container';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { DialogTitle } from '@radix-ui/react-dialog';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { SearchIcon } from 'lucide-react';
|
||||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { Input } from '../ui/input';
|
||||
|
||||
const ROW_HEIGHT = 36;
|
||||
|
||||
// Revenue pie chart component
|
||||
function RevenuePieChart({ percentage }: { percentage: number }) {
|
||||
const size = 16;
|
||||
const strokeWidth = 2;
|
||||
const radius = (size - strokeWidth) / 2;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const offset = circumference - percentage * circumference;
|
||||
|
||||
return (
|
||||
<svg width={size} height={size} className="flex-shrink-0">
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
className="text-def-200"
|
||||
/>
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="#3ba974"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={offset}
|
||||
strokeLinecap="round"
|
||||
transform={`rotate(-90 ${size / 2} ${size / 2})`}
|
||||
className="transition-all"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Base data type that all items must conform to
|
||||
export interface OverviewListItem {
|
||||
sessions: number;
|
||||
pageviews: number;
|
||||
revenue?: number;
|
||||
}
|
||||
|
||||
interface OverviewListModalProps<T extends OverviewListItem> {
|
||||
/** Modal title */
|
||||
title: string;
|
||||
/** Search placeholder text */
|
||||
searchPlaceholder?: string;
|
||||
/** The data to display */
|
||||
data: T[];
|
||||
/** Extract a unique key for each item */
|
||||
keyExtractor: (item: T) => string;
|
||||
/** Filter function for search - receives item and lowercase search query */
|
||||
searchFilter: (item: T, query: string) => boolean;
|
||||
/** Render the main content cell (first column) */
|
||||
renderItem: (item: T) => React.ReactNode;
|
||||
/** Optional footer content */
|
||||
footer?: React.ReactNode;
|
||||
/** Optional header content (appears below title/search) */
|
||||
headerContent?: React.ReactNode;
|
||||
/** Column name for the first column */
|
||||
columnName?: string;
|
||||
/** Whether to show pageviews column */
|
||||
showPageviews?: boolean;
|
||||
/** Whether to show sessions column */
|
||||
showSessions?: boolean;
|
||||
}
|
||||
|
||||
export function OverviewListModal<T extends OverviewListItem>({
|
||||
title,
|
||||
searchPlaceholder = 'Search...',
|
||||
data,
|
||||
keyExtractor,
|
||||
searchFilter,
|
||||
renderItem,
|
||||
footer,
|
||||
headerContent,
|
||||
columnName = 'Name',
|
||||
showPageviews = true,
|
||||
showSessions = true,
|
||||
}: OverviewListModalProps<T>) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
const number = useNumber();
|
||||
|
||||
// Filter data based on search query
|
||||
const filteredData = useMemo(() => {
|
||||
if (!searchQuery.trim()) {
|
||||
return data;
|
||||
}
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return data.filter((item) => searchFilter(item, queryLower));
|
||||
}, [data, searchQuery, searchFilter]);
|
||||
|
||||
// Calculate totals and check for revenue
|
||||
const { maxSessions, totalRevenue, hasRevenue, hasPageviews } =
|
||||
useMemo(() => {
|
||||
const maxSessions = Math.max(...filteredData.map((item) => item.sessions));
|
||||
const totalRevenue = filteredData.reduce(
|
||||
(sum, item) => sum + (item.revenue ?? 0),
|
||||
0,
|
||||
);
|
||||
const hasRevenue = filteredData.some((item) => (item.revenue ?? 0) > 0);
|
||||
const hasPageviews =
|
||||
showPageviews && filteredData.some((item) => item.pageviews > 0);
|
||||
return { maxSessions, totalRevenue, hasRevenue, hasPageviews };
|
||||
}, [filteredData, showPageviews]);
|
||||
|
||||
// Virtual list setup
|
||||
const virtualizer = useVirtualizer({
|
||||
count: filteredData.length,
|
||||
getScrollElement: () => scrollAreaRef.current,
|
||||
estimateSize: () => ROW_HEIGHT,
|
||||
overscan: 10,
|
||||
});
|
||||
|
||||
const virtualItems = virtualizer.getVirtualItems();
|
||||
|
||||
return (
|
||||
<ModalContent className="flex !max-h-[90vh] flex-col p-0 gap-0 sm:max-w-2xl">
|
||||
{/* Sticky Header */}
|
||||
<div className="flex-shrink-0 border-b border-border">
|
||||
<div className="p-6 pb-4">
|
||||
<DialogTitle className="text-lg font-semibold mb-4">
|
||||
{title}
|
||||
</DialogTitle>
|
||||
<div className="relative">
|
||||
<SearchIcon className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
{headerContent}
|
||||
</div>
|
||||
|
||||
{/* Column Headers */}
|
||||
<div
|
||||
className="grid px-4 py-2 text-sm font-medium text-muted-foreground bg-def-100"
|
||||
style={{
|
||||
gridTemplateColumns: `1fr ${hasRevenue ? '100px' : ''} ${hasPageviews ? '80px' : ''} ${showSessions ? '80px' : ''}`.trim(),
|
||||
}}
|
||||
>
|
||||
<div className="text-left truncate">{columnName}</div>
|
||||
{hasRevenue && <div className="text-right">Revenue</div>}
|
||||
{hasPageviews && <div className="text-right">Views</div>}
|
||||
{showSessions && <div className="text-right">Sessions</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Virtualized Scrollable Body */}
|
||||
<div
|
||||
ref={scrollAreaRef}
|
||||
className="flex-1 min-h-0 overflow-y-auto"
|
||||
style={{ maxHeight: '60vh' }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
height: `${virtualizer.getTotalSize()}px`,
|
||||
width: '100%',
|
||||
position: 'relative',
|
||||
}}
|
||||
>
|
||||
{virtualItems.map((virtualRow) => {
|
||||
const item = filteredData[virtualRow.index];
|
||||
if (!item) return null;
|
||||
|
||||
const percentage = item.sessions / maxSessions;
|
||||
const revenuePercentage =
|
||||
totalRevenue > 0 ? (item.revenue ?? 0) / totalRevenue : 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={keyExtractor(item)}
|
||||
className="absolute top-0 left-0 w-full group/row"
|
||||
style={{
|
||||
height: `${virtualRow.size}px`,
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
>
|
||||
{/* Background bar */}
|
||||
<div className="absolute inset-0 overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-def-200 group-hover/row:bg-blue-200 dark:group-hover/row:bg-blue-900 transition-colors"
|
||||
style={{ width: `${percentage * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row content */}
|
||||
<div
|
||||
className="relative grid h-full items-center px-4 border-b border-border"
|
||||
style={{
|
||||
gridTemplateColumns: `1fr ${hasRevenue ? '100px' : ''} ${hasPageviews ? '80px' : ''} ${showSessions ? '80px' : ''}`.trim(),
|
||||
}}
|
||||
>
|
||||
{/* Main content cell */}
|
||||
<div className="min-w-0 truncate pr-2">{renderItem(item)}</div>
|
||||
|
||||
{/* Revenue cell */}
|
||||
{hasRevenue && (
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span
|
||||
className="font-semibold font-mono text-sm"
|
||||
style={{ color: '#3ba974' }}
|
||||
>
|
||||
{(item.revenue ?? 0) > 0
|
||||
? number.currency((item.revenue ?? 0) / 100, {
|
||||
short: true,
|
||||
})
|
||||
: '-'}
|
||||
</span>
|
||||
<RevenuePieChart percentage={revenuePercentage} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pageviews cell */}
|
||||
{hasPageviews && (
|
||||
<div className="text-right font-semibold font-mono text-sm">
|
||||
{number.short(item.pageviews)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Sessions cell */}
|
||||
{showSessions && (
|
||||
<div className="text-right font-semibold font-mono text-sm">
|
||||
{number.short(item.sessions)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Empty state */}
|
||||
{filteredData.length === 0 && (
|
||||
<div className="flex items-center justify-center h-32 text-muted-foreground">
|
||||
{searchQuery ? 'No results found' : 'No data available'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Fixed Footer */}
|
||||
{footer && (
|
||||
<div className="flex-shrink-0 border-t border-border p-4">{footer}</div>
|
||||
)}
|
||||
</ModalContent>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
@@ -8,18 +7,14 @@ import * as Portal from '@radix-ui/react-portal';
|
||||
import { bind } from 'bind-event-listener';
|
||||
import throttle from 'lodash.throttle';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Customized,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts';
|
||||
import { BarShapeBlue } from '../charts/common-bar';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
interface OverviewLiveHistogramProps {
|
||||
projectId: string;
|
||||
@@ -86,10 +81,8 @@ export function OverviewLiveHistogram({
|
||||
<YAxis hide domain={[0, maxDomain]} />
|
||||
<Bar
|
||||
dataKey="sessionCount"
|
||||
fill="rgba(59, 121, 255, 0.2)"
|
||||
className="fill-chart-0"
|
||||
isAnimationActive={false}
|
||||
shape={BarShapeBlue}
|
||||
activeBar={BarShapeBlue}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { cn } from '@/utils/cn';
|
||||
import AutoSizer from 'react-virtualized-auto-sizer';
|
||||
import { Area, AreaChart, Tooltip } from 'recharts';
|
||||
import { Area, AreaChart, Bar, BarChart, Tooltip } from 'recharts';
|
||||
|
||||
import { formatDate, timeAgo } from '@/utils/date';
|
||||
import { getChartColor } from '@/utils/theme';
|
||||
@@ -144,51 +144,33 @@ export function OverviewMetricCard({
|
||||
<div className={cn('group relative p-4')}>
|
||||
<div
|
||||
className={cn(
|
||||
'absolute -left-1 -right-1 bottom-0 top-0 z-0 opacity-50 transition-opacity duration-300 group-hover:opacity-100',
|
||||
'absolute left-4 right-4 bottom-0 z-0 opacity-50 transition-opacity duration-300 group-hover:opacity-100',
|
||||
)}
|
||||
>
|
||||
<AutoSizer>
|
||||
{({ width, height }) => (
|
||||
<AreaChart
|
||||
<AutoSizer style={{ height: 20 }}>
|
||||
{({ width }) => (
|
||||
<BarChart
|
||||
width={width}
|
||||
height={height / 4}
|
||||
height={20}
|
||||
data={data}
|
||||
style={{ marginTop: (height / 4) * 3, background: 'transparent' }}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
}}
|
||||
onMouseMove={(event) => {
|
||||
setCurrentIndex(event.activeTooltipIndex ?? null);
|
||||
}}
|
||||
margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={`colorUv${id}`}
|
||||
x1="0"
|
||||
y1="0"
|
||||
x2="0"
|
||||
y2="1"
|
||||
>
|
||||
<stop
|
||||
offset="0%"
|
||||
stopColor={graphColors}
|
||||
stopOpacity={0.2}
|
||||
/>
|
||||
<stop
|
||||
offset="100%"
|
||||
stopColor={graphColors}
|
||||
stopOpacity={0.05}
|
||||
/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<Tooltip content={() => null} />
|
||||
<Area
|
||||
<Tooltip content={() => null} cursor={false} />
|
||||
<Bar
|
||||
dataKey={'current'}
|
||||
type="step"
|
||||
fill={`url(#colorUv${id})`}
|
||||
fill={graphColors}
|
||||
fillOpacity={1}
|
||||
stroke={graphColors}
|
||||
strokeWidth={1}
|
||||
strokeWidth={0}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
</AreaChart>
|
||||
</BarChart>
|
||||
)}
|
||||
</AutoSizer>
|
||||
</div>
|
||||
@@ -225,13 +207,11 @@ export function OverviewMetricCardNumber({
|
||||
isLoading?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex min-w-0 flex-col gap-2', className)}>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 items-center gap-2 text-left">
|
||||
<span className="truncate text-sm font-medium text-muted-foreground leading-[1.1]">
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
<div className={cn('min-w-0 col gap-2 items-start', className)}>
|
||||
<div className="flex min-w-0 items-center gap-2 text-left">
|
||||
<span className="truncate text-sm font-medium text-muted-foreground leading-[1.1]">
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
@@ -239,13 +219,13 @@ export function OverviewMetricCardNumber({
|
||||
<Skeleton className="h-6 w-12" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div className="truncate font-mono text-3xl leading-[1.1] font-bold">
|
||||
{value}
|
||||
</div>
|
||||
{enhancer}
|
||||
<div className="truncate font-mono text-3xl leading-[1.1] font-bold">
|
||||
{value}
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute right-0 top-0 bottom-0 center justify-center col pr-4">
|
||||
{enhancer}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { NOT_SET_VALUE } from '@openpanel/constants';
|
||||
import type { IChartType } from '@openpanel/validation';
|
||||
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { pushModal } from '@/modals';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
@@ -13,7 +11,12 @@ import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { Widget, WidgetBody } from '../widget';
|
||||
import { OVERVIEW_COLUMNS_NAME } from './overview-constants';
|
||||
import OverviewDetailsButton from './overview-details-button';
|
||||
import { WidgetButtons, WidgetFooter, WidgetHead } from './overview-widget';
|
||||
import {
|
||||
OverviewLineChart,
|
||||
OverviewLineChartLoading,
|
||||
} from './overview-line-chart';
|
||||
import { OverviewViewToggle, useOverviewView } from './overview-view-toggle';
|
||||
import { WidgetFooter, WidgetHeadSearchable } from './overview-widget';
|
||||
import {
|
||||
OverviewWidgetTableGeneric,
|
||||
OverviewWidgetTableLoading,
|
||||
@@ -31,6 +34,7 @@ export default function OverviewTopDevices({
|
||||
useOverviewOptions();
|
||||
const [filters, setFilter] = useEventQueryFilters();
|
||||
const [chartType] = useState<IChartType>('bar');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const isPageFilter = filters.find((filter) => filter.name === 'path');
|
||||
const [widget, setWidget, widgets] = useOverviewWidget('tech', {
|
||||
device: {
|
||||
@@ -316,6 +320,7 @@ export default function OverviewTopDevices({
|
||||
});
|
||||
|
||||
const trpc = useTRPC();
|
||||
const [view] = useOverviewView();
|
||||
|
||||
const query = useQuery(
|
||||
trpc.overview.topGeneric.queryOptions({
|
||||
@@ -328,31 +333,67 @@ export default function OverviewTopDevices({
|
||||
}),
|
||||
);
|
||||
|
||||
const seriesQuery = useQuery(
|
||||
trpc.overview.topGenericSeries.queryOptions(
|
||||
{
|
||||
projectId,
|
||||
range,
|
||||
filters,
|
||||
column: widget.key,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
},
|
||||
{
|
||||
enabled: view === 'chart',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
const data = (query.data ?? []).slice(0, 15);
|
||||
if (!searchQuery.trim()) {
|
||||
return data;
|
||||
}
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return data.filter((item) => item.name?.toLowerCase().includes(queryLower));
|
||||
}, [query.data, searchQuery]);
|
||||
|
||||
const tabs = widgets.map((w) => ({
|
||||
key: w.key,
|
||||
label: w.btn,
|
||||
}));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Widget className="col-span-6 md:col-span-3">
|
||||
<WidgetHead>
|
||||
<div className="title">{widget.title}</div>
|
||||
|
||||
<WidgetButtons>
|
||||
{widgets.map((w) => (
|
||||
<button
|
||||
type="button"
|
||||
key={w.key}
|
||||
onClick={() => setWidget(w.key)}
|
||||
className={cn(w.key === widget.key && 'active')}
|
||||
>
|
||||
{w.btn}
|
||||
</button>
|
||||
))}
|
||||
</WidgetButtons>
|
||||
</WidgetHead>
|
||||
<WidgetHeadSearchable
|
||||
tabs={tabs}
|
||||
activeTab={widget.key}
|
||||
onTabChange={setWidget}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
|
||||
className="border-b-0 pb-2"
|
||||
/>
|
||||
<WidgetBody className="p-0">
|
||||
{query.isLoading ? (
|
||||
{view === 'chart' ? (
|
||||
seriesQuery.isLoading ? (
|
||||
<OverviewLineChartLoading />
|
||||
) : seriesQuery.data ? (
|
||||
<OverviewLineChart
|
||||
data={seriesQuery.data}
|
||||
interval={interval}
|
||||
searchQuery={searchQuery}
|
||||
/>
|
||||
) : (
|
||||
<OverviewLineChartLoading />
|
||||
)
|
||||
) : query.isLoading ? (
|
||||
<OverviewWidgetTableLoading />
|
||||
) : (
|
||||
<OverviewWidgetTableGeneric
|
||||
data={query.data ?? []}
|
||||
data={filteredData}
|
||||
column={{
|
||||
name: OVERVIEW_COLUMNS_NAME[widget.key],
|
||||
render(item) {
|
||||
@@ -384,7 +425,8 @@ export default function OverviewTopDevices({
|
||||
})
|
||||
}
|
||||
/>
|
||||
{/* <OverviewChartToggle {...{ chartType, setChartType }} /> */}
|
||||
<div className="flex-1" />
|
||||
<OverviewViewToggle />
|
||||
</WidgetFooter>
|
||||
</Widget>
|
||||
</>
|
||||
|
||||
@@ -1,225 +1,172 @@
|
||||
import { ReportChart } from '@/components/report-chart';
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import type { IChartType } from '@openpanel/validation';
|
||||
import type { IReportInput } from '@openpanel/validation';
|
||||
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Widget, WidgetBody } from '../widget';
|
||||
import { OverviewChartToggle } from './overview-chart-toggle';
|
||||
import { WidgetButtons, WidgetFooter, WidgetHead } from './overview-widget';
|
||||
import { WidgetFooter, WidgetHeadSearchable } from './overview-widget';
|
||||
import {
|
||||
type EventTableItem,
|
||||
OverviewWidgetTableEvents,
|
||||
OverviewWidgetTableLoading,
|
||||
} from './overview-widget-table';
|
||||
import { useOverviewOptions } from './useOverviewOptions';
|
||||
import { useOverviewWidget } from './useOverviewWidget';
|
||||
import { useOverviewWidgetV2 } from './useOverviewWidget';
|
||||
|
||||
export interface OverviewTopEventsProps {
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
export default function OverviewTopEvents({
|
||||
projectId,
|
||||
}: OverviewTopEventsProps) {
|
||||
const { interval, range, previous, startDate, endDate } =
|
||||
useOverviewOptions();
|
||||
const [filters] = useEventQueryFilters();
|
||||
const [filters, setFilter] = useEventQueryFilters();
|
||||
const trpc = useTRPC();
|
||||
const { data: conversions } = useQuery(
|
||||
trpc.event.conversionNames.queryOptions({ projectId }),
|
||||
);
|
||||
const [chartType, setChartType] = useState<IChartType>('bar');
|
||||
const [widget, setWidget, widgets] = useOverviewWidget('ev', {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
const [widget, setWidget, widgets] = useOverviewWidgetV2('ev', {
|
||||
your: {
|
||||
title: 'Top events',
|
||||
btn: 'Your',
|
||||
chart: {
|
||||
report: {
|
||||
limit: 10,
|
||||
projectId,
|
||||
startDate,
|
||||
endDate,
|
||||
series: [
|
||||
{
|
||||
type: 'event',
|
||||
segment: 'event',
|
||||
filters: [
|
||||
...filters,
|
||||
{
|
||||
id: 'ex_session',
|
||||
name: 'name',
|
||||
operator: 'isNot',
|
||||
value: ['session_start', 'session_end', 'screen_view'],
|
||||
},
|
||||
],
|
||||
id: 'A',
|
||||
name: '*',
|
||||
},
|
||||
],
|
||||
breakdowns: [
|
||||
{
|
||||
id: 'A',
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
chartType,
|
||||
lineType: 'monotone',
|
||||
interval: interval,
|
||||
name: 'Your top events',
|
||||
range: range,
|
||||
previous: previous,
|
||||
metric: 'sum',
|
||||
},
|
||||
},
|
||||
},
|
||||
all: {
|
||||
title: 'Top events',
|
||||
btn: 'All',
|
||||
chart: {
|
||||
report: {
|
||||
limit: 10,
|
||||
projectId,
|
||||
startDate,
|
||||
endDate,
|
||||
series: [
|
||||
{
|
||||
type: 'event',
|
||||
segment: 'event',
|
||||
filters: [...filters],
|
||||
id: 'A',
|
||||
name: '*',
|
||||
},
|
||||
],
|
||||
breakdowns: [
|
||||
{
|
||||
id: 'A',
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
chartType,
|
||||
lineType: 'monotone',
|
||||
interval: interval,
|
||||
name: 'All top events',
|
||||
range: range,
|
||||
previous: previous,
|
||||
metric: 'sum',
|
||||
},
|
||||
title: 'Events',
|
||||
btn: 'Events',
|
||||
meta: {
|
||||
filters: [
|
||||
{
|
||||
id: 'ex_session',
|
||||
name: 'name',
|
||||
operator: 'isNot',
|
||||
value: ['session_start', 'session_end', 'screen_view'],
|
||||
},
|
||||
],
|
||||
eventName: '*',
|
||||
},
|
||||
},
|
||||
conversions: {
|
||||
title: 'Conversions',
|
||||
btn: 'Conversions',
|
||||
hide: !conversions || conversions.length === 0,
|
||||
chart: {
|
||||
report: {
|
||||
limit: 10,
|
||||
projectId,
|
||||
startDate,
|
||||
endDate,
|
||||
series: [
|
||||
{
|
||||
type: 'event',
|
||||
segment: 'event',
|
||||
filters: [
|
||||
...filters,
|
||||
{
|
||||
id: 'conversion',
|
||||
name: 'name',
|
||||
operator: 'is',
|
||||
value: conversions?.map((c) => c.name) ?? [],
|
||||
},
|
||||
],
|
||||
id: 'A',
|
||||
name: '*',
|
||||
},
|
||||
],
|
||||
breakdowns: [
|
||||
{
|
||||
id: 'A',
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
chartType,
|
||||
lineType: 'monotone',
|
||||
interval: interval,
|
||||
name: 'Conversions',
|
||||
range: range,
|
||||
previous: previous,
|
||||
metric: 'sum',
|
||||
},
|
||||
meta: {
|
||||
filters: [
|
||||
{
|
||||
id: 'conversion',
|
||||
name: 'name',
|
||||
operator: 'is',
|
||||
value: conversions?.map((c) => c.name) ?? [],
|
||||
},
|
||||
],
|
||||
eventName: '*',
|
||||
},
|
||||
},
|
||||
link_out: {
|
||||
title: 'Link out',
|
||||
btn: 'Link out',
|
||||
chart: {
|
||||
report: {
|
||||
limit: 10,
|
||||
projectId,
|
||||
startDate,
|
||||
endDate,
|
||||
series: [
|
||||
{
|
||||
type: 'event',
|
||||
segment: 'event',
|
||||
id: 'A',
|
||||
name: 'link_out',
|
||||
filters: [],
|
||||
},
|
||||
],
|
||||
breakdowns: [
|
||||
{
|
||||
id: 'A',
|
||||
name: 'properties.href',
|
||||
},
|
||||
],
|
||||
chartType,
|
||||
lineType: 'monotone',
|
||||
interval: interval,
|
||||
name: 'Link out',
|
||||
range: range,
|
||||
previous: previous,
|
||||
metric: 'sum',
|
||||
},
|
||||
meta: {
|
||||
filters: [],
|
||||
eventName: 'link_out',
|
||||
breakdownProperty: 'properties.href',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const report: IReportInput = useMemo(
|
||||
() => ({
|
||||
limit: 1000,
|
||||
projectId,
|
||||
startDate,
|
||||
endDate,
|
||||
series: [
|
||||
{
|
||||
type: 'event' as const,
|
||||
segment: 'event' as const,
|
||||
filters: [...filters, ...(widget.meta?.filters ?? [])],
|
||||
id: 'A',
|
||||
name: widget.meta?.eventName ?? '*',
|
||||
},
|
||||
],
|
||||
breakdowns: [
|
||||
{
|
||||
id: 'A',
|
||||
name: widget.meta?.breakdownProperty ?? 'name',
|
||||
},
|
||||
],
|
||||
chartType: 'bar' as const,
|
||||
interval,
|
||||
range,
|
||||
previous,
|
||||
metric: 'sum' as const,
|
||||
}),
|
||||
[projectId, startDate, endDate, filters, widget, interval, range, previous],
|
||||
);
|
||||
|
||||
const query = useQuery(trpc.chart.aggregate.queryOptions(report));
|
||||
|
||||
const tableData: EventTableItem[] = useMemo(() => {
|
||||
if (!query.data?.series) return [];
|
||||
|
||||
return query.data.series.map((serie) => ({
|
||||
id: serie.id,
|
||||
name: serie.names[serie.names.length - 1] ?? serie.names[0] ?? '',
|
||||
count: serie.metrics.sum,
|
||||
}));
|
||||
}, [query.data]);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (!searchQuery.trim()) {
|
||||
return tableData.slice(0, 15);
|
||||
}
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return tableData
|
||||
.filter((item) => item.name?.toLowerCase().includes(queryLower))
|
||||
.slice(0, 15);
|
||||
}, [tableData, searchQuery]);
|
||||
|
||||
const tabs = useMemo(
|
||||
() =>
|
||||
widgets
|
||||
.filter((item) => item.hide !== true)
|
||||
.map((w) => ({
|
||||
key: w.key,
|
||||
label: w.btn,
|
||||
})),
|
||||
[widgets],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Widget className="col-span-6 md:col-span-3">
|
||||
<WidgetHead>
|
||||
<div className="title">{widget.title}</div>
|
||||
<WidgetButtons>
|
||||
{widgets
|
||||
.filter((item) => item.hide !== true)
|
||||
.map((w) => (
|
||||
<button
|
||||
type="button"
|
||||
key={w.key}
|
||||
onClick={() => setWidget(w.key)}
|
||||
className={cn(w.key === widget.key && 'active')}
|
||||
>
|
||||
{w.btn}
|
||||
</button>
|
||||
))}
|
||||
</WidgetButtons>
|
||||
</WidgetHead>
|
||||
<WidgetBody className="p-3">
|
||||
<ReportChart
|
||||
options={{
|
||||
hideID: true,
|
||||
columns: ['Event'],
|
||||
renderSerieName(names) {
|
||||
return names[1];
|
||||
},
|
||||
}}
|
||||
report={{
|
||||
...widget.chart.report,
|
||||
previous: false,
|
||||
}}
|
||||
/>
|
||||
<WidgetHeadSearchable
|
||||
tabs={tabs}
|
||||
activeTab={widget.key}
|
||||
onTabChange={setWidget}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
|
||||
className="border-b-0 pb-2"
|
||||
/>
|
||||
<WidgetBody className="p-0">
|
||||
{query.isLoading ? (
|
||||
<OverviewWidgetTableLoading />
|
||||
) : (
|
||||
<OverviewWidgetTableEvents
|
||||
data={filteredData}
|
||||
onItemClick={(name) => {
|
||||
if (widget.meta?.breakdownProperty) {
|
||||
setFilter(widget.meta.breakdownProperty, name);
|
||||
} else {
|
||||
setFilter('name', name);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</WidgetBody>
|
||||
<WidgetFooter>
|
||||
<OverviewChartToggle {...{ chartType, setChartType }} />
|
||||
<div className="flex-1" />
|
||||
</WidgetFooter>
|
||||
</Widget>
|
||||
</>
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { ModalContent, ModalHeader } from '@/modals/Modal/Container';
|
||||
import type { IGetTopGenericInput } from '@openpanel/db';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ChevronRightIcon } from 'lucide-react';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { Button } from '../ui/button';
|
||||
import { ScrollArea } from '../ui/scroll-area';
|
||||
import {
|
||||
OVERVIEW_COLUMNS_NAME,
|
||||
OVERVIEW_COLUMNS_NAME_PLURAL,
|
||||
} from './overview-constants';
|
||||
import { OverviewWidgetTableGeneric } from './overview-widget-table';
|
||||
import { OverviewListModal } from './overview-list-modal';
|
||||
import { useOverviewOptions } from './useOverviewOptions';
|
||||
|
||||
interface OverviewTopGenericModalProps {
|
||||
@@ -24,83 +21,55 @@ export default function OverviewTopGenericModal({
|
||||
projectId,
|
||||
column,
|
||||
}: OverviewTopGenericModalProps) {
|
||||
const [filters, setFilter] = useEventQueryFilters();
|
||||
const [_filters, setFilter] = useEventQueryFilters();
|
||||
const { startDate, endDate, range } = useOverviewOptions();
|
||||
const trpc = useTRPC();
|
||||
const query = useInfiniteQuery(
|
||||
trpc.overview.topGeneric.infiniteQueryOptions(
|
||||
{
|
||||
projectId,
|
||||
filters,
|
||||
startDate,
|
||||
endDate,
|
||||
range,
|
||||
limit: 50,
|
||||
column,
|
||||
},
|
||||
{
|
||||
getNextPageParam: (lastPage, pages) => {
|
||||
if (lastPage.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return pages.length + 1;
|
||||
},
|
||||
},
|
||||
),
|
||||
const query = useQuery(
|
||||
trpc.overview.topGeneric.queryOptions({
|
||||
projectId,
|
||||
filters: _filters,
|
||||
startDate,
|
||||
endDate,
|
||||
range,
|
||||
column,
|
||||
}),
|
||||
);
|
||||
|
||||
const data = query.data?.pages.flat() || [];
|
||||
const isEmpty = !query.hasNextPage && !query.isFetching;
|
||||
|
||||
const columnNamePlural = OVERVIEW_COLUMNS_NAME_PLURAL[column];
|
||||
const columnName = OVERVIEW_COLUMNS_NAME[column];
|
||||
|
||||
return (
|
||||
<ModalContent>
|
||||
<ModalHeader title={`Top ${columnNamePlural}`} />
|
||||
<ScrollArea className="-mx-6 px-2">
|
||||
<OverviewWidgetTableGeneric
|
||||
data={data}
|
||||
column={{
|
||||
name: columnName,
|
||||
render(item) {
|
||||
return (
|
||||
<div className="row items-center gap-2 min-w-0 relative">
|
||||
<SerieIcon name={item.prefix || item.name} />
|
||||
<button
|
||||
type="button"
|
||||
className="truncate"
|
||||
onClick={() => {
|
||||
setFilter(column, item.name);
|
||||
}}
|
||||
>
|
||||
{item.prefix && (
|
||||
<span className="mr-1 row inline-flex items-center gap-1">
|
||||
<span>{item.prefix}</span>
|
||||
<span>
|
||||
<ChevronRightIcon className="size-3" />
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{item.name || 'Not set'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<div className="row center-center p-4 pb-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => query.fetchNextPage()}
|
||||
disabled={isEmpty}
|
||||
<OverviewListModal
|
||||
title={`Top ${columnNamePlural}`}
|
||||
searchPlaceholder={`Search ${columnNamePlural.toLowerCase()}...`}
|
||||
data={query.data ?? []}
|
||||
keyExtractor={(item) => (item.prefix ?? '') + item.name}
|
||||
searchFilter={(item, query) =>
|
||||
item.name?.toLowerCase().includes(query) ||
|
||||
item.prefix?.toLowerCase().includes(query) ||
|
||||
false
|
||||
}
|
||||
columnName={columnName}
|
||||
renderItem={(item) => (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<SerieIcon name={item.prefix || item.name} />
|
||||
<button
|
||||
type="button"
|
||||
className="truncate hover:underline"
|
||||
onClick={() => {
|
||||
setFilter(column, item.name);
|
||||
}}
|
||||
>
|
||||
Load more
|
||||
</Button>
|
||||
{item.prefix && (
|
||||
<span className="mr-1 inline-flex items-center gap-1">
|
||||
<span>{item.prefix}</span>
|
||||
<ChevronRightIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{item.name || 'Not set'}
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</ModalContent>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import type { IChartType } from '@openpanel/validation';
|
||||
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { pushModal } from '@/modals';
|
||||
import { countries } from '@/translations/countries';
|
||||
@@ -13,10 +11,20 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { ChevronRightIcon } from 'lucide-react';
|
||||
import { ReportChart } from '../report-chart';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { ReportChartShortcut } from '../report-chart/shortcut';
|
||||
import { Widget, WidgetBody } from '../widget';
|
||||
import { OVERVIEW_COLUMNS_NAME } from './overview-constants';
|
||||
import OverviewDetailsButton from './overview-details-button';
|
||||
import { WidgetButtons, WidgetFooter, WidgetHead } from './overview-widget';
|
||||
import {
|
||||
OverviewLineChart,
|
||||
OverviewLineChartLoading,
|
||||
} from './overview-line-chart';
|
||||
import { OverviewViewToggle, useOverviewView } from './overview-view-toggle';
|
||||
import {
|
||||
WidgetFooter,
|
||||
WidgetHead,
|
||||
WidgetHeadSearchable,
|
||||
} from './overview-widget';
|
||||
import {
|
||||
OverviewWidgetTableGeneric,
|
||||
OverviewWidgetTableLoading,
|
||||
@@ -32,6 +40,7 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
useOverviewOptions();
|
||||
const [chartType, setChartType] = useState<IChartType>('bar');
|
||||
const [filters, setFilter] = useEventQueryFilters();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const isPageFilter = filters.find((filter) => filter.name === 'path');
|
||||
const [widget, setWidget, widgets] = useOverviewWidgetV2('geo', {
|
||||
country: {
|
||||
@@ -48,8 +57,8 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
},
|
||||
});
|
||||
|
||||
const number = useNumber();
|
||||
const trpc = useTRPC();
|
||||
const [view] = useOverviewView();
|
||||
|
||||
const query = useQuery(
|
||||
trpc.overview.topGeneric.queryOptions({
|
||||
@@ -62,31 +71,74 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
}),
|
||||
);
|
||||
|
||||
const seriesQuery = useQuery(
|
||||
trpc.overview.topGenericSeries.queryOptions(
|
||||
{
|
||||
projectId,
|
||||
range,
|
||||
filters,
|
||||
column: widget.key,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
},
|
||||
{
|
||||
enabled: view === 'chart',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
const data = (query.data ?? []).slice(0, 15);
|
||||
if (!searchQuery.trim()) {
|
||||
return data;
|
||||
}
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return data.filter(
|
||||
(item) =>
|
||||
item.name?.toLowerCase().includes(queryLower) ||
|
||||
item.prefix?.toLowerCase().includes(queryLower) ||
|
||||
countries[item.name as keyof typeof countries]
|
||||
?.toLowerCase()
|
||||
.includes(queryLower),
|
||||
);
|
||||
}, [query.data, searchQuery]);
|
||||
|
||||
const tabs = widgets.map((w) => ({
|
||||
key: w.key,
|
||||
label: w.btn,
|
||||
}));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Widget className="col-span-6 md:col-span-3">
|
||||
<WidgetHead>
|
||||
<div className="title">{widget.title}</div>
|
||||
|
||||
<WidgetButtons>
|
||||
{widgets.map((w) => (
|
||||
<button
|
||||
type="button"
|
||||
key={w.key}
|
||||
onClick={() => setWidget(w.key)}
|
||||
className={cn(w.key === widget.key && 'active')}
|
||||
>
|
||||
{w.btn}
|
||||
</button>
|
||||
))}
|
||||
</WidgetButtons>
|
||||
</WidgetHead>
|
||||
<WidgetHeadSearchable
|
||||
tabs={tabs}
|
||||
activeTab={widget.key}
|
||||
onTabChange={setWidget}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
|
||||
className="border-b-0 pb-2"
|
||||
/>
|
||||
<WidgetBody className="p-0">
|
||||
{query.isLoading ? (
|
||||
{view === 'chart' ? (
|
||||
seriesQuery.isLoading ? (
|
||||
<OverviewLineChartLoading />
|
||||
) : seriesQuery.data ? (
|
||||
<OverviewLineChart
|
||||
data={seriesQuery.data}
|
||||
interval={interval}
|
||||
searchQuery={searchQuery}
|
||||
/>
|
||||
) : (
|
||||
<OverviewLineChartLoading />
|
||||
)
|
||||
) : query.isLoading ? (
|
||||
<OverviewWidgetTableLoading />
|
||||
) : (
|
||||
<OverviewWidgetTableGeneric
|
||||
data={query.data ?? []}
|
||||
data={filteredData}
|
||||
column={{
|
||||
name: OVERVIEW_COLUMNS_NAME[widget.key],
|
||||
render(item) {
|
||||
@@ -130,7 +182,7 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
/>
|
||||
)}
|
||||
</WidgetBody>
|
||||
<WidgetFooter>
|
||||
<WidgetFooter className="row items-center justify-between">
|
||||
<OverviewDetailsButton
|
||||
onClick={() =>
|
||||
pushModal('OverviewTopGenericModal', {
|
||||
@@ -139,7 +191,19 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
})
|
||||
}
|
||||
/>
|
||||
{/* <OverviewChartToggle {...{ chartType, setChartType }} /> */}
|
||||
<div className="flex-1" />
|
||||
<OverviewViewToggle />
|
||||
<span className="text-sm text-muted-foreground pr-2 ml-2">
|
||||
Geo data provided by{' '}
|
||||
<a
|
||||
href="https://ipdata.co"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
className="hover:underline"
|
||||
>
|
||||
MaxMind
|
||||
</a>
|
||||
</span>
|
||||
</WidgetFooter>
|
||||
</Widget>
|
||||
<Widget className="col-span-6 md:col-span-3">
|
||||
@@ -147,9 +211,8 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
<div className="title">Map</div>
|
||||
</WidgetHead>
|
||||
<WidgetBody>
|
||||
<ReportChart
|
||||
options={{ hideID: true }}
|
||||
report={{
|
||||
<ReportChartShortcut
|
||||
{...{
|
||||
projectId,
|
||||
startDate,
|
||||
endDate,
|
||||
@@ -169,12 +232,9 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
|
||||
},
|
||||
],
|
||||
chartType: 'map',
|
||||
lineType: 'monotone',
|
||||
interval: interval,
|
||||
name: 'Top sources',
|
||||
range: range,
|
||||
previous: previous,
|
||||
metric: 'sum',
|
||||
}}
|
||||
/>
|
||||
</WidgetBody>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { ModalContent, ModalHeader } from '@/modals/Modal/Container';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { Button } from '../ui/button';
|
||||
import { ScrollArea } from '../ui/scroll-area';
|
||||
import { OverviewWidgetTablePages } from './overview-widget-table';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ExternalLinkIcon } from 'lucide-react';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { Tooltiper } from '../ui/tooltip';
|
||||
import { OverviewListModal } from './overview-list-modal';
|
||||
import { useOverviewOptions } from './useOverviewOptions';
|
||||
|
||||
interface OverviewTopPagesProps {
|
||||
@@ -18,44 +18,54 @@ export default function OverviewTopPagesModal({
|
||||
const [filters, setFilter] = useEventQueryFilters();
|
||||
const { startDate, endDate, range } = useOverviewOptions();
|
||||
const trpc = useTRPC();
|
||||
const query = useInfiniteQuery(
|
||||
trpc.overview.topPages.infiniteQueryOptions(
|
||||
{
|
||||
projectId,
|
||||
filters,
|
||||
startDate,
|
||||
endDate,
|
||||
mode: 'page',
|
||||
range,
|
||||
limit: 50,
|
||||
},
|
||||
{
|
||||
getNextPageParam: (_, pages) => pages.length + 1,
|
||||
},
|
||||
),
|
||||
const query = useQuery(
|
||||
trpc.overview.topPages.queryOptions({
|
||||
projectId,
|
||||
filters,
|
||||
startDate,
|
||||
endDate,
|
||||
mode: 'page',
|
||||
range,
|
||||
}),
|
||||
);
|
||||
|
||||
const data = query.data?.pages.flat();
|
||||
|
||||
return (
|
||||
<ModalContent>
|
||||
<ModalHeader title="Top Pages" />
|
||||
<ScrollArea className="-mx-6 px-2">
|
||||
<OverviewWidgetTablePages
|
||||
data={data ?? []}
|
||||
lastColumnName={'Sessions'}
|
||||
/>
|
||||
<div className="row center-center p-4 pb-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => query.fetchNextPage()}
|
||||
loading={query.isFetching}
|
||||
>
|
||||
Load more
|
||||
</Button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</ModalContent>
|
||||
<OverviewListModal
|
||||
title="Top Pages"
|
||||
searchPlaceholder="Search pages..."
|
||||
data={query.data ?? []}
|
||||
keyExtractor={(item) => item.path + item.origin}
|
||||
searchFilter={(item, query) =>
|
||||
item.path.toLowerCase().includes(query) ||
|
||||
item.origin.toLowerCase().includes(query)
|
||||
}
|
||||
columnName="Path"
|
||||
renderItem={(item) => (
|
||||
<Tooltiper asChild content={item.origin + item.path} side="left">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<SerieIcon name={item.origin} />
|
||||
<button
|
||||
type="button"
|
||||
className="truncate hover:underline"
|
||||
onClick={() => {
|
||||
setFilter('path', item.path);
|
||||
setFilter('origin', item.origin);
|
||||
}}
|
||||
>
|
||||
{item.path || <span className="opacity-40">Not set</span>}
|
||||
</button>
|
||||
<a
|
||||
href={item.origin + item.path}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
<ExternalLinkIcon className="size-3 opacity-0 group-hover/row:opacity-100 transition-opacity" />
|
||||
</a>
|
||||
</div>
|
||||
</Tooltiper>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { Globe2Icon } from 'lucide-react';
|
||||
import { parseAsBoolean, useQueryState } from 'nuqs';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { pushModal } from '@/modals';
|
||||
@@ -9,8 +9,9 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '../ui/button';
|
||||
import { Widget, WidgetBody } from '../widget';
|
||||
import OverviewDetailsButton from './overview-details-button';
|
||||
import { WidgetButtons, WidgetFooter, WidgetHead } from './overview-widget';
|
||||
import { WidgetFooter, WidgetHeadSearchable } from './overview-widget';
|
||||
import {
|
||||
OverviewWidgetTableEntries,
|
||||
OverviewWidgetTableLoading,
|
||||
OverviewWidgetTablePages,
|
||||
} from './overview-widget-table';
|
||||
@@ -25,15 +26,11 @@ export default function OverviewTopPages({ projectId }: OverviewTopPagesProps) {
|
||||
const { interval, range, startDate, endDate } = useOverviewOptions();
|
||||
const [filters] = useEventQueryFilters();
|
||||
const [domain, setDomain] = useQueryState('d', parseAsBoolean);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [widget, setWidget, widgets] = useOverviewWidgetV2('pages', {
|
||||
page: {
|
||||
title: 'Top pages',
|
||||
btn: 'Top pages',
|
||||
meta: {
|
||||
columns: {
|
||||
sessions: 'Sessions',
|
||||
},
|
||||
},
|
||||
btn: 'Pages',
|
||||
},
|
||||
entry: {
|
||||
title: 'Entry Pages',
|
||||
@@ -53,10 +50,6 @@ export default function OverviewTopPages({ projectId }: OverviewTopPagesProps) {
|
||||
},
|
||||
},
|
||||
},
|
||||
// bot: {
|
||||
// title: 'Bots',
|
||||
// btn: 'Bots',
|
||||
// },
|
||||
});
|
||||
const trpc = useTRPC();
|
||||
|
||||
@@ -71,37 +64,53 @@ export default function OverviewTopPages({ projectId }: OverviewTopPagesProps) {
|
||||
}),
|
||||
);
|
||||
|
||||
const data = query.data;
|
||||
const filteredData = useMemo(() => {
|
||||
const data = query.data?.slice(0, 15) ?? [];
|
||||
if (!searchQuery.trim()) {
|
||||
return data;
|
||||
}
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return data.filter(
|
||||
(item) =>
|
||||
item.path.toLowerCase().includes(queryLower) ||
|
||||
item.origin.toLowerCase().includes(queryLower),
|
||||
);
|
||||
}, [query.data, searchQuery]);
|
||||
|
||||
const tabs = widgets.map((w) => ({
|
||||
key: w.key,
|
||||
label: w.btn,
|
||||
}));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Widget className="col-span-6 md:col-span-3">
|
||||
<WidgetHead>
|
||||
<div className="title">{widget.title}</div>
|
||||
<WidgetButtons>
|
||||
{widgets.map((w) => (
|
||||
<button
|
||||
type="button"
|
||||
key={w.key}
|
||||
onClick={() => setWidget(w.key)}
|
||||
className={cn(w.key === widget.key && 'active')}
|
||||
>
|
||||
{w.btn}
|
||||
</button>
|
||||
))}
|
||||
</WidgetButtons>
|
||||
</WidgetHead>
|
||||
<WidgetHeadSearchable
|
||||
tabs={tabs}
|
||||
activeTab={widget.key}
|
||||
onTabChange={setWidget}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
|
||||
className="border-b-0 pb-2"
|
||||
/>
|
||||
<WidgetBody className="p-0">
|
||||
{query.isLoading ? (
|
||||
<OverviewWidgetTableLoading />
|
||||
) : (
|
||||
<>
|
||||
{/*<OverviewWidgetTableBots data={data ?? []} />*/}
|
||||
<OverviewWidgetTablePages
|
||||
data={data ?? []}
|
||||
lastColumnName={widget.meta.columns.sessions}
|
||||
showDomain={!!domain}
|
||||
/>
|
||||
{widget.meta?.columns.sessions ? (
|
||||
<OverviewWidgetTableEntries
|
||||
data={filteredData}
|
||||
lastColumnName={widget.meta.columns.sessions}
|
||||
showDomain={!!domain}
|
||||
/>
|
||||
) : (
|
||||
<OverviewWidgetTablePages
|
||||
data={filteredData}
|
||||
showDomain={!!domain}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</WidgetBody>
|
||||
@@ -109,7 +118,6 @@ export default function OverviewTopPages({ projectId }: OverviewTopPagesProps) {
|
||||
<OverviewDetailsButton
|
||||
onClick={() => pushModal('OverviewTopPagesModal', { projectId })}
|
||||
/>
|
||||
{/* <OverviewChartToggle {...{ chartType, setChartType }} /> */}
|
||||
<div className="flex-1" />
|
||||
<Button
|
||||
variant={'ghost'}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { pushModal } from '@/modals';
|
||||
@@ -9,7 +9,12 @@ import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
import { Widget, WidgetBody } from '../widget';
|
||||
import { OVERVIEW_COLUMNS_NAME } from './overview-constants';
|
||||
import OverviewDetailsButton from './overview-details-button';
|
||||
import { WidgetButtons, WidgetFooter, WidgetHead } from './overview-widget';
|
||||
import {
|
||||
OverviewLineChart,
|
||||
OverviewLineChartLoading,
|
||||
} from './overview-line-chart';
|
||||
import { OverviewViewToggle, useOverviewView } from './overview-view-toggle';
|
||||
import { WidgetFooter, WidgetHeadSearchable } from './overview-widget';
|
||||
import {
|
||||
OverviewWidgetTableGeneric,
|
||||
OverviewWidgetTableLoading,
|
||||
@@ -23,16 +28,18 @@ interface OverviewTopSourcesProps {
|
||||
export default function OverviewTopSources({
|
||||
projectId,
|
||||
}: OverviewTopSourcesProps) {
|
||||
const { range, startDate, endDate } = useOverviewOptions();
|
||||
const { interval, range, startDate, endDate } = useOverviewOptions();
|
||||
const [filters, setFilter] = useEventQueryFilters();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [view] = useOverviewView();
|
||||
const [widget, setWidget, widgets] = useOverviewWidgetV2('sources', {
|
||||
referrer_name: {
|
||||
title: 'Top sources',
|
||||
btn: 'All',
|
||||
btn: 'Refs',
|
||||
},
|
||||
referrer: {
|
||||
title: 'Top urls',
|
||||
btn: 'URLs',
|
||||
btn: 'Urls',
|
||||
},
|
||||
referrer_type: {
|
||||
title: 'Top types',
|
||||
@@ -72,31 +79,67 @@ export default function OverviewTopSources({
|
||||
}),
|
||||
);
|
||||
|
||||
const seriesQuery = useQuery(
|
||||
trpc.overview.topGenericSeries.queryOptions(
|
||||
{
|
||||
projectId,
|
||||
range,
|
||||
filters,
|
||||
column: widget.key,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
},
|
||||
{
|
||||
enabled: view === 'chart',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
const data = (query.data ?? []).slice(0, 15);
|
||||
if (!searchQuery.trim()) {
|
||||
return data;
|
||||
}
|
||||
const queryLower = searchQuery.toLowerCase();
|
||||
return data.filter((item) => item.name?.toLowerCase().includes(queryLower));
|
||||
}, [query.data, searchQuery]);
|
||||
|
||||
const tabs = widgets.map((w) => ({
|
||||
key: w.key,
|
||||
label: w.btn,
|
||||
}));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Widget className="col-span-6 md:col-span-3">
|
||||
<WidgetHead>
|
||||
<div className="title">{widget.title}</div>
|
||||
|
||||
<WidgetButtons>
|
||||
{widgets.map((w) => (
|
||||
<button
|
||||
type="button"
|
||||
key={w.key}
|
||||
onClick={() => setWidget(w.key)}
|
||||
className={cn(w.key === widget.key && 'active')}
|
||||
>
|
||||
{w.btn}
|
||||
</button>
|
||||
))}
|
||||
</WidgetButtons>
|
||||
</WidgetHead>
|
||||
<WidgetHeadSearchable
|
||||
tabs={tabs}
|
||||
activeTab={widget.key}
|
||||
onTabChange={setWidget}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
|
||||
className="border-b-0 pb-2"
|
||||
/>
|
||||
<WidgetBody className="p-0">
|
||||
{query.isLoading ? (
|
||||
{view === 'chart' ? (
|
||||
seriesQuery.isLoading ? (
|
||||
<OverviewLineChartLoading />
|
||||
) : seriesQuery.data ? (
|
||||
<OverviewLineChart
|
||||
data={seriesQuery.data}
|
||||
interval={interval}
|
||||
searchQuery={searchQuery}
|
||||
/>
|
||||
) : (
|
||||
<OverviewLineChartLoading />
|
||||
)
|
||||
) : query.isLoading ? (
|
||||
<OverviewWidgetTableLoading />
|
||||
) : (
|
||||
<OverviewWidgetTableGeneric
|
||||
data={query.data ?? []}
|
||||
data={filteredData}
|
||||
column={{
|
||||
name: OVERVIEW_COLUMNS_NAME[widget.key],
|
||||
render(item) {
|
||||
@@ -137,7 +180,8 @@ export default function OverviewTopSources({
|
||||
})
|
||||
}
|
||||
/>
|
||||
{/* <OverviewChartToggle {...{ chartType, setChartType }} /> */}
|
||||
<div className="flex-1" />
|
||||
<OverviewViewToggle />
|
||||
</WidgetFooter>
|
||||
</Widget>
|
||||
</>
|
||||
|
||||
408
apps/start/src/components/overview/overview-user-journey.tsx
Normal file
@@ -0,0 +1,408 @@
|
||||
import {
|
||||
ChartTooltipContainer,
|
||||
ChartTooltipHeader,
|
||||
ChartTooltipItem,
|
||||
} from '@/components/charts/chart-tooltip';
|
||||
import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { round } from '@/utils/math';
|
||||
import { ResponsiveSankey } from '@nivo/sankey';
|
||||
import { parseAsInteger, useQueryState } from 'nuqs';
|
||||
import {
|
||||
type ReactNode,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { truncate } from '@/utils/truncate';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowRightIcon } from 'lucide-react';
|
||||
import { useTheme } from '../theme-provider';
|
||||
import { Widget, WidgetBody } from '../widget';
|
||||
import { WidgetButtons, WidgetFooter, WidgetHead } from './overview-widget';
|
||||
import { useOverviewOptions } from './useOverviewOptions';
|
||||
|
||||
interface OverviewUserJourneyProps {
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
type PortalTooltipPosition = { left: number; top: number; ready: boolean };
|
||||
|
||||
const showPath = (string: string) => {
|
||||
try {
|
||||
const url = new URL(string);
|
||||
return url.pathname;
|
||||
} catch {
|
||||
return string;
|
||||
}
|
||||
};
|
||||
|
||||
const showDomain = (string: string) => {
|
||||
try {
|
||||
const url = new URL(string);
|
||||
return url.hostname;
|
||||
} catch {
|
||||
return string;
|
||||
}
|
||||
};
|
||||
|
||||
function SankeyPortalTooltip({
|
||||
children,
|
||||
offset = 12,
|
||||
padding = 8,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
offset?: number;
|
||||
padding?: number;
|
||||
}) {
|
||||
const anchorRef = useRef<HTMLSpanElement | null>(null);
|
||||
const tooltipRef = useRef<HTMLDivElement | null>(null);
|
||||
const [anchorRect, setAnchorRect] = useState<DOMRect | null>(null);
|
||||
const [pos, setPos] = useState<PortalTooltipPosition>({
|
||||
left: 0,
|
||||
top: 0,
|
||||
ready: false,
|
||||
});
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = anchorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
// Nivo renders the tooltip content inside an absolutely-positioned wrapper <div>.
|
||||
// The wrapper is the immediate parent of our rendered content.
|
||||
const wrapper = el.parentElement;
|
||||
if (!wrapper) return;
|
||||
|
||||
const update = () => {
|
||||
setAnchorRect(wrapper.getBoundingClientRect());
|
||||
};
|
||||
|
||||
update();
|
||||
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(wrapper);
|
||||
|
||||
window.addEventListener('scroll', update, true);
|
||||
window.addEventListener('resize', update);
|
||||
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
window.removeEventListener('scroll', update, true);
|
||||
window.removeEventListener('resize', update);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!mounted) return;
|
||||
if (!anchorRect) return;
|
||||
const tooltipEl = tooltipRef.current;
|
||||
if (!tooltipEl) return;
|
||||
|
||||
const rect = tooltipEl.getBoundingClientRect();
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
|
||||
// Start by following Nivo's tooltip anchor position.
|
||||
let left = anchorRect.left + offset;
|
||||
let top = anchorRect.top + offset;
|
||||
|
||||
// Clamp inside viewport with a little padding.
|
||||
left = Math.min(
|
||||
Math.max(padding, left),
|
||||
Math.max(padding, vw - rect.width - padding),
|
||||
);
|
||||
top = Math.min(
|
||||
Math.max(padding, top),
|
||||
Math.max(padding, vh - rect.height - padding),
|
||||
);
|
||||
|
||||
setPos({ left, top, ready: true });
|
||||
}, [mounted, anchorRect, children, offset, padding]);
|
||||
|
||||
// SSR safety: on the server, just render the tooltip normally.
|
||||
if (typeof document === 'undefined') {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Render a tiny (screen-reader-only) anchor inside Nivo's tooltip wrapper. */}
|
||||
<span ref={anchorRef} className="sr-only" />
|
||||
{mounted &&
|
||||
createPortal(
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
className="pointer-events-none fixed z-[9999]"
|
||||
style={{
|
||||
left: pos.left,
|
||||
top: pos.top,
|
||||
visibility: pos.ready ? 'visible' : 'hidden',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function OverviewUserJourney({
|
||||
projectId,
|
||||
}: OverviewUserJourneyProps) {
|
||||
const { range, startDate, endDate } = useOverviewOptions();
|
||||
const [filters] = useEventQueryFilters();
|
||||
const [steps, setSteps] = useQueryState(
|
||||
'journeySteps',
|
||||
parseAsInteger.withDefault(5).withOptions({ history: 'push' }),
|
||||
);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const trpc = useTRPC();
|
||||
|
||||
const query = useQuery(
|
||||
trpc.overview.userJourney.queryOptions({
|
||||
projectId,
|
||||
filters,
|
||||
startDate,
|
||||
endDate,
|
||||
range,
|
||||
steps: steps ?? 5,
|
||||
}),
|
||||
);
|
||||
|
||||
const data = query.data;
|
||||
const number = useNumber();
|
||||
|
||||
// Process data for Sankey - nodes are already sorted by step then value from backend
|
||||
const sankeyData = useMemo(() => {
|
||||
if (!data) return { nodes: [], links: [] };
|
||||
|
||||
return {
|
||||
nodes: data.nodes.map((node: any) => ({
|
||||
...node,
|
||||
// Store label for display in tooltips
|
||||
label: node.label || node.id,
|
||||
data: {
|
||||
percentage: node.percentage,
|
||||
value: node.value,
|
||||
step: node.step,
|
||||
label: node.label || node.id,
|
||||
},
|
||||
})),
|
||||
links: data.links,
|
||||
};
|
||||
}, [data]);
|
||||
|
||||
const totalSessions = useMemo(() => {
|
||||
if (!sankeyData.nodes || sankeyData.nodes.length === 0) return 0;
|
||||
// Total sessions used by backend for percentages is the sum of entry nodes (step 1).
|
||||
// Fall back to summing all nodes if step is missing for some reason.
|
||||
const step1 = sankeyData.nodes.filter((n: any) => n.data?.step === 1);
|
||||
const base = step1.length > 0 ? step1 : sankeyData.nodes;
|
||||
return base.reduce((sum: number, n: any) => sum + (n.data?.value ?? 0), 0);
|
||||
}, [sankeyData.nodes]);
|
||||
|
||||
const stepOptions = [3, 5];
|
||||
|
||||
const { appTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<Widget className="col-span-6">
|
||||
<WidgetHead>
|
||||
<div className="title">User Journey</div>
|
||||
<WidgetButtons>
|
||||
{stepOptions.map((option) => (
|
||||
<button
|
||||
type="button"
|
||||
key={option}
|
||||
onClick={() => setSteps(option)}
|
||||
className={cn((steps ?? 5) === option && 'active')}
|
||||
>
|
||||
{option} Steps
|
||||
</button>
|
||||
))}
|
||||
</WidgetButtons>
|
||||
</WidgetHead>
|
||||
<WidgetBody>
|
||||
{query.isLoading ? (
|
||||
<div className="flex items-center justify-center h-96">
|
||||
<div className="text-sm text-muted-foreground">Loading...</div>
|
||||
</div>
|
||||
) : sankeyData.nodes.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-96">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
No journey data available
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="w-full relative aspect-square md:aspect-[2]"
|
||||
>
|
||||
<ResponsiveSankey
|
||||
margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
|
||||
data={sankeyData}
|
||||
colors={(node: any) => node.nodeColor}
|
||||
nodeBorderRadius={2}
|
||||
animate={false}
|
||||
nodeBorderWidth={0}
|
||||
nodeOpacity={0.8}
|
||||
linkContract={1}
|
||||
linkOpacity={0.3}
|
||||
linkBlendMode={'normal'}
|
||||
nodeTooltip={({ node }: any) => {
|
||||
const label = node?.data?.label ?? node?.label ?? node?.id;
|
||||
const value = node?.data?.value ?? node?.value ?? 0;
|
||||
const step = node?.data?.step;
|
||||
const pct =
|
||||
typeof node?.data?.percentage === 'number'
|
||||
? node.data.percentage
|
||||
: totalSessions > 0
|
||||
? (value / totalSessions) * 100
|
||||
: 0;
|
||||
const color =
|
||||
node?.color ??
|
||||
node?.data?.nodeColor ??
|
||||
node?.data?.color ??
|
||||
node?.nodeColor ??
|
||||
'#64748b';
|
||||
|
||||
return (
|
||||
<SankeyPortalTooltip>
|
||||
<ChartTooltipContainer className="min-w-[250px]">
|
||||
<ChartTooltipHeader>
|
||||
<div className="min-w-0 flex-1 font-medium break-words">
|
||||
<span className="opacity-40 mr-1">
|
||||
{showDomain(label)}
|
||||
</span>
|
||||
{showPath(label)}
|
||||
</div>
|
||||
{typeof step === 'number' && (
|
||||
<div className="shrink-0 text-muted-foreground">
|
||||
Step {step}
|
||||
</div>
|
||||
)}
|
||||
</ChartTooltipHeader>
|
||||
<ChartTooltipItem color={color} innerClassName="gap-2">
|
||||
<div className="flex items-center justify-between gap-8 font-mono font-medium">
|
||||
<div className="text-muted-foreground">Sessions</div>
|
||||
<div>{number.format(value)}</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-8 font-mono font-medium">
|
||||
<div className="text-muted-foreground">Share</div>
|
||||
<div>{number.format(round(pct, 1))} %</div>
|
||||
</div>
|
||||
</ChartTooltipItem>
|
||||
</ChartTooltipContainer>
|
||||
</SankeyPortalTooltip>
|
||||
);
|
||||
}}
|
||||
linkTooltip={({ link }: any) => {
|
||||
const sourceLabel =
|
||||
link?.source?.data?.label ??
|
||||
link?.source?.label ??
|
||||
link?.source?.id;
|
||||
const targetLabel =
|
||||
link?.target?.data?.label ??
|
||||
link?.target?.label ??
|
||||
link?.target?.id;
|
||||
|
||||
const value = link?.value ?? 0;
|
||||
const sourceValue =
|
||||
link?.source?.data?.value ?? link?.source?.value ?? 0;
|
||||
|
||||
const pctOfTotal =
|
||||
totalSessions > 0 ? (value / totalSessions) * 100 : 0;
|
||||
const pctOfSource =
|
||||
sourceValue > 0 ? (value / sourceValue) * 100 : 0;
|
||||
|
||||
const sourceStep = link?.source?.data?.step;
|
||||
const targetStep = link?.target?.data?.step;
|
||||
|
||||
const color =
|
||||
link?.color ??
|
||||
link?.source?.color ??
|
||||
link?.source?.data?.nodeColor ??
|
||||
'#64748b';
|
||||
|
||||
const sourceDomain = showDomain(sourceLabel);
|
||||
const targetDomain = showDomain(targetLabel);
|
||||
const isSameDomain = sourceDomain === targetDomain;
|
||||
|
||||
return (
|
||||
<SankeyPortalTooltip>
|
||||
<ChartTooltipContainer>
|
||||
<ChartTooltipHeader>
|
||||
<div className="min-w-0 flex-1 font-medium break-words">
|
||||
<span className="opacity-40 mr-1">
|
||||
{showDomain(sourceLabel)}
|
||||
</span>
|
||||
{showPath(sourceLabel)}
|
||||
<ArrowRightIcon className="size-2 inline-block mx-3" />
|
||||
{!isSameDomain && (
|
||||
<span className="opacity-40 mr-1">
|
||||
{showDomain(targetLabel)}
|
||||
</span>
|
||||
)}
|
||||
{showPath(targetLabel)}
|
||||
</div>
|
||||
{typeof sourceStep === 'number' &&
|
||||
typeof targetStep === 'number' && (
|
||||
<div className="shrink-0 text-muted-foreground">
|
||||
{sourceStep} → {targetStep}
|
||||
</div>
|
||||
)}
|
||||
</ChartTooltipHeader>
|
||||
|
||||
<ChartTooltipItem color={color} innerClassName="gap-2">
|
||||
<div className="flex items-center justify-between gap-8 font-mono font-medium">
|
||||
<div className="text-muted-foreground">Sessions</div>
|
||||
<div>{number.format(value)}</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-8 font-mono text-sm">
|
||||
<div className="text-muted-foreground">
|
||||
% of total
|
||||
</div>
|
||||
<div>{number.format(round(pctOfTotal, 1))} %</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-8 font-mono text-sm">
|
||||
<div className="text-muted-foreground">
|
||||
% of source
|
||||
</div>
|
||||
<div>{number.format(round(pctOfSource, 1))} %</div>
|
||||
</div>
|
||||
</ChartTooltipItem>
|
||||
</ChartTooltipContainer>
|
||||
</SankeyPortalTooltip>
|
||||
);
|
||||
}}
|
||||
label={(node: any) => {
|
||||
const label = showPath(
|
||||
node.data?.label || node.label || node.id,
|
||||
);
|
||||
return truncate(label, 30, 'middle');
|
||||
}}
|
||||
labelTextColor={appTheme === 'dark' ? '#e2e8f0' : '#0f172a'}
|
||||
nodeSpacing={10}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</WidgetBody>
|
||||
<WidgetFooter>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Shows the most common paths users take through your application
|
||||
</div>
|
||||
</WidgetFooter>
|
||||
</Widget>
|
||||
);
|
||||
}
|
||||
54
apps/start/src/components/overview/overview-view-toggle.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import { LineChartIcon, TableIcon } from 'lucide-react';
|
||||
import { parseAsStringEnum, useQueryState } from 'nuqs';
|
||||
|
||||
import { Button } from '../ui/button';
|
||||
|
||||
type ViewType = 'table' | 'chart';
|
||||
|
||||
interface OverviewViewToggleProps {
|
||||
defaultView?: ViewType;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function OverviewViewToggle({
|
||||
defaultView = 'table',
|
||||
className,
|
||||
}: OverviewViewToggleProps) {
|
||||
const [view, setView] = useQueryState<ViewType>(
|
||||
'view',
|
||||
parseAsStringEnum(['table', 'chart'])
|
||||
.withDefault(defaultView)
|
||||
.withOptions({ history: 'push' }),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setView(view === 'table' ? 'chart' : 'table');
|
||||
}}
|
||||
title={view === 'table' ? 'Switch to chart view' : 'Switch to table view'}
|
||||
>
|
||||
{view === 'table' ? (
|
||||
<LineChartIcon size={16} />
|
||||
) : (
|
||||
<TableIcon size={16} />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function useOverviewView() {
|
||||
const [view, setView] = useQueryState<ViewType>(
|
||||
'view',
|
||||
parseAsStringEnum(['table', 'chart'])
|
||||
.withDefault('table')
|
||||
.withOptions({ history: 'push' }),
|
||||
);
|
||||
|
||||
return [view, setView] as const;
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ export const OverviewWidgetTable = <T,>({
|
||||
<WidgetTable
|
||||
data={data ?? []}
|
||||
keyExtractor={keyExtractor}
|
||||
className={'text-sm min-h-[358px] @container [&_.head]:pt-3'}
|
||||
className={'text-sm min-h-[358px] @container'}
|
||||
columnClassName="[&_.cell:first-child]:pl-4 [&_.cell:last-child]:pr-4"
|
||||
eachRow={(item) => {
|
||||
return (
|
||||
@@ -109,15 +109,6 @@ export function OverviewWidgetTableLoading({
|
||||
render: () => <Skeleton className="h-4 w-1/3" />,
|
||||
width: 'w-full',
|
||||
},
|
||||
{
|
||||
name: 'BR',
|
||||
render: () => <Skeleton className="h-4 w-[30px]" />,
|
||||
width: '60px',
|
||||
},
|
||||
// {
|
||||
// name: 'Duration',
|
||||
// render: () => <Skeleton className="h-4 w-[30px]" />,
|
||||
// },
|
||||
{
|
||||
name: 'Sessions',
|
||||
render: () => <Skeleton className="h-4 w-[30px]" />,
|
||||
@@ -142,27 +133,24 @@ function getPath(path: string, showDomain = false) {
|
||||
|
||||
export function OverviewWidgetTablePages({
|
||||
data,
|
||||
lastColumnName,
|
||||
className,
|
||||
showDomain = false,
|
||||
}: {
|
||||
className?: string;
|
||||
lastColumnName: string;
|
||||
data: {
|
||||
origin: string;
|
||||
path: string;
|
||||
avg_duration: number;
|
||||
bounce_rate: number;
|
||||
sessions: number;
|
||||
revenue: number;
|
||||
pageviews: number;
|
||||
revenue?: number;
|
||||
}[];
|
||||
showDomain?: boolean;
|
||||
}) {
|
||||
const [_filters, setFilter] = useEventQueryFilters();
|
||||
const number = useNumber();
|
||||
const maxSessions = Math.max(...data.map((item) => item.sessions));
|
||||
const totalRevenue = data.reduce((sum, item) => sum + item.revenue, 0);
|
||||
const hasRevenue = data.some((item) => item.revenue > 0);
|
||||
const totalRevenue = data.reduce((sum, item) => sum + (item.revenue ?? 0), 0);
|
||||
const hasRevenue = data.some((item) => (item.revenue ?? 0) > 0);
|
||||
return (
|
||||
<OverviewWidgetTable
|
||||
className={className}
|
||||
@@ -214,20 +202,135 @@ export function OverviewWidgetTablePages({
|
||||
);
|
||||
},
|
||||
},
|
||||
...(hasRevenue
|
||||
? [
|
||||
{
|
||||
name: 'Revenue',
|
||||
width: '100px',
|
||||
responsive: { priority: 3 }, // Always show if possible
|
||||
render(item: (typeof data)[number]) {
|
||||
const revenue = item.revenue ?? 0;
|
||||
const revenuePercentage =
|
||||
totalRevenue > 0 ? revenue / totalRevenue : 0;
|
||||
return (
|
||||
<div className="row gap-2 items-center justify-end">
|
||||
<span
|
||||
className="font-semibold"
|
||||
style={{ color: '#3ba974' }}
|
||||
>
|
||||
{revenue > 0 ? number.currency(revenue / 100) : '-'}
|
||||
</span>
|
||||
<RevenuePieChart percentage={revenuePercentage} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
} as const,
|
||||
]
|
||||
: []),
|
||||
{
|
||||
name: 'BR',
|
||||
width: '60px',
|
||||
responsive: { priority: 6 }, // Hidden when space is tight
|
||||
name: 'Views',
|
||||
width: '84px',
|
||||
responsive: { priority: 2 }, // Always show if possible
|
||||
render(item) {
|
||||
return number.shortWithUnit(item.bounce_rate, '%');
|
||||
return (
|
||||
<div className="row gap-2 justify-end">
|
||||
<span className="font-semibold">
|
||||
{number.short(item.pageviews)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Duration',
|
||||
width: '75px',
|
||||
responsive: { priority: 7 }, // Hidden when space is tight
|
||||
name: 'Sess.',
|
||||
width: '84px',
|
||||
responsive: { priority: 2 }, // Always show if possible
|
||||
render(item) {
|
||||
return number.shortWithUnit(item.avg_duration, 'min');
|
||||
return (
|
||||
<div className="row gap-2 justify-end">
|
||||
<span className="font-semibold">
|
||||
{number.short(item.sessions)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function OverviewWidgetTableEntries({
|
||||
data,
|
||||
lastColumnName,
|
||||
className,
|
||||
showDomain = false,
|
||||
}: {
|
||||
className?: string;
|
||||
lastColumnName: string;
|
||||
data: {
|
||||
origin: string;
|
||||
path: string;
|
||||
sessions: number;
|
||||
pageviews: number;
|
||||
revenue?: number;
|
||||
}[];
|
||||
showDomain?: boolean;
|
||||
}) {
|
||||
const [_filters, setFilter] = useEventQueryFilters();
|
||||
const number = useNumber();
|
||||
const maxSessions = Math.max(...data.map((item) => item.sessions));
|
||||
const totalRevenue = data.reduce((sum, item) => sum + (item.revenue ?? 0), 0);
|
||||
const hasRevenue = data.some((item) => (item.revenue ?? 0) > 0);
|
||||
return (
|
||||
<OverviewWidgetTable
|
||||
className={className}
|
||||
data={data ?? []}
|
||||
keyExtractor={(item) => item.path + item.origin}
|
||||
getColumnPercentage={(item) => item.sessions / maxSessions}
|
||||
columns={[
|
||||
{
|
||||
name: 'Path',
|
||||
width: 'w-full',
|
||||
responsive: { priority: 1 }, // Always visible
|
||||
render(item) {
|
||||
return (
|
||||
<Tooltiper asChild content={item.origin + item.path} side="left">
|
||||
<div className="row items-center gap-2 min-w-0 relative">
|
||||
<SerieIcon name={item.origin} />
|
||||
<button
|
||||
type="button"
|
||||
className="truncate"
|
||||
onClick={() => {
|
||||
setFilter('path', item.path);
|
||||
setFilter('origin', item.origin);
|
||||
}}
|
||||
>
|
||||
{item.path ? (
|
||||
<>
|
||||
{showDomain ? (
|
||||
<>
|
||||
<span className="opacity-40">{item.origin}</span>
|
||||
<span>{item.path}</span>
|
||||
</>
|
||||
) : (
|
||||
item.path
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="opacity-40">Not set</span>
|
||||
)}
|
||||
</button>
|
||||
<a
|
||||
href={item.origin + item.path}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<ExternalLinkIcon className="size-3 group-hover/row:opacity-100 opacity-0 transition-opacity" />
|
||||
</a>
|
||||
</div>
|
||||
</Tooltiper>
|
||||
);
|
||||
},
|
||||
},
|
||||
...(hasRevenue
|
||||
@@ -237,17 +340,16 @@ export function OverviewWidgetTablePages({
|
||||
width: '100px',
|
||||
responsive: { priority: 3 }, // Always show if possible
|
||||
render(item: (typeof data)[number]) {
|
||||
const revenue = item.revenue ?? 0;
|
||||
const revenuePercentage =
|
||||
totalRevenue > 0 ? item.revenue / totalRevenue : 0;
|
||||
totalRevenue > 0 ? revenue / totalRevenue : 0;
|
||||
return (
|
||||
<div className="row gap-2 items-center justify-end">
|
||||
<span
|
||||
className="font-semibold"
|
||||
style={{ color: '#3ba974' }}
|
||||
>
|
||||
{item.revenue > 0
|
||||
? number.currency(item.revenue / 100)
|
||||
: '-'}
|
||||
{revenue > 0 ? number.currency(revenue / 100) : '-'}
|
||||
</span>
|
||||
<RevenuePieChart percentage={revenuePercentage} />
|
||||
</div>
|
||||
@@ -373,6 +475,7 @@ export function OverviewWidgetTableGeneric({
|
||||
const maxSessions = Math.max(...data.map((item) => item.sessions));
|
||||
const totalRevenue = data.reduce((sum, item) => sum + (item.revenue ?? 0), 0);
|
||||
const hasRevenue = data.some((item) => (item.revenue ?? 0) > 0);
|
||||
const hasPageviews = data.some((item) => item.pageviews > 0);
|
||||
return (
|
||||
<OverviewWidgetTable
|
||||
className={className}
|
||||
@@ -385,27 +488,12 @@ export function OverviewWidgetTableGeneric({
|
||||
width: 'w-full',
|
||||
responsive: { priority: 1 }, // Always visible
|
||||
},
|
||||
{
|
||||
name: 'BR',
|
||||
width: '60px',
|
||||
responsive: { priority: 6 }, // Hidden when space is tight
|
||||
render(item) {
|
||||
return number.shortWithUnit(item.bounce_rate, '%');
|
||||
},
|
||||
},
|
||||
// {
|
||||
// name: 'Duration',
|
||||
// render(item) {
|
||||
// return number.shortWithUnit(item.avg_session_duration, 'min');
|
||||
// },
|
||||
// },
|
||||
|
||||
...(hasRevenue
|
||||
? [
|
||||
{
|
||||
name: 'Revenue',
|
||||
width: '100px',
|
||||
responsive: { priority: 3 }, // Always show if possible
|
||||
responsive: { priority: 3 },
|
||||
render(item: RouterOutputs['overview']['topGeneric'][number]) {
|
||||
const revenue = item.revenue ?? 0;
|
||||
const revenuePercentage =
|
||||
@@ -427,10 +515,28 @@ export function OverviewWidgetTableGeneric({
|
||||
} as const,
|
||||
]
|
||||
: []),
|
||||
...(hasPageviews
|
||||
? [
|
||||
{
|
||||
name: 'Views',
|
||||
width: '84px',
|
||||
responsive: { priority: 2 },
|
||||
render(item: RouterOutputs['overview']['topGeneric'][number]) {
|
||||
return (
|
||||
<div className="row gap-2 justify-end">
|
||||
<span className="font-semibold">
|
||||
{number.short(item.pageviews)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
} as const,
|
||||
]
|
||||
: []),
|
||||
{
|
||||
name: 'Sessions',
|
||||
name: 'Sess.',
|
||||
width: '84px',
|
||||
responsive: { priority: 2 }, // Always show if possible
|
||||
responsive: { priority: 2 },
|
||||
render(item) {
|
||||
return (
|
||||
<div className="row gap-2 justify-end">
|
||||
@@ -445,3 +551,65 @@ export function OverviewWidgetTableGeneric({
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export type EventTableItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
count: number;
|
||||
};
|
||||
|
||||
export function OverviewWidgetTableEvents({
|
||||
data,
|
||||
className,
|
||||
onItemClick,
|
||||
}: {
|
||||
className?: string;
|
||||
data: EventTableItem[];
|
||||
onItemClick?: (name: string) => void;
|
||||
}) {
|
||||
const number = useNumber();
|
||||
const maxCount = Math.max(...data.map((item) => item.count), 1);
|
||||
return (
|
||||
<OverviewWidgetTable
|
||||
className={className}
|
||||
data={data ?? []}
|
||||
keyExtractor={(item) => item.id}
|
||||
getColumnPercentage={(item) => item.count / maxCount}
|
||||
columns={[
|
||||
{
|
||||
name: 'Event',
|
||||
width: 'w-full',
|
||||
responsive: { priority: 1 },
|
||||
render(item) {
|
||||
return (
|
||||
<div className="row items-center gap-2 min-w-0 relative">
|
||||
<SerieIcon name={item.name} />
|
||||
<button
|
||||
type="button"
|
||||
className="truncate"
|
||||
onClick={() => onItemClick?.(item.name)}
|
||||
>
|
||||
{item.name || 'Not set'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Count',
|
||||
width: '84px',
|
||||
responsive: { priority: 2 },
|
||||
render(item) {
|
||||
return (
|
||||
<div className="row gap-2 justify-end">
|
||||
<span className="font-semibold">
|
||||
{number.short(item.count)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useThrottle } from '@/hooks/use-throttle';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { ChevronsUpDownIcon, Icon, type LucideIcon } from 'lucide-react';
|
||||
import { ChevronsUpDownIcon, type LucideIcon, SearchIcon } from 'lucide-react';
|
||||
import { last } from 'ramda';
|
||||
import { Children, useEffect, useRef, useState } from 'react';
|
||||
import { Children, useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu';
|
||||
import { Input } from '../ui/input';
|
||||
import type { WidgetHeadProps, WidgetTitleProps } from '../widget';
|
||||
import { WidgetHead as WidgetHeadBase } from '../widget';
|
||||
|
||||
@@ -169,6 +170,128 @@ export function WidgetButtons({
|
||||
);
|
||||
}
|
||||
|
||||
interface WidgetTab<T extends string = string> {
|
||||
key: T;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface WidgetHeadSearchableProps<T extends string = string> {
|
||||
tabs: WidgetTab<T>[];
|
||||
activeTab: T;
|
||||
className?: string;
|
||||
onTabChange: (key: T) => void;
|
||||
searchValue?: string;
|
||||
onSearchChange?: (value: string) => void;
|
||||
searchPlaceholder?: string;
|
||||
}
|
||||
|
||||
export function WidgetHeadSearchable<T extends string>({
|
||||
tabs,
|
||||
className,
|
||||
activeTab,
|
||||
onTabChange,
|
||||
searchValue,
|
||||
onSearchChange,
|
||||
searchPlaceholder = 'Search',
|
||||
}: WidgetHeadSearchableProps<T>) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [showLeftGradient, setShowLeftGradient] = useState(false);
|
||||
const [showRightGradient, setShowRightGradient] = useState(false);
|
||||
|
||||
const updateGradients = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const { scrollLeft, scrollWidth, clientWidth } = el;
|
||||
const hasOverflow = scrollWidth > clientWidth;
|
||||
|
||||
setShowLeftGradient(hasOverflow && scrollLeft > 0);
|
||||
setShowRightGradient(
|
||||
hasOverflow && scrollLeft < scrollWidth - clientWidth - 1,
|
||||
);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
|
||||
updateGradients();
|
||||
|
||||
el.addEventListener('scroll', updateGradients);
|
||||
window.addEventListener('resize', updateGradients);
|
||||
|
||||
return () => {
|
||||
el.removeEventListener('scroll', updateGradients);
|
||||
window.removeEventListener('resize', updateGradients);
|
||||
};
|
||||
}, [updateGradients]);
|
||||
|
||||
// Update gradients when tabs change
|
||||
useEffect(() => {
|
||||
// Use RAF to ensure DOM has updated
|
||||
requestAnimationFrame(updateGradients);
|
||||
}, [tabs, updateGradients]);
|
||||
|
||||
return (
|
||||
<div className={cn('border-b border-border', className)}>
|
||||
{/* Scrollable tabs container */}
|
||||
<div className="relative">
|
||||
{/* Left gradient */}
|
||||
<div
|
||||
className={cn(
|
||||
'pointer-events-none absolute left-0 top-0 z-10 h-full w-8 bg-gradient-to-r from-card to-transparent transition-opacity duration-200',
|
||||
showLeftGradient ? 'opacity-100' : 'opacity-0',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Scrollable tabs */}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="flex gap-1 overflow-x-auto px-2 py-3 hide-scrollbar"
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
onClick={() => onTabChange(tab.key)}
|
||||
className={cn(
|
||||
'shrink-0 rounded-md py-1.5 text-sm font-medium transition-colors px-2',
|
||||
activeTab === tab.key
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground hover:bg-def-100 hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Right gradient */}
|
||||
<div
|
||||
className={cn(
|
||||
'pointer-events-none absolute right-0 top-0 z-10 bottom-px w-8 bg-gradient-to-l from-card to-transparent transition-opacity duration-200',
|
||||
showRightGradient ? 'opacity-100' : 'opacity-0',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Search input */}
|
||||
{onSearchChange && (
|
||||
<div className="relative">
|
||||
<SearchIcon className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchValue ?? ''}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
className="pl-9 bg-transparent border-0 text-sm rounded-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0 border-y"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WidgetFooter({
|
||||
className,
|
||||
children,
|
||||
|
||||
@@ -33,7 +33,10 @@ export function useOverviewWidget<T extends string>(
|
||||
|
||||
export function useOverviewWidgetV2<T extends string>(
|
||||
key: string,
|
||||
widgets: Record<T, { title: string; btn: string; meta?: any }>,
|
||||
widgets: Record<
|
||||
T,
|
||||
{ title: string; btn: string; meta?: any; hide?: boolean }
|
||||
>,
|
||||
) {
|
||||
const keys = Object.keys(widgets) as T[];
|
||||
const [widget, setWidget] = useQueryState<T>(
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ReportChart } from '@/components/report-chart';
|
||||
import { Widget, WidgetBody } from '@/components/widget';
|
||||
import { memo } from 'react';
|
||||
|
||||
import type { IChartProps } from '@openpanel/validation';
|
||||
import type { IReport } from '@openpanel/validation';
|
||||
import { WidgetHead } from '../overview/overview-widget';
|
||||
|
||||
type Props = {
|
||||
@@ -12,7 +12,7 @@ type Props = {
|
||||
|
||||
export const ProfileCharts = memo(
|
||||
({ profileId, projectId }: Props) => {
|
||||
const pageViewsChart: IChartProps = {
|
||||
const pageViewsChart: IReport = {
|
||||
projectId,
|
||||
chartType: 'linear',
|
||||
series: [
|
||||
@@ -46,7 +46,7 @@ export const ProfileCharts = memo(
|
||||
metric: 'sum',
|
||||
};
|
||||
|
||||
const eventsChart: IChartProps = {
|
||||
const eventsChart: IReport = {
|
||||
projectId,
|
||||
chartType: 'linear',
|
||||
series: [
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
YAxis,
|
||||
} from 'recharts';
|
||||
import { AnimatedNumber } from '../animated-number';
|
||||
import { BarShapeBlue } from '../charts/common-bar';
|
||||
import { SerieIcon } from '../report-chart/common/serie-icon';
|
||||
|
||||
interface RealtimeLiveHistogramProps {
|
||||
@@ -87,10 +86,8 @@ export function RealtimeLiveHistogram({
|
||||
<YAxis hide domain={[0, maxDomain]} />
|
||||
<Bar
|
||||
dataKey="visitorCount"
|
||||
fill="rgba(59, 121, 255, 0.2)"
|
||||
className="fill-chart-0"
|
||||
isAnimationActive={false}
|
||||
shape={BarShapeBlue}
|
||||
activeBar={BarShapeBlue}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -9,15 +10,27 @@ import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportAreaChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.chart.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
|
||||
@@ -4,160 +4,322 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { useVisibleSeries } from '@/hooks/use-visible-series';
|
||||
import type { IChartData } from '@/trpc/client';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { getChartColor } from '@/utils/theme';
|
||||
import { DropdownMenuPortal } from '@radix-ui/react-dropdown-menu';
|
||||
import { SearchIcon } from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { round } from '@openpanel/common';
|
||||
import { NOT_SET_VALUE } from '@openpanel/constants';
|
||||
|
||||
import { OverviewWidgetTable } from '../../overview/overview-widget-table';
|
||||
import { DeltaChip } from '@/components/delta-chip';
|
||||
import { PreviousDiffIndicator } from '../common/previous-diff-indicator';
|
||||
import { SerieIcon } from '../common/serie-icon';
|
||||
import { SerieName } from '../common/serie-name';
|
||||
import { useReportChartContext } from '../context';
|
||||
|
||||
type SortOption =
|
||||
| 'count-desc'
|
||||
| 'count-asc'
|
||||
| 'name-asc'
|
||||
| 'name-desc'
|
||||
| 'percent-desc'
|
||||
| 'percent-asc';
|
||||
|
||||
interface Props {
|
||||
data: IChartData;
|
||||
}
|
||||
|
||||
export function Chart({ data }: Props) {
|
||||
const [isOpen, setOpen] = useState<string | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortBy, setSortBy] = useState<SortOption>('count-desc');
|
||||
const {
|
||||
isEditMode,
|
||||
report: { metric, limit, previous },
|
||||
options: { onClick, dropdownMenuContent, columns },
|
||||
options: { onClick, dropdownMenuContent },
|
||||
} = useReportChartContext();
|
||||
const number = useNumber();
|
||||
const series = useMemo(
|
||||
() => (isEditMode ? data.series : data.series.slice(0, limit || 10)),
|
||||
[data, isEditMode, limit],
|
||||
);
|
||||
const maxCount = Math.max(
|
||||
...series.map((serie) => serie.metrics[metric] ?? 0),
|
||||
);
|
||||
|
||||
const tableColumns = [
|
||||
{
|
||||
name: columns?.[0] || 'Name',
|
||||
width: 'w-full',
|
||||
render: (serie: (typeof series)[0]) => {
|
||||
const isClickable = !serie.names.includes(NOT_SET_VALUE) && onClick;
|
||||
const isDropDownEnabled =
|
||||
!serie.names.includes(NOT_SET_VALUE) &&
|
||||
(dropdownMenuContent?.(serie) || []).length > 0;
|
||||
// Use useVisibleSeries to add index property for colors
|
||||
const { series: allSeriesWithIndex } = useVisibleSeries(data, 500);
|
||||
|
||||
return (
|
||||
<DropdownMenu
|
||||
onOpenChange={() =>
|
||||
setOpen((p) => (p === serie.id ? null : serie.id))
|
||||
}
|
||||
open={isOpen === serie.id}
|
||||
>
|
||||
<DropdownMenuTrigger
|
||||
asChild
|
||||
disabled={!isDropDownEnabled}
|
||||
{...(isDropDownEnabled
|
||||
? {
|
||||
onPointerDown: (e) => e.preventDefault(),
|
||||
onClick: () => setOpen(serie.id),
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-2 break-all font-medium',
|
||||
(isClickable || isDropDownEnabled) && 'cursor-pointer',
|
||||
)}
|
||||
{...(isClickable && !isDropDownEnabled
|
||||
? {
|
||||
onClick: () => onClick(serie),
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
<SerieIcon name={serie.names[0]} />
|
||||
<SerieName name={serie.names} />
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent>
|
||||
{dropdownMenuContent?.(serie).map((item) => (
|
||||
<DropdownMenuItem key={item.title} onClick={item.onClick}>
|
||||
{item.icon && <item.icon size={16} className="mr-2" />}
|
||||
{item.title}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenu>
|
||||
);
|
||||
},
|
||||
},
|
||||
// Percentage column
|
||||
{
|
||||
name: '%',
|
||||
width: '70px',
|
||||
render: (serie: (typeof series)[0]) => (
|
||||
<div className="text-muted-foreground font-mono">
|
||||
{number.format(
|
||||
round((serie.metrics.sum / data.metrics.sum) * 100, 2),
|
||||
)}
|
||||
%
|
||||
</div>
|
||||
),
|
||||
},
|
||||
const totalSum = data.metrics.sum || 1;
|
||||
|
||||
// Previous value column
|
||||
{
|
||||
name: 'Previous',
|
||||
width: '130px',
|
||||
render: (serie: (typeof series)[0]) => (
|
||||
<div className="flex items-center gap-2 font-mono justify-end">
|
||||
<div className="font-bold">
|
||||
{number.format(serie.metrics.previous?.[metric]?.value)}
|
||||
</div>
|
||||
<PreviousDiffIndicator
|
||||
{...serie.metrics.previous?.[metric]}
|
||||
size="xs"
|
||||
className="text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
// Calculate original ranks (based on count descending - default sort)
|
||||
const seriesWithOriginalRank = useMemo(() => {
|
||||
const sortedByCount = [...allSeriesWithIndex].sort(
|
||||
(a, b) => b.metrics.sum - a.metrics.sum,
|
||||
);
|
||||
const rankMap = new Map<string, number>();
|
||||
sortedByCount.forEach((serie, idx) => {
|
||||
rankMap.set(serie.id, idx + 1);
|
||||
});
|
||||
return allSeriesWithIndex.map((serie) => ({
|
||||
...serie,
|
||||
originalRank: rankMap.get(serie.id) ?? 0,
|
||||
}));
|
||||
}, [allSeriesWithIndex]);
|
||||
|
||||
// Main count column (always last)
|
||||
{
|
||||
name: 'Count',
|
||||
width: '80px',
|
||||
render: (serie: (typeof series)[0]) => (
|
||||
<div className="font-bold font-mono">
|
||||
{number.format(serie.metrics.sum)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
// Filter and sort series
|
||||
const series = useMemo(() => {
|
||||
let filtered = seriesWithOriginalRank;
|
||||
|
||||
// Filter by search query
|
||||
if (searchQuery.trim()) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
filtered = filtered.filter((serie) =>
|
||||
serie.names.some((name) => name.toLowerCase().includes(query)),
|
||||
);
|
||||
}
|
||||
|
||||
// Sort
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
switch (sortBy) {
|
||||
case 'count-desc':
|
||||
return b.metrics.sum - a.metrics.sum;
|
||||
case 'count-asc':
|
||||
return a.metrics.sum - b.metrics.sum;
|
||||
case 'name-asc':
|
||||
return a.names.join(' > ').localeCompare(b.names.join(' > '));
|
||||
case 'name-desc':
|
||||
return b.names.join(' > ').localeCompare(a.names.join(' > '));
|
||||
case 'percent-desc':
|
||||
return b.metrics.sum / totalSum - a.metrics.sum / totalSum;
|
||||
case 'percent-asc':
|
||||
return a.metrics.sum / totalSum - b.metrics.sum / totalSum;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
// Apply limit if not in edit mode
|
||||
return isEditMode ? sorted : sorted.slice(0, limit || 10);
|
||||
}, [
|
||||
seriesWithOriginalRank,
|
||||
searchQuery,
|
||||
sortBy,
|
||||
totalSum,
|
||||
isEditMode,
|
||||
limit,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'text-sm',
|
||||
isEditMode ? 'card gap-2 p-4 text-base' : '-m-3',
|
||||
<div className={cn('w-full', isEditMode && 'card')}>
|
||||
{isEditMode && (
|
||||
<div className="flex items-center gap-3 p-4 border-b border-def-200 dark:border-def-800">
|
||||
<div className="relative flex-1">
|
||||
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Filter by name"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
value={sortBy}
|
||||
onValueChange={(value) => setSortBy(value as SortOption)}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-[180px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="count-desc">Count (High → Low)</SelectItem>
|
||||
<SelectItem value="count-asc">Count (Low → High)</SelectItem>
|
||||
<SelectItem value="name-asc">Name (A → Z)</SelectItem>
|
||||
<SelectItem value="name-desc">Name (Z → A)</SelectItem>
|
||||
<SelectItem value="percent-desc">
|
||||
Percentage (High → Low)
|
||||
</SelectItem>
|
||||
<SelectItem value="percent-asc">
|
||||
Percentage (Low → High)
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<OverviewWidgetTable
|
||||
data={series}
|
||||
keyExtractor={(serie) => serie.id}
|
||||
columns={tableColumns.filter((column) => {
|
||||
if (!previous && column.name === 'Previous') {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})}
|
||||
getColumnPercentage={(serie) => serie.metrics.sum / maxCount}
|
||||
className={cn(isEditMode ? 'min-h-[358px]' : 'min-h-0')}
|
||||
/>
|
||||
<div className="overflow-hidden">
|
||||
<div className="divide-y divide-def-200 dark:divide-def-800">
|
||||
{series.map((serie, idx) => {
|
||||
const isClickable =
|
||||
!serie.names.includes(NOT_SET_VALUE) && !!onClick;
|
||||
const isDropDownEnabled =
|
||||
!serie.names.includes(NOT_SET_VALUE) &&
|
||||
(dropdownMenuContent?.(serie) || []).length > 0;
|
||||
|
||||
const color = getChartColor(serie.index);
|
||||
const percentOfTotal = round(
|
||||
(serie.metrics.sum / totalSum) * 100,
|
||||
1,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={serie.id}
|
||||
className={cn(
|
||||
'group relative px-4 py-3 transition-colors overflow-hidden',
|
||||
isClickable && 'cursor-pointer',
|
||||
)}
|
||||
role={isClickable ? 'button' : undefined}
|
||||
tabIndex={isClickable ? 0 : undefined}
|
||||
onClick={() => {
|
||||
if (isClickable && !isDropDownEnabled) {
|
||||
onClick?.(serie);
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (!isClickable || isDropDownEnabled) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
onClick?.(serie);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Subtle accent glow */}
|
||||
<div
|
||||
className="pointer-events-none absolute -left-10 -top-10 h-40 w-96 rounded-full opacity-0 blur-3xl transition-opacity duration-500 group-hover:opacity-10"
|
||||
style={{
|
||||
background: `radial-gradient(circle, ${color} 0%, transparent 70%)`,
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="relative z-10 flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border bg-def-50 dark:border-def-800 dark:bg-def-900"
|
||||
style={{ borderColor: `${color}22` }}
|
||||
>
|
||||
<SerieIcon name={serie.names[0]} />
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<div
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
Rank {serie.originalRank}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<DropdownMenu
|
||||
onOpenChange={() =>
|
||||
setOpen((p) => (p === serie.id ? null : serie.id))
|
||||
}
|
||||
open={isOpen === serie.id}
|
||||
>
|
||||
<DropdownMenuTrigger
|
||||
asChild
|
||||
disabled={!isDropDownEnabled}
|
||||
{...(isDropDownEnabled
|
||||
? {
|
||||
onPointerDown: (e) => e.preventDefault(),
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
setOpen(serie.id);
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'min-w-0',
|
||||
isDropDownEnabled && 'cursor-pointer',
|
||||
)}
|
||||
{...(isClickable && !isDropDownEnabled
|
||||
? {
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
onClick?.(serie);
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
<SerieName
|
||||
name={serie.names}
|
||||
className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm font-semibold tracking-tight"
|
||||
/>
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent>
|
||||
{dropdownMenuContent?.(serie).map((item) => (
|
||||
<DropdownMenuItem
|
||||
key={item.title}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
item.onClick();
|
||||
}}
|
||||
>
|
||||
{item.icon && (
|
||||
<item.icon size={16} className="mr-2" />
|
||||
)}
|
||||
{item.title}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col items-end gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="text-base font-semibold font-mono tracking-tight">
|
||||
{number.format(serie.metrics.sum)}
|
||||
</div>
|
||||
{previous && serie.metrics.previous?.[metric] && (
|
||||
<DeltaChip
|
||||
variant={
|
||||
serie.metrics.previous[metric].state ===
|
||||
'positive'
|
||||
? 'inc'
|
||||
: 'dec'
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
{serie.metrics.previous[metric].diff?.toFixed(1)}%
|
||||
</DeltaChip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bar */}
|
||||
<div className="flex items-center">
|
||||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-def-100 dark:bg-def-900">
|
||||
<div
|
||||
className="h-full rounded-full transition-[width] duration-700 ease-out"
|
||||
style={{
|
||||
width: `${percentOfTotal}%`,
|
||||
background: `linear-gradient(90deg, ${color}aa, ${color})`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -8,15 +10,27 @@ import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportBarChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.aggregate.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -26,7 +40,6 @@ export function ReportBarChart() {
|
||||
) {
|
||||
return <Loading />;
|
||||
}
|
||||
|
||||
if (res.isError) {
|
||||
return <Error />;
|
||||
}
|
||||
@@ -39,22 +52,62 @@ export function ReportBarChart() {
|
||||
}
|
||||
|
||||
function Loading() {
|
||||
const { isEditMode } = useReportChartContext();
|
||||
return (
|
||||
<AspectContainer className="col gap-4 overflow-hidden">
|
||||
{Array.from({ length: 10 }).map((_, index) => (
|
||||
<div
|
||||
key={index as number}
|
||||
className="row animate-pulse justify-between"
|
||||
>
|
||||
<div className="h-4 w-2/5 rounded bg-def-200" />
|
||||
<div className="row w-1/5 gap-2">
|
||||
<div className="h-4 w-full rounded bg-def-200" />
|
||||
<div className="h-4 w-full rounded bg-def-200" />
|
||||
<div className="h-4 w-full rounded bg-def-200" />
|
||||
</div>
|
||||
<div className={cn('w-full', isEditMode && 'card')}>
|
||||
<div className="overflow-hidden">
|
||||
<div className="divide-y divide-def-200 dark:divide-def-800">
|
||||
{Array.from({ length: 10 }).map((_, index) => (
|
||||
<div
|
||||
key={index as number}
|
||||
className="relative px-4 py-3 animate-pulse"
|
||||
>
|
||||
<div className="relative z-10 flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
{/* Icon skeleton */}
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border bg-def-100 dark:border-def-800 dark:bg-def-900" />
|
||||
|
||||
<div className="min-w-0">
|
||||
{/* Rank badge skeleton */}
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<div className="h-2 w-2 rounded-full bg-def-200 dark:bg-def-700" />
|
||||
<div className="h-2 w-12 rounded bg-def-200 dark:bg-def-700" />
|
||||
</div>
|
||||
|
||||
{/* Name skeleton */}
|
||||
<div
|
||||
className="h-4 rounded bg-def-200 dark:bg-def-700"
|
||||
style={{
|
||||
width: `${Math.random() * 100 + 100}px`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Count skeleton */}
|
||||
<div className="flex shrink-0 flex-col items-end gap-1">
|
||||
<div className="h-5 w-16 rounded bg-def-200 dark:bg-def-700" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bar skeleton */}
|
||||
<div className="flex items-center">
|
||||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-def-100 dark:bg-def-900">
|
||||
<div
|
||||
className="h-full rounded-full bg-def-200 dark:bg-def-700"
|
||||
style={{
|
||||
width: `${Math.random() * 60 + 20}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</AspectContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ export function ReportChartEmpty({
|
||||
</div>
|
||||
<ForkliftIcon
|
||||
strokeWidth={1.2}
|
||||
className="mb-4 size-1/3 animate-pulse text-muted-foreground"
|
||||
className="mb-4 size-1/3 max-w-40 animate-pulse text-muted-foreground"
|
||||
/>
|
||||
<div className="font-medium text-muted-foreground">
|
||||
Ready when you're
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { ArrowDownIcon, ArrowUpIcon } from 'lucide-react';
|
||||
|
||||
import { DeltaChip } from '@/components/delta-chip';
|
||||
import { useReportChartContext } from '../context';
|
||||
|
||||
export function getDiffIndicator<A, B, C>(
|
||||
@@ -29,7 +30,7 @@ interface PreviousDiffIndicatorProps {
|
||||
children?: React.ReactNode;
|
||||
inverted?: boolean;
|
||||
className?: string;
|
||||
size?: 'sm' | 'lg' | 'md' | 'xs';
|
||||
size?: 'sm' | 'lg' | 'md';
|
||||
}
|
||||
|
||||
export function PreviousDiffIndicator({
|
||||
@@ -41,10 +42,10 @@ export function PreviousDiffIndicator({
|
||||
className,
|
||||
}: PreviousDiffIndicatorProps) {
|
||||
const {
|
||||
report: { previousIndicatorInverted, previous },
|
||||
report: { previous },
|
||||
} = useReportChartContext();
|
||||
const variant = getDiffIndicator(
|
||||
inverted ?? previousIndicatorInverted,
|
||||
inverted,
|
||||
state,
|
||||
'bg-emerald-300',
|
||||
'bg-rose-300',
|
||||
@@ -81,7 +82,6 @@ export function PreviousDiffIndicator({
|
||||
variant,
|
||||
size === 'lg' && 'size-8',
|
||||
size === 'md' && 'size-6',
|
||||
size === 'xs' && 'size-3',
|
||||
)}
|
||||
>
|
||||
{renderIcon()}
|
||||
@@ -97,7 +97,7 @@ interface PreviousDiffIndicatorPureProps {
|
||||
diff?: number | null | undefined;
|
||||
state?: string | null | undefined;
|
||||
inverted?: boolean;
|
||||
size?: 'sm' | 'lg' | 'md' | 'xs';
|
||||
size?: 'sm' | 'lg' | 'md';
|
||||
className?: string;
|
||||
showPrevious?: boolean;
|
||||
}
|
||||
@@ -133,25 +133,35 @@ export function PreviousDiffIndicatorPure({
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-1 font-mono font-medium',
|
||||
size === 'lg' && 'gap-2',
|
||||
className,
|
||||
)}
|
||||
<DeltaChip
|
||||
variant={state === 'positive' ? 'inc' : 'dec'}
|
||||
size={size}
|
||||
inverted={inverted}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-2.5 items-center justify-center rounded-full',
|
||||
variant,
|
||||
size === 'lg' && 'size-8',
|
||||
size === 'md' && 'size-6',
|
||||
size === 'xs' && 'size-3',
|
||||
)}
|
||||
>
|
||||
{renderIcon()}
|
||||
</div>
|
||||
{diff.toFixed(1)}%
|
||||
</div>
|
||||
</DeltaChip>
|
||||
);
|
||||
|
||||
// return (
|
||||
// <div
|
||||
// className={cn(
|
||||
// 'flex items-center gap-1 font-mono font-medium',
|
||||
// size === 'lg' && 'gap-2',
|
||||
// className,
|
||||
// )}
|
||||
// >
|
||||
// <div
|
||||
// className={cn(
|
||||
// 'flex size-2.5 items-center justify-center rounded-full',
|
||||
// variant,
|
||||
// size === 'lg' && 'size-8',
|
||||
// size === 'md' && 'size-6',
|
||||
// size === 'xs' && 'size-3',
|
||||
// )}
|
||||
// >
|
||||
// {renderIcon()}
|
||||
// </div>
|
||||
// {diff.toFixed(1)}%
|
||||
// </div>
|
||||
// );
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ const data = {
|
||||
whale: 'https://whale.naver.com',
|
||||
wechat: 'https://wechat.com',
|
||||
chrome: 'https://upload.wikimedia.org/wikipedia/commons/e/e1/Google_Chrome_icon_%28February_2022%29.svg',
|
||||
'mobile chrome': 'https://upload.wikimedia.org/wikipedia/commons/e/e1/Google_Chrome_icon_%28February_2022%29.svg',
|
||||
'chrome webview': 'https://upload.wikimedia.org/wikipedia/commons/e/e1/Google_Chrome_icon_%28February_2022%29.svg',
|
||||
'chrome headless': 'https://upload.wikimedia.org/wikipedia/commons/e/e1/Google_Chrome_icon_%28February_2022%29.svg',
|
||||
chromecast: 'https://upload.wikimedia.org/wikipedia/commons/archive/2/26/20161130022732%21Chromecast_cast_button_icon.svg',
|
||||
@@ -39,6 +40,7 @@ const data = {
|
||||
edge: 'https://upload.wikimedia.org/wikipedia/commons/7/7e/Microsoft_Edge_logo_%282019%29.png',
|
||||
facebook: 'https://facebook.com',
|
||||
firefox: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Firefox_logo%2C_2019.svg/1920px-Firefox_logo%2C_2019.svg.png',
|
||||
'mobile firefox': 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Firefox_logo%2C_2019.svg/1920px-Firefox_logo%2C_2019.svg.png',
|
||||
github: 'https://github.com',
|
||||
gmail: 'https://mail.google.com',
|
||||
google: 'https://google.com',
|
||||
|
||||
@@ -2,16 +2,11 @@ import isEqual from 'lodash.isequal';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
import type {
|
||||
IChartInput,
|
||||
IChartProps,
|
||||
IChartSerie,
|
||||
} from '@openpanel/validation';
|
||||
import type { IChartSerie, IReportInput } from '@openpanel/validation';
|
||||
|
||||
export type ReportChartContextType = {
|
||||
options: Partial<{
|
||||
columns: React.ReactNode[];
|
||||
hideID: boolean;
|
||||
hideLegend: boolean;
|
||||
hideXAxis: boolean;
|
||||
hideYAxis: boolean;
|
||||
@@ -28,9 +23,11 @@ export type ReportChartContextType = {
|
||||
onClick: () => void;
|
||||
}[];
|
||||
}>;
|
||||
report: IChartProps;
|
||||
report: IReportInput & { id?: string };
|
||||
isLazyLoading: boolean;
|
||||
isEditMode: boolean;
|
||||
shareId?: string;
|
||||
reportId?: string;
|
||||
};
|
||||
|
||||
type ReportChartContextProviderProps = ReportChartContextType & {
|
||||
@@ -38,7 +35,7 @@ type ReportChartContextProviderProps = ReportChartContextType & {
|
||||
};
|
||||
|
||||
export type ReportChartProps = Partial<ReportChartContextType> & {
|
||||
report: IChartInput;
|
||||
report: IReportInput & { id?: string };
|
||||
lazy?: boolean;
|
||||
};
|
||||
|
||||
@@ -54,20 +51,6 @@ export const useReportChartContext = () => {
|
||||
return ctx;
|
||||
};
|
||||
|
||||
export const useSelectReportChartContext = <T,>(
|
||||
selector: (ctx: ReportChartContextType) => T,
|
||||
) => {
|
||||
const ctx = useReportChartContext();
|
||||
const [state, setState] = useState(selector(ctx));
|
||||
useEffect(() => {
|
||||
const newState = selector(ctx);
|
||||
if (!isEqual(newState, state)) {
|
||||
setState(newState);
|
||||
}
|
||||
}, [ctx]);
|
||||
return state;
|
||||
};
|
||||
|
||||
export const ReportChartProvider = ({
|
||||
children,
|
||||
...propsToContext
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
@@ -11,15 +12,27 @@ import { Chart } from './chart';
|
||||
import { Summary } from './summary';
|
||||
|
||||
export function ReportConversionChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
console.log(report.limit);
|
||||
const res = useQuery(
|
||||
trpc.chart.conversion.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.conversion.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
|
||||
@@ -131,34 +131,36 @@ export function Tables({
|
||||
series: reportSeries,
|
||||
breakdowns: reportBreakdowns,
|
||||
previous,
|
||||
funnelWindow,
|
||||
funnelGroup,
|
||||
options,
|
||||
},
|
||||
} = useReportChartContext();
|
||||
|
||||
const funnelOptions = options?.type === 'funnel' ? options : undefined;
|
||||
const funnelWindow = funnelOptions?.funnelWindow;
|
||||
const funnelGroup = funnelOptions?.funnelGroup;
|
||||
|
||||
const handleInspectStep = (step: (typeof steps)[0], stepIndex: number) => {
|
||||
if (!projectId || !step.event.id) return;
|
||||
|
||||
// For funnels, we need to pass the step index so the modal can query
|
||||
// users who completed at least that step in the funnel sequence
|
||||
pushModal('ViewChartUsers', {
|
||||
type: 'funnel',
|
||||
report: {
|
||||
projectId,
|
||||
series: reportSeries,
|
||||
breakdowns: reportBreakdowns || [],
|
||||
interval: interval || 'day',
|
||||
startDate,
|
||||
endDate,
|
||||
range,
|
||||
previous,
|
||||
chartType: 'funnel',
|
||||
metric: 'sum',
|
||||
funnelWindow,
|
||||
funnelGroup,
|
||||
},
|
||||
stepIndex, // Pass the step index for funnel queries
|
||||
});
|
||||
pushModal('ViewChartUsers', {
|
||||
type: 'funnel',
|
||||
report: {
|
||||
projectId,
|
||||
series: reportSeries,
|
||||
breakdowns: reportBreakdowns || [],
|
||||
interval: interval || 'day',
|
||||
startDate,
|
||||
endDate,
|
||||
range,
|
||||
previous,
|
||||
chartType: 'funnel',
|
||||
metric: 'sum',
|
||||
options: funnelOptions,
|
||||
},
|
||||
stepIndex, // Pass the step index for funnel queries
|
||||
});
|
||||
};
|
||||
return (
|
||||
<div className={cn('col @container divide-y divide-border card')}>
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useTRPC } from '@/integrations/trpc/react';
|
||||
import type { RouterOutputs } from '@/trpc/client';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import type { IChartInput } from '@openpanel/validation';
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import type { IReportInput } from '@openpanel/validation';
|
||||
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
@@ -14,35 +15,39 @@ import { Chart, Summary, Tables } from './chart';
|
||||
export function ReportFunnelChart() {
|
||||
const {
|
||||
report: {
|
||||
id,
|
||||
series,
|
||||
range,
|
||||
projectId,
|
||||
funnelWindow,
|
||||
funnelGroup,
|
||||
options,
|
||||
startDate,
|
||||
endDate,
|
||||
previous,
|
||||
breakdowns,
|
||||
interval,
|
||||
},
|
||||
isLazyLoading,
|
||||
shareId,
|
||||
} = useReportChartContext();
|
||||
const { range: overviewRange, startDate: overviewStartDate, endDate: overviewEndDate, interval: overviewInterval } = useOverviewOptions();
|
||||
|
||||
const input: IChartInput = {
|
||||
const funnelOptions = options?.type === 'funnel' ? options : undefined;
|
||||
|
||||
const trpc = useTRPC();
|
||||
const input: IReportInput = {
|
||||
series,
|
||||
range,
|
||||
range: overviewRange ?? range,
|
||||
projectId,
|
||||
interval: 'day',
|
||||
interval: overviewInterval ?? interval ?? 'day',
|
||||
chartType: 'funnel',
|
||||
breakdowns,
|
||||
funnelWindow,
|
||||
funnelGroup,
|
||||
previous,
|
||||
metric: 'sum',
|
||||
startDate,
|
||||
endDate,
|
||||
startDate: overviewStartDate ?? startDate,
|
||||
endDate: overviewEndDate ?? endDate,
|
||||
limit: 20,
|
||||
options: funnelOptions,
|
||||
};
|
||||
const trpc = useTRPC();
|
||||
const res = useQuery(
|
||||
trpc.chart.funnel.queryOptions(input, {
|
||||
enabled: !isLazyLoading && input.series.length > 0,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -9,15 +10,27 @@ import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportHistogramChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.chart.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
|
||||
@@ -15,6 +15,7 @@ import { ReportMapChart } from './map';
|
||||
import { ReportMetricChart } from './metric';
|
||||
import { ReportPieChart } from './pie';
|
||||
import { ReportRetentionChart } from './retention';
|
||||
import { ReportSankeyChart } from './sankey';
|
||||
|
||||
export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
@@ -57,6 +58,8 @@ export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {
|
||||
return <ReportRetentionChart />;
|
||||
case 'conversion':
|
||||
return <ReportConversionChart />;
|
||||
case 'sankey':
|
||||
return <ReportSankeyChart />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { cn } from '@/utils/cn';
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -10,15 +11,27 @@ import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportLineChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.chart.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -9,15 +10,27 @@ import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportMapChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.chart.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
|
||||
@@ -1,19 +1,35 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportMetricChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.chart.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -47,28 +63,18 @@ export function Loading() {
|
||||
);
|
||||
}
|
||||
|
||||
export function Error() {
|
||||
function Error() {
|
||||
return (
|
||||
<div className="relative h-[70px]">
|
||||
<div className="opacity-50">
|
||||
<Loading />
|
||||
</div>
|
||||
<div className="center-center absolute inset-0 text-muted-foreground">
|
||||
<div className="text-sm font-medium">Error fetching data</div>
|
||||
</div>
|
||||
</div>
|
||||
<AspectContainer>
|
||||
<ReportChartError />
|
||||
</AspectContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export function Empty() {
|
||||
function Empty() {
|
||||
return (
|
||||
<div className="relative h-[70px]">
|
||||
<div className="opacity-50">
|
||||
<Loading />
|
||||
</div>
|
||||
<div className="center-center absolute inset-0 text-muted-foreground">
|
||||
<div className="text-sm font-medium">No data</div>
|
||||
</div>
|
||||
</div>
|
||||
<AspectContainer>
|
||||
<ReportChartEmpty />
|
||||
</AspectContainer>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -54,10 +54,7 @@ export function MetricCard({
|
||||
metric,
|
||||
unit,
|
||||
}: MetricCardProps) {
|
||||
const {
|
||||
report: { previousIndicatorInverted },
|
||||
isEditMode,
|
||||
} = useReportChartContext();
|
||||
const { isEditMode } = useReportChartContext();
|
||||
const number = useNumber();
|
||||
|
||||
const renderValue = (value: number | undefined, unitClassName?: string) => {
|
||||
@@ -80,7 +77,7 @@ export function MetricCard({
|
||||
const previous = serie.metrics.previous?.[metric];
|
||||
|
||||
const graphColors = getDiffIndicator(
|
||||
previousIndicatorInverted,
|
||||
false,
|
||||
previous?.state,
|
||||
'#6ee7b7', // green
|
||||
'#fda4af', // red
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -9,15 +10,27 @@ import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportPieChart() {
|
||||
const { isLazyLoading, report } = useReportChartContext();
|
||||
const { isLazyLoading, report, shareId } = useReportChartContext();
|
||||
const trpc = useTRPC();
|
||||
const { range, startDate, endDate, interval } = useOverviewOptions();
|
||||
|
||||
const res = useQuery(
|
||||
trpc.chart.chart.queryOptions(report, {
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
}),
|
||||
trpc.chart.aggregate.queryOptions(
|
||||
{
|
||||
...report,
|
||||
shareId,
|
||||
reportId: 'id' in report ? report.id : undefined,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? report.startDate,
|
||||
endDate: endDate ?? report.endDate,
|
||||
interval: interval ?? report.interval,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1000 * 60 * 1,
|
||||
enabled: !isLazyLoading,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
changeStartDate,
|
||||
ready,
|
||||
reset,
|
||||
setName,
|
||||
setReport,
|
||||
} from '@/components/report/reportSlice';
|
||||
import { ReportSidebar } from '@/components/report/sidebar/ReportSidebar';
|
||||
@@ -19,9 +18,10 @@ import { TimeWindowPicker } from '@/components/time-window-picker';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import { useAppParams } from '@/hooks/use-app-params';
|
||||
import { pushModal } from '@/modals';
|
||||
import { useDispatch, useSelector } from '@/redux';
|
||||
import { bind } from 'bind-event-listener';
|
||||
import { GanttChartSquareIcon } from 'lucide-react';
|
||||
import { GanttChartSquareIcon, ShareIcon } from 'lucide-react';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import type { IServiceReport } from '@openpanel/db';
|
||||
@@ -54,8 +54,19 @@ export default function ReportEditor({
|
||||
return (
|
||||
<Sheet>
|
||||
<div>
|
||||
<div className="p-4">
|
||||
<div className="p-4 flex items-center justify-between">
|
||||
<EditReportName />
|
||||
{initialReport?.id && (
|
||||
<Button
|
||||
variant="outline"
|
||||
icon={ShareIcon}
|
||||
onClick={() =>
|
||||
pushModal('ShareReportModal', { reportId: initialReport.id })
|
||||
}
|
||||
>
|
||||
Share
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 p-4 pt-0 md:grid-cols-6">
|
||||
<SheetTrigger asChild>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
@@ -12,21 +13,33 @@ import CohortTable from './table';
|
||||
export function ReportRetentionChart() {
|
||||
const {
|
||||
report: {
|
||||
id,
|
||||
series,
|
||||
range,
|
||||
projectId,
|
||||
options,
|
||||
startDate,
|
||||
endDate,
|
||||
criteria,
|
||||
interval,
|
||||
},
|
||||
isLazyLoading,
|
||||
shareId,
|
||||
} = useReportChartContext();
|
||||
const {
|
||||
range: overviewRange,
|
||||
startDate: overviewStartDate,
|
||||
endDate: overviewEndDate,
|
||||
interval: overviewInterval,
|
||||
} = useOverviewOptions();
|
||||
const eventSeries = series.filter((item) => item.type === 'event');
|
||||
const firstEvent = (eventSeries[0]?.filters?.[0]?.value ?? []).map(String);
|
||||
const secondEvent = (eventSeries[1]?.filters?.[0]?.value ?? []).map(String);
|
||||
const isEnabled =
|
||||
firstEvent.length > 0 && secondEvent.length > 0 && !isLazyLoading;
|
||||
|
||||
const retentionOptions = options?.type === 'retention' ? options : undefined;
|
||||
const criteria = retentionOptions?.criteria ?? 'on_or_after';
|
||||
|
||||
const trpc = useTRPC();
|
||||
const res = useQuery(
|
||||
trpc.chart.cohort.queryOptions(
|
||||
@@ -34,11 +47,13 @@ export function ReportRetentionChart() {
|
||||
firstEvent,
|
||||
secondEvent,
|
||||
projectId,
|
||||
range,
|
||||
startDate,
|
||||
endDate,
|
||||
range: overviewRange ?? range,
|
||||
startDate: overviewStartDate ?? startDate,
|
||||
endDate: overviewEndDate ?? endDate,
|
||||
criteria,
|
||||
interval,
|
||||
interval: overviewInterval ?? interval,
|
||||
shareId,
|
||||
reportId: id,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
|
||||
302
apps/start/src/components/report-chart/sankey/chart.tsx
Normal file
@@ -0,0 +1,302 @@
|
||||
import {
|
||||
ChartTooltipContainer,
|
||||
ChartTooltipHeader,
|
||||
ChartTooltipItem,
|
||||
} from '@/components/charts/chart-tooltip';
|
||||
import { useNumber } from '@/hooks/use-numer-formatter';
|
||||
import { round } from '@/utils/math';
|
||||
import { ResponsiveSankey } from '@nivo/sankey';
|
||||
import {
|
||||
type ReactNode,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
import { useTheme } from '@/components/theme-provider';
|
||||
import { truncate } from '@/utils/truncate';
|
||||
import { ArrowRightIcon } from 'lucide-react';
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
|
||||
type PortalTooltipPosition = { left: number; top: number; ready: boolean };
|
||||
|
||||
function SankeyPortalTooltip({
|
||||
children,
|
||||
offset = 12,
|
||||
padding = 8,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
offset?: number;
|
||||
padding?: number;
|
||||
}) {
|
||||
const anchorRef = useRef<HTMLSpanElement | null>(null);
|
||||
const tooltipRef = useRef<HTMLDivElement | null>(null);
|
||||
const [anchorRect, setAnchorRect] = useState<DOMRect | null>(null);
|
||||
const [pos, setPos] = useState<PortalTooltipPosition>({
|
||||
left: 0,
|
||||
top: 0,
|
||||
ready: false,
|
||||
});
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = anchorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const wrapper = el.parentElement;
|
||||
if (!wrapper) return;
|
||||
|
||||
const update = () => {
|
||||
setAnchorRect(wrapper.getBoundingClientRect());
|
||||
};
|
||||
|
||||
update();
|
||||
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(wrapper);
|
||||
|
||||
window.addEventListener('scroll', update, true);
|
||||
window.addEventListener('resize', update);
|
||||
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
window.removeEventListener('scroll', update, true);
|
||||
window.removeEventListener('resize', update);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!mounted) return;
|
||||
if (!anchorRect) return;
|
||||
const tooltipEl = tooltipRef.current;
|
||||
if (!tooltipEl) return;
|
||||
|
||||
const rect = tooltipEl.getBoundingClientRect();
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
|
||||
let left = anchorRect.left + offset;
|
||||
let top = anchorRect.top + offset;
|
||||
|
||||
left = Math.min(
|
||||
Math.max(padding, left),
|
||||
Math.max(padding, vw - rect.width - padding),
|
||||
);
|
||||
top = Math.min(
|
||||
Math.max(padding, top),
|
||||
Math.max(padding, vh - rect.height - padding),
|
||||
);
|
||||
|
||||
setPos({ left, top, ready: true });
|
||||
}, [mounted, anchorRect, children, offset, padding]);
|
||||
|
||||
if (typeof document === 'undefined') {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span ref={anchorRef} className="sr-only" />
|
||||
{mounted &&
|
||||
createPortal(
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
className="pointer-events-none fixed z-[9999]"
|
||||
style={{
|
||||
left: pos.left,
|
||||
top: pos.top,
|
||||
visibility: pos.ready ? 'visible' : 'hidden',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type SankeyData = {
|
||||
nodes: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
nodeColor: string;
|
||||
percentage?: number;
|
||||
value?: number;
|
||||
step?: number;
|
||||
}>;
|
||||
links: Array<{ source: string; target: string; value: number }>;
|
||||
};
|
||||
|
||||
export function Chart({ data }: { data: SankeyData }) {
|
||||
const number = useNumber();
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const { appTheme } = useTheme();
|
||||
|
||||
// Process data for Sankey
|
||||
const sankeyData = useMemo(() => {
|
||||
if (!data) return { nodes: [], links: [] };
|
||||
|
||||
return {
|
||||
nodes: data.nodes.map((node) => ({
|
||||
...node,
|
||||
label: node.label || node.id,
|
||||
data: {
|
||||
percentage: node.percentage,
|
||||
value: node.value,
|
||||
step: node.step,
|
||||
label: node.label || node.id,
|
||||
},
|
||||
})),
|
||||
links: data.links,
|
||||
};
|
||||
}, [data]);
|
||||
|
||||
const totalSessions = useMemo(() => {
|
||||
if (!sankeyData.nodes || sankeyData.nodes.length === 0) return 0;
|
||||
const step1 = sankeyData.nodes.filter((n: any) => n.data?.step === 1);
|
||||
const base = step1.length > 0 ? step1 : sankeyData.nodes;
|
||||
return base.reduce((sum: number, n: any) => sum + (n.data?.value ?? 0), 0);
|
||||
}, [sankeyData.nodes]);
|
||||
|
||||
return (
|
||||
<AspectContainer>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="w-full relative aspect-square md:aspect-[2]"
|
||||
>
|
||||
<ResponsiveSankey
|
||||
margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
|
||||
data={sankeyData}
|
||||
colors={(node: any) => node.nodeColor}
|
||||
nodeBorderRadius={2}
|
||||
animate={false}
|
||||
nodeBorderWidth={0}
|
||||
nodeOpacity={0.8}
|
||||
linkContract={1}
|
||||
linkOpacity={0.3}
|
||||
linkBlendMode={'normal'}
|
||||
nodeTooltip={({ node }: any) => {
|
||||
const label = node?.data?.label ?? node?.label ?? node?.id;
|
||||
const value = node?.data?.value ?? node?.value ?? 0;
|
||||
const step = node?.data?.step;
|
||||
const pct =
|
||||
typeof node?.data?.percentage === 'number'
|
||||
? node.data.percentage
|
||||
: totalSessions > 0
|
||||
? (value / totalSessions) * 100
|
||||
: 0;
|
||||
const color =
|
||||
node?.color ??
|
||||
node?.data?.nodeColor ??
|
||||
node?.data?.color ??
|
||||
node?.nodeColor ??
|
||||
'#64748b';
|
||||
|
||||
return (
|
||||
<SankeyPortalTooltip>
|
||||
<ChartTooltipContainer className="min-w-[250px]">
|
||||
<ChartTooltipHeader>
|
||||
<div className="min-w-0 flex-1 font-medium break-words">
|
||||
{label}
|
||||
</div>
|
||||
{typeof step === 'number' && (
|
||||
<div className="shrink-0 text-muted-foreground">
|
||||
Step {step}
|
||||
</div>
|
||||
)}
|
||||
</ChartTooltipHeader>
|
||||
<ChartTooltipItem color={color} innerClassName="gap-2">
|
||||
<div className="flex items-center justify-between gap-8 font-mono font-medium">
|
||||
<div className="text-muted-foreground">Sessions</div>
|
||||
<div>{number.format(value)}</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-8 font-mono font-medium">
|
||||
<div className="text-muted-foreground">Share</div>
|
||||
<div>{number.format(round(pct, 1))} %</div>
|
||||
</div>
|
||||
</ChartTooltipItem>
|
||||
</ChartTooltipContainer>
|
||||
</SankeyPortalTooltip>
|
||||
);
|
||||
}}
|
||||
linkTooltip={({ link }: any) => {
|
||||
const sourceLabel =
|
||||
link?.source?.data?.label ??
|
||||
link?.source?.label ??
|
||||
link?.source?.id;
|
||||
const targetLabel =
|
||||
link?.target?.data?.label ??
|
||||
link?.target?.label ??
|
||||
link?.target?.id;
|
||||
|
||||
const value = link?.value ?? 0;
|
||||
const sourceValue =
|
||||
link?.source?.data?.value ?? link?.source?.value ?? 0;
|
||||
|
||||
const pctOfTotal =
|
||||
totalSessions > 0 ? (value / totalSessions) * 100 : 0;
|
||||
const pctOfSource =
|
||||
sourceValue > 0 ? (value / sourceValue) * 100 : 0;
|
||||
|
||||
const sourceStep = link?.source?.data?.step;
|
||||
const targetStep = link?.target?.data?.step;
|
||||
|
||||
const color =
|
||||
link?.color ??
|
||||
link?.source?.color ??
|
||||
link?.source?.data?.nodeColor ??
|
||||
'#64748b';
|
||||
|
||||
return (
|
||||
<SankeyPortalTooltip>
|
||||
<ChartTooltipContainer>
|
||||
<ChartTooltipHeader>
|
||||
<div className="min-w-0 flex-1 font-medium break-words">
|
||||
{sourceLabel}
|
||||
<ArrowRightIcon className="size-2 inline-block mx-3" />
|
||||
{targetLabel}
|
||||
</div>
|
||||
{typeof sourceStep === 'number' &&
|
||||
typeof targetStep === 'number' && (
|
||||
<div className="shrink-0 text-muted-foreground">
|
||||
{sourceStep} → {targetStep}
|
||||
</div>
|
||||
)}
|
||||
</ChartTooltipHeader>
|
||||
|
||||
<ChartTooltipItem color={color} innerClassName="gap-2">
|
||||
<div className="flex items-center justify-between gap-8 font-mono font-medium">
|
||||
<div className="text-muted-foreground">Sessions</div>
|
||||
<div>{number.format(value)}</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-8 font-mono text-sm">
|
||||
<div className="text-muted-foreground">% of total</div>
|
||||
<div>{number.format(round(pctOfTotal, 1))} %</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-8 font-mono text-sm">
|
||||
<div className="text-muted-foreground">% of source</div>
|
||||
<div>{number.format(round(pctOfSource, 1))} %</div>
|
||||
</div>
|
||||
</ChartTooltipItem>
|
||||
</ChartTooltipContainer>
|
||||
</SankeyPortalTooltip>
|
||||
);
|
||||
}}
|
||||
label={(node: any) => {
|
||||
const label = node.data?.label || node.label || node.id;
|
||||
return truncate(label, 30, 'middle');
|
||||
}}
|
||||
labelTextColor={appTheme === 'dark' ? '#e2e8f0' : '#0f172a'}
|
||||
nodeSpacing={10}
|
||||
/>
|
||||
</div>
|
||||
</AspectContainer>
|
||||
);
|
||||
}
|
||||
93
apps/start/src/components/report-chart/sankey/index.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useTRPC } from '@/integrations/trpc/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import type { IReportInput } from '@openpanel/validation';
|
||||
|
||||
import { AspectContainer } from '../aspect-container';
|
||||
import { ReportChartEmpty } from '../common/empty';
|
||||
import { ReportChartError } from '../common/error';
|
||||
import { ReportChartLoading } from '../common/loading';
|
||||
import { useReportChartContext } from '../context';
|
||||
import { Chart } from './chart';
|
||||
|
||||
export function ReportSankeyChart() {
|
||||
const {
|
||||
report: {
|
||||
series,
|
||||
range,
|
||||
projectId,
|
||||
options,
|
||||
startDate,
|
||||
endDate,
|
||||
breakdowns,
|
||||
},
|
||||
isLazyLoading,
|
||||
} = useReportChartContext();
|
||||
|
||||
if (!options) {
|
||||
return <Empty />;
|
||||
}
|
||||
|
||||
const input: IReportInput = {
|
||||
series,
|
||||
range,
|
||||
projectId,
|
||||
interval: 'day',
|
||||
chartType: 'sankey',
|
||||
breakdowns,
|
||||
options,
|
||||
metric: 'sum',
|
||||
startDate,
|
||||
endDate,
|
||||
limit: 20,
|
||||
previous: false,
|
||||
};
|
||||
const trpc = useTRPC();
|
||||
const res = useQuery(
|
||||
trpc.chart.sankey.queryOptions(input, {
|
||||
enabled: !isLazyLoading && input.series.length > 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (isLazyLoading || res.isLoading) {
|
||||
return <Loading />;
|
||||
}
|
||||
|
||||
if (res.isError) {
|
||||
return <Error />;
|
||||
}
|
||||
|
||||
if (!res.data || res.data.nodes.length === 0) {
|
||||
return <Empty />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="col gap-4">
|
||||
<Chart data={res.data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Loading() {
|
||||
return (
|
||||
<AspectContainer>
|
||||
<ReportChartLoading />
|
||||
</AspectContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function Error() {
|
||||
return (
|
||||
<AspectContainer>
|
||||
<ReportChartError />
|
||||
</AspectContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function Empty() {
|
||||
return (
|
||||
<AspectContainer>
|
||||
<ReportChartEmpty />
|
||||
</AspectContainer>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export const ReportChartShortcut = ({
|
||||
return (
|
||||
<ReportChart
|
||||
report={{
|
||||
name: 'Shortcut',
|
||||
projectId,
|
||||
range,
|
||||
breakdowns: breakdowns ?? [],
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
ChartColumnIncreasingIcon,
|
||||
ConeIcon,
|
||||
GaugeIcon,
|
||||
GitBranchIcon,
|
||||
Globe2Icon,
|
||||
LineChartIcon,
|
||||
type LucideIcon,
|
||||
@@ -58,6 +59,7 @@ export function ReportChartType({
|
||||
retention: UsersIcon,
|
||||
map: Globe2Icon,
|
||||
conversion: TrendingUpIcon,
|
||||
sankey: GitBranchIcon,
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
255
apps/start/src/components/report/report-item.tsx
Normal file
@@ -0,0 +1,255 @@
|
||||
import { ReportChart } from '@/components/report-chart';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { CopyIcon, MoreHorizontal, Trash } from 'lucide-react';
|
||||
|
||||
import { timeWindows } from '@openpanel/constants';
|
||||
|
||||
import { useRouter } from '@tanstack/react-router';
|
||||
|
||||
export function ReportItemSkeleton() {
|
||||
return (
|
||||
<div className="card h-full flex flex-col animate-pulse">
|
||||
<div className="flex items-center justify-between border-b border-border p-4">
|
||||
<div className="flex-1">
|
||||
<div className="h-5 w-32 bg-muted rounded mb-2" />
|
||||
<div className="h-4 w-24 bg-muted/50 rounded" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-muted rounded" />
|
||||
<div className="w-8 h-8 bg-muted rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 flex-1 flex items-center justify-center aspect-video" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReportItem({
|
||||
report,
|
||||
organizationId,
|
||||
projectId,
|
||||
range,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
onDelete,
|
||||
onDuplicate,
|
||||
}: {
|
||||
report: any;
|
||||
organizationId: string;
|
||||
projectId: string;
|
||||
range: any;
|
||||
startDate: any;
|
||||
endDate: any;
|
||||
interval: any;
|
||||
onDelete: (reportId: string) => void;
|
||||
onDuplicate: (reportId: string) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const chartRange = report.range;
|
||||
|
||||
return (
|
||||
<div className="card h-full flex flex-col">
|
||||
<div className="flex items-center hover:bg-muted/50 justify-between border-b border-border p-4 leading-none [&_svg]:hover:opacity-100">
|
||||
<div
|
||||
className="flex-1 cursor-pointer -m-4 p-4"
|
||||
onClick={(event) => {
|
||||
if (event.metaKey) {
|
||||
window.open(
|
||||
`/${organizationId}/${projectId}/reports/${report.id}`,
|
||||
'_blank',
|
||||
);
|
||||
return;
|
||||
}
|
||||
router.navigate({
|
||||
to: '/$organizationId/$projectId/reports/$reportId',
|
||||
params: {
|
||||
organizationId,
|
||||
projectId,
|
||||
reportId: report.id,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onKeyUp={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
router.navigate({
|
||||
to: '/$organizationId/$projectId/reports/$reportId',
|
||||
params: {
|
||||
organizationId,
|
||||
projectId,
|
||||
reportId: report.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
>
|
||||
<div className="font-medium">{report.name}</div>
|
||||
{chartRange !== null && (
|
||||
<div className="mt-2 flex gap-2 ">
|
||||
<span
|
||||
className={
|
||||
(chartRange !== range && range !== null) ||
|
||||
(startDate && endDate)
|
||||
? 'line-through'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{timeWindows[chartRange as keyof typeof timeWindows]?.label}
|
||||
</span>
|
||||
{startDate && endDate ? (
|
||||
<span>Custom dates</span>
|
||||
) : (
|
||||
range !== null &&
|
||||
chartRange !== range && (
|
||||
<span>
|
||||
{timeWindows[range as keyof typeof timeWindows]?.label}
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="drag-handle cursor-move p-2 hover:bg-muted rounded">
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
className="opacity-30 hover:opacity-100"
|
||||
>
|
||||
<circle cx="4" cy="4" r="1.5" />
|
||||
<circle cx="4" cy="8" r="1.5" />
|
||||
<circle cx="4" cy="12" r="1.5" />
|
||||
<circle cx="12" cy="4" r="1.5" />
|
||||
<circle cx="12" cy="8" r="1.5" />
|
||||
<circle cx="12" cy="12" r="1.5" />
|
||||
</svg>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger className="flex h-8 w-8 items-center justify-center rounded hover:border">
|
||||
<MoreHorizontal size={16} />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-[200px]">
|
||||
<DropdownMenuItem
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onDuplicate(report.id);
|
||||
}}
|
||||
>
|
||||
<CopyIcon size={16} className="mr-2" />
|
||||
Duplicate
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onDelete(report.id);
|
||||
}}
|
||||
>
|
||||
<Trash size={16} className="mr-2" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'p-4 overflow-auto flex-1',
|
||||
report.chartType === 'metric' && 'p-0',
|
||||
)}
|
||||
>
|
||||
<ReportChart
|
||||
report={{
|
||||
...report,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? null,
|
||||
endDate: endDate ?? null,
|
||||
interval: interval ?? report.interval,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReportItemReadOnly({
|
||||
report,
|
||||
shareId,
|
||||
range,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
}: {
|
||||
report: any;
|
||||
shareId: string;
|
||||
range: any;
|
||||
startDate: any;
|
||||
endDate: any;
|
||||
interval: any;
|
||||
}) {
|
||||
const chartRange = report.range;
|
||||
|
||||
return (
|
||||
<div className="card h-full flex flex-col">
|
||||
<div className="flex items-center justify-between border-b border-border p-4 leading-none">
|
||||
<div className="flex-1">
|
||||
<div className="font-medium">{report.name}</div>
|
||||
{chartRange !== null && (
|
||||
<div className="mt-2 flex gap-2 ">
|
||||
<span
|
||||
className={
|
||||
(chartRange !== range && range !== null) ||
|
||||
(startDate && endDate)
|
||||
? 'line-through'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{timeWindows[chartRange as keyof typeof timeWindows]?.label}
|
||||
</span>
|
||||
{startDate && endDate ? (
|
||||
<span>Custom dates</span>
|
||||
) : (
|
||||
range !== null &&
|
||||
chartRange !== range && (
|
||||
<span>
|
||||
{timeWindows[range as keyof typeof timeWindows]?.label}
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'p-4 overflow-auto flex-1',
|
||||
report.chartType === 'metric' && 'p-0',
|
||||
)}
|
||||
>
|
||||
<ReportChart
|
||||
report={{
|
||||
...report,
|
||||
range: range ?? report.range,
|
||||
startDate: startDate ?? null,
|
||||
endDate: endDate ?? null,
|
||||
interval: interval ?? report.interval,
|
||||
}}
|
||||
shareId={shareId}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { PayloadAction } from '@reduxjs/toolkit';
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
import { endOfDay, format, isSameDay, isSameMonth, startOfDay } from 'date-fns';
|
||||
|
||||
import { shortId } from '@openpanel/common';
|
||||
import {
|
||||
@@ -12,18 +11,19 @@ import {
|
||||
import type {
|
||||
IChartBreakdown,
|
||||
IChartEventItem,
|
||||
IChartFormula,
|
||||
IChartLineType,
|
||||
IChartProps,
|
||||
IChartRange,
|
||||
IChartType,
|
||||
IInterval,
|
||||
IReport,
|
||||
IReportOptions,
|
||||
UnionOmit,
|
||||
zCriteria,
|
||||
} from '@openpanel/validation';
|
||||
import type { z } from 'zod';
|
||||
|
||||
type InitialState = IChartProps & {
|
||||
type InitialState = IReport & {
|
||||
id?: string;
|
||||
dirty: boolean;
|
||||
ready: boolean;
|
||||
startDate: string | null;
|
||||
@@ -34,7 +34,6 @@ type InitialState = IChartProps & {
|
||||
const initialState: InitialState = {
|
||||
ready: false,
|
||||
dirty: false,
|
||||
// TODO: remove this
|
||||
projectId: '',
|
||||
name: '',
|
||||
chartType: 'linear',
|
||||
@@ -50,9 +49,7 @@ const initialState: InitialState = {
|
||||
unit: undefined,
|
||||
metric: 'sum',
|
||||
limit: 500,
|
||||
criteria: 'on_or_after',
|
||||
funnelGroup: undefined,
|
||||
funnelWindow: undefined,
|
||||
options: undefined,
|
||||
};
|
||||
|
||||
export const reportSlice = createSlice({
|
||||
@@ -74,7 +71,7 @@ export const reportSlice = createSlice({
|
||||
ready: true,
|
||||
};
|
||||
},
|
||||
setReport(state, action: PayloadAction<IChartProps>) {
|
||||
setReport(state, action: PayloadAction<IReport>) {
|
||||
return {
|
||||
...state,
|
||||
...action.payload,
|
||||
@@ -187,6 +184,16 @@ export const reportSlice = createSlice({
|
||||
state.dirty = true;
|
||||
state.chartType = action.payload;
|
||||
|
||||
// Initialize sankey options if switching to sankey
|
||||
if (action.payload === 'sankey' && !state.options) {
|
||||
state.options = {
|
||||
type: 'sankey',
|
||||
mode: 'after',
|
||||
steps: 5,
|
||||
exclude: [],
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
!isMinuteIntervalEnabledByRange(state.range) &&
|
||||
state.interval === 'minute'
|
||||
@@ -254,7 +261,14 @@ export const reportSlice = createSlice({
|
||||
|
||||
changeCriteria(state, action: PayloadAction<z.infer<typeof zCriteria>>) {
|
||||
state.dirty = true;
|
||||
state.criteria = action.payload;
|
||||
if (!state.options || state.options.type !== 'retention') {
|
||||
state.options = {
|
||||
type: 'retention',
|
||||
criteria: action.payload,
|
||||
};
|
||||
} else {
|
||||
state.options.criteria = action.payload;
|
||||
}
|
||||
},
|
||||
|
||||
changeUnit(state, action: PayloadAction<string | undefined>) {
|
||||
@@ -264,12 +278,88 @@ export const reportSlice = createSlice({
|
||||
|
||||
changeFunnelGroup(state, action: PayloadAction<string | undefined>) {
|
||||
state.dirty = true;
|
||||
state.funnelGroup = action.payload || undefined;
|
||||
if (!state.options || state.options.type !== 'funnel') {
|
||||
state.options = {
|
||||
type: 'funnel',
|
||||
funnelGroup: action.payload,
|
||||
funnelWindow: undefined,
|
||||
};
|
||||
} else {
|
||||
state.options.funnelGroup = action.payload;
|
||||
}
|
||||
},
|
||||
|
||||
changeFunnelWindow(state, action: PayloadAction<number | undefined>) {
|
||||
state.dirty = true;
|
||||
state.funnelWindow = action.payload || undefined;
|
||||
if (!state.options || state.options.type !== 'funnel') {
|
||||
state.options = {
|
||||
type: 'funnel',
|
||||
funnelGroup: undefined,
|
||||
funnelWindow: action.payload,
|
||||
};
|
||||
} else {
|
||||
state.options.funnelWindow = action.payload;
|
||||
}
|
||||
},
|
||||
changeOptions(state, action: PayloadAction<IReportOptions | undefined>) {
|
||||
state.dirty = true;
|
||||
state.options = action.payload || undefined;
|
||||
},
|
||||
changeSankeyMode(
|
||||
state,
|
||||
action: PayloadAction<'between' | 'after' | 'before'>,
|
||||
) {
|
||||
state.dirty = true;
|
||||
if (!state.options) {
|
||||
state.options = {
|
||||
type: 'sankey',
|
||||
mode: action.payload,
|
||||
steps: 5,
|
||||
exclude: [],
|
||||
};
|
||||
} else if (state.options.type === 'sankey') {
|
||||
state.options.mode = action.payload;
|
||||
}
|
||||
},
|
||||
changeSankeySteps(state, action: PayloadAction<number>) {
|
||||
state.dirty = true;
|
||||
if (!state.options) {
|
||||
state.options = {
|
||||
type: 'sankey',
|
||||
mode: 'after',
|
||||
steps: action.payload,
|
||||
exclude: [],
|
||||
};
|
||||
} else if (state.options.type === 'sankey') {
|
||||
state.options.steps = action.payload;
|
||||
}
|
||||
},
|
||||
changeSankeyExclude(state, action: PayloadAction<string[]>) {
|
||||
state.dirty = true;
|
||||
if (!state.options) {
|
||||
state.options = {
|
||||
type: 'sankey',
|
||||
mode: 'after',
|
||||
steps: 5,
|
||||
exclude: action.payload,
|
||||
};
|
||||
} else if (state.options.type === 'sankey') {
|
||||
state.options.exclude = action.payload;
|
||||
}
|
||||
},
|
||||
changeSankeyInclude(state, action: PayloadAction<string[] | undefined>) {
|
||||
state.dirty = true;
|
||||
if (!state.options) {
|
||||
state.options = {
|
||||
type: 'sankey',
|
||||
mode: 'after',
|
||||
steps: 5,
|
||||
exclude: [],
|
||||
include: action.payload,
|
||||
};
|
||||
} else if (state.options.type === 'sankey') {
|
||||
state.options.include = action.payload;
|
||||
}
|
||||
},
|
||||
reorderEvents(
|
||||
state,
|
||||
@@ -311,6 +401,11 @@ export const {
|
||||
changeUnit,
|
||||
changeFunnelGroup,
|
||||
changeFunnelWindow,
|
||||
changeOptions,
|
||||
changeSankeyMode,
|
||||
changeSankeySteps,
|
||||
changeSankeyExclude,
|
||||
changeSankeyInclude,
|
||||
reorderEvents,
|
||||
} = reportSlice.actions;
|
||||
|
||||
|
||||
@@ -23,15 +23,13 @@ import {
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { shortId } from '@openpanel/common';
|
||||
import { alphabetIds } from '@openpanel/constants';
|
||||
import type {
|
||||
IChartEvent,
|
||||
IChartEventItem,
|
||||
IChartFormula,
|
||||
} from '@openpanel/validation';
|
||||
import { FilterIcon, HandIcon, PiIcon } from 'lucide-react';
|
||||
import { ReportSegment } from '../ReportSegment';
|
||||
import { HandIcon, PiIcon, PlusIcon } from 'lucide-react';
|
||||
import {
|
||||
addSerie,
|
||||
changeEvent,
|
||||
@@ -39,27 +37,21 @@ import {
|
||||
removeEvent,
|
||||
reorderEvents,
|
||||
} from '../reportSlice';
|
||||
import { EventPropertiesCombobox } from './EventPropertiesCombobox';
|
||||
import { PropertiesCombobox } from './PropertiesCombobox';
|
||||
import type { ReportEventMoreProps } from './ReportEventMore';
|
||||
import { ReportEventMore } from './ReportEventMore';
|
||||
import { FiltersList } from './filters/FiltersList';
|
||||
import {
|
||||
ReportSeriesItem,
|
||||
type ReportSeriesItemProps,
|
||||
} from './ReportSeriesItem';
|
||||
|
||||
function SortableSeries({
|
||||
function SortableReportSeriesItem({
|
||||
event,
|
||||
index,
|
||||
showSegment,
|
||||
showAddFilter,
|
||||
isSelectManyEvents,
|
||||
...props
|
||||
}: {
|
||||
event: IChartEventItem | IChartEvent;
|
||||
index: number;
|
||||
showSegment: boolean;
|
||||
showAddFilter: boolean;
|
||||
isSelectManyEvents: boolean;
|
||||
} & React.HTMLAttributes<HTMLDivElement>) {
|
||||
const dispatch = useDispatch();
|
||||
}: Omit<ReportSeriesItemProps, 'renderDragHandle'>) {
|
||||
const eventId = 'type' in event ? event.id : (event as IChartEvent).id;
|
||||
const { attributes, listeners, setNodeRef, transform, transition } =
|
||||
useSortable({ id: eventId ?? '' });
|
||||
@@ -69,85 +61,26 @@ function SortableSeries({
|
||||
transition,
|
||||
};
|
||||
|
||||
// Normalize event to have type field
|
||||
const normalizedEvent: IChartEventItem =
|
||||
'type' in event ? event : { ...event, type: 'event' as const };
|
||||
|
||||
const isFormula = normalizedEvent.type === 'formula';
|
||||
const chartEvent = isFormula
|
||||
? null
|
||||
: (normalizedEvent as IChartEventItem & { type: 'event' });
|
||||
|
||||
return (
|
||||
<div ref={setNodeRef} style={style} {...attributes} {...props}>
|
||||
<div className="flex items-center gap-2 p-2 group">
|
||||
<button className="cursor-grab active:cursor-grabbing" {...listeners}>
|
||||
<ColorSquare className="relative">
|
||||
<HandIcon className="size-3 opacity-0 scale-50 group-hover:opacity-100 group-hover:scale-100 transition-all absolute inset-1" />
|
||||
<span className="block group-hover:opacity-0 group-hover:scale-0 transition-all">
|
||||
{alphabetIds[index]}
|
||||
</span>
|
||||
</ColorSquare>
|
||||
</button>
|
||||
{props.children}
|
||||
</div>
|
||||
|
||||
{/* Segment and Filter buttons - only for events */}
|
||||
{chartEvent && (showSegment || showAddFilter) && (
|
||||
<div className="flex gap-2 p-2 pt-0">
|
||||
{showSegment && (
|
||||
<ReportSegment
|
||||
value={chartEvent.segment}
|
||||
onChange={(segment) => {
|
||||
dispatch(
|
||||
changeEvent({
|
||||
...chartEvent,
|
||||
segment,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{showAddFilter && (
|
||||
<PropertiesCombobox
|
||||
event={chartEvent}
|
||||
onSelect={(action) => {
|
||||
dispatch(
|
||||
changeEvent({
|
||||
...chartEvent,
|
||||
filters: [
|
||||
...chartEvent.filters,
|
||||
{
|
||||
id: shortId(),
|
||||
name: action.value,
|
||||
operator: 'is',
|
||||
value: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{(setOpen) => (
|
||||
<button
|
||||
onClick={() => setOpen((p) => !p)}
|
||||
type="button"
|
||||
className="flex items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-sm font-medium leading-none"
|
||||
>
|
||||
<FilterIcon size={12} /> Add filter
|
||||
</button>
|
||||
)}
|
||||
</PropertiesCombobox>
|
||||
)}
|
||||
|
||||
{showSegment && chartEvent.segment.startsWith('property_') && (
|
||||
<EventPropertiesCombobox event={chartEvent} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filters - only for events */}
|
||||
{chartEvent && !isSelectManyEvents && <FiltersList event={chartEvent} />}
|
||||
<div ref={setNodeRef} style={style} {...attributes}>
|
||||
<ReportSeriesItem
|
||||
event={event}
|
||||
index={index}
|
||||
showSegment={showSegment}
|
||||
showAddFilter={showAddFilter}
|
||||
isSelectManyEvents={isSelectManyEvents}
|
||||
renderDragHandle={(index) => (
|
||||
<button className="cursor-grab active:cursor-grabbing" {...listeners}>
|
||||
<ColorSquare className="relative">
|
||||
<HandIcon className="size-3 opacity-0 scale-50 group-hover:opacity-100 group-hover:scale-100 transition-all absolute inset-1" />
|
||||
<span className="block group-hover:opacity-0 group-hover:scale-0 transition-all">
|
||||
{alphabetIds[index]}
|
||||
</span>
|
||||
</ColorSquare>
|
||||
</button>
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -161,12 +94,23 @@ export function ReportSeries() {
|
||||
projectId,
|
||||
});
|
||||
|
||||
const showSegment = !['retention', 'funnel'].includes(chartType);
|
||||
const showAddFilter = !['retention'].includes(chartType);
|
||||
const showDisplayNameInput = !['retention'].includes(chartType);
|
||||
const showSegment = !['retention', 'funnel', 'sankey'].includes(chartType);
|
||||
const showAddFilter = !['retention', 'sankey'].includes(chartType);
|
||||
const showDisplayNameInput = !['retention', 'sankey'].includes(chartType);
|
||||
const options = useSelector((state) => state.report.options);
|
||||
const isSankey = chartType === 'sankey';
|
||||
const isAddEventDisabled =
|
||||
(chartType === 'retention' || chartType === 'conversion') &&
|
||||
selectedSeries.length >= 2;
|
||||
const isSankeyEventLimitReached =
|
||||
isSankey &&
|
||||
options &&
|
||||
((options.type === 'sankey' &&
|
||||
options.mode === 'between' &&
|
||||
selectedSeries.length >= 2) ||
|
||||
(options.type === 'sankey' &&
|
||||
options.mode !== 'between' &&
|
||||
selectedSeries.length >= 1));
|
||||
const dispatchChangeEvent = useDebounceFn((event: IChartEventItem) => {
|
||||
dispatch(changeEvent(event));
|
||||
});
|
||||
@@ -218,7 +162,8 @@ export function ReportSeries() {
|
||||
const showFormula =
|
||||
chartType !== 'conversion' &&
|
||||
chartType !== 'funnel' &&
|
||||
chartType !== 'retention';
|
||||
chartType !== 'retention' &&
|
||||
chartType !== 'sankey';
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -239,7 +184,7 @@ export function ReportSeries() {
|
||||
const isFormula = event.type === 'formula';
|
||||
|
||||
return (
|
||||
<SortableSeries
|
||||
<SortableReportSeriesItem
|
||||
key={event.id}
|
||||
event={event}
|
||||
index={index}
|
||||
@@ -348,13 +293,14 @@ export function ReportSeries() {
|
||||
<ReportEventMore onClick={handleMore(event)} />
|
||||
</>
|
||||
)}
|
||||
</SortableSeries>
|
||||
</SortableReportSeriesItem>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<ComboboxEvents
|
||||
disabled={isAddEventDisabled}
|
||||
className="flex-1"
|
||||
disabled={isAddEventDisabled || isSankeyEventLimitReached}
|
||||
value={''}
|
||||
searchable
|
||||
onChange={(value) => {
|
||||
@@ -392,6 +338,7 @@ export function ReportSeries() {
|
||||
type="button"
|
||||
variant="outline"
|
||||
icon={PiIcon}
|
||||
className="flex-1 justify-start text-left px-4"
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
addSerie({
|
||||
@@ -403,6 +350,7 @@ export function ReportSeries() {
|
||||
}}
|
||||
>
|
||||
Add Formula
|
||||
<PlusIcon className="size-4 ml-auto text-muted-foreground" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
114
apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { ColorSquare } from '@/components/color-square';
|
||||
import { useDispatch } from '@/redux';
|
||||
import { shortId } from '@openpanel/common';
|
||||
import { alphabetIds } from '@openpanel/constants';
|
||||
import type { IChartEvent, IChartEventItem } from '@openpanel/validation';
|
||||
import { FilterIcon } from 'lucide-react';
|
||||
import { ReportSegment } from '../ReportSegment';
|
||||
import { changeEvent } from '../reportSlice';
|
||||
import { EventPropertiesCombobox } from './EventPropertiesCombobox';
|
||||
import { PropertiesCombobox } from './PropertiesCombobox';
|
||||
import { FiltersList } from './filters/FiltersList';
|
||||
|
||||
export interface ReportSeriesItemProps
|
||||
extends React.HTMLAttributes<HTMLDivElement> {
|
||||
event: IChartEventItem | IChartEvent;
|
||||
index: number;
|
||||
showSegment: boolean;
|
||||
showAddFilter: boolean;
|
||||
isSelectManyEvents: boolean;
|
||||
renderDragHandle?: (index: number) => React.ReactNode;
|
||||
}
|
||||
|
||||
export function ReportSeriesItem({
|
||||
event,
|
||||
index,
|
||||
showSegment,
|
||||
showAddFilter,
|
||||
isSelectManyEvents,
|
||||
renderDragHandle,
|
||||
...props
|
||||
}: ReportSeriesItemProps) {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
// Normalize event to have type field
|
||||
const normalizedEvent: IChartEventItem =
|
||||
'type' in event ? event : { ...event, type: 'event' as const };
|
||||
|
||||
const isFormula = normalizedEvent.type === 'formula';
|
||||
const chartEvent = isFormula
|
||||
? null
|
||||
: (normalizedEvent as IChartEventItem & { type: 'event' });
|
||||
|
||||
return (
|
||||
<div {...props}>
|
||||
<div className="flex items-center gap-2 p-2 group">
|
||||
{renderDragHandle ? (
|
||||
renderDragHandle(index)
|
||||
) : (
|
||||
<ColorSquare>
|
||||
<span className="block">{alphabetIds[index]}</span>
|
||||
</ColorSquare>
|
||||
)}
|
||||
{props.children}
|
||||
</div>
|
||||
|
||||
{/* Segment and Filter buttons - only for events */}
|
||||
{chartEvent && (showSegment || showAddFilter) && (
|
||||
<div className="flex gap-2 p-2 pt-0">
|
||||
{showSegment && (
|
||||
<ReportSegment
|
||||
value={chartEvent.segment}
|
||||
onChange={(segment) => {
|
||||
dispatch(
|
||||
changeEvent({
|
||||
...chartEvent,
|
||||
segment,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{showAddFilter && (
|
||||
<PropertiesCombobox
|
||||
event={chartEvent}
|
||||
onSelect={(action) => {
|
||||
dispatch(
|
||||
changeEvent({
|
||||
...chartEvent,
|
||||
filters: [
|
||||
...chartEvent.filters,
|
||||
{
|
||||
id: shortId(),
|
||||
name: action.value,
|
||||
operator: 'is',
|
||||
value: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{(setOpen) => (
|
||||
<button
|
||||
onClick={() => setOpen((p) => !p)}
|
||||
type="button"
|
||||
className="flex items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-sm font-medium leading-none"
|
||||
>
|
||||
<FilterIcon size={12} /> Add filter
|
||||
</button>
|
||||
)}
|
||||
</PropertiesCombobox>
|
||||
)}
|
||||
|
||||
{showSegment && chartEvent.segment.startsWith('property_') && (
|
||||
<EventPropertiesCombobox event={chartEvent} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filters - only for events */}
|
||||
{chartEvent && !isSelectManyEvents && <FiltersList event={chartEvent} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +1,46 @@
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { useDispatch, useSelector } from '@/redux';
|
||||
|
||||
import { ComboboxEvents } from '@/components/ui/combobox-events';
|
||||
import { InputEnter } from '@/components/ui/input-enter';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useAppParams } from '@/hooks/use-app-params';
|
||||
import { useEventNames } from '@/hooks/use-event-names';
|
||||
import { useMemo } from 'react';
|
||||
import {
|
||||
changeCriteria,
|
||||
changeFunnelGroup,
|
||||
changeFunnelWindow,
|
||||
changePrevious,
|
||||
changeSankeyExclude,
|
||||
changeSankeyInclude,
|
||||
changeSankeyMode,
|
||||
changeSankeySteps,
|
||||
changeUnit,
|
||||
} from '../reportSlice';
|
||||
|
||||
export function ReportSettings() {
|
||||
const chartType = useSelector((state) => state.report.chartType);
|
||||
const previous = useSelector((state) => state.report.previous);
|
||||
const criteria = useSelector((state) => state.report.criteria);
|
||||
const unit = useSelector((state) => state.report.unit);
|
||||
const funnelGroup = useSelector((state) => state.report.funnelGroup);
|
||||
const funnelWindow = useSelector((state) => state.report.funnelWindow);
|
||||
const options = useSelector((state) => state.report.options);
|
||||
|
||||
const retentionOptions = options?.type === 'retention' ? options : undefined;
|
||||
const criteria = retentionOptions?.criteria ?? 'on_or_after';
|
||||
|
||||
const funnelOptions = options?.type === 'funnel' ? options : undefined;
|
||||
const funnelGroup = funnelOptions?.funnelGroup;
|
||||
const funnelWindow = funnelOptions?.funnelWindow;
|
||||
|
||||
const dispatch = useDispatch();
|
||||
const { projectId } = useAppParams();
|
||||
const eventNames = useEventNames({ projectId });
|
||||
|
||||
const fields = useMemo(() => {
|
||||
const fields = [];
|
||||
|
||||
if (chartType !== 'retention') {
|
||||
if (chartType !== 'retention' && chartType !== 'sankey') {
|
||||
fields.push('previous');
|
||||
}
|
||||
|
||||
@@ -40,6 +54,13 @@ export function ReportSettings() {
|
||||
fields.push('funnelWindow');
|
||||
}
|
||||
|
||||
if (chartType === 'sankey') {
|
||||
fields.push('sankeyMode');
|
||||
fields.push('sankeySteps');
|
||||
fields.push('sankeyExclude');
|
||||
fields.push('sankeyInclude');
|
||||
}
|
||||
|
||||
return fields;
|
||||
}, [chartType]);
|
||||
|
||||
@@ -50,7 +71,7 @@ export function ReportSettings() {
|
||||
return (
|
||||
<div>
|
||||
<h3 className="mb-2 font-medium">Settings</h3>
|
||||
<div className="col rounded-lg border bg-def-100 p-4 gap-2">
|
||||
<div className="col rounded-lg border bg-card p-4 gap-4">
|
||||
{fields.includes('previous') && (
|
||||
<Label className="flex items-center justify-between mb-0">
|
||||
<span className="whitespace-nowrap">
|
||||
@@ -64,7 +85,9 @@ export function ReportSettings() {
|
||||
)}
|
||||
{fields.includes('criteria') && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="whitespace-nowrap font-medium">Criteria</span>
|
||||
<Label className="whitespace-nowrap font-medium mb-0">
|
||||
Criteria
|
||||
</Label>
|
||||
<Combobox
|
||||
align="end"
|
||||
placeholder="Select criteria"
|
||||
@@ -85,7 +108,7 @@ export function ReportSettings() {
|
||||
)}
|
||||
{fields.includes('unit') && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="whitespace-nowrap font-medium">Unit</span>
|
||||
<Label className="whitespace-nowrap font-medium mb-0">Unit</Label>
|
||||
<Combobox
|
||||
align="end"
|
||||
placeholder="Unit"
|
||||
@@ -108,7 +131,9 @@ export function ReportSettings() {
|
||||
)}
|
||||
{fields.includes('funnelGroup') && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="whitespace-nowrap font-medium">Funnel Group</span>
|
||||
<Label className="whitespace-nowrap font-medium mb-0">
|
||||
Funnel Group
|
||||
</Label>
|
||||
<Combobox
|
||||
align="end"
|
||||
placeholder="Default: Session"
|
||||
@@ -133,7 +158,9 @@ export function ReportSettings() {
|
||||
)}
|
||||
{fields.includes('funnelWindow') && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="whitespace-nowrap font-medium">Funnel Window</span>
|
||||
<Label className="whitespace-nowrap font-medium mb-0">
|
||||
Funnel Window
|
||||
</Label>
|
||||
<InputEnter
|
||||
type="number"
|
||||
value={funnelWindow ? String(funnelWindow) : ''}
|
||||
@@ -149,6 +176,89 @@ export function ReportSettings() {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{fields.includes('sankeyMode') && options?.type === 'sankey' && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label className="whitespace-nowrap font-medium mb-0">Mode</Label>
|
||||
<Combobox
|
||||
align="end"
|
||||
placeholder="Select mode"
|
||||
value={options?.mode || 'after'}
|
||||
onChange={(val) => {
|
||||
dispatch(
|
||||
changeSankeyMode(val as 'between' | 'after' | 'before'),
|
||||
);
|
||||
}}
|
||||
items={[
|
||||
{
|
||||
label: 'After',
|
||||
value: 'after',
|
||||
},
|
||||
{
|
||||
label: 'Before',
|
||||
value: 'before',
|
||||
},
|
||||
{
|
||||
label: 'Between',
|
||||
value: 'between',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{fields.includes('sankeySteps') && options?.type === 'sankey' && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label className="whitespace-nowrap font-medium mb-0">Steps</Label>
|
||||
<InputEnter
|
||||
type="number"
|
||||
value={options?.steps ? String(options.steps) : '5'}
|
||||
placeholder="Default: 5"
|
||||
onChangeValue={(value) => {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (Number.isNaN(parsed) || parsed < 2 || parsed > 10) {
|
||||
dispatch(changeSankeySteps(5));
|
||||
} else {
|
||||
dispatch(changeSankeySteps(parsed));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{fields.includes('sankeyExclude') && options?.type === 'sankey' && (
|
||||
<div className="flex flex-col">
|
||||
<Label className="whitespace-nowrap font-medium">
|
||||
Exclude Events
|
||||
</Label>
|
||||
<ComboboxEvents
|
||||
multiple
|
||||
searchable
|
||||
value={options?.exclude || []}
|
||||
onChange={(value) => {
|
||||
dispatch(changeSankeyExclude(value));
|
||||
}}
|
||||
items={eventNames.filter((item) => item.name !== '*')}
|
||||
placeholder="Select events to exclude"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{fields.includes('sankeyInclude') && options?.type === 'sankey' && (
|
||||
<div className="flex flex-col">
|
||||
<Label className="whitespace-nowrap font-medium">
|
||||
Include events
|
||||
</Label>
|
||||
<ComboboxEvents
|
||||
multiple
|
||||
searchable
|
||||
value={options?.include || []}
|
||||
onChange={(value) => {
|
||||
dispatch(
|
||||
changeSankeyInclude(value.length > 0 ? value : undefined),
|
||||
);
|
||||
}}
|
||||
items={eventNames.filter((item) => item.name !== '*')}
|
||||
placeholder="Leave empty to include all"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,14 +5,24 @@ import { useSelector } from '@/redux';
|
||||
import { ReportBreakdowns } from './ReportBreakdowns';
|
||||
import { ReportSeries } from './ReportSeries';
|
||||
import { ReportSettings } from './ReportSettings';
|
||||
import { ReportFixedEvents } from './report-fixed-events';
|
||||
|
||||
export function ReportSidebar() {
|
||||
const { chartType } = useSelector((state) => state.report);
|
||||
const showBreakdown = chartType !== 'retention';
|
||||
const { chartType, options } = useSelector((state) => state.report);
|
||||
const showBreakdown = chartType !== 'retention' && chartType !== 'sankey';
|
||||
const showFixedEvents = chartType === 'sankey';
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-8">
|
||||
<ReportSeries />
|
||||
{showFixedEvents ? (
|
||||
<ReportFixedEvents
|
||||
numberOfEvents={
|
||||
options?.type === 'sankey' && options.mode === 'between' ? 2 : 1
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ReportSeries />
|
||||
)}
|
||||
{showBreakdown && <ReportBreakdowns />}
|
||||
<ReportSettings />
|
||||
</div>
|
||||
|
||||
223
apps/start/src/components/report/sidebar/report-fixed-events.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
import { ColorSquare } from '@/components/color-square';
|
||||
import { ComboboxEvents } from '@/components/ui/combobox-events';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { InputEnter } from '@/components/ui/input-enter';
|
||||
import { useAppParams } from '@/hooks/use-app-params';
|
||||
import { useDebounceFn } from '@/hooks/use-debounce-fn';
|
||||
import { useEventNames } from '@/hooks/use-event-names';
|
||||
import { useDispatch, useSelector } from '@/redux';
|
||||
import { alphabetIds } from '@openpanel/constants';
|
||||
import type {
|
||||
IChartEvent,
|
||||
IChartEventItem,
|
||||
IChartFormula,
|
||||
} from '@openpanel/validation';
|
||||
import {
|
||||
addSerie,
|
||||
changeEvent,
|
||||
duplicateEvent,
|
||||
removeEvent,
|
||||
} from '../reportSlice';
|
||||
import type { ReportEventMoreProps } from './ReportEventMore';
|
||||
import { ReportEventMore } from './ReportEventMore';
|
||||
import { ReportSeriesItem } from './ReportSeriesItem';
|
||||
|
||||
export function ReportFixedEvents({
|
||||
numberOfEvents,
|
||||
}: {
|
||||
numberOfEvents: number;
|
||||
}) {
|
||||
const selectedSeries = useSelector((state) => state.report.series);
|
||||
const chartType = useSelector((state) => state.report.chartType);
|
||||
const dispatch = useDispatch();
|
||||
const { projectId } = useAppParams();
|
||||
const eventNames = useEventNames({
|
||||
projectId,
|
||||
});
|
||||
|
||||
const showSegment = !['retention', 'funnel', 'sankey'].includes(chartType);
|
||||
const showAddFilter = !['retention'].includes(chartType);
|
||||
const showDisplayNameInput = !['retention', 'sankey'].includes(chartType);
|
||||
const dispatchChangeEvent = useDebounceFn((event: IChartEventItem) => {
|
||||
dispatch(changeEvent(event));
|
||||
});
|
||||
const isSelectManyEvents = chartType === 'retention';
|
||||
|
||||
const handleMore = (event: IChartEventItem | IChartEvent) => {
|
||||
const callback: ReportEventMoreProps['onClick'] = (action) => {
|
||||
switch (action) {
|
||||
case 'remove': {
|
||||
return dispatch(
|
||||
removeEvent({
|
||||
id: 'type' in event ? event.id : (event as IChartEvent).id,
|
||||
}),
|
||||
);
|
||||
}
|
||||
case 'duplicate': {
|
||||
const normalized =
|
||||
'type' in event ? event : { ...event, type: 'event' as const };
|
||||
return dispatch(duplicateEvent(normalized));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return callback;
|
||||
};
|
||||
|
||||
const dispatchChangeFormula = useDebounceFn((formula: IChartFormula) => {
|
||||
dispatch(changeEvent(formula));
|
||||
});
|
||||
|
||||
const showFormula =
|
||||
chartType !== 'conversion' &&
|
||||
chartType !== 'funnel' &&
|
||||
chartType !== 'retention' &&
|
||||
chartType !== 'sankey';
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3 className="mb-2 font-medium">Metrics</h3>
|
||||
<div className="flex flex-col gap-4">
|
||||
{Array.from({ length: numberOfEvents }, (_, index) => ({
|
||||
slotId: `fixed-event-slot-${index}`,
|
||||
index,
|
||||
})).map(({ slotId, index }) => {
|
||||
const event = selectedSeries[index];
|
||||
|
||||
// If no event exists at this index, render an empty slot
|
||||
if (!event) {
|
||||
return (
|
||||
<div key={slotId} className="rounded-lg border bg-def-100">
|
||||
<div className="flex items-center gap-2 p-2">
|
||||
<ColorSquare>
|
||||
<span className="block">{alphabetIds[index]}</span>
|
||||
</ColorSquare>
|
||||
<ComboboxEvents
|
||||
className="flex-1"
|
||||
searchable
|
||||
multiple={isSelectManyEvents as false}
|
||||
value={''}
|
||||
onChange={(value) => {
|
||||
if (isSelectManyEvents) {
|
||||
dispatch(
|
||||
addSerie({
|
||||
type: 'event',
|
||||
segment: 'user',
|
||||
name: value,
|
||||
filters: [
|
||||
{
|
||||
name: 'name',
|
||||
operator: 'is',
|
||||
value: [value],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
dispatch(
|
||||
addSerie({
|
||||
type: 'event',
|
||||
name: value,
|
||||
segment: 'event',
|
||||
filters: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}}
|
||||
items={eventNames}
|
||||
placeholder="Select event"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isFormula = event.type === 'formula';
|
||||
if (isFormula) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ReportSeriesItem
|
||||
key={event.id}
|
||||
event={event}
|
||||
index={index}
|
||||
showSegment={showSegment}
|
||||
showAddFilter={showAddFilter}
|
||||
isSelectManyEvents={isSelectManyEvents}
|
||||
className="rounded-lg border bg-def-100"
|
||||
>
|
||||
<ComboboxEvents
|
||||
className="flex-1"
|
||||
searchable
|
||||
multiple={isSelectManyEvents as false}
|
||||
value={
|
||||
(isSelectManyEvents
|
||||
? ((
|
||||
event as IChartEventItem & {
|
||||
type: 'event';
|
||||
}
|
||||
).filters[0]?.value ?? [])
|
||||
: (
|
||||
event as IChartEventItem & {
|
||||
type: 'event';
|
||||
}
|
||||
).name) as any
|
||||
}
|
||||
onChange={(value) => {
|
||||
dispatch(
|
||||
changeEvent(
|
||||
Array.isArray(value)
|
||||
? {
|
||||
id: event.id,
|
||||
type: 'event',
|
||||
segment: 'user',
|
||||
filters: [
|
||||
{
|
||||
name: 'name',
|
||||
operator: 'is',
|
||||
value: value,
|
||||
},
|
||||
],
|
||||
name: '*',
|
||||
}
|
||||
: {
|
||||
...event,
|
||||
type: 'event',
|
||||
name: value,
|
||||
filters: [],
|
||||
},
|
||||
),
|
||||
);
|
||||
}}
|
||||
items={eventNames}
|
||||
placeholder="Select event"
|
||||
/>
|
||||
{showDisplayNameInput && (
|
||||
<Input
|
||||
placeholder={
|
||||
(event as IChartEventItem & { type: 'event' }).name
|
||||
? `${(event as IChartEventItem & { type: 'event' }).name} (${alphabetIds[index]})`
|
||||
: 'Display name'
|
||||
}
|
||||
defaultValue={
|
||||
(event as IChartEventItem & { type: 'event' }).displayName
|
||||
}
|
||||
onChange={(e) => {
|
||||
dispatchChangeEvent({
|
||||
...(event as IChartEventItem & {
|
||||
type: 'event';
|
||||
}),
|
||||
displayName: e.target.value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<ReportEventMore onClick={handleMore(event)} />
|
||||
</ReportSeriesItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -178,7 +178,7 @@ export function ComboboxEvents<
|
||||
|
||||
<CommandEmpty>Nothing selected</CommandEmpty>
|
||||
<VirtualList
|
||||
height={400}
|
||||
height={300}
|
||||
data={items.filter((item) => {
|
||||
if (search === '') return true;
|
||||
return item.name.toLowerCase().includes(search.toLowerCase());
|
||||
|
||||
@@ -4,7 +4,7 @@ import { cva } from 'class-variance-authority';
|
||||
import * as React from 'react';
|
||||
|
||||
const inputVariant = cva(
|
||||
'file: flex w-full rounded-md border border-input bg-card ring-offset-background file:border-0 file:bg-transparent file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'flex w-full rounded-md border border-input bg-card ring-offset-background file:border-0 file:bg-transparent file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { VariantProps } from 'class-variance-authority';
|
||||
import * as React from 'react';
|
||||
|
||||
const labelVariants = cva(
|
||||
'mb-3 text-sm block font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
|
||||
'mb-3 text-sm block font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-foreground/70',
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
|
||||
@@ -185,7 +185,6 @@ export function WidgetTable<T>({
|
||||
columns.length > 1 && column !== columns[0]
|
||||
? 'text-right'
|
||||
: 'text-left',
|
||||
column.className,
|
||||
responsiveClass,
|
||||
)}
|
||||
style={{ width: column.width }}
|
||||
|
||||
@@ -10,20 +10,27 @@ const VALID_COOKIES = [
|
||||
'chartType',
|
||||
'range',
|
||||
'supporter-prompt-closed',
|
||||
'feedback-prompt-seen',
|
||||
] as const;
|
||||
const COOKIE_EVENT_NAME = '__cookie-change';
|
||||
|
||||
const setCookieFn = createServerFn({ method: 'POST' })
|
||||
.inputValidator(z.object({ key: z.enum(VALID_COOKIES), value: z.string() }))
|
||||
.handler(({ data: { key, value } }) => {
|
||||
.inputValidator(
|
||||
z.object({
|
||||
key: z.enum(VALID_COOKIES),
|
||||
value: z.string(),
|
||||
maxAge: z.number().optional(),
|
||||
}),
|
||||
)
|
||||
.handler(({ data: { key, value, maxAge } }) => {
|
||||
if (!VALID_COOKIES.includes(key)) {
|
||||
return;
|
||||
}
|
||||
const maxAge = 60 * 60 * 24 * 365 * 10;
|
||||
const cookieMaxAge = maxAge ?? 60 * 60 * 24 * 365 * 10;
|
||||
setCookie(key, value, {
|
||||
maxAge,
|
||||
maxAge: cookieMaxAge,
|
||||
path: '/',
|
||||
expires: new Date(Date.now() + maxAge),
|
||||
expires: new Date(Date.now() + cookieMaxAge),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,6 +43,7 @@ export const getCookiesFn = createServerFn({ method: 'GET' }).handler(() =>
|
||||
export function useCookieStore<T>(
|
||||
key: (typeof VALID_COOKIES)[number],
|
||||
defaultValue: T,
|
||||
options?: { maxAge?: number },
|
||||
) {
|
||||
const { cookies } = useRouteContext({ strict: false });
|
||||
const [value, setValue] = useState<T>((cookies?.[key] ?? defaultValue) as T);
|
||||
@@ -68,7 +76,9 @@ export function useCookieStore<T>(
|
||||
value,
|
||||
(newValue: T) => {
|
||||
setValue(newValue);
|
||||
setCookieFn({ data: { key, value: String(newValue) } });
|
||||
setCookieFn({
|
||||
data: { key, value: String(newValue), maxAge: options?.maxAge },
|
||||
});
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COOKIE_EVENT_NAME, {
|
||||
detail: { key, value: newValue, from: ref.current },
|
||||
@@ -76,6 +86,6 @@ export function useCookieStore<T>(
|
||||
);
|
||||
},
|
||||
] as const,
|
||||
[value, key],
|
||||
[value, key, options?.maxAge],
|
||||
);
|
||||
}
|
||||
|
||||