This commit is contained in:
Carl-Gerhard Lindesvärd
2026-01-10 21:55:24 +01:00
parent ba79ac570c
commit 347a01a941
35 changed files with 1544 additions and 1404 deletions

View File

@@ -0,0 +1,95 @@
import type { IServiceReport } from '@openpanel/db';
import { useMemo } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
const ResponsiveGridLayout = WidthProvider(Responsive);
export type Layout = ReactGridLayout.Layout;
export const useReportLayouts = (
reports: NonNullable<IServiceReport>[],
): ReactGridLayout.Layouts => {
return useMemo(() => {
const baseLayout = reports.map((report, index) => ({
i: report.id,
x: report.layout?.x ?? (index % 2) * 6,
y: report.layout?.y ?? Math.floor(index / 2) * 4,
w: report.layout?.w ?? 6,
h: report.layout?.h ?? 4,
minW: 3,
minH: 3,
}));
return {
lg: baseLayout,
md: baseLayout,
sm: baseLayout.map((item) => ({ ...item, w: Math.min(item.w, 6) })),
xs: baseLayout.map((item) => ({ ...item, w: 4, x: 0 })),
xxs: baseLayout.map((item) => ({ ...item, w: 2, x: 0 })),
};
}, [reports]);
};
export function GrafanaGrid({
layouts,
children,
transitions,
onLayoutChange,
onDragStop,
onResizeStop,
isDraggable,
isResizable,
}: {
children: React.ReactNode;
transitions?: boolean;
} & Pick<
ReactGridLayout.ResponsiveProps,
| 'layouts'
| 'onLayoutChange'
| 'onDragStop'
| 'onResizeStop'
| 'isDraggable'
| 'isResizable'
>) {
return (
<>
<style>{`
.react-grid-item {
transition: ${transitions ? 'transform 200ms ease, width 200ms ease, height 200ms ease' : 'none'} !important;
}
.react-grid-item.react-grid-placeholder {
background: none !important;
opacity: 0.5;
transition-duration: 100ms;
border-radius: 0.5rem;
border: 1px dashed var(--primary);
}
.react-grid-item.resizing {
transition: none !important;
}
`}</style>
<div className="-m-4">
<ResponsiveGridLayout
className="layout"
layouts={layouts}
breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
rowHeight={100}
draggableHandle=".drag-handle"
compactType="vertical"
preventCollision={false}
margin={[16, 16]}
transformScale={1}
useCSSTransforms={true}
onLayoutChange={onLayoutChange}
onDragStop={onDragStop}
onResizeStop={onResizeStop}
isDraggable={isDraggable}
isResizable={isResizable}
>
{children}
</ResponsiveGridLayout>
</div>
</>
);
}

View File

@@ -33,7 +33,7 @@ export function LoginNavbar({ className }: { className?: string }) {
</a>
</li>
<li>
<a href="https://openpanel.dev/compare/mixpanel-alternative">
<a href="https://openpanel.dev/compare/posthog-alternative">
Posthog alternative
</a>
</li>

View File

@@ -211,7 +211,6 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
</WidgetHead>
<WidgetBody>
<ReportChart
options={{ hideID: true }}
report={{
projectId,
startDate,
@@ -232,9 +231,7 @@ export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) {
},
],
chartType: 'map',
lineType: 'monotone',
interval: interval,
name: 'Top sources',
range: range,
previous: previous,
metric: 'sum',

View File

@@ -10,33 +10,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportAreaChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.chartByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.chart.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.chart.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -10,33 +10,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportBarChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.aggregateByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.aggregate.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.aggregate.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -42,10 +42,10 @@ export function PreviousDiffIndicator({
className,
}: PreviousDiffIndicatorProps) {
const {
report: { previousIndicatorInverted, previous },
report: { previous },
} = useReportChartContext();
const variant = getDiffIndicator(
inverted ?? previousIndicatorInverted,
inverted,
state,
'bg-emerald-300',
'bg-rose-300',

View File

@@ -11,7 +11,6 @@ import type {
export type ReportChartContextType = {
options: Partial<{
columns: React.ReactNode[];
hideID: boolean;
hideLegend: boolean;
hideXAxis: boolean;
hideYAxis: boolean;
@@ -28,11 +27,11 @@ export type ReportChartContextType = {
onClick: () => void;
}[];
}>;
report: IChartProps & { id?: string };
report: IChartInput & { id?: string };
isLazyLoading: boolean;
isEditMode: boolean;
shareId?: string;
shareType?: 'dashboard' | 'report';
reportId?: string;
};
type ReportChartContextProviderProps = ReportChartContextType & {
@@ -42,8 +41,6 @@ type ReportChartContextProviderProps = ReportChartContextType & {
export type ReportChartProps = Partial<ReportChartContextType> & {
report: IChartInput;
lazy?: boolean;
shareId?: string;
shareType?: 'dashboard' | 'report';
};
const context = createContext<ReportChartContextType | null>(null);
@@ -58,20 +55,6 @@ export const useReportChartContext = () => {
return ctx;
};
export const useSelectReportChartContext = <T,>(
selector: (ctx: ReportChartContextType) => T,
) => {
const ctx = useReportChartContext();
const [state, setState] = useState(selector(ctx));
useEffect(() => {
const newState = selector(ctx);
if (!isEqual(newState, state)) {
setState(newState);
}
}, [ctx]);
return state;
};
export const ReportChartProvider = ({
children,
...propsToContext

View File

@@ -12,33 +12,27 @@ import { Chart } from './chart';
import { Summary } from './summary';
export function ReportConversionChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
console.log(report.limit);
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.conversionByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.conversion.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.conversion.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -25,50 +25,35 @@ export function ReportFunnelChart() {
endDate,
previous,
breakdowns,
interval,
},
isLazyLoading,
shareId,
shareType,
} = useReportChartContext();
const { range: overviewRange, startDate: overviewStartDate, endDate: overviewEndDate, interval: overviewInterval } = useOverviewOptions();
const trpc = useTRPC();
const input: IChartInput = {
series,
range: overviewRange ?? range,
projectId,
interval: overviewInterval ?? interval ?? 'day',
chartType: 'funnel',
breakdowns,
funnelWindow,
funnelGroup,
previous,
metric: 'sum',
startDate: overviewStartDate ?? startDate,
endDate: overviewEndDate ?? endDate,
limit: 20,
shareId,
reportId: id,
};
const res = useQuery(
shareId && shareType && id
? trpc.chart.funnelByReport.queryOptions(
{
reportId: id,
shareId,
shareType,
range: overviewRange ?? undefined,
startDate: overviewStartDate ?? undefined,
endDate: overviewEndDate ?? undefined,
interval: overviewInterval ?? undefined,
},
{
enabled: !isLazyLoading && series.length > 0,
},
)
: (() => {
const input: IChartInput = {
series,
range,
projectId,
interval: 'day',
chartType: 'funnel',
breakdowns,
funnelWindow,
funnelGroup,
previous,
metric: 'sum',
startDate,
endDate,
limit: 20,
};
return trpc.chart.funnel.queryOptions(input, {
enabled: !isLazyLoading && input.series.length > 0,
});
})(),
trpc.chart.funnel.queryOptions(input, {
enabled: !isLazyLoading && input.series.length > 0,
}),
);
if (isLazyLoading || res.isLoading) {

View File

@@ -10,33 +10,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportHistogramChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.chartByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.chart.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.chart.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -11,33 +11,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportLineChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.chartByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.chart.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.chart.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -10,33 +10,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportMapChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.chartByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.chart.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.chart.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -9,33 +9,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportMetricChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.chartByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.chart.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.chart.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -54,10 +54,7 @@ export function MetricCard({
metric,
unit,
}: MetricCardProps) {
const {
report: { previousIndicatorInverted },
isEditMode,
} = useReportChartContext();
const { isEditMode } = useReportChartContext();
const number = useNumber();
const renderValue = (value: number | undefined, unitClassName?: string) => {
@@ -80,7 +77,7 @@ export function MetricCard({
const previous = serie.metrics.previous?.[metric];
const graphColors = getDiffIndicator(
previousIndicatorInverted,
false,
previous?.state,
'#6ee7b7', // green
'#fda4af', // red

View File

@@ -10,33 +10,27 @@ import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportPieChart() {
const { isLazyLoading, report, shareId, shareType } = useReportChartContext();
const { isLazyLoading, report, shareId } = useReportChartContext();
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const res = useQuery(
shareId && shareType && 'id' in report && report.id
? trpc.chart.aggregateByReport.queryOptions(
{
reportId: report.id,
shareId,
shareType,
range: range ?? undefined,
startDate: startDate ?? undefined,
endDate: endDate ?? undefined,
interval: interval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
)
: trpc.chart.aggregate.queryOptions(report, {
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
}),
trpc.chart.aggregate.queryOptions(
{
...report,
shareId,
reportId: 'id' in report ? report.id : undefined,
range: range ?? report.range,
startDate: startDate ?? report.startDate,
endDate: endDate ?? report.endDate,
interval: interval ?? report.interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: !isLazyLoading,
},
),
);
if (

View File

@@ -24,7 +24,6 @@ export function ReportRetentionChart() {
},
isLazyLoading,
shareId,
shareType,
} = useReportChartContext();
const { range: overviewRange, startDate: overviewStartDate, endDate: overviewEndDate, interval: overviewInterval } = useOverviewOptions();
const eventSeries = series.filter((item) => item.type === 'event');
@@ -34,40 +33,25 @@ export function ReportRetentionChart() {
firstEvent.length > 0 && secondEvent.length > 0 && !isLazyLoading;
const trpc = useTRPC();
const res = useQuery(
shareId && shareType && id
? trpc.chart.cohortByReport.queryOptions(
{
reportId: id,
shareId,
shareType,
range: overviewRange ?? undefined,
startDate: overviewStartDate ?? undefined,
endDate: overviewEndDate ?? undefined,
interval: overviewInterval ?? undefined,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: isEnabled,
},
)
: trpc.chart.cohort.queryOptions(
{
firstEvent,
secondEvent,
projectId,
range,
startDate,
endDate,
criteria,
interval,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: isEnabled,
},
),
trpc.chart.cohort.queryOptions(
{
firstEvent,
secondEvent,
projectId,
range: overviewRange ?? range,
startDate: overviewStartDate ?? startDate,
endDate: overviewEndDate ?? endDate,
criteria,
interval: overviewInterval ?? interval,
shareId,
reportId: id,
},
{
placeholderData: keepPreviousData,
staleTime: 1000 * 60 * 1,
enabled: isEnabled,
},
),
);
if (!isEnabled) {

View File

@@ -0,0 +1,258 @@
import { ReportChart } from '@/components/report-chart';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
import { CopyIcon, MoreHorizontal, Trash } from 'lucide-react';
import { timeWindows } from '@openpanel/constants';
import { useRouter } from '@tanstack/react-router';
export function ReportItemSkeleton() {
return (
<div className="card h-full flex flex-col animate-pulse">
<div className="flex items-center justify-between border-b border-border p-4">
<div className="flex-1">
<div className="h-5 w-32 bg-muted rounded mb-2" />
<div className="h-4 w-24 bg-muted/50 rounded" />
</div>
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-muted rounded" />
<div className="w-8 h-8 bg-muted rounded" />
</div>
</div>
<div className="p-4 flex-1 flex items-center justify-center aspect-video" />
</div>
);
}
export function ReportItem({
report,
organizationId,
projectId,
range,
startDate,
endDate,
interval,
onDelete,
onDuplicate,
}: {
report: any;
organizationId: string;
projectId: string;
range: any;
startDate: any;
endDate: any;
interval: any;
onDelete: (reportId: string) => void;
onDuplicate: (reportId: string) => void;
}) {
const router = useRouter();
const chartRange = report.range;
return (
<div className="card h-full flex flex-col">
<div className="flex items-center hover:bg-muted/50 justify-between border-b border-border p-4 leading-none [&_svg]:hover:opacity-100">
<div
className="flex-1 cursor-pointer -m-4 p-4"
onClick={(event) => {
if (event.metaKey) {
window.open(
`/${organizationId}/${projectId}/reports/${report.id}`,
'_blank',
);
return;
}
router.navigate({
to: '/$organizationId/$projectId/reports/$reportId',
params: {
organizationId,
projectId,
reportId: report.id,
},
});
}}
onKeyUp={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
router.navigate({
to: '/$organizationId/$projectId/reports/$reportId',
params: {
organizationId,
projectId,
reportId: report.id,
},
});
}
}}
role="button"
tabIndex={0}
>
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
<div className="mt-2 flex gap-2 ">
<span
className={
(chartRange !== range && range !== null) ||
(startDate && endDate)
? 'line-through'
: ''
}
>
{timeWindows[chartRange as keyof typeof timeWindows]?.label}
</span>
{startDate && endDate ? (
<span>Custom dates</span>
) : (
range !== null &&
chartRange !== range && (
<span>
{timeWindows[range as keyof typeof timeWindows]?.label}
</span>
)
)}
</div>
)}
</div>
<div className="flex items-center gap-2">
<div className="drag-handle cursor-move p-2 hover:bg-muted rounded">
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="currentColor"
className="opacity-30 hover:opacity-100"
>
<circle cx="4" cy="4" r="1.5" />
<circle cx="4" cy="8" r="1.5" />
<circle cx="4" cy="12" r="1.5" />
<circle cx="12" cy="4" r="1.5" />
<circle cx="12" cy="8" r="1.5" />
<circle cx="12" cy="12" r="1.5" />
</svg>
</div>
<DropdownMenu>
<DropdownMenuTrigger className="flex h-8 w-8 items-center justify-center rounded hover:border">
<MoreHorizontal size={16} />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuItem
onClick={(event) => {
event.stopPropagation();
onDuplicate(report.id);
}}
>
<CopyIcon size={16} className="mr-2" />
Duplicate
</DropdownMenuItem>
<DropdownMenuGroup>
<DropdownMenuItem
className="text-destructive"
onClick={(event) => {
event.stopPropagation();
onDelete(report.id);
}}
>
<Trash size={16} className="mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div
className={cn(
'p-4 overflow-auto flex-1',
report.chartType === 'metric' && 'p-0',
)}
>
<ReportChart
report={
{
...report,
range: range ?? report.range,
startDate: startDate ?? null,
endDate: endDate ?? null,
interval: interval ?? report.interval,
} as any
}
/>
</div>
</div>
);
}
export function ReportItemReadOnly({
report,
shareId,
range,
startDate,
endDate,
interval,
}: {
report: any;
shareId: string;
range: any;
startDate: any;
endDate: any;
interval: any;
}) {
const chartRange = report.range;
return (
<div className="card h-full flex flex-col">
<div className="flex items-center justify-between border-b border-border p-4 leading-none">
<div className="flex-1">
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
<div className="mt-2 flex gap-2 ">
<span
className={
(chartRange !== range && range !== null) ||
(startDate && endDate)
? 'line-through'
: ''
}
>
{timeWindows[chartRange as keyof typeof timeWindows]?.label}
</span>
{startDate && endDate ? (
<span>Custom dates</span>
) : (
range !== null &&
chartRange !== range && (
<span>
{timeWindows[range as keyof typeof timeWindows]?.label}
</span>
)
)}
</div>
)}
</div>
</div>
<div
className={cn(
'p-4 overflow-auto flex-1',
report.chartType === 'metric' && 'p-0',
)}
>
<ReportChart
type="inputs"
report={{
...report,
range: range ?? report.range,
startDate: startDate ?? null,
endDate: endDate ?? null,
interval: interval ?? report.interval,
}}
shareId={shareId}
/>
</div>
</div>
);
}

View File

@@ -67,7 +67,7 @@ export function ReportSettings() {
return (
<div>
<h3 className="mb-2 font-medium">Settings</h3>
<div className="col rounded-lg border bg-card p-4 gap-2">
<div className="col rounded-lg border bg-card p-4 gap-4">
{fields.includes('previous') && (
<Label className="flex items-center justify-between mb-0">
<span className="whitespace-nowrap">
@@ -81,7 +81,9 @@ export function ReportSettings() {
)}
{fields.includes('criteria') && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Criteria</span>
<Label className="whitespace-nowrap font-medium mb-0">
Criteria
</Label>
<Combobox
align="end"
placeholder="Select criteria"
@@ -102,7 +104,7 @@ export function ReportSettings() {
)}
{fields.includes('unit') && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Unit</span>
<Label className="whitespace-nowrap font-medium mb-0">Unit</Label>
<Combobox
align="end"
placeholder="Unit"
@@ -125,7 +127,9 @@ export function ReportSettings() {
)}
{fields.includes('funnelGroup') && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Funnel Group</span>
<Label className="whitespace-nowrap font-medium mb-0">
Funnel Group
</Label>
<Combobox
align="end"
placeholder="Default: Session"
@@ -150,7 +154,9 @@ export function ReportSettings() {
)}
{fields.includes('funnelWindow') && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Funnel Window</span>
<Label className="whitespace-nowrap font-medium mb-0">
Funnel Window
</Label>
<InputEnter
type="number"
value={funnelWindow ? String(funnelWindow) : ''}
@@ -168,7 +174,7 @@ export function ReportSettings() {
)}
{fields.includes('sankeyMode') && options?.type === 'sankey' && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Mode</span>
<Label className="whitespace-nowrap font-medium mb-0">Mode</Label>
<Combobox
align="end"
placeholder="Select mode"
@@ -197,7 +203,7 @@ export function ReportSettings() {
)}
{fields.includes('sankeySteps') && options?.type === 'sankey' && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Steps</span>
<Label className="whitespace-nowrap font-medium mb-0">Steps</Label>
<InputEnter
type="number"
value={options?.steps ? String(options.steps) : '5'}
@@ -214,10 +220,10 @@ export function ReportSettings() {
</div>
)}
{fields.includes('sankeyExclude') && options?.type === 'sankey' && (
<div className="flex flex-col gap-2">
<span className="whitespace-nowrap font-medium">
<div className="flex flex-col">
<Label className="whitespace-nowrap font-medium">
Exclude Events
</span>
</Label>
<ComboboxEvents
multiple
searchable
@@ -231,10 +237,10 @@ export function ReportSettings() {
</div>
)}
{fields.includes('sankeyInclude') && options?.type === 'sankey' && (
<div className="flex flex-col gap-2">
<span className="whitespace-nowrap font-medium">
<div className="flex flex-col">
<Label className="whitespace-nowrap font-medium">
Include events
</span>
</Label>
<ComboboxEvents
multiple
searchable

View File

@@ -5,7 +5,7 @@ import type { VariantProps } from 'class-variance-authority';
import * as React from 'react';
const labelVariants = cva(
'mb-3 text-sm block font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
'mb-3 text-sm block font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-foreground/70',
);
const Label = React.forwardRef<

View File

@@ -25,12 +25,40 @@ export function createTRPCClientWithHeaders(apiUrl: string) {
transformer: superjson,
url: `${apiUrl}/trpc`,
headers: () => getIsomorphicHeaders(),
fetch: (url, options) => {
return fetch(url, {
...options,
mode: 'cors',
credentials: 'include',
});
fetch: async (url, options) => {
try {
console.log('fetching', url, options);
const response = await fetch(url, {
...options,
mode: 'cors',
credentials: 'include',
});
// Log HTTP errors on server
if (!response.ok && typeof window === 'undefined') {
const text = await response.clone().text();
console.error('[tRPC SSR Error]', {
url: url.toString(),
status: response.status,
statusText: response.statusText,
body: text,
options,
});
}
return response;
} catch (error) {
// Log fetch errors on server
if (typeof window === 'undefined') {
console.error('[tRPC SSR Error]', {
url: url.toString(),
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
options,
});
}
throw error;
}
},
}),
],

View File

@@ -11,8 +11,11 @@ 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, useQueryClient } from '@tanstack/react-query';
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';
@@ -27,20 +30,37 @@ export default function ShareDashboardModal({
}) {
const { projectId, organizationId } = useAppParams();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const { register, handleSubmit } = useForm<IForm>({
const trpc = useTRPC();
const queryClient = useQueryClient();
// Fetch current share status
const shareQuery = useQuery(
trpc.share.dashboard.queryOptions({
dashboardId,
}),
);
const existingShare = shareQuery.data;
const isShared = existingShare?.public ?? false;
const shareUrl = existingShare?.id
? `${window.location.origin}/share/dashboard/${existingShare.id}`
: '';
const { register, handleSubmit, watch } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
public: true,
password: '',
password: existingShare?.password ? '••••••••' : '',
projectId,
organizationId,
dashboardId,
},
});
const trpc = useTRPC();
const queryClient = useQueryClient();
const password = watch('password');
const mutation = useMutation(
trpc.share.createDashboard.mutationOptions({
onError: handleError,
@@ -50,48 +70,123 @@ export default function ShareDashboardModal({
description: `Your dashboard is now ${
res.public ? 'public' : 'private'
}`,
action: {
label: 'View',
onClick: () =>
navigate({
to: '/share/dashboard/$shareId',
params: {
shareId: res.id,
},
}),
},
action: res.public
? {
label: 'View',
onClick: () =>
navigate({
to: '/share/dashboard/$shareId',
params: {
shareId: res.id,
},
}),
}
: undefined,
});
popModal();
},
}),
);
const handleCopyLink = () => {
navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
toast('Link copied to clipboard');
};
const handleMakePrivate = () => {
mutation.mutate({
public: false,
password: null,
projectId,
organizationId,
dashboardId,
});
};
return (
<ModalContent className="max-w-md">
<ModalHeader
title="Dashboard public availability"
text="You can choose if you want to add a password to make it a bit more private."
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.'
}
/>
{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">
<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" />
<Tooltiper content="Copy link">
<Button
type="button"
variant="outline"
size="sm"
onClick={handleCopyLink}
>
{copied ? (
<CheckCircle2 className="size-4" />
) : (
<Copy className="size-4" />
)}
</Button>
</Tooltiper>
<Tooltiper content="Open in new tab">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="size-4" />
</Button>
</Tooltiper>
<Tooltiper content="Make private">
<Button
type="button"
variant="destructive"
onClick={handleMakePrivate}
>
<TrashIcon className="size-4" />
</Button>
</Tooltiper>
</div>
</div>
)}
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
mutation.mutate({
...values,
// Only send password if it's not the placeholder
password:
values.password === '••••••••' ? null : values.password || null,
});
})}
>
<Input
{...register('password')}
placeholder="Enter your password"
placeholder="Enter your password (optional)"
size="large"
type={password === '••••••••' ? 'text' : 'password'}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" loading={mutation.isPending}>
Make it public
<Button type="submit">
{isShared ? 'Update' : 'Make it public'}
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -11,8 +11,11 @@ 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, useQueryClient } from '@tanstack/react-query';
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';
@@ -23,19 +26,36 @@ type IForm = z.infer<typeof validator>;
export default function ShareOverviewModal() {
const { projectId, organizationId } = useAppParams();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const { register, handleSubmit } = useForm<IForm>({
const trpc = useTRPC();
const queryClient = useQueryClient();
// Fetch current share status
const shareQuery = useQuery(
trpc.share.overview.queryOptions({
projectId,
}),
);
const existingShare = shareQuery.data;
const isShared = existingShare?.public ?? false;
const shareUrl = existingShare?.id
? `${window.location.origin}/share/overview/${existingShare.id}`
: '';
const { register, handleSubmit, watch } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
public: true,
password: '',
password: existingShare?.password ? '••••••••' : '',
projectId,
organizationId,
},
});
const trpc = useTRPC();
const queryClient = useQueryClient();
const password = watch('password');
const mutation = useMutation(
trpc.share.createOverview.mutationOptions({
onError: handleError,
@@ -45,47 +65,122 @@ export default function ShareOverviewModal() {
description: `Your overview is now ${
res.public ? 'public' : 'private'
}`,
action: {
label: 'View',
onClick: () =>
navigate({
to: '/share/overview/$shareId',
params: {
shareId: res.id,
},
}),
},
action: res.public
? {
label: 'View',
onClick: () =>
navigate({
to: '/share/overview/$shareId',
params: {
shareId: res.id,
},
}),
}
: undefined,
});
popModal();
},
}),
);
const handleCopyLink = () => {
navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
toast('Link copied to clipboard');
};
const handleMakePrivate = () => {
mutation.mutate({
public: false,
password: null,
projectId,
organizationId,
});
};
return (
<ModalContent className="max-w-md">
<ModalHeader
title="Dashboard public availability"
text="You can choose if you want to add a password to make it a bit more private."
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.'
}
/>
{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">
<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" />
<Tooltiper content="Copy link">
<Button
type="button"
variant="outline"
size="sm"
onClick={handleCopyLink}
>
{copied ? (
<CheckCircle2 className="size-4" />
) : (
<Copy className="size-4" />
)}
</Button>
</Tooltiper>
<Tooltiper content="Open in new tab">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="size-4" />
</Button>
</Tooltiper>
<Tooltiper content="Make private">
<Button
type="button"
variant="destructive"
onClick={handleMakePrivate}
>
<TrashIcon className="size-4" />
</Button>
</Tooltiper>
</div>
</div>
)}
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
mutation.mutate({
...values,
// Only send password if it's not the placeholder
password:
values.password === '••••••••' ? null : values.password || null,
});
})}
>
<Input
{...register('password')}
placeholder="Enter your password"
placeholder="Enter your password (optional)"
size="large"
type={password === '••••••••' ? 'text' : 'password'}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" loading={mutation.isPending}>
Make it public
<Button type="submit">
{isShared ? 'Update' : 'Make it public'}
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}
}

View File

@@ -11,8 +11,11 @@ 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, useQueryClient } from '@tanstack/react-query';
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';
@@ -23,20 +26,37 @@ type IForm = z.infer<typeof validator>;
export default function ShareReportModal({ reportId }: { reportId: string }) {
const { projectId, organizationId } = useAppParams();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const { register, handleSubmit } = useForm<IForm>({
const trpc = useTRPC();
const queryClient = useQueryClient();
// Fetch current share status
const shareQuery = useQuery(
trpc.share.report.queryOptions({
reportId,
}),
);
const existingShare = shareQuery.data;
const isShared = existingShare?.public ?? false;
const shareUrl = existingShare?.id
? `${window.location.origin}/share/report/${existingShare.id}`
: '';
const { register, handleSubmit, watch } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
public: true,
password: '',
password: existingShare?.password ? '••••••••' : '',
projectId,
organizationId,
reportId,
},
});
const trpc = useTRPC();
const queryClient = useQueryClient();
const password = watch('password');
const mutation = useMutation(
trpc.share.createReport.mutationOptions({
onError: handleError,
@@ -44,48 +64,123 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
queryClient.invalidateQueries(trpc.share.report.pathFilter());
toast('Success', {
description: `Your report is now ${res.public ? 'public' : 'private'}`,
action: {
label: 'View',
onClick: () =>
navigate({
to: '/share/report/$shareId',
params: {
shareId: res.id,
},
}),
},
action: res.public
? {
label: 'View',
onClick: () =>
navigate({
to: '/share/report/$shareId',
params: {
shareId: res.id,
},
}),
}
: undefined,
});
popModal();
},
}),
);
const handleCopyLink = () => {
navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
toast('Link copied to clipboard');
};
const handleMakePrivate = () => {
mutation.mutate({
public: false,
password: null,
projectId,
organizationId,
reportId,
});
};
return (
<ModalContent className="max-w-md">
<ModalHeader
title="Report public availability"
text="You can choose if you want to add a password to make it a bit more private."
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.'
}
/>
{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">
<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" />
<Tooltiper content="Copy link">
<Button
type="button"
variant="outline"
size="sm"
onClick={handleCopyLink}
>
{copied ? (
<CheckCircle2 className="size-4" />
) : (
<Copy className="size-4" />
)}
</Button>
</Tooltiper>
<Tooltiper content="Open in new tab">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="size-4" />
</Button>
</Tooltiper>
<Tooltiper content="Make private">
<Button
type="button"
variant="destructive"
onClick={handleMakePrivate}
>
<TrashIcon className="size-4" />
</Button>
</Tooltiper>
</div>
</div>
)}
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
mutation.mutate({
...values,
// Only send password if it's not the placeholder
password:
values.password === '••••••••' ? null : values.password || null,
});
})}
>
<Input
{...register('password')}
placeholder="Enter your password"
placeholder="Enter your password (optional)"
size="large"
type={password === '••••••••' ? 'text' : 'password'}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" loading={mutation.isPending}>
Make it public
<Button type="submit">
{isShared ? 'Update' : 'Make it public'}
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}
}

View File

@@ -2,7 +2,6 @@ import {
HeadContent,
Scripts,
createRootRouteWithContext,
useRouteContext,
} from '@tanstack/react-router';
import 'flag-icons/css/flag-icons.min.css';

View File

@@ -1,6 +1,5 @@
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { ReportChart } from '@/components/report-chart';
import { Button, LinkButton } from '@/components/ui/button';
import {
DropdownMenu,
@@ -9,49 +8,36 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
import { createProjectTitle } from '@/utils/title';
import {
CopyIcon,
LayoutPanelTopIcon,
MoreHorizontal,
PlusIcon,
RotateCcw,
ShareIcon,
Trash,
TrashIcon,
} from 'lucide-react';
import { toast } from 'sonner';
import { timeWindows } from '@openpanel/constants';
import FullPageLoadingState from '@/components/full-page-loading-state';
import {
GrafanaGrid,
type Layout,
useReportLayouts,
} from '@/components/grafana-grid';
import { OverviewInterval } from '@/components/overview/overview-interval';
import { OverviewRange } from '@/components/overview/overview-range';
import { PageContainer } from '@/components/page-container';
import { PageHeader } from '@/components/page-header';
import {
ReportItem,
ReportItemSkeleton,
} from '@/components/report/report-item';
import { handleErrorToastOptions, useTRPC } from '@/integrations/trpc/react';
import { pushModal, showConfirm } from '@/modals';
import { useMutation, useQuery } from '@tanstack/react-query';
import { createFileRoute, useRouter } from '@tanstack/react-router';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
const ResponsiveGridLayout = WidthProvider(Responsive);
type Layout = {
i: string;
x: number;
y: number;
w: number;
h: number;
minW?: number;
minH?: number;
maxW?: number;
maxH?: number;
};
import { useCallback, useEffect, useState } from 'react';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/dashboards_/$dashboardId',
@@ -95,180 +81,6 @@ export const Route = createFileRoute(
pendingComponent: FullPageLoadingState,
});
// Report Skeleton Component
function ReportSkeleton() {
return (
<div className="card h-full flex flex-col animate-pulse">
<div className="flex items-center justify-between border-b border-border p-4">
<div className="flex-1">
<div className="h-5 w-32 bg-muted rounded mb-2" />
<div className="h-4 w-24 bg-muted/50 rounded" />
</div>
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-muted rounded" />
<div className="w-8 h-8 bg-muted rounded" />
</div>
</div>
<div className="p-4 flex-1 flex items-center justify-center aspect-video" />
</div>
);
}
// Report Item Component
function ReportItem({
report,
organizationId,
projectId,
range,
startDate,
endDate,
interval,
onDelete,
onDuplicate,
}: {
report: any;
organizationId: string;
projectId: string;
range: any;
startDate: any;
endDate: any;
interval: any;
onDelete: (reportId: string) => void;
onDuplicate: (reportId: string) => void;
}) {
const router = useRouter();
const chartRange = report.range;
return (
<div className="card h-full flex flex-col">
<div className="flex items-center hover:bg-muted/50 justify-between border-b border-border p-4 leading-none [&_svg]:hover:opacity-100">
<div
className="flex-1 cursor-pointer -m-4 p-4"
onClick={(event) => {
if (event.metaKey) {
window.open(
`/${organizationId}/${projectId}/reports/${report.id}`,
'_blank',
);
return;
}
router.navigate({
from: Route.fullPath,
to: '/$organizationId/$projectId/reports/$reportId',
params: {
reportId: report.id,
},
});
}}
onKeyUp={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
router.navigate({
from: Route.fullPath,
to: '/$organizationId/$projectId/reports/$reportId',
params: {
reportId: report.id,
},
});
}
}}
role="button"
tabIndex={0}
>
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
<div className="mt-2 flex gap-2 ">
<span
className={
(chartRange !== range && range !== null) ||
(startDate && endDate)
? 'line-through'
: ''
}
>
{timeWindows[chartRange as keyof typeof timeWindows]?.label}
</span>
{startDate && endDate ? (
<span>Custom dates</span>
) : (
range !== null &&
chartRange !== range && (
<span>
{timeWindows[range as keyof typeof timeWindows]?.label}
</span>
)
)}
</div>
)}
</div>
<div className="flex items-center gap-2">
<div className="drag-handle cursor-move p-2 hover:bg-muted rounded">
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="currentColor"
className="opacity-30 hover:opacity-100"
>
<circle cx="4" cy="4" r="1.5" />
<circle cx="4" cy="8" r="1.5" />
<circle cx="4" cy="12" r="1.5" />
<circle cx="12" cy="4" r="1.5" />
<circle cx="12" cy="8" r="1.5" />
<circle cx="12" cy="12" r="1.5" />
</svg>
</div>
<DropdownMenu>
<DropdownMenuTrigger className="flex h-8 w-8 items-center justify-center rounded hover:border">
<MoreHorizontal size={16} />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuItem
onClick={(event) => {
event.stopPropagation();
onDuplicate(report.id);
}}
>
<CopyIcon size={16} className="mr-2" />
Duplicate
</DropdownMenuItem>
<DropdownMenuGroup>
<DropdownMenuItem
className="text-destructive"
onClick={(event) => {
event.stopPropagation();
onDelete(report.id);
}}
>
<Trash size={16} className="mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div
className={cn(
'p-4 overflow-auto flex-1',
report.chartType === 'metric' && 'p-0',
)}
>
<ReportChart
report={
{
...report,
range: range ?? report.range,
startDate: startDate ?? null,
endDate: endDate ?? null,
interval: interval ?? report.interval,
} as any
}
/>
</div>
</div>
);
}
function Component() {
const router = useRouter();
const { organizationId, dashboardId, projectId } = Route.useParams();
@@ -364,26 +176,7 @@ function Component() {
);
// Convert reports to grid layout format for all breakpoints
const layouts = useMemo(() => {
const baseLayout = reports.map((report, index) => ({
i: report.id,
x: report.layout?.x ?? (index % 2) * 6,
y: report.layout?.y ?? Math.floor(index / 2) * 4,
w: report.layout?.w ?? 6,
h: report.layout?.h ?? 4,
minW: 3,
minH: 3,
}));
// Create responsive layouts for different breakpoints
return {
lg: baseLayout,
md: baseLayout,
sm: baseLayout.map((item) => ({ ...item, w: Math.min(item.w, 6) })),
xs: baseLayout.map((item) => ({ ...item, w: 4, x: 0 })),
xxs: baseLayout.map((item) => ({ ...item, w: 2, x: 0 })),
};
}, [reports]);
const layouts = useReportLayouts(reports);
const handleLayoutChange = useCallback((newLayout: Layout[]) => {
// This is called during dragging/resizing, we'll save on drag/resize stop
@@ -464,7 +257,7 @@ function Component() {
<PageHeader
title={dashboard.name}
description="View and manage your reports"
className="mb-0"
className="mb-4"
actions={
<>
<OverviewRange />
@@ -486,7 +279,9 @@ function Component() {
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuGroup>
<DropdownMenuItem
onClick={() => pushModal('ShareDashboardModal', { dashboardId })}
onClick={() =>
pushModal('ShareDashboardModal', { dashboardId })
}
>
<ShareIcon className="mr-2 size-4" />
Share dashboard
@@ -539,69 +334,43 @@ function Component() {
</FullPageEmptyState>
) : !isGridReady || reportsQuery.isLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<ReportSkeleton />
<ReportSkeleton />
<ReportSkeleton />
<ReportSkeleton />
<ReportSkeleton />
<ReportSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
</div>
) : (
<div className="w-full overflow-hidden -mx-4">
<style>{`
.react-grid-item {
transition: ${enableTransitions ? 'transform 200ms ease, width 200ms ease, height 200ms ease' : 'none'} !important;
}
.react-grid-item.react-grid-placeholder {
background: none !important;
opacity: 0.5;
transition-duration: 100ms;
border-radius: 0.5rem;
border: 1px dashed var(--primary);
}
.react-grid-item.resizing {
transition: none !important;
}
`}</style>
<ResponsiveGridLayout
className="layout"
layouts={layouts}
breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
rowHeight={100}
onLayoutChange={handleLayoutChange}
onDragStop={handleDragStop}
onResizeStop={handleResizeStop}
draggableHandle=".drag-handle"
compactType="vertical"
preventCollision={false}
isDraggable={true}
isResizable={true}
margin={[16, 16]}
transformScale={1}
useCSSTransforms={true}
>
{reports.map((report) => (
<div key={report.id}>
<ReportItem
report={report}
organizationId={organizationId}
projectId={projectId}
range={range}
startDate={startDate}
endDate={endDate}
interval={interval}
onDelete={(reportId) => {
reportDeletion.mutate({ reportId });
}}
onDuplicate={(reportId) => {
reportDuplicate.mutate({ reportId });
}}
/>
</div>
))}
</ResponsiveGridLayout>
</div>
<GrafanaGrid
transitions={enableTransitions}
layouts={layouts}
onLayoutChange={handleLayoutChange}
onDragStop={handleDragStop}
onResizeStop={handleResizeStop}
isDraggable={true}
isResizable={true}
>
{reports.map((report) => (
<div key={report.id}>
<ReportItem
report={report}
organizationId={organizationId}
projectId={projectId}
range={range}
startDate={startDate}
endDate={endDate}
interval={interval}
onDelete={(reportId) => {
reportDeletion.mutate({ reportId });
}}
onDuplicate={(reportId) => {
reportDuplicate.mutate({ reportId });
}}
/>
</div>
))}
</GrafanaGrid>
)}
</PageContainer>
);

View File

@@ -274,20 +274,16 @@ const PageCard = memo(
</div>
<ReportChart
options={{
hideID: true,
hideXAxis: true,
hideYAxis: true,
aspectRatio: 0.15,
}}
report={{
lineType: 'linear',
breakdowns: [],
name: 'screen_view',
metric: 'sum',
range,
interval,
previous: true,
chartType: 'linear',
projectId,
series: [

View File

@@ -1,36 +1,23 @@
import { ShareEnterPassword } from '@/components/auth/share-enter-password';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { GrafanaGrid, useReportLayouts } from '@/components/grafana-grid';
import { LoginNavbar } from '@/components/login-navbar';
import { ReportChart } from '@/components/report-chart';
import { OverviewRange } from '@/components/overview/overview-range';
import { OverviewInterval } from '@/components/overview/overview-interval';
import { OverviewRange } from '@/components/overview/overview-range';
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { PageContainer } from '@/components/page-container';
import { ReportChart } from '@/components/report-chart';
import {
ReportItem,
ReportItemReadOnly,
ReportItemSkeleton,
} from '@/components/report/report-item';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
import { timeWindows } from '@openpanel/constants';
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, notFound, useSearch } from '@tanstack/react-router';
import { z } from 'zod';
import { useMemo } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import { cn } from '@/utils/cn';
import { timeWindows } from '@openpanel/constants';
const ResponsiveGridLayout = WidthProvider(Responsive);
type Layout = {
i: string;
x: number;
y: number;
w: number;
h: number;
minW?: number;
minH?: number;
maxW?: number;
maxH?: number;
};
const shareSearchSchema = z.object({
header: z.optional(z.number().or(z.string().or(z.boolean()))),
@@ -77,85 +64,12 @@ export const Route = createFileRoute('/share/dashboard/$shareId')({
),
});
// Report Item Component for shared view
function ReportItem({
report,
shareId,
range,
startDate,
endDate,
interval,
}: {
report: any;
shareId: string;
range: any;
startDate: any;
endDate: any;
interval: any;
}) {
const chartRange = report.range;
return (
<div className="card h-full flex flex-col">
<div className="flex items-center justify-between border-b border-border p-4 leading-none">
<div className="flex-1">
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
<div className="mt-2 flex gap-2 ">
<span
className={
(chartRange !== range && range !== null) ||
(startDate && endDate)
? 'line-through'
: ''
}
>
{timeWindows[chartRange as keyof typeof timeWindows]?.label}
</span>
{startDate && endDate ? (
<span>Custom dates</span>
) : (
range !== null &&
chartRange !== range && (
<span>
{timeWindows[range as keyof typeof timeWindows]?.label}
</span>
)
)}
</div>
)}
</div>
</div>
<div
className={cn(
'p-4 overflow-auto flex-1',
report.chartType === 'metric' && 'p-0',
)}
>
<ReportChart
report={
{
...report,
range: range ?? report.range,
startDate: startDate ?? null,
endDate: endDate ?? null,
interval: interval ?? report.interval,
} as any
}
shareId={shareId}
shareType="dashboard"
/>
</div>
</div>
);
}
function RouteComponent() {
const { shareId } = Route.useParams();
const { header } = useSearch({ from: '/share/dashboard/$shareId' });
const trpc = useTRPC();
const { range, startDate, endDate, interval } = useOverviewOptions();
const shareQuery = useSuspenseQuery(
trpc.share.dashboard.queryOptions({
shareId,
@@ -182,9 +96,7 @@ function RouteComponent() {
// Handle password protection
if (share.password && !hasAccess) {
return (
<ShareEnterPassword shareId={share.id} shareType="dashboard" />
);
return <ShareEnterPassword shareId={share.id} shareType="dashboard" />;
}
const isHeaderVisible =
@@ -193,26 +105,7 @@ function RouteComponent() {
const reports = reportsQuery.data ?? [];
// Convert reports to grid layout format for all breakpoints
const layouts = useMemo(() => {
const baseLayout = reports.map((report, index) => ({
i: report.id,
x: report.layout?.x ?? (index % 2) * 6,
y: report.layout?.y ?? Math.floor(index / 2) * 4,
w: report.layout?.w ?? 6,
h: report.layout?.h ?? 4,
minW: 3,
minH: 3,
}));
// Create responsive layouts for different breakpoints
return {
lg: baseLayout,
md: baseLayout,
sm: baseLayout.map((item) => ({ ...item, w: Math.min(item.w, 6) })),
xs: baseLayout.map((item) => ({ ...item, w: 4, x: 0 })),
xxs: baseLayout.map((item) => ({ ...item, w: 2, x: 0 })),
};
}, [reports]);
const layouts = useReportLayouts(reports);
return (
<div>
@@ -221,61 +114,45 @@ function RouteComponent() {
<LoginNavbar className="relative p-4" />
</div>
)}
<PageContainer>
<div className="sticky-header [animation-range:50px_100px]!">
<div className="p-4 col gap-2 mx-auto max-w-7xl">
<div className="row justify-between">
<div className="flex gap-2">
<OverviewRange />
<OverviewInterval />
</div>
<div className="sticky-header [animation-range:50px_100px]!">
<div className="p-4 col gap-2 mx-auto max-w-7xl">
<div className="row justify-between">
<div className="flex gap-2">
<OverviewRange />
<OverviewInterval />
</div>
</div>
</div>
{reports.length === 0 ? (
</div>
<div className="mx-auto max-w-7xl p-4">
{reportsQuery.isLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
<ReportItemSkeleton />
</div>
) : reports.length === 0 ? (
<FullPageEmptyState title="No reports" />
) : (
<div className="w-full overflow-hidden -mx-4">
<style>{`
.react-grid-item {
transition: none !important;
}
.react-grid-item.react-grid-placeholder {
display: none !important;
}
`}</style>
<ResponsiveGridLayout
className="layout"
layouts={layouts}
breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
rowHeight={100}
draggableHandle=".drag-handle"
compactType="vertical"
preventCollision={false}
isDraggable={false}
isResizable={false}
margin={[16, 16]}
transformScale={1}
useCSSTransforms={true}
>
{reports.map((report) => (
<div key={report.id}>
<ReportItem
report={report}
shareId={shareId}
range={range}
startDate={startDate}
endDate={endDate}
interval={interval}
/>
</div>
))}
</ResponsiveGridLayout>
</div>
<GrafanaGrid layouts={layouts}>
{reports.map((report) => (
<div key={report.id}>
<ReportItemReadOnly
report={report}
shareId={shareId}
range={range}
startDate={startDate}
endDate={endDate}
interval={interval}
/>
</div>
))}
</GrafanaGrid>
)}
</PageContainer>
</div>
</div>
);
}

View File

@@ -2,10 +2,9 @@ import { ShareEnterPassword } from '@/components/auth/share-enter-password';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { LoginNavbar } from '@/components/login-navbar';
import { ReportChart } from '@/components/report-chart';
import { OverviewRange } from '@/components/overview/overview-range';
import { OverviewInterval } from '@/components/overview/overview-interval';
import { PageContainer } from '@/components/page-container';
import { OverviewRange } from '@/components/overview/overview-range';
import { ReportChart } from '@/components/report-chart';
import { useTRPC } from '@/integrations/trpc/react';
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, notFound, useSearch } from '@tanstack/react-router';
@@ -29,13 +28,7 @@ export const Route = createFileRoute('/share/report/$shareId')({
return { share: null };
}
const report = await context.queryClient.ensureQueryData(
context.trpc.report.get.queryOptions({
reportId: share.reportId,
}),
);
return { share, report };
return { share };
},
head: ({ loaderData }) => {
if (!loaderData || !loaderData.share) {
@@ -51,7 +44,7 @@ export const Route = createFileRoute('/share/report/$shareId')({
return {
meta: [
{
title: `${loaderData.report?.name || 'Report'} - ${loaderData.share.organization?.name} - OpenPanel.dev`,
title: `${loaderData.share.report.name || 'Report'} - ${loaderData.share.organization?.name} - OpenPanel.dev`,
},
],
};
@@ -76,12 +69,6 @@ function RouteComponent() {
}),
);
const reportQuery = useSuspenseQuery(
trpc.report.get.queryOptions({
reportId: shareQuery.data!.reportId,
}),
);
const hasAccess = shareQuery.data?.hasAccess;
if (!shareQuery.data) {
@@ -93,7 +80,8 @@ function RouteComponent() {
}
const share = shareQuery.data;
const report = reportQuery.data;
console.log('share', share);
// Handle password protection
if (share.password && !hasAccess) {
@@ -110,33 +98,26 @@ function RouteComponent() {
<LoginNavbar className="relative p-4" />
</div>
)}
<PageContainer>
<div className="sticky-header [animation-range:50px_100px]!">
<div className="p-4 col gap-2 mx-auto max-w-7xl">
<div className="row justify-between">
<div className="flex gap-2">
<OverviewRange />
<OverviewInterval />
</div>
<div className="sticky-header [animation-range:50px_100px]!">
<div className="p-4 col gap-2 mx-auto max-w-7xl">
<div className="row justify-between">
<div className="flex gap-2">
<OverviewRange />
<OverviewInterval />
</div>
</div>
</div>
<div className="p-4">
<div className="card">
<div className="p-4 border-b">
<div className="font-medium text-xl">{report.name}</div>
</div>
<div className="p-4">
<ReportChart
report={report}
shareId={shareId}
shareType="report"
/>
</div>
</div>
<div className="mx-auto max-w-7xl p-4">
<div className="card">
<div className="p-4 border-b">
<div className="font-medium text-xl">{share.report.name}</div>
</div>
<div className="p-4">
<ReportChart report={share.report} shareId={shareId} />
</div>
</div>
</PageContainer>
</div>
</div>
);
}