feature(dashboard,api): add timezone support

* feat(dashboard): add support for today, yesterday etc (timezones)

* fix(db): escape js dates

* fix(dashboard): ensure we support default timezone

* final fixes

* remove complete series and add sql with fill instead
This commit is contained in:
Carl-Gerhard Lindesvärd
2025-05-23 11:26:44 +02:00
committed by GitHub
parent 46bfeee131
commit 680727355b
48 changed files with 1817 additions and 758 deletions

View File

@@ -1,5 +1,5 @@
import Chat from '@/components/chat/chat';
import { db, getOrganizationBySlug } from '@openpanel/db';
import { db, getOrganizationById } from '@openpanel/db';
import type { UIMessage } from 'ai';
export default async function ChatPage({
@@ -9,7 +9,7 @@ export default async function ChatPage({
}) {
const { projectId } = await params;
const [organization, chat] = await Promise.all([
getOrganizationBySlug(params.organizationSlug),
getOrganizationById(params.organizationSlug),
db.chat.findFirst({
where: {
projectId,

View File

@@ -24,7 +24,6 @@ import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { useAppParams } from '@/hooks/useAppParams';
import { useDispatch, useSelector } from '@/redux';
import { bind } from 'bind-event-listener';
import { endOfDay, startOfDay } from 'date-fns';
import { GanttChartSquareIcon } from 'lucide-react';
import { useEffect } from 'react';
@@ -89,12 +88,8 @@ export default function ReportEditor({
dispatch(changeDateRanges(value));
}}
value={report.range}
onStartDateChange={(date) =>
dispatch(changeStartDate(startOfDay(date).toISOString()))
}
onEndDateChange={(date) =>
dispatch(changeEndDate(endOfDay(date).toISOString()))
}
onStartDateChange={(date) => dispatch(changeStartDate(date))}
onEndDateChange={(date) => dispatch(changeEndDate(date))}
endDate={report.endDate}
startDate={report.startDate}
/>

View File

@@ -1,20 +1,19 @@
'use client';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
import { api, handleError } from '@/trpc/client';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { z } from 'zod';
import { Combobox } from '@/components/ui/combobox';
import type { IServiceOrganization } from '@openpanel/db';
import { zEditOrganization } from '@openpanel/validation';
const validator = z.object({
id: z.string().min(2),
name: z.string().min(2),
});
const validator = zEditOrganization;
type IForm = z.infer<typeof validator>;
interface EditOrganizationProps {
@@ -25,8 +24,12 @@ export default function EditOrganization({
}: EditOrganizationProps) {
const router = useRouter();
const { register, handleSubmit, formState, reset } = useForm<IForm>({
defaultValues: organization ?? undefined,
const { register, handleSubmit, formState, reset, control } = useForm<IForm>({
defaultValues: {
id: organization.id,
name: organization.name,
timezone: organization.timezone ?? undefined,
},
});
const mutation = api.organization.update.useMutation({
@@ -34,7 +37,10 @@ export default function EditOrganization({
toast('Organization updated', {
description: 'Your organization has been updated.',
});
reset(res);
reset({
...res,
timezone: res.timezone!,
});
router.refresh();
},
onError: handleError,
@@ -50,14 +56,37 @@ export default function EditOrganization({
<WidgetHead className="flex items-center justify-between">
<span className="title">Details</span>
</WidgetHead>
<WidgetBody className="flex items-end gap-2">
<WidgetBody className="gap-4 col">
<InputWithLabel
className="flex-1"
label="Name"
{...register('name')}
defaultValue={organization?.name}
/>
<Button size="sm" type="submit" disabled={!formState.isDirty}>
<Controller
name="timezone"
control={control}
render={({ field }) => (
<WithLabel label="Timezone">
<Combobox
placeholder="Select timezone"
items={Intl.supportedValuesOf('timeZone').map((item) => ({
value: item,
label: item,
}))}
value={field.value}
onChange={field.onChange}
className="w-full"
/>
</WithLabel>
)}
/>
<Button
size="sm"
type="submit"
disabled={!formState.isDirty}
className="self-end"
>
Save
</Button>
</WidgetBody>

View File

@@ -6,7 +6,7 @@ import { notFound } from 'next/navigation';
import { parseAsStringEnum } from 'nuqs/server';
import { auth } from '@openpanel/auth/nextjs';
import { db, transformOrganization } from '@openpanel/db';
import { db } from '@openpanel/db';
import InvitesServer from './invites';
import MembersServer from './members';

View File

@@ -83,12 +83,7 @@ export default function EditProjectDetails({ project }: Props) {
<span className="title">Details</span>
</WidgetHead>
<WidgetBody>
<form
onSubmit={form.handleSubmit(onSubmit, (errors) => {
console.log(errors);
})}
className="col gap-4"
>
<form onSubmit={form.handleSubmit(onSubmit)} className="col gap-4">
<InputWithLabel
label="Name"
{...form.register('name')}

View File

@@ -0,0 +1,61 @@
'use client';
import { differenceInHours } from 'date-fns';
import { useEffect, useState } from 'react';
import { ProjectLink } from '@/components/links';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import type { IServiceOrganization } from '@openpanel/db';
import { useOpenPanel } from '@openpanel/nextjs';
import { FREE_PRODUCT_IDS } from '@openpanel/payments';
import Billing from './settings/organization/organization/billing';
interface SideEffectsProps {
organization: IServiceOrganization;
}
export default function SideEffectsFreePlan({
organization,
}: SideEffectsProps) {
const op = useOpenPanel();
const willEndInHours = organization.subscriptionEndsAt
? differenceInHours(organization.subscriptionEndsAt, new Date())
: null;
const [isFreePlan, setIsFreePlan] = useState<boolean>(
!!organization.subscriptionProductId &&
FREE_PRODUCT_IDS.includes(organization.subscriptionProductId),
);
useEffect(() => {
if (isFreePlan) {
op.track('free_plan_removed');
}
}, []);
return (
<Dialog open={isFreePlan} onOpenChange={setIsFreePlan}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsFreePlan(false)}
title={'Free plan has been removed'}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,91 @@
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Dialog, DialogContent, DialogFooter } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import { api, handleError } from '@/trpc/client';
import { TIMEZONES } from '@openpanel/common';
import type { IServiceOrganization } from '@openpanel/db';
import { toast } from 'sonner';
interface SideEffectsProps {
organization: IServiceOrganization;
}
export default function SideEffectsTimezone({
organization,
}: SideEffectsProps) {
const [isMissingTimezone, setIsMissingTimezone] = useState<boolean>(
!organization.timezone,
);
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const [timezone, setTimezone] = useState<string>(
TIMEZONES.includes(defaultTimezone) ? defaultTimezone : '',
);
const mutation = api.organization.update.useMutation({
onSuccess(res) {
toast('Timezone updated', {
description: 'Your timezone has been updated.',
});
window.location.reload();
},
onError: handleError,
});
return (
<Dialog open={isMissingTimezone} onOpenChange={setIsMissingTimezone}>
<DialogContent
className="max-w-xl"
onEscapeKeyDown={(e) => {
e.preventDefault();
}}
onInteractOutside={(e) => {
e.preventDefault();
}}
>
<ModalHeader
onClose={false}
title="Select your timezone"
text={
<>
We have introduced new features that requires your timezone.
Please select the timezone you want to use for your organization.
</>
}
/>
<Combobox
items={TIMEZONES.map((item) => ({
value: item,
label: item,
}))}
value={timezone}
onChange={setTimezone}
placeholder="Select a timezone"
searchable
size="lg"
className="w-full px-4"
/>
<DialogFooter className="mt-4">
<Button
size="lg"
disabled={!TIMEZONES.includes(timezone)}
loading={mutation.isLoading}
onClick={() =>
mutation.mutate({
id: organization.id,
name: organization.name,
timezone: timezone ?? '',
})
}
>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,67 @@
'use client';
import { differenceInHours } from 'date-fns';
import { useEffect, useState } from 'react';
import { ProjectLink } from '@/components/links';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import type { IServiceOrganization } from '@openpanel/db';
import { useOpenPanel } from '@openpanel/nextjs';
import Billing from './settings/organization/organization/billing';
interface SideEffectsProps {
organization: IServiceOrganization;
}
export default function SideEffectsTrial({ organization }: SideEffectsProps) {
const op = useOpenPanel();
const willEndInHours = organization.subscriptionEndsAt
? differenceInHours(organization.subscriptionEndsAt, new Date())
: null;
const [isTrialDialogOpen, setIsTrialDialogOpen] = useState<boolean>(
willEndInHours !== null &&
organization.subscriptionStatus === 'trialing' &&
organization.subscriptionEndsAt !== null &&
willEndInHours <= 48,
);
useEffect(() => {
if (isTrialDialogOpen) {
op.track('trial_expires_soon');
}
}, [isTrialDialogOpen]);
return (
<>
<Dialog open={isTrialDialogOpen} onOpenChange={setIsTrialDialogOpen}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsTrialDialogOpen(false)}
title={
willEndInHours !== null && willEndInHours > 0
? `Your trial is ending in ${willEndInHours} hours`
: 'Your trial has ended'
}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -4,12 +4,16 @@ import { differenceInHours } from 'date-fns';
import { useEffect, useState } from 'react';
import { ProjectLink } from '@/components/links';
import { Combobox } from '@/components/ui/combobox';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import type { IServiceOrganization } from '@openpanel/db';
import { useOpenPanel } from '@openpanel/nextjs';
import { FREE_PRODUCT_IDS } from '@openpanel/payments';
import Billing from './settings/organization/organization/billing';
import SideEffectsFreePlan from './side-effects-free-plan';
import SideEffectsTimezone from './side-effects-timezone';
import SideEffectsTrial from './side-effects-trial';
interface SideEffectsProps {
organization: IServiceOrganization;
@@ -17,41 +21,11 @@ interface SideEffectsProps {
export default function SideEffects({ organization }: SideEffectsProps) {
const [mounted, setMounted] = useState(false);
const op = useOpenPanel();
const willEndInHours = organization.subscriptionEndsAt
? differenceInHours(organization.subscriptionEndsAt, new Date())
: null;
const [isTrialDialogOpen, setIsTrialDialogOpen] = useState<boolean>(false);
const [isFreePlan, setIsFreePlan] = useState<boolean>(false);
useEffect(() => {
if (!mounted) {
setMounted(true);
}
setMounted(true);
}, []);
useEffect(() => {
if (
willEndInHours !== null &&
organization.subscriptionStatus === 'trialing' &&
organization.subscriptionEndsAt !== null &&
willEndInHours <= 48
) {
setIsTrialDialogOpen(true);
op.track('trial_expires_soon');
}
}, [mounted, organization]);
useEffect(() => {
if (
organization.subscriptionProductId &&
FREE_PRODUCT_IDS.includes(organization.subscriptionProductId)
) {
setIsFreePlan(true);
op.track('free_plan_removed');
}
}, [mounted, organization]);
// Avoids hydration errors
if (!mounted) {
return null;
@@ -59,56 +33,9 @@ export default function SideEffects({ organization }: SideEffectsProps) {
return (
<>
<Dialog open={isTrialDialogOpen} onOpenChange={setIsTrialDialogOpen}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsTrialDialogOpen(false)}
title={
willEndInHours !== null && willEndInHours > 0
? `Your trial is ending in ${willEndInHours} hours`
: 'Your trial has ended'
}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
<Dialog open={isFreePlan} onOpenChange={setIsFreePlan}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsFreePlan(false)}
title={'Free plan has been removed'}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
<SideEffectsTimezone organization={organization} />
<SideEffectsTrial organization={organization} />
<SideEffectsFreePlan organization={organization} />
</>
);
}

View File

@@ -51,6 +51,7 @@ export const OnboardingCreateProject = ({
resolver: zodResolver(zOnboardingProject),
defaultValues: {
organization: '',
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
project: '',
domain: '',
cors: [],
@@ -130,13 +131,33 @@ export const OnboardingCreateProject = ({
}}
/>
) : (
<InputWithLabel
label="Workspace name"
info="This is the name of your workspace. It can be anything you like."
placeholder="Eg. The Music Company"
error={form.formState.errors.organization?.message}
{...form.register('organization')}
/>
<>
<InputWithLabel
label="Workspace name"
info="This is the name of your workspace. It can be anything you like."
placeholder="Eg. The Music Company"
error={form.formState.errors.organization?.message}
{...form.register('organization')}
/>
<Controller
name="timezone"
control={form.control}
render={({ field }) => (
<WithLabel label="Timezone">
<Combobox
placeholder="Select timezone"
items={Intl.supportedValuesOf('timeZone').map((item) => ({
value: item,
label: item,
}))}
value={field.value}
onChange={field.onChange}
className="w-full"
/>
</WithLabel>
)}
/>
</>
)}
<InputWithLabel
label="Project name"

View File

@@ -11,7 +11,7 @@ import { notFound } from 'next/navigation';
import { ShareEnterPassword } from '@/components/auth/share-enter-password';
import { OverviewRange } from '@/components/overview/overview-range';
import { getOrganizationBySlug, getShareOverviewById } from '@openpanel/db';
import { getOrganizationById, getShareOverviewById } from '@openpanel/db';
import { cookies } from 'next/headers';
interface PageProps {
@@ -35,7 +35,7 @@ export default async function Page({
return notFound();
}
const projectId = share.projectId;
const organization = await getOrganizationBySlug(share.organizationId);
const organization = await getOrganizationById(share.organizationId);
if (share.password) {
const cookie = cookies().get(`shared-overview-${share.id}`)?.value;

View File

@@ -34,10 +34,7 @@ export function SignInEmailForm() {
};
return (
<form
onSubmit={form.handleSubmit(onSubmit, (err) => console.log(err))}
className="col gap-6"
>
<form onSubmit={form.handleSubmit(onSubmit)} className="col gap-6">
<h3 className="text-2xl font-medium text-left">Sign in with email</h3>
<InputWithLabel
{...form.register('email')}

View File

@@ -7,7 +7,6 @@ import type {
IChartType,
IInterval,
} from '@openpanel/validation';
import { endOfDay, startOfDay } from 'date-fns';
import { SaveIcon } from 'lucide-react';
import { useState } from 'react';
import { ReportChart } from '../report-chart';
@@ -50,10 +49,8 @@ export function ChatReport({
className="min-w-0"
onChange={setRange}
value={report.range}
onStartDateChange={(date) =>
setStartDate(startOfDay(date).toISOString())
}
onEndDateChange={(date) => setEndDate(endOfDay(date).toISOString())}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
endDate={report.endDate}
startDate={report.startDate}
/>

View File

@@ -173,7 +173,9 @@ export function OverviewMetricCardNumber({
<div className={cn('flex min-w-0 flex-col gap-2', className)}>
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2 text-left">
<span className="truncate text-muted-foreground">{label}</span>
<span className="truncate text-sm font-medium text-muted-foreground">
{label}
</span>
</div>
</div>
{isLoading ? (

View File

@@ -4,15 +4,19 @@ import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { useEventQueryFilters } from '@/hooks/useEventQueryFilters';
import { cn } from '@/utils/cn';
import { useDashedStroke } from '@/hooks/use-dashed-stroke';
import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
import { useNumber } from '@/hooks/useNumerFormatter';
import { type RouterOutputs, api } from '@/trpc/client';
import { getChartColor } from '@/utils/theme';
import { getPreviousMetric } from '@openpanel/common';
import type { IInterval } from '@openpanel/validation';
import { isSameDay, isSameHour, isSameMonth, isSameWeek } from 'date-fns';
import { last } from 'ramda';
import React from 'react';
import {
CartesianGrid,
Customized,
Line,
LineChart,
ResponsiveContainer,
@@ -93,6 +97,44 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
const xAxisProps = useXAxisProps({ interval });
const yAxisProps = useYAxisProps();
let dotIndex = undefined;
if (range === 'today') {
// Find closest index based on times
dotIndex = data.findIndex((item) => {
return isSameHour(item.date, new Date());
});
}
const { calcStrokeDasharray, handleAnimationEnd, getStrokeDasharray } =
useDashedStroke({
dotIndex,
});
const lastSerieDataItem = last(data)?.date || new Date();
const useDashedLastLine = (() => {
if (range === 'today') {
return true;
}
if (interval === 'hour') {
return isSameHour(lastSerieDataItem, new Date());
}
if (interval === 'day') {
return isSameDay(lastSerieDataItem, new Date());
}
if (interval === 'month') {
return isSameMonth(lastSerieDataItem, new Date());
}
if (interval === 'week') {
return isSameWeek(lastSerieDataItem, new Date());
}
return false;
})();
return (
<>
<div className="relative -top-0.5 col-span-6 -m-4 mb-0 mt-0 md:m-0">
@@ -127,7 +169,7 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
</div>
<div className="card p-4">
<div className="text-center text-muted-foreground mb-2">
<div className="text-center mb-3 -mt-1 text-sm font-medium text-muted-foreground">
{activeMetric.title}
</div>
<div className="w-full h-[150px]">
@@ -135,6 +177,13 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
<TooltipProvider metric={activeMetric} interval={interval}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={data}>
<Customized component={calcStrokeDasharray} />
<Line
dataKey="calcStrokeDasharray"
legendType="none"
animationDuration={0}
onAnimationEnd={handleAnimationEnd}
/>
<Tooltip />
<YAxis
{...yAxisProps}
@@ -184,6 +233,11 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
dataKey={activeMetric.key}
stroke={getChartColor(0)}
strokeWidth={2}
strokeDasharray={
useDashedLastLine
? getStrokeDasharray(activeMetric.key)
: undefined
}
isAnimationActive={false}
dot={
data.length > 90

View File

@@ -2,7 +2,6 @@
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { TimeWindowPicker } from '@/components/time-window-picker';
import { endOfDay, formatISO, startOfDay } from 'date-fns';
export function OverviewRange() {
const { range, setRange, setStartDate, setEndDate, endDate, startDate } =
@@ -12,14 +11,8 @@ export function OverviewRange() {
<TimeWindowPicker
onChange={setRange}
value={range}
onStartDateChange={(date) => {
const d = formatISO(startOfDay(new Date(date)));
setStartDate(d);
}}
onEndDateChange={(date) => {
const d = formatISO(endOfDay(new Date(date)));
setEndDate(d);
}}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
endDate={endDate}
startDate={startDate}
/>

View File

@@ -6,13 +6,20 @@ import { api } from '@/trpc/client';
import type { IChartData } from '@/trpc/client';
import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
import { isSameDay, isSameHour, isSameMonth } from 'date-fns';
import {
isFuture,
isSameDay,
isSameHour,
isSameMonth,
isSameWeek,
} from 'date-fns';
import { last } from 'ramda';
import React, { useCallback } from 'react';
import React, { useCallback, useState } from 'react';
import {
Area,
CartesianGrid,
ComposedChart,
Customized,
Legend,
Line,
ReferenceLine,
@@ -22,6 +29,7 @@ import {
YAxis,
} from 'recharts';
import { useDashedStroke, useStrokeDasharray } from '@/hooks/use-dashed-stroke';
import { useXAxisProps, useYAxisProps } from '../common/axis';
import { SolidToDashedGradient } from '../common/linear-gradient';
import { ReportChartTooltip } from '../common/report-chart-tooltip';
@@ -63,15 +71,20 @@ export function Chart({ data }: Props) {
const { series, setVisibleSeries } = useVisibleSeries(data);
const rechartData = useRechartDataModel(series);
// great care should be taken when computing lastIntervalPercent
// the expression below works for data.length - 1 equal intervals
// but if there are numeric x values in a "linear" axis, the formula
// should be updated to use those values
const lastIntervalPercent =
((rechartData.length - 2) * 100) / (rechartData.length - 1);
let dotIndex = undefined;
if (range === 'today') {
// Find closest index based on times
dotIndex = rechartData.findIndex((item) => {
return isSameHour(item.date, new Date());
});
}
const lastSerieDataItem = last(series[0]?.data || [])?.date || new Date();
const useDashedLastLine = (() => {
if (range === 'today') {
return true;
}
if (interval === 'hour') {
return isSameHour(lastSerieDataItem, new Date());
}
@@ -84,9 +97,18 @@ export function Chart({ data }: Props) {
return isSameMonth(lastSerieDataItem, new Date());
}
if (interval === 'week') {
return isSameWeek(lastSerieDataItem, new Date());
}
return false;
})();
const { getStrokeDasharray, calcStrokeDasharray, handleAnimationEnd } =
useDashedStroke({
dotIndex,
});
const CustomLegend = useCallback(() => {
return (
<div className="flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs mt-4 -mb-2">
@@ -117,6 +139,13 @@ export function Chart({ data }: Props) {
<div className={cn('h-full w-full', isEditMode && 'card p-4')}>
<ResponsiveContainer>
<ComposedChart data={rechartData}>
<Customized component={calcStrokeDasharray} />
<Line
dataKey="calcStrokeDasharray"
legendType="none"
animationDuration={0}
onAnimationEnd={handleAnimationEnd}
/>
<CartesianGrid
strokeDasharray="3 3"
horizontal={true}
@@ -166,13 +195,6 @@ export function Chart({ data }: Props) {
/>
</linearGradient>
)}
{useDashedLastLine && (
<SolidToDashedGradient
percentage={lastIntervalPercent}
baseColor={color}
id={`stroke${color}`}
/>
)}
</defs>
<Line
dot={isAreaStyle && dataLength <= 8}
@@ -181,7 +203,12 @@ export function Chart({ data }: Props) {
isAnimationActive={false}
strokeWidth={2}
dataKey={`${serie.id}:count`}
stroke={useDashedLastLine ? `url(#stroke${color})` : color}
stroke={color}
strokeDasharray={
useDashedLastLine
? getStrokeDasharray(`${serie.id}:count`)
: undefined
}
// Use for legend
fill={color}
/>

View File

@@ -1,16 +1,9 @@
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import {
endOfDay,
formatISO,
isSameDay,
isSameMonth,
startOfDay,
} from 'date-fns';
import { createSlice } from '@reduxjs/toolkit';
import { endOfDay, format, isSameDay, isSameMonth, startOfDay } from 'date-fns';
import { shortId } from '@openpanel/common';
import {
alphabetIds,
getDefaultIntervalByDates,
getDefaultIntervalByRange,
isHourIntervalEnabledByRange,
@@ -192,31 +185,10 @@ export const reportSlice = createSlice({
state.lineType = action.payload;
},
// Custom start and end date
changeDates: (
state,
action: PayloadAction<{
startDate: string;
endDate: string;
}>,
) => {
state.dirty = true;
state.startDate = formatISO(startOfDay(action.payload.startDate));
state.endDate = formatISO(endOfDay(action.payload.endDate));
if (isSameDay(state.startDate, state.endDate)) {
state.interval = 'hour';
} else if (isSameMonth(state.startDate, state.endDate)) {
state.interval = 'day';
} else {
state.interval = 'month';
}
},
// Date range
changeStartDate: (state, action: PayloadAction<string>) => {
state.dirty = true;
state.startDate = formatISO(startOfDay(action.payload));
state.startDate = action.payload;
const interval = getDefaultIntervalByDates(
state.startDate,
@@ -230,7 +202,7 @@ export const reportSlice = createSlice({
// Date range
changeEndDate: (state, action: PayloadAction<string>) => {
state.dirty = true;
state.endDate = formatISO(endOfDay(action.payload));
state.endDate = action.payload;
const interval = getDefaultIntervalByDates(
state.startDate,
@@ -263,8 +235,6 @@ export const reportSlice = createSlice({
},
changeUnit(state, action: PayloadAction<string | undefined>) {
console.log('here?!?!', action.payload);
state.dirty = true;
state.unit = action.payload || undefined;
},
@@ -305,7 +275,6 @@ export const {
removeBreakdown,
changeBreakdown,
changeInterval,
changeDates,
changeStartDate,
changeEndDate,
changeDateRanges,

View File

@@ -18,6 +18,7 @@ import { useCallback, useEffect, useRef } from 'react';
import { shouldIgnoreKeypress } from '@/utils/should-ignore-keypress';
import { timeWindows } from '@openpanel/constants';
import type { IChartRange } from '@openpanel/validation';
import { endOfDay, format, startOfDay } from 'date-fns';
type Props = {
value: IChartRange;
@@ -46,8 +47,8 @@ export function TimeWindowPicker({
const handleCustom = useCallback(() => {
pushModal('DateRangerPicker', {
onChange: ({ startDate, endDate }) => {
onStartDateChange(startDate.toISOString());
onEndDateChange(endDate.toISOString());
onStartDateChange(format(startOfDay(startDate), 'yyyy-MM-dd HH:mm:ss'));
onEndDateChange(format(endOfDay(endDate), 'yyyy-MM-dd HH:mm:ss'));
onChange('custom');
},
startDate: startDate ? new Date(startDate) : undefined,
@@ -113,6 +114,12 @@ export function TimeWindowPicker({
{timeWindows.today.shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onChange(timeWindows.yesterday.key)}>
{timeWindows.yesterday.label}
<DropdownMenuShortcut>
{timeWindows.yesterday.shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
@@ -130,6 +137,18 @@ export function TimeWindowPicker({
{timeWindows['30d'].shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onChange(timeWindows['6m'].key)}>
{timeWindows['6m'].label}
<DropdownMenuShortcut>
{timeWindows['6m'].shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onChange(timeWindows['12m'].key)}>
{timeWindows['12m'].label}
<DropdownMenuShortcut>
{timeWindows['12m'].shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />

View File

@@ -18,8 +18,6 @@ export function InputEnter({
useEffect(() => {
if (value !== internalValue) {
console.log(value, internalValue);
setInternalValue(value ?? '');
}
}, [value]);

View File

@@ -0,0 +1,199 @@
import { forwardRef, useCallback, useRef, useState } from 'react';
import { Customized, Line } from 'recharts';
export type GraphicalItemPoint = {
/**
* x point coordinate.
*/
x?: number;
/**
* y point coordinate.
*/
y?: number;
};
export type GraphicalItemProps = {
/**
* graphical item points.
*/
points?: GraphicalItemPoint[];
};
export type ItemProps = {
/**
* item data key.
*/
dataKey?: string;
};
export type ItemType = {
/**
* recharts item display name.
*/
displayName?: string;
};
export type Item = {
/**
* item props.
*/
props?: ItemProps;
/**
* recharts item class.
*/
type?: ItemType;
};
export type GraphicalItem = {
/**
* from recharts internal state and props of chart.
*/
props?: GraphicalItemProps;
/**
* from recharts internal state and props of chart.
*/
item?: Item;
};
export type RechartsChartProps = {
/**
* from recharts internal state and props of chart.
*/
formattedGraphicalItems?: GraphicalItem[];
};
export type CalculateStrokeDasharray = (props?: any) => any;
export type LineStrokeDasharray = {
/**
* line name.
*/
name?: string;
/**
* line strokeDasharray.
*/
strokeDasharray?: string;
};
export type LinesStrokeDasharray = LineStrokeDasharray[];
export type LineProps = {
/**
* line name.
*/
name?: string;
/**
* specifies the starting index of the first dot in the dash pattern.
*/
dotIndex?: number;
/**
* defines the pattern of dashes and gaps. an array of [gap length, dash length].
*/
strokeDasharray?: [number, number];
/**
* adjusts the percentage correction of the first line segment for better alignment in curved lines.
*/
curveCorrection?: number;
};
export type UseStrokeDasharrayProps = {
/**
* an array of properties to target specific line(s) and override default settings.
*/
linesProps?: LineProps[];
} & LineProps;
export function useStrokeDasharray({
linesProps = [],
dotIndex = -2,
strokeDasharray: restStroke = [5, 3],
curveCorrection = 1,
}: UseStrokeDasharrayProps): [CalculateStrokeDasharray, LinesStrokeDasharray] {
const linesStrokeDasharray = useRef<LinesStrokeDasharray>([]);
const calculateStrokeDasharray = useCallback(
(props: RechartsChartProps): null => {
const items = props?.formattedGraphicalItems;
const getLineWidth = (points: GraphicalItemPoint[]) => {
const width = points?.reduce((acc, point, index) => {
if (!index) return acc;
const prevPoint = points?.[index - 1];
const xAxis = point?.x || 0;
const prevXAxis = prevPoint?.x || 0;
const xWidth = xAxis - prevXAxis;
const yAxis = point?.y || 0;
const prevYAxis = prevPoint?.y || 0;
const yWidth = Math.abs(yAxis - prevYAxis);
const hypotenuse = Math.sqrt(xWidth * xWidth + yWidth * yWidth);
acc += hypotenuse;
return acc;
}, 0);
return width || 0;
};
items?.forEach((line) => {
const linePoints = line?.props?.points;
const lineWidth = getLineWidth(linePoints || []);
const name = line?.item?.props?.dataKey;
const targetLine = linesProps?.find((target) => target?.name === name);
const targetIndex = targetLine?.dotIndex ?? dotIndex;
const dashedPoints = linePoints?.slice(targetIndex);
const dashedWidth = getLineWidth(dashedPoints || []);
if (!lineWidth || !dashedWidth) return;
const firstWidth = lineWidth - dashedWidth;
const targetCurve = targetLine?.curveCorrection ?? curveCorrection;
const correctionWidth = (firstWidth * targetCurve) / 100;
const firstDasharray = firstWidth + correctionWidth;
const targetRestStroke = targetLine?.strokeDasharray || restStroke;
const gapDashWidth = targetRestStroke?.[0] + targetRestStroke?.[1] || 1;
const restDasharrayLength = dashedWidth / gapDashWidth;
const restDasharray = new Array(Math.ceil(restDasharrayLength)).fill(
targetRestStroke.join(' '),
);
const strokeDasharray = `${firstDasharray} ${restDasharray.join(' ')}`;
const lineStrokeDasharray = { name, strokeDasharray };
const dasharrayIndex = linesStrokeDasharray.current.findIndex((d) => {
return d.name === line?.item?.props?.dataKey;
});
if (dasharrayIndex === -1) {
linesStrokeDasharray.current.push(lineStrokeDasharray);
return;
}
linesStrokeDasharray.current[dasharrayIndex] = lineStrokeDasharray;
});
return null;
},
[dotIndex],
);
return [calculateStrokeDasharray, linesStrokeDasharray.current];
}
export function useDashedStroke(options: UseStrokeDasharrayProps = {}) {
const [calcStrokeDasharray, strokes] = useStrokeDasharray(options);
const [strokeDasharray, setStrokeDasharray] = useState([...strokes]);
const handleAnimationEnd = () => setStrokeDasharray([...strokes]);
const getStrokeDasharray = (name: string) => {
return strokeDasharray.find((s) => s?.name === name)?.strokeDasharray;
};
return {
calcStrokeDasharray,
getStrokeDasharray,
handleAnimationEnd,
};
}

View File

@@ -83,12 +83,7 @@ export default function AddProject() {
return (
<ModalContent>
<ModalHeader title="Create project" />
<form
onSubmit={form.handleSubmit(onSubmit, (errors) => {
console.log(errors);
})}
className="col gap-4"
>
<form onSubmit={form.handleSubmit(onSubmit)} className="col gap-4">
<InputWithLabel label="Name" {...form.register('name')} />
<div className="-mb-2 flex gap-2 items-center justify-between">