Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M11-007): Codemod apps/start (+ db, common, sdks/express leftovers) from the checked-in map; common utils and super-json into apps/start/src/utils

ralph6a31bd45fdd1
diff --git a/apps/start/package.json b/apps/start/package.json
index 731b34b6c..f4a9b7765 100644
--- a/apps/start/package.json
+++ b/apps/start/package.json
@@ -31,13 +31,9 @@
"@hookform/resolvers": "^5.2.2",
"@nivo/sankey": "^0.99.0",
"@number-flow/react": "0.5.10",
- "@openpanel/common": "workspace:^",
- "@openpanel/constants": "workspace:^",
"@openpanel/core": "workspace:^",
- "@openpanel/json": "workspace:*",
"@openpanel/payments": "workspace:*",
"@openpanel/sdk-info": "workspace:^",
- "@openpanel/validation": "workspace:^",
"@openpanel/web": "^1.0.1",
"@radix-ui/react-accordion": "^1.2.12",
"@radix-ui/react-alert-dialog": "^1.1.15",
@@ -116,8 +112,10 @@
"lodash.throttle": "^4.1.1",
"lottie-react": "^2.4.0",
"lucide-react": "^0.476.0",
+ "mathjs": "^12.3.2",
"mitt": "^3.0.1",
"motion": "^12.40.0",
+ "nanoid": "^5.1.6",
"nuqs": "^2.5.2",
"prisma-error-enum": "^0.1.3",
"pushmodal": "^1.0.3",
diff --git a/apps/start/src/agents/client.ts b/apps/start/src/agents/client.ts
index 0cd836d4a..c3fe935d4 100644
--- a/apps/start/src/agents/client.ts
+++ b/apps/start/src/agents/client.ts
@@ -10,15 +10,15 @@ import type { ChatApp } from '@openpanel/core';
* About the import: `ChatApp = typeof chatApp` is the full Better
* Agent-inferred application type, which inherently binds to the
* server-side agent definition (models, tools, context). It can't be
- * moved into `@openpanel/validation` without dragging the entire agent
- * definition (DB services, providers, etc.) along with it. It is
+ * moved into `@openpanel/core`'s assistant.constants without dragging the
+ * entire agent definition (DB services, providers, etc.) along with it. It is
* type-only, erased at build time — no runtime coupling, which is what
* keeps it inside ADR-008's rule that only `*.constants.ts` may be
* VALUE-imported here. It used to reach `apps/api/src/agents/app`
* relatively; M9-004 deleted that wrapper and core's barrel exports the
* type. The shared schemas (context, client tool inputs, model
- * whitelist) live in `@openpanel/validation` so only this one type
- * import crosses the app boundary.
+ * whitelist) live in `@openpanel/core`'s assistant.constants so only this
+ * one type import crosses the app boundary.
*/
export type AppClient = ReturnType<typeof createClient<ChatApp>>;
diff --git a/apps/start/src/agents/models.ts b/apps/start/src/agents/models.ts
index 0397422ab..14ce69e19 100644
--- a/apps/start/src/agents/models.ts
+++ b/apps/start/src/agents/models.ts
@@ -1,12 +1,14 @@
-// Re-export the shared model whitelist helpers from `@openpanel/validation`.
+// Re-export the shared model whitelist helpers from
+// `@openpanel/core`'s assistant.constants.
// Server + client consume the same source, so drift is a compile error
// rather than a silent "agent not found at runtime".
//
// The *available* model list is fetched at runtime via `trpc.chat.models` —
// it filters by which provider API keys the API process has configured.
+
+export type { ChatModelEntry as ChatModelOption } from '@openpanel/core/modules/assistant/assistant.constants';
export {
- MODEL_STORAGE_KEY,
getModelLabel,
isValidModelId,
-} from '@openpanel/validation';
-export type { ChatModelEntry as ChatModelOption } from '@openpanel/validation';
+ MODEL_STORAGE_KEY,
+} from '@openpanel/core/modules/assistant/assistant.constants';
diff --git a/apps/start/src/components/auth/reset-password-form.tsx b/apps/start/src/components/auth/reset-password-form.tsx
index a4d6dd4ca..ff449b3cd 100644
--- a/apps/start/src/components/auth/reset-password-form.tsx
+++ b/apps/start/src/components/auth/reset-password-form.tsx
@@ -1,6 +1,5 @@
-import { useTRPC } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
-import { zResetPassword } from '@openpanel/validation';
+import { zResetPassword } from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import { useForm } from 'react-hook-form';
@@ -8,6 +7,7 @@ import { toast } from 'sonner';
import type { z } from 'zod';
import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
+import { useTRPC } from '@/integrations/trpc/react';
const validator = zResetPassword;
type IForm = z.infer<typeof validator>;
@@ -26,7 +26,7 @@ export function ResetPasswordForm({ token }: { token: string }) {
onError(error) {
toast.error(error.message);
},
- }),
+ })
);
const form = useForm<IForm>({
@@ -44,17 +44,17 @@ export function ResetPasswordForm({ token }: { token: string }) {
return (
<div className="col gap-8">
<div>
- <h1 className="text-3xl font-bold text-foreground mb-2">
+ <h1 className="mb-2 font-bold text-3xl text-foreground">
Reset your password
</h1>
<p className="text-muted-foreground">
Already have an account?{' '}
- <a href="/login" className="underline">
+ <a className="underline" href="/login">
Sign in
</a>
</p>
</div>
- <form onSubmit={onSubmit} className="col gap-6">
+ <form className="col gap-6" onSubmit={onSubmit}>
<InputWithLabel
label="New password"
placeholder="New password"
diff --git a/apps/start/src/components/auth/share-enter-password.tsx b/apps/start/src/components/auth/share-enter-password.tsx
index 9f1e7ce7a..a5f1012a8 100644
--- a/apps/start/src/components/auth/share-enter-password.tsx
+++ b/apps/start/src/components/auth/share-enter-password.tsx
@@ -1,12 +1,15 @@
-import { useTRPC } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
-import { type ISignInShare, zSignInShare } from '@openpanel/validation';
+import {
+ type ISignInShare,
+ zSignInShare,
+} from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { PublicPageCard } from '../public-page-card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
+import { useTRPC } from '@/integrations/trpc/react';
export function ShareEnterPassword({
shareId,
@@ -24,7 +27,7 @@ export function ShareEnterPassword({
onError() {
toast.error('Incorrect password');
},
- }),
+ })
);
const form = useForm<ISignInShare>({
resolver: zodResolver(zSignInShare),
@@ -52,15 +55,15 @@ export function ShareEnterPassword({
return (
<PublicPageCard
- title={`${typeLabel} is locked`}
description={`Please enter correct password to access this ${typeLabel.toLowerCase()}`}
+ title={`${typeLabel} is locked`}
>
- <form onSubmit={onSubmit} className="col gap-4">
+ <form className="col gap-4" onSubmit={onSubmit}>
<Input
{...form.register('password')}
- type="password"
placeholder="Enter your password"
size="large"
+ type="password"
/>
<Button type="submit">Get access</Button>
</form>
diff --git a/apps/start/src/components/auth/sign-in-email-form.tsx b/apps/start/src/components/auth/sign-in-email-form.tsx
index aec9a789a..8bc08b767 100644
--- a/apps/start/src/components/auth/sign-in-email-form.tsx
+++ b/apps/start/src/components/auth/sign-in-email-form.tsx
@@ -1,14 +1,13 @@
-import { useTRPC } from '@/integrations/trpc/react';
-import { pushModal } from '@/modals';
import { zodResolver } from '@hookform/resolvers/zod';
-import { zSignInEmail } from '@openpanel/validation';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
-import { useNavigate, useRouter } from '@tanstack/react-router';
+import { zSignInEmail } from '@openpanel/core/modules/auth/auth.constants';
+import { useMutation } from '@tanstack/react-query';
import { type SubmitHandler, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
+import { useTRPC } from '@/integrations/trpc/react';
+import { pushModal } from '@/modals';
const validator = zSignInEmail;
type IForm = z.infer<typeof validator>;
@@ -16,7 +15,10 @@ type IForm = z.infer<typeof validator>;
export function SignInEmailForm({
isLastUsed,
inviteId,
-}: { isLastUsed?: boolean; inviteId?: string }) {
+}: {
+ isLastUsed?: boolean;
+ inviteId?: string;
+}) {
const trpc = useTRPC();
const mutation = useMutation(
trpc.auth.signInEmail.mutationOptions({
@@ -31,7 +33,7 @@ export function SignInEmailForm({
onError(error) {
toast.error(error.message);
},
- }),
+ })
);
const form = useForm<IForm>({
resolver: zodResolver(validator),
@@ -48,38 +50,38 @@ export function SignInEmailForm({
};
return (
- <form onSubmit={form.handleSubmit(onSubmit)} className="col gap-4">
+ <form className="col gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<InputWithLabel
{...form.register('email')}
+ className="border-def-300 bg-def-100/50 focus:border-highlight focus:ring-highlight/20"
error={form.formState.errors.email?.message}
label="Email"
- className="bg-def-100/50 border-def-300 focus:border-highlight focus:ring-highlight/20"
/>
<InputWithLabel
{...form.register('password')}
+ className="border-def-300 bg-def-100/50 focus:border-highlight focus:ring-highlight/20"
error={form.formState.errors.password?.message}
label="Password"
type="password"
- className="bg-def-100/50 border-def-300 focus:border-highlight focus:ring-highlight/20"
/>
<div className="relative">
- <Button type="submit" size="lg" className="w-full">
+ <Button className="w-full" size="lg" type="submit">
Sign in
</Button>
{isLastUsed && (
- <span className="absolute -top-2 right-3 text-[10px] font-medium bg-highlight text-white px-1.5 py-0.5 rounded-full leading-none">
+ <span className="absolute -top-2 right-3 rounded-full bg-highlight px-1.5 py-0.5 font-medium text-[10px] text-white leading-none">
Used last time
</span>
)}
</div>
<button
- type="button"
+ className="mt-2 text-center text-muted-foreground text-sm transition-colors duration-200 hover:text-highlight hover:underline"
onClick={() =>
pushModal('RequestPasswordReset', {
email: form.getValues('email'),
})
}
- className="text-sm text-muted-foreground hover:text-highlight hover:underline transition-colors duration-200 text-center mt-2"
+ type="button"
>
Forgot password?
</button>
diff --git a/apps/start/src/components/auth/sign-up-email-form.tsx b/apps/start/src/components/auth/sign-up-email-form.tsx
index f85df49ff..b47aaa634 100644
--- a/apps/start/src/components/auth/sign-up-email-form.tsx
+++ b/apps/start/src/components/auth/sign-up-email-form.tsx
@@ -1,21 +1,21 @@
-import { useTRPC } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
-import { zSignUpEmail } from '@openpanel/validation';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
-
-import { useRouter } from '@tanstack/react-router';
+import { zSignUpEmail } from '@openpanel/core/modules/auth/auth.constants';
+import { useMutation } from '@tanstack/react-query';
import { type SubmitHandler, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
+import { useTRPC } from '@/integrations/trpc/react';
const validator = zSignUpEmail;
type IForm = z.infer<typeof validator>;
export function SignUpEmailForm({
inviteId,
-}: { inviteId: string | undefined }) {
+}: {
+ inviteId: string | undefined;
+}) {
const trpc = useTRPC();
const mutation = useMutation(
trpc.auth.signUpEmail.mutationOptions({
@@ -26,7 +26,7 @@ export function SignUpEmailForm({
onError(error) {
toast.error(error.message);
},
- }),
+ })
);
const form = useForm<IForm>({
resolver: zodResolver(validator),
@@ -39,46 +39,46 @@ export function SignUpEmailForm({
};
return (
<form className="col gap-4" onSubmit={form.handleSubmit(onSubmit)}>
- <div className="row gap-4 w-full flex-1">
+ <div className="row w-full flex-1 gap-4">
<InputWithLabel
- label="First name"
className="flex-1"
+ label="First name"
type="text"
{...form.register('firstName')}
error={form.formState.errors.firstName?.message}
/>
<InputWithLabel
- label="Last name"
className="flex-1"
+ label="Last name"
type="text"
{...form.register('lastName')}
error={form.formState.errors.lastName?.message}
/>
</div>
<InputWithLabel
- label="Email"
className="w-full"
+ label="Email"
type="email"
{...form.register('email')}
error={form.formState.errors.email?.message}
/>
- <div className="row gap-4 w-full">
+ <div className="row w-full gap-4">
<InputWithLabel
- label="Password"
className="flex-1"
+ label="Password"
type="password"
{...form.register('password')}
error={form.formState.errors.password?.message}
/>
<InputWithLabel
- label="Confirm password"
className="flex-1"
+ label="Confirm password"
type="password"
{...form.register('confirmPassword')}
error={form.formState.errors.confirmPassword?.message}
/>
</div>
- <Button type="submit" className="w-full" size="lg">
+ <Button className="w-full" size="lg" type="submit">
Create account
</Button>
</form>
diff --git a/apps/start/src/components/charts/op-dashed-tail.ts b/apps/start/src/components/charts/op-dashed-tail.ts
index f04629974..76463d9fe 100644
--- a/apps/start/src/components/charts/op-dashed-tail.ts
+++ b/apps/start/src/components/charts/op-dashed-tail.ts
@@ -1,4 +1,4 @@
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
interface UseDashedTailOptions<T extends { date: string | Date }> {
data: T[];
@@ -27,15 +27,21 @@ export function useDashedTail<T extends { date: string | Date }>({
range,
interval: _interval,
}: UseDashedTailOptions<T>): number | undefined {
- if (data.length < 2) return undefined;
+ if (data.length < 2) {
+ return undefined;
+ }
const now = Date.now();
let currentIdx = -1;
for (let i = 0; i < data.length; i++) {
const item = data[i];
- if (!item) continue;
+ if (!item) {
+ continue;
+ }
const t =
- item.date instanceof Date ? item.date.getTime() : new Date(item.date).getTime();
+ item.date instanceof Date
+ ? item.date.getTime()
+ : new Date(item.date).getTime();
if (t <= now) {
currentIdx = i;
} else {
@@ -65,15 +71,21 @@ export function useDashedTail<T extends { date: string | Date }>({
function isLastBucketInProgress<T extends { date: string | Date }>(
data: T[],
- now: number,
+ now: number
): boolean {
const last = data[data.length - 1];
const prev = data[data.length - 2];
- if (!(last && prev)) return false;
+ if (!(last && prev)) {
+ return false;
+ }
const lastT =
- last.date instanceof Date ? last.date.getTime() : new Date(last.date).getTime();
+ last.date instanceof Date
+ ? last.date.getTime()
+ : new Date(last.date).getTime();
const prevT =
- prev.date instanceof Date ? prev.date.getTime() : new Date(prev.date).getTime();
+ prev.date instanceof Date
+ ? prev.date.getTime()
+ : new Date(prev.date).getTime();
// Bucket width = gap between consecutive points. If "now" lies within the
// last bucket's window, it's in progress.
const bucketMs = lastT - prevT;
diff --git a/apps/start/src/components/charts/op-date-pill.tsx b/apps/start/src/components/charts/op-date-pill.tsx
index 3622cd838..205e6e234 100644
--- a/apps/start/src/components/charts/op-date-pill.tsx
+++ b/apps/start/src/components/charts/op-date-pill.tsx
@@ -1,8 +1,8 @@
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
+import { differenceInHours, getISOWeek } from 'date-fns';
import { motion, useSpring } from 'motion/react';
import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
-import { differenceInHours, getISOWeek } from 'date-fns';
-import type { IInterval } from '@openpanel/validation';
import {
type TooltipData,
useChartHover,
@@ -37,7 +37,7 @@ export function OPDatePill({ interval }: OPDatePillProps) {
setMounted(true);
}, []);
- if (!mounted || !containerRef.current || !tooltipData) {
+ if (!(mounted && containerRef.current && tooltipData)) {
return null;
}
@@ -73,18 +73,20 @@ function OPDatePillInner({
xAccessor(tooltipData.point),
interval ?? 'day',
data,
- xAccessor,
+ xAccessor
),
- [tooltipData, data, xAccessor, interval],
+ [tooltipData, data, xAccessor, interval]
);
// Stable across hovers — depends only on chart dimensions.
const maxWidth = useMemo(
() => Math.max(120, width - margin.left - margin.right),
- [width, margin.left, margin.right],
+ [width, margin.left, margin.right]
);
- if (!label) return null;
+ if (!label) {
+ return null;
+ }
return createPortal(
<motion.div
@@ -96,11 +98,11 @@ function OPDatePillInner({
maxWidth,
}}
>
- <div className="rounded-full bg-foreground px-2.5 py-1 text-[11px] font-medium tracking-tight text-background shadow-md whitespace-nowrap">
+ <div className="whitespace-nowrap rounded-full bg-foreground px-2.5 py-1 font-medium text-[11px] text-background tracking-tight shadow-md">
{label}
</div>
</motion.div>,
- container,
+ container
);
}
@@ -128,7 +130,7 @@ function formatPillDate(
date: Date,
interval: IInterval,
data: Record<string, unknown>[],
- xAccessor: (d: Record<string, unknown>) => Date,
+ xAccessor: (d: Record<string, unknown>) => Date
): string {
const first = data[0] ? xAccessor(data[0]) : date;
const last = data[data.length - 1] ? xAccessor(data[data.length - 1]!) : date;
@@ -139,13 +141,19 @@ function formatPillDate(
switch (interval) {
case 'minute':
- if (spanHours <= 1) return time;
- if (spanHours <= 24) return time;
+ if (spanHours <= 1) {
+ return time;
+ }
+ if (spanHours <= 24) {
+ return time;
+ }
return `${dayMonth} ${time}`;
case 'hour':
// ≤ ~25h span → single day, show only the hour
- if (spanHours <= 25) return `${pad(date.getHours())}:00`;
+ if (spanHours <= 25) {
+ return `${pad(date.getHours())}:00`;
+ }
// Otherwise include the date
return `${dayMonth} ${pad(date.getHours())}:00`;
diff --git a/apps/start/src/components/charts/op-tooltip.tsx b/apps/start/src/components/charts/op-tooltip.tsx
index dd74dab7b..b33a52b8d 100644
--- a/apps/start/src/components/charts/op-tooltip.tsx
+++ b/apps/start/src/components/charts/op-tooltip.tsx
@@ -1,13 +1,13 @@
-import { getPreviousMetric } from '@openpanel/common';
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import { type ReactNode, useMemo } from 'react';
-import { SerieIcon } from '@/components/report-chart/common/serie-icon';
+import { getPreviousMetric } from '../../utils/math';
import { PreviousDiffIndicatorPure } from '../report-chart/common/previous-diff-indicator';
import { useChart } from './chart-context';
import type { ChartMarker } from './markers/marker-group';
-import type { OPReferrerSpikeItem } from './op-referrer-spikes';
import { type OPReferenceItem, toChartMarkers } from './op-references';
+import type { OPReferrerSpikeItem } from './op-referrer-spikes';
import { ChartTooltip, type ChartTooltipProps } from './tooltip/chart-tooltip';
+import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';
import { cn } from '@/utils/cn';
@@ -200,20 +200,20 @@ function useReferencesForHoveredPoint(
}
function useSpikeForHoveredPoint(
- spikes: OPReferrerSpikeItem[] | null,
+ spikes: OPReferrerSpikeItem[] | null
): OPReferrerSpikeItem | null {
const { tooltipData, data, xAccessor } = useChart();
const nearestIndices = useMemo(
() =>
computeNearestIndices(spikes ?? [], data, xAccessor, (s) =>
- typeof s.date === 'string' ? new Date(s.date) : s.date,
+ typeof s.date === 'string' ? new Date(s.date) : s.date
),
- [spikes, data, xAccessor],
+ [spikes, data, xAccessor]
);
return useMemo(() => {
- if (!tooltipData || !spikes || spikes.length === 0) {
+ if (!(tooltipData && spikes) || spikes.length === 0) {
return null;
}
const hoveredIndex = tooltipData.index;
@@ -235,7 +235,7 @@ function computeNearestIndices<T>(
items: T[],
data: Record<string, unknown>[],
xAccessor: (d: Record<string, unknown>) => Date,
- getDate: (item: T) => Date,
+ getDate: (item: T) => Date
): number[] {
if (items.length === 0 || data.length === 0) {
return [];
@@ -251,7 +251,9 @@ function computeNearestIndices<T>(
let minDiff = Number.POSITIVE_INFINITY;
for (let i = 0; i < dataTimes.length; i++) {
const t = dataTimes[i]!;
- if (Number.isNaN(t)) continue;
+ if (Number.isNaN(t)) {
+ continue;
+ }
const diff = Math.abs(t - target);
if (diff < minDiff) {
minDiff = diff;
@@ -273,16 +275,18 @@ function OPAnnotationsBlock({
}) {
const visibleRefs = references.slice(0, referencesLimit);
const hiddenRefs = Math.max(0, references.length - referencesLimit);
- if (visibleRefs.length === 0 && !spike) return null;
+ if (visibleRefs.length === 0 && !spike) {
+ return null;
+ }
return (
<div className="col mt-1 gap-2 border-border border-t pt-2">
{visibleRefs.map((marker) => (
<OPAnnotationRow
- key={marker.title}
+ description={marker.description}
icon={marker.icon}
+ key={marker.title}
title={marker.title}
- description={marker.description}
/>
))}
{hiddenRefs > 0 && (
@@ -318,9 +322,9 @@ function OPSpikeAnnotation({ spike }: { spike: OPReferrerSpikeItem }) {
return (
<OPAnnotationRow
+ description={description}
icon={<SerieIcon fill name={spike.referrer_name} />}
title={`Spike from ${spike.referrer_name}`}
- description={description}
/>
);
}
diff --git a/apps/start/src/components/chat/chat-context-widget.tsx b/apps/start/src/components/chat/chat-context-widget.tsx
index eb3be33b5..a703ff8b9 100644
--- a/apps/start/src/components/chat/chat-context-widget.tsx
+++ b/apps/start/src/components/chat/chat-context-widget.tsx
@@ -1,6 +1,4 @@
-import { usePageContextValue } from '@/contexts/page-context';
-import { cn } from '@/utils/cn';
-import { timeWindows } from '@openpanel/constants';
+import { timeWindows } from '@openpanel/core/modules/report/report.constants';
import {
Building2Icon,
GanttChartIcon,
@@ -14,6 +12,8 @@ import {
UsersIcon,
WallpaperIcon,
} from 'lucide-react';
+import { usePageContextValue } from '@/contexts/page-context';
+import { cn } from '@/utils/cn';
/**
* Small banner shown at the top of the chat body explaining what
@@ -24,7 +24,9 @@ import {
*/
export function ChatContextWidget() {
const ctx = usePageContextValue();
- if (!ctx) return null;
+ if (!ctx) {
+ return null;
+ }
const meta = PAGE_META[ctx.page];
const Icon = meta?.icon ?? WallpaperIcon;
@@ -53,32 +55,39 @@ export function ChatContextWidget() {
operator?: string;
value?: unknown[];
};
- if (!filter.name) continue;
- const op = filter.operator && filter.operator !== 'is'
- ? ` ${filter.operator}`
- : '';
- const value = Array.isArray(filter.value)
- ? filter.value.join(', ')
- : '';
+ if (!filter.name) {
+ continue;
+ }
+ const op =
+ filter.operator && filter.operator !== 'is'
+ ? ` ${filter.operator}`
+ : '';
+ const value = Array.isArray(filter.value) ? filter.value.join(', ') : '';
chips.push(`${filter.name}${op}${value ? `: ${value}` : ''}`);
}
}
// Entity ids on detail pages
- if (ctx.ids?.profileId) chips.push('Profile');
- if (ctx.ids?.sessionId) chips.push('Session');
- if (ctx.ids?.groupId) chips.push('Group');
- if (ctx.ids?.reportId) chips.push('Report');
+ if (ctx.ids?.profileId) {
+ chips.push('Profile');
+ }
+ if (ctx.ids?.sessionId) {
+ chips.push('Session');
+ }
+ if (ctx.ids?.groupId) {
+ chips.push('Group');
+ }
+ if (ctx.ids?.reportId) {
+ chips.push('Report');
+ }
return (
<div className="mx-3 mt-3 mb-1 rounded-lg border bg-card/95 px-3 py-2">
<div className="flex items-start gap-2">
- <Icon className="size-3.5 mt-0.5 text-muted-foreground shrink-0" />
- <div className="min-w-0 flex-1 col gap-1">
- <div className="text-sm text-muted-foreground">
- Assistant context
- </div>
- <div className="text-sm font-medium text-foreground/90">
+ <Icon className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <div className="col min-w-0 flex-1 gap-1">
+ <div className="text-muted-foreground text-sm">Assistant context</div>
+ <div className="font-medium text-foreground/90 text-sm">
{pageLabel}
</div>
{chips.length > 0 && (
@@ -99,7 +108,7 @@ function ContextChip({ children }: { children: React.ReactNode }) {
<span
className={cn(
'inline-flex items-center rounded-md border bg-muted/40 px-1.5 py-0.5',
- 'text-[11px] leading-none text-muted-foreground',
+ 'text-[11px] text-muted-foreground leading-none'
)}
>
{children}
@@ -107,10 +116,7 @@ function ContextChip({ children }: { children: React.ReactNode }) {
);
}
-const PAGE_META: Record<
- string,
- { label: string; icon: LucideIcon }
-> = {
+const PAGE_META: Record<string, { label: string; icon: LucideIcon }> = {
overview: { label: 'Overview', icon: WallpaperIcon },
insights: { label: 'Insights', icon: TrendingUpDownIcon },
pages: { label: 'Pages', icon: LayersIcon },
diff --git a/apps/start/src/components/chat/tool-handlers.ts b/apps/start/src/components/chat/tool-handlers.ts
index e5fc6aea6..8612f59d6 100644
--- a/apps/start/src/components/chat/tool-handlers.ts
+++ b/apps/start/src/components/chat/tool-handlers.ts
@@ -3,7 +3,7 @@ import type {
ChatClientToolHandlers,
SetEventNamesFilterInput,
SetPropertyFiltersInput,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/assistant/assistant.constants';
/**
* Client-side handlers for tools the LLM can invoke to mutate page
@@ -22,8 +22,8 @@ import type {
* After mutating the URL we dispatch a `popstate` event so nuqs picks
* up the change without a hook subscription on our side.
*
- * Handler types come from `@openpanel/validation` (shared with the
- * server's tool schemas) so the map stays in sync with the Zod inputs
+ * Handler types come from `@openpanel/core`'s assistant.constants (shared
+ * with the server's tool schemas) so the map stays in sync with the Zod inputs
* without crossing the app boundary for its type.
*/
diff --git a/apps/start/src/components/chat/tool-results/chat-report-result.tsx b/apps/start/src/components/chat/tool-results/chat-report-result.tsx
index 8d119f70e..726250a77 100644
--- a/apps/start/src/components/chat/tool-results/chat-report-result.tsx
+++ b/apps/start/src/components/chat/tool-results/chat-report-result.tsx
@@ -1,11 +1,14 @@
-import { ReportChart } from '@/components/report-chart';
-import { Button } from '@/components/ui/button';
-import { pushModal } from '@/modals';
-import type { IReport, IReportInput } from '@openpanel/validation';
+import type {
+ IReport,
+ IReportInput,
+} from '@openpanel/core/modules/report/report.constants';
import { SaveIcon } from 'lucide-react';
import { asReportOutput } from './output-types';
import { ResultCard, ToolStateGuard } from './shared';
import type { ToolResultProps } from './types';
+import { ReportChart } from '@/components/report-chart';
+import { Button } from '@/components/ui/button';
+import { pushModal } from '@/modals';
/**
* Renders the result of `get_report_data` / `generate_report` /
@@ -20,13 +23,13 @@ import type { ToolResultProps } from './types';
export function ChatReportResult({ part }: ToolResultProps) {
return (
<ToolStateGuard
- state={part.state}
errorText={part.errorText}
+ state={part.state}
toolName={part.type.replace(/^tool-/, '')}
>
<ChatReportInner
- output={part.output}
input={part.input}
+ output={part.output}
toolType={part.type}
/>
</ToolStateGuard>
@@ -46,7 +49,7 @@ function ChatReportInner({
if (!value || value.error) {
return (
<ResultCard>
- <div className="px-3 py-2 text-sm text-muted-foreground">
+ <div className="px-3 py-2 text-muted-foreground text-sm">
{value?.error ?? 'No data'}
</div>
</ResultCard>
@@ -54,10 +57,10 @@ function ChatReportInner({
}
const report = value.report;
- if (!report || !report.chartType) {
+ if (!(report && report.chartType)) {
return (
<ResultCard title={value.name ?? 'Report'}>
- <div className="px-3 py-2 text-sm text-muted-foreground">
+ <div className="px-3 py-2 text-muted-foreground text-sm">
Report data returned but no renderable config.
</div>
</ResultCard>
@@ -73,7 +76,6 @@ function ChatReportInner({
<ResultCard title={title}>
<div className="p-2">
<ReportChart
- report={report as unknown as IReportInput}
lazy={false}
options={{
hideLegend: false,
@@ -81,22 +83,21 @@ function ChatReportInner({
minHeight: 180,
maxHeight: 260,
}}
+ report={report as unknown as IReportInput}
/>
</div>
{value.dashboard_url && (
- <div className="border-t px-3 py-1.5 flex items-center justify-between gap-2">
+ <div className="flex items-center justify-between gap-2 border-t px-3 py-1.5">
<a
+ className="text-muted-foreground text-sm hover:underline"
href={value.dashboard_url}
- target="_blank"
rel="noopener noreferrer"
- className="text-sm text-muted-foreground hover:underline"
+ target="_blank"
>
Open in dashboard →
</a>
{!report.id && (
<Button
- size="sm"
- variant="ghost"
className="h-6 text-sm"
onClick={() =>
pushModal('SaveReport', {
@@ -104,8 +105,10 @@ function ChatReportInner({
disableRedirect: true,
})
}
+ size="sm"
+ variant="ghost"
>
- <SaveIcon className="size-3 mr-1" />
+ <SaveIcon className="mr-1 size-3" />
Save
</Button>
)}
@@ -122,7 +125,9 @@ function ChatReportInner({
* user actually asked for.
*/
function deriveTitleFromInput(toolType: string, input: unknown): string | null {
- if (!input || typeof input !== 'object') return null;
+ if (!input || typeof input !== 'object') {
+ return null;
+ }
const args = input as {
steps?: unknown;
series?: Array<{ name?: string; displayName?: string }>;
@@ -134,15 +139,26 @@ function deriveTitleFromInput(toolType: string, input: unknown): string | null {
switch (toolType) {
case 'tool-get_funnel': {
if (Array.isArray(args.steps) && args.steps.length > 0) {
- const names = args.steps.filter((s): s is string => typeof s === 'string');
- if (names.length > 0) return `Funnel: ${names.join(' → ')}`;
+ const names = args.steps.filter(
+ (s): s is string => typeof s === 'string'
+ );
+ if (names.length > 0) {
+ return `Funnel: ${names.join(' → ')}`;
+ }
}
return 'Funnel';
}
case 'tool-get_rolling_active_users': {
const w = args.windowDays ?? 1;
- const label = w === 1 ? 'DAU' : w === 7 ? 'WAU' : w === 30 ? 'MAU' : `${w}-day active users`;
+ const label =
+ w === 1
+ ? 'DAU'
+ : w === 7
+ ? 'WAU'
+ : w === 30
+ ? 'MAU'
+ : `${w}-day active users`;
const days = args.days ?? 30;
return `${label} — last ${days} days`;
}
@@ -156,8 +172,12 @@ function deriveTitleFromInput(toolType: string, input: unknown): string | null {
const kind = args.chartType
? humanizeChartType(args.chartType)
: 'Report';
- if (events.length === 0) return kind;
- if (events.length === 1) return `${kind}: ${events[0]}`;
+ if (events.length === 0) {
+ return kind;
+ }
+ if (events.length === 1) {
+ return `${kind}: ${events[0]}`;
+ }
return `${kind}: ${events.join(', ')}`;
}
diff --git a/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx b/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx
index 935a260b2..c8e03e544 100644
--- a/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx
+++ b/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx
@@ -1,4 +1,4 @@
-import { timeWindows } from '@openpanel/constants';
+import { timeWindows } from '@openpanel/core/modules/report/report.constants';
import { CheckIcon } from 'lucide-react';
import type { ReactNode } from 'react';
import type { ToolResultProps } from './types';
@@ -73,8 +73,8 @@ export function SetEventNamesFilterResult({ part }: ToolResultProps) {
function AppliedChip({ children }: { children: ReactNode }) {
return (
- <div className="inline-flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-foreground/80">
- <CheckIcon className="size-3.5 text-emerald-500 shrink-0" />
+ <div className="inline-flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-foreground/80 text-sm">
+ <CheckIcon className="size-3.5 shrink-0 text-emerald-500" />
<span className="truncate">{children}</span>
</div>
);
diff --git a/apps/start/src/components/cohort/cohort-criteria-builder.tsx b/apps/start/src/components/cohort/cohort-criteria-builder.tsx
index ed9c199fc..9dbba726f 100644
--- a/apps/start/src/components/cohort/cohort-criteria-builder.tsx
+++ b/apps/start/src/components/cohort/cohort-criteria-builder.tsx
@@ -1,20 +1,22 @@
-import { Button } from '@/components/ui/button';
-import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
-import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
-import { useAppParams } from '@/hooks/use-app-params';
-import { useEventNames } from '@/hooks/use-event-names';
import type {
CohortDefinition,
EventBasedCohortDefinition,
EventCriteria,
+ PropertyBasedCohortDefinition,
+} from '@openpanel/core/modules/cohort/cohort.constants';
+import type {
IChartEventFilter,
IChartEventFilterOperator,
IChartEventFilterValue,
- PropertyBasedCohortDefinition,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/report/report.constants';
import { PlusIcon, TrashIcon } from 'lucide-react';
import { PureFilterItem } from '../report/sidebar/filters/FilterItem';
import { PropertiesCombobox } from '../report/sidebar/PropertiesCombobox';
+import { Button } from '@/components/ui/button';
+import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useEventNames } from '@/hooks/use-event-names';
interface CohortCriteriaBuilderProps {
definition: CohortDefinition;
@@ -46,18 +48,18 @@ export function CohortCriteriaBuilder({
<div className="flex flex-col gap-4">
<div className="flex gap-2">
<Button
+ className="flex-1"
+ onClick={() => handleTypeChange('event')}
type="button"
variant={definition.type === 'event' ? 'default' : 'outline'}
- onClick={() => handleTypeChange('event')}
- className="flex-1"
>
Event-based
</Button>
<Button
+ className="flex-1"
+ onClick={() => handleTypeChange('property')}
type="button"
variant={definition.type === 'property' ? 'default' : 'outline'}
- onClick={() => handleTypeChange('property')}
- className="flex-1"
>
Property-based
</Button>
@@ -66,8 +68,8 @@ export function CohortCriteriaBuilder({
{definition.type === 'event' && (
<EventBasedBuilder
definition={definition}
- onChange={onChange}
eventNames={eventNames}
+ onChange={onChange}
/>
)}
@@ -129,7 +131,7 @@ function EventBasedBuilder({
criteria: {
...definition.criteria,
events: definition.criteria.events.map((e, i) =>
- i === index ? criteria : e,
+ i === index ? criteria : e
),
},
});
@@ -145,16 +147,16 @@ function EventBasedBuilder({
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
- <span className="text-sm text-muted-foreground">Match</span>
+ <span className="text-muted-foreground text-sm">Match</span>
<DropdownMenuComposed
- onChange={updateOperator}
items={[
{ value: 'or', label: 'Any of these events' },
{ value: 'and', label: 'All of these events' },
]}
label="Operator"
+ onChange={updateOperator}
>
- <Button variant="outline" size="sm">
+ <Button size="sm" variant="outline">
{definition.criteria.operator === 'or' ? 'Any' : 'All'}
</Button>
</DropdownMenuComposed>
@@ -162,19 +164,19 @@ function EventBasedBuilder({
{definition.criteria.events.map((eventCriteria, index) => (
<EventCriteriaItem
- key={index}
criteria={eventCriteria}
+ eventNames={eventNames}
+ key={index}
onChange={(criteria) => updateEventCriteria(index, criteria)}
onRemove={() => removeEventCriteria(index)}
- eventNames={eventNames}
/>
))}
<Button
+ icon={PlusIcon}
+ onClick={addEventCriteria}
type="button"
variant="outline"
- onClick={addEventCriteria}
- icon={PlusIcon}
>
Add event criteria
</Button>
@@ -219,26 +221,24 @@ function EventCriteriaItem({
const updateFilterValue = (
value: IChartEventFilterValue[],
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => {
onChange({
...criteria,
filters: criteria.filters.map((f) =>
- f.id === filter.id ? { ...f, value } : f,
+ f.id === filter.id ? { ...f, value } : f
),
});
};
const updateFilterOperator = (
operator: IChartEventFilterOperator,
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => {
onChange({
...criteria,
filters: criteria.filters.map((f) =>
- f.id === filter.id
- ? { ...f, operator, value: f.value.slice(0, 1) }
- : f,
+ f.id === filter.id ? { ...f, operator, value: f.value.slice(0, 1) } : f
),
});
};
@@ -247,32 +247,38 @@ function EventCriteriaItem({
<div className="rounded border p-4">
<div className="mb-3 flex items-start justify-between gap-2">
<div className="flex-1">
- <label className="mb-1 block text-sm font-medium">Event</label>
+ <label className="mb-1 block font-medium text-sm">Event</label>
<ComboboxAdvanced
+ className="w-full"
items={eventNames}
- value={criteria.name ? [criteria.name] : []}
onChange={(values) =>
onChange({ ...criteria, name: String(values[0] ?? '') })
}
placeholder="Select event..."
- className="w-full"
+ value={criteria.name ? [criteria.name] : []}
/>
</div>
<Button
+ className="mt-6"
+ onClick={onRemove}
+ size="sm"
type="button"
variant="ghost"
- size="sm"
- onClick={onRemove}
- className="mt-6"
>
<TrashIcon size={16} />
</Button>
</div>
<div className="mb-3">
- <label className="mb-1 block text-sm font-medium">Frequency</label>
+ <label className="mb-1 block font-medium text-sm">Frequency</label>
<div className="flex gap-2">
<DropdownMenuComposed
+ items={[
+ { value: 'gte', label: 'At least' },
+ { value: 'eq', label: 'Exactly' },
+ { value: 'lte', label: 'At most' },
+ ]}
+ label="Operator"
onChange={(operator) =>
onChange({
...criteria,
@@ -282,23 +288,16 @@ function EventCriteriaItem({
},
})
}
- items={[
- { value: 'gte', label: 'At least' },
- { value: 'eq', label: 'Exactly' },
- { value: 'lte', label: 'At most' },
- ]}
- label="Operator"
>
- <Button variant="outline" size="sm">
+ <Button size="sm" variant="outline">
{criteria.frequency?.operator === 'gte' && 'At least'}
{criteria.frequency?.operator === 'eq' && 'Exactly'}
{criteria.frequency?.operator === 'lte' && 'At most'}
</Button>
</DropdownMenuComposed>
<input
- type="number"
+ className="w-20 rounded border px-2 py-1 text-sm"
min="1"
- value={criteria.frequency?.count ?? 1}
onChange={(e) =>
onChange({
...criteria,
@@ -308,19 +307,26 @@ function EventCriteriaItem({
},
})
}
- className="w-20 rounded border px-2 py-1 text-sm"
+ type="number"
+ value={criteria.frequency?.count ?? 1}
/>
- <span className="flex items-center text-sm text-muted-foreground">
+ <span className="flex items-center text-muted-foreground text-sm">
times
</span>
</div>
</div>
<div className="mb-3">
- <label className="mb-1 block text-sm font-medium">Timeframe</label>
+ <label className="mb-1 block font-medium text-sm">Timeframe</label>
<div className="flex flex-col gap-2">
<div className="flex gap-2">
<DropdownMenuComposed
+ items={[
+ { value: 'relative', label: 'Last' },
+ { value: 'since', label: 'Since' },
+ { value: 'between', label: 'Between' },
+ ]}
+ label="Type"
onChange={(type) => {
if (type === 'relative') {
onChange({
@@ -332,8 +338,7 @@ function EventCriteriaItem({
...criteria,
timeframe: {
type: 'absolute',
- start:
- new Date().toISOString().split('T')[0] ?? '',
+ start: new Date().toISOString().split('T')[0] ?? '',
},
});
} else {
@@ -352,14 +357,8 @@ function EventCriteriaItem({
});
}
}}
- items={[
- { value: 'relative', label: 'Last' },
- { value: 'since', label: 'Since' },
- { value: 'between', label: 'Between' },
- ]}
- label="Type"
>
- <Button variant="outline" size="sm">
+ <Button size="sm" variant="outline">
{criteria.timeframe.type === 'relative'
? 'Last'
: criteria.timeframe.type === 'absolute' &&
@@ -370,12 +369,6 @@ function EventCriteriaItem({
</DropdownMenuComposed>
{criteria.timeframe.type === 'relative' ? (
<DropdownMenuComposed
- onChange={(value) =>
- onChange({
- ...criteria,
- timeframe: { type: 'relative', value },
- })
- }
items={[
{ value: '7d', label: '7 days' },
{ value: '30d', label: '30 days' },
@@ -384,8 +377,14 @@ function EventCriteriaItem({
{ value: '365d', label: '365 days' },
]}
label="Period"
+ onChange={(value) =>
+ onChange({
+ ...criteria,
+ timeframe: { type: 'relative', value },
+ })
+ }
>
- <Button variant="outline" size="sm">
+ <Button size="sm" variant="outline">
{criteria.timeframe.value === '7d' && '7 days'}
{criteria.timeframe.value === '30d' && '30 days'}
{criteria.timeframe.value === '90d' && '90 days'}
@@ -393,79 +392,79 @@ function EventCriteriaItem({
{criteria.timeframe.value === '365d' && '365 days'}
</Button>
</DropdownMenuComposed>
- ) : !criteria.timeframe.end ? (
+ ) : criteria.timeframe.end ? null : (
<input
- type="date"
- value={criteria.timeframe.start}
+ className="rounded border px-2 py-1 text-sm"
onChange={(e) =>
onChange({
...criteria,
timeframe: { type: 'absolute', start: e.target.value },
})
}
- className="rounded border px-2 py-1 text-sm"
+ type="date"
+ value={criteria.timeframe.start}
/>
- ) : null}
+ )}
</div>
- {criteria.timeframe.type === 'absolute' &&
- criteria.timeframe.end && (
- <div className="flex items-center gap-2">
- <input
- type="date"
- value={criteria.timeframe.start}
- onChange={(e) =>
- onChange({
- ...criteria,
- timeframe: {
- type: 'absolute',
- start: e.target.value,
- end: criteria.timeframe.type === 'absolute'
+ {criteria.timeframe.type === 'absolute' && criteria.timeframe.end && (
+ <div className="flex items-center gap-2">
+ <input
+ className="flex-1 rounded border px-2 py-1 text-sm"
+ onChange={(e) =>
+ onChange({
+ ...criteria,
+ timeframe: {
+ type: 'absolute',
+ start: e.target.value,
+ end:
+ criteria.timeframe.type === 'absolute'
? criteria.timeframe.end
: undefined,
- },
- })
- }
- className="flex-1 rounded border px-2 py-1 text-sm"
- />
- <span className="text-sm text-muted-foreground">to</span>
- <input
- type="date"
- value={criteria.timeframe.end}
- onChange={(e) =>
- onChange({
- ...criteria,
- timeframe: {
- type: 'absolute',
- start:
- criteria.timeframe.type === 'absolute'
- ? criteria.timeframe.start
- : '',
- end: e.target.value,
- },
- })
- }
- className="flex-1 rounded border px-2 py-1 text-sm"
- />
- </div>
- )}
+ },
+ })
+ }
+ type="date"
+ value={criteria.timeframe.start}
+ />
+ <span className="text-muted-foreground text-sm">to</span>
+ <input
+ className="flex-1 rounded border px-2 py-1 text-sm"
+ onChange={(e) =>
+ onChange({
+ ...criteria,
+ timeframe: {
+ type: 'absolute',
+ start:
+ criteria.timeframe.type === 'absolute'
+ ? criteria.timeframe.start
+ : '',
+ end: e.target.value,
+ },
+ })
+ }
+ type="date"
+ value={criteria.timeframe.end}
+ />
+ </div>
+ )}
</div>
</div>
{criteria.filters.length > 0 && (
<div className="mb-2">
- <label className="mb-2 block text-sm font-medium">
+ <label className="mb-2 block font-medium text-sm">
Event Filters
</label>
<div className="space-y-2">
{criteria.filters.map((filter) => (
<PureFilterItem
- key={filter.id}
+ className="rounded border p-2"
eventName={criteria.name}
filter={filter}
- onRemove={removeFilter}
- onChangeValue={updateFilterValue}
+ key={filter.id}
onChangeOperator={updateFilterOperator}
- className="rounded border p-2"
+ onChangeValue={updateFilterValue}
+ onRemove={removeFilter}
/>
))}
</div>
@@ -473,20 +472,20 @@ function EventCriteriaItem({
)}
<PropertiesCombobox
+ categories={['event']}
event={{ name: criteria.name, id: 'cohort-event' } as never}
onSelect={(action) => {
addFilter(action.value);
}}
- categories={['event']}
>
{(setOpen) => (
<Button
+ disabled={!criteria.name}
+ icon={PlusIcon}
+ onClick={() => setOpen(true)}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={() => setOpen(true)}
- icon={PlusIcon}
- disabled={!criteria.name}
>
Add filter
</Button>
@@ -529,7 +528,7 @@ function PropertyBasedBuilder({
criteria: {
...definition.criteria,
properties: definition.criteria.properties.filter(
- (f) => f.id !== filter.id,
+ (f) => f.id !== filter.id
),
},
});
@@ -537,14 +536,14 @@ function PropertyBasedBuilder({
const updatePropertyFilterValue = (
value: IChartEventFilterValue[],
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => {
onChange({
...definition,
criteria: {
...definition.criteria,
properties: definition.criteria.properties.map((f) =>
- f.id === filter.id ? { ...f, value } : f,
+ f.id === filter.id ? { ...f, value } : f
),
},
});
@@ -552,7 +551,7 @@ function PropertyBasedBuilder({
const updatePropertyFilterOperator = (
operator: IChartEventFilterOperator,
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => {
onChange({
...definition,
@@ -561,7 +560,7 @@ function PropertyBasedBuilder({
properties: definition.criteria.properties.map((f) =>
f.id === filter.id
? { ...f, operator, value: f.value.slice(0, 1) }
- : f,
+ : f
),
},
});
@@ -577,16 +576,16 @@ function PropertyBasedBuilder({
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
- <span className="text-sm text-muted-foreground">Match</span>
+ <span className="text-muted-foreground text-sm">Match</span>
<DropdownMenuComposed
- onChange={updateOperator}
items={[
{ value: 'or', label: 'Any of these properties' },
{ value: 'and', label: 'All of these properties' },
]}
label="Operator"
+ onChange={updateOperator}
>
- <Button variant="outline" size="sm">
+ <Button size="sm" variant="outline">
{definition.criteria.operator === 'or' ? 'Any' : 'All'}
</Button>
</DropdownMenuComposed>
@@ -596,30 +595,30 @@ function PropertyBasedBuilder({
<div className="space-y-2">
{definition.criteria.properties.map((filter) => (
<PureFilterItem
- key={filter.id}
+ className="rounded border p-2"
eventName=""
filter={filter}
- onRemove={removePropertyFilter}
- onChangeValue={updatePropertyFilterValue}
+ key={filter.id}
onChangeOperator={updatePropertyFilterOperator}
- className="rounded border p-2"
+ onChangeValue={updatePropertyFilterValue}
+ onRemove={removePropertyFilter}
/>
))}
</div>
)}
<PropertiesCombobox
+ categories={['profile']}
onSelect={(action) => {
addPropertyFilter(action.value);
}}
- categories={['profile']}
>
{(setOpen) => (
<Button
+ icon={PlusIcon}
+ onClick={() => setOpen(true)}
type="button"
variant="outline"
- onClick={() => setOpen(true)}
- icon={PlusIcon}
>
Add property filter
</Button>
diff --git a/apps/start/src/components/filters/FiltersBuilder.tsx b/apps/start/src/components/filters/FiltersBuilder.tsx
index 5019946cb..5f38e7151 100644
--- a/apps/start/src/components/filters/FiltersBuilder.tsx
+++ b/apps/start/src/components/filters/FiltersBuilder.tsx
@@ -1,16 +1,16 @@
+import type {
+ IChartEventFilter,
+ IChartEventFilterOperator,
+ IChartEventFilterValue,
+} from '@openpanel/core/modules/report/report.constants';
import { FilterIcon } from 'lucide-react';
-import { Button } from '@/components/ui/button';
+import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
+import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
import {
PropertiesCombobox,
type PropertiesComboboxCategory,
} from '@/components/report/sidebar/PropertiesCombobox';
-import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
-import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
-import type {
- IChartEventFilter,
- IChartEventFilterOperator,
- IChartEventFilterValue,
-} from '@openpanel/validation';
+import { Button } from '@/components/ui/button';
interface FiltersBuilderProps {
value: IChartEventFilter[];
@@ -48,9 +48,11 @@ export function FiltersBuilder({
const addFilter = (action: { value: string }) => {
if (action.value === 'cohort') {
const hasCohort = value.some(
- (f) => f.operator === 'inCohort' || f.operator === 'notInCohort',
+ (f) => f.operator === 'inCohort' || f.operator === 'notInCohort'
);
- if (hasCohort) return;
+ if (hasCohort) {
+ return;
+ }
onChange([
...value,
{
@@ -83,13 +85,9 @@ export function FiltersBuilder({
if (isCohort) {
return (
<PureCohortFilterItem
- key={filter.id}
- filter={filter}
className="rounded border bg-def-100 p-3"
- onRemove={removeFilter}
- onChangeOperator={(operator, original) =>
- setFilter({ ...original, operator })
- }
+ filter={filter}
+ key={filter.id}
onChangeCohort={(cohortIds, original) => {
setFilter({
...original,
@@ -97,23 +95,23 @@ export function FiltersBuilder({
cohortIds,
});
}}
+ onChangeOperator={(operator, original) =>
+ setFilter({ ...original, operator })
+ }
+ onRemove={removeFilter}
/>
);
}
return (
<PureFilterItem
- key={filter.id}
- filter={filter}
- eventName={eventName}
className="rounded border bg-def-100 p-3"
+ eventName={eventName}
+ filter={filter}
immediateInput
- onRemove={removeFilter}
- onChangeValue={(nextValue: IChartEventFilterValue[], original) =>
- setFilter({ ...original, value: nextValue })
- }
+ key={filter.id}
onChangeOperator={(
operator: IChartEventFilterOperator,
- original,
+ original
) =>
setFilter({
...original,
@@ -123,6 +121,10 @@ export function FiltersBuilder({
value: original.value.filter(Boolean).slice(0, 1),
})
}
+ onChangeValue={(nextValue: IChartEventFilterValue[], original) =>
+ setFilter({ ...original, value: nextValue })
+ }
+ onRemove={removeFilter}
/>
);
})}
@@ -130,15 +132,19 @@ export function FiltersBuilder({
<div className="mt-2">
<PropertiesCombobox
categories={categories}
+ event={
+ eventName
+ ? ({ name: eventName, id: 'builder' } as never)
+ : undefined
+ }
onSelect={addFilter}
- event={eventName ? ({ name: eventName, id: 'builder' } as never) : undefined}
>
{(setOpen) => (
<Button
- variant="outline"
- size="sm"
icon={FilterIcon}
onClick={() => setOpen((p) => !p)}
+ size="sm"
+ variant="outline"
>
{addLabel}
</Button>
diff --git a/apps/start/src/components/filters/TableFilterPills.tsx b/apps/start/src/components/filters/TableFilterPills.tsx
index 001e777dd..8d9ac1ad9 100644
--- a/apps/start/src/components/filters/TableFilterPills.tsx
+++ b/apps/start/src/components/filters/TableFilterPills.tsx
@@ -1,19 +1,19 @@
+import {
+ getCohortIds,
+ type IChartEventFilter,
+ operators,
+} from '@openpanel/core/modules/report/report.constants';
import { FilterIcon, X } from 'lucide-react';
import type { Options as NuqsOptions } from 'nuqs';
+import type { PropertiesComboboxCategory } from '@/components/report/sidebar/PropertiesCombobox';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
-import type { PropertiesComboboxCategory } from '@/components/report/sidebar/PropertiesCombobox';
import { useAppParams } from '@/hooks/use-app-params';
import { useCohorts } from '@/hooks/use-cohorts';
import { useTableFilters } from '@/hooks/use-table-filters';
import { pushModal } from '@/modals';
import { getPropertyLabel } from '@/translations/properties';
import { cn } from '@/utils/cn';
-import { operators } from '@openpanel/constants';
-import {
- getCohortIds,
- type IChartEventFilter,
-} from '@openpanel/validation';
interface TableFilterPillsProps {
/** URL key the filters live under. Sessions tables use `f`. */
@@ -38,8 +38,12 @@ const SESSION_LABELS: Record<string, string> = {
};
function humanizeFilterName(name: string): string {
- if (name === 'cohort' || name.startsWith('cohort:')) return 'Cohort';
- if (SESSION_LABELS[name]) return SESSION_LABELS[name]!;
+ if (name === 'cohort' || name.startsWith('cohort:')) {
+ return 'Cohort';
+ }
+ if (SESSION_LABELS[name]) {
+ return SESSION_LABELS[name]!;
+ }
if (name.startsWith('profile.')) {
const rest = name.replace(/^profile\./, '');
return `Profile · ${rest.replace(/^properties\./, '')}`;
@@ -54,7 +58,9 @@ function humanizeFilterName(name: string): string {
function formatFilterValue(filter: IChartEventFilter): string {
if (filter.name === 'session.is_bounce') {
const v = filter.value[0];
- if (v === undefined) return '';
+ if (v === undefined) {
+ return '';
+ }
const truthy =
typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true';
return truthy ? 'Yes' : 'No';
@@ -76,7 +82,7 @@ export function TableFilterPills({
const [filters, setFilters] = useTableFilters(urlKey, nuqsOptions);
const cohorts = useCohorts(
{ projectId, includeCount: false },
- { enabled: categories.includes('cohort') },
+ { enabled: categories.includes('cohort') }
);
const cohortNames = new Map(cohorts.map((c) => [c.id, c.name]));
@@ -94,12 +100,7 @@ export function TableFilterPills({
return (
<div className={cn('row flex-wrap items-center gap-2', className)}>
- <Button
- variant="outline"
- size="sm"
- icon={FilterIcon}
- onClick={openSheet}
- >
+ <Button icon={FilterIcon} onClick={openSheet} size="sm" variant="outline">
Filters
{filters.length > 0 && (
<Badge className="ml-2 rounded-full px-1.5 py-0 text-xs">
@@ -114,7 +115,9 @@ export function TableFilterPills({
const valueText = isCohort
? cohortIds
.map(
- (id) => cohortNames.get(id) ?? cohortNames.get(id.replace(/^cohort:/, '')),
+ (id) =>
+ cohortNames.get(id) ??
+ cohortNames.get(id.replace(/^cohort:/, ''))
)
.filter(Boolean)
.join(', ') || 'pick cohort'
@@ -122,37 +125,37 @@ export function TableFilterPills({
return (
<div
+ className="flex h-8 items-stretch overflow-hidden rounded-md border bg-card text-sm"
key={`${filter.name}-${index}`}
- className="flex items-stretch text-sm border rounded-md overflow-hidden h-8 bg-card"
>
<button
- type="button"
+ className="cursor-pointer px-2 transition-colors hover:bg-accent"
onClick={openSheet}
- className="px-2 hover:bg-accent transition-colors cursor-pointer"
+ type="button"
>
{humanizeFilterName(filter.name)}
</button>
<button
- type="button"
+ className="cursor-pointer border-l px-2 lowercase opacity-50 transition-colors hover:bg-accent hover:opacity-100"
onClick={openSheet}
- className="px-2 opacity-50 lowercase hover:opacity-100 hover:bg-accent transition-colors border-l cursor-pointer"
+ type="button"
>
{operators[filter.operator] ?? filter.operator}
</button>
{valueText && (
<button
- type="button"
+ className="max-w-40 cursor-pointer truncate border-l px-2 font-semibold transition-colors hover:bg-accent"
onClick={openSheet}
- className="px-2 font-semibold hover:bg-accent transition-colors border-l cursor-pointer max-w-40 truncate"
+ type="button"
>
{valueText}
</button>
)}
<button
- type="button"
- onClick={() => removeAt(index)}
- className="px-2 hover:bg-destructive hover:text-destructive-foreground transition-colors border-l cursor-pointer"
aria-label="Remove filter"
+ className="cursor-pointer border-l px-2 transition-colors hover:bg-destructive hover:text-destructive-foreground"
+ onClick={() => removeAt(index)}
+ type="button"
>
<X className="size-3" />
</button>
diff --git a/apps/start/src/components/insights/insight-card.tsx b/apps/start/src/components/insights/insight-card.tsx
index 6336aae50..984d88073 100644
--- a/apps/start/src/components/insights/insight-card.tsx
+++ b/apps/start/src/components/insights/insight-card.tsx
@@ -1,21 +1,12 @@
-import { countries } from '@/translations/countries';
-import type { RouterOutputs } from '@/trpc/client';
-import { cn } from '@/utils/cn';
-import type { InsightPayload } from '@openpanel/validation';
-import { pushModal } from '@/modals';
-import {
- ArrowDown,
- ArrowUp,
- FilterIcon,
- RotateCcwIcon,
- SparklesIcon,
-} from 'lucide-react';
-import { last } from 'ramda';
+import { FilterIcon, RotateCcwIcon, SparklesIcon } from 'lucide-react';
import { useState } from 'react';
import { DeltaChip } from '../delta-chip';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
+import { pushModal } from '@/modals';
+import type { RouterOutputs } from '@/trpc/client';
+import { cn } from '@/utils/cn';
function formatWindowKind(windowKind: string): string {
switch (windowKind) {
@@ -46,7 +37,7 @@ export function InsightCard({
// Pick what to display: prefer share if available (geo/devices), else primaryMetric
const [metricIndex, setMetricIndex] = useState(
- availableMetrics.findIndex(([key]) => key === payload?.primaryMetric),
+ availableMetrics.findIndex(([key]) => key === payload?.primaryMetric)
);
const currentMetricKey = availableMetrics[metricIndex][0];
const currentMetricEntry = availableMetrics[metricIndex][1];
@@ -66,8 +57,12 @@ export function InsightCard({
// Format metric values
const formatValue = (value: number | null): string => {
- if (value == null) return '-';
- if (metricUnit === 'ratio') return `${(value * 100).toFixed(1)}%`;
+ if (value == null) {
+ return '-';
+ }
+ if (metricUnit === 'ratio') {
+ return `${(value * 100).toFixed(1)}%`;
+ }
return Math.round(value).toLocaleString();
};
@@ -84,7 +79,7 @@ export function InsightCard({
dimensions[0]?.key === 'device'
) {
return (
- <span className="capitalize flex items-center gap-2">
+ <span className="flex items-center gap-2 capitalize">
<SerieIcon name={dimensions[0]?.value} /> {insight.displayName}
</span>
);
@@ -107,22 +102,22 @@ export function InsightCard({
return (
<div
className={cn(
- 'card p-4 h-full flex flex-col hover:bg-def-50 transition-colors group/card',
- className,
+ 'card group/card flex h-full flex-col p-4 transition-colors hover:bg-def-50',
+ className
)}
>
<div
className={cn(
- 'row justify-between h-4 items-center',
- onFilter && 'group-hover/card:hidden',
+ 'row h-4 items-center justify-between',
+ onFilter && 'group-hover/card:hidden'
)}
>
- <Badge variant="outline" className="-ml-2">
+ <Badge className="-ml-2" variant="outline">
{formatWindowKind(insight.windowKind)}
</Badge>
{/* Severity: subtle dot instead of big pill */}
{insight.severityBand && (
- <div className="flex items-center gap-1 shrink-0">
+ <div className="flex shrink-0 items-center gap-1">
<span
className={cn(
'h-2 w-2 rounded-full',
@@ -130,7 +125,7 @@ export function InsightCard({
? 'bg-red-500'
: insight.severityBand === 'moderate'
? 'bg-yellow-500'
- : 'bg-blue-500',
+ : 'bg-blue-500'
)}
/>
<span className="text-[11px] text-muted-foreground capitalize">
@@ -140,42 +135,40 @@ export function InsightCard({
)}
</div>
{onFilter && (
- <div className="row group-hover/card:flex hidden h-4 justify-between gap-2">
+ <div className="row hidden h-4 justify-between gap-2 group-hover/card:flex">
{availableMetrics.length > 1 ? (
<button
- type="button"
- className="text-[11px] text-muted-foreground capitalize flex items-center gap-1"
+ className="flex items-center gap-1 text-[11px] text-muted-foreground capitalize"
onClick={() =>
setMetricIndex((metricIndex + 1) % availableMetrics.length)
}
+ type="button"
>
<RotateCcwIcon className="size-2" />
Show{' '}
{metricKeyToLabel(
- availableMetrics[
- (metricIndex + 1) % availableMetrics.length
- ][0],
+ availableMetrics[(metricIndex + 1) % availableMetrics.length][0]
)}
</button>
) : (
<div />
)}
<button
- type="button"
- className="text-[11px] text-muted-foreground capitalize flex items-center gap-1"
+ className="flex items-center gap-1 text-[11px] text-muted-foreground capitalize"
onClick={onFilter}
+ type="button"
>
Filter <FilterIcon className="size-2" />
</button>
</div>
)}
- <div className="font-semibold text-sm leading-snug line-clamp-2 mt-2">
+ <div className="mt-2 line-clamp-2 font-semibold text-sm leading-snug">
{renderTitle()}
</div>
{/* AI plain-language summary (Tier-1 enrichment) */}
{insight.aiSummary && (
- <p className="text-xs text-muted-foreground leading-snug line-clamp-3 mt-1">
+ <p className="mt-1 line-clamp-3 text-muted-foreground text-xs leading-snug">
{insight.aiSummary}
</p>
)}
@@ -184,18 +177,18 @@ export function InsightCard({
<div className="mt-auto pt-2">
<div className="flex items-end justify-between gap-3">
<div className="min-w-0">
- <div className="text-[11px] text-muted-foreground mb-1">
+ <div className="mb-1 text-[11px] text-muted-foreground">
{metricLabel}
</div>
<div className="col gap-1">
- <div className="text-2xl font-semibold tracking-tight">
+ <div className="font-semibold text-2xl tracking-tight">
{formatValue(currentValue)}
</div>
{/* Inline compare, smaller */}
{compareValue != null && (
- <div className="text-xs text-muted-foreground">
+ <div className="text-muted-foreground text-xs">
vs {formatValue(compareValue)}
</div>
)}
@@ -204,15 +197,15 @@ export function InsightCard({
{/* Delta chip */}
<DeltaChip
- variant={isIncrease ? 'inc' : isDecrease ? 'dec' : 'default'}
size="sm"
+ variant={isIncrease ? 'inc' : isDecrease ? 'dec' : 'default'}
>
{deltaText}
</DeltaChip>
</div>
<Button
- className="-ml-2 mt-2 h-7 self-start px-2 text-muted-foreground text-xs"
+ className="mt-2 -ml-2 h-7 self-start px-2 text-muted-foreground text-xs"
icon={SparklesIcon}
onClick={() => pushModal('InsightDetails', { insight })}
size="sm"
diff --git a/apps/start/src/components/integrations/forms/discord-integration.tsx b/apps/start/src/components/integrations/forms/discord-integration.tsx
index a28a8c622..a740462b6 100644
--- a/apps/start/src/components/integrations/forms/discord-integration.tsx
+++ b/apps/start/src/components/integrations/forms/discord-integration.tsx
@@ -1,15 +1,15 @@
-import { InputWithLabel } from '@/components/forms/input-with-label';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { useTRPC } from '@/integrations/trpc/react';
-import type { RouterOutputs } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
-import { zCreateDiscordIntegration } from '@openpanel/validation';
+import { zCreateDiscordIntegration } from '@openpanel/core/modules/integration/integration.constants';
import { useMutation } from '@tanstack/react-query';
-import { path, mergeDeepRight } from 'ramda';
+import { mergeDeepRight, path } from 'ramda';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
+import { InputWithLabel } from '@/components/forms/input-with-label';
+import { Button } from '@/components/ui/button';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useTRPC } from '@/integrations/trpc/react';
+import type { RouterOutputs } from '@/trpc/client';
type IForm = z.infer<typeof zCreateDiscordIntegration>;
@@ -32,7 +32,7 @@ export function DiscordIntegrationForm({
headers: {},
},
},
- defaultValues ?? {},
+ defaultValues ?? {}
),
resolver: zodResolver(zCreateDiscordIntegration),
});
@@ -43,7 +43,7 @@ export function DiscordIntegrationForm({
onError() {
toast.error('Failed to create integration');
},
- }),
+ })
);
const handleSubmit = (values: IForm) => {
@@ -55,7 +55,7 @@ export function DiscordIntegrationForm({
};
const testMutation = useMutation(
- trpc.integration.testConnection.mutationOptions(),
+ trpc.integration.testConnection.mutationOptions()
);
const handleTest = async () => {
@@ -76,8 +76,8 @@ export function DiscordIntegrationForm({
return (
<form
- onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
+ onSubmit={form.handleSubmit(handleSubmit, handleError)}
>
<InputWithLabel
label="Name"
@@ -91,10 +91,10 @@ export function DiscordIntegrationForm({
error={path(['config', 'url', 'message'], form.formState.errors)}
/>
<div className="row gap-4">
- <Button type="button" variant="outline" onClick={handleTest}>
+ <Button onClick={handleTest} type="button" variant="outline">
Test connection
</Button>
- <Button type="submit" className="flex-1">
+ <Button className="flex-1" type="submit">
Create
</Button>
</div>
diff --git a/apps/start/src/components/integrations/forms/gcs-export-integration.tsx b/apps/start/src/components/integrations/forms/gcs-export-integration.tsx
index 96c39e462..2d268c776 100644
--- a/apps/start/src/components/integrations/forms/gcs-export-integration.tsx
+++ b/apps/start/src/components/integrations/forms/gcs-export-integration.tsx
@@ -1,3 +1,10 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { zCreateGCSExportIntegration } from '@openpanel/core/modules/integration/integration.constants';
+import { useMutation } from '@tanstack/react-query';
+import { mergeDeepRight, path } from 'ramda';
+import { Controller, useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import type { z } from 'zod';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import {
@@ -10,13 +17,6 @@ import {
import { useAppParams } from '@/hooks/use-app-params';
import { useTRPC } from '@/integrations/trpc/react';
import type { RouterOutputs } from '@/trpc/client';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { zCreateGCSExportIntegration } from '@openpanel/validation';
-import { useMutation } from '@tanstack/react-query';
-import { path, mergeDeepRight } from 'ramda';
-import { Controller, useForm } from 'react-hook-form';
-import { toast } from 'sonner';
-import type { z } from 'zod';
type IForm = z.infer<typeof zCreateGCSExportIntegration>;
@@ -42,7 +42,7 @@ export function GCSExportIntegrationForm({
serviceAccountKey: '',
},
},
- defaultValues ?? {},
+ defaultValues ?? {}
),
resolver: zodResolver(zCreateGCSExportIntegration),
});
@@ -53,7 +53,7 @@ export function GCSExportIntegrationForm({
onError(error) {
toast.error(error.message || 'Failed to create integration');
},
- }),
+ })
);
const testMutation = useMutation(
@@ -68,7 +68,7 @@ export function GCSExportIntegrationForm({
onError(error) {
toast.error(error.message || 'Failed to test connection');
},
- }),
+ })
);
const handleSubmit = (values: IForm) => {
@@ -81,7 +81,7 @@ export function GCSExportIntegrationForm({
const handleTest = () => {
const values = form.getValues();
- if (!values.config.bucket || !values.config.serviceAccountKey) {
+ if (!(values.config.bucket && values.config.serviceAccountKey)) {
return toast.error('Bucket and Service Account Key are required');
}
testMutation.mutate(values);
@@ -89,8 +89,8 @@ export function GCSExportIntegrationForm({
return (
<form
- onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
+ onSubmit={form.handleSubmit(handleSubmit, handleError)}
>
<InputWithLabel
label="Name"
@@ -115,10 +115,10 @@ export function GCSExportIntegrationForm({
</div>
<div className="col gap-1.5">
- <label className="text-sm font-medium">Format</label>
+ <label className="font-medium text-sm">Format</label>
<Controller
- name="config.format"
control={form.control}
+ name="config.format"
render={({ field }) => (
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger className="w-48">
@@ -126,7 +126,7 @@ export function GCSExportIntegrationForm({
</SelectTrigger>
<SelectContent>
<SelectItem value="jsonl_gzip">JSONL (gzip)</SelectItem>
- <SelectItem value="parquet" disabled>
+ <SelectItem disabled value="parquet">
Parquet (coming soon)
</SelectItem>
</SelectContent>
@@ -136,11 +136,11 @@ export function GCSExportIntegrationForm({
</div>
<div className="col gap-1.5">
- <label className="text-sm font-medium">
+ <label className="font-medium text-sm">
Service Account Key (JSON)
</label>
<textarea
- className="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring min-h-32 w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
+ className="min-h-32 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
placeholder={
defaultValues?.id
? 'Leave blank to keep the current key'
@@ -152,13 +152,13 @@ export function GCSExportIntegrationForm({
/>
{!!path(
['config', 'serviceAccountKey', 'message'],
- form.formState.errors,
+ form.formState.errors
) && (
<p className="text-destructive text-xs">
{
path(
['config', 'serviceAccountKey', 'message'],
- form.formState.errors,
+ form.formState.errors
) as any
}
</p>
@@ -172,14 +172,14 @@ export function GCSExportIntegrationForm({
<div className="row gap-4">
<Button
+ disabled={testMutation.isPending}
+ onClick={handleTest}
type="button"
variant="outline"
- onClick={handleTest}
- disabled={testMutation.isPending}
>
{testMutation.isPending ? 'Testing...' : 'Test connection'}
</Button>
- <Button type="submit" className="flex-1" disabled={mutation.isPending}>
+ <Button className="flex-1" disabled={mutation.isPending} type="submit">
{mutation.isPending
? 'Saving...'
: defaultValues?.id
diff --git a/apps/start/src/components/integrations/forms/s3-export-integration.tsx b/apps/start/src/components/integrations/forms/s3-export-integration.tsx
index 705ea9939..4ee42c614 100644
--- a/apps/start/src/components/integrations/forms/s3-export-integration.tsx
+++ b/apps/start/src/components/integrations/forms/s3-export-integration.tsx
@@ -1,3 +1,10 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { zCreateS3ExportIntegration } from '@openpanel/core/modules/integration/integration.constants';
+import { useMutation } from '@tanstack/react-query';
+import { mergeDeepRight, path } from 'ramda';
+import { Controller, useForm, useWatch } from 'react-hook-form';
+import { toast } from 'sonner';
+import type { z } from 'zod';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import {
@@ -10,13 +17,6 @@ import {
import { useAppParams } from '@/hooks/use-app-params';
import { useTRPC } from '@/integrations/trpc/react';
import type { RouterOutputs } from '@/trpc/client';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { zCreateS3ExportIntegration } from '@openpanel/validation';
-import { useMutation } from '@tanstack/react-query';
-import { path, mergeDeepRight } from 'ramda';
-import { Controller, useForm, useWatch } from 'react-hook-form';
-import { toast } from 'sonner';
-import type { z } from 'zod';
type IForm = z.infer<typeof zCreateS3ExportIntegration>;
@@ -66,7 +66,7 @@ export function S3ExportIntegrationForm({
kmsKeyId: '',
},
},
- defaultValues ?? {},
+ defaultValues ?? {}
),
resolver: zodResolver(zCreateS3ExportIntegration),
});
@@ -77,7 +77,7 @@ export function S3ExportIntegrationForm({
onError(error) {
toast.error(error.message || 'Failed to create integration');
},
- }),
+ })
);
const testMutation = useMutation(
@@ -92,11 +92,14 @@ export function S3ExportIntegrationForm({
onError(error) {
toast.error(error.message || 'Failed to test connection');
},
- }),
+ })
);
const authMode = useWatch({ control: form.control, name: 'config.authMode' });
- const encryption = useWatch({ control: form.control, name: 'config.encryption' });
+ const encryption = useWatch({
+ control: form.control,
+ name: 'config.encryption',
+ });
const handleSubmit = (values: IForm) => {
mutation.mutate(values);
@@ -108,24 +111,25 @@ export function S3ExportIntegrationForm({
const handleTest = () => {
const values = form.getValues();
- if (!values.config.bucket || !values.config.region) {
+ if (!(values.config.bucket && values.config.region)) {
return toast.error('Bucket and Region are required');
}
if (values.config.authMode === 'iam_role' && !values.config.roleArn) {
return toast.error('IAM Role ARN is required');
}
- if (values.config.authMode === 'access_key') {
- if (!values.config.accessKeyId || !values.config.secretAccessKey) {
- return toast.error('Access Key ID and Secret Access Key are required');
- }
+ if (
+ values.config.authMode === 'access_key' &&
+ !(values.config.accessKeyId && values.config.secretAccessKey)
+ ) {
+ return toast.error('Access Key ID and Secret Access Key are required');
}
testMutation.mutate(values);
};
return (
<form
- onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
+ onSubmit={form.handleSubmit(handleSubmit, handleError)}
>
<InputWithLabel
label="Name"
@@ -151,10 +155,10 @@ export function S3ExportIntegrationForm({
<div className="grid grid-cols-2 gap-4">
<div className="col gap-1.5">
- <label className="text-sm font-medium">Region</label>
+ <label className="font-medium text-sm">Region</label>
<Controller
- name="config.region"
control={form.control}
+ name="config.region"
render={({ field }) => (
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
@@ -173,10 +177,10 @@ export function S3ExportIntegrationForm({
</div>
<div className="col gap-1.5">
- <label className="text-sm font-medium">Format</label>
+ <label className="font-medium text-sm">Format</label>
<Controller
- name="config.format"
control={form.control}
+ name="config.format"
render={({ field }) => (
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
@@ -184,7 +188,7 @@ export function S3ExportIntegrationForm({
</SelectTrigger>
<SelectContent>
<SelectItem value="jsonl_gzip">JSONL (gzip)</SelectItem>
- <SelectItem value="parquet" disabled>
+ <SelectItem disabled value="parquet">
Parquet (coming soon)
</SelectItem>
</SelectContent>
@@ -196,10 +200,10 @@ export function S3ExportIntegrationForm({
{/* Auth Mode Selector */}
<div className="col gap-1.5">
- <label className="text-sm font-medium">Authentication Mode</label>
+ <label className="font-medium text-sm">Authentication Mode</label>
<Controller
- name="config.authMode"
control={form.control}
+ name="config.authMode"
render={({ field }) => (
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
@@ -207,7 +211,9 @@ export function S3ExportIntegrationForm({
</SelectTrigger>
<SelectContent>
<SelectItem value="iam_role">IAM Role (AWS)</SelectItem>
- <SelectItem value="access_key">Access Keys (R2, MinIO, Spaces)</SelectItem>
+ <SelectItem value="access_key">
+ Access Keys (R2, MinIO, Spaces)
+ </SelectItem>
</SelectContent>
</Select>
)}
@@ -226,14 +232,20 @@ export function S3ExportIntegrationForm({
label="IAM Role ARN"
placeholder="arn:aws:iam::123456789012:role/OpenPanelExportRole"
{...form.register('config.roleArn')}
- error={path(['config', 'roleArn', 'message'], form.formState.errors)}
+ error={path(
+ ['config', 'roleArn', 'message'],
+ form.formState.errors
+ )}
/>
<InputWithLabel
label="External ID (optional)"
placeholder="Optional external ID for cross-account access"
{...form.register('config.externalId')}
- error={path(['config', 'externalId', 'message'], form.formState.errors)}
+ error={path(
+ ['config', 'externalId', 'message'],
+ form.formState.errors
+ )}
/>
</>
)}
@@ -245,9 +257,12 @@ export function S3ExportIntegrationForm({
label="Endpoint URL (optional)"
placeholder="https://your-account-id.r2.cloudflarestorage.com"
{...form.register('config.endpoint')}
- error={path(['config', 'endpoint', 'message'], form.formState.errors)}
+ error={path(
+ ['config', 'endpoint', 'message'],
+ form.formState.errors
+ )}
/>
- <p className="text-muted-foreground -mt-2 text-xs">
+ <p className="-mt-2 text-muted-foreground text-xs">
Required for R2, MinIO, etc. Leave empty for AWS S3.
</p>
@@ -256,20 +271,26 @@ export function S3ExportIntegrationForm({
label="Access Key ID"
placeholder="AKIAIOSFODNN7EXAMPLE"
{...form.register('config.accessKeyId')}
- error={path(['config', 'accessKeyId', 'message'], form.formState.errors)}
+ error={path(
+ ['config', 'accessKeyId', 'message'],
+ form.formState.errors
+ )}
/>
<InputWithLabel
label="Secret Access Key"
- type="password"
placeholder={
defaultValues?.id
? 'Leave blank to keep the current key'
: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'
}
+ type="password"
// Stored secrets are never sent back to the browser, so an edit
// starts blank and blank means "keep the stored key".
{...form.register('config.secretAccessKey')}
- error={path(['config', 'secretAccessKey', 'message'], form.formState.errors)}
+ error={path(
+ ['config', 'secretAccessKey', 'message'],
+ form.formState.errors
+ )}
/>
</div>
</>
@@ -277,10 +298,10 @@ export function S3ExportIntegrationForm({
<div className="grid grid-cols-2 gap-4">
<div className="col gap-1.5">
- <label className="text-sm font-medium">Encryption</label>
+ <label className="font-medium text-sm">Encryption</label>
<Controller
- name="config.encryption"
control={form.control}
+ name="config.encryption"
render={({ field }) => (
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
@@ -303,7 +324,7 @@ export function S3ExportIntegrationForm({
{...form.register('config.kmsKeyId')}
error={path(
['config', 'kmsKeyId', 'message'],
- form.formState.errors,
+ form.formState.errors
)}
/>
)}
@@ -311,14 +332,14 @@ export function S3ExportIntegrationForm({
<div className="row gap-4">
<Button
+ disabled={testMutation.isPending}
+ onClick={handleTest}
type="button"
variant="outline"
- onClick={handleTest}
- disabled={testMutation.isPending}
>
{testMutation.isPending ? 'Testing...' : 'Test connection'}
</Button>
- <Button type="submit" className="flex-1" disabled={mutation.isPending}>
+ <Button className="flex-1" disabled={mutation.isPending} type="submit">
{mutation.isPending
? 'Saving...'
: defaultValues?.id
diff --git a/apps/start/src/components/integrations/forms/slack-integration.tsx b/apps/start/src/components/integrations/forms/slack-integration.tsx
index 17d3c3687..bd4d62897 100644
--- a/apps/start/src/components/integrations/forms/slack-integration.tsx
+++ b/apps/start/src/components/integrations/forms/slack-integration.tsx
@@ -1,14 +1,14 @@
-import { InputWithLabel } from '@/components/forms/input-with-label';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { useTRPC } from '@/integrations/trpc/react';
-import type { RouterOutputs } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
-import { zCreateSlackIntegration } from '@openpanel/validation';
+import { zCreateSlackIntegration } from '@openpanel/core/modules/integration/integration.constants';
import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
+import { InputWithLabel } from '@/components/forms/input-with-label';
+import { Button } from '@/components/ui/button';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useTRPC } from '@/integrations/trpc/react';
+import type { RouterOutputs } from '@/trpc/client';
type IForm = z.infer<typeof zCreateSlackIntegration>;
@@ -39,7 +39,7 @@ export function SlackIntegrationForm({
onError() {
toast.error('Failed to create integration');
},
- }),
+ })
);
const handleSubmit = (values: IForm) => {
@@ -52,8 +52,8 @@ export function SlackIntegrationForm({
return (
<form
- onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
+ onSubmit={form.handleSubmit(handleSubmit, handleError)}
>
<InputWithLabel
label="Name"
diff --git a/apps/start/src/components/integrations/forms/webhook-integration.tsx b/apps/start/src/components/integrations/forms/webhook-integration.tsx
index edd3be0cc..36f506cd6 100644
--- a/apps/start/src/components/integrations/forms/webhook-integration.tsx
+++ b/apps/start/src/components/integrations/forms/webhook-integration.tsx
@@ -1,3 +1,12 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { zCreateWebhookIntegration } from '@openpanel/core/modules/integration/integration.constants';
+import { useMutation } from '@tanstack/react-query';
+import { PlusIcon, TrashIcon } from 'lucide-react';
+import { mergeDeepRight, path } from 'ramda';
+import { useEffect } from 'react';
+import { Controller, useFieldArray, useForm, useWatch } from 'react-hook-form';
+import { toast } from 'sonner';
+import type { z } from 'zod';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import { JsonEditor } from '@/components/json-editor';
import { Button } from '@/components/ui/button';
@@ -6,16 +15,6 @@ import { Input } from '@/components/ui/input';
import { useAppParams } from '@/hooks/use-app-params';
import { useTRPC } from '@/integrations/trpc/react';
import type { RouterOutputs } from '@/trpc/client';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { zCreateWebhookIntegration } from '@openpanel/validation';
-import { useMutation } from '@tanstack/react-query';
-import { PlusIcon, TrashIcon } from 'lucide-react';
-import { path, mergeDeepRight } from 'ramda';
-import { useEffect } from 'react';
-import { Controller, useFieldArray, useWatch } from 'react-hook-form';
-import { useForm } from 'react-hook-form';
-import { toast } from 'sonner';
-import type { z } from 'zod';
type IForm = z.infer<typeof zCreateWebhookIntegration>;
@@ -25,7 +24,7 @@ const DEFAULT_TRANSFORMER = `(payload) => {
// Convert Record<string, string> to array format for form
function headersToArray(
- headers: Record<string, string> | undefined,
+ headers: Record<string, string> | undefined
): { key: string; value: string }[] {
if (!headers || Object.keys(headers).length === 0) {
return [];
@@ -35,7 +34,7 @@ function headersToArray(
// Convert array format back to Record<string, string> for API
function headersToRecord(
- headers: { key: string; value: string }[],
+ headers: { key: string; value: string }[]
): Record<string, string> {
return headers.reduce(
(acc, { key, value }) => {
@@ -44,7 +43,7 @@ function headersToRecord(
}
return acc;
},
- {} as Record<string, string>,
+ {} as Record<string, string>
);
}
@@ -76,7 +75,7 @@ export function WebhookIntegrationForm({
javascriptTemplate: undefined,
},
},
- defaultValues ?? {},
+ defaultValues ?? {}
),
resolver: zodResolver(zCreateWebhookIntegration),
});
@@ -106,7 +105,7 @@ export function WebhookIntegrationForm({
(h): h is { key: string; value: string } =>
h !== undefined &&
typeof h.key === 'string' &&
- typeof h.value === 'string',
+ typeof h.value === 'string'
);
form.setValue('config.headers', headersToRecord(validHeaders), {
shouldValidate: false,
@@ -135,7 +134,7 @@ export function WebhookIntegrationForm({
toast.error('Failed to create integration');
}
},
- }),
+ })
);
const handleSubmit = (values: IForm) => {
@@ -148,8 +147,8 @@ export function WebhookIntegrationForm({
return (
<form
- onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
+ onSubmit={form.handleSubmit(handleSubmit, handleError)}
>
<InputWithLabel
label="Name"
@@ -164,43 +163,41 @@ export function WebhookIntegrationForm({
/>
<WithLabel
- label="Headers"
info="Add custom HTTP headers to include with webhook requests"
+ label="Headers"
>
<div className="col gap-2">
{headersArray.fields.map((field, index) => (
- <div key={field.id} className="row gap-2">
+ <div className="row gap-2" key={field.id}>
<Input
placeholder="Header Name"
{...headersForm.register(`headers.${index}.key`)}
className="flex-1"
/>
<Input
- placeholder={
- defaultValues?.id ? 'Unchanged' : 'Header Value'
- }
+ placeholder={defaultValues?.id ? 'Unchanged' : 'Header Value'}
// Header values are never sent back to the browser, so an edit
// starts blank and blank means "keep the stored value".
{...headersForm.register(`headers.${index}.value`)}
className="flex-1"
/>
<Button
+ className="text-destructive"
+ onClick={() => headersArray.remove(index)}
+ size="icon"
type="button"
variant="ghost"
- size="icon"
- onClick={() => headersArray.remove(index)}
- className="text-destructive"
>
<TrashIcon className="h-4 w-4" />
</Button>
</div>
))}
<Button
- type="button"
- variant="outline"
- onClick={() => headersArray.append({ key: '', value: '' })}
className="self-start"
icon={PlusIcon}
+ onClick={() => headersArray.append({ key: '', value: '' })}
+ type="button"
+ variant="outline"
>
Add Header
</Button>
@@ -212,13 +209,12 @@ export function WebhookIntegrationForm({
name="config.mode"
render={({ field }) => (
<WithLabel
- label="Payload Format"
info="Choose how to format the webhook payload"
+ label="Payload Format"
>
<Combobox
{...field}
className="w-full"
- placeholder="Select format"
items={[
{
label: 'Message',
@@ -229,8 +225,9 @@ export function WebhookIntegrationForm({
value: 'javascript' as const,
},
]}
- value={field.value ?? 'message'}
onChange={field.onChange}
+ placeholder="Select format"
+ value={field.value ?? 'message'}
/>
</WithLabel>
)}
@@ -242,7 +239,6 @@ export function WebhookIntegrationForm({
name="config.javascriptTemplate"
render={({ field }) => (
<WithLabel
- label="JavaScript Transform"
info={
<div className="prose dark:prose-invert max-w-none">
<p>
@@ -250,7 +246,7 @@ export function WebhookIntegrationForm({
payload. The function receives <code>payload</code> as a
parameter and should return an object.
</p>
- <p className="text-sm font-semibold mt-2">
+ <p className="mt-2 font-semibold text-sm">
Available in payload:
</p>
<ul className="text-sm">
@@ -271,7 +267,7 @@ export function WebhookIntegrationForm({
<code>payload.profile.firstName</code> - Profile property
</li>
<li>
- <div className="flex gap-x-2 flex-wrap mt-1">
+ <div className="mt-1 flex flex-wrap gap-x-2">
<code>country</code>
<code>city</code>
<code>device</code>
@@ -283,7 +279,7 @@ export function WebhookIntegrationForm({
</div>
</li>
</ul>
- <p className="text-sm font-semibold mt-2">
+ <p className="mt-2 font-semibold text-sm">
Available helpers:
</p>
<ul className="text-sm">
@@ -293,10 +289,10 @@ export function WebhookIntegrationForm({
<code>Object</code>
</li>
</ul>
- <p className="text-sm mt-2">
+ <p className="mt-2 text-sm">
<strong>Example:</strong>
</p>
- <pre className="text-xs bg-muted p-2 rounded mt-1 overflow-x-auto">
+ <pre className="mt-1 overflow-x-auto rounded bg-muted p-2 text-xs">
{`(payload) => ({
event: payload.name,
user: payload.profileId,
@@ -305,15 +301,17 @@ export function WebhookIntegrationForm({
location: \`\${payload.city}, \${payload.country}\`
})`}
</pre>
- <p className="text-sm mt-2 text-yellow-600 dark:text-yellow-400">
+ <p className="mt-2 text-sm text-yellow-600 dark:text-yellow-400">
<strong>Security:</strong> Network calls, file system
access, and other dangerous operations are blocked.
</p>
</div>
}
+ label="JavaScript Transform"
>
<JsonEditor
- value={field.value ?? DEFAULT_TRANSFORMER}
+ language="javascript"
+ minHeight="300px"
onChange={(value) => {
field.onChange(value);
// Clear error when user starts typing
@@ -322,11 +320,10 @@ export function WebhookIntegrationForm({
}
}}
placeholder={DEFAULT_TRANSFORMER}
- minHeight="300px"
- language="javascript"
+ value={field.value ?? DEFAULT_TRANSFORMER}
/>
{form.formState.errors.config?.javascriptTemplate && (
- <p className="mt-1 text-sm text-destructive">
+ <p className="mt-1 text-destructive text-sm">
{form.formState.errors.config.javascriptTemplate.message}
</p>
)}
diff --git a/apps/start/src/components/integrations/integrations.tsx b/apps/start/src/components/integrations/integrations.tsx
index f48265fd1..afd816c3b 100644
--- a/apps/start/src/components/integrations/integrations.tsx
+++ b/apps/start/src/components/integrations/integrations.tsx
@@ -1,8 +1,7 @@
-import type { RouterOutputs } from '@/trpc/client';
import {
- INTEGRATION_DESCRIPTORS,
type IIntegrationType,
-} from '@openpanel/validation';
+ INTEGRATION_DESCRIPTORS,
+} from '@openpanel/core/modules/integration/integration.constants';
import { BoxIcon, CloudIcon, DatabaseIcon, WebhookIcon } from 'lucide-react';
import { DiscordIntegrationForm } from './forms/discord-integration';
import { GCSExportIntegrationForm } from './forms/gcs-export-integration';
@@ -13,6 +12,7 @@ import {
IntegrationCardLogo,
IntegrationCardLogoImage,
} from './integration-card';
+import type { RouterOutputs } from '@/trpc/client';
type IntegrationFormComponent = React.ComponentType<{
defaultValues?: RouterOutputs['integration']['get'];
@@ -42,55 +42,55 @@ const placeholderIcon = (
*/
export const CLIENT_INTEGRATIONS: Record<IIntegrationType, IClientIntegration> =
{
- slack: {
- type: 'slack',
- icon: (
- <IntegrationCardLogoImage
- src="https://play-lh.googleusercontent.com/mzJpTCsTW_FuR6YqOPaLHrSEVCSJuXzCljdxnCKhVZMcu6EESZBQTCHxMh8slVtnKqo"
- backgroundColor="#481449"
- />
- ),
- Form: SlackIntegrationForm,
- },
- discord: {
- type: 'discord',
- icon: (
- <IntegrationCardLogoImage
- src="https://static.vecteezy.com/system/resources/previews/006/892/625/non_2x/discord-logo-icon-editorial-free-vector.jpg"
- backgroundColor="#5864F2"
- />
- ),
- Form: DiscordIntegrationForm,
- },
- webhook: {
- type: 'webhook',
- icon: (
- <IntegrationCardLogo className="bg-foreground text-background">
- <WebhookIcon className="size-10" />
- </IntegrationCardLogo>
- ),
- Form: WebhookIntegrationForm,
- },
- app: { type: 'app', icon: placeholderIcon },
- email: { type: 'email', icon: placeholderIcon },
- s3_export: {
- type: 's3_export',
- icon: (
- <IntegrationCardLogo className="bg-[#FF9900] text-white">
- <CloudIcon className="size-10" />
- </IntegrationCardLogo>
- ),
- Form: S3ExportIntegrationForm,
- },
- gcs_export: {
- type: 'gcs_export',
- icon: (
- <IntegrationCardLogo className="bg-[#4285F4] text-white">
- <DatabaseIcon className="size-10" />
- </IntegrationCardLogo>
- ),
- Form: GCSExportIntegrationForm,
- },
+ slack: {
+ type: 'slack',
+ icon: (
+ <IntegrationCardLogoImage
+ backgroundColor="#481449"
+ src="https://play-lh.googleusercontent.com/mzJpTCsTW_FuR6YqOPaLHrSEVCSJuXzCljdxnCKhVZMcu6EESZBQTCHxMh8slVtnKqo"
+ />
+ ),
+ Form: SlackIntegrationForm,
+ },
+ discord: {
+ type: 'discord',
+ icon: (
+ <IntegrationCardLogoImage
+ backgroundColor="#5864F2"
+ src="https://static.vecteezy.com/system/resources/previews/006/892/625/non_2x/discord-logo-icon-editorial-free-vector.jpg"
+ />
+ ),
+ Form: DiscordIntegrationForm,
+ },
+ webhook: {
+ type: 'webhook',
+ icon: (
+ <IntegrationCardLogo className="bg-foreground text-background">
+ <WebhookIcon className="size-10" />
+ </IntegrationCardLogo>
+ ),
+ Form: WebhookIntegrationForm,
+ },
+ app: { type: 'app', icon: placeholderIcon },
+ email: { type: 'email', icon: placeholderIcon },
+ s3_export: {
+ type: 's3_export',
+ icon: (
+ <IntegrationCardLogo className="bg-[#FF9900] text-white">
+ <CloudIcon className="size-10" />
+ </IntegrationCardLogo>
+ ),
+ Form: S3ExportIntegrationForm,
+ },
+ gcs_export: {
+ type: 'gcs_export',
+ icon: (
+ <IntegrationCardLogo className="bg-[#4285F4] text-white">
+ <DatabaseIcon className="size-10" />
+ </IntegrationCardLogo>
+ ),
+ Form: GCSExportIntegrationForm,
+ },
};
export interface IIntegrationCatalogEntry {
@@ -106,7 +106,7 @@ export interface IIntegrationCatalogEntry {
*/
export const INTEGRATIONS: IIntegrationCatalogEntry[] =
INTEGRATION_DESCRIPTORS.filter(
- (d) => !('hidden' in d.catalog && d.catalog.hidden),
+ (d) => !('hidden' in d.catalog && d.catalog.hidden)
).map((d) => ({
type: d.type,
name: d.catalog.name,
diff --git a/apps/start/src/components/organization/billing-usage.tsx b/apps/start/src/components/organization/billing-usage.tsx
index 2d6b393f8..02c8ea5d8 100644
--- a/apps/start/src/components/organization/billing-usage.tsx
+++ b/apps/start/src/components/organization/billing-usage.tsx
@@ -1,4 +1,3 @@
-import { sum } from '@openpanel/common';
import type { IServiceOrganization } from '@openpanel/core';
import { useQuery } from '@tanstack/react-query';
import { Loader2Icon } from 'lucide-react';
@@ -11,6 +10,7 @@ import {
XAxis,
YAxis,
} from 'recharts';
+import { sum } from '../../utils/math';
import { BarShapeBlue } from '../charts/common-bar';
import {
useXAxisProps,
diff --git a/apps/start/src/components/organization/cancel-subscription-flow.tsx b/apps/start/src/components/organization/cancel-subscription-flow.tsx
index 91cca91c0..b675ca384 100644
--- a/apps/start/src/components/organization/cancel-subscription-flow.tsx
+++ b/apps/start/src/components/organization/cancel-subscription-flow.tsx
@@ -1,5 +1,5 @@
import type { IServiceOrganization } from '@openpanel/core';
-import type { ICancellationReason } from '@openpanel/validation';
+import type { ICancellationReason } from '@openpanel/core/modules/subscription/subscription.constants';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { CheckIcon } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
diff --git a/apps/start/src/components/organization/edit-organization.tsx b/apps/start/src/components/organization/edit-organization.tsx
index 235f09051..4bf54b13e 100644
--- a/apps/start/src/components/organization/edit-organization.tsx
+++ b/apps/start/src/components/organization/edit-organization.tsx
@@ -1,16 +1,15 @@
-import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
-import { Button } from '@/components/ui/button';
-import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
-import { useTRPC } from '@/integrations/trpc/react';
-import { handleError } from '@/trpc/client';
+import type { IServiceOrganization } from '@openpanel/core';
+import { zEditOrganization } from '@openpanel/core/modules/organization/organization.constants';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-
+import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
+import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
-import type { IServiceOrganization } from '@openpanel/core';
-import { zEditOrganization } from '@openpanel/validation';
+import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
+import { useTRPC } from '@/integrations/trpc/react';
+import { handleError } from '@/trpc/client';
const validator = zEditOrganization;
@@ -44,7 +43,7 @@ export default function EditOrganization({
queryClient.invalidateQueries(trpc.organization.get.pathFilter());
},
onError: handleError,
- }),
+ })
);
return (
@@ -57,7 +56,7 @@ export default function EditOrganization({
<WidgetHead className="flex items-center justify-between">
<span className="title">Details</span>
</WidgetHead>
- <WidgetBody className="gap-4 col">
+ <WidgetBody className="col gap-4">
<InputWithLabel
className="flex-1"
label="Name"
@@ -65,28 +64,28 @@ export default function EditOrganization({
defaultValue={organization?.name}
/>
<Controller
- name="timezone"
control={control}
+ name="timezone"
render={({ field }) => (
<WithLabel label="Timezone">
<Combobox
- placeholder="Select timezone"
+ className="w-full"
items={Intl.supportedValuesOf('timeZone').map((item) => ({
value: item,
label: item,
}))}
- value={field.value}
onChange={field.onChange}
- className="w-full"
+ placeholder="Select timezone"
+ value={field.value}
/>
</WithLabel>
)}
/>
<Button
+ className="self-end"
+ disabled={!formState.isDirty}
size="sm"
type="submit"
- disabled={!formState.isDirty}
- className="self-end"
>
Save
</Button>
diff --git a/apps/start/src/components/overview/filters/overview-filters-buttons.tsx b/apps/start/src/components/overview/filters/overview-filters-buttons.tsx
index 886b850f8..8c8e96919 100644
--- a/apps/start/src/components/overview/filters/overview-filters-buttons.tsx
+++ b/apps/start/src/components/overview/filters/overview-filters-buttons.tsx
@@ -1,7 +1,15 @@
+import {
+ getCohortIds,
+ type IChartEventFilter,
+ type IChartEventFilterOperator,
+ operators,
+} from '@openpanel/core/modules/report/report.constants';
+import { FilterIcon, X } from 'lucide-react';
+import type { Options as NuqsOptions } from 'nuqs';
+import { FilterOperatorSelect } from '@/components/report/sidebar/filters/FilterOperatorSelect';
import { Button } from '@/components/ui/button';
import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
-import { FilterOperatorSelect } from '@/components/report/sidebar/filters/FilterOperatorSelect';
import { useAppParams } from '@/hooks/use-app-params';
import { useCohorts } from '@/hooks/use-cohorts';
import {
@@ -13,14 +21,6 @@ import { pushModal } from '@/modals';
import type { OverviewFiltersProps } from '@/modals/overview-filters';
import { getPropertyLabel } from '@/translations/properties';
import { cn } from '@/utils/cn';
-import { operators } from '@openpanel/constants';
-import {
- getCohortIds,
- type IChartEventFilter,
- type IChartEventFilterOperator,
-} from '@openpanel/validation';
-import { FilterIcon, X } from 'lucide-react';
-import type { Options as NuqsOptions } from 'nuqs';
interface OverviewFiltersButtonsProps {
className?: string;
@@ -30,14 +30,14 @@ interface OverviewFiltersButtonsProps {
export function OverviewFilterButton(props: OverviewFiltersProps) {
return (
<Button
- variant="outline"
- responsive
icon={FilterIcon}
onClick={() =>
pushModal('OverviewFilters', {
...props,
})
}
+ responsive
+ variant="outline"
>
Filters
</Button>
@@ -71,59 +71,58 @@ function CohortFilterPill({
const cohorts = useCohorts({ projectId, includeCount: false });
const selectedIds = getCohortIds(filter);
const cohortItems = cohorts.map((c) => ({ value: c.id, label: c.name }));
- const valueLabel =
- selectedIds
- .map((id) => cohorts.find((c) => c.id === id)?.name)
- .filter(Boolean)
- .join(', ');
+ const valueLabel = selectedIds
+ .map((id) => cohorts.find((c) => c.id === id)?.name)
+ .filter(Boolean)
+ .join(', ');
return (
- <div className="flex items-stretch text-sm border rounded-md overflow-hidden h-8">
+ <div className="flex h-8 items-stretch overflow-hidden rounded-md border text-sm">
<button
- type="button"
+ className="cursor-pointer px-2 transition-colors hover:bg-accent"
onClick={() => pushModal('OverviewFilters', { nuqsOptions })}
- className="px-2 hover:bg-accent transition-colors cursor-pointer"
+ type="button"
>
Cohort
</button>
<DropdownMenuComposed
- onChange={onChangeOperator}
items={[
{ value: 'inCohort', label: 'In cohort' },
{ value: 'notInCohort', label: 'Not in cohort' },
]}
label="Operator"
+ onChange={onChangeOperator}
>
<button
+ className="cursor-pointer border-l px-2 lowercase opacity-50 transition-colors hover:bg-accent hover:opacity-100"
type="button"
- className="px-2 opacity-50 lowercase hover:opacity-100 hover:bg-accent transition-colors border-l cursor-pointer"
>
{filter.operator === 'inCohort' ? 'in cohort' : 'not in cohort'}
</button>
</DropdownMenuComposed>
<ComboboxAdvanced
items={cohortItems}
- value={selectedIds}
onChange={(next) =>
onChangeCohorts(
- next.filter((id): id is string => typeof id === 'string'),
+ next.filter((id): id is string => typeof id === 'string')
)
}
+ value={selectedIds}
>
<button
+ className="max-w-40 cursor-pointer truncate border-l px-2 font-semibold transition-colors hover:bg-accent"
type="button"
- className="px-2 font-semibold hover:bg-accent transition-colors border-l cursor-pointer max-w-40 truncate"
>
{valueLabel || (
- <span className="opacity-40 font-normal italic">pick cohort</span>
+ <span className="font-normal italic opacity-40">pick cohort</span>
)}
</button>
</ComboboxAdvanced>
<button
- type="button"
- onClick={onRemove}
- className="px-2 hover:bg-destructive hover:text-destructive-foreground transition-colors border-l cursor-pointer"
aria-label="Remove filter"
+ className="cursor-pointer border-l px-2 transition-colors hover:bg-destructive hover:text-destructive-foreground"
+ onClick={onRemove}
+ type="button"
>
<X className="size-3" />
</button>
@@ -149,21 +148,21 @@ function FilterPill({
filter.operator === 'isNull' || filter.operator === 'isNotNull';
return (
- <div className="flex items-stretch text-sm border rounded-md overflow-hidden h-8">
+ <div className="flex h-8 items-stretch overflow-hidden rounded-md border text-sm">
{/* Key — opens modal to change the property */}
<button
- type="button"
+ className="cursor-pointer px-2 transition-colors hover:bg-accent"
onClick={() => pushModal('OverviewFilters', { nuqsOptions })}
- className="px-2 hover:bg-accent transition-colors cursor-pointer"
+ type="button"
>
{getPropertyLabel(filter.name)}
</button>
{/* Operator dropdown */}
- <FilterOperatorSelect value={filter.operator} onChange={onChangeOperator}>
+ <FilterOperatorSelect onChange={onChangeOperator} value={filter.operator}>
<button
+ className="cursor-pointer border-l px-2 lowercase opacity-50 transition-colors hover:bg-accent hover:opacity-100"
type="button"
- className="px-2 opacity-50 lowercase hover:opacity-100 hover:bg-accent transition-colors border-l cursor-pointer"
>
{operators[filter.operator]}
</button>
@@ -173,17 +172,17 @@ function FilterPill({
{!noValueNeeded && (
<ComboboxAdvanced
items={potentialValues.map((v) => ({ value: v, label: v }))}
- value={filter.value}
onChange={onChangeValue}
+ value={filter.value}
>
<button
+ className="max-w-40 cursor-pointer truncate border-l px-2 font-semibold transition-colors hover:bg-accent"
type="button"
- className="px-2 font-semibold hover:bg-accent transition-colors border-l cursor-pointer max-w-40 truncate"
>
{filter.value.length > 0 ? (
filter.value.join(', ')
) : (
- <span className="opacity-40 font-normal italic">pick value</span>
+ <span className="font-normal italic opacity-40">pick value</span>
)}
</button>
</ComboboxAdvanced>
@@ -191,10 +190,10 @@ function FilterPill({
{/* Remove */}
<button
- type="button"
- onClick={onRemove}
- className="px-2 hover:bg-destructive hover:text-destructive-foreground transition-colors border-l cursor-pointer"
aria-label="Remove filter"
+ className="cursor-pointer border-l px-2 transition-colors hover:bg-destructive hover:text-destructive-foreground"
+ onClick={onRemove}
+ type="button"
>
<X className="size-3" />
</button>
@@ -210,7 +209,9 @@ export function OverviewFiltersButtons({
const [filters, setFilter, setFilters, removeFilter] =
useEventQueryFilters(nuqsOptions);
- if (filters.length === 0 && events.length === 0) return null;
+ if (filters.length === 0 && events.length === 0) {
+ return null;
+ }
const updateCohortFilter = (updated: IChartEventFilter) => {
setFilters((prev) =>
@@ -224,8 +225,8 @@ export function OverviewFiltersButtons({
...(updated.cohortIds ? { cohortIds: updated.cohortIds } : {}),
...(updated.cohortId ? { cohortId: updated.cohortId } : {}),
}
- : f,
- ),
+ : f
+ )
);
};
@@ -233,11 +234,11 @@ export function OverviewFiltersButtons({
<div className={cn('flex flex-wrap gap-2', className)}>
{events.map((event) => (
<Button
+ icon={X}
key={event}
+ onClick={() => setEvents((p) => p.filter((e) => e !== event))}
size="sm"
variant="outline"
- icon={X}
- onClick={() => setEvents((p) => p.filter((e) => e !== event))}
>
<strong className="font-semibold">{event}</strong>
</Button>
@@ -248,13 +249,9 @@ export function OverviewFiltersButtons({
if (isCohort) {
return (
<CohortFilterPill
- key={filter.name}
filter={filter}
+ key={filter.name}
nuqsOptions={nuqsOptions}
- onRemove={() => removeFilter(filter.name)}
- onChangeOperator={(operator) =>
- updateCohortFilter({ ...filter, operator })
- }
onChangeCohorts={(cohortIds) =>
updateCohortFilter({
...filter,
@@ -262,21 +259,25 @@ export function OverviewFiltersButtons({
cohortIds,
})
}
+ onChangeOperator={(operator) =>
+ updateCohortFilter({ ...filter, operator })
+ }
+ onRemove={() => removeFilter(filter.name)}
/>
);
}
return (
<FilterPill
- key={filter.name}
filter={filter}
+ key={filter.name}
nuqsOptions={nuqsOptions}
- onRemove={() => removeFilter(filter.name)}
onChangeOperator={(operator) =>
setFilter(filter.name, filter.value, operator)
}
onChangeValue={(value) =>
setFilter(filter.name, value, filter.operator)
}
+ onRemove={() => removeFilter(filter.name)}
/>
);
})}
diff --git a/apps/start/src/components/overview/overview-chart-toggle.tsx b/apps/start/src/components/overview/overview-chart-toggle.tsx
index d446fa06e..5adc0b648 100644
--- a/apps/start/src/components/overview/overview-chart-toggle.tsx
+++ b/apps/start/src/components/overview/overview-chart-toggle.tsx
@@ -1,8 +1,6 @@
+import type { IChartType } from '@openpanel/core/modules/report/report.constants';
import { BarChartIcon, LineChartIcon } from 'lucide-react';
import type { Dispatch, SetStateAction } from 'react';
-
-import type { IChartType } from '@openpanel/validation';
-
import { Button } from '../ui/button';
interface Props {
@@ -12,11 +10,11 @@ interface Props {
export function OverviewChartToggle({ chartType, setChartType }: Props) {
return (
<Button
- size={'icon'}
- variant={'ghost'}
onClick={() => {
setChartType((p) => (p === 'linear' ? 'bar' : 'linear'));
}}
+ size={'icon'}
+ variant={'ghost'}
>
{chartType === 'bar' ? (
<LineChartIcon size={16} />
diff --git a/apps/start/src/components/overview/overview-interval.tsx b/apps/start/src/components/overview/overview-interval.tsx
index aa0b7cf17..cb75f99ae 100644
--- a/apps/start/src/components/overview/overview-interval.tsx
+++ b/apps/start/src/components/overview/overview-interval.tsx
@@ -1,11 +1,5 @@
-import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
-import {
- isHourIntervalEnabledByRange,
- isMinuteIntervalEnabledByRange,
-} from '@openpanel/constants';
-import { ClockIcon } from 'lucide-react';
import { ReportInterval } from '../report/ReportInterval';
-import { Combobox } from '../ui/combobox';
+import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
export function OverviewInterval() {
const { interval, setInterval, range, startDate, endDate } =
@@ -13,12 +7,12 @@ export function OverviewInterval() {
return (
<ReportInterval
+ chartType="linear"
+ endDate={endDate}
interval={interval}
onChange={setInterval}
range={range}
- chartType="linear"
startDate={startDate}
- endDate={endDate}
/>
);
}
diff --git a/apps/start/src/components/overview/overview-line-chart.tsx b/apps/start/src/components/overview/overview-line-chart.tsx
index 5ad30012d..3775d6832 100644
--- a/apps/start/src/components/overview/overview-line-chart.tsx
+++ b/apps/start/src/components/overview/overview-line-chart.tsx
@@ -1,5 +1,7 @@
-import type { timeWindows } from '@openpanel/constants';
-import type { IInterval } from '@openpanel/validation';
+import type {
+ IInterval,
+ timeWindows,
+} from '@openpanel/core/modules/report/report.constants';
import { curveMonotoneX } from '@visx/curve';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Grid } from '../charts/grid';
diff --git a/apps/start/src/components/overview/overview-metric-card.tsx b/apps/start/src/components/overview/overview-metric-card.tsx
index 0fb0e74ab..0dd9b414e 100644
--- a/apps/start/src/components/overview/overview-metric-card.tsx
+++ b/apps/start/src/components/overview/overview-metric-card.tsx
@@ -1,10 +1,7 @@
-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
-import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';
-import { cn } from '@/utils/cn';
-import { timeWindows } from '@openpanel/constants';
-import { getPreviousMetric } from '@openpanel/common';
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
+import { timeWindows } from '@openpanel/core/modules/report/report.constants';
import { type ReactNode, useState } from 'react';
+import { getPreviousMetric } from '../../utils/math';
import { Bar } from '../charts/bar';
import { BarChart } from '../charts/bar-chart';
import {
@@ -13,6 +10,9 @@ import {
} from '../charts/op-stat-hover-bridge';
import { PreviousDiffIndicatorPure } from '../report-chart/common/previous-diff-indicator';
import { Skeleton } from '../skeleton';
+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
+import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';
+import { cn } from '@/utils/cn';
import { formatDate as formatAbsoluteDate, timeAgo } from '@/utils/date';
const PRIMARY_COLOR = 'var(--chart-0)';
@@ -75,7 +75,7 @@ export function OverviewMetricCard({
<MetricCardShell active={active} onClick={onClick}>
<div className="px-3 pt-2.5">
<div className="flex items-start justify-between gap-2">
- <span className="truncate text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
+ <span className="truncate font-medium text-[10px] text-muted-foreground uppercase tracking-wider">
{label}
</span>
{isLoading ? null : (
@@ -90,10 +90,10 @@ export function OverviewMetricCard({
{isLoading ? (
<Skeleton className="h-5 w-20" />
) : (
- <MetricValue value={displayValue} unit={unit} />
+ <MetricValue unit={unit} value={displayValue} />
)}
</div>
- <div className="mt-0.5 truncate text-[11px] leading-none text-muted-foreground">
+ <div className="mt-0.5 truncate text-[11px] text-muted-foreground leading-none">
{displayLabel}
</div>
</div>
@@ -101,21 +101,21 @@ export function OverviewMetricCard({
<div className="mt-1.5 h-[40px]">
{data.length > 0 && (
<BarChart
- data={data}
- xDataKey="date"
+ animationDuration={0}
aspectRatio="auto"
+ barGap={0.25}
className="h-full"
+ data={data}
margin={{ top: 6, right: 0, bottom: 0, left: 0 }}
- animationDuration={0}
- barGap={0.25}
+ xDataKey="date"
>
<OPStatHoverBridge onHoverChange={setHover} />
<Bar
+ animate={false}
dataKey="current"
- fill={PRIMARY_COLOR}
fadedOpacity={0.35}
+ fill={PRIMARY_COLOR}
lineCap={1}
- animate={false}
/>
</BarChart>
)}
@@ -143,15 +143,15 @@ export function MetricCardShell({
const Tag: 'button' | 'div' = onClick ? 'button' : 'div';
return (
<Tag
- type={onClick ? 'button' : undefined}
- onClick={onClick}
className={cn(
'group relative flex flex-col overflow-hidden text-left',
'shadow-[0_0_0_0.5px] shadow-border transition-colors',
active ? 'bg-def-100' : 'bg-card hover:bg-def-100/50',
onClick && 'cursor-pointer',
- className,
+ className
)}
+ onClick={onClick}
+ type={onClick ? 'button' : undefined}
>
{active && (
<span
@@ -180,7 +180,9 @@ function MetricValue({ value, unit }: { value: number; unit?: MetricUnit }) {
if (unit === 'timeAgo') {
return (
- <span className={VALUE_CLASS}>{value ? timeAgo(new Date(value)) : 'N/A'}</span>
+ <span className={VALUE_CLASS}>
+ {value ? timeAgo(new Date(value)) : 'N/A'}
+ </span>
);
}
@@ -200,7 +202,7 @@ function MetricValue({ value, unit }: { value: number; unit?: MetricUnit }) {
return (
<>
<span className={VALUE_CLASS}>{number.format(value)}</span>
- <span className="font-mono font-medium text-sm text-muted-foreground">
+ <span className="font-medium font-mono text-muted-foreground text-sm">
%
</span>
</>
diff --git a/apps/start/src/components/overview/overview-metrics.tsx b/apps/start/src/components/overview/overview-metrics.tsx
index 8449d9837..a8dfdabf3 100644
--- a/apps/start/src/components/overview/overview-metrics.tsx
+++ b/apps/start/src/components/overview/overview-metrics.tsx
@@ -1,4 +1,4 @@
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import { useQuery } from '@tanstack/react-query';
import { curveMonotoneX } from '@visx/curve';
import { DollarSignIcon } from 'lucide-react';
diff --git a/apps/start/src/components/overview/overview-top-devices.tsx b/apps/start/src/components/overview/overview-top-devices.tsx
index 9605a63d4..ed56c4574 100644
--- a/apps/start/src/components/overview/overview-top-devices.tsx
+++ b/apps/start/src/components/overview/overview-top-devices.tsx
@@ -1,12 +1,7 @@
-import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
-import { useMemo, useState } from 'react';
-
-import { NOT_SET_VALUE } from '@openpanel/constants';
-import type { IChartType } from '@openpanel/validation';
-
-import { useTRPC } from '@/integrations/trpc/react';
-import { pushModal } from '@/modals';
+import type { IChartType } from '@openpanel/core/modules/report/report.constants';
+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';
import { useQuery } from '@tanstack/react-query';
+import { useMemo, useState } from 'react';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { Widget, WidgetBody } from '../widget';
import { OVERVIEW_COLUMNS_NAME } from './overview-constants';
@@ -23,6 +18,9 @@ import {
} from './overview-widget-table';
import { useOverviewOptions } from './useOverviewOptions';
import { useOverviewWidget } from './useOverviewWidget';
+import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
+import { useTRPC } from '@/integrations/trpc/react';
+import { pushModal } from '@/modals';
interface OverviewTopDevicesProps {
projectId: string;
@@ -68,10 +66,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top devices',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -105,10 +103,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top browser',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -149,10 +147,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top Browser Version',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -186,10 +184,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top OS',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -230,10 +228,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top OS version',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -267,10 +265,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top Brands',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -311,10 +309,10 @@ export default function OverviewTopDevices({
],
chartType,
lineType: 'monotone',
- interval: interval,
+ interval,
name: 'Top Models',
- range: range,
- previous: previous,
+ range,
+ previous,
metric: 'sum',
},
},
@@ -333,7 +331,7 @@ export default function OverviewTopDevices({
column: widget.key,
startDate,
endDate,
- }),
+ })
);
const seriesQuery = useQuery(
@@ -350,8 +348,8 @@ export default function OverviewTopDevices({
},
{
enabled: view === 'chart',
- },
- ),
+ }
+ )
);
const filteredData = useMemo(() => {
@@ -372,13 +370,13 @@ export default function OverviewTopDevices({
<>
<Widget className="col-span-6 md:col-span-3">
<WidgetHeadSearchable
- tabs={tabs}
activeTab={widget.key}
- onTabChange={setWidget}
- searchValue={searchQuery}
+ className="border-b-0 pb-2"
onSearchChange={setSearchQuery}
+ onTabChange={setWidget}
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
- className="border-b-0 pb-2"
+ searchValue={searchQuery}
+ tabs={tabs}
/>
<WidgetBody className="p-0">
{view === 'chart' ? (
@@ -398,19 +396,18 @@ export default function OverviewTopDevices({
<OverviewWidgetTableLoading />
) : (
<OverviewWidgetTableGeneric
- data={filteredData}
column={{
name: OVERVIEW_COLUMNS_NAME[widget.key],
render(item) {
return (
- <div className="row items-center gap-2 min-w-0 relative">
+ <div className="row relative min-w-0 items-center gap-2">
<SerieIcon name={item.name || NOT_SET_VALUE} />
<button
- type="button"
className="truncate"
onClick={() => {
setFilter(widget.key, item.name);
}}
+ type="button"
>
{item.name || 'Not set'}
</button>
@@ -418,6 +415,7 @@ export default function OverviewTopDevices({
);
},
}}
+ data={filteredData}
/>
)}
</WidgetBody>
diff --git a/apps/start/src/components/overview/overview-top-geo.tsx b/apps/start/src/components/overview/overview-top-geo.tsx
index eb2409e15..ae6723323 100644
--- a/apps/start/src/components/overview/overview-top-geo.tsx
+++ b/apps/start/src/components/overview/overview-top-geo.tsx
@@ -1,14 +1,8 @@
-import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
-import { useMemo, useState } from 'react';
-
-import type { IChartType } from '@openpanel/validation';
-
-import { useTRPC } from '@/integrations/trpc/react';
-import { pushModal } from '@/modals';
-import { countries } from '@/translations/countries';
-import { NOT_SET_VALUE } from '@openpanel/constants';
+import type { IChartType } from '@openpanel/core/modules/report/report.constants';
+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';
import { useQuery } from '@tanstack/react-query';
import { ChevronRightIcon } from 'lucide-react';
+import { useMemo, useState } from 'react';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { Widget, WidgetBody } from '../widget';
import { OVERVIEW_COLUMNS_NAME } from './overview-constants';
@@ -30,6 +24,10 @@ import {
} from './overview-widget-table';
import { useOverviewOptions } from './useOverviewOptions';
import { useOverviewWidgetV2 } from './useOverviewWidget';
+import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
+import { useTRPC } from '@/integrations/trpc/react';
+import { pushModal } from '@/modals';
+import { countries } from '@/translations/countries';
interface OverviewTopGeoProps {
projectId: string;
@@ -72,7 +70,7 @@ export default function OverviewTopGeo({
column: widget.key,
startDate,
endDate,
- }),
+ })
);
const seriesQuery = useQuery(
@@ -89,8 +87,8 @@ export default function OverviewTopGeo({
},
{
enabled: view === 'chart',
- },
- ),
+ }
+ )
);
const filteredData = useMemo(() => {
@@ -105,7 +103,7 @@ export default function OverviewTopGeo({
item.prefix?.toLowerCase().includes(queryLower) ||
countries[item.name as keyof typeof countries]
?.toLowerCase()
- .includes(queryLower),
+ .includes(queryLower)
);
}, [query.data, searchQuery]);
@@ -118,13 +116,13 @@ export default function OverviewTopGeo({
<>
<Widget className="col-span-6 md:col-span-3">
<WidgetHeadSearchable
- tabs={tabs}
activeTab={widget.key}
- onTabChange={setWidget}
- searchValue={searchQuery}
+ className="border-b-0 pb-2"
onSearchChange={setSearchQuery}
+ onTabChange={setWidget}
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
- className="border-b-0 pb-2"
+ searchValue={searchQuery}
+ tabs={tabs}
/>
<WidgetBody className="p-0">
{view === 'chart' ? (
@@ -144,17 +142,15 @@ export default function OverviewTopGeo({
<OverviewWidgetTableLoading />
) : (
<OverviewWidgetTableGeneric
- data={filteredData}
column={{
name: OVERVIEW_COLUMNS_NAME[widget.key],
render(item) {
return (
- <div className="row items-center gap-2 min-w-0 relative">
+ <div className="row relative min-w-0 items-center gap-2">
<SerieIcon
name={item.prefix || item.name || NOT_SET_VALUE}
/>
<button
- type="button"
className="truncate"
onClick={() => {
if (widget.key === 'country') {
@@ -164,9 +160,10 @@ export default function OverviewTopGeo({
}
setFilter(widget.key, item.name);
}}
+ type="button"
>
{item.prefix && (
- <span className="mr-1 row inline-flex items-center gap-1">
+ <span className="row mr-1 inline-flex items-center gap-1">
<span>
{countries[
item.prefix as keyof typeof countries
@@ -185,6 +182,7 @@ export default function OverviewTopGeo({
);
},
}}
+ data={filteredData}
/>
)}
</WidgetBody>
@@ -199,13 +197,13 @@ export default function OverviewTopGeo({
/>
<div className="flex-1" />
<OverviewViewToggle />
- <span className="text-sm text-muted-foreground pr-2 ml-2">
+ <span className="ml-2 pr-2 text-muted-foreground text-sm">
Geo data provided by{' '}
<a
+ className="hover:underline"
href="https://ipdata.co"
- target="_blank"
rel="noopener noreferrer nofollow"
- className="hover:underline"
+ target="_blank"
>
MaxMind
</a>
diff --git a/apps/start/src/components/overview/overview-top-sources.tsx b/apps/start/src/components/overview/overview-top-sources.tsx
index 4c8513814..4d53d00ae 100644
--- a/apps/start/src/components/overview/overview-top-sources.tsx
+++ b/apps/start/src/components/overview/overview-top-sources.tsx
@@ -1,10 +1,6 @@
-import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
-import { useMemo, useState } from 'react';
-
-import { useTRPC } from '@/integrations/trpc/react';
-import { pushModal } from '@/modals';
-import { NOT_SET_VALUE } from '@openpanel/constants';
+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';
import { useQuery } from '@tanstack/react-query';
+import { useMemo, useState } from 'react';
import { SerieIcon } from '../report-chart/common/serie-icon';
import { Widget, WidgetBody } from '../widget';
import { OVERVIEW_COLUMNS_NAME } from './overview-constants';
@@ -21,6 +17,9 @@ import {
} from './overview-widget-table';
import { useOverviewOptions } from './useOverviewOptions';
import { useOverviewWidgetV2 } from './useOverviewWidget';
+import { useEventQueryFilters } from '@/hooks/use-event-query-filters';
+import { useTRPC } from '@/integrations/trpc/react';
+import { pushModal } from '@/modals';
interface OverviewTopSourcesProps {
projectId: string;
@@ -79,7 +78,7 @@ export default function OverviewTopSources({
column: widget.key,
startDate,
endDate,
- }),
+ })
);
const seriesQuery = useQuery(
@@ -96,8 +95,8 @@ export default function OverviewTopSources({
},
{
enabled: view === 'chart',
- },
- ),
+ }
+ )
);
const filteredData = useMemo(() => {
@@ -118,13 +117,13 @@ export default function OverviewTopSources({
<>
<Widget className="col-span-6 md:col-span-3">
<WidgetHeadSearchable
- tabs={tabs}
activeTab={widget.key}
- onTabChange={setWidget}
- searchValue={searchQuery}
+ className="border-b-0 pb-2"
onSearchChange={setSearchQuery}
+ onTabChange={setWidget}
searchPlaceholder={`Search ${widget.btn.toLowerCase()}`}
- className="border-b-0 pb-2"
+ searchValue={searchQuery}
+ tabs={tabs}
/>
<WidgetBody className="p-0">
{view === 'chart' ? (
@@ -144,26 +143,25 @@ export default function OverviewTopSources({
<OverviewWidgetTableLoading />
) : (
<OverviewWidgetTableGeneric
- data={filteredData}
column={{
name: OVERVIEW_COLUMNS_NAME[widget.key],
render(item) {
return (
- <div className="row items-center gap-2 min-w-0 relative">
+ <div className="row relative min-w-0 items-center gap-2">
<SerieIcon name={item.name || NOT_SET_VALUE} />
<button
- type="button"
className="truncate"
onClick={() => {
if (widget.key.startsWith('utm_')) {
setFilter(
`properties.__query.${widget.key}`,
- item.name,
+ item.name
);
} else {
setFilter(widget.key, item.name);
}
}}
+ type="button"
>
{(item.name || 'Direct / Not set')
.replace(/https?:\/\//, '')
@@ -173,6 +171,7 @@ export default function OverviewTopSources({
);
},
}}
+ data={filteredData}
/>
)}
</WidgetBody>
diff --git a/apps/start/src/components/overview/useOverviewOptions.ts b/apps/start/src/components/overview/useOverviewOptions.ts
index 47640fe5e..dd8f56cf2 100644
--- a/apps/start/src/components/overview/useOverviewOptions.ts
+++ b/apps/start/src/components/overview/useOverviewOptions.ts
@@ -1,3 +1,10 @@
+import type { IChartRange } from '@openpanel/core/modules/report/report.constants';
+import {
+ getDefaultIntervalByDates,
+ getDefaultIntervalByRange,
+ intervals,
+ timeWindows,
+} from '@openpanel/core/modules/report/report.constants';
import { differenceInCalendarMonths } from 'date-fns';
import {
parseAsInteger,
@@ -5,31 +12,23 @@ import {
parseAsStringEnum,
useQueryState,
} from 'nuqs';
-
import { useCookieStore } from '@/hooks/use-cookie-store';
import { mapKeys } from '@/utils/object-to-zod-enums';
-import {
- getDefaultIntervalByDates,
- getDefaultIntervalByRange,
- intervals,
- timeWindows,
-} from '@openpanel/constants';
-import type { IChartRange } from '@openpanel/validation';
const nuqsOptions = { history: 'push' } as const;
export function useOverviewOptions() {
const [startDate, setStartDate] = useQueryState(
'start',
- parseAsString.withOptions(nuqsOptions),
+ parseAsString.withOptions(nuqsOptions)
);
const [endDate, setEndDate] = useQueryState(
'end',
- parseAsString.withOptions(nuqsOptions),
+ parseAsString.withOptions(nuqsOptions)
);
const [cookieRange, setCookieRange] = useCookieStore<IChartRange>(
'range',
- '7d',
+ '7d'
);
const [range, setRange] = useQueryState(
'range',
@@ -38,14 +37,14 @@ export function useOverviewOptions() {
.withOptions({
...nuqsOptions,
clearOnDefault: false,
- }),
+ })
);
const [overrideInterval, setInterval] = useQueryState(
'overrideInterval',
parseAsStringEnum(mapKeys(intervals)).withOptions({
...nuqsOptions,
clearOnDefault: false,
- }),
+ })
);
const interval =
@@ -55,7 +54,7 @@ export function useOverviewOptions() {
const [metric, setMetric] = useQueryState(
'metric',
- parseAsInteger.withDefault(0).withOptions(nuqsOptions),
+ parseAsInteger.withDefault(0).withOptions(nuqsOptions)
);
return {
diff --git a/apps/start/src/components/page/gsc-cannibalization.tsx b/apps/start/src/components/page/gsc-cannibalization.tsx
index 50b590dce..f30a40c95 100644
--- a/apps/start/src/components/page/gsc-cannibalization.tsx
+++ b/apps/start/src/components/page/gsc-cannibalization.tsx
@@ -1,4 +1,7 @@
-import type { IChartRange, IInterval } from '@openpanel/validation';
+import type {
+ IChartRange,
+ IInterval,
+} from '@openpanel/core/modules/report/report.constants';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { AlertCircleIcon, ChevronsUpDownIcon, SearchIcon } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
diff --git a/apps/start/src/components/profiles/profile-charts.tsx b/apps/start/src/components/profiles/profile-charts.tsx
index 21428ea6d..77562f020 100644
--- a/apps/start/src/components/profiles/profile-charts.tsx
+++ b/apps/start/src/components/profiles/profile-charts.tsx
@@ -1,9 +1,8 @@
-import { ReportChart } from '@/components/report-chart';
-import { Widget, WidgetBody } from '@/components/widget';
+import type { IReport } from '@openpanel/core/modules/report/report.constants';
import { memo } from 'react';
-
-import type { IReport } from '@openpanel/validation';
import { WidgetHead } from '../overview/overview-widget';
+import { ReportChart } from '@/components/report-chart';
+import { Widget, WidgetBody } from '@/components/widget';
type Props = {
profileId: string;
@@ -103,5 +102,5 @@ export const ProfileCharts = memo(
},
(a, b) => {
return a.profileId === b.profileId && a.projectId === b.projectId;
- },
+ }
);
diff --git a/apps/start/src/components/report-chart/aspect-container.tsx b/apps/start/src/components/report-chart/aspect-container.tsx
index a331ce54b..3cac791e0 100644
--- a/apps/start/src/components/report-chart/aspect-container.tsx
+++ b/apps/start/src/components/report-chart/aspect-container.tsx
@@ -1,8 +1,6 @@
-import { cn } from '@/utils/cn';
-
-import { DEFAULT_ASPECT_RATIO } from '@openpanel/constants';
-
+import { DEFAULT_ASPECT_RATIO } from '@openpanel/core/modules/report/report.constants';
import { useReportChartContext } from './context';
+import { cn } from '@/utils/cn';
interface AspectContainerProps {
children: React.ReactNode;
diff --git a/apps/start/src/components/report-chart/bar/chart.tsx b/apps/start/src/components/report-chart/bar/chart.tsx
index 2d7e0ffc0..31e65a641 100644
--- a/apps/start/src/components/report-chart/bar/chart.tsx
+++ b/apps/start/src/components/report-chart/bar/chart.tsx
@@ -1,3 +1,12 @@
+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';
+import { DropdownMenuPortal } from '@radix-ui/react-dropdown-menu';
+import { SearchIcon } from 'lucide-react';
+import { useMemo, useState } from 'react';
+import { round } from '../../../utils/math';
+import { SerieIcon } from '../common/serie-icon';
+import { SerieName } from '../common/serie-name';
+import { useReportChartContext } from '../context';
+import { DeltaChip } from '@/components/delta-chip';
import {
DropdownMenu,
DropdownMenuContent,
@@ -17,18 +26,6 @@ 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 { 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'
@@ -61,7 +58,7 @@ export function Chart({ data }: Props) {
// Calculate original ranks (based on count descending - default sort)
const seriesWithOriginalRank = useMemo(() => {
const sortedByCount = [...allSeriesWithIndex].sort(
- (a, b) => b.metrics.sum - a.metrics.sum,
+ (a, b) => b.metrics.sum - a.metrics.sum
);
const rankMap = new Map<string, number>();
sortedByCount.forEach((serie, idx) => {
@@ -81,7 +78,7 @@ export function Chart({ data }: Props) {
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase();
filtered = filtered.filter((serie) =>
- serie.names.some((name) => name.toLowerCase().includes(query)),
+ serie.names.some((name) => name.toLowerCase().includes(query))
);
}
@@ -119,23 +116,23 @@ export function Chart({ data }: Props) {
return (
<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="flex items-center gap-3 border-def-200 border-b p-4 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" />
+ <SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
- type="text"
- placeholder="Filter by name"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Filter by name"
size="sm"
+ type="text"
+ value={searchQuery}
/>
</div>
<Select
- value={sortBy}
onValueChange={(value) => setSortBy(value as SortOption)}
+ value={sortBy}
>
- <SelectTrigger size="sm" className="w-[180px]">
+ <SelectTrigger className="w-[180px]" size="sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -165,34 +162,36 @@ export function Chart({ data }: Props) {
const color = getChartColor(serie.index);
const percentOfTotal = round(
(serie.metrics.sum / totalSum) * 100,
- 1,
+ 1
);
return (
<div
- key={serie.id}
className={cn(
- 'group relative px-4 py-3 transition-colors overflow-hidden',
- isClickable && 'cursor-pointer',
+ 'group relative overflow-hidden px-4 py-3 transition-colors',
+ isClickable && 'cursor-pointer'
)}
- role={isClickable ? 'button' : undefined}
- tabIndex={isClickable ? 0 : undefined}
+ key={serie.id}
onClick={() => {
if (isClickable && !isDropDownEnabled) {
onClick?.(serie);
}
}}
onKeyDown={(e) => {
- if (!isClickable || isDropDownEnabled) return;
+ if (!isClickable || isDropDownEnabled) {
+ return;
+ }
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onClick?.(serie);
}
}}
+ role={isClickable ? 'button' : undefined}
+ tabIndex={isClickable ? 0 : undefined}
>
{/* 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"
+ className="pointer-events-none absolute -top-10 -left-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%)`,
}}
@@ -214,7 +213,7 @@ export function Chart({ data }: Props) {
className="h-2 w-2 rounded-full"
style={{ backgroundColor: color }}
/>
- <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
+ <span className="font-semibold text-[10px] text-muted-foreground uppercase tracking-widest">
Rank {serie.originalRank}
</span>
</div>
@@ -241,7 +240,7 @@ export function Chart({ data }: Props) {
<div
className={cn(
'min-w-0',
- isDropDownEnabled && 'cursor-pointer',
+ isDropDownEnabled && 'cursor-pointer'
)}
{...(isClickable && !isDropDownEnabled
? {
@@ -253,8 +252,8 @@ export function Chart({ data }: Props) {
: {})}
>
<SerieName
+ className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap font-semibold text-sm tracking-tight"
name={serie.names}
- className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm font-semibold tracking-tight"
/>
</div>
</DropdownMenuTrigger>
@@ -269,7 +268,7 @@ export function Chart({ data }: Props) {
}}
>
{item.icon && (
- <item.icon size={16} className="mr-2" />
+ <item.icon className="mr-2" size={16} />
)}
{item.title}
</DropdownMenuItem>
@@ -282,18 +281,18 @@ export function Chart({ data }: Props) {
<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">
+ <div className="font-mono font-semibold text-base tracking-tight">
{number.format(serie.metrics.sum)}
</div>
{previous && serie.metrics.previous?.[metric] && (
<DeltaChip
+ size="sm"
variant={
serie.metrics.previous[metric].state ===
'positive'
? 'inc'
: 'dec'
}
- size="sm"
>
{serie.metrics.previous[metric].diff?.toFixed(1)}%
</DeltaChip>
diff --git a/apps/start/src/components/report-chart/common/axis.tsx b/apps/start/src/components/report-chart/common/axis.tsx
index 2b25782b6..eca3763c0 100644
--- a/apps/start/src/components/report-chart/common/axis.tsx
+++ b/apps/start/src/components/report-chart/common/axis.tsx
@@ -1,11 +1,10 @@
-import { useDebounceFn } from '@/hooks/use-debounce-fn';
-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
-import { useNumber } from '@/hooks/use-numer-formatter';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import { isNil } from 'ramda';
import { useRef, useState } from 'react';
import type { AxisDomain } from 'recharts/types/util/types';
-
-import type { IInterval } from '@openpanel/validation';
+import { useDebounceFn } from '@/hooks/use-debounce-fn';
+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
+import { useNumber } from '@/hooks/use-numer-formatter';
export const AXIS_FONT_PROPS = {
fontSize: 8,
className: 'font-mono',
@@ -41,7 +40,7 @@ export const useYAxisProps = (options?: {
const tick = options?.tickFormatter
? options.tickFormatter(value)
: number.short(value);
- if(!options?.width) {
+ if (!options?.width) {
const newWidth = getYAxisWidth(tick);
ref.current.push(newWidth);
setWidthDebounced(Math.max(...ref.current));
@@ -69,7 +68,7 @@ export const useXAxisProps = (
} = {
hide: false,
interval: 'auto',
- },
+ }
) => {
const formatDate = useFormatDateInterval({
interval: interval === 'auto' ? 'day' : interval,
diff --git a/apps/start/src/components/report-chart/common/report-chart-tooltip.tsx b/apps/start/src/components/report-chart/common/report-chart-tooltip.tsx
index 02c024690..ed1b21a4c 100644
--- a/apps/start/src/components/report-chart/common/report-chart-tooltip.tsx
+++ b/apps/start/src/components/report-chart/common/report-chart-tooltip.tsx
@@ -1,15 +1,4 @@
-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
-import { useNumber } from '@/hooks/use-numer-formatter';
-import type { IRechartPayloadItem } from '@/hooks/use-rechart-data-model';
-import React from 'react';
-
-import {
- ChartTooltipHeader,
- ChartTooltipItem,
- createChartTooltip,
-} from '@/components/charts/chart-tooltip';
-import type { RouterOutputs } from '@/trpc/client';
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import {
format,
isSameDay,
@@ -18,15 +7,25 @@ import {
isSameMonth,
isSameWeek,
} from 'date-fns';
+import React from 'react';
import { useReportChartContext } from '../context';
import { PreviousDiffIndicator } from './previous-diff-indicator';
import { SerieIcon } from './serie-icon';
import { SerieName } from './serie-name';
+import {
+ ChartTooltipHeader,
+ ChartTooltipItem,
+ createChartTooltip,
+} from '@/components/charts/chart-tooltip';
+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
+import { useNumber } from '@/hooks/use-numer-formatter';
+import type { IRechartPayloadItem } from '@/hooks/use-rechart-data-model';
+import type { RouterOutputs } from '@/trpc/client';
const getMatchingReferences = (
interval: IInterval,
references: RouterOutputs['reference']['getChartReferences'],
- date: Date,
+ date: Date
) => {
return references.filter((reference) => {
if (interval === 'minute') {
@@ -76,15 +75,14 @@ export const ReportChartTooltip = createChartTooltip<Data, Context>(
const matchingReferences = getMatchingReferences(
interval,
references ?? [],
- new Date(firstItem.date),
+ new Date(firstItem.date)
);
// Get all payload items from the first data point
const payloadItems = Object.keys(firstItem)
.filter((key) => key.endsWith(':payload'))
.map(
- (key) =>
- firstItem[key as keyof typeof firstItem] as IRechartPayloadItem,
+ (key) => firstItem[key as keyof typeof firstItem] as IRechartPayloadItem
)
.filter((item) => item && typeof item === 'object' && 'id' in item);
@@ -108,7 +106,7 @@ export const ReportChartTooltip = createChartTooltip<Data, Context>(
<SerieIcon name={item.names} />
<SerieName name={item.names} />
</div>
- <div className="flex justify-between gap-8 font-mono font-medium">
+ <div className="flex justify-between gap-8 font-medium font-mono">
<div className="row gap-1">
{number.formatWithUnit(item.count, unit)}
{!!item.previous && (
@@ -132,11 +130,11 @@ export const ReportChartTooltip = createChartTooltip<Data, Context>(
<hr className="border-border" />
{matchingReferences.map((reference) => (
<div
+ className="row items-center justify-between"
key={reference.id}
- className="row justify-between items-center"
>
<div className="font-medium text-sm">{reference.title}</div>
- <div className="font-medium text-sm shrink-0 text-muted-foreground">
+ <div className="shrink-0 font-medium text-muted-foreground text-sm">
{format(reference.date, 'HH:mm')}
</div>
</div>
@@ -145,5 +143,5 @@ export const ReportChartTooltip = createChartTooltip<Data, Context>(
)}
</>
);
- },
+ }
);
diff --git a/apps/start/src/components/report-chart/common/serie-icon.tsx b/apps/start/src/components/report-chart/common/serie-icon.tsx
index 043285960..dca6f95cc 100644
--- a/apps/start/src/components/report-chart/common/serie-icon.tsx
+++ b/apps/start/src/components/report-chart/common/serie-icon.tsx
@@ -1,3 +1,4 @@
+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';
import type { LucideProps } from 'lucide-react';
import {
ActivityIcon,
@@ -17,11 +18,8 @@ import {
TvIcon,
} from 'lucide-react';
import { useState } from 'react';
-
-import { NOT_SET_VALUE } from '@openpanel/constants';
-
-import { useAppContext } from '@/hooks/use-app-context';
import iconsWithUrls from './serie-icon.urls';
+import { useAppContext } from '@/hooks/use-app-context';
// ============================================================================
// Types
@@ -289,13 +287,16 @@ function resolveIcon(name: string): ResolvedIcon {
function IconWrapper({
children,
fill,
-}: { children: React.ReactNode; fill?: boolean }) {
+}: {
+ children: React.ReactNode;
+ fill?: boolean;
+}) {
return (
<div
className={
fill
- ? 'relative size-full flex-shrink-0 [&_svg]:!rounded-[2px]'
- : 'relative max-h-4 flex-shrink-0 [&_svg]:!rounded-[2px]'
+ ? '[&_svg]:!rounded-[2px] relative size-full flex-shrink-0'
+ : '[&_svg]:!rounded-[2px] relative max-h-4 flex-shrink-0'
}
>
{children}
@@ -316,16 +317,16 @@ function ImageIcon({ url, fill }: { url: string; fill?: boolean }) {
return (
<IconWrapper fill={fill}>
<img
- src={fullUrl}
alt=""
className={
fill
? 'size-full rounded-full object-cover'
- : 'w-full max-h-4 rounded-[2px] object-contain'
+ : 'max-h-4 w-full rounded-[2px] object-contain'
}
- loading="lazy"
decoding="async"
+ loading="lazy"
onError={() => setHasError(true)}
+ src={fullUrl}
/>
</IconWrapper>
);
@@ -377,9 +378,9 @@ export function SerieIcon({ name: names, fill, ...props }: SerieIconProps) {
switch (resolved.type) {
case 'lucide':
- return <LucideIconWrapper Icon={resolved.Icon} fill={fill} {...props} />;
+ return <LucideIconWrapper fill={fill} Icon={resolved.Icon} {...props} />;
case 'image':
- return <ImageIcon url={resolved.url} fill={fill} />;
+ return <ImageIcon fill={fill} url={resolved.url} />;
case 'flag':
return <FlagIcon code={resolved.code} fill={fill} />;
}
diff --git a/apps/start/src/components/report-chart/common/serie-name.tsx b/apps/start/src/components/report-chart/common/serie-name.tsx
index 3e3819128..c26f54fbe 100644
--- a/apps/start/src/components/report-chart/common/serie-name.tsx
+++ b/apps/start/src/components/report-chart/common/serie-name.tsx
@@ -1,10 +1,8 @@
-import { cn } from '@/utils/cn';
+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';
import { ChevronRightIcon } from 'lucide-react';
-
-import { NOT_SET_VALUE } from '@openpanel/constants';
-
-import React, { Fragment } from 'react';
+import { Fragment } from 'react';
import { useReportChartContext } from '../context';
+import { cn } from '@/utils/cn';
interface SerieNameProps {
name: string | string[];
diff --git a/apps/start/src/components/report-chart/context.tsx b/apps/start/src/components/report-chart/context.tsx
index d313f3c51..9a35edba7 100644
--- a/apps/start/src/components/report-chart/context.tsx
+++ b/apps/start/src/components/report-chart/context.tsx
@@ -1,9 +1,11 @@
+import type {
+ IChartSerie,
+ IReportInput,
+} from '@openpanel/core/modules/report/report.constants';
import isEqual from 'lodash.isequal';
import type { LucideIcon } from 'lucide-react';
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
-import type { IChartSerie, IReportInput } from '@openpanel/validation';
-
export type ReportChartContextType = {
options: Partial<{
columns: React.ReactNode[];
@@ -45,7 +47,7 @@ export const useReportChartContext = () => {
const ctx = useContext(context);
if (!ctx) {
throw new Error(
- 'useReportChartContext must be used within a ReportChartProvider',
+ 'useReportChartContext must be used within a ReportChartProvider'
);
}
return ctx;
diff --git a/apps/start/src/components/report-chart/conversion/chart.tsx b/apps/start/src/components/report-chart/conversion/chart.tsx
index 7ce1cf83e..b75c730d2 100644
--- a/apps/start/src/components/report-chart/conversion/chart.tsx
+++ b/apps/start/src/components/report-chart/conversion/chart.tsx
@@ -1,9 +1,5 @@
-import { changeVisibleSeries } from '@/components/report/reportSlice';
-import { pushModal } from '@/modals';
-import { useDispatch } from '@/redux';
-import type { RouterOutputs } from '@/trpc/client';
-import { cn } from '@/utils/cn';
-import { getChartColor } from '@/utils/theme';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
+import { useQuery } from '@tanstack/react-query';
import React, { useCallback, useMemo } from 'react';
import {
CartesianGrid,
@@ -15,26 +11,29 @@ import {
XAxis,
YAxis,
} from 'recharts';
-
+import { average, getPreviousMetric, round } from '../../../utils/math';
+import { useXAxisProps, useYAxisProps } from '../common/axis';
+import { PreviousDiffIndicator } from '../common/previous-diff-indicator';
+import { SerieIcon } from '../common/serie-icon';
+import { SerieName } from '../common/serie-name';
+import { useReportChartContext } from '../context';
+import { ConversionTable } from './conversion-table';
import {
ChartTooltipHeader,
ChartTooltipItem,
createChartTooltip,
} from '@/components/charts/chart-tooltip';
+import { changeVisibleSeries } from '@/components/report/reportSlice';
import { useConversionRechartDataModel } from '@/hooks/use-conversion-rechart-data-model';
import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
import { useNumber } from '@/hooks/use-numer-formatter';
import { useVisibleConversionSeries } from '@/hooks/use-visible-conversion-series';
import { useTRPC } from '@/integrations/trpc/react';
-import { average, getPreviousMetric, round } from '@openpanel/common';
-import type { IInterval } from '@openpanel/validation';
-import { useQuery } from '@tanstack/react-query';
-import { useXAxisProps, useYAxisProps } from '../common/axis';
-import { PreviousDiffIndicator } from '../common/previous-diff-indicator';
-import { SerieIcon } from '../common/serie-icon';
-import { SerieName } from '../common/serie-name';
-import { useReportChartContext } from '../context';
-import { ConversionTable } from './conversion-table';
+import { pushModal } from '@/modals';
+import { useDispatch } from '@/redux';
+import type { RouterOutputs } from '@/trpc/client';
+import { cn } from '@/utils/cn';
+import { getChartColor } from '@/utils/theme';
interface Props {
data: RouterOutputs['chart']['conversion'];
@@ -70,23 +69,31 @@ export function Chart({ data }: Props) {
startDate,
endDate,
range,
- }),
+ })
);
const xAxisProps = useXAxisProps({ interval, hide: hideXAxis });
const number = useNumber();
-
+
// Calculate dynamic Y-axis domain based on max rate
const yAxisDomain = useMemo(() => {
- if (!series.length) return [0, 100];
-
+ if (!series.length) {
+ return [0, 100];
+ }
+
const maxRate = Math.max(
...series.flatMap((serie) => serie.data.map((item) => item.rate))
);
-
- if (maxRate <= 5) return [0, 10];
- if (maxRate <= 20) return [0, 30];
- if (maxRate <= 50) return [0, 60];
+
+ if (maxRate <= 5) {
+ return [0, 10];
+ }
+ if (maxRate <= 20) {
+ return [0, 30];
+ }
+ if (maxRate <= 50) {
+ return [0, 60];
+ }
return [0, 100];
}, [series]);
@@ -100,7 +107,7 @@ export function Chart({ data }: Props) {
const averageConversionRate = average(
series.map((serie) => {
return average(serie.data.map((item) => item.rate));
- }, 0),
+ }, 0)
);
// Show dots when we have 30 or fewer data points
@@ -119,7 +126,7 @@ export function Chart({ data }: Props) {
const CustomLegend = useCallback(() => {
return (
- <div className="flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs mt-4 -mb-2">
+ <div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs">
{series.map((serie) => (
<div
className="flex items-center gap-1"
@@ -130,10 +137,10 @@ export function Chart({ data }: Props) {
>
<SerieIcon name={serie.breakdowns} />
<SerieName
+ className="font-semibold"
name={
serie.breakdowns.length > 0 ? serie.breakdowns : ['Conversion']
}
- className="font-semibold"
/>
</div>
))}
@@ -151,24 +158,24 @@ export function Chart({ data }: Props) {
<ResponsiveContainer>
<LineChart data={rechartData} onClick={handleChartClick}>
<CartesianGrid
- strokeDasharray="3 3"
+ className="stroke-border"
horizontal={true}
+ strokeDasharray="3 3"
vertical={false}
- className="stroke-border"
/>
{references.data?.map((ref) => (
<ReferenceLine
+ fontSize={10}
key={ref.id}
- x={ref.date.getTime()}
- stroke={'oklch(from var(--foreground) l c h / 0.1)'}
- strokeDasharray={'3 3'}
label={{
value: ref.title,
position: 'centerTop',
fill: '#334155',
fontSize: 12,
}}
- fontSize={10}
+ stroke={'oklch(from var(--foreground) l c h / 0.1)'}
+ strokeDasharray={'3 3'}
+ x={ref.date.getTime()}
/>
))}
<YAxis {...yAxisProps} domain={yAxisDomain} />
@@ -179,14 +186,14 @@ export function Chart({ data }: Props) {
const color = getChartColor(serie.index);
return (
<Line
- key={`${serie.id}:previousRate`}
- dot={false}
dataKey={`${serie.id}:previousRate`}
- stroke={color}
- type={lineType}
+ dot={false}
isAnimationActive={false}
- strokeWidth={1}
+ key={`${serie.id}:previousRate`}
+ stroke={color}
strokeOpacity={0.3}
+ strokeWidth={1}
+ type={lineType}
/>
);
})}
@@ -194,26 +201,22 @@ export function Chart({ data }: Props) {
const color = getChartColor(serie.index);
return (
<Line
- key={`${serie.id}:rate`}
+ activeDot={showDots ? { r: 5, strokeWidth: 2 } : { r: 4 }}
dataKey={`${serie.id}:rate`}
- stroke={color}
- type={lineType}
+ dot={
+ showDots ? { r: 3, strokeWidth: 2, fill: 'white' } : false
+ }
isAnimationActive={false}
+ key={`${serie.id}:rate`}
+ stroke={color}
strokeWidth={2}
- dot={showDots ? { r: 3, strokeWidth: 2, fill: 'white' } : false}
- activeDot={showDots ? { r: 5, strokeWidth: 2 } : { r: 4 }}
+ type={lineType}
/>
);
})}
{typeof averageConversionRate === 'number' &&
averageConversionRate && (
<ReferenceLine
- y={averageConversionRate}
- stroke={getChartColor(series.length)}
- strokeWidth={2}
- strokeDasharray="3 3"
- strokeOpacity={0.6}
- strokeLinecap="round"
label={{
value: `Average (${round(averageConversionRate, 2)}%)`,
fill: getChartColor(series.length),
@@ -221,6 +224,12 @@ export function Chart({ data }: Props) {
fontSize: 13,
fontWeight: 500,
}}
+ stroke={getChartColor(series.length)}
+ strokeDasharray="3 3"
+ strokeLinecap="round"
+ strokeOpacity={0.6}
+ strokeWidth={2}
+ y={averageConversionRate}
/>
)}
</LineChart>
@@ -228,8 +237,8 @@ export function Chart({ data }: Props) {
</div>
<ConversionTable
data={data}
- visibleSeries={series}
setVisibleSeries={setVisibleSeries}
+ visibleSeries={series}
/>
</TooltipProvider>
);
@@ -243,7 +252,7 @@ const { Tooltip, TooltipProvider } = createChartTooltip<
visibleSeries: RouterOutputs['chart']['conversion']['current'];
}
>(({ data, context }) => {
- if (!data || !data[0]) {
+ if (!(data && data[0])) {
return null;
}
@@ -267,7 +276,7 @@ const { Tooltip, TooltipProvider } = createChartTooltip<
}
const prevSerie = context.conversion?.previous?.find(
- (p) => p.id === serie.id,
+ (p) => p.id === serie.id
);
const prevItem = prevSerie?.data.find((d) => d.date === date);
const previousMetric = getPreviousMetric(rate, previousRate);
@@ -296,7 +305,7 @@ const { Tooltip, TooltipProvider } = createChartTooltip<
}
/>
</div>
- <div className="flex justify-between gap-8 font-mono font-medium">
+ <div className="flex justify-between gap-8 font-medium font-mono">
<div className="row gap-1">
<span>{number.formatWithUnit(rate / 100, '%')}</span>
<span className="text-muted-foreground">({total})</span>
diff --git a/apps/start/src/components/report-chart/conversion/conversion-table.tsx b/apps/start/src/components/report-chart/conversion/conversion-table.tsx
index 5242dd1ea..316e7cf8f 100644
--- a/apps/start/src/components/report-chart/conversion/conversion-table.tsx
+++ b/apps/start/src/components/report-chart/conversion/conversion-table.tsx
@@ -1,3 +1,10 @@
+import type { SortingState } from '@tanstack/react-table';
+import { useMemo, useState } from 'react';
+import { getPreviousMetric } from '../../../utils/math';
+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';
+import { ReportTableToolbar } from '../common/report-table-toolbar';
+import { SerieIcon } from '../common/serie-icon';
+import { SerieName } from '../common/serie-name';
import { Checkbox } from '@/components/ui/checkbox';
import { useFormatDateInterval } from '@/hooks/use-format-date-interval';
import { useNumber } from '@/hooks/use-numer-formatter';
@@ -5,13 +12,6 @@ import { useSelector } from '@/redux';
import type { RouterOutputs } from '@/trpc/client';
import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
-import { getPreviousMetric } from '@openpanel/common';
-import type { SortingState } from '@tanstack/react-table';
-import { useMemo, useState } from 'react';
-import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';
-import { ReportTableToolbar } from '../common/report-table-toolbar';
-import { SerieIcon } from '../common/serie-icon';
-import { SerieName } from '../common/serie-name';
interface ConversionTableProps {
data: RouterOutputs['chart']['conversion'];
@@ -36,7 +36,7 @@ export function ConversionTable({
// Get all unique dates from the first series
const dates = useMemo(
() => data.current[0]?.data.map((item) => item.date) ?? [],
- [data.current],
+ [data.current]
);
// Get all series (including non-visible ones for toggle functionality)
@@ -54,7 +54,7 @@ export function ConversionTable({
const total = serie.data.reduce((sum, item) => sum + item.total, 0);
const conversions = serie.data.reduce(
(sum, item) => sum + item.conversions,
- 0,
+ 0
);
const avgRate =
serie.data.length > 0
@@ -113,21 +113,21 @@ export function ConversionTable({
// Metric ranges
metricRanges.avgRate.min = Math.min(
metricRanges.avgRate.min,
- row.avgRate,
+ row.avgRate
);
metricRanges.avgRate.max = Math.max(
metricRanges.avgRate.max,
- row.avgRate,
+ row.avgRate
);
metricRanges.total.min = Math.min(metricRanges.total.min, row.total);
metricRanges.total.max = Math.max(metricRanges.total.max, row.total);
metricRanges.conversions.min = Math.min(
metricRanges.conversions.min,
- row.conversions,
+ row.conversions
);
metricRanges.conversions.max = Math.max(
metricRanges.conversions.max,
- row.conversions,
+ row.conversions
);
// Date ranges
@@ -146,7 +146,7 @@ export function ConversionTable({
value: number,
min: number,
max: number,
- colorClass: 'purple' | 'emerald' = 'emerald',
+ colorClass: 'purple' | 'emerald' = 'emerald'
): React.CSSProperties => {
if (value === 0 || max === min) {
return {};
@@ -165,7 +165,7 @@ export function ConversionTable({
const visibleSeriesIds = useMemo(
() => visibleSeries.map((s) => s.id),
- [visibleSeries],
+ [visibleSeries]
);
const getSerieIndex = (serieId: string): number => {
@@ -192,7 +192,7 @@ export function ConversionTable({
// Search in serie name
if (
row.serieName.some((name) =>
- name?.toLowerCase().includes(searchLower),
+ name?.toLowerCase().includes(searchLower)
)
) {
return true;
@@ -201,7 +201,7 @@ export function ConversionTable({
// Search in breakdown values
if (
row.breakdownValues.some((val) =>
- val?.toLowerCase().includes(searchLower),
+ val?.toLowerCase().includes(searchLower)
)
) {
return true;
@@ -219,7 +219,7 @@ export function ConversionTable({
// Search in date values
if (
Object.values(row.dateValues).some((val) =>
- String(val).toLowerCase().includes(searchLower),
+ String(val).toLowerCase().includes(searchLower)
)
) {
return true;
@@ -258,17 +258,29 @@ export function ConversionTable({
}
// Handle null/undefined values
- if (aValue == null && bValue == null) continue;
- if (aValue == null) return 1;
- if (bValue == null) return -1;
+ if (aValue == null && bValue == null) {
+ continue;
+ }
+ if (aValue == null) {
+ return 1;
+ }
+ if (bValue == null) {
+ return -1;
+ }
// Compare values
if (typeof aValue === 'string' && typeof bValue === 'string') {
const comparison = aValue.localeCompare(bValue);
- if (comparison !== 0) return desc ? -comparison : comparison;
+ if (comparison !== 0) {
+ return desc ? -comparison : comparison;
+ }
} else {
- if (aValue < bValue) return desc ? 1 : -1;
- if (aValue > bValue) return desc ? -1 : 1;
+ if (aValue < bValue) {
+ return desc ? 1 : -1;
+ }
+ if (aValue > bValue) {
+ return desc ? -1 : 1;
+ }
}
}
return 0;
@@ -296,7 +308,9 @@ export function ConversionTable({
const getSortIcon = (columnId: string) => {
const sort = sorting.find((s) => s.id === columnId);
- if (!sort) return '⇅';
+ if (!sort) {
+ return '⇅';
+ }
return sort.desc ? '↓' : '↑';
};
@@ -305,11 +319,11 @@ export function ConversionTable({
}
return (
- <div className="flex flex-col border rounded-lg overflow-hidden bg-card mt-8">
+ <div className="mt-8 flex flex-col overflow-hidden rounded-lg border bg-card">
<ReportTableToolbar
- search={globalFilter}
onSearchChange={setGlobalFilter}
onUnselectAll={() => setVisibleSeries([])}
+ search={globalFilter}
/>
<div
className="overflow-x-auto overflow-y-auto"
@@ -319,10 +333,10 @@ export function ConversionTable({
}}
>
<table className="w-full" style={{ minWidth: 'fit-content' }}>
- <thead className="bg-muted/30 border-b sticky top-0 z-10">
+ <thead className="sticky top-0 z-10 border-b bg-muted/30">
<tr>
<th
- className="text-left h-10 px-4 text-[10px] uppercase font-semibold sticky left-0 bg-card z-20 min-w-[200px] border-r border-border whitespace-nowrap"
+ className="sticky left-0 z-20 h-10 min-w-[200px] whitespace-nowrap border-border border-r bg-card px-4 text-left font-semibold text-[10px] uppercase"
style={{
boxShadow: '2px 0 4px -2px var(--border)',
}}
@@ -330,7 +344,7 @@ export function ConversionTable({
<div className="flex items-center">Serie</div>
</th>
<th
- className="text-right h-10 px-4 text-[10px] uppercase font-semibold min-w-[100px] cursor-pointer hover:bg-muted/50 select-none border-r border-border whitespace-nowrap"
+ className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"
onClick={() => handleSort('metric-avgRate')}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -347,7 +361,7 @@ export function ConversionTable({
</div>
</th>
<th
- className="text-right h-10 px-4 text-[10px] uppercase font-semibold min-w-[100px] cursor-pointer hover:bg-muted/50 select-none border-r border-border whitespace-nowrap"
+ className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"
onClick={() => handleSort('metric-total')}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -364,7 +378,7 @@ export function ConversionTable({
</div>
</th>
<th
- className="text-right h-10 px-4 text-[10px] uppercase font-semibold min-w-[100px] cursor-pointer hover:bg-muted/50 select-none border-r border-border whitespace-nowrap"
+ className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"
onClick={() => handleSort('metric-conversions')}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -382,8 +396,8 @@ export function ConversionTable({
</th>
{dates.map((date) => (
<th
+ className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"
key={date}
- className="text-right h-10 px-4 text-[10px] uppercase font-semibold min-w-[100px] cursor-pointer hover:bg-muted/50 select-none border-r border-border whitespace-nowrap"
onClick={() => handleSort(`date-${date}`)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -414,14 +428,14 @@ export function ConversionTable({
return (
<tr
- key={row.id}
className={cn(
- 'border-b hover:bg-muted/30 transition-colors',
- !isVisible && 'opacity-50',
+ 'border-b transition-colors hover:bg-muted/30',
+ !isVisible && 'opacity-50'
)}
+ key={row.id}
>
<td
- className="px-4 py-3 sticky left-0 z-10 border-r border-border"
+ className="sticky left-0 z-10 border-border border-r px-4 py-3"
style={{
backgroundColor: 'var(--card)',
boxShadow: '2px 0 4px -2px var(--border)',
@@ -430,6 +444,7 @@ export function ConversionTable({
<div className="flex items-center gap-2">
<Checkbox
checked={isVisible}
+ className="h-4 w-4 shrink-0"
onCheckedChange={() =>
toggleSerieVisibility(row.serieId)
}
@@ -437,14 +452,13 @@ export function ConversionTable({
borderColor: color,
backgroundColor: isVisible ? color : 'transparent',
}}
- className="h-4 w-4 shrink-0"
/>
<div
- className="w-[3px] rounded-full shrink-0"
+ className="w-[3px] shrink-0 rounded-full"
style={{ background: color }}
/>
<SerieIcon name={row.serieName} />
- <SerieName name={row.serieName} className="truncate" />
+ <SerieName className="truncate" name={row.serieName} />
</div>
</td>
<td
@@ -453,7 +467,7 @@ export function ConversionTable({
row.avgRate,
metricRanges.avgRate.min,
metricRanges.avgRate.max,
- 'purple',
+ 'purple'
)}
>
<div className="flex items-center justify-end gap-2">
@@ -471,7 +485,7 @@ export function ConversionTable({
row.total,
metricRanges.total.min,
metricRanges.total.max,
- 'purple',
+ 'purple'
)}
>
{number.format(row.total)}
@@ -482,7 +496,7 @@ export function ConversionTable({
row.conversions,
metricRanges.conversions.min,
metricRanges.conversions.max,
- 'purple',
+ 'purple'
)}
>
{number.format(row.conversions)}
@@ -491,13 +505,13 @@ export function ConversionTable({
const value = row.dateValues[date] ?? 0;
return (
<td
- key={date}
className="px-4 py-3 text-right font-mono text-sm"
+ key={date}
style={getCellBackgroundStyle(
value,
dateRanges[date]!.min,
dateRanges[date]!.max,
- 'emerald',
+ 'emerald'
)}
>
{number.formatWithUnit(value / 100, '%')}
diff --git a/apps/start/src/components/report-chart/conversion/summary.tsx b/apps/start/src/components/report-chart/conversion/summary.tsx
index fe6ba42dc..98411db08 100644
--- a/apps/start/src/components/report-chart/conversion/summary.tsx
+++ b/apps/start/src/components/report-chart/conversion/summary.tsx
@@ -1,6 +1,3 @@
-import type { RouterOutputs } from '@/trpc/client';
-import type React from 'react';
-import { useMemo } from 'react';
import {
ArrowDownRight,
ArrowUpRight,
@@ -10,13 +7,18 @@ import {
Target,
Trophy,
} from 'lucide-react';
-
+import type React from 'react';
+import { useMemo } from 'react';
+import { average, sum } from '../../../utils/math';
+import { useReportChartContext } from '../context';
import { useNumber } from '@/hooks/use-numer-formatter';
+import type { RouterOutputs } from '@/trpc/client';
import { formatDate } from '@/utils/date';
-import { average, sum } from '@openpanel/common';
-import { useReportChartContext } from '../context';
-const SUMMARY_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
+const SUMMARY_ICONS: Record<
+ string,
+ React.ComponentType<{ className?: string }>
+> = {
Flow: GitBranch,
'Average conversion rate': Percent,
'Total conversions': Target,
@@ -46,7 +48,7 @@ export function Summary({ data }: Props) {
}
return maxInSerie;
},
- { rate: 0, serieIndex, dataIndex: 0 },
+ { rate: 0, serieIndex, dataIndex: 0 }
);
return serieMax.rate > acc.rate ? serieMax : acc;
@@ -55,7 +57,7 @@ export function Summary({ data }: Props) {
rate: 0,
serieIndex: 0,
dataIndex: 0,
- },
+ }
);
}, [data.current]);
@@ -69,7 +71,7 @@ export function Summary({ data }: Props) {
}
return minInSerie;
},
- { rate: 100, serieIndex, dataIndex: 0 },
+ { rate: 100, serieIndex, dataIndex: 0 }
);
return serieMin.rate < acc.rate ? serieMin : acc;
@@ -78,7 +80,7 @@ export function Summary({ data }: Props) {
rate: 100,
serieIndex: 0,
dataIndex: 0,
- },
+ }
);
}, [data.current]);
const bestConversionRate =
@@ -95,27 +97,27 @@ export function Summary({ data }: Props) {
const averageRate = average(serie.data.map((item) => item.rate));
return averageRate > acc.averageRate ? { serie, averageRate } : acc;
},
- { serie: data.current[0], averageRate: 0 },
+ { serie: data.current[0], averageRate: 0 }
);
const worstAverageConversionRateMatch = data.current.reduce(
(acc, serie) => {
const averageRate = average(serie.data.map((item) => item.rate));
return averageRate < acc.averageRate ? { serie, averageRate } : acc;
},
- { serie: data.current[0], averageRate: 100 },
+ { serie: data.current[0], averageRate: 100 }
);
const averageConversionRate = average(
data.current.map((serie) => {
return average(serie.data.map((item) => item.rate));
- }, 0),
+ }, 0)
);
const averageConversionRatePrevious =
average(
data.previous?.map((serie) => {
return average(serie.data.map((item) => item.rate));
- }) ?? [],
+ }) ?? []
) ?? 0;
const sumConversions = data.current.reduce((acc, serie) => {
@@ -146,13 +148,13 @@ export function Summary({ data }: Props) {
name: 'Previous period average conversion rate',
value: number.formatWithUnit(
averageConversionRatePrevious / 100,
- '%',
+ '%'
),
},
{
name: 'Previous period total conversions',
value: sumConversionsPrevious ?? 0,
- },
+ }
);
}
if (hasManySeries && bestAverageConversionRateMatch) {
@@ -208,10 +210,10 @@ export function Summary({ data }: Props) {
const Icon = SUMMARY_ICONS[item.name];
return (
<div
+ className="card row items-center justify-between gap-4 p-4 py-3 font-medium"
key={item.name}
- className="card row items-center justify-between p-4 py-3 font-medium gap-4"
>
- <span className="text-muted-foreground row items-center gap-2">
+ <span className="row items-center gap-2 text-muted-foreground">
{Icon != null && <Icon className="size-4 shrink-0" />}
{item.name}
</span>
diff --git a/apps/start/src/components/report-chart/funnel/breakdown-list.tsx b/apps/start/src/components/report-chart/funnel/breakdown-list.tsx
index 791a14425..f08ea1fb8 100644
--- a/apps/start/src/components/report-chart/funnel/breakdown-list.tsx
+++ b/apps/start/src/components/report-chart/funnel/breakdown-list.tsx
@@ -1,13 +1,13 @@
+import { ChevronDown, ChevronRight } from 'lucide-react';
+import { useState } from 'react';
+import { getPreviousMetric } from '../../../utils/math';
+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';
+import { Tables } from './chart';
import { Checkbox } from '@/components/ui/checkbox';
import { useNumber } from '@/hooks/use-numer-formatter';
import type { RouterOutputs } from '@/trpc/client';
import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
-import { getPreviousMetric } from '@openpanel/common';
-import { ChevronDown, ChevronRight } from 'lucide-react';
-import { useState } from 'react';
-import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';
-import { Tables } from './chart';
interface BreakdownListProps {
data: RouterOutputs['chart']['funnel'];
@@ -65,11 +65,11 @@ export function BreakdownList({
<div className="col gap-4">
{allBreakdowns.map((item, index) => (
<Tables
- key={item.id}
data={{
current: item,
previous: previousData[index] ?? null,
}}
+ key={item.id}
/>
))}
</div>
@@ -84,26 +84,25 @@ export function BreakdownList({
const isVisible = visibleSeriesIds.includes(item.id);
const stableColorIndex = getStableColorIndex(item.id);
const previousItem = previousData[index] ?? null;
- const hasBreakdownName =
- item.breakdowns && item.breakdowns.length > 0;
+ const hasBreakdownName = item.breakdowns && item.breakdowns.length > 0;
const color =
stableColorIndex >= 0 ? getChartColor(stableColorIndex) : undefined;
return (
- <div key={item.id} className="col">
+ <div className="col" key={item.id}>
{/* Compact row */}
<div
className={cn(
- 'card row items-center gap-3 px-4 py-3 text-left w-full',
- isExpanded && 'rounded-b-none',
+ 'card row w-full items-center gap-3 px-4 py-3 text-left',
+ isExpanded && 'rounded-b-none'
)}
>
{/* Chart visibility checkbox */}
{hasBreakdowns && (
<Checkbox
checked={isVisible}
- onCheckedChange={() => toggleVisibility(item.id)}
className="shrink-0"
+ onCheckedChange={() => toggleVisibility(item.id)}
style={{
borderColor: color,
backgroundColor: isVisible && color ? color : 'transparent',
@@ -113,46 +112,39 @@ export function BreakdownList({
{/* Expandable row content */}
<button
- type="button"
+ className="flex min-w-0 flex-1 items-center gap-3 transition-opacity hover:opacity-80"
onClick={() => toggleExpanded(item.id)}
- className="flex items-center gap-3 flex-1 min-w-0 hover:opacity-80 transition-opacity"
+ type="button"
>
{isExpanded ? (
<ChevronDown className="size-4 shrink-0 text-muted-foreground" />
) : (
<ChevronRight className="size-4 shrink-0 text-muted-foreground" />
)}
- <span className="font-medium truncate">
- {hasBreakdownName
- ? item.breakdowns.join(' > ')
- : 'Funnel'}
+ <span className="truncate font-medium">
+ {hasBreakdownName ? item.breakdowns.join(' > ') : 'Funnel'}
</span>
</button>
- <div className="flex items-center gap-6 shrink-0">
- <div className="text-right row gap-2 items-center">
+ <div className="flex shrink-0 items-center gap-6">
+ <div className="row items-center gap-2 text-right">
<div className="text-muted-foreground text-sm">
Conversion
</div>
<div className="font-mono font-semibold text-sm">
- {number.formatWithUnit(
- item.lastStep.percent / 100,
- '%',
- )}
+ {number.formatWithUnit(item.lastStep.percent / 100, '%')}
</div>
{previousItem && (
<PreviousDiffIndicatorPure
{...getPreviousMetric(
item.lastStep.percent,
- previousItem.lastStep.percent,
+ previousItem.lastStep.percent
)}
/>
)}
</div>
- <div className="text-right row gap-2 items-center">
- <div className="text-muted-foreground text-sm">
- Completed
- </div>
+ <div className="row items-center gap-2 text-right">
+ <div className="text-muted-foreground text-sm">Completed</div>
<div className="font-mono font-semibold text-sm">
{number.format(item.lastStep.count)}
</div>
@@ -160,7 +152,7 @@ export function BreakdownList({
<PreviousDiffIndicatorPure
{...getPreviousMetric(
item.lastStep.count,
- previousItem.lastStep.count,
+ previousItem.lastStep.count
)}
/>
)}
diff --git a/apps/start/src/components/report-chart/funnel/chart.tsx b/apps/start/src/components/report-chart/funnel/chart.tsx
index 6293c3b71..7cc2d593f 100644
--- a/apps/start/src/components/report-chart/funnel/chart.tsx
+++ b/apps/start/src/components/report-chart/funnel/chart.tsx
@@ -1,5 +1,4 @@
-import { getPreviousMetric } from '@openpanel/common';
-import { alphabetIds } from '@openpanel/constants';
+import { alphabetIds } from '@openpanel/core/modules/report/report.constants';
import { ChevronRightIcon, InfoIcon, UsersIcon } from 'lucide-react';
import { useCallback } from 'react';
import {
@@ -12,6 +11,7 @@ import {
XAxis,
YAxis,
} from 'recharts';
+import { getPreviousMetric } from '../../../utils/math';
import { useXAxisProps, useYAxisProps } from '../common/axis';
import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';
import { SerieIcon } from '../common/serie-icon';
@@ -469,7 +469,9 @@ export function Chart({
return (
<div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs">
{visibleBreakdowns.map((breakdown, idx) => {
- const stableIndex = data.current.findIndex((b) => b.id === breakdown.id);
+ const stableIndex = data.current.findIndex(
+ (b) => b.id === breakdown.id
+ );
const colorIndex = stableIndex >= 0 ? stableIndex : idx;
return (
<div
@@ -568,7 +570,7 @@ export function Chart({
{hasBreakdowns &&
visibleBreakdowns.map((item, breakdownIndex) => {
const stableIndex = data.current.findIndex(
- (b) => b.id === item.id,
+ (b) => b.id === item.id
);
const colorIndex =
stableIndex >= 0 ? stableIndex : breakdownIndex;
@@ -727,16 +729,16 @@ const { Tooltip, TooltipProvider } = createChartTooltip<
return (
<div className="row gap-2" key={key}>
<div
- className="w-[3px] rounded-full shrink-0"
+ className="w-[3px] shrink-0 rounded-full"
style={{
background: getChartColor(colorIndex),
}}
/>
- <div className="col flex-1 gap-1 min-w-0">
+ <div className="col min-w-0 flex-1 gap-1">
<div className="flex items-center gap-1">
<ChartName breakdowns={variant.breakdowns ?? []} />
</div>
- <div className="flex items-center justify-between gap-4 font-mono font-medium">
+ <div className="flex items-center justify-between gap-4 font-medium font-mono">
<div className="col gap-0.5">
<span>
{number.formatWithUnit(variant.step.percent / 100, '%')}
diff --git a/apps/start/src/components/report-chart/metric/metric-card.tsx b/apps/start/src/components/report-chart/metric/metric-card.tsx
index e98b1d63d..2cafe47ee 100644
--- a/apps/start/src/components/report-chart/metric/metric-card.tsx
+++ b/apps/start/src/components/report-chart/metric/metric-card.tsx
@@ -1,24 +1,22 @@
-import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';
-import type { IChartData } from '@/trpc/client';
-import { cn } from '@/utils/cn';
+import type { IChartMetric } from '@openpanel/core/modules/report/report.constants';
import AutoSizer from 'react-virtualized-auto-sizer';
import { Area, AreaChart, Tooltip } from 'recharts';
-
-import type { IChartMetric } from '@openpanel/validation';
-
+import {
+ getDiffIndicator,
+ PreviousDiffIndicator,
+} from '../common/previous-diff-indicator';
+import { SerieName } from '../common/serie-name';
+import { useReportChartContext } from '../context';
import {
ChartTooltipContainer,
ChartTooltipHeader,
ChartTooltipItem,
} from '@/components/charts/chart-tooltip';
+import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';
+import type { IChartData } from '@/trpc/client';
+import { cn } from '@/utils/cn';
import { formatDate } from '@/utils/date';
import { getChartColor } from '@/utils/theme';
-import {
- PreviousDiffIndicator,
- getDiffIndicator,
-} from '../common/previous-diff-indicator';
-import { SerieName } from '../common/serie-name';
-import { useReportChartContext } from '../context';
interface MetricCardProps {
serie: IChartData['series'][number];
@@ -34,7 +32,7 @@ const TooltipContent = (props: { payload?: any[] }) => {
{props.payload?.map((item) => {
const { date, count } = item.payload;
return (
- <div key={item.id} className="col gap-2">
+ <div className="col gap-2" key={item.id}>
<ChartTooltipHeader>
<div>{formatDate(new Date(date))}</div>
</ChartTooltipHeader>
@@ -85,36 +83,36 @@ export function MetricCard({
previous?.state,
'#6ee7b7', // green
'#fda4af', // red
- '#93c5fd', // blue
+ '#93c5fd' // blue
);
return (
<div
className={cn(
'group relative p-4 hover:z-10',
- isEditMode && 'card h-auto',
+ isEditMode && 'card h-auto'
)}
key={serie.id}
>
<div
className={cn(
- 'absolute -left-1 -right-1 bottom-0 top-0 z-0 opacity-100 transition-opacity duration-300 group-hover:opacity-100',
+ 'absolute top-0 -right-1 bottom-0 -left-1 z-0 opacity-100 transition-opacity duration-300 group-hover:opacity-100'
)}
>
<AutoSizer>
{({ width, height }) => (
<AreaChart
- width={width}
- height={height / 4}
data={serie.data}
+ height={height / 4}
style={{ marginTop: (height / 4) * 3 }}
+ width={width}
>
<defs>
<linearGradient
id={`colorUv${serie.id}`}
x1="0"
- y1="0"
x2="0"
+ y1="0"
y2="1"
>
<stop offset="0%" stopColor={graphColors} stopOpacity={0.2} />
@@ -128,26 +126,26 @@ export function MetricCard({
<Tooltip content={TooltipContent} />
<Area
dataKey="count"
- type="step"
fill={`url(#colorUv${serie.id})`}
fillOpacity={1}
+ isAnimationActive={false}
stroke={graphColors}
strokeWidth={1}
- isAnimationActive={false}
+ type="step"
/>
</AreaChart>
)}
</AutoSizer>
</div>
<MetricCardNumber
- label={<SerieName name={serie.names} />}
- value={renderValue(serie.metrics[metric], 'ml-1 font-light text-xl')}
enhancer={
<PreviousDiffIndicator
{...previous}
- className="text-sm text-muted-foreground"
+ className="text-muted-foreground text-sm"
/>
}
+ label={<SerieName name={serie.names} />}
+ value={renderValue(serie.metrics[metric], 'ml-1 font-light text-xl')}
/>
</div>
);
@@ -172,7 +170,7 @@ export function MetricCardNumber({
</div>
</div>
<div className="flex items-end justify-between gap-4">
- <div className="truncate font-mono text-3xl font-bold">{value}</div>
+ <div className="truncate font-bold font-mono text-3xl">{value}</div>
{enhancer}
</div>
</div>
diff --git a/apps/start/src/components/report-chart/retention/chart.tsx b/apps/start/src/components/report-chart/retention/chart.tsx
index aa772a702..2016529cb 100644
--- a/apps/start/src/components/report-chart/retention/chart.tsx
+++ b/apps/start/src/components/report-chart/retention/chart.tsx
@@ -1,6 +1,3 @@
-import type { RouterOutputs } from '@/trpc/client';
-import { cn } from '@/utils/cn';
-import { getChartColor } from '@/utils/theme';
import {
Area,
CartesianGrid,
@@ -11,11 +8,13 @@ import {
XAxis,
YAxis,
} from 'recharts';
-
-import { average, round } from '@openpanel/common';
+import { average, round } from '../../../utils/math';
import { useXAxisProps, useYAxisProps } from '../common/axis';
import { useReportChartContext } from '../context';
import { RetentionTooltip } from './tooltip';
+import type { RouterOutputs } from '@/trpc/client';
+import { cn } from '@/utils/cn';
+import { getChartColor } from '@/utils/theme';
interface Props {
data: RouterOutputs['chart']['cohort'];
@@ -49,24 +48,24 @@ export function Chart({ data }: Props) {
<ResponsiveContainer>
<ComposedChart data={rechartData}>
<CartesianGrid
- strokeDasharray="3 3"
+ className="stroke-border"
horizontal={true}
+ strokeDasharray="3 3"
vertical={true}
- className="stroke-border"
/>
<YAxis {...yAxisProps} dataKey="retentionRate" domain={[0, 100]} />
<XAxis
{...xAxisProps}
- dataKey="days"
allowDuplicatedCategory
+ dataKey="days"
+ interval={0}
scale="linear"
- tickFormatter={(value) => value.toString()}
tickCount={31}
- interval={0}
+ tickFormatter={(value) => value.toString()}
/>
<Tooltip content={<RetentionTooltip />} />
<defs>
- <linearGradient id={'color'} x1="0" y1="0" x2="0" y2="1">
+ <linearGradient id={'color'} x1="0" x2="0" y1="0" y2="1">
<stop
offset="0%"
stopColor={getChartColor(0)}
@@ -80,27 +79,27 @@ export function Chart({ data }: Props) {
</linearGradient>
</defs>
<ReferenceLine
- y={averageRetentionRate}
- stroke={getChartColor(1)}
- strokeWidth={2}
- strokeDasharray="3 3"
- strokeOpacity={0.5}
- strokeLinecap="round"
label={{
value: `Average (${round(averageRetentionRate, 2)} %)`,
fill: getChartColor(1),
position: 'insideBottomRight',
fontSize: 12,
}}
+ stroke={getChartColor(1)}
+ strokeDasharray="3 3"
+ strokeLinecap="round"
+ strokeOpacity={0.5}
+ strokeWidth={2}
+ y={averageRetentionRate}
/>
<Area
dataKey="percentage"
fill={'url(#color)'}
- type={'monotone'}
+ fillOpacity={0.1}
isAnimationActive={false}
- strokeWidth={2}
stroke={getChartColor(0)}
- fillOpacity={0.1}
+ strokeWidth={2}
+ type={'monotone'}
/>
</ComposedChart>
</ResponsiveContainer>
diff --git a/apps/start/src/components/report-chart/retention/table.tsx b/apps/start/src/components/report-chart/retention/table.tsx
index f81e65376..2e830428c 100644
--- a/apps/start/src/components/report-chart/retention/table.tsx
+++ b/apps/start/src/components/report-chart/retention/table.tsx
@@ -1,8 +1,8 @@
+import { max, min } from '../../../utils/math';
+import { useReportChartContext } from '../context';
import { useNumber } from '@/hooks/use-numer-formatter';
import type { RouterOutputs } from '@/trpc/client';
import { cn } from '@/utils/cn';
-import { max, min } from '@openpanel/common';
-import { useReportChartContext } from '../context';
type CohortData = RouterOutputs['chart']['cohort'];
@@ -19,15 +19,16 @@ const CohortTable: React.FC<CohortTableProps> = ({ data }) => {
const highestValue = max(data.map((row) => max(row.values)));
const lowestValue = min(data.map((row) => min(row.values)));
const rowWithHigestSum = data.find(
- (row) => row.sum === max(data.map((row) => row.sum)),
+ (row) => row.sum === max(data.map((row) => row.sum))
);
const getBackground = (value: number | undefined) => {
- if (!value)
+ if (!value) {
return {
backgroundClassName: '',
opacity: 0,
};
+ }
const percentage = isPercentage
? value / 100
@@ -44,25 +45,25 @@ const CohortTable: React.FC<CohortTableProps> = ({ data }) => {
'h-10 align-top pt-3 whitespace-nowrap font-semibold text-muted-foreground';
return (
- <div className="relative card overflow-hidden">
+ <div className="card relative overflow-hidden">
<div
- className={'h-10 absolute left-0 right-0 top-px bg-def-100 border-b'}
+ className={'absolute top-px right-0 left-0 h-10 border-b bg-def-100'}
/>
- <div className="w-full overflow-x-auto hide-scrollbar">
- <div className="min-w-full relative">
+ <div className="hide-scrollbar w-full overflow-x-auto">
+ <div className="relative min-w-full">
<table className="w-full table-auto whitespace-nowrap">
<thead>
<tr>
<th className={cn(thClassName, 'sticky left-0 z-10')}>
<div className="bg-def-100">
- <div className="h-10 center-center -mt-3">Date</div>
+ <div className="center-center -mt-3 h-10">Date</div>
</div>
</th>
<th className={cn(thClassName, 'pr-1')}>Total profiles</th>
{data[0]?.values.map((column, index) => (
<th
- key={index.toString()}
className={cn(thClassName, 'capitalize')}
+ key={index.toString()}
>
{index === 0 ? `< ${interval} 1` : `${interval} ${index}`}
</th>
@@ -74,13 +75,13 @@ const CohortTable: React.FC<CohortTableProps> = ({ data }) => {
const values = isPercentage ? row.percentages : row.values;
return (
<tr key={row.cohort_interval}>
- <td className="sticky left-0 bg-card z-10 w-36 p-0">
- <div className="h-10 center-center font-medium text-muted-foreground px-4">
+ <td className="sticky left-0 z-10 w-36 bg-card p-0">
+ <div className="center-center h-10 px-4 font-medium text-muted-foreground">
{row.cohort_interval}
</div>
</td>
- <td className="p-0 min-w-12">
- <div className={cn('font-mono rounded px-3 font-medium')}>
+ <td className="min-w-12 p-0">
+ <div className={cn('rounded px-3 font-medium font-mono')}>
{number.format(row?.sum)}
{row.cohort_interval ===
rowWithHigestSum?.cohort_interval && ' 🚀'}
@@ -91,20 +92,20 @@ const CohortTable: React.FC<CohortTableProps> = ({ data }) => {
getBackground(value);
return (
<td
+ className="min-w-24 p-0"
key={row.cohort_interval + index.toString()}
- className="p-0 min-w-24"
>
<div
className={cn(
- 'h-10 center-center font-mono hover:shadow-[inset_0_0_0_2px_rgb(255,255,255)] relative',
+ 'center-center relative h-10 font-mono hover:shadow-[inset_0_0_0_2px_rgb(255,255,255)]',
opacity > 0.7 &&
- 'text-white [text-shadow:_0_0_3px_rgb(0_0_0_/_20%)]',
+ 'text-white [text-shadow:_0_0_3px_rgb(0_0_0_/_20%)]'
)}
>
<div
className={cn(
backgroundClassName,
- 'w-full h-full inset-0 absolute',
+ 'absolute inset-0 h-full w-full'
)}
style={{
opacity,
diff --git a/apps/start/src/components/report-chart/sankey/index.tsx b/apps/start/src/components/report-chart/sankey/index.tsx
index 879d90211..fe006bf87 100644
--- a/apps/start/src/components/report-chart/sankey/index.tsx
+++ b/apps/start/src/components/report-chart/sankey/index.tsx
@@ -1,14 +1,12 @@
-import { useTRPC } from '@/integrations/trpc/react';
+import type { IReportInput } from '@openpanel/core/modules/report/report.constants';
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';
+import { useTRPC } from '@/integrations/trpc/react';
export function ReportSankeyChart() {
const {
@@ -46,7 +44,7 @@ export function ReportSankeyChart() {
const res = useQuery(
trpc.chart.sankey.queryOptions(input, {
enabled: !isLazyLoading && input.series.length > 0,
- }),
+ })
);
if (isLazyLoading || res.isLoading) {
diff --git a/apps/start/src/components/report/ReportChartType.tsx b/apps/start/src/components/report/ReportChartType.tsx
index dd88a379e..a9f048438 100644
--- a/apps/start/src/components/report/ReportChartType.tsx
+++ b/apps/start/src/components/report/ReportChartType.tsx
@@ -1,4 +1,5 @@
-import { useDispatch, useSelector } from '@/redux';
+import type { IChartType } from '@openpanel/core/modules/report/report.constants';
+import { chartTypes } from '@openpanel/core/modules/report/report.constants';
import {
AreaChartIcon,
ChartBarIcon,
@@ -13,10 +14,7 @@ import {
TrendingUpIcon,
UsersIcon,
} from 'lucide-react';
-
-import { chartTypes } from '@openpanel/constants';
-import type { IChartType } from '@openpanel/validation';
-
+import { Button } from '../ui/button';
import {
DropdownMenu,
DropdownMenuContent,
@@ -29,8 +27,6 @@ import {
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
import { objectToZodEnums } from '@/utils/object-to-zod-enums';
-import { Button } from '../ui/button';
-import { changeChartType } from './reportSlice';
interface ReportChartTypeProps {
className?: string;
@@ -67,9 +63,9 @@ export function ReportChartType({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
- variant="outline"
- icon={Icons[value]}
className={cn('justify-start', className)}
+ icon={Icons[value]}
+ variant="outline"
>
{items.find((item) => item.value === value)?.label}
</Button>
@@ -83,13 +79,13 @@ export function ReportChartType({
const Icon = Icons[item.value];
return (
<DropdownMenuItem
+ className="group"
key={item.value}
onClick={() => onChange(item.value)}
- className="group"
>
{item.label}
<DropdownMenuShortcut>
- <Icon className="size-4 group-hover:text-blue-500 group-hover:scale-125 transition-all group-hover:rotate-12" />
+ <Icon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
</DropdownMenuShortcut>
</DropdownMenuItem>
);
diff --git a/apps/start/src/components/report/ReportInterval.tsx b/apps/start/src/components/report/ReportInterval.tsx
index 27d78945c..1d153d6a4 100644
--- a/apps/start/src/components/report/ReportInterval.tsx
+++ b/apps/start/src/components/report/ReportInterval.tsx
@@ -1,13 +1,14 @@
-import { ClockIcon } from 'lucide-react';
-
+import type {
+ IChartRange,
+ IChartType,
+ IInterval,
+} from '@openpanel/core/modules/report/report.constants';
import {
isHourIntervalEnabledByRange,
isMinuteIntervalEnabledByRange,
-} from '@openpanel/constants';
-
-import { cn } from '@/utils/cn';
-import type { IChartRange, IChartType, IInterval } from '@openpanel/validation';
-import { differenceInDays, isSameDay } from 'date-fns';
+} from '@openpanel/core/modules/report/report.constants';
+import { differenceInDays } from 'date-fns';
+import { ClockIcon } from 'lucide-react';
import { Button } from '../ui/button';
import { CommandShortcut } from '../ui/command';
import {
@@ -20,6 +21,7 @@ import {
DropdownMenuShortcut,
DropdownMenuTrigger,
} from '../ui/dropdown-menu';
+import { cn } from '@/utils/cn';
interface ReportIntervalProps {
className?: string;
@@ -97,9 +99,9 @@ export function ReportInterval({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
- variant="outline"
- icon={ClockIcon}
className={cn('justify-start', className)}
+ icon={ClockIcon}
+ variant="outline"
>
{items.find((item) => item.value === interval)?.label || 'Interval'}
</Button>
@@ -115,9 +117,9 @@ export function ReportInterval({
<DropdownMenuGroup>
{items.map((item) => (
<DropdownMenuItem
+ disabled={item.disabled}
key={item.value}
onClick={() => onChange(item.value as IInterval)}
- disabled={item.disabled}
>
{item.label}
{item.value === interval && (
diff --git a/apps/start/src/components/report/ReportLineType.tsx b/apps/start/src/components/report/ReportLineType.tsx
index b528e5871..c9451d013 100644
--- a/apps/start/src/components/report/ReportLineType.tsx
+++ b/apps/start/src/components/report/ReportLineType.tsx
@@ -1,11 +1,9 @@
-import { useDispatch, useSelector } from '@/redux';
-import { objectToZodEnums } from '@/utils/object-to-zod-enums';
+import { lineTypes } from '@openpanel/core/modules/report/report.constants';
import { Tv2Icon } from 'lucide-react';
-
-import { lineTypes } from '@openpanel/constants';
-
import { Combobox } from '../ui/combobox';
import { changeLineType } from './reportSlice';
+import { useDispatch, useSelector } from '@/redux';
+import { objectToZodEnums } from '@/utils/object-to-zod-enums';
interface ReportLineTypeProps {
className?: string;
@@ -19,22 +17,23 @@ export function ReportLineType({ className }: ReportLineTypeProps) {
chartType !== 'conversion' &&
chartType !== 'linear' &&
chartType !== 'area'
- )
+ ) {
return null;
+ }
return (
<Combobox
- icon={Tv2Icon}
className={className}
- placeholder="Line type"
- onChange={(value) => {
- dispatch(changeLineType(value));
- }}
- value={type}
+ icon={Tv2Icon}
items={objectToZodEnums(lineTypes).map((key) => ({
label: lineTypes[key],
value: key,
}))}
+ onChange={(value) => {
+ dispatch(changeLineType(value));
+ }}
+ placeholder="Line type"
+ value={type}
/>
);
}
diff --git a/apps/start/src/components/report/ReportSegment.tsx b/apps/start/src/components/report/ReportSegment.tsx
index 15a61ae6c..bc57add83 100644
--- a/apps/start/src/components/report/ReportSegment.tsx
+++ b/apps/start/src/components/report/ReportSegment.tsx
@@ -1,5 +1,5 @@
-import { chartSegments } from '@openpanel/constants';
-import type { IChartEventSegment } from '@openpanel/validation';
+import type { IChartEventSegment } from '@openpanel/core/modules/report/report.constants';
+import { chartSegments } from '@openpanel/core/modules/report/report.constants';
import {
ActivityIcon,
Building2Icon,
diff --git a/apps/start/src/components/report/report-item.tsx b/apps/start/src/components/report/report-item.tsx
index 26210b309..eb904cf99 100644
--- a/apps/start/src/components/report/report-item.tsx
+++ b/apps/start/src/components/report/report-item.tsx
@@ -1,3 +1,11 @@
+import { timeWindows } from '@openpanel/core/modules/report/report.constants';
+import { useRouter } from '@tanstack/react-router';
+import {
+ CopyIcon,
+ LayoutPanelTopIcon,
+ MoreHorizontal,
+ Trash,
+} from 'lucide-react';
import { ReportChart } from '@/components/report-chart';
import {
DropdownMenu,
@@ -7,31 +15,21 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
-import {
- CopyIcon,
- LayoutPanelTopIcon,
- 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="card flex h-full animate-pulse flex-col">
+ <div className="flex items-center justify-between border-border border-b 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 className="mb-2 h-5 w-32 rounded bg-muted" />
+ <div className="h-4 w-24 rounded bg-muted/50" />
</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 className="h-8 w-8 rounded bg-muted" />
+ <div className="h-8 w-8 rounded bg-muted" />
</div>
</div>
- <div className="p-4 flex-1 flex items-center justify-center aspect-video" />
+ <div className="flex aspect-video flex-1 items-center justify-center p-4" />
</div>
);
}
@@ -63,15 +61,15 @@ export function ReportItem({
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="card flex h-full flex-col">
+ <div className="flex items-center justify-between border-border border-b p-4 leading-none hover:bg-muted/50 [&_svg]:hover:opacity-100">
<div
- className="flex-1 cursor-pointer -m-4 p-4"
+ className="-m-4 flex-1 cursor-pointer p-4"
onClick={(event) => {
if (event.metaKey) {
window.open(
`/${organizationId}/${projectId}/reports/${report.id}`,
- '_blank',
+ '_blank'
);
return;
}
@@ -101,7 +99,7 @@ export function ReportItem({
>
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
- <div className="mt-2 flex gap-2 ">
+ <div className="mt-2 flex gap-2">
<span
className={
(chartRange !== range && range !== null) ||
@@ -126,13 +124,13 @@ export function ReportItem({
)}
</div>
<div className="flex items-center gap-2">
- <div className="drag-handle cursor-move p-2 hover:bg-muted rounded">
+ <div className="drag-handle cursor-move rounded p-2 hover:bg-muted">
<svg
- width="16"
+ className="opacity-30 hover:opacity-100"
+ fill="currentColor"
height="16"
viewBox="0 0 16 16"
- fill="currentColor"
- className="opacity-30 hover:opacity-100"
+ width="16"
>
<circle cx="4" cy="4" r="1.5" />
<circle cx="4" cy="8" r="1.5" />
@@ -153,7 +151,7 @@ export function ReportItem({
onDuplicate(report.id);
}}
>
- <CopyIcon size={16} className="mr-2" />
+ <CopyIcon className="mr-2" size={16} />
Duplicate
</DropdownMenuItem>
{onMove && (
@@ -163,7 +161,7 @@ export function ReportItem({
onMove(report.id);
}}
>
- <LayoutPanelTopIcon size={16} className="mr-2" />
+ <LayoutPanelTopIcon className="mr-2" size={16} />
Move to dashboard
</DropdownMenuItem>
)}
@@ -175,7 +173,7 @@ export function ReportItem({
onDelete(report.id);
}}
>
- <Trash size={16} className="mr-2" />
+ <Trash className="mr-2" size={16} />
Delete
</DropdownMenuItem>
</DropdownMenuGroup>
@@ -185,8 +183,8 @@ export function ReportItem({
</div>
<div
className={cn(
- 'p-4 overflow-auto flex-1',
- report.chartType === 'metric' && 'p-0',
+ 'flex-1 overflow-auto p-4',
+ report.chartType === 'metric' && 'p-0'
)}
>
<ReportChart
@@ -221,12 +219,12 @@ export function ReportItemReadOnly({
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="card flex h-full flex-col">
+ <div className="flex items-center justify-between border-border border-b p-4 leading-none">
<div className="flex-1">
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
- <div className="mt-2 flex gap-2 ">
+ <div className="mt-2 flex gap-2">
<span
className={
(chartRange !== range && range !== null) ||
@@ -253,8 +251,8 @@ export function ReportItemReadOnly({
</div>
<div
className={cn(
- 'p-4 overflow-auto flex-1',
- report.chartType === 'metric' && 'p-0',
+ 'flex-1 overflow-auto p-4',
+ report.chartType === 'metric' && 'p-0'
)}
>
<ReportChart
diff --git a/apps/start/src/components/report/reportSlice.ts b/apps/start/src/components/report/reportSlice.ts
index 87df79de7..3b23862c2 100644
--- a/apps/start/src/components/report/reportSlice.ts
+++ b/apps/start/src/components/report/reportSlice.ts
@@ -1,13 +1,3 @@
-import type { PayloadAction } from '@reduxjs/toolkit';
-import { createSlice } from '@reduxjs/toolkit';
-
-import { shortId } from '@openpanel/common';
-import {
- getDefaultIntervalByDates,
- getDefaultIntervalByRange,
- isHourIntervalEnabledByRange,
- isMinuteIntervalEnabledByRange,
-} from '@openpanel/constants';
import type {
IChartBreakdown,
IChartEventFilter,
@@ -19,10 +9,19 @@ import type {
IInterval,
IReport,
IReportOptions,
- UnionOmit,
zCriteria,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/report/report.constants';
+import {
+ getDefaultIntervalByDates,
+ getDefaultIntervalByRange,
+ isHourIntervalEnabledByRange,
+ isMinuteIntervalEnabledByRange,
+} from '@openpanel/core/modules/report/report.constants';
+import type { PayloadAction } from '@reduxjs/toolkit';
+import { createSlice } from '@reduxjs/toolkit';
import type { z } from 'zod';
+import { shortId } from '../../utils/math';
+import type { UnionOmit } from '../../utils/union-omit';
type InitialState = IReport & {
id?: string;
@@ -96,7 +95,7 @@ export const reportSlice = createSlice({
// Series (Events and Formulas)
addSerie: (
state,
- action: PayloadAction<UnionOmit<IChartEventItem, 'id'>>,
+ action: PayloadAction<UnionOmit<IChartEventItem, 'id'>>
) => {
state.dirty = true;
state.series.push({
@@ -126,7 +125,7 @@ export const reportSlice = createSlice({
state,
action: PayloadAction<{
id?: string;
- }>,
+ }>
) => {
state.dirty = true;
state.series = state.series.filter((event) => {
@@ -152,7 +151,7 @@ export const reportSlice = createSlice({
// Breakdowns
addBreakdown: (
state,
- action: PayloadAction<Omit<IChartBreakdown, 'id'>>,
+ action: PayloadAction<Omit<IChartBreakdown, 'id'>>
) => {
state.dirty = true;
state.breakdowns.push({
@@ -164,11 +163,11 @@ export const reportSlice = createSlice({
state,
action: PayloadAction<{
id?: string;
- }>,
+ }>
) => {
state.dirty = true;
state.breakdowns = state.breakdowns.filter(
- (event) => event.id !== action.payload.id,
+ (event) => event.id !== action.payload.id
);
},
changeBreakdown: (state, action: PayloadAction<IChartBreakdown>) => {
@@ -189,13 +188,13 @@ export const reportSlice = createSlice({
removeGlobalFilter: (state, action: PayloadAction<{ id?: string }>) => {
state.dirty = true;
state.globalFilters = state.globalFilters.filter(
- (filter) => filter.id !== action.payload.id,
+ (filter) => filter.id !== action.payload.id
);
},
changeGlobalFilter: (state, action: PayloadAction<IChartEventFilter>) => {
state.dirty = true;
state.globalFilters = state.globalFilters.map((filter) =>
- filter.id === action.payload.id ? action.payload : filter,
+ filter.id === action.payload.id ? action.payload : filter
);
},
@@ -256,7 +255,7 @@ export const reportSlice = createSlice({
const interval = getDefaultIntervalByDates(
state.startDate,
- state.endDate,
+ state.endDate
);
if (interval) {
state.interval = interval;
@@ -270,7 +269,7 @@ export const reportSlice = createSlice({
const interval = getDefaultIntervalByDates(
state.startDate,
- state.endDate,
+ state.endDate
);
if (interval) {
state.interval = interval;
@@ -346,7 +345,7 @@ export const reportSlice = createSlice({
},
changeSankeyMode(
state,
- action: PayloadAction<'between' | 'after' | 'before'>,
+ action: PayloadAction<'between' | 'after' | 'before'>
) {
state.dirty = true;
if (!state.options) {
@@ -413,7 +412,7 @@ export const reportSlice = createSlice({
},
reorderEvents(
state,
- action: PayloadAction<{ fromIndex: number; toIndex: number }>,
+ action: PayloadAction<{ fromIndex: number; toIndex: number }>
) {
state.dirty = true;
const { fromIndex, toIndex } = action.payload;
@@ -422,10 +421,7 @@ export const reportSlice = createSlice({
state.series.splice(toIndex, 0, movedEvent);
}
},
- changeVisibleSeries(
- state,
- action: PayloadAction<string[] | undefined>,
- ) {
+ changeVisibleSeries(state, action: PayloadAction<string[] | undefined>) {
state.dirty = true;
state.visibleSeries = action.payload;
},
diff --git a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
index 54c52e713..00e573ba5 100644
--- a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
+++ b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
@@ -1,4 +1,4 @@
-import type { IChartEvent } from '@openpanel/validation';
+import type { IChartEvent } from '@openpanel/core/modules/report/report.constants';
import { useQuery } from '@tanstack/react-query';
import { AnimatePresence, motion } from 'framer-motion';
import {
@@ -137,8 +137,8 @@ export function PropertiesCombobox({
const groupPropertiesQuery = useQuery(
trpc.group.properties.queryOptions(
{ projectId },
- { enabled: categories.includes('group') },
- ),
+ { enabled: categories.includes('group') }
+ )
);
/**
@@ -169,7 +169,9 @@ export function PropertiesCombobox({
};
const shouldShowProperty = (property: string) => {
- return !exclude.some((pattern) => matchesPropertyPattern(property, pattern));
+ return !exclude.some((pattern) =>
+ matchesPropertyPattern(property, pattern)
+ );
};
const allProperties = Array.from(new Set([...properties, ...include]));
@@ -205,7 +207,7 @@ export function PropertiesCombobox({
description: property.split('.').slice(0, -1).join('.'),
}));
const sessionActions = SESSION_ACTIONS.filter((a) =>
- shouldShowProperty(a.value),
+ shouldShowProperty(a.value)
);
const handleStateChange = (newState: State) => {
@@ -293,12 +295,12 @@ export function PropertiesCombobox({
const renderActionList = (
actions: PropertiesComboboxAction[],
- options: { itemKey?: string } = {},
+ options: { itemKey?: string } = {}
) => {
const filtered = actions.filter(
(action) =>
action.label.toLowerCase().includes(search.toLowerCase()) ||
- action.description.toLowerCase().includes(search.toLowerCase()),
+ action.description.toLowerCase().includes(search.toLowerCase())
);
return (
diff --git a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
index 142826700..1fa8ac14c 100644
--- a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
+++ b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
@@ -1,17 +1,12 @@
-import { ColorSquare } from '@/components/color-square';
-import { Combobox } from '@/components/ui/combobox';
-import { useAppParams } from '@/hooks/use-app-params';
-import { useEventProperties } from '@/hooks/use-event-properties';
-import { useDispatch, useSelector } from '@/redux';
+import type { IChartBreakdown } from '@openpanel/core/modules/report/report.constants';
import { ChevronsUpDownIcon, SplitIcon } from 'lucide-react';
-
-import type { IChartBreakdown } from '@openpanel/validation';
-
-import { Button } from '@/components/ui/button';
import { addBreakdown, changeBreakdown, removeBreakdown } from '../reportSlice';
import { PropertiesCombobox } from './PropertiesCombobox';
import { ReportBreakdownMore } from './ReportBreakdownMore';
import type { ReportEventMoreProps } from './ReportEventMore';
+import { ColorSquare } from '@/components/color-square';
+import { Button } from '@/components/ui/button';
+import { useDispatch, useSelector } from '@/redux';
export function ReportBreakdowns() {
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
@@ -35,7 +30,7 @@ export function ReportBreakdowns() {
<div className="flex flex-col gap-4">
{selectedBreakdowns.map((item, index) => {
return (
- <div key={item.name} className="rounded-lg border bg-def-100">
+ <div className="rounded-lg border bg-def-100" key={item.name}>
<div className="flex items-center gap-2 p-2 px-4">
<ColorSquare>{index}</ColorSquare>
<PropertiesCombobox
@@ -45,19 +40,19 @@ export function ReportBreakdowns() {
changeBreakdown({
...item,
name: action.value,
- }),
+ })
);
}}
>
{(setOpen) => (
<Button
- variant={'outline'}
- onClick={() => setOpen((prev) => !prev)}
- size={'sm'}
autoHeight
className="flex-1"
+ onClick={() => setOpen((prev) => !prev)}
+ size={'sm'}
+ variant={'outline'}
>
- <div className="row w-full gap-2 items-center">
+ <div className="row w-full items-center gap-2">
<SplitIcon className="size-4" />
{item.name === 'cohort' ? 'Cohorts' : item.name}
</div>
@@ -77,19 +72,19 @@ export function ReportBreakdowns() {
dispatch(
addBreakdown({
name: action.value,
- }),
+ })
);
}}
>
{(setOpen) => (
<Button
- variant={'outline'}
- onClick={() => setOpen((prev) => !prev)}
- size={'sm'}
autoHeight
className="flex-1"
+ onClick={() => setOpen((prev) => !prev)}
+ size={'sm'}
+ variant={'outline'}
>
- <div className="row w-full gap-2 items-center">
+ <div className="row w-full items-center gap-2">
<SplitIcon className="size-4" />
Select breakdown
</div>
diff --git a/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx b/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx
index 3ad97746a..40426ace2 100644
--- a/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx
+++ b/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx
@@ -1,10 +1,9 @@
-import { useDispatch, useSelector } from '@/redux';
-import { shortId } from '@openpanel/common';
import { FilterIcon, type LucideIcon } from 'lucide-react';
-
+import { shortId } from '../../../utils/math';
import { addGlobalFilter } from '../reportSlice';
-import { PropertiesCombobox } from './PropertiesCombobox';
import { GlobalFilterItem } from './filters/GlobalFilterItem';
+import { PropertiesCombobox } from './PropertiesCombobox';
+import { useDispatch, useSelector } from '@/redux';
export function ReportGlobalFilters() {
const globalFilters = useSelector((state) => state.report.globalFilters);
@@ -13,7 +12,7 @@ export function ReportGlobalFilters() {
return (
<div>
<h3 className="mb-2 font-medium">Global filters</h3>
- <p className="mb-2 text-sm text-muted-foreground">
+ <p className="mb-2 text-muted-foreground text-sm">
Applied to every series in this report.
</p>
<div className="rounded-lg border bg-def-100">
@@ -26,7 +25,7 @@ export function ReportGlobalFilters() {
isCohortAction &&
globalFilters.some(
(f) =>
- f.operator === 'inCohort' || f.operator === 'notInCohort',
+ f.operator === 'inCohort' || f.operator === 'notInCohort'
)
) {
return;
@@ -47,16 +46,13 @@ export function ReportGlobalFilters() {
operator: 'is',
value: [],
type: 'string',
- },
- ),
+ }
+ )
);
}}
>
{(setOpen) => (
- <SmallButton
- onClick={() => setOpen((p) => !p)}
- icon={FilterIcon}
- >
+ <SmallButton icon={FilterIcon} onClick={() => setOpen((p) => !p)}>
Add filter
</SmallButton>
)}
@@ -67,8 +63,8 @@ export function ReportGlobalFilters() {
<div className="flex flex-col divide-y overflow-hidden rounded-b-lg">
{globalFilters.map((filter) => (
<GlobalFilterItem
- key={filter.id ?? filter.name}
filter={filter}
+ key={filter.id ?? filter.name}
/>
))}
</div>
@@ -88,11 +84,11 @@ function SmallButton({
} & React.ButtonHTMLAttributes<HTMLButtonElement>) {
return (
<button
+ className="flex min-w-0 items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-left font-medium text-sm leading-none"
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 text-left min-w-0"
{...props}
>
- <Icon size={12} className="shrink-0" />
+ <Icon className="shrink-0" size={12} />
<span className="truncate">{children}</span>
</button>
);
diff --git a/apps/start/src/components/report/sidebar/ReportSeries.tsx b/apps/start/src/components/report/sidebar/ReportSeries.tsx
index bd46b070b..9bb884845 100644
--- a/apps/start/src/components/report/sidebar/ReportSeries.tsx
+++ b/apps/start/src/components/report/sidebar/ReportSeries.tsx
@@ -1,19 +1,9 @@
-import { ColorSquare } from '@/components/color-square';
-import { Button } from '@/components/ui/button';
-import { Checkbox } from '@/components/ui/checkbox';
-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 {
+ closestCenter,
DndContext,
type DragEndEvent,
KeyboardSensor,
PointerSensor,
- closestCenter,
useSensor,
useSensors,
} from '@dnd-kit/core';
@@ -24,12 +14,12 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
-import { alphabetIds } from '@openpanel/constants';
import type {
IChartEvent,
IChartEventItem,
IChartFormula,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/report/report.constants';
+import { alphabetIds } from '@openpanel/core/modules/report/report.constants';
import { HandIcon, PiIcon, PlusIcon } from 'lucide-react';
import {
addSerie,
@@ -44,6 +34,16 @@ import {
ReportSeriesItem,
type ReportSeriesItemProps,
} from './ReportSeriesItem';
+import { ColorSquare } from '@/components/color-square';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+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';
// Matches a single uppercase letter that isn't part of a larger identifier,
// which is how mathjs treats series references in formulas (A, B, C, ...).
@@ -51,7 +51,7 @@ const ALPHA_REFERENCE_REGEX = /(?<![a-zA-Z0-9_])[A-Z](?![a-zA-Z0-9_])/g;
function getReferencedAlphaIds(
formula: string,
- formulaIndex: number,
+ formulaIndex: number
): string[] {
if (!formula) {
return [];
@@ -96,19 +96,19 @@ function SortableReportSeriesItem({
<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">
+ <HandIcon className="absolute inset-1 size-3 scale-50 opacity-0 transition-all group-hover:scale-100 group-hover:opacity-100" />
+ <span className="block transition-all group-hover:scale-0 group-hover:opacity-0">
{alphabetIds[index]}
</span>
</ColorSquare>
</button>
)}
+ showAddFilter={showAddFilter}
+ showSegment={showSegment}
{...props}
/>
</div>
@@ -152,7 +152,7 @@ export function ReportSeries() {
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
- }),
+ })
);
const handleDragEnd = (event: DragEndEvent) => {
@@ -173,7 +173,7 @@ export function ReportSeries() {
return dispatch(
removeEvent({
id: 'type' in event ? event.id : (event as IChartEvent).id,
- }),
+ })
);
}
case 'duplicate': {
@@ -201,9 +201,9 @@ export function ReportSeries() {
<div>
<h3 className="mb-2 font-medium">Metrics</h3>
<DndContext
- sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
+ sensors={sensors}
>
<SortableContext
items={selectedSeries.map((e) => ({
@@ -217,30 +217,29 @@ export function ReportSeries() {
return (
<SortableReportSeriesItem
- key={event.id}
+ className="rounded-lg border bg-def-100"
event={event}
index={index}
- showSegment={showSegment}
- showAddFilter={showAddFilter}
isSelectManyEvents={isSelectManyEvents}
- className="rounded-lg border bg-def-100"
+ key={event.id}
+ showAddFilter={showAddFilter}
+ showSegment={showSegment}
>
{isFormula ? (
<>
- <div className="flex-1 flex flex-col gap-2">
+ <div className="flex flex-1 flex-col gap-2">
<InputEnter
- placeholder="eg: A+B"
- value={event.formula}
onChangeValue={(value) => {
dispatchChangeFormula({
...event,
formula: value,
});
}}
+ placeholder="eg: A+B"
+ value={event.formula}
/>
{showDisplayNameInput && (
<Input
- placeholder={`Name: Formula (${alphabetIds[index]})`}
defaultValue={event.displayName}
onChange={(e) => {
dispatchChangeFormula({
@@ -248,12 +247,13 @@ export function ReportSeries() {
displayName: e.target.value,
});
}}
+ placeholder={`Name: Formula (${alphabetIds[index]})`}
/>
)}
{(() => {
const referencedAlphaIds = getReferencedAlphaIds(
event.formula,
- index,
+ index
);
if (referencedAlphaIds.length === 0) {
return null;
@@ -265,8 +265,8 @@ export function ReportSeries() {
const isHidden = hideSeries.includes(alphaId);
return (
<label
+ className="flex cursor-pointer select-none items-center gap-1.5 font-medium text-xs"
key={alphaId}
- className="flex items-center gap-1.5 text-xs font-medium select-none cursor-pointer"
>
<Checkbox
checked={isHidden}
@@ -274,18 +274,18 @@ export function ReportSeries() {
const next = checked
? [
...hideSeries.filter(
- (id) => id !== alphaId,
+ (id) => id !== alphaId
),
alphaId,
]
: hideSeries.filter(
- (id) => id !== alphaId,
+ (id) => id !== alphaId
);
dispatch(
changeEvent({
...event,
hideSeries: next,
- }),
+ })
);
}}
/>
@@ -303,21 +303,8 @@ export function ReportSeries() {
<>
<ComboboxEvents
className="flex-1"
- searchable
+ items={eventNames}
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(
@@ -330,7 +317,7 @@ export function ReportSeries() {
{
name: 'name',
operator: 'is',
- value: value,
+ value,
},
],
name: '*',
@@ -340,20 +327,28 @@ export function ReportSeries() {
type: 'event',
name: value,
filters: [],
- },
- ),
+ }
+ )
);
}}
- items={eventNames}
placeholder="Select event"
+ searchable
+ value={
+ (isSelectManyEvents
+ ? ((
+ event as IChartEventItem & {
+ type: 'event';
+ }
+ ).filters[0]?.value ?? [])
+ : (
+ event as IChartEventItem & {
+ type: 'event';
+ }
+ ).name) as any
+ }
/>
{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
@@ -366,6 +361,11 @@ export function ReportSeries() {
displayName: e.target.value,
});
}}
+ placeholder={
+ (event as IChartEventItem & { type: 'event' }).name
+ ? `${(event as IChartEventItem & { type: 'event' }).name} (${alphabetIds[index]})`
+ : 'Display name'
+ }
/>
)}
<ReportEventMore onClick={handleMore(event)} />
@@ -379,8 +379,7 @@ export function ReportSeries() {
<ComboboxEvents
className="flex-1"
disabled={isAddEventDisabled || isSankeyEventLimitReached}
- value={''}
- searchable
+ items={eventNames}
onChange={(value) => {
if (isSelectManyEvents) {
dispatch(
@@ -395,7 +394,7 @@ export function ReportSeries() {
value: [value],
},
],
- }),
+ })
);
} else {
dispatch(
@@ -404,31 +403,32 @@ export function ReportSeries() {
name: value,
segment: 'event',
filters: [],
- }),
+ })
);
}
}}
placeholder="Select event"
- items={eventNames}
+ searchable
+ value={''}
/>
{showFormula && (
<Button
- type="button"
- variant="outline"
+ className="flex-1 justify-start px-4 text-left"
icon={PiIcon}
- className="flex-1 justify-start text-left px-4"
onClick={() => {
dispatch(
addSerie({
type: 'formula',
formula: '',
displayName: '',
- }),
+ })
);
}}
+ type="button"
+ variant="outline"
>
Add Formula
- <PlusIcon className="size-4 ml-auto text-muted-foreground" />
+ <PlusIcon className="ml-auto size-4 text-muted-foreground" />
</Button>
)}
</div>
diff --git a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
index 6f8a22115..b09208006 100644
--- a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
+++ b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
@@ -1,13 +1,16 @@
-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 type {
+ IChartEvent,
+ IChartEventItem,
+} from '@openpanel/core/modules/report/report.constants';
+import { alphabetIds } from '@openpanel/core/modules/report/report.constants';
import { DatabaseIcon, FilterIcon, type LucideIcon } from 'lucide-react';
+import { shortId } from '../../../utils/math';
import { ReportSegment } from '../ReportSegment';
import { changeEvent } from '../reportSlice';
-import { PropertiesCombobox } from './PropertiesCombobox';
import { FiltersList } from './filters/FiltersList';
+import { PropertiesCombobox } from './PropertiesCombobox';
+import { ColorSquare } from '@/components/color-square';
+import { useDispatch } from '@/redux';
export interface ReportSeriesItemProps
extends React.HTMLAttributes<HTMLDivElement> {
@@ -41,7 +44,7 @@ export function ReportSeriesItem({
return (
<div {...props}>
- <div className="flex items-center gap-2 p-2 group">
+ <div className="group flex items-center gap-2 p-2">
{renderDragHandle ? (
renderDragHandle(index)
) : (
@@ -57,28 +60,28 @@ export function ReportSeriesItem({
<div className="flex gap-2 p-2 pt-0">
{showSegment && (
<ReportSegment
- value={chartEvent.segment}
onChange={(segment) => {
dispatch(
changeEvent({
...chartEvent,
segment,
- }),
+ })
);
}}
+ value={chartEvent.segment}
/>
)}
{showAddFilter && (
<PropertiesCombobox
- event={chartEvent}
categories={['event', 'profile', 'group', 'cohort']}
+ event={chartEvent}
onSelect={(action) => {
const isCohortAction = action.value === 'cohort';
if (
isCohortAction &&
chartEvent.filters.some(
(f) =>
- f.operator === 'inCohort' || f.operator === 'notInCohort',
+ f.operator === 'inCohort' || f.operator === 'notInCohort'
)
) {
return;
@@ -104,14 +107,14 @@ export function ReportSeriesItem({
type: 'string',
},
],
- }),
+ })
);
}}
>
{(setOpen) => (
<SmallButton
- onClick={() => setOpen((p) => !p)}
icon={FilterIcon}
+ onClick={() => setOpen((p) => !p)}
>
Add filter
</SmallButton>
@@ -121,15 +124,15 @@ export function ReportSeriesItem({
{showSegment && chartEvent.segment.startsWith('property_') && (
<PropertiesCombobox
- include={chartEvent.name === 'session_end' ? ['duration'] : []}
event={chartEvent}
+ include={chartEvent.name === 'session_end' ? ['duration'] : []}
onSelect={(item) => {
dispatch(
changeEvent({
...chartEvent,
property: item.value,
type: 'event',
- }),
+ })
);
}}
>
@@ -167,11 +170,11 @@ function SmallButton({
} & React.ButtonHTMLAttributes<HTMLButtonElement>) {
return (
<button
+ className="flex min-w-0 items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-left font-medium text-sm leading-none"
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 text-left min-w-0"
{...props}
>
- <Icon size={12} className="shrink-0" />
+ <Icon className="shrink-0" size={12} />
<span className="truncate">{children}</span>
</button>
);
diff --git a/apps/start/src/components/report/sidebar/ReportSettings.tsx b/apps/start/src/components/report/sidebar/ReportSettings.tsx
index 777a93d28..cdc883002 100644
--- a/apps/start/src/components/report/sidebar/ReportSettings.tsx
+++ b/apps/start/src/components/report/sidebar/ReportSettings.tsx
@@ -1,13 +1,4 @@
-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 type { IChartMetric } from '@openpanel/validation';
+import type { IChartMetric } from '@openpanel/core/modules/report/report.constants';
import { useMemo } from 'react';
import {
changeCriteria,
@@ -22,6 +13,14 @@ import {
changeStacked,
changeUnit,
} from '../reportSlice';
+import { Combobox } from '@/components/ui/combobox';
+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 { useDispatch, useSelector } from '@/redux';
export function ReportSettings() {
const chartType = useSelector((state) => state.report.chartType);
@@ -87,9 +86,9 @@ export function ReportSettings() {
return (
<div>
<h3 className="mb-2 font-medium">Settings</h3>
- <div className="col rounded-lg border bg-card p-4 gap-4">
+ <div className="col gap-4 rounded-lg border bg-card p-4">
{fields.includes('previous') && (
- <Label className="flex items-center justify-between mb-0">
+ <Label className="mb-0 flex items-center justify-between">
<span className="whitespace-nowrap">
Compare to previous period
</span>
@@ -101,14 +100,11 @@ export function ReportSettings() {
)}
{fields.includes('criteria') && (
<div className="flex items-center justify-between gap-4">
- <Label className="whitespace-nowrap font-medium mb-0">
+ <Label className="mb-0 whitespace-nowrap font-medium">
Criteria
</Label>
<Combobox
align="end"
- placeholder="Select criteria"
- value={criteria}
- onChange={(val) => dispatch(changeCriteria(val))}
items={[
{
label: 'On or After',
@@ -119,19 +115,17 @@ export function ReportSettings() {
value: 'on',
},
]}
+ onChange={(val) => dispatch(changeCriteria(val))}
+ placeholder="Select criteria"
+ value={criteria}
/>
</div>
)}
{fields.includes('unit') && (
<div className="flex items-center justify-between gap-4">
- <Label className="whitespace-nowrap font-medium mb-0">Unit</Label>
+ <Label className="mb-0 whitespace-nowrap font-medium">Unit</Label>
<Combobox
align="end"
- placeholder="Unit"
- value={unit || 'count'}
- onChange={(val) => {
- dispatch(changeUnit(val === 'count' ? undefined : val));
- }}
items={[
{
label: 'Count',
@@ -142,20 +136,21 @@ export function ReportSettings() {
value: '%',
},
]}
+ onChange={(val) => {
+ dispatch(changeUnit(val === 'count' ? undefined : val));
+ }}
+ placeholder="Unit"
+ value={unit || 'count'}
/>
</div>
)}
{fields.includes('metric') && (
<div className="flex items-center justify-between gap-4">
- <Label className="whitespace-nowrap font-medium mb-0">
+ <Label className="mb-0 whitespace-nowrap font-medium">
Aggregation
</Label>
<Combobox
align="end"
- placeholder="Aggregation"
- value={metric}
- onChange={(val) => dispatch(changeMetric(val as IChartMetric))}
- // Same labels the report table uses for these columns.
items={[
{ label: 'Unique', value: 'count' },
{ label: 'Sum', value: 'sum' },
@@ -163,23 +158,20 @@ export function ReportSettings() {
{ label: 'Min', value: 'min' },
{ label: 'Max', value: 'max' },
]}
+ onChange={(val) => dispatch(changeMetric(val as IChartMetric))}
+ placeholder="Aggregation"
+ // Same labels the report table uses for these columns.
+ value={metric}
/>
</div>
)}
{fields.includes('funnelGroup') && (
<div className="flex items-center justify-between gap-4">
- <Label className="whitespace-nowrap font-medium mb-0">
+ <Label className="mb-0 whitespace-nowrap font-medium">
Funnel Group
</Label>
<Combobox
align="end"
- placeholder="Default: Session"
- value={funnelGroup || 'session_id'}
- onChange={(val) => {
- dispatch(
- changeFunnelGroup(val === 'session_id' ? undefined : val),
- );
- }}
items={[
{
label: 'Session',
@@ -190,18 +182,22 @@ export function ReportSettings() {
value: 'profile_id',
},
]}
+ onChange={(val) => {
+ dispatch(
+ changeFunnelGroup(val === 'session_id' ? undefined : val)
+ );
+ }}
+ placeholder="Default: Session"
+ value={funnelGroup || 'session_id'}
/>
</div>
)}
{fields.includes('funnelWindow') && (
<div className="flex items-center justify-between gap-4">
- <Label className="whitespace-nowrap font-medium mb-0">
+ <Label className="mb-0 whitespace-nowrap font-medium">
Funnel Window
</Label>
<InputEnter
- type="number"
- value={funnelWindow ? String(funnelWindow) : ''}
- placeholder="Default: 24h"
onChangeValue={(value) => {
const parsed = Number.parseFloat(value);
if (Number.isNaN(parsed)) {
@@ -210,21 +206,17 @@ export function ReportSettings() {
dispatch(changeFunnelWindow(parsed));
}
}}
+ placeholder="Default: 24h"
+ type="number"
+ value={funnelWindow ? String(funnelWindow) : ''}
/>
</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>
+ <Label className="mb-0 whitespace-nowrap font-medium">Mode</Label>
<Combobox
align="end"
- placeholder="Select mode"
- value={options?.mode || 'after'}
- onChange={(val) => {
- dispatch(
- changeSankeyMode(val as 'between' | 'after' | 'before'),
- );
- }}
items={[
{
label: 'After',
@@ -239,16 +231,20 @@ export function ReportSettings() {
value: 'between',
},
]}
+ onChange={(val) => {
+ dispatch(
+ changeSankeyMode(val as 'between' | 'after' | 'before')
+ );
+ }}
+ placeholder="Select mode"
+ value={options?.mode || 'after'}
/>
</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>
+ <Label className="mb-0 whitespace-nowrap font-medium">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) {
@@ -257,6 +253,9 @@ export function ReportSettings() {
dispatch(changeSankeySteps(parsed));
}
}}
+ placeholder="Default: 5"
+ type="number"
+ value={options?.steps ? String(options.steps) : '5'}
/>
</div>
)}
@@ -266,14 +265,14 @@ export function ReportSettings() {
Exclude Events
</Label>
<ComboboxEvents
+ items={eventNames.filter((item) => item.name !== '*')}
multiple
- searchable
- value={options?.exclude || []}
onChange={(value) => {
dispatch(changeSankeyExclude(value));
}}
- items={eventNames.filter((item) => item.name !== '*')}
placeholder="Select events to exclude"
+ searchable
+ value={options?.exclude || []}
/>
</div>
)}
@@ -283,21 +282,21 @@ export function ReportSettings() {
Include events
</Label>
<ComboboxEvents
+ items={eventNames.filter((item) => item.name !== '*')}
multiple
- searchable
- value={options?.include || []}
onChange={(value) => {
dispatch(
- changeSankeyInclude(value.length > 0 ? value : undefined),
+ changeSankeyInclude(value.length > 0 ? value : undefined)
);
}}
- items={eventNames.filter((item) => item.name !== '*')}
placeholder="Leave empty to include all"
+ searchable
+ value={options?.include || []}
/>
</div>
)}
{fields.includes('stacked') && (
- <Label className="flex items-center justify-between mb-0">
+ <Label className="mb-0 flex items-center justify-between">
<span className="whitespace-nowrap">Stack series</span>
<Switch
checked={stacked}
diff --git a/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx b/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx
index 9b1fda0b6..4a678c172 100644
--- a/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx
+++ b/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx
@@ -1,19 +1,19 @@
-import { ColorSquare } from '@/components/color-square';
-import { RenderDots } from '@/components/ui/RenderDots';
-import { Button } from '@/components/ui/button';
-import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
-import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
-import { useAppParams } from '@/hooks/use-app-params';
-import { useCohorts } from '@/hooks/use-cohorts';
-import { useDispatch } from '@/redux';
import {
getCohortIds,
type IChartEvent,
type IChartEventFilter,
type IChartEventFilterOperator,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/report/report.constants';
import { SlidersHorizontal, Trash } from 'lucide-react';
import { changeEvent } from '../../reportSlice';
+import { ColorSquare } from '@/components/color-square';
+import { Button } from '@/components/ui/button';
+import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
+import { RenderDots } from '@/components/ui/RenderDots';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useCohorts } from '@/hooks/use-cohorts';
+import { useDispatch } from '@/redux';
interface CohortFilterItemProps {
event: IChartEvent;
@@ -25,7 +25,7 @@ interface PureCohortFilterItemProps {
onRemove: (filter: IChartEventFilter) => void;
onChangeOperator: (
operator: IChartEventFilterOperator,
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => void;
onChangeCohort: (cohortIds: string[], filter: IChartEventFilter) => void;
className?: string;
@@ -40,22 +40,22 @@ export function CohortFilterItem({ filter, event }: CohortFilterItemProps) {
...event,
filters: event.filters.filter((item) => item.id !== id),
type: 'event',
- }),
+ })
);
};
const onChangeOperator = (
operator: IChartEventFilterOperator,
- { id }: IChartEventFilter,
+ { id }: IChartEventFilter
) => {
dispatch(
changeEvent({
...event,
type: 'event',
filters: event.filters.map((item) =>
- item.id === id ? { ...item, operator } : item,
+ item.id === id ? { ...item, operator } : item
),
- }),
+ })
);
};
@@ -75,19 +75,19 @@ export function CohortFilterItem({ filter, event }: CohortFilterItemProps) {
cohortId: firstId,
cohortIds,
}
- : item,
+ : item
),
- }),
+ })
);
};
return (
<PureCohortFilterItem
+ className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
filter={filter}
- onRemove={onRemove}
- onChangeOperator={onChangeOperator}
onChangeCohort={onChangeCohort}
- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
+ onChangeOperator={onChangeOperator}
+ onRemove={onRemove}
/>
);
}
@@ -132,7 +132,7 @@ export function PureCohortFilterItem({
const changeCohort = (next: Array<string | number>) => {
onChangeCohort(
next.filter((id): id is string => typeof id === 'string'),
- filter,
+ filter
);
};
@@ -145,29 +145,29 @@ export function PureCohortFilterItem({
<div className="flex flex-1">
<RenderDots truncate>{cohortLabel}</RenderDots>
</div>
- <Button variant="ghost" size="sm" onClick={removeFilter}>
+ <Button onClick={removeFilter} size="sm" variant="ghost">
<Trash size={16} />
</Button>
</div>
<div className="flex gap-1">
<DropdownMenuComposed
- onChange={changeFilterOperator}
items={[
{ value: 'inCohort', label: 'In cohort' },
{ value: 'notInCohort', label: 'Not in cohort' },
]}
label="Operator"
+ onChange={changeFilterOperator}
>
- <Button variant="outline" className="whitespace-nowrap">
+ <Button className="whitespace-nowrap" variant="outline">
{filter.operator === 'inCohort' ? 'In cohort' : 'Not in cohort'}
</Button>
</DropdownMenuComposed>
<ComboboxAdvanced
- items={cohortsCombobox}
- value={selectedIds}
className="flex-1"
+ items={cohortsCombobox}
onChange={changeCohort}
placeholder="Select cohorts..."
+ value={selectedIds}
/>
</div>
</div>
diff --git a/apps/start/src/components/report/sidebar/filters/FilterItem.tsx b/apps/start/src/components/report/sidebar/filters/FilterItem.tsx
index 1f67d7805..e6dd2cbde 100644
--- a/apps/start/src/components/report/sidebar/filters/FilterItem.tsx
+++ b/apps/start/src/components/report/sidebar/filters/FilterItem.tsx
@@ -1,34 +1,33 @@
+import type {
+ IChartEvent,
+ IChartEventFilter,
+ IChartEventFilterOperator,
+ IChartEventFilterValue,
+ IChartFilterValueType,
+} from '@openpanel/core/modules/report/report.constants';
+import { getOperatorsForType } from '@openpanel/core/modules/report/report.constants';
+import { SlidersHorizontal, Trash } from 'lucide-react';
+import { changeEvent } from '../../reportSlice';
import { ColorSquare } from '@/components/color-square';
import { FilterOperatorSelect } from '@/components/report/sidebar/filters/FilterOperatorSelect';
import { FilterTypeSelect } from '@/components/report/sidebar/filters/FilterTypeSelect';
-import { RenderDots } from '@/components/ui/RenderDots';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
import { ComboboxEvents } from '@/components/ui/combobox-events';
import { InputEnter } from '@/components/ui/input-enter';
+import { RenderDots } from '@/components/ui/RenderDots';
import { useAppParams } from '@/hooks/use-app-params';
import { useEventNames } from '@/hooks/use-event-names';
import { usePropertyValues } from '@/hooks/use-property-values';
import { useDispatch } from '@/redux';
-import { getOperatorsForType } from '@openpanel/constants';
-import type {
- IChartEvent,
- IChartEventFilter,
- IChartEventFilterOperator,
- IChartEventFilterValue,
- IChartFilterValueType,
-} from '@openpanel/validation';
-
-import { SlidersHorizontal, Trash } from 'lucide-react';
-import { changeEvent } from '../../reportSlice';
// Client-side sanity check: can this raw value possibly match the chosen cast
// type? Mirrors the SQL casts in packages/db filter-cast.ts. Returns an error
// message to show inline, or undefined when valid (or empty / untyped).
function validateFilterValue(
value: string,
- type: IChartFilterValueType | undefined,
+ type: IChartFilterValueType | undefined
): string | undefined {
if (!value) {
return undefined;
@@ -59,17 +58,17 @@ interface PureFilterProps {
onRemove: (filter: IChartEventFilter) => void;
onChangeValue: (
value: IChartEventFilterValue[],
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => void;
onChangeOperator: (
operator: IChartEventFilterOperator,
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => void;
// Optional: surfaces the cast-type select. Callers that don't pass it (the
// overview/table/cohort modals) simply don't render the control.
onChangeType?: (
type: IChartFilterValueType,
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => void;
className?: string;
immediateInput?: boolean;
@@ -82,13 +81,13 @@ export function FilterItem({ filter, event }: FilterProps) {
...event,
filters: event.filters.filter((item) => item.id !== id),
type: 'event',
- }),
+ })
);
};
const onChangeValue = (
value: IChartEventFilterValue[],
- { id }: IChartEventFilter,
+ { id }: IChartEventFilter
) => {
dispatch(
changeEvent({
@@ -104,13 +103,13 @@ export function FilterItem({ filter, event }: FilterProps) {
return item;
}),
- }),
+ })
);
};
const onChangeOperator = (
operator: IChartEventFilterOperator,
- { id }: IChartEventFilter,
+ { id }: IChartEventFilter
) => {
dispatch(
changeEvent({
@@ -127,13 +126,13 @@ export function FilterItem({ filter, event }: FilterProps) {
return item;
}),
- }),
+ })
);
};
const onChangeType = (
type: IChartFilterValueType,
- { id }: IChartEventFilter,
+ { id }: IChartEventFilter
) => {
dispatch(
changeEvent({
@@ -149,7 +148,7 @@ export function FilterItem({ filter, event }: FilterProps) {
// like onChangeOperator does, since the input shape may change).
const allowed = getOperatorsForType(type);
const operator = (allowed as readonly string[]).includes(
- item.operator,
+ item.operator
)
? item.operator
: allowed[0]!;
@@ -166,20 +165,20 @@ export function FilterItem({ filter, event }: FilterProps) {
: [],
};
}),
- }),
+ })
);
};
const dispatch = useDispatch();
return (
<PureFilterItem
- filter={filter}
+ className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
eventName={event.name}
- onRemove={onRemove}
- onChangeValue={onChangeValue}
+ filter={filter}
onChangeOperator={onChangeOperator}
onChangeType={onChangeType}
- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
+ onChangeValue={onChangeValue}
+ onRemove={onRemove}
/>
);
}
@@ -211,13 +210,11 @@ export function PureFilterItem({
// Only the free-text input path (gt/gte/lt/lte) carries a single typed value
// we can validate inline; is/isNot use a multi-value combobox.
const usesTypedInput =
- showTypeSelect &&
- filter.operator !== 'is' &&
- filter.operator !== 'isNot';
+ showTypeSelect && filter.operator !== 'is' && filter.operator !== 'isNot';
const valueError = usesTypedInput
? validateFilterValue(
filter.value[0] != null ? String(filter.value[0]) : '',
- filter.type,
+ filter.type
)
: undefined;
@@ -265,11 +262,9 @@ export function PureFilterItem({
<Combobox
className="flex-1"
items={BOOLEAN_VALUE_ITEMS}
- value={
- filter.value[0] === undefined ? null : String(filter.value[0])
- }
onChange={(v) => changeFilterValue([v])}
placeholder="Yes / No"
+ value={filter.value[0] === undefined ? null : String(filter.value[0])}
/>
);
}
@@ -279,10 +274,10 @@ export function PureFilterItem({
<ComboboxEvents
className="flex-1"
items={eventNames}
- value={filter.value[0] ? String(filter.value[0]) : null}
onChange={(v: string) => changeFilterValue([v])}
placeholder="Select event"
searchable
+ value={filter.value[0] ? String(filter.value[0]) : null}
/>
);
}
@@ -290,21 +285,21 @@ export function PureFilterItem({
if (filter.operator === 'is' || filter.operator === 'isNot') {
return (
<ComboboxAdvanced
- items={valuesCombobox}
- value={filter.value}
className="flex-1"
+ items={valuesCombobox}
onChange={changeFilterValue}
placeholder="Select..."
+ value={filter.value}
/>
);
}
return (
<InputEnter
- value={filter.value[0] ? String(filter.value[0]) : ''}
- onChangeValue={(value) => changeFilterValue([value])}
- immediate={immediateInput}
error={valueError}
+ immediate={immediateInput}
+ onChangeValue={(value) => changeFilterValue([value])}
+ value={filter.value[0] ? String(filter.value[0]) : ''}
/>
);
};
@@ -315,24 +310,21 @@ export function PureFilterItem({
<ColorSquare className="bg-emerald-500">
<SlidersHorizontal size={10} />
</ColorSquare>
- <div className="flex flex-1 ">
+ <div className="flex flex-1">
<RenderDots truncate>{filter.name}</RenderDots>
</div>
- <Button variant="ghost" size="sm" onClick={removeFilter}>
+ <Button onClick={removeFilter} size="sm" variant="ghost">
<Trash size={16} />
</Button>
</div>
<div className="flex gap-1">
{showTypeSelect && (
- <FilterTypeSelect
- value={filter.type}
- onChange={changeFilterType}
- />
+ <FilterTypeSelect onChange={changeFilterType} value={filter.type} />
)}
<FilterOperatorSelect
- value={filter.operator}
onChange={changeFilterOperator}
type={filter.type}
+ value={filter.operator}
/>
{renderValueControl()}
</div>
diff --git a/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx b/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx
index d0bdb58e4..a2b94f4c8 100644
--- a/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx
+++ b/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx
@@ -1,14 +1,14 @@
-import { Button } from '@/components/ui/button';
-import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
+import type {
+ IChartEventFilterOperator,
+ IChartFilterValueType,
+} from '@openpanel/core/modules/report/report.constants';
import {
getOperatorsForType,
operators,
operatorsShort,
-} from '@openpanel/constants';
-import type {
- IChartEventFilterOperator,
- IChartFilterValueType,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/report/report.constants';
+import { Button } from '@/components/ui/button';
+import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
interface FilterOperatorSelectProps {
value: IChartEventFilterOperator;
@@ -26,14 +26,13 @@ export function FilterOperatorSelect({
children,
}: FilterOperatorSelectProps) {
const trigger = children ?? (
- <Button variant="outline" className="whitespace-nowrap">
+ <Button className="whitespace-nowrap" variant="outline">
{operatorsShort[value]}
</Button>
);
return (
<DropdownMenuComposed
- onChange={onChange}
items={getOperatorsForType(type).map((key) => ({
value: key,
label: operatorsShort[key],
@@ -43,6 +42,7 @@ export function FilterOperatorSelect({
operatorsShort[key] === operators[key] ? undefined : operators[key],
}))}
label="Operator"
+ onChange={onChange}
>
{trigger}
</DropdownMenuComposed>
diff --git a/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx b/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx
index c89ab1578..895e0f4fd 100644
--- a/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx
+++ b/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx
@@ -1,8 +1,8 @@
+import type { IChartFilterValueType } from '@openpanel/core/modules/report/report.constants';
+import { filterValueTypes } from '@openpanel/core/modules/report/report.constants';
import { Button } from '@/components/ui/button';
import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
import { mapKeys } from '@/utils/object-to-zod-enums';
-import { filterValueTypes } from '@openpanel/constants';
-import type { IChartFilterValueType } from '@openpanel/validation';
interface FilterTypeSelectProps {
value: IChartFilterValueType | undefined;
@@ -19,19 +19,19 @@ export function FilterTypeSelect({
children,
}: FilterTypeSelectProps) {
const trigger = children ?? (
- <Button variant="outline" className="whitespace-nowrap">
+ <Button className="whitespace-nowrap" variant="outline">
{filterValueTypes[value ?? 'string']}
</Button>
);
return (
<DropdownMenuComposed
- onChange={onChange}
items={mapKeys(filterValueTypes).map((key) => ({
value: key,
label: filterValueTypes[key],
}))}
label="Value type"
+ onChange={onChange}
>
{trigger}
</DropdownMenuComposed>
diff --git a/apps/start/src/components/report/sidebar/filters/FiltersList.tsx b/apps/start/src/components/report/sidebar/filters/FiltersList.tsx
index b5308aacb..88c5c634e 100644
--- a/apps/start/src/components/report/sidebar/filters/FiltersList.tsx
+++ b/apps/start/src/components/report/sidebar/filters/FiltersList.tsx
@@ -1,5 +1,4 @@
-import type { IChartEvent } from '@openpanel/validation';
-
+import type { IChartEvent } from '@openpanel/core/modules/report/report.constants';
import { CohortFilterItem } from './CohortFilterItem';
import { FilterItem } from './FilterItem';
@@ -27,25 +26,24 @@ export function FiltersList({
return (
<div>
- <div className="bg-def-100 flex flex-col divide-y overflow-hidden rounded-b-md">
+ <div className="flex flex-col divide-y overflow-hidden rounded-b-md bg-def-100">
{filters.map((filter) => {
const isCohortFilter =
- filter.operator === 'inCohort' ||
- filter.operator === 'notInCohort';
+ filter.operator === 'inCohort' || filter.operator === 'notInCohort';
if (isCohortFilter) {
return (
<CohortFilterItem
- key={filter.id ?? filter.name}
- filter={filter}
event={event}
+ filter={filter}
+ key={filter.id ?? filter.name}
/>
);
}
return (
<FilterItem
- key={filter.id ?? filter.name}
- filter={filter}
event={event}
+ filter={filter}
+ key={filter.id ?? filter.name}
/>
);
})}
diff --git a/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx b/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx
index e794873d1..8aa04ecf2 100644
--- a/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx
+++ b/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx
@@ -1,18 +1,14 @@
-import { useDispatch } from '@/redux';
-import { getOperatorsForType } from '@openpanel/constants';
import type {
IChartEventFilter,
IChartEventFilterOperator,
IChartEventFilterValue,
IChartFilterValueType,
-} from '@openpanel/validation';
-
-import {
- changeGlobalFilter,
- removeGlobalFilter,
-} from '../../reportSlice';
+} from '@openpanel/core/modules/report/report.constants';
+import { getOperatorsForType } from '@openpanel/core/modules/report/report.constants';
+import { changeGlobalFilter, removeGlobalFilter } from '../../reportSlice';
import { PureCohortFilterItem } from './CohortFilterItem';
import { PureFilterItem } from './FilterItem';
+import { useDispatch } from '@/redux';
interface GlobalFilterItemProps {
filter: IChartEventFilter;
@@ -33,27 +29,27 @@ export function GlobalFilterItem({ filter }: GlobalFilterItemProps) {
const onChangeValue = (
value: IChartEventFilterValue[],
- item: IChartEventFilter,
+ item: IChartEventFilter
) => {
dispatch(changeGlobalFilter({ ...item, value }));
};
const onChangeOperator = (
operator: IChartEventFilterOperator,
- item: IChartEventFilter,
+ item: IChartEventFilter
) => {
dispatch(
changeGlobalFilter({
...item,
value: item.value ? item.value.filter(Boolean).slice(0, 1) : [],
operator,
- }),
+ })
);
};
const onChangeType = (
type: IChartFilterValueType,
- item: IChartEventFilter,
+ item: IChartEventFilter
) => {
const allowed = getOperatorsForType(type);
const operator = (allowed as readonly string[]).includes(item.operator)
@@ -71,7 +67,7 @@ export function GlobalFilterItem({ filter }: GlobalFilterItemProps) {
: item.value
? item.value.filter(Boolean).slice(0, 1)
: [],
- }),
+ })
);
};
@@ -83,7 +79,7 @@ export function GlobalFilterItem({ filter }: GlobalFilterItemProps) {
name: firstId ? `cohort:${firstId}` : item.name,
cohortId: firstId,
cohortIds,
- }),
+ })
);
};
@@ -93,24 +89,24 @@ export function GlobalFilterItem({ filter }: GlobalFilterItemProps) {
if (isCohortFilter) {
return (
<PureCohortFilterItem
+ className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
filter={filter}
- onRemove={onRemove}
- onChangeOperator={onChangeOperator}
onChangeCohort={onChangeCohort}
- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
+ onChangeOperator={onChangeOperator}
+ onRemove={onRemove}
/>
);
}
return (
<PureFilterItem
- filter={filter}
+ className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
eventName="*"
- onRemove={onRemove}
- onChangeValue={onChangeValue}
+ filter={filter}
onChangeOperator={onChangeOperator}
onChangeType={onChangeType}
- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"
+ onChangeValue={onChangeValue}
+ onRemove={onRemove}
/>
);
}
diff --git a/apps/start/src/components/report/sidebar/report-fixed-events.tsx b/apps/start/src/components/report/sidebar/report-fixed-events.tsx
index bdea470e1..76180cc8d 100644
--- a/apps/start/src/components/report/sidebar/report-fixed-events.tsx
+++ b/apps/start/src/components/report/sidebar/report-fixed-events.tsx
@@ -1,17 +1,9 @@
-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';
+} from '@openpanel/core/modules/report/report.constants';
+import { alphabetIds } from '@openpanel/core/modules/report/report.constants';
import {
addSerie,
changeEvent,
@@ -21,6 +13,13 @@ import {
import type { ReportEventMoreProps } from './ReportEventMore';
import { ReportEventMore } from './ReportEventMore';
import { ReportSeriesItem } from './ReportSeriesItem';
+import { ColorSquare } from '@/components/color-square';
+import { ComboboxEvents } from '@/components/ui/combobox-events';
+import { Input } from '@/components/ui/input';
+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';
export function ReportFixedEvents({
numberOfEvents,
@@ -50,7 +49,7 @@ export function ReportFixedEvents({
return dispatch(
removeEvent({
id: 'type' in event ? event.id : (event as IChartEvent).id,
- }),
+ })
);
}
case 'duplicate': {
@@ -87,16 +86,15 @@ export function ReportFixedEvents({
// 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="rounded-lg border bg-def-100" key={slotId}>
<div className="flex items-center gap-2 p-2">
<ColorSquare>
<span className="block">{alphabetIds[index]}</span>
</ColorSquare>
<ComboboxEvents
className="flex-1"
- searchable
+ items={eventNames}
multiple={isSelectManyEvents as false}
- value={''}
onChange={(value) => {
if (isSelectManyEvents) {
dispatch(
@@ -111,7 +109,7 @@ export function ReportFixedEvents({
value: [value],
},
],
- }),
+ })
);
} else {
dispatch(
@@ -120,12 +118,13 @@ export function ReportFixedEvents({
name: value,
segment: 'event',
filters: [],
- }),
+ })
);
}
}}
- items={eventNames}
placeholder="Select event"
+ searchable
+ value={''}
/>
</div>
</div>
@@ -139,31 +138,18 @@ export function ReportFixedEvents({
return (
<ReportSeriesItem
- key={event.id}
+ className="rounded-lg border bg-def-100"
event={event}
index={index}
- showSegment={showSegment}
- showAddFilter={showAddFilter}
isSelectManyEvents={isSelectManyEvents}
- className="rounded-lg border bg-def-100"
+ key={event.id}
+ showAddFilter={showAddFilter}
+ showSegment={showSegment}
>
<ComboboxEvents
className="flex-1"
- searchable
+ items={eventNames}
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(
@@ -176,7 +162,7 @@ export function ReportFixedEvents({
{
name: 'name',
operator: 'is',
- value: value,
+ value,
},
],
name: '*',
@@ -186,20 +172,28 @@ export function ReportFixedEvents({
type: 'event',
name: value,
filters: [],
- },
- ),
+ }
+ )
);
}}
- items={eventNames}
placeholder="Select event"
+ searchable
+ value={
+ (isSelectManyEvents
+ ? ((
+ event as IChartEventItem & {
+ type: 'event';
+ }
+ ).filters[0]?.value ?? [])
+ : (
+ event as IChartEventItem & {
+ type: 'event';
+ }
+ ).name) as any
+ }
/>
{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
}
@@ -211,6 +205,11 @@ export function ReportFixedEvents({
displayName: e.target.value,
});
}}
+ placeholder={
+ (event as IChartEventItem & { type: 'event' }).name
+ ? `${(event as IChartEventItem & { type: 'event' }).name} (${alphabetIds[index]})`
+ : 'Display name'
+ }
/>
)}
<ReportEventMore onClick={handleMore(event)} />
diff --git a/apps/start/src/components/sessions/table/columns.tsx b/apps/start/src/components/sessions/table/columns.tsx
index c0f49bfd1..204bcb567 100644
--- a/apps/start/src/components/sessions/table/columns.tsx
+++ b/apps/start/src/components/sessions/table/columns.tsx
@@ -1,7 +1,7 @@
-import { round } from '@openpanel/common';
import type { IServiceSession } from '@openpanel/core';
import type { ColumnDef } from '@tanstack/react-table';
import { Video } from 'lucide-react';
+import { round } from '../../../utils/math';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { ProjectLink } from '@/components/links';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
@@ -48,9 +48,9 @@ export function useColumns() {
<div className="row items-center gap-2">
<ProjectLink
className="font-medium"
- to="/sessions/$sessionId"
params={{ sessionId: session.id }}
title={session.id}
+ to="/sessions/$sessionId"
>
{session.id.slice(0, 8)}...
</ProjectLink>
@@ -58,10 +58,10 @@ export function useColumns() {
<ProjectLink
aria-label="View replay"
className="text-muted-foreground hover:text-foreground"
- to="/sessions/$sessionId"
- params={{ sessionId: session.id }}
hash="replay"
+ params={{ sessionId: session.id }}
title="View replay"
+ to="/sessions/$sessionId"
>
<Video className="size-4" />
</ProjectLink>
@@ -80,8 +80,8 @@ export function useColumns() {
return (
<ProjectLink
className="row items-center gap-2 font-medium hover:underline"
- to="/profiles/$profileId"
params={{ profileId: session.profile.id }}
+ to="/profiles/$profileId"
>
<ProfileAvatar size="sm" {...session.profile} />
{getProfileName(session.profile)}
@@ -91,8 +91,8 @@ export function useColumns() {
return (
<ProjectLink
className="font-medium font-mono"
- to="/profiles/$profileId"
params={{ profileId: session.profileId }}
+ to="/profiles/$profileId"
>
{session.profileId}
</ProjectLink>
@@ -283,13 +283,15 @@ export function useColumns() {
size: 200,
cell: ({ row }) => {
const { groups } = row.original;
- if (!groups?.length) return null;
+ if (!groups?.length) {
+ return null;
+ }
return (
<div className="flex flex-wrap gap-1">
{groups.map((g) => (
<span
+ className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs"
key={g}
- className="rounded bg-muted px-1.5 py-0.5 text-xs font-mono"
>
{g}
</span>
diff --git a/apps/start/src/components/settings/edit-project-details.tsx b/apps/start/src/components/settings/edit-project-details.tsx
index 7defd3851..9dcf26baa 100644
--- a/apps/start/src/components/settings/edit-project-details.tsx
+++ b/apps/start/src/components/settings/edit-project-details.tsx
@@ -1,3 +1,12 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import type { IServiceProjectWithClients } from '@openpanel/core';
+import { zProject } from '@openpanel/core/modules/project/project.constants';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { SaveIcon } from 'lucide-react';
+import { useState } from 'react';
+import { Controller, useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import type { z } from 'zod';
import AnimateHeight from '@/components/animate-height';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import TagInput from '@/components/forms/tag-input';
@@ -8,15 +17,6 @@ import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
import { handleError, useTRPC } from '@/integrations/trpc/react';
-import { zodResolver } from '@hookform/resolvers/zod';
-import type { IServiceProjectWithClients } from '@openpanel/core';
-import { zProject } from '@openpanel/validation';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
-import { SaveIcon } from 'lucide-react';
-import { useState } from 'react';
-import { Controller, useForm } from 'react-hook-form';
-import { toast } from 'sonner';
-import type { z } from 'zod';
type Props = { project: IServiceProjectWithClients };
@@ -53,15 +53,15 @@ export default function EditProjectDetails({ project }: Props) {
queryClient.invalidateQueries(
trpc.project.list.queryFilter({
organizationId: project.organizationId,
- }),
+ })
);
queryClient.invalidateQueries(
trpc.project.getProjectWithClients.queryFilter({
projectId: project.id,
- }),
+ })
);
},
- }),
+ })
);
const onSubmit = (values: IForm) => {
@@ -92,19 +92,19 @@ export default function EditProjectDetails({ project }: Props) {
};
return (
- <Widget className="max-w-screen-md w-full">
+ <Widget className="w-full max-w-screen-md">
<WidgetHead>
<span className="title">Details</span>
</WidgetHead>
<WidgetBody>
- <form onSubmit={form.handleSubmit(onSubmit)} className="col gap-4">
+ <form className="col gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<InputWithLabel
label="Name"
{...form.register('name')}
defaultValue={project.name}
/>
- <div className="-mb-2 flex gap-2 items-center justify-between">
+ <div className="-mb-2 flex items-center justify-between gap-2">
<Label className="mb-0">Domain</Label>
<Switch checked={hasDomain} onCheckedChange={setHasDomain} />
</div>
@@ -113,26 +113,21 @@ export default function EditProjectDetails({ project }: Props) {
placeholder="https://example.com"
{...form.register('domain')}
className="mb-4"
- error={form.formState.errors.domain?.message}
defaultValue={project.domain ?? ''}
+ error={form.formState.errors.domain?.message}
/>
<Controller
- name="cors"
control={form.control}
+ name="cors"
render={({ field }) => (
<WithLabel
- label="Allowed domains"
error={form.formState.errors.cors?.message}
+ label="Allowed domains"
>
<TagInput
{...field}
error={form.formState.errors.cors?.message}
- placeholder="Add a domain"
- value={field.value ?? []}
- renderTag={(tag) =>
- tag === '*' ? 'Allow all domains' : tag
- }
onChange={(newValue) => {
field.onChange(
newValue.map((item) => {
@@ -145,24 +140,29 @@ export default function EditProjectDetails({ project }: Props) {
return trimmed;
}
return `https://${trimmed}`;
- }),
+ })
);
}}
+ placeholder="Add a domain"
+ renderTag={(tag) =>
+ tag === '*' ? 'Allow all domains' : tag
+ }
+ value={field.value ?? []}
/>
</WithLabel>
)}
/>
<Controller
- name="crossDomain"
control={form.control}
+ name="crossDomain"
render={({ field }) => {
return (
- <WithLabel label="Cross domain support" className="mt-4">
+ <WithLabel className="mt-4" label="Cross domain support">
<CheckboxInput
- ref={field.ref}
- onBlur={field.onBlur}
defaultChecked={field.value}
+ onBlur={field.onBlur}
onCheckedChange={field.onChange}
+ ref={field.ref}
>
<div>Enable cross domain support</div>
<div className="font-normal text-muted-foreground">
@@ -176,16 +176,16 @@ export default function EditProjectDetails({ project }: Props) {
</AnimateHeight>
<Controller
- name="allowUnsafeRevenueTracking"
control={form.control}
+ name="allowUnsafeRevenueTracking"
render={({ field }) => {
return (
<WithLabel label="Revenue tracking">
<CheckboxInput
- ref={field.ref}
- onBlur={field.onBlur}
defaultChecked={field.value}
+ onBlur={field.onBlur}
onCheckedChange={field.onChange}
+ ref={field.ref}
>
<div>Allow "unsafe" revenue tracking</div>
<div className="font-normal text-muted-foreground">
@@ -198,10 +198,10 @@ export default function EditProjectDetails({ project }: Props) {
/>
<Button
+ className="self-start"
+ icon={SaveIcon}
loading={mutation.isPending}
type="submit"
- icon={SaveIcon}
- className="self-start"
>
Save
</Button>
diff --git a/apps/start/src/components/settings/edit-project-filters.tsx b/apps/start/src/components/settings/edit-project-filters.tsx
index 54943640b..165b8a118 100644
--- a/apps/start/src/components/settings/edit-project-filters.tsx
+++ b/apps/start/src/components/settings/edit-project-filters.tsx
@@ -1,29 +1,31 @@
-import { WithLabel } from '@/components/forms/input-with-label';
-import TagInput from '@/components/forms/tag-input';
-import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
-import { PropertiesCombobox } from '@/components/report/sidebar/PropertiesCombobox';
-import { Button } from '@/components/ui/button';
-import { ComboboxEvents } from '@/components/ui/combobox-events';
-import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
-import { useEventNames } from '@/hooks/use-event-names';
-import { handleError, useTRPC } from '@/integrations/trpc/react';
-import type { RouterOutputs } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
-import { shortId } from '@openpanel/common';
import type {
- IChartEventFilter,
- IChartEventFilterOperator,
- IChartEventFilterValue,
IProjectFilterEvent,
IProjectFilterIp,
IProjectFilterProfileId,
-} from '@openpanel/validation';
-import { zProjectFilterEvent } from '@openpanel/validation';
+} from '@openpanel/core/modules/project/project.constants';
+import { zProjectFilterEvent } from '@openpanel/core/modules/project/project.constants';
+import type {
+ IChartEventFilter,
+ IChartEventFilterOperator,
+ IChartEventFilterValue,
+} from '@openpanel/core/modules/report/report.constants';
import { useMutation } from '@tanstack/react-query';
import { PlusIcon, SaveIcon, Trash2Icon } from 'lucide-react';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
+import { shortId } from '../../utils/math';
+import { WithLabel } from '@/components/forms/input-with-label';
+import TagInput from '@/components/forms/tag-input';
+import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
+import { PropertiesCombobox } from '@/components/report/sidebar/PropertiesCombobox';
+import { Button } from '@/components/ui/button';
+import { ComboboxEvents } from '@/components/ui/combobox-events';
+import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
+import { useEventNames } from '@/hooks/use-event-names';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
+import type { RouterOutputs } from '@/trpc/client';
type Props = {
project: NonNullable<RouterOutputs['project']['getProjectWithClients']>;
@@ -76,26 +78,26 @@ function EventRuleItem({
const changeFilterValue = (
value: IChartEventFilterValue[],
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => {
onChange({
...rule,
filters: rule.filters.map((f) =>
- f.id === filter.id ? { ...f, value } : f,
+ f.id === filter.id ? { ...f, value } : f
),
});
};
const changeFilterOperator = (
operator: IChartEventFilterOperator,
- filter: IChartEventFilter,
+ filter: IChartEventFilter
) => {
onChange({
...rule,
filters: rule.filters.map((f) =>
f.id === filter.id
? { ...f, operator, value: f.value.filter(Boolean).slice(0, 1) }
- : f,
+ : f
),
});
};
@@ -105,15 +107,15 @@ function EventRuleItem({
<div className="flex items-center gap-2 p-4">
<div className="flex-1">
<ComboboxEvents
- placeholder="Select event name..."
+ className="w-full"
items={eventNames}
- value={rule.name}
onChange={(name) => onChange({ ...rule, name })}
- className="w-full"
+ placeholder="Select event name..."
searchable
+ value={rule.name}
/>
</div>
- <Button variant="ghost" size="icon" onClick={onRemove}>
+ <Button onClick={onRemove} size="icon" variant="ghost">
<Trash2Icon size={16} />
</Button>
</div>
@@ -122,26 +124,26 @@ function EventRuleItem({
<>
{rule.filters.map((filter) => (
<PureFilterItem
- key={filter.id}
- filter={filter}
+ className="border-t border-l-2 border-l-emerald-500 p-2 px-4"
eventName={rule.name}
- onRemove={removeFilter}
- onChangeValue={changeFilterValue}
- onChangeOperator={changeFilterOperator}
+ filter={filter}
immediateInput
- className="border-t p-2 px-4 border-l-2 border-l-emerald-500"
+ key={filter.id}
+ onChangeOperator={changeFilterOperator}
+ onChangeValue={changeFilterValue}
+ onRemove={removeFilter}
/>
))}
</>
)}
- <div className="p-4 border-t">
- <PropertiesCombobox onSelect={addFilter} categories={['event']}>
+ <div className="border-t p-4">
+ <PropertiesCombobox categories={['event']} onSelect={addFilter}>
{(setOpen) => (
<Button
- variant="outline"
- size="sm"
- onClick={() => setOpen(true)}
icon={PlusIcon}
+ onClick={() => setOpen(true)}
+ size="sm"
+ variant="outline"
>
Add property filter
</Button>
@@ -161,7 +163,7 @@ export default function EditProjectFilters({ project }: Props) {
.map((item) => item.ip),
profileIds: project.filters
.filter(
- (item): item is IProjectFilterProfileId => item.type === 'profile_id',
+ (item): item is IProjectFilterProfileId => item.type === 'profile_id'
)
.map((item) => item.profileId),
eventRules: project.filters
@@ -183,7 +185,7 @@ export default function EditProjectFilters({ project }: Props) {
onSuccess: () => {
toast.success('Project filters updated');
},
- }),
+ })
);
const onSubmit = (values: IForm) => {
@@ -223,12 +225,12 @@ export default function EditProjectFilters({ project }: Props) {
const removeEventRule = (index: number) => {
form.setValue(
'eventRules',
- eventRules.filter((_, i) => i !== index),
+ eventRules.filter((_, i) => i !== index)
);
};
return (
- <Widget className="max-w-screen-md w-full">
+ <Widget className="w-full max-w-screen-md">
<WidgetHead className="space-y-2">
<span className="title">Exclude events</span>
<p className="text-muted-foreground">
@@ -237,43 +239,43 @@ export default function EditProjectFilters({ project }: Props) {
</WidgetHead>
<WidgetBody>
<form
- onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-4"
onKeyDown={(e) => {
if (e.key === 'Enter' && e.target instanceof HTMLInputElement) {
e.preventDefault();
}
}}
- className="space-y-4"
+ onSubmit={form.handleSubmit(onSubmit)}
>
<Controller
- name="ips"
control={form.control}
+ name="ips"
render={({ field }) => (
<WithLabel label="IP addresses">
<TagInput
{...field}
- id="IP addresses"
error={form.formState.errors.ips?.message}
+ id="IP addresses"
+ onChange={field.onChange}
placeholder="Exclude IP addresses"
value={field.value}
- onChange={field.onChange}
/>
</WithLabel>
)}
/>
<Controller
- name="profileIds"
control={form.control}
+ name="profileIds"
render={({ field }) => (
<WithLabel label="Profile IDs">
<TagInput
{...field}
- id="Profile IDs"
error={form.formState.errors.profileIds?.message}
+ id="Profile IDs"
+ onChange={field.onChange}
placeholder="Exclude Profile IDs"
value={field.value}
- onChange={field.onChange}
/>
</WithLabel>
)}
@@ -285,18 +287,18 @@ export default function EditProjectFilters({ project }: Props) {
<EventRuleItem
// biome-ignore lint/suspicious/noArrayIndexKey: order is stable
key={index}
- projectId={project.id}
- rule={rule}
onChange={(updated) => updateEventRule(index, updated)}
onRemove={() => removeEventRule(index)}
+ projectId={project.id}
+ rule={rule}
/>
))}
<Button
+ icon={PlusIcon}
+ onClick={addEventRule}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={addEventRule}
- icon={PlusIcon}
>
Add event rule
</Button>
@@ -304,10 +306,10 @@ export default function EditProjectFilters({ project }: Props) {
</WithLabel>
<Button
+ className="self-end"
+ icon={SaveIcon}
loading={mutation.isPending}
type="submit"
- icon={SaveIcon}
- className="self-end"
>
Save
</Button>
diff --git a/apps/start/src/components/settings/project-access-grants.tsx b/apps/start/src/components/settings/project-access-grants.tsx
index 8ad3e120b..9a04cc785 100644
--- a/apps/start/src/components/settings/project-access-grants.tsx
+++ b/apps/start/src/components/settings/project-access-grants.tsx
@@ -1,3 +1,4 @@
+import type { IProjectAccessGrant } from '@openpanel/core/modules/organization/organization.constants';
import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
import {
Select,
@@ -6,7 +7,6 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import type { IProjectAccessGrant } from '@openpanel/validation';
interface ProjectAccessGrantsProps {
value: IProjectAccessGrant[];
@@ -35,47 +35,47 @@ export function ProjectAccessGrants({
projectId,
// Write is the default: restricting someone is the deliberate act.
level: 'write' as const,
- },
- ),
+ }
+ )
);
};
const handleLevelChange = (projectId: string, level: 'read' | 'write') => {
onChange(
value.map((grant) =>
- grant.projectId === projectId ? { ...grant, level } : grant,
- ),
+ grant.projectId === projectId ? { ...grant, level } : grant
+ )
);
};
return (
<div className="col gap-2">
<ComboboxAdvanced
- placeholder="Restrict access to projects"
- value={selectedIds}
- onChange={(ids) => handleSelectionChange(ids as string[])}
items={projects.map((project) => ({
label: project.name,
value: project.id,
}))}
+ onChange={(ids) => handleSelectionChange(ids as string[])}
+ placeholder="Restrict access to projects"
+ value={selectedIds}
/>
{value.length > 0 && (
<div className="col divide-y rounded-lg border">
{value.map((grant) => (
<div
- key={grant.projectId}
className="row items-center justify-between gap-2 p-2"
+ key={grant.projectId}
>
<span className="truncate text-sm">
{projects.find((project) => project.id === grant.projectId)
?.name ?? grant.projectId}
</span>
<Select
- value={grant.level}
onValueChange={(level) =>
handleLevelChange(grant.projectId, level as 'read' | 'write')
}
+ value={grant.level}
>
<SelectTrigger className="w-36 shrink-0">
<SelectValue />
diff --git a/apps/start/src/components/time-window-picker.tsx b/apps/start/src/components/time-window-picker.tsx
index f487154ac..9f19405de 100644
--- a/apps/start/src/components/time-window-picker.tsx
+++ b/apps/start/src/components/time-window-picker.tsx
@@ -1,5 +1,11 @@
-import { getDefaultIntervalByDates, timeWindows } from '@openpanel/constants';
-import type { IChartRange, IInterval } from '@openpanel/validation';
+import type {
+ IChartRange,
+ IInterval,
+} from '@openpanel/core/modules/report/report.constants';
+import {
+ getDefaultIntervalByDates,
+ timeWindows,
+} from '@openpanel/core/modules/report/report.constants';
import { bind } from 'bind-event-listener';
import { addDays, endOfDay, format, startOfDay, subDays } from 'date-fns';
import { CalendarIcon } from 'lucide-react';
diff --git a/apps/start/src/contexts/page-context.tsx b/apps/start/src/contexts/page-context.tsx
index 326a3b6ed..c82821de9 100644
--- a/apps/start/src/contexts/page-context.tsx
+++ b/apps/start/src/contexts/page-context.tsx
@@ -1,7 +1,17 @@
+import type {
+ PageContextPage,
+ PageContext as ValidatedPageContext,
+} from '@openpanel/core/modules/assistant/assistant.constants';
+import type {
+ IChartEventFilter,
+ IChartRange,
+ IInterval,
+ IReportInput,
+} from '@openpanel/core/modules/report/report.constants';
import {
+ createContext,
type MutableRefObject,
type ReactNode,
- createContext,
useCallback,
useContext,
useEffect,
@@ -9,14 +19,6 @@ import {
useRef,
useState,
} from 'react';
-import type {
- IChartEventFilter,
- IChartRange,
- IInterval,
- IReportInput,
- PageContext as ValidatedPageContext,
- PageContextPage,
-} from '@openpanel/validation';
export type { PageContextPage };
@@ -24,8 +26,9 @@ export type { PageContextPage };
* What the chat backend needs to know about "what the user is currently
* looking at".
*
- * Same wire shape as `ValidatedPageContext` from `@openpanel/validation`,
- * but with stricter typing for `filters` / `reportDraft`. The validation
+ * Same wire shape as `ValidatedPageContext` from
+ * `@openpanel/core`'s assistant.constants, but with stricter typing for
+ * `filters` / `reportDraft`. The validation
* schema keeps those loose (`z.record(unknown)`) because Zod can't narrow
* `IChartEventFilter` / `IReportInput` at the boundary; the server
* re-narrows in `apps/api/src/agents/tools/helpers.ts`.
@@ -70,7 +73,7 @@ export function PageContextProvider({ children }: { children: ReactNode }) {
const value = useMemo(
() => ({ context, setContext, ref }),
- [context, setContext],
+ [context, setContext]
);
return (
diff --git a/apps/start/src/hooks/use-event-query-filters.ts b/apps/start/src/hooks/use-event-query-filters.ts
index c824c2ec9..3e01213e6 100644
--- a/apps/start/src/hooks/use-event-query-filters.ts
+++ b/apps/start/src/hooks/use-event-query-filters.ts
@@ -1,3 +1,4 @@
+import type { IChartEventFilterOperator } from '@openpanel/core/modules/report/report.constants';
import type { Options as NuqsOptions } from 'nuqs';
import {
createParser,
@@ -7,13 +8,13 @@ import {
} from 'nuqs';
import { useCallback } from 'react';
-import type { IChartEventFilterOperator } from '@openpanel/validation';
-
const nuqsOptions = { history: 'push' } as const;
export const eventQueryFiltersParser = createParser({
parse: (query: string) => {
- if (query === '') return [];
+ if (query === '') {
+ return [];
+ }
const filters = query.split(';');
return filters.map((filter) => {
@@ -33,14 +34,10 @@ export const eventQueryFiltersParser = createParser({
id: name,
name,
operator: (operator ?? 'is') as IChartEventFilterOperator,
- value: value
- ? value.split('|').map((v) => decodeURIComponent(v))
- : [],
+ value: value ? value.split('|').map((v) => decodeURIComponent(v)) : [],
// Keep both fields populated for legacy consumers that read
// `cohortId` directly. `cohortIds` is the source of truth.
- ...(cohortIds.length > 0
- ? { cohortId: cohortIds[0], cohortIds }
- : {}),
+ ...(cohortIds.length > 0 ? { cohortId: cohortIds[0], cohortIds } : {}),
};
});
},
@@ -78,7 +75,7 @@ export function useEventQueryFilters(options: NuqsOptions = {}) {
eventQueryFiltersParser.withDefault([]).withOptions({
...nuqsOptions,
...options,
- }),
+ })
);
const setFilter = useCallback(
@@ -91,7 +88,7 @@ export function useEventQueryFilters(options: NuqsOptions = {}) {
| undefined
| null
| (string | number | boolean | undefined | null)[],
- operator?: IChartEventFilterOperator,
+ operator?: IChartEventFilterOperator
) => {
setFilters((prev) => {
const exists = prev.find((filter) => filter.name === name);
@@ -137,21 +134,21 @@ export function useEventQueryFilters(options: NuqsOptions = {}) {
];
});
},
- [setFilters],
+ [setFilters]
);
const removeFilter = useCallback(
(name: string) => {
setFilters((prev) => prev.filter((filter) => filter.name !== name));
},
- [setFilters],
+ [setFilters]
);
return [filters, setFilter, setFilters, removeFilter] as const;
}
export const eventQueryNamesFilter = parseAsArrayOf(parseAsString).withDefault(
- [],
+ []
);
export function useEventQueryNamesFilter(options: NuqsOptions = {}) {
diff --git a/apps/start/src/hooks/use-format-date-interval.ts b/apps/start/src/hooks/use-format-date-interval.ts
index 4a4e88adc..33ca4fe49 100644
--- a/apps/start/src/hooks/use-format-date-interval.ts
+++ b/apps/start/src/hooks/use-format-date-interval.ts
@@ -1,7 +1,6 @@
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import { getISOWeek } from 'date-fns';
-import type { IInterval } from '@openpanel/validation';
-
export function formatDateInterval(options: {
interval: IInterval;
date: Date;
diff --git a/apps/start/src/hooks/use-page-context-helpers.ts b/apps/start/src/hooks/use-page-context-helpers.ts
index f753db0a2..d8a2c21c6 100644
--- a/apps/start/src/hooks/use-page-context-helpers.ts
+++ b/apps/start/src/hooks/use-page-context-helpers.ts
@@ -1,15 +1,15 @@
+import type { IReportInput } from '@openpanel/core/modules/report/report.constants';
+import { useAppParams } from './use-app-params';
+import {
+ useEventQueryFilters,
+ useEventQueryNamesFilter,
+} from './use-event-query-filters';
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import {
type PageContext,
type PageContextPage,
usePageContext,
} from '@/contexts/page-context';
-import {
- useEventQueryFilters,
- useEventQueryNamesFilter,
-} from './use-event-query-filters';
-import { useAppParams } from './use-app-params';
-import type { IReportInput } from '@openpanel/validation';
/**
* For pages that share the standard date-range / interval filters
@@ -50,7 +50,7 @@ export function useRangePageContext(page: PageContextPage) {
export function useEntityPageContext(
page: 'sessionDetail' | 'profileDetail' | 'groupDetail',
ids: PageContext['ids'],
- primer?: Record<string, unknown>,
+ primer?: Record<string, unknown>
) {
const { projectId, organizationId } = useAppParams();
@@ -71,7 +71,7 @@ export function useEntityPageContext(
*/
export function useDashboardPageContext(
dashboardId: string,
- primer?: Record<string, unknown>,
+ primer?: Record<string, unknown>
) {
const { projectId, organizationId } = useAppParams();
const { range, startDate, endDate, interval } = useOverviewOptions();
diff --git a/apps/start/src/hooks/use-table-filters.ts b/apps/start/src/hooks/use-table-filters.ts
index 08dd67dcc..e129e0f76 100644
--- a/apps/start/src/hooks/use-table-filters.ts
+++ b/apps/start/src/hooks/use-table-filters.ts
@@ -1,9 +1,7 @@
+import type { IChartEventFilter } from '@openpanel/core/modules/report/report.constants';
import type { Options as NuqsOptions } from 'nuqs';
import { useQueryState } from 'nuqs';
import { useCallback, useMemo } from 'react';
-
-import type { IChartEventFilter } from '@openpanel/validation';
-
import { eventQueryFiltersParser } from './use-event-query-filters';
const nuqsOptions = { history: 'push' } as const;
@@ -15,22 +13,19 @@ const nuqsOptions = { history: 'push' } as const;
*/
export function useTableFilters(
key = 'f',
- options: NuqsOptions = {},
-): [
- IChartEventFilter[],
- (next: IChartEventFilter[]) => void,
-] {
+ options: NuqsOptions = {}
+): [IChartEventFilter[], (next: IChartEventFilter[]) => void] {
const [rawFilters, setFilters] = useQueryState(
key,
eventQueryFiltersParser.withDefault([]).withOptions({
...nuqsOptions,
...options,
- }),
+ })
);
const filters = useMemo<IChartEventFilter[]>(
() => rawFilters as unknown as IChartEventFilter[],
- [rawFilters],
+ [rawFilters]
);
const setAll = useCallback(
@@ -48,10 +43,10 @@ export function useTableFilters(
? { cohortIds: filter.cohortIds }
: {}),
...(filter.cohortId ? { cohortId: filter.cohortId } : {}),
- })),
+ }))
);
},
- [setFilters],
+ [setFilters]
);
return [filters, setAll];
diff --git a/apps/start/src/hooks/use-ws.ts b/apps/start/src/hooks/use-ws.ts
index fe74da522..4b86c96b7 100644
--- a/apps/start/src/hooks/use-ws.ts
+++ b/apps/start/src/hooks/use-ws.ts
@@ -1,8 +1,7 @@
import debounce from 'lodash.debounce';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useWebSocket } from 'react-use-websocket/dist/lib/use-websocket';
-
-import { getSuperJson } from '@openpanel/json';
+import { getSuperJson } from '../utils/super-json';
import { useAppContext } from './use-app-context';
type UseWSOptions = {
@@ -15,7 +14,7 @@ type UseWSOptions = {
export default function useWS<T>(
path: string,
onMessage: (event: T) => void,
- options?: UseWSOptions,
+ options?: UseWSOptions
) {
const context = useAppContext();
const ws = context.apiUrl.replace(/^https/, 'wss').replace(/^http/, 'ws');
@@ -39,7 +38,9 @@ export default function useWS<T>(
}, [options?.debounce?.delay, options?.debounce?.maxWait]);
useEffect(() => {
- if (baseUrl === `${ws}${path}`) return;
+ if (baseUrl === `${ws}${path}`) {
+ return;
+ }
setBaseUrl(`${ws}${path}`);
}, [path, baseUrl, ws]);
diff --git a/apps/start/src/modals/add-cohort.tsx b/apps/start/src/modals/add-cohort.tsx
index a45eeb043..f5e1eee9d 100644
--- a/apps/start/src/modals/add-cohort.tsx
+++ b/apps/start/src/modals/add-cohort.tsx
@@ -1,3 +1,11 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import type { CohortDefinition } from '@openpanel/core/modules/cohort/cohort.constants';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { Controller, useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import { z } from 'zod';
+import { popModal } from '.';
+import { ModalContent, ModalHeader } from './Modal/Container';
import { ButtonContainer } from '@/components/button-container';
import { CohortCriteriaBuilder } from '@/components/cohort/cohort-criteria-builder';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
@@ -7,15 +15,6 @@ import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { useAppParams } from '@/hooks/use-app-params';
import { handleError, useTRPC } from '@/integrations/trpc/react';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
-import type { CohortDefinition } from '@openpanel/validation';
-import { Controller, useForm } from 'react-hook-form';
-import { toast } from 'sonner';
-import { z } from 'zod';
-
-import { popModal } from '.';
-import { ModalContent, ModalHeader } from './Modal/Container';
const validator = z.object({
name: z.string().min(1, 'Required'),
@@ -55,7 +54,7 @@ export default function AddCohort() {
popModal();
},
onError: handleError,
- }),
+ })
);
return (
@@ -86,17 +85,17 @@ export default function AddCohort() {
<div className="flex items-center gap-2">
<Controller
- name="isStatic"
control={control}
+ name="isStatic"
render={({ field }) => (
<Switch
- id="isStatic"
checked={field.value}
+ id="isStatic"
onCheckedChange={field.onChange}
/>
)}
/>
- <Label htmlFor="isStatic" className="cursor-pointer text-sm mb-0">
+ <Label className="mb-0 cursor-pointer text-sm" htmlFor="isStatic">
Freeze snapshot (don&apos;t auto-refresh)
</Label>
</div>
@@ -104,8 +103,8 @@ export default function AddCohort() {
<div>
<Label className="mb-2 block">Cohort Criteria</Label>
<Controller
- name="definition"
control={control}
+ name="definition"
render={({ field }) => (
<CohortCriteriaBuilder
definition={field.value as CohortDefinition}
@@ -116,10 +115,10 @@ export default function AddCohort() {
</div>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
- <Button type="submit" disabled={!formState.isDirty}>
+ <Button disabled={!formState.isDirty} type="submit">
Create
</Button>
</ButtonContainer>
diff --git a/apps/start/src/modals/add-group.tsx b/apps/start/src/modals/add-group.tsx
index 05192da29..59b3667b2 100644
--- a/apps/start/src/modals/add-group.tsx
+++ b/apps/start/src/modals/add-group.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { zCreateGroup } from '@openpanel/validation';
+import { zCreateGroup } from '@openpanel/core/modules/group/group.constants';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, Trash2Icon } from 'lucide-react';
import { useFieldArray, useForm } from 'react-hook-form';
diff --git a/apps/start/src/modals/add-import.tsx b/apps/start/src/modals/add-import.tsx
index d2384304c..e3cf57fe7 100644
--- a/apps/start/src/modals/add-import.tsx
+++ b/apps/start/src/modals/add-import.tsx
@@ -1,24 +1,26 @@
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { toast } from 'sonner';
-
-import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
-import { ProjectMapper } from '@/components/project-mapper';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { useTRPC } from '@/integrations/trpc/react';
-import { cn } from '@/lib/utils';
import { zodResolver } from '@hookform/resolvers/zod';
import type {
IAmplitudeImportConfig,
IImportConfig,
IMixpanelImportConfig,
IUmamiImportConfig,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/import/import.constants';
import {
zAmplitudeImportConfig,
zMixpanelImportConfig,
zUmamiImportConfig,
-} from '@openpanel/validation';
+} from '@openpanel/core/modules/import/import.constants';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { format } from 'date-fns';
+import { CalendarIcon } from 'lucide-react';
+import { useFieldArray, useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import type { z } from 'zod';
+import { popModal, pushModal } from '.';
+import { ModalContent, ModalHeader } from './Modal/Container';
+import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
+import { ProjectMapper } from '@/components/project-mapper';
+import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
@@ -26,12 +28,9 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import { format } from 'date-fns';
-import { CalendarIcon } from 'lucide-react';
-import { useFieldArray, useForm } from 'react-hook-form';
-import type { z } from 'zod';
-import { popModal, pushModal } from '.';
-import { ModalContent, ModalHeader } from './Modal/Container';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useTRPC } from '@/integrations/trpc/react';
+import { cn } from '@/lib/utils';
type Provider = 'umami' | 'plausible' | 'mixpanel' | 'amplitude';
@@ -60,7 +59,7 @@ function UmamiImport({
const { data: projects = [] } = useQuery(
trpc.project.list.queryOptions({
organizationId,
- }),
+ })
);
const form = useForm<UmamiFormData>({
@@ -83,32 +82,32 @@ function UmamiImport({
});
return (
- <form onSubmit={handleSubmit} className="space-y-4">
+ <form className="space-y-4" onSubmit={handleSubmit}>
<div className="space-y-4 py-4">
<InputWithLabel
- label="File URL"
- placeholder="https://example.com/export.csv"
error={form.formState.errors.fileUrl?.message}
info="Provide a publicly accessible URL to your exported CSV file."
+ label="File URL"
+ placeholder="https://example.com/export.csv"
{...form.register('fileUrl')}
/>
<ProjectMapper
- fields={fields}
append={append}
- remove={remove}
+ fields={fields}
projects={projects}
register={form.register}
- watch={form.watch}
+ remove={remove}
setValue={form.setValue}
+ watch={form.watch}
/>
</div>
<div className="flex justify-between">
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
- <Button type="submit" disabled={isPending}>
+ <Button disabled={isPending} type="submit">
{isPending ? 'Starting...' : 'Start Import'}
</Button>
</div>
@@ -163,47 +162,47 @@ function MixpanelImport({
});
return (
- <form onSubmit={handleSubmit} className="space-y-4">
+ <form className="space-y-4" onSubmit={handleSubmit}>
<div className="space-y-4 py-4">
<InputWithLabel
+ error={form.formState.errors.serviceAccount?.message}
label="Service Account"
placeholder="Eg. xxx.xxx.mp-service-account"
- error={form.formState.errors.serviceAccount?.message}
{...form.register('serviceAccount')}
/>
<InputWithLabel
+ error={form.formState.errors.serviceSecret?.message}
label="Service Secret"
- type="password"
placeholder="Your Mixpanel service secret"
- error={form.formState.errors.serviceSecret?.message}
+ type="password"
{...form.register('serviceSecret')}
/>
<InputWithLabel
+ error={form.formState.errors.projectId?.message}
label="Project ID"
placeholder="Your Mixpanel project ID"
- error={form.formState.errors.projectId?.message}
{...form.register('projectId')}
/>
<WithLabel
- label="Date Range"
info={
- !form.getValues('from') || !form.getValues('to')
- ? 'Select the date range for importing data'
- : undefined
+ form.getValues('from') && form.getValues('to')
+ ? undefined
+ : 'Select the date range for importing data'
}
+ label="Date Range"
>
<Button
- type="button"
- variant="outline"
className={cn(
'w-full justify-start text-left font-normal',
- (!form.getValues('from') || !form.getValues('to')) &&
- 'text-muted-foreground',
+ !(form.getValues('from') && form.getValues('to')) &&
+ 'text-muted-foreground'
)}
onClick={handleDateRangeSelect}
+ type="button"
+ variant="outline"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.getValues('from') && form.getValues('to') ? (
@@ -218,19 +217,22 @@ function MixpanelImport({
</WithLabel>
<InputWithLabel
+ error={form.formState.errors.mapScreenViewProperty?.message}
+ info="Leave empty if not applicable"
label="Screen View Property"
placeholder="Enter the name of the property that contains the screen name"
- info="Leave empty if not applicable"
- error={form.formState.errors.mapScreenViewProperty?.message}
{...form.register('mapScreenViewProperty')}
/>
- <WithLabel label="Data Residency" info="Select the Mixpanel data center your project uses">
+ <WithLabel
+ info="Select the Mixpanel data center your project uses"
+ label="Data Residency"
+ >
<Select
- value={form.watch('dataResidency') ?? 'us'}
onValueChange={(value) =>
form.setValue('dataResidency', value as 'us' | 'eu' | 'in')
}
+ value={form.watch('dataResidency') ?? 'us'}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="US (default)" />
@@ -245,10 +247,10 @@ function MixpanelImport({
</div>
<div className="flex justify-between">
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
- <Button type="submit" disabled={isPending}>
+ <Button disabled={isPending} type="submit">
{isPending ? 'Starting...' : 'Start Import'}
</Button>
</div>
@@ -297,41 +299,41 @@ function AmplitudeImport({ onSubmit, isPending }: AmplitudeImportProps) {
});
return (
- <form onSubmit={handleSubmit} className="space-y-4">
+ <form className="space-y-4" onSubmit={handleSubmit}>
<div className="space-y-4 py-4">
<InputWithLabel
- label="API Key"
- placeholder="Your Amplitude API key"
error={form.formState.errors.apiKey?.message}
info="Settings → Projects → General in Amplitude."
+ label="API Key"
+ placeholder="Your Amplitude API key"
{...form.register('apiKey')}
/>
<InputWithLabel
+ error={form.formState.errors.secretKey?.message}
label="Secret Key"
- type="password"
placeholder="Your Amplitude secret key"
- error={form.formState.errors.secretKey?.message}
+ type="password"
{...form.register('secretKey')}
/>
<WithLabel
- label="Date Range"
info={
- !form.getValues('from') || !form.getValues('to')
- ? 'Select the date range for importing data'
- : undefined
+ form.getValues('from') && form.getValues('to')
+ ? undefined
+ : 'Select the date range for importing data'
}
+ label="Date Range"
>
<Button
- type="button"
- variant="outline"
className={cn(
'w-full justify-start text-left font-normal',
- (!form.getValues('from') || !form.getValues('to')) &&
- 'text-muted-foreground',
+ !(form.getValues('from') && form.getValues('to')) &&
+ 'text-muted-foreground'
)}
onClick={handleDateRangeSelect}
+ type="button"
+ variant="outline"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.getValues('from') && form.getValues('to') ? (
@@ -346,22 +348,22 @@ function AmplitudeImport({ onSubmit, isPending }: AmplitudeImportProps) {
</WithLabel>
<InputWithLabel
+ error={form.formState.errors.mapScreenViewProperty?.message}
+ info="Leave empty if not applicable"
label="Screen View Property"
placeholder="Enter the name of the property that contains the screen name"
- info="Leave empty if not applicable"
- error={form.formState.errors.mapScreenViewProperty?.message}
{...form.register('mapScreenViewProperty')}
/>
<WithLabel
- label="Data Residency"
info="Select the Amplitude data region your project uses"
+ label="Data Residency"
>
<Select
- value={form.watch('dataResidency') ?? 'us'}
onValueChange={(value) =>
form.setValue('dataResidency', value as 'us' | 'eu')
}
+ value={form.watch('dataResidency') ?? 'us'}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="US (default)" />
@@ -375,10 +377,10 @@ function AmplitudeImport({ onSubmit, isPending }: AmplitudeImportProps) {
</div>
<div className="flex justify-between">
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
- <Button type="submit" disabled={isPending}>
+ <Button disabled={isPending} type="submit">
{isPending ? 'Starting...' : 'Start Import'}
</Button>
</div>
@@ -405,7 +407,7 @@ export default function AddImport({ provider, name }: AddImportProps) {
description: error.message,
});
},
- }),
+ })
);
const handleImportSubmit = (config: IImportConfig) => {
@@ -422,24 +424,24 @@ export default function AddImport({ provider, name }: AddImportProps) {
{provider === 'umami' && (
<UmamiImport
- onSubmit={handleImportSubmit}
isPending={createImport.isPending}
+ onSubmit={handleImportSubmit}
organizationId={organizationId}
/>
)}
{provider === 'mixpanel' && (
<MixpanelImport
- onSubmit={handleImportSubmit}
isPending={createImport.isPending}
+ onSubmit={handleImportSubmit}
organizationId={organizationId}
/>
)}
{provider === 'amplitude' && (
<AmplitudeImport
- onSubmit={handleImportSubmit}
isPending={createImport.isPending}
+ onSubmit={handleImportSubmit}
organizationId={organizationId}
/>
)}
diff --git a/apps/start/src/modals/add-integration.tsx b/apps/start/src/modals/add-integration.tsx
index 2aec336ff..4e4b5bf37 100644
--- a/apps/start/src/modals/add-integration.tsx
+++ b/apps/start/src/modals/add-integration.tsx
@@ -1,5 +1,9 @@
-import { useTRPC } from '@/integrations/trpc/react';
-
+import type { IIntegrationConfig } from '@openpanel/core/modules/integration/integration.constants';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useNavigate } from '@tanstack/react-router';
+import { toast } from 'sonner';
+import { popModal } from '.';
+import { ModalHeader } from './Modal/Container';
import { IntegrationCardContent } from '@/components/integrations/integration-card';
import {
CLIENT_INTEGRATIONS,
@@ -7,13 +11,7 @@ import {
} from '@/components/integrations/integrations';
import { SheetContent } from '@/components/ui/sheet';
import { useAppParams } from '@/hooks/use-app-params';
-import type { IIntegrationConfig } from '@openpanel/validation';
-import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { useNavigate } from '@tanstack/react-router';
-import { useQueryState } from 'nuqs';
-import { toast } from 'sonner';
-import { popModal } from '.';
-import { ModalHeader } from './Modal/Container';
+import { useTRPC } from '@/integrations/trpc/react';
interface Props {
id?: string;
@@ -29,8 +27,8 @@ export default function AddIntegration(props: Props) {
},
{
enabled: !!props.id,
- },
- ),
+ }
+ )
);
const integration = INTEGRATIONS.find((i) => i.type === props.type);
@@ -53,7 +51,7 @@ export default function AddIntegration(props: Props) {
popModal();
client.invalidateQueries(trpc.integration.list.pathFilter());
client.invalidateQueries(
- trpc.integration.get.queryFilter({ id: props.id }),
+ trpc.integration.get.queryFilter({ id: props.id })
);
navigate({
to: '/$organizationId/$projectId/integrations/installed',
diff --git a/apps/start/src/modals/add-notification-rule.tsx b/apps/start/src/modals/add-notification-rule.tsx
index 85862dca1..8f75f169d 100644
--- a/apps/start/src/modals/add-notification-rule.tsx
+++ b/apps/start/src/modals/add-notification-rule.tsx
@@ -1,6 +1,6 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { shortId } from '@openpanel/common';
-import { isKind, zCreateNotificationRule } from '@openpanel/validation';
+import { isKind } from '@openpanel/core/modules/integration/integration.constants';
+import { zCreateNotificationRule } from '@openpanel/core/modules/notification/notification.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { FilterIcon, PlusIcon, SaveIcon, TrashIcon } from 'lucide-react';
import {
@@ -13,6 +13,7 @@ import {
} from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
+import { shortId } from '../utils/math';
import { popModal } from '.';
import { ModalHeader } from './Modal/Container';
import { ColorSquare } from '@/components/color-square';
@@ -100,7 +101,7 @@ export default function AddNotificationRule({ rule }: Props) {
// Only notification sinks belong in a rule — export integrations (S3/GCS)
// come back from the same list endpoint but have nothing to deliver to.
const integrations = (integrationsQuery.data ?? []).filter((integration) =>
- isKind(integration.config, 'notification'),
+ isKind(integration.config, 'notification')
);
return (
diff --git a/apps/start/src/modals/add-project.tsx b/apps/start/src/modals/add-project.tsx
index 75b688a62..1af404b52 100644
--- a/apps/start/src/modals/add-project.tsx
+++ b/apps/start/src/modals/add-project.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { zOnboardingProject } from '@openpanel/validation';
+import { zOnboardingProject } from '@openpanel/core/modules/onboarding/onboarding.constants';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import {
diff --git a/apps/start/src/modals/add-reference.tsx b/apps/start/src/modals/add-reference.tsx
index 4af13aab1..4c84a09c2 100644
--- a/apps/start/src/modals/add-reference.tsx
+++ b/apps/start/src/modals/add-reference.tsx
@@ -1,20 +1,17 @@
-import { ButtonContainer } from '@/components/button-container';
-import { InputWithLabel } from '@/components/forms/input-with-label';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { handleError } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
+import { zCreateReference } from '@openpanel/core/modules/reference/reference.constants';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-
-import { zCreateReference } from '@openpanel/validation';
-
-import { InputDateTime } from '@/components/ui/input-date-time';
-import { useTRPC } from '@/integrations/trpc/react';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { ButtonContainer } from '@/components/button-container';
+import { InputWithLabel } from '@/components/forms/input-with-label';
+import { Button } from '@/components/ui/button';
+import { InputDateTime } from '@/components/ui/input-date-time';
+import { useAppParams } from '@/hooks/use-app-params';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
type IForm = z.infer<typeof zCreateReference>;
@@ -46,7 +43,7 @@ export default function AddReference({ datetime }: AddReferenceProps = {}) {
popModal();
},
onError: handleError,
- }),
+ })
);
return (
@@ -66,10 +63,10 @@ export default function AddReference({ datetime }: AddReferenceProps = {}) {
)}
/>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
- <Button type="submit" disabled={!formState.isDirty}>
+ <Button disabled={!formState.isDirty} type="submit">
Create
</Button>
</ButtonContainer>
diff --git a/apps/start/src/modals/create-invite.tsx b/apps/start/src/modals/create-invite.tsx
index c1a4de663..2411d1375 100644
--- a/apps/start/src/modals/create-invite.tsx
+++ b/apps/start/src/modals/create-invite.tsx
@@ -1,27 +1,25 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { zInviteUser } from '@openpanel/core/modules/organization/organization.constants';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { SendIcon } from 'lucide-react';
+import { Controller, useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import type { z } from 'zod';
import { InputWithLabel } from '@/components/forms/input-with-label';
+import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
+ closeSheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
- closeSheet,
} from '@/components/ui/sheet';
import { useAppParams } from '@/hooks/use-app-params';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { SendIcon } from 'lucide-react';
-import { Controller, useForm } from 'react-hook-form';
-import { toast } from 'sonner';
-import type { z } from 'zod';
-
-import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
import { useTRPC } from '@/integrations/trpc/react';
-import type { IServiceProject } from '@openpanel/core';
-import { zInviteUser } from '@openpanel/validation';
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
type IForm = z.infer<typeof zInviteUser>;
@@ -31,7 +29,7 @@ export default function CreateInvite() {
const projectsQuery = useQuery(
trpc.project.list.queryOptions({
organizationId,
- }),
+ })
);
const projects = projectsQuery.data ?? [];
@@ -52,7 +50,7 @@ export default function CreateInvite() {
toast.success('User has been invited');
reset();
queryClient.invalidateQueries(
- trpc.organization.invitations.queryFilter({ organizationId }),
+ trpc.organization.invitations.queryFilter({ organizationId })
);
},
onError(error) {
@@ -60,7 +58,7 @@ export default function CreateInvite() {
description: error.message,
});
},
- }),
+ })
);
return (
@@ -86,11 +84,11 @@ export default function CreateInvite() {
organization.
</p>
)}
- <div className="row gap-4 mt-8">
+ <div className="row mt-8 gap-4">
<Button onClick={() => mutation.reset()}>
Invite another user
</Button>
- <Button variant="outline" onClick={() => closeSheet()}>
+ <Button onClick={() => closeSheet()} variant="outline">
Close
</Button>
</div>
@@ -108,37 +106,37 @@ export default function CreateInvite() {
</div>
</SheetHeader>
<form
- onSubmit={handleSubmit((values) => mutation.mutate(values))}
className="flex flex-col gap-8"
+ onSubmit={handleSubmit((values) => mutation.mutate(values))}
>
<InputWithLabel
className="w-full max-w-sm"
- label="Email"
error={formState.errors.email?.message}
+ label="Email"
placeholder="Who do you want to invite?"
{...register('email')}
/>
<div>
<Label>What role?</Label>
<Controller
- name="role"
control={control}
+ name="role"
render={({ field }) => (
<RadioGroup
+ className="flex gap-4"
defaultValue={field.value}
+ onBlur={field.onBlur}
onChange={field.onChange}
ref={field.ref}
- onBlur={field.onBlur}
- className="flex gap-4"
>
<div className="flex items-center gap-2">
- <RadioGroupItem value="org:member" id="member" />
+ <RadioGroupItem id="member" value="org:member" />
<Label className="mb-0" htmlFor="member">
Member
</Label>
</div>
<div className="flex items-center gap-2">
- <RadioGroupItem value="org:admin" id="admin" />
+ <RadioGroupItem id="admin" value="org:admin" />
<Label className="mb-0" htmlFor="admin">
Admin
</Label>
@@ -148,17 +146,17 @@ export default function CreateInvite() {
/>
</div>
<Controller
- name="access"
control={control}
+ name="access"
render={({ field }) => (
<div>
<Label>Restrict access</Label>
<ProjectAccessGrants
- value={field.value}
onChange={field.onChange}
projects={projects}
+ value={field.value}
/>
- <p className="mt-1 text-sm text-muted-foreground">
+ <p className="mt-1 text-muted-foreground text-sm">
Leave empty to give access to all projects
</p>
</div>
@@ -167,8 +165,8 @@ export default function CreateInvite() {
<SheetFooter>
<Button
icon={SendIcon}
- type="submit"
loading={mutation.isPending}
+ type="submit"
>
Invite user
</Button>
diff --git a/apps/start/src/modals/date-ranger-picker.tsx b/apps/start/src/modals/date-ranger-picker.tsx
index e2cd2c90b..a08c15266 100644
--- a/apps/start/src/modals/date-ranger-picker.tsx
+++ b/apps/start/src/modals/date-ranger-picker.tsx
@@ -1,5 +1,5 @@
-import { getDefaultIntervalByDates } from '@openpanel/constants';
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
+import { getDefaultIntervalByDates } from '@openpanel/core/modules/report/report.constants';
import { endOfDay, subMonths } from 'date-fns';
import { CheckIcon, XIcon } from 'lucide-react';
import { useState } from 'react';
diff --git a/apps/start/src/modals/edit-cohort.tsx b/apps/start/src/modals/edit-cohort.tsx
index cfe4b4378..72d870a05 100644
--- a/apps/start/src/modals/edit-cohort.tsx
+++ b/apps/start/src/modals/edit-cohort.tsx
@@ -1,3 +1,11 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import type { CohortDefinition } from '@openpanel/core/modules/cohort/cohort.constants';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { Controller, useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import { z } from 'zod';
+import { popModal } from '.';
+import { ModalContent, ModalHeader } from './Modal/Container';
import { ButtonContainer } from '@/components/button-container';
import { CohortCriteriaBuilder } from '@/components/cohort/cohort-criteria-builder';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
@@ -6,15 +14,6 @@ import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { handleError, useTRPC } from '@/integrations/trpc/react';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
-import type { CohortDefinition } from '@openpanel/validation';
-import { Controller, useForm } from 'react-hook-form';
-import { toast } from 'sonner';
-import { z } from 'zod';
-
-import { popModal } from '.';
-import { ModalContent, ModalHeader } from './Modal/Container';
const validator = z.object({
name: z.string().min(1, 'Required'),
@@ -55,7 +54,7 @@ export default function EditCohort(props: EditCohortProps) {
popModal();
},
onError: handleError,
- }),
+ })
);
return (
@@ -88,17 +87,17 @@ export default function EditCohort(props: EditCohortProps) {
<div className="flex items-center gap-2">
<Controller
- name="isStatic"
control={control}
+ name="isStatic"
render={({ field }) => (
<Switch
- id="isStatic"
checked={field.value}
+ id="isStatic"
onCheckedChange={field.onChange}
/>
)}
/>
- <Label htmlFor="isStatic" className="cursor-pointer text-sm mb-0">
+ <Label className="mb-0 cursor-pointer text-sm" htmlFor="isStatic">
Freeze snapshot (don&apos;t auto-refresh)
</Label>
</div>
@@ -106,8 +105,8 @@ export default function EditCohort(props: EditCohortProps) {
<div>
<Label className="mb-2 block">Cohort Criteria</Label>
<Controller
- name="definition"
control={control}
+ name="definition"
render={({ field }) => (
<CohortCriteriaBuilder
definition={field.value as CohortDefinition}
@@ -118,10 +117,10 @@ export default function EditCohort(props: EditCohortProps) {
</div>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
- <Button type="submit" disabled={!formState.isDirty}>
+ <Button disabled={!formState.isDirty} type="submit">
Save changes
</Button>
</ButtonContainer>
diff --git a/apps/start/src/modals/edit-group.tsx b/apps/start/src/modals/edit-group.tsx
index e4015f74c..5caf7270a 100644
--- a/apps/start/src/modals/edit-group.tsx
+++ b/apps/start/src/modals/edit-group.tsx
@@ -1,6 +1,6 @@
import { zodResolver } from '@hookform/resolvers/zod';
import type { IServiceGroup } from '@openpanel/core';
-import { zUpdateGroup } from '@openpanel/validation';
+import { zUpdateGroup } from '@openpanel/core/modules/group/group.constants';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, Trash2Icon } from 'lucide-react';
import { useFieldArray, useForm } from 'react-hook-form';
diff --git a/apps/start/src/modals/edit-member.tsx b/apps/start/src/modals/edit-member.tsx
index bd5af023b..8792d4f53 100644
--- a/apps/start/src/modals/edit-member.tsx
+++ b/apps/start/src/modals/edit-member.tsx
@@ -1,17 +1,14 @@
-import { ButtonContainer } from '@/components/button-container';
-import { Button } from '@/components/ui/button';
-import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
-import { useTRPC } from '@/integrations/trpc/react';
-import { handleError } from '@/integrations/trpc/react';
+import type { IServiceMember } from '@openpanel/core';
+import type { IProjectAccessGrant } from '@openpanel/core/modules/organization/organization.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { toast } from 'sonner';
-
-import type { IServiceMember } from '@openpanel/core';
-import type { IProjectAccessGrant } from '@openpanel/validation';
-
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { ButtonContainer } from '@/components/button-container';
+import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
+import { Button } from '@/components/ui/button';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
type EditMemberProps = IServiceMember;
@@ -29,7 +26,7 @@ export default function EditMember(member: EditMemberProps) {
const [access, setAccess] = useState<IProjectAccessGrant[]>(toGrants);
const projectsQuery = useQuery(
- trpc.project.list.queryOptions({ organizationId: member.organizationId }),
+ trpc.project.list.queryOptions({ organizationId: member.organizationId })
);
const mutation = useMutation(
@@ -44,7 +41,7 @@ export default function EditMember(member: EditMemberProps) {
queryClient.invalidateQueries(trpc.organization.members.pathFilter());
popModal();
},
- }),
+ })
);
const projects = projectsQuery.data ?? [];
@@ -63,24 +60,24 @@ export default function EditMember(member: EditMemberProps) {
<div className="col gap-4">
<ProjectAccessGrants
- value={access}
onChange={setAccess}
projects={projects}
+ value={access}
/>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
<Button
+ disabled={mutation.isPending}
onClick={() =>
mutation.mutate({
userId: member.user!.id,
organizationId: member.organizationId,
- access: access,
+ access,
})
}
- disabled={mutation.isPending}
>
Save
</Button>
diff --git a/apps/start/src/modals/gsc-details.tsx b/apps/start/src/modals/gsc-details.tsx
index 1891744a8..848f8a56f 100644
--- a/apps/start/src/modals/gsc-details.tsx
+++ b/apps/start/src/modals/gsc-details.tsx
@@ -1,4 +1,7 @@
-import type { IChartRange, IInterval } from '@openpanel/validation';
+import type {
+ IChartRange,
+ IInterval,
+} from '@openpanel/core/modules/report/report.constants';
import { useQuery } from '@tanstack/react-query';
import {
CartesianGrid,
@@ -133,7 +136,8 @@ export default function GscDetails(props: Props) {
return { origin: url.origin, path: url.pathname + url.search };
} catch {
return {
- origin: typeof window !== 'undefined' ? window.location.origin : '',
+ origin:
+ typeof window !== 'undefined' ? window.location.origin : '',
path: value,
};
}
diff --git a/apps/start/src/modals/insight-details.tsx b/apps/start/src/modals/insight-details.tsx
index 4a414b50c..4123e1494 100644
--- a/apps/start/src/modals/insight-details.tsx
+++ b/apps/start/src/modals/insight-details.tsx
@@ -1,3 +1,7 @@
+import type { IReportInput } from '@openpanel/core/modules/report/report.constants';
+import { useMutation } from '@tanstack/react-query';
+import { SparklesIcon } from 'lucide-react';
+import { useEffect, useState } from 'react';
import { DeltaChip } from '@/components/delta-chip';
import { ReportChart } from '@/components/report-chart';
import { Badge } from '@/components/ui/badge';
@@ -5,10 +9,6 @@ import { SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { useTRPC } from '@/integrations/trpc/react';
import type { RouterOutputs } from '@/trpc/client';
import { cn } from '@/utils/cn';
-import type { IReportInput } from '@openpanel/validation';
-import { useMutation } from '@tanstack/react-query';
-import { SparklesIcon } from 'lucide-react';
-import { useEffect, useState } from 'react';
type Insight = RouterOutputs['insight']['list'][number];
type Explanation = RouterOutputs['insight']['explain'];
@@ -35,7 +35,7 @@ function SeverityDot({ band }: { band: string }) {
? 'bg-red-500'
: band === 'moderate'
? 'bg-yellow-500'
- : 'bg-blue-500',
+ : 'bg-blue-500'
)}
/>
<span className="text-muted-foreground text-xs capitalize">{band}</span>
@@ -57,7 +57,9 @@ function buildInsightReport(insight: Insight): IReportInput | null {
operator: 'is' as const,
value: [d.value],
}));
- if (filters.length === 0) return null;
+ if (filters.length === 0) {
+ return null;
+ }
const range = insight.windowKind === 'yesterday' ? '7d' : '30d';
@@ -96,7 +98,7 @@ export default function InsightDetails({ insight }: { insight: Insight }) {
const mutation = useMutation(
trpc.insight.explain.mutationOptions({
onSuccess: (data) => setExplanation(data),
- }),
+ })
);
// Fetch the explanation once when the sheet opens.
@@ -129,7 +131,9 @@ export default function InsightDetails({ insight }: { insight: Insight }) {
<div className="flex flex-col gap-2 pr-8">
<div className="flex items-center gap-2">
<Badge variant="outline">{formatWindow(insight.windowKind)}</Badge>
- {insight.severityBand && <SeverityDot band={insight.severityBand} />}
+ {insight.severityBand && (
+ <SeverityDot band={insight.severityBand} />
+ )}
</div>
<SheetTitle className="text-lg leading-snug">
{insight.displayName || insight.title}
@@ -161,7 +165,11 @@ export default function InsightDetails({ insight }: { insight: Insight }) {
<DeltaChip
size="sm"
variant={
- direction === 'up' ? 'inc' : direction === 'down' ? 'dec' : 'default'
+ direction === 'up'
+ ? 'inc'
+ : direction === 'down'
+ ? 'dec'
+ : 'default'
}
>
{deltaText}
diff --git a/apps/start/src/modals/overview-chart-details.tsx b/apps/start/src/modals/overview-chart-details.tsx
index 1ab580e91..3fa0eb711 100644
--- a/apps/start/src/modals/overview-chart-details.tsx
+++ b/apps/start/src/modals/overview-chart-details.tsx
@@ -1,10 +1,8 @@
+import type { IReport } from '@openpanel/core/modules/report/report.constants';
+import { ModalContent, ModalHeader } from './Modal/Container';
import { ReportChart } from '@/components/report-chart';
import { ScrollArea } from '@/components/ui/scroll-area';
-import type { IReport } from '@openpanel/validation';
-
-import { ModalContent, ModalHeader } from './Modal/Container';
-
type Props = {
chart: IReport;
};
diff --git a/apps/start/src/modals/overview-filters.tsx b/apps/start/src/modals/overview-filters.tsx
index 2336ccc2f..02f20c6ff 100644
--- a/apps/start/src/modals/overview-filters.tsx
+++ b/apps/start/src/modals/overview-filters.tsx
@@ -1,30 +1,36 @@
+import type {
+ IChartEventFilter,
+ IChartEventFilterOperator,
+ IChartEventFilterValue,
+} from '@openpanel/core/modules/report/report.constants';
+import {
+ FilterIcon,
+ GanttChartIcon,
+ GlobeIcon,
+ type LucideIcon,
+ SlidersHorizontal,
+ SparklesIcon,
+ XIcon,
+} from 'lucide-react';
+import type { Options as NuqsOptions } from 'nuqs';
+import { ModalHeader } from './Modal/Container';
+import { OriginFilter } from '@/components/overview/filters/origin-filter';
+import { OverviewAICommand } from '@/components/overview/overview-ai-command';
import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
+import { PropertiesCombobox } from '@/components/report/sidebar/PropertiesCombobox';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
+import { ComboboxEvents } from '@/components/ui/combobox-events';
import { SheetContent } from '@/components/ui/sheet';
+import { useAppParams } from '@/hooks/use-app-params';
import { useEventNames } from '@/hooks/use-event-names';
import {
useEventQueryFilters,
useEventQueryNamesFilter,
} from '@/hooks/use-event-query-filters';
import { useProfileValues } from '@/hooks/use-profile-values';
-import { FilterIcon, GanttChartIcon, GlobeIcon, LucideIcon, SlidersHorizontal, SparklesIcon, XIcon } from 'lucide-react';
-import type { Options as NuqsOptions } from 'nuqs';
-
-import type {
- IChartEventFilter,
- IChartEventFilterOperator,
- IChartEventFilterValue,
-} from '@openpanel/validation';
-
-import { OriginFilter } from '@/components/overview/filters/origin-filter';
-import { OverviewAICommand } from '@/components/overview/overview-ai-command';
-import { PropertiesCombobox } from '@/components/report/sidebar/PropertiesCombobox';
-import { ComboboxEvents } from '@/components/ui/combobox-events';
-import { useAppParams } from '@/hooks/use-app-params';
import { cn } from '@/utils/cn';
-import { ModalHeader } from './Modal/Container';
export interface OverviewFiltersProps {
nuqsOptions?: NuqsOptions;
@@ -32,13 +38,17 @@ export interface OverviewFiltersProps {
mode?: 'events' | 'profile';
}
-const Seperator = () => <div className="h-px bg-border -mx-6" />
-const Heading = ({ title, icon: Icon }: { title: string, icon: LucideIcon }) => (
+const Seperator = () => <div className="-mx-6 h-px bg-border" />;
+const Heading = ({
+ title,
+ icon: Icon,
+}: {
+ title: string;
+ icon: LucideIcon;
+}) => (
<div className="row items-center gap-2">
<Icon className="size-4" />
- <h2 className="text-sm font-medium">
- {title}
- </h2>
+ <h2 className="font-medium text-sm">{title}</h2>
</div>
);
@@ -69,8 +79,8 @@ export default function OverviewFilters({
...(updated.cohortIds ? { cohortIds: updated.cohortIds } : {}),
...(updated.cohortId ? { cohortId: updated.cohortId } : {}),
}
- : f,
- ),
+ : f
+ )
);
};
return (
@@ -85,31 +95,27 @@ export default function OverviewFilters({
<Seperator />
{enableEventsFilter && (
<>
- <Heading icon={GanttChartIcon} title="Events" />
- <ComboboxEvents
- size="lg"
- className="w-full"
- value={event}
- onChange={setEvent}
- multiple
- items={eventNames}
- placeholder="Select event"
- maxDisplayItems={2}
- searchable
+ <Heading icon={GanttChartIcon} title="Events" />
+ <ComboboxEvents
+ className="w-full"
+ items={eventNames}
+ maxDisplayItems={2}
+ multiple
+ onChange={setEvent}
+ placeholder="Select event"
+ searchable
+ size="lg"
+ value={event}
/>
<Seperator />
</>
)}
</div>
- <Heading icon={SlidersHorizontal} title="Filters" />
+ <Heading icon={SlidersHorizontal} title="Filters" />
<div className="flex flex-col gap-2">
- <div
- className={cn(
- 'bg-card rounded-lg border',
- )}
- >
+ <div className={cn('rounded-lg border bg-card')}>
{selectedFilters.length === 0 && (
- <div className="p-4 text-center text-sm text-muted-foreground">
+ <div className="p-4 text-center text-muted-foreground text-sm">
No filters selected
</div>
)}
@@ -118,12 +124,8 @@ export default function OverviewFilters({
return (
<PureCohortFilterItem
className="border-t p-4 first:border-0"
- key={filter.id ?? filter.name}
filter={filter}
- onRemove={(target) => removeFilter(target.name)}
- onChangeOperator={(operator, original) =>
- updateCohortFilter({ ...original, operator })
- }
+ key={filter.id ?? filter.name}
onChangeCohort={(cohortIds, original) =>
updateCohortFilter({
...original,
@@ -131,6 +133,10 @@ export default function OverviewFilters({
cohortIds,
})
}
+ onChangeOperator={(operator, original) =>
+ updateCohortFilter({ ...original, operator })
+ }
+ onRemove={(target) => removeFilter(target.name)}
/>
);
}
@@ -138,16 +144,16 @@ export default function OverviewFilters({
<PureFilterItem
className="border-t p-4 first:border-0"
eventName="screen_view"
- key={filter.name}
filter={filter}
- onRemove={() => {
- setFilter(filter.name, [], filter.operator);
+ key={filter.name}
+ onChangeOperator={(operator) => {
+ setFilter(filter.name, filter.value, operator);
}}
onChangeValue={(value) => {
setFilter(filter.name, value, filter.operator);
}}
- onChangeOperator={(operator) => {
- setFilter(filter.name, filter.value, operator);
+ onRemove={() => {
+ setFilter(filter.name, [], filter.operator);
}}
/>
);
@@ -177,7 +183,9 @@ export default function OverviewFilters({
// Only one cohort filter at a time; OR-semantics live inside
// the filter's cohortIds array.
const hasCohort = filters.some(isCohortFilter);
- if (hasCohort) return;
+ if (hasCohort) {
+ return;
+ }
setFilters((prev) => [
...prev,
{
@@ -195,11 +203,11 @@ export default function OverviewFilters({
>
{(setOpen) => (
<Button
- onClick={() => setOpen((p) => !p)}
- variant="outline"
- size="lg"
className="w-full"
icon={FilterIcon}
+ onClick={() => setOpen((p) => !p)}
+ size="lg"
+ variant="outline"
>
Add filter
</Button>
@@ -219,7 +227,7 @@ export function FilterOptionProfile({
setFilter: (
name: string,
value: IChartEventFilterValue,
- operator: IChartEventFilterOperator,
+ operator: IChartEventFilterOperator
) => void;
}) {
const values = useProfileValues(projectId, filter.name);
@@ -229,20 +237,20 @@ export function FilterOptionProfile({
<div>{filter.name}</div>
<Combobox
className="flex-1"
- onChange={(value) => setFilter(filter.name, value, filter.operator)}
- placeholder={'Select a value'}
items={values.map((value) => ({
value,
label: value,
}))}
+ onChange={(value) => setFilter(filter.name, value, filter.operator)}
+ placeholder={'Select a value'}
value={String(filter.value[0] ?? '')}
/>
<Button
- size="icon"
- variant="ghost"
onClick={() =>
setFilter(filter.name, filter.value[0] ?? '', filter.operator)
}
+ size="icon"
+ variant="ghost"
>
<XIcon />
</Button>
diff --git a/apps/start/src/modals/request-reset-password.tsx b/apps/start/src/modals/request-reset-password.tsx
index 89f695bc4..2b25d14e6 100644
--- a/apps/start/src/modals/request-reset-password.tsx
+++ b/apps/start/src/modals/request-reset-password.tsx
@@ -1,19 +1,17 @@
-import { Button } from '@/components/ui/button';
-import { DialogFooter } from '@/components/ui/dialog';
-import { handleError } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
+import { zRequestResetPassword } from '@openpanel/core/modules/auth/auth.constants';
+import { useMutation } from '@tanstack/react-query';
import { useRouter } from '@tanstack/react-router';
import { SendIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-
-import { InputWithLabel } from '@/components/forms/input-with-label';
-import { useTRPC } from '@/integrations/trpc/react';
-import { zRequestResetPassword } from '@openpanel/validation';
-import { useMutation } from '@tanstack/react-query';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { InputWithLabel } from '@/components/forms/input-with-label';
+import { Button } from '@/components/ui/button';
+import { DialogFooter } from '@/components/ui/dialog';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
const validation = zRequestResetPassword;
type IForm = z.infer<typeof validation>;
@@ -38,7 +36,7 @@ export default function RequestPasswordReset({ email }: Props) {
popModal();
},
onError: handleError,
- }),
+ })
);
const onSubmit = form.handleSubmit((values) => {
@@ -52,21 +50,21 @@ export default function RequestPasswordReset({ email }: Props) {
<ModalHeader title="Request password reset" />
<form className="flex flex-col gap-4" onSubmit={onSubmit}>
<InputWithLabel
+ error={form.formState.errors.email?.message}
label="Email"
placeholder="Your email address"
- error={form.formState.errors.email?.message}
{...form.register('email')}
/>
<DialogFooter>
<Button
+ onClick={() => popModal()}
type="button"
variant={'secondary'}
- onClick={() => popModal()}
>
Cancel
</Button>
- <Button type="submit" icon={SendIcon} loading={mutation.isPending}>
+ <Button icon={SendIcon} loading={mutation.isPending} type="submit">
Continue
</Button>
</DialogFooter>
diff --git a/apps/start/src/modals/save-report.tsx b/apps/start/src/modals/save-report.tsx
index 1fbec1422..ae15d59bb 100644
--- a/apps/start/src/modals/save-report.tsx
+++ b/apps/start/src/modals/save-report.tsx
@@ -1,21 +1,18 @@
-import { ButtonContainer } from '@/components/button-container';
-import { SelectDashboard } from '@/components/dashboards/select-dashboard';
-import { InputWithLabel } from '@/components/forms/input-with-label';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { handleError } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
+import type { IReport } from '@openpanel/core/modules/report/report.constants';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter, useSearch } from '@tanstack/react-router';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
-
-import type { IReport } from '@openpanel/validation';
-
-import { useTRPC } from '@/integrations/trpc/react';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { ButtonContainer } from '@/components/button-container';
+import { SelectDashboard } from '@/components/dashboards/select-dashboard';
+import { InputWithLabel } from '@/components/forms/input-with-label';
+import { Button } from '@/components/ui/button';
+import { useAppParams } from '@/hooks/use-app-params';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
type SaveReportProps = {
report: IReport;
@@ -51,7 +48,7 @@ export default function SaveReport({
trpc.report.list.queryFilter({
dashboardId: res.dashboardId,
projectId,
- }),
+ })
);
queryClient.invalidateQueries(trpc.dashboard.list.pathFilter());
@@ -81,7 +78,7 @@ export default function SaveReport({
popModal();
},
- }),
+ })
);
const { register, handleSubmit, formState, control, setValue } =
@@ -120,23 +117,23 @@ export default function SaveReport({
render={({ field }) => {
return (
<SelectDashboard
- value={field.value}
onChange={field.onChange}
projectId={projectId!}
+ value={field.value}
/>
);
}}
/>
<ButtonContainer>
<Button
- type="button"
- variant="outline"
onClick={() => popModal()}
size="default"
+ type="button"
+ variant="outline"
>
Cancel
</Button>
- <Button type="submit" disabled={!formState.isValid} size="default">
+ <Button disabled={!formState.isValid} size="default" type="submit">
Save
</Button>
</ButtonContainer>
@@ -144,4 +141,3 @@ export default function SaveReport({
</ModalContent>
);
}
-
diff --git a/apps/start/src/modals/share-dashboard-modal.tsx b/apps/start/src/modals/share-dashboard-modal.tsx
index 5ac705540..c0c5dd411 100644
--- a/apps/start/src/modals/share-dashboard-modal.tsx
+++ b/apps/start/src/modals/share-dashboard-modal.tsx
@@ -1,23 +1,20 @@
-import { ButtonContainer } from '@/components/button-container';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { handleError } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
+import { zShareDashboard } from '@openpanel/core/modules/share/share.constants';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
+import { CheckCircle2, Copy, ExternalLink, TrashIcon } from 'lucide-react';
+import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-
-import { zShareDashboard } from '@openpanel/validation';
-
-import { Input } from '@/components/ui/input';
-import { Tooltiper } from '@/components/ui/tooltip';
-import { useTRPC } from '@/integrations/trpc/react';
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { CheckCircle2, Copy, ExternalLink, TrashIcon } from 'lucide-react';
-import { useState } from 'react';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { ButtonContainer } from '@/components/button-container';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Tooltiper } from '@/components/ui/tooltip';
+import { useAppParams } from '@/hooks/use-app-params';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
const validator = zShareDashboard;
@@ -40,7 +37,7 @@ export default function ShareDashboardModal({
trpc.share.dashboardSettings.queryOptions({
projectId,
dashboardId,
- }),
+ })
);
const existingShare = shareQuery.data;
@@ -66,7 +63,9 @@ export default function ShareDashboardModal({
trpc.share.createDashboard.mutationOptions({
onError: handleError,
onSuccess(res) {
- queryClient.invalidateQueries(trpc.share.dashboardSettings.pathFilter());
+ queryClient.invalidateQueries(
+ trpc.share.dashboardSettings.pathFilter()
+ );
toast('Success', {
description: `Your dashboard is now ${
res.public ? 'public' : 'private'
@@ -86,7 +85,7 @@ export default function ShareDashboardModal({
});
popModal();
},
- }),
+ })
);
const handleCopyLink = () => {
@@ -109,28 +108,28 @@ export default function ShareDashboardModal({
return (
<ModalContent className="max-w-md">
<ModalHeader
- title="Dashboard public availability"
text={
isShared
? 'Your dashboard is currently public and can be accessed by anyone with the link.'
: 'You can choose if you want to add a password to make it a bit more private.'
}
+ title="Dashboard public availability"
/>
{isShared && (
- <div className="p-4 bg-def-100 border rounded-lg space-y-3">
- <div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
+ <div className="space-y-3 rounded-lg border bg-def-100 p-4">
+ <div className="flex items-center gap-2 text-green-600 text-sm dark:text-green-400">
<CheckCircle2 className="size-4" />
<span className="font-medium">Currently shared</span>
</div>
<div className="flex items-center gap-1">
- <Input value={shareUrl} readOnly className="flex-1 text-sm" />
+ <Input className="flex-1 text-sm" readOnly value={shareUrl} />
<Tooltiper content="Copy link">
<Button
+ onClick={handleCopyLink}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={handleCopyLink}
>
{copied ? (
<CheckCircle2 className="size-4" />
@@ -141,19 +140,19 @@ export default function ShareDashboardModal({
</Tooltiper>
<Tooltiper content="Open in new tab">
<Button
+ onClick={() => window.open(shareUrl, '_blank')}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="size-4" />
</Button>
</Tooltiper>
<Tooltiper content="Make private">
<Button
+ onClick={handleMakePrivate}
type="button"
variant="destructive"
- onClick={handleMakePrivate}
>
<TrashIcon className="size-4" />
</Button>
@@ -179,7 +178,7 @@ export default function ShareDashboardModal({
type={password === '••••••••' ? 'text' : 'password'}
/>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
diff --git a/apps/start/src/modals/share-overview-modal.tsx b/apps/start/src/modals/share-overview-modal.tsx
index ced7a9660..3223aa22b 100644
--- a/apps/start/src/modals/share-overview-modal.tsx
+++ b/apps/start/src/modals/share-overview-modal.tsx
@@ -1,23 +1,20 @@
-import { ButtonContainer } from '@/components/button-container';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { handleError } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
+import { zShareOverview } from '@openpanel/core/modules/share/share.constants';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
+import { CheckCircle2, Copy, ExternalLink, TrashIcon } from 'lucide-react';
+import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-
-import { zShareOverview } from '@openpanel/validation';
-
-import { Input } from '@/components/ui/input';
-import { Tooltiper } from '@/components/ui/tooltip';
-import { useTRPC } from '@/integrations/trpc/react';
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { CheckCircle2, Copy, ExternalLink, TrashIcon } from 'lucide-react';
-import { useState } from 'react';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { ButtonContainer } from '@/components/button-container';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Tooltiper } from '@/components/ui/tooltip';
+import { useAppParams } from '@/hooks/use-app-params';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
const validator = zShareOverview;
@@ -35,7 +32,7 @@ export default function ShareOverviewModal() {
const shareQuery = useQuery(
trpc.share.overviewSettings.queryOptions({
projectId,
- }),
+ })
);
const existingShare = shareQuery.data;
@@ -80,7 +77,7 @@ export default function ShareOverviewModal() {
});
popModal();
},
- }),
+ })
);
const handleCopyLink = () => {
@@ -102,28 +99,28 @@ export default function ShareOverviewModal() {
return (
<ModalContent className="max-w-md">
<ModalHeader
- title="Overview public availability"
text={
isShared
? 'Your overview is currently public and can be accessed by anyone with the link.'
: 'You can choose if you want to add a password to make it a bit more private.'
}
+ title="Overview public availability"
/>
{isShared && (
- <div className="p-4 bg-def-100 border rounded-lg space-y-3">
- <div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
+ <div className="space-y-3 rounded-lg border bg-def-100 p-4">
+ <div className="flex items-center gap-2 text-green-600 text-sm dark:text-green-400">
<CheckCircle2 className="size-4" />
<span className="font-medium">Currently shared</span>
</div>
<div className="flex items-center gap-1">
- <Input value={shareUrl} readOnly className="flex-1 text-sm" />
+ <Input className="flex-1 text-sm" readOnly value={shareUrl} />
<Tooltiper content="Copy link">
<Button
+ onClick={handleCopyLink}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={handleCopyLink}
>
{copied ? (
<CheckCircle2 className="size-4" />
@@ -134,19 +131,19 @@ export default function ShareOverviewModal() {
</Tooltiper>
<Tooltiper content="Open in new tab">
<Button
+ onClick={() => window.open(shareUrl, '_blank')}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="size-4" />
</Button>
</Tooltiper>
<Tooltiper content="Make private">
<Button
+ onClick={handleMakePrivate}
type="button"
variant="destructive"
- onClick={handleMakePrivate}
>
<TrashIcon className="size-4" />
</Button>
@@ -172,7 +169,7 @@ export default function ShareOverviewModal() {
type={password === '••••••••' ? 'text' : 'password'}
/>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
@@ -183,4 +180,4 @@ export default function ShareOverviewModal() {
</form>
</ModalContent>
);
-}
\ No newline at end of file
+}
diff --git a/apps/start/src/modals/share-report-modal.tsx b/apps/start/src/modals/share-report-modal.tsx
index 139180e58..fb91ab0ba 100644
--- a/apps/start/src/modals/share-report-modal.tsx
+++ b/apps/start/src/modals/share-report-modal.tsx
@@ -1,23 +1,20 @@
-import { ButtonContainer } from '@/components/button-container';
-import { Button } from '@/components/ui/button';
-import { useAppParams } from '@/hooks/use-app-params';
-import { handleError } from '@/integrations/trpc/react';
import { zodResolver } from '@hookform/resolvers/zod';
+import { zShareReport } from '@openpanel/core/modules/share/share.constants';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
+import { CheckCircle2, Copy, ExternalLink, TrashIcon } from 'lucide-react';
+import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-
-import { zShareReport } from '@openpanel/validation';
-
-import { Input } from '@/components/ui/input';
-import { Tooltiper } from '@/components/ui/tooltip';
-import { useTRPC } from '@/integrations/trpc/react';
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { CheckCircle2, Copy, ExternalLink, TrashIcon } from 'lucide-react';
-import { useState } from 'react';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import { ButtonContainer } from '@/components/button-container';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Tooltiper } from '@/components/ui/tooltip';
+import { useAppParams } from '@/hooks/use-app-params';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
const validator = zShareReport;
@@ -36,7 +33,7 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
trpc.share.reportSettings.queryOptions({
projectId,
reportId,
- }),
+ })
);
const existingShare = shareQuery.data;
@@ -80,7 +77,7 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
});
popModal();
},
- }),
+ })
);
const handleCopyLink = () => {
@@ -103,28 +100,28 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
return (
<ModalContent className="max-w-md">
<ModalHeader
- title="Report public availability"
text={
isShared
? 'Your report is currently public and can be accessed by anyone with the link.'
: 'You can choose if you want to add a password to make it a bit more private.'
}
+ title="Report public availability"
/>
{isShared && (
- <div className="p-4 bg-def-100 border rounded-lg space-y-3">
- <div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
+ <div className="space-y-3 rounded-lg border bg-def-100 p-4">
+ <div className="flex items-center gap-2 text-green-600 text-sm dark:text-green-400">
<CheckCircle2 className="size-4" />
<span className="font-medium">Currently shared</span>
</div>
<div className="flex items-center gap-1">
- <Input value={shareUrl} readOnly className="flex-1 text-sm" />
+ <Input className="flex-1 text-sm" readOnly value={shareUrl} />
<Tooltiper content="Copy link">
<Button
+ onClick={handleCopyLink}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={handleCopyLink}
>
{copied ? (
<CheckCircle2 className="size-4" />
@@ -135,19 +132,19 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
</Tooltiper>
<Tooltiper content="Open in new tab">
<Button
+ onClick={() => window.open(shareUrl, '_blank')}
+ size="sm"
type="button"
variant="outline"
- size="sm"
- onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="size-4" />
</Button>
</Tooltiper>
<Tooltiper content="Make private">
<Button
+ onClick={handleMakePrivate}
type="button"
variant="destructive"
- onClick={handleMakePrivate}
>
<TrashIcon className="size-4" />
</Button>
@@ -173,7 +170,7 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
type={password === '••••••••' ? 'text' : 'password'}
/>
<ButtonContainer>
- <Button type="button" variant="outline" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} type="button" variant="outline">
Cancel
</Button>
@@ -184,4 +181,4 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
</form>
</ModalContent>
);
-}
\ No newline at end of file
+}
diff --git a/apps/start/src/modals/table-filters.tsx b/apps/start/src/modals/table-filters.tsx
index b6bb9f17e..0ead52b95 100644
--- a/apps/start/src/modals/table-filters.tsx
+++ b/apps/start/src/modals/table-filters.tsx
@@ -1,16 +1,16 @@
+import type { IChartEventFilter } from '@openpanel/core/modules/report/report.constants';
import { FilterIcon, type LucideIcon, SlidersHorizontal } from 'lucide-react';
-import type { IChartEventFilter } from '@openpanel/validation';
+import { ModalHeader } from './Modal/Container';
+import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
+import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
import {
PropertiesCombobox,
type PropertiesComboboxCategory,
} from '@/components/report/sidebar/PropertiesCombobox';
-import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
-import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
import { Button } from '@/components/ui/button';
import { SheetContent } from '@/components/ui/sheet';
import { useTableFilters } from '@/hooks/use-table-filters';
import { cn } from '@/utils/cn';
-import { ModalHeader } from './Modal/Container';
export interface TableFiltersProps {
/** URL query-string key the filters are stored under (matches useTableFilters). */
@@ -30,7 +30,7 @@ const Heading = ({
}) => (
<div className="row items-center gap-2">
<Icon className="size-4" />
- <h2 className="text-sm font-medium">{title}</h2>
+ <h2 className="font-medium text-sm">{title}</h2>
</div>
);
@@ -59,9 +59,11 @@ export default function TableFilters({
// Only one cohort filter at a time — multi-cohort OR semantics already
// live inside a single filter's cohortIds array.
const hasCohort = filters.some(
- (f) => f.operator === 'inCohort' || f.operator === 'notInCohort',
+ (f) => f.operator === 'inCohort' || f.operator === 'notInCohort'
);
- if (hasCohort) return;
+ if (hasCohort) {
+ return;
+ }
setFilters([
...filters,
{
@@ -92,9 +94,9 @@ export default function TableFilters({
<ModalHeader title={title} />
<Heading icon={SlidersHorizontal} title="Filters" />
<div className="flex flex-col gap-2">
- <div className={cn('bg-card rounded-lg border')}>
+ <div className={cn('rounded-lg border bg-card')}>
{filters.length === 0 && (
- <div className="p-4 text-center text-sm text-muted-foreground">
+ <div className="p-4 text-center text-muted-foreground text-sm">
No filters selected
</div>
)}
@@ -106,12 +108,8 @@ export default function TableFilters({
return (
<PureCohortFilterItem
className="border-t p-4 first:border-0"
- key={filter.id ?? filter.name}
filter={filter}
- onRemove={removeFilter}
- onChangeOperator={(operator, original) =>
- setFilter({ ...original, operator })
- }
+ key={filter.id ?? filter.name}
onChangeCohort={(cohortIds, original) => {
// Write both cohort fields so legacy consumers reading
// `cohortId` keep working. Name stays stable as `cohort`
@@ -123,6 +121,10 @@ export default function TableFilters({
cohortIds,
});
}}
+ onChangeOperator={(operator, original) =>
+ setFilter({ ...original, operator })
+ }
+ onRemove={removeFilter}
/>
);
}
@@ -130,12 +132,8 @@ export default function TableFilters({
<PureFilterItem
className="border-t p-4 first:border-0"
eventName="screen_view"
- key={filter.id ?? filter.name}
filter={filter}
- onRemove={removeFilter}
- onChangeValue={(value, original) =>
- setFilter({ ...original, value })
- }
+ key={filter.id ?? filter.name}
onChangeOperator={(operator, original) =>
setFilter({
...original,
@@ -143,6 +141,10 @@ export default function TableFilters({
value: original.value.filter(Boolean).slice(0, 1),
})
}
+ onChangeValue={(value, original) =>
+ setFilter({ ...original, value })
+ }
+ onRemove={removeFilter}
/>
);
})}
@@ -150,11 +152,11 @@ export default function TableFilters({
<PropertiesCombobox categories={categories} onSelect={addFilter}>
{(setOpen) => (
<Button
- onClick={() => setOpen((p) => !p)}
- variant="outline"
- size="lg"
className="w-full"
icon={FilterIcon}
+ onClick={() => setOpen((p) => !p)}
+ size="lg"
+ variant="outline"
>
Add filter
</Button>
diff --git a/apps/start/src/modals/view-chart-users.tsx b/apps/start/src/modals/view-chart-users.tsx
index 9d117ce9a..4fc78b8cc 100644
--- a/apps/start/src/modals/view-chart-users.tsx
+++ b/apps/start/src/modals/view-chart-users.tsx
@@ -1,3 +1,10 @@
+import type { IReportInput } from '@openpanel/core/modules/report/report.constants';
+import { useQuery } from '@tanstack/react-query';
+import { useVirtualizer } from '@tanstack/react-virtual';
+import { useEffect, useMemo, useState } from 'react';
+import { popModal } from '.';
+import { ModalHeader } from './Modal/Container';
+import { ScrollableModal, useScrollableModal } from './Modal/scrollable-modal';
import { ProjectLink } from '@/components/links';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
@@ -13,39 +20,32 @@ import { useTRPC } from '@/integrations/trpc/react';
import type { IChartData } from '@/trpc/client';
import { cn } from '@/utils/cn';
import { getProfileName } from '@/utils/getters';
-import type { IReportInput } from '@openpanel/validation';
-import { useQuery } from '@tanstack/react-query';
-import { useVirtualizer } from '@tanstack/react-virtual';
-import { useEffect, useMemo, useState } from 'react';
-import { popModal } from '.';
-import { ModalHeader } from './Modal/Container';
-import { ScrollableModal, useScrollableModal } from './Modal/scrollable-modal';
const ProfileItem = ({ profile }: { profile: any }) => {
return (
<ProjectLink
- preload={false}
- to="/profiles/$profileId"
- params={{ profileId: profile.id }}
- title={getProfileName(profile, false)}
- className="col gap-2 rounded-lg border p-2 bg-card"
+ className="col gap-2 rounded-lg border bg-card p-2"
onClick={(e) => {
if (e.metaKey || e.ctrlKey || e.shiftKey) {
return;
}
popModal();
}}
+ params={{ profileId: profile.id }}
+ preload={false}
+ title={getProfileName(profile, false)}
+ to="/profiles/$profileId"
>
- <div className="row gap-2 items-center">
+ <div className="row items-center gap-2">
<ProfileAvatar {...profile} />
<div className="flex-1">
<div className="font-medium">{getProfileName(profile)}</div>
</div>
</div>
- <div className="row gap-4 text-sm overflow-hidden">
+ <div className="row gap-4 overflow-hidden text-sm">
{profile.properties.country && (
- <div className="row gap-2 items-center">
+ <div className="row items-center gap-2">
<SerieIcon name={profile.properties.country} />
<span>
{profile.properties.country}
@@ -54,13 +54,13 @@ const ProfileItem = ({ profile }: { profile: any }) => {
</div>
)}
{profile.properties.os && (
- <div className="row gap-2 items-center">
+ <div className="row items-center gap-2">
<SerieIcon name={profile.properties.os} />
<span>{profile.properties.os}</span>
</div>
)}
{profile.properties.browser && (
- <div className="row gap-2 items-center">
+ <div className="row items-center gap-2">
<SerieIcon name={profile.properties.browser} />
<span>{profile.properties.browser}</span>
</div>
@@ -129,8 +129,8 @@ function ProfileList({ profiles }: { profiles: any[] }) {
const profile = profiles[virtualItem.index];
return (
<div
- key={profile.id}
data-index={virtualItem.index}
+ key={profile.id}
ref={virtualizer.measureElement}
style={{
position: 'absolute',
@@ -193,25 +193,29 @@ interface ChartUsersViewProps {
function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
const trpc = useTRPC();
const [selectedSerieId, setSelectedSerieId] = useState<string | null>(
- report.series[0]?.id || null,
+ report.series[0]?.id || null
);
const [selectedBreakdownId, setSelectedBreakdownId] = useState<string | null>(
- null,
+ null
);
const selectedReportSerie = useMemo(
() => report.series.find((s) => s.id === selectedSerieId),
- [report.series, selectedSerieId],
+ [report.series, selectedSerieId]
);
// Get all chart series that match the selected report serie
const matchingChartSeries = useMemo(() => {
- if (!selectedSerieId || !chartData) return [];
+ if (!(selectedSerieId && chartData)) {
+ return [];
+ }
return chartData.series.filter((s) => s.event.id === selectedSerieId);
}, [chartData?.series, selectedSerieId]);
const selectedBreakdown = useMemo(() => {
- if (!selectedBreakdownId) return null;
+ if (!selectedBreakdownId) {
+ return null;
+ }
return matchingChartSeries.find((s) => s.id === selectedBreakdownId);
}, [matchingChartSeries, selectedBreakdownId]);
@@ -225,7 +229,7 @@ function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
trpc.chart.getProfiles.queryOptions(
{
projectId: report.projectId,
- date: date,
+ date,
series:
selectedReportSerie && selectedReportSerie.type === 'event'
? [
@@ -243,8 +247,8 @@ function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
},
{
enabled: !!selectedReportSerie && selectedReportSerie.type === 'event',
- },
- ),
+ }
+ )
);
return (
@@ -252,14 +256,14 @@ function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
header={
<div>
<ModalHeader
- title="View Users"
text={`Users who performed actions on ${new Date(date).toLocaleDateString()}`}
+ title="View Users"
/>
{report.series.length > 0 && (
<div className="col md:row gap-2">
<Select
- value={selectedSerieId || ''}
onValueChange={handleSerieChange}
+ value={selectedSerieId || ''}
>
<SelectTrigger className="flex-1">
<SelectValue placeholder="Select Serie" />
@@ -277,8 +281,8 @@ function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
{matchingChartSeries.length > 1 && (
<Select
- value={selectedBreakdownId || ''}
onValueChange={(value) => setSelectedBreakdownId(value)}
+ value={selectedBreakdownId || ''}
>
<SelectTrigger className="flex-1">
<SelectValue placeholder="Select Breakdown" />
@@ -289,7 +293,7 @@ function ChartUsersView({ chartData, report, date }: ChartUsersViewProps) {
.map((serie) => (
<SelectItem key={serie.id} value={serie.id}>
{Object.values(serie.event.breakdowns ?? {}).join(
- ', ',
+ ', '
)}
<DropdownMenuShortcut className="ml-auto">
({serie.data.find((d) => d.date === date)?.count})
@@ -318,7 +322,11 @@ interface FunnelUsersViewProps {
breakdownValues?: string[];
}
-function FunnelUsersView({ report, stepIndex, breakdownValues }: FunnelUsersViewProps) {
+function FunnelUsersView({
+ report,
+ stepIndex,
+ breakdownValues,
+}: FunnelUsersViewProps) {
const trpc = useTRPC();
const [showDropoffs, setShowDropoffs] = useState(false);
@@ -335,10 +343,10 @@ function FunnelUsersView({ report, stepIndex, breakdownValues }: FunnelUsersView
...item,
filters: [...(report.globalFilters ?? []), ...item.filters],
}
- : item,
+ : item
),
- stepIndex: stepIndex,
- showDropoffs: showDropoffs,
+ stepIndex,
+ showDropoffs,
funnelWindow:
report.options?.type === 'funnel'
? report.options.funnelWindow
@@ -348,12 +356,12 @@ function FunnelUsersView({ report, stepIndex, breakdownValues }: FunnelUsersView
? report.options.funnelGroup
: undefined,
breakdowns: report.breakdowns,
- breakdownValues: breakdownValues,
+ breakdownValues,
},
{
enabled: stepIndex !== undefined,
- },
- ),
+ }
+ )
);
const isLastStep = stepIndex === report.series.length - 1;
@@ -363,36 +371,36 @@ function FunnelUsersView({ report, stepIndex, breakdownValues }: FunnelUsersView
header={
<div className="flex flex-col gap-2">
<ModalHeader
- title="View Users"
text={
showDropoffs
? `Users who dropped off after step ${stepIndex + 1} of ${report.series.length}`
: `Users who completed step ${stepIndex + 1} of ${report.series.length} in the funnel`
}
+ title="View Users"
/>
{!isLastStep && (
<div className="flex items-center gap-2">
<button
- type="button"
- onClick={() => setShowDropoffs(false)}
className={cn(
- 'px-3 py-1.5 text-sm rounded-md transition-colors',
- !showDropoffs
- ? 'bg-primary text-primary-foreground'
- : 'bg-muted text-muted-foreground hover:bg-muted/80',
+ 'rounded-md px-3 py-1.5 text-sm transition-colors',
+ showDropoffs
+ ? 'bg-muted text-muted-foreground hover:bg-muted/80'
+ : 'bg-primary text-primary-foreground'
)}
+ onClick={() => setShowDropoffs(false)}
+ type="button"
>
Completed
</button>
<button
- type="button"
- onClick={() => setShowDropoffs(true)}
className={cn(
- 'px-3 py-1.5 text-sm rounded-md transition-colors',
+ 'rounded-md px-3 py-1.5 text-sm transition-colors',
showDropoffs
? 'bg-primary text-primary-foreground'
- : 'bg-muted text-muted-foreground hover:bg-muted/80',
+ : 'bg-muted text-muted-foreground hover:bg-muted/80'
)}
+ onClick={() => setShowDropoffs(true)}
+ type="button"
>
Dropped Off
</button>
@@ -427,15 +435,19 @@ type ViewChartUsersProps =
export default function ViewChartUsers(props: ViewChartUsersProps) {
if (props.type === 'funnel') {
return (
- <FunnelUsersView report={props.report} stepIndex={props.stepIndex} breakdownValues={props.breakdownValues} />
+ <FunnelUsersView
+ breakdownValues={props.breakdownValues}
+ report={props.report}
+ stepIndex={props.stepIndex}
+ />
);
}
return (
<ChartUsersView
chartData={props.chartData}
- report={props.report}
date={props.date}
+ report={props.report}
/>
);
}
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx
index 54731f892..c2570dfb9 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx
@@ -9,7 +9,7 @@ import {
useEventQueryNamesFilter,
} from '@/hooks/use-event-query-filters';
-import type { IChartEventItem } from '@openpanel/validation';
+import type { IChartEventItem } from '@openpanel/core/modules/report/report.constants';
import { createFileRoute } from '@tanstack/react-router';
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.widgets.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.widgets.tsx
index 26ce2affc..798d07b6a 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.widgets.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.widgets.tsx
@@ -8,10 +8,7 @@ import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
import { useAppContext } from '@/hooks/use-app-context';
import { useAppParams } from '@/hooks/use-app-params';
import { useTRPC } from '@/integrations/trpc/react';
-import type {
- IRealtimeWidgetOptions,
- IWidgetType,
-} from '@openpanel/validation';
+import type { IRealtimeWidgetOptions, IWidgetType } from '@openpanel/core/modules/report/report.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { ExternalLinkIcon } from 'lucide-react';
diff --git a/apps/start/src/routes/_app.$organizationId.account._tabs.email-preferences.tsx b/apps/start/src/routes/_app.$organizationId.account._tabs.email-preferences.tsx
index dfe6eb782..71ce594e8 100644
--- a/apps/start/src/routes/_app.$organizationId.account._tabs.email-preferences.tsx
+++ b/apps/start/src/routes/_app.$organizationId.account._tabs.email-preferences.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { emailCategories } from '@openpanel/constants';
+import { emailCategories } from '@openpanel/core/modules/email/email.constants';
import {
useMutation,
useQueryClient,
diff --git a/apps/start/src/routes/_app.$organizationId.settings.tsx b/apps/start/src/routes/_app.$organizationId.settings.tsx
index ed408a49a..5ae63068f 100644
--- a/apps/start/src/routes/_app.$organizationId.settings.tsx
+++ b/apps/start/src/routes/_app.$organizationId.settings.tsx
@@ -8,7 +8,7 @@ import DeleteOrganization from '@/components/settings/delete-organization';
import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
import { handleError, useTRPC } from '@/integrations/trpc/react';
import { PAGE_TITLES, createOrganizationTitle } from '@/utils/title';
-import { zEditOrganization } from '@openpanel/validation';
+import { zEditOrganization } from '@openpanel/core/modules/organization/organization.constants';
import { useMutation, useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { Controller, useForm } from 'react-hook-form';
diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsx
index 108617504..857f4398c 100644
--- a/apps/start/src/routes/_steps.onboarding.project.tsx
+++ b/apps/start/src/routes/_steps.onboarding.project.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { zOnboardingProject } from '@openpanel/validation';
+import { zOnboardingProject } from '@openpanel/core/modules/onboarding/onboarding.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router';
import {
diff --git a/apps/start/src/routes/share.dashboard.$shareId.tsx b/apps/start/src/routes/share.dashboard.$shareId.tsx
index 139932fbd..b02fe4081 100644
--- a/apps/start/src/routes/share.dashboard.$shareId.tsx
+++ b/apps/start/src/routes/share.dashboard.$shareId.tsx
@@ -14,7 +14,7 @@ import {
} from '@/components/report/report-item';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
-import { timeWindows } from '@openpanel/constants';
+import { timeWindows } from '@openpanel/core/modules/report/report.constants';
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, notFound, useSearch } from '@tanstack/react-router';
import { z } from 'zod';
diff --git a/apps/start/src/routes/unsubscribe.tsx b/apps/start/src/routes/unsubscribe.tsx
index e7ddfea9f..edc267cf2 100644
--- a/apps/start/src/routes/unsubscribe.tsx
+++ b/apps/start/src/routes/unsubscribe.tsx
@@ -1,12 +1,12 @@
-import FullPageLoadingState from '@/components/full-page-loading-state';
-import { PublicPageCard } from '@/components/public-page-card';
-import { Button, LinkButton } from '@/components/ui/button';
-import { useTRPC } from '@/integrations/trpc/react';
-import { emailCategories } from '@openpanel/constants';
+import { emailCategories } from '@openpanel/core/modules/email/email.constants';
import { useMutation } from '@tanstack/react-query';
import { createFileRoute, useSearch } from '@tanstack/react-router';
import { useState } from 'react';
import { z } from 'zod';
+import FullPageLoadingState from '@/components/full-page-loading-state';
+import { PublicPageCard } from '@/components/public-page-card';
+import { Button, LinkButton } from '@/components/ui/button';
+import { useTRPC } from '@/integrations/trpc/react';
const unsubscribeSearchSchema = z.object({
email: z.string().email(),
@@ -38,7 +38,7 @@ function RouteComponent() {
setError(err.message || 'Failed to unsubscribe');
setIsUnsubscribing(false);
},
- }),
+ })
);
const handleUnsubscribe = () => {
@@ -48,21 +48,21 @@ function RouteComponent() {
};
const categoryName =
- emailCategories[category as keyof typeof emailCategories]?.label ?? category;
+ emailCategories[category as keyof typeof emailCategories]?.label ??
+ category;
if (isSuccess) {
return (
<PublicPageCard
- title="Unsubscribed"
description={`You've been unsubscribed from ${categoryName} emails. You won't receive any more ${categoryName.toLowerCase()} emails from
us.`}
+ title="Unsubscribed"
/>
);
}
return (
<PublicPageCard
- title="Unsubscribe"
description={
<>
Unsubscribe from {categoryName} emails? You'll stop receiving{' '}
@@ -70,14 +70,15 @@ function RouteComponent() {
<span className="">{email}</span>
</>
}
+ title="Unsubscribe"
>
<div className="col gap-3">
{error && (
- <div className="bg-destructive/10 text-destructive px-4 py-3 rounded-md text-sm">
+ <div className="rounded-md bg-destructive/10 px-4 py-3 text-destructive text-sm">
{error}
</div>
)}
- <Button onClick={handleUnsubscribe} disabled={isUnsubscribing}>
+ <Button disabled={isUnsubscribing} onClick={handleUnsubscribe}>
{isUnsubscribing ? 'Unsubscribing...' : 'Confirm Unsubscribe'}
</Button>
<LinkButton href="/" variant="ghost">
diff --git a/apps/start/src/utils/math.test.ts b/apps/start/src/utils/math.test.ts
new file mode 100644
index 000000000..624288c31
--- /dev/null
+++ b/apps/start/src/utils/math.test.ts
@@ -0,0 +1,15 @@
+// Ported from packages/core/src/shared/id.test.ts's `describe('shortId')`
+// block — the only id.test.ts coverage relevant here, since generateId
+// isn't one of the seven utilities copied into this file.
+import { describe, expect, test } from 'vitest';
+import { shortId } from './math';
+
+describe('shortId', () => {
+ test('is 4 characters', () => {
+ expect(shortId()).toHaveLength(4);
+ });
+
+ test('is not the same twice in a row', () => {
+ expect(shortId()).not.toBe(shortId());
+ });
+});
diff --git a/apps/start/src/utils/math.ts b/apps/start/src/utils/math.ts
index e41d4e1f5..8fccb12f0 100644
--- a/apps/start/src/utils/math.ts
+++ b/apps/start/src/utils/math.ts
@@ -1 +1,88 @@
-export * from '@openpanel/common';
+// Copied from @openpanel/core/src/shared/math.ts + id.ts (ADR-007/ADR-008:
+// frontend-values-only-constants forbids apps/start value-importing core
+// outside a *.constants.ts path, so these seven common utils are duplicated
+// here rather than re-exported).
+//
+// `isNumber` is mathjs's, not `typeof n === 'number'` — it is the filter
+// predicate for every chart aggregate below, so it stays exactly as it was.
+
+import type { PreviousValue } from '@openpanel/core/modules/report/report.constants';
+import { isNumber } from 'mathjs';
+import { nanoid } from 'nanoid/non-secure';
+import { isNil } from 'ramda';
+
+const SHORT_ID_LENGTH = 4;
+
+export function shortId(): string {
+ return nanoid(SHORT_ID_LENGTH);
+}
+
+export const round = (num: number, decimals = 2) => {
+ const factor = 10 ** decimals;
+ return Math.round((num + Number.EPSILON) * factor) / factor;
+};
+
+export const average = (arr: (number | null)[], includeZero = false) => {
+ const filtered = arr.filter(
+ (n): n is number =>
+ isNumber(n) &&
+ !Number.isNaN(n) &&
+ Number.isFinite(n) &&
+ (includeZero || n !== 0)
+ );
+ const avg = filtered.reduce((p, c) => p + c, 0) / filtered.length;
+ return Number.isNaN(avg) ? 0 : avg;
+};
+
+export const sum = (arr: (number | null | undefined)[]): number =>
+ round(arr.filter(isNumber).reduce((acc, item) => acc + item, 0));
+
+export const min = (arr: (number | null | undefined)[]): number => {
+ const filtered = arr.filter(isNumber);
+ if (filtered.length === 0) {
+ return 0;
+ }
+ return filtered.reduce((a, b) => (b < a ? b : a), filtered[0]!);
+};
+
+export const max = (arr: (number | null | undefined)[]): number => {
+ const filtered = arr.filter(isNumber);
+ if (filtered.length === 0) {
+ return 0;
+ }
+ return filtered.reduce((a, b) => (b > a ? b : a), filtered[0]!);
+};
+
+export function getPreviousMetric(
+ current: number,
+ previous: number | null | undefined
+): PreviousValue {
+ if (isNil(previous)) {
+ return undefined;
+ }
+
+ const diff = round(
+ ((current > previous
+ ? current / previous
+ : current < previous
+ ? previous / current
+ : 0) -
+ 1) *
+ 100,
+ 1
+ );
+
+ return {
+ diff:
+ Number.isNaN(diff) || !Number.isFinite(diff) || current === previous
+ ? null
+ : diff,
+ state:
+ current > previous
+ ? 'positive'
+ : current < previous
+ ? 'negative'
+ : 'neutral',
+ value: previous,
+ };
+}
diff --git a/apps/start/src/utils/slug.ts b/apps/start/src/utils/slug.ts
index e41d4e1f5..3197ae0c9 100644
--- a/apps/start/src/utils/slug.ts
+++ b/apps/start/src/utils/slug.ts
@@ -1 +1,22 @@
-export * from '@openpanel/common';
+// Copied from @openpanel/core/src/shared/slug.ts (ADR-007/ADR-008:
+// frontend-values-only-constants forbids apps/start value-importing core
+// outside a *.constants.ts path).
+import _slugify from 'slugify';
+
+const slugify = (str: string) => {
+ return _slugify(
+ str
+ .replaceAll('å', 'a')
+ .replaceAll('ä', 'a')
+ .replaceAll('ö', 'o')
+ .replaceAll('Å', 'A')
+ .replaceAll('Ä', 'A')
+ .replaceAll('Ö', 'O')
+ .replace(/\|+/g, '-'),
+ { lower: true, strict: true, trim: true }
+ );
+};
+
+export function slug(str: string): string {
+ return slugify(str);
+}
diff --git a/apps/start/src/utils/super-json.ts b/apps/start/src/utils/super-json.ts
new file mode 100644
index 000000000..1b2cbf56a
--- /dev/null
+++ b/apps/start/src/utils/super-json.ts
@@ -0,0 +1,22 @@
+// Copied from @openpanel/core/src/shared/json.ts (ADR-007/ADR-008:
+// frontend-values-only-constants forbids apps/start value-importing core
+// outside a *.constants.ts path). getSuperJson only hands off to superjson's
+// parser when the payload looks like its own `{ json, meta }` envelope; a
+// plain JSON payload round-trips through JSON.parse instead.
+import superjson from 'superjson';
+
+function getSafeJson<T>(str: string): T | null {
+ try {
+ return JSON.parse(str);
+ } catch {
+ return null;
+ }
+}
+
+export function getSuperJson<T>(str: string): T | null {
+ const json = getSafeJson<T>(str);
+ if (typeof json === 'object' && json !== null && 'json' in json) {
+ return superjson.parse<T>(str);
+ }
+ return json;
+}
diff --git a/apps/start/src/utils/theme.ts b/apps/start/src/utils/theme.ts
index 0f2102515..38b3fe228 100644
--- a/apps/start/src/utils/theme.ts
+++ b/apps/start/src/utils/theme.ts
@@ -1,6 +1,6 @@
// import resolveConfig from 'tailwindcss/resolveConfig';
-import { chartColors } from '@openpanel/constants';
+import { chartColors } from '@openpanel/core/modules/report/report.constants';
// import tailwinConfig from '../../tailwind.config';
diff --git a/apps/start/src/utils/union-omit.ts b/apps/start/src/utils/union-omit.ts
new file mode 100644
index 000000000..29c2221d2
--- /dev/null
+++ b/apps/start/src/utils/union-omit.ts
@@ -0,0 +1,4 @@
+// No owning module (ADR-008) — copied rather than value-imported from core.
+export type UnionOmit<T, K extends keyof any> = T extends any
+ ? Omit<T, K>
+ : never;
diff --git a/packages/db/package.json b/packages/db/package.json
index 320496fac..32e591824 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -18,10 +18,8 @@
"@clickhouse/client": "^1.18.5",
"@hyperdx/node-opentelemetry": "catalog:",
"@openpanel/core": "workspace:*",
- "@openpanel/json": "workspace:*",
"@openpanel/payments": "workspace:*",
"@openpanel/redis": "workspace:*",
- "@openpanel/validation": "workspace:*",
"@prisma/client": "^6.14.0",
"jiti": "^2.4.1",
"pino": "catalog:",
diff --git a/packages/db/src/clickhouse/client.ts b/packages/db/src/clickhouse/client.ts
index aae1f6a4b..12c4ff23b 100644
--- a/packages/db/src/clickhouse/client.ts
+++ b/packages/db/src/clickhouse/client.ts
@@ -5,7 +5,7 @@ import type {
} from '@clickhouse/client';
import { ClickHouseLogLevel, createClient } from '@clickhouse/client';
import type { NodeClickHouseClientConfigOptions } from '@clickhouse/client/dist/config';
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import sqlstring from 'sqlstring';
import { createLogger } from '../logger';
import { RoundRobinPicker, withRoundRobinRetry } from './round-robin';
@@ -16,7 +16,10 @@ export { createClient } from '@clickhouse/client';
const logger = createLogger({ name: 'clickhouse' });
import type { Logger } from '@clickhouse/client';
-import { getSafeJson } from '@openpanel/json';
+// Reached by relative path, not the `@openpanel/core` barrel: core depends on
+// this package (@openpanel/db), so importing the barrel here would pull core's
+// entire module graph into packages/db for one leaf JSON helper.
+import { getSafeJson } from '../../../core/src/shared/json';
// All three LogParams types are exported by the client
interface LogParams {
diff --git a/packages/db/src/clickhouse/query-builder.ts b/packages/db/src/clickhouse/query-builder.ts
index 8c5abdc94..d42885852 100644
--- a/packages/db/src/clickhouse/query-builder.ts
+++ b/packages/db/src/clickhouse/query-builder.ts
@@ -1,5 +1,5 @@
import type { ClickHouseClient, ResponseJSON } from '@clickhouse/client';
-import type { IInterval } from '@openpanel/validation';
+import type { IInterval } from '@openpanel/core/modules/report/report.constants';
import sqlstring from 'sqlstring';
type SqlValue = string | number | boolean | Date | null | Expression;
@@ -75,7 +75,8 @@ export class Query<T = any> {
private _transform?: Record<string, (item: T) => any>;
private _union?: Query;
private _dateRegex = /\d{4}-\d{2}-\d{2}([\s:\d.]+)?/g;
- private _dateValueRegex = /^(?:[a-zA-Z]\w*\()?\d{4}-\d{2}-\d{2}(?:[\s:\d.]+)?\)?$/;
+ private _dateValueRegex =
+ /^(?:[a-zA-Z]\w*\()?\d{4}-\d{2}-\d{2}(?:[\s:\d.]+)?\)?$/;
constructor(
private client: ClickHouseClient,
private timezone: string
@@ -342,7 +343,9 @@ export class Query<T = any> {
}
rawJoin(sql: string): this {
- if (this._skipNext) return this;
+ if (this._skipNext) {
+ return this;
+ }
this._rawJoins.push(sql);
return this;
}
diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts
index b4b74b4aa..aaee03717 100644
--- a/packages/db/src/types.ts
+++ b/packages/db/src/types.ts
@@ -1,13 +1,3 @@
-import type {
- CohortDefinition,
- IImportConfig,
- IProjectAccessGrant,
- IIntegrationConfig,
- INotificationRuleConfig,
- IProjectFilters,
- IWidgetOptions,
- InsightPayload,
-} from '@openpanel/validation';
// `IClickhouseEvent`/`IClickhouseBotEvent`/`IClickhouseProfile`/
// `INotificationPayload` all moved to @openpanel/core (M9-CLEANUP-001,
// packages/db's final-surface shrink) — the three local re-export shims that
@@ -25,6 +15,14 @@ import type {
IClickhouseProfile,
INotificationPayload,
} from '@openpanel/core';
+import type { CohortDefinition } from '@openpanel/core/modules/cohort/cohort.constants';
+import type { IImportConfig } from '@openpanel/core/modules/import/import.constants';
+import type { InsightPayload } from '@openpanel/core/modules/insight/insight.constants';
+import type { IIntegrationConfig } from '@openpanel/core/modules/integration/integration.constants';
+import type { INotificationRuleConfig } from '@openpanel/core/modules/notification/notification.constants';
+import type { IProjectAccessGrant } from '@openpanel/core/modules/organization/organization.constants';
+import type { IProjectFilters } from '@openpanel/core/modules/project/project.constants';
+import type { IWidgetOptions } from '@openpanel/core/modules/report/report.constants';
declare global {
namespace PrismaJson {
diff --git a/packages/sdks/express/get-client-ip.ts b/packages/sdks/express/get-client-ip.ts
new file mode 100644
index 000000000..732769297
--- /dev/null
+++ b/packages/sdks/express/get-client-ip.ts
@@ -0,0 +1,155 @@
+/**
+ * Get client IP from headers
+ *
+ * Can be configured via IP_HEADER_ORDER env variable
+ * Example: IP_HEADER_ORDER="cf-connecting-ip,x-real-ip,x-forwarded-for"
+ *
+ * Copied from @openpanel/core's shared get-client-ip module — this package is
+ * bundled standalone (tsup `noExternal` used to pull in the workspace-internal
+ * common shim for exactly this function), so it stays dependency-free rather
+ * than importing @openpanel/core.
+ */
+
+// Order matters: client-forwarded headers (set explicitly by SDKs/upstream
+// servers) must come before infrastructure headers like `cf-connecting-ip`.
+// Otherwise, when our API sits behind Cloudflare (orange cloud), Cloudflare
+// rewrites `cf-connecting-ip` to the SDK server's IP — losing the original
+// end-user IP that the SDK forwarded in `x-client-ip` / `openpanel-client-ip`.
+export const DEFAULT_IP_HEADER_ORDER = [
+ 'openpanel-client-ip',
+ 'true-client-ip',
+ 'x-client-ip',
+ 'cf-connecting-ip',
+ 'x-forwarded-for',
+ 'x-real-ip',
+ 'fastly-client-ip',
+ 'x-cluster-client-ip',
+ 'x-appengine-user-ip',
+ 'do-connecting-ip',
+ 'x-nf-client-connection-ip',
+ 'x-forwarded',
+ 'forwarded',
+];
+
+function isPublicIp(ip: string): boolean {
+ // Handle IPv4-mapped IPv6 addresses (e.g., ::ffff:127.0.0.1)
+ if (ip.startsWith('::ffff:')) {
+ const ipv4Part = ip.substring(7); // Extract IPv4 part after "::ffff:"
+ return isPublicIp(ipv4Part); // Recursively check the IPv4 address
+ }
+
+ // IPv6 loopback
+ if (ip === '::1') {
+ return false;
+ }
+
+ // IPv6 private ranges (fc00::/7 and fe80::/10)
+ if (
+ ip.startsWith('fc00:') ||
+ ip.startsWith('fd00:') ||
+ ip.startsWith('fe80:')
+ ) {
+ return false;
+ }
+
+ // IPv4 loopback (127.0.0.0/8)
+ if (ip.startsWith('127.')) {
+ return false;
+ }
+
+ // IPv4 private ranges
+ // 10.0.0.0/8
+ if (ip.startsWith('10.')) {
+ return false;
+ }
+ // 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
+ if (ip.startsWith('172.')) {
+ const parts = ip.split('.');
+ if (parts.length >= 2) {
+ const secondOctet = Number.parseInt(parts[1] || '0', 10);
+ if (secondOctet >= 16 && secondOctet <= 31) {
+ return false;
+ }
+ }
+ }
+ // 192.168.0.0/16
+ if (ip.startsWith('192.168.')) {
+ return false;
+ }
+ // 169.254.0.0/16 (link-local)
+ if (ip.startsWith('169.254.')) {
+ return false;
+ }
+
+ return true;
+}
+
+function getHeaderOrder(): string[] {
+ if (typeof process !== 'undefined' && process.env?.IP_HEADER_ORDER) {
+ return process.env.IP_HEADER_ORDER.split(',').map((h) => h.trim());
+ }
+ return DEFAULT_IP_HEADER_ORDER;
+}
+
+function isValidIp(ip: string): boolean {
+ // Basic IP validation
+ const ipv4 = /^(\d{1,3}\.){3}\d{1,3}$/;
+ const ipv6 = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/;
+ return isPublicIp(ip) && (ipv4.test(ip) || ipv6.test(ip));
+}
+
+export function getClientIpFromHeaders(
+ headers: Record<string, string | string[] | undefined> | Headers,
+ overrideHeaderName?: string
+): {
+ ip: string;
+ header: string;
+} {
+ let headerOrder = getHeaderOrder();
+
+ if (overrideHeaderName) {
+ headerOrder = [overrideHeaderName];
+ }
+
+ for (const headerName of headerOrder) {
+ let value: string | null = null;
+
+ // Get header value
+ if (headers instanceof Headers) {
+ value = headers.get(headerName);
+ } else {
+ const headerValue = headers[headerName];
+ if (Array.isArray(headerValue)) {
+ value = headerValue[0] || null;
+ } else {
+ value = headerValue || null;
+ }
+ }
+
+ if (!value) {
+ continue;
+ }
+
+ // Handle x-forwarded-for (comma separated)
+ if (headerName === 'x-forwarded-for') {
+ const firstIp = value.split(',')[0]?.trim();
+ if (firstIp && isValidIp(firstIp)) {
+ return { ip: firstIp, header: headerName };
+ }
+ }
+ // Handle forwarded header (RFC 7239)
+ else if (headerName === 'forwarded') {
+ const match = value.match(/for=(?:"?\[?([^\]"]+)\]?"?)/i);
+ const ip = match?.[1];
+ if (ip && isValidIp(ip)) {
+ return { ip, header: headerName };
+ }
+ }
+ // Regular headers
+ else if (isValidIp(value)) {
+ return { ip: value, header: headerName };
+ }
+ }
+
+ return { ip: '', header: '' };
+}
diff --git a/packages/sdks/express/index.ts b/packages/sdks/express/index.ts
index eeb8164ee..caaea76bc 100644
--- a/packages/sdks/express/index.ts
+++ b/packages/sdks/express/index.ts
@@ -1,7 +1,7 @@
-import { getClientIpFromHeaders } from '@openpanel/common';
import type { OpenPanelOptions } from '@openpanel/sdk';
import { OpenPanel } from '@openpanel/sdk';
import type { NextFunction, Request, Response } from 'express';
+import { getClientIpFromHeaders } from './get-client-ip';
export * from '@openpanel/sdk';
diff --git a/packages/sdks/express/package.json b/packages/sdks/express/package.json
index da8b2f5f5..0f9e394ae 100644
--- a/packages/sdks/express/package.json
+++ b/packages/sdks/express/package.json
@@ -11,8 +11,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "@openpanel/sdk": "workspace:1.3.1-local",
- "@openpanel/common": "workspace:*"
+ "@openpanel/sdk": "workspace:1.3.1-local"
},
"peerDependencies": {
"express": "^4.17.0 || ^5.0.0"
diff --git a/packages/sdks/express/tsup.config.ts b/packages/sdks/express/tsup.config.ts
index cca1fee07..541734ed5 100644
--- a/packages/sdks/express/tsup.config.ts
+++ b/packages/sdks/express/tsup.config.ts
@@ -8,6 +8,4 @@ export default defineConfig({
sourcemap: false,
clean: true,
minify: true,
- // Bundle @openpanel/common into the output instead of treating it as external
- noExternal: ['@openpanel/common'],
});
diff --git a/packages/sdks/sdk/src/index.ts b/packages/sdks/sdk/src/index.ts
index c08f700b7..0d135aa93 100644
--- a/packages/sdks/sdk/src/index.ts
+++ b/packages/sdks/sdk/src/index.ts
@@ -5,10 +5,10 @@
// rollup-plugin-dts (tsup's dts bundler) cannot inline a type that resolves
// through that map's `*` pattern: it leaves an unresolvable
// `@openpanel/core/...` reference in dist/index.d.ts, which breaks for every
-// consumer since core isn't published. A plain deep import into
-// `@openpanel/validation` hits the same wall one hop later, since that
-// package now just re-exports core's. Keeping a literal copy here is what
-// keeps this package's shipped .d.ts self-contained. The SDK wire contract
+// consumer since core isn't published. A plain deep import into any
+// workspace-internal shim package hits the same wall one hop later, since
+// those packages now just re-export core's. Keeping a literal copy here is
+// what keeps this package's shipped .d.ts self-contained. The SDK wire contract
// tests (verification/contracts/sdk) exercise both sides at runtime, so a
// drift shows up as a behavioral failure even without a type-level check.
import { Api } from './api';
diff --git a/packages/sdks/sdk/tsup.config.ts b/packages/sdks/sdk/tsup.config.ts
index 7ebb7ff82..d30d4450a 100644
--- a/packages/sdks/sdk/tsup.config.ts
+++ b/packages/sdks/sdk/tsup.config.ts
@@ -3,9 +3,9 @@ import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['index.ts'],
format: ['cjs', 'esm'],
- // Inline @openpanel/validation types into the bundled .d.ts so consumers
- // don't see `import type { … } from '@openpanel/validation'` (the
- // package is workspace-internal and not published).
+ // Inline @openpanel/core's constants types into the bundled .d.ts so
+ // consumers don't see an `import type { … }` of a workspace-internal,
+ // unpublished package.
dts: { resolve: [/^@openpanel\//] },
splitting: false,
sourcemap: false,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 95b0dd44a..b954963ec 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -307,27 +307,15 @@ importers:
'@number-flow/react':
specifier: 0.5.10
- '@openpanel/common':
- specifier: workspace:^
- version: link:../../packages/common
- '@openpanel/constants':
- specifier: workspace:^
- version: link:../../packages/constants
'@openpanel/core':
specifier: workspace:^
version: link:../../packages/core
- '@openpanel/json':
- specifier: workspace:*
- version: link:../../packages/json
'@openpanel/payments':
specifier: workspace:*
version: link:../../packages/payments
'@openpanel/sdk-info':
specifier: workspace:^
version: link:../../packages/sdks/_info
- '@openpanel/validation':
- specifier: workspace:^
- version: link:../../packages/validation
'@openpanel/web':
specifier: ^1.0.1
version: 1.0.5
@@ -562,12 +550,18 @@ importers:
lucide-react:
specifier: ^0.476.0
version: 0.476.0([email protected])
+ mathjs:
+ specifier: ^12.3.2
+ version: 12.3.2
mitt:
specifier: ^3.0.1
version: 3.0.1
motion:
specifier: ^12.40.0
+ nanoid:
+ specifier: ^5.1.6
+ version: 5.1.6
nuqs:
specifier: ^2.5.2
@@ -1092,18 +1086,12 @@ importers:
'@openpanel/core':
specifier: workspace:*
version: link:../core
- '@openpanel/json':
- specifier: workspace:*
- version: link:../json
'@openpanel/payments':
specifier: workspace:*
version: link:../payments
'@openpanel/redis':
specifier: workspace:*
version: link:../redis
- '@openpanel/validation':
- specifier: workspace:*
- version: link:../validation
'@prisma/client':
specifier: ^6.14.0
@@ -1309,9 +1297,6 @@ importers:
packages/sdks/express:
dependencies:
- '@openpanel/common':
- specifier: workspace:*
- version: link:../../common
'@openpanel/sdk':
specifier: workspace:1.3.1-local
version: link:../sdk
@@ -25591,7 +25576,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/primitive': 1.0.0
'@radix-ui/react-compose-refs': 1.0.0([email protected])
'@radix-ui/react-context': 1.0.0([email protected])
@@ -34451,7 +34436,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
complex.js: 2.1.1
decimal.js: 10.6.0
escape-latex: 1.2.0
@@ -36953,7 +36938,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
classnames: 2.5.1
react: 19.2.3
@@ -36962,7 +36947,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
react: 19.2.3
react-dom: 19.2.3([email protected])
react-is: 18.2.0
diff --git a/tooling/codemods/p11-repoint-imports.ts b/tooling/codemods/p11-codemod.ts
similarity index 74%
rename from tooling/codemods/p11-repoint-imports.ts
rename to tooling/codemods/p11-codemod.ts
index c29168d3c..2df895581 100644
--- a/tooling/codemods/p11-repoint-imports.ts
+++ b/tooling/codemods/p11-codemod.ts
@@ -7,18 +7,24 @@
* docs/P11_DISSOLUTION_MAP.md verbatim. A row's `to` is the default target;
* `toByConsumer[<workspace>]` overrides it for one workspace.
*
- * Two things it does that a sed cannot:
+ * Three things it does that a sed cannot:
* - one import statement fans out to several targets (packages/db/src/types.ts
* splits eight ways), so statements are regrouped by target;
* - per-symbol `type` keywords are preserved exactly as written. A `type`
* keyword can sit on a runtime binding used only in `z.infer<typeof x>`;
* dropping it promotes an erased import into a real one and changes the
- * bundle (ADR-008 risk 4).
+ * bundle (ADR-008 risk 4);
+ * - a named re-export (`export { X } from '@openpanel/validation'`) is
+ * rewritten the same way an import is — same clause grammar, same
+ * per-symbol targets.
*
- * Usage: bun tooling/codemods/p11-repoint-imports.ts <file...>
+ * Idempotent: a rewritten specifier no longer matches DYING, so a second run
+ * over the same files changes nothing.
+ *
+ * Usage: bun tooling/codemods/p11-codemod.ts <file...>
*/
-import { readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, relative, resolve } from 'node:path';
interface MapRow {
@@ -43,14 +49,24 @@ for (const row of MAP) {
const DYING = ['validation', 'constants', 'common', 'json']
.map((name) => `@openpanel/${name}`)
.join('|');
+// Matches both `import { … } from '…'` and the named re-export form
+// `export { … } from '…'` — same clause grammar, same per-symbol targets.
const IMPORT_STATEMENT = new RegExp(
- `import\\s+(type\\s+)?\\{([^}]*)\\}\\s*from\\s*'(${DYING})';`,
+ `(import|export)\\s+(type\\s+)?\\{([^}]*)\\}\\s*from\\s*'(${DYING})';`,
'g'
);
-/** `packages/core`, `apps/start`, … — the key `toByConsumer` is written in. */
+/**
+ * `packages/core`, `apps/start`, `packages/sdks/express`, … — the key
+ * `toByConsumer` is written in. A fixed segment count breaks on the
+ * doubly-nested SDK packages, so this walks up to the nearest package.json.
+ */
function workspaceOf(file: string): string {
- return relative(REPO_ROOT, file).split('/').slice(0, 2).join('/');
+ let dir = dirname(resolve(REPO_ROOT, file));
+ while (dir !== REPO_ROOT && !existsSync(resolve(dir, 'package.json'))) {
+ dir = dirname(dir);
+ }
+ return relative(REPO_ROOT, dir);
}
function targetSpecifier(target: string, file: string): string {
@@ -101,12 +117,16 @@ function parseBindings(clause: string, statementIsType: boolean): Binding[] {
});
}
-function render(bindings: Binding[], specifier: string): string {
+function render(
+ keyword: string,
+ bindings: Binding[],
+ specifier: string
+): string {
const allType = bindings.every((b) => b.isType);
const list = bindings
.map((b) => (allType || !b.isType ? b.text : `type ${b.text}`))
.join(', ');
- return `import ${allType ? 'type ' : ''}{ ${list} } from '${specifier}';`;
+ return `${keyword} ${allType ? 'type ' : ''}{ ${list} } from '${specifier}';`;
}
let changedFiles = 0;
@@ -116,7 +136,7 @@ for (const file of process.argv.slice(2)) {
const source = readFileSync(file, 'utf8');
const next = source.replace(
IMPORT_STATEMENT,
- (statement, typeKeyword, clause, from) => {
+ (statement, keyword, typeKeyword, clause, from) => {
const byTarget = new Map<string, Binding[]>();
for (const binding of parseBindings(clause, Boolean(typeKeyword))) {
const row = rows.get(`${from}\t${binding.symbol}`);
@@ -129,7 +149,7 @@ for (const file of process.argv.slice(2)) {
byTarget.set(specifier, [...(byTarget.get(specifier) ?? []), binding]);
}
return [...byTarget.entries()]
- .map(([specifier, bindings]) => render(bindings, specifier))
+ .map(([specifier, bindings]) => render(keyword, bindings, specifier))
.join('\n');
}
);
diff --git a/tooling/codemods/p11-map.json b/tooling/codemods/p11-map.json
index e446bf3d2..30e6a314e 100644
--- a/tooling/codemods/p11-map.json
+++ b/tooling/codemods/p11-map.json
@@ -371,7 +371,7 @@
{"from":"@openpanel/common","symbol":"parseSearchParams","kind":"value","to":"packages/core/src/shared/url.ts","keepTypeKeyword":false},
{"from":"@openpanel/common","symbol":"parsePath","kind":"value","to":"packages/core/src/shared/url.ts","keepTypeKeyword":false},
{"from":"@openpanel/common","symbol":"isSameDomain","kind":"value","to":"packages/core/src/shared/url.ts","keepTypeKeyword":false},
-{"from":"@openpanel/json","symbol":"getSafeJson","kind":"value","to":"packages/core/src/shared/json.ts","keepTypeKeyword":false,"toByConsumer":{"packages/db":"@openpanel/core"}},
+{"from":"@openpanel/json","symbol":"getSafeJson","kind":"value","to":"packages/core/src/shared/json.ts","keepTypeKeyword":false},
{"from":"@openpanel/json","symbol":"getSuperJson","kind":"value","to":"packages/core/src/shared/json.ts","keepTypeKeyword":false,"toByConsumer":{"apps/start":"apps/start/src/utils/super-json.ts","packages/redis":"packages/redis/json.ts"}},
{"from":"@openpanel/json","symbol":"setSuperJson","kind":"value","to":"packages/core/src/shared/json.ts","keepTypeKeyword":false,"toByConsumer":{"packages/redis":"packages/redis/json.ts"}}
]