move sdk packages to its own folder and rename api & dashboard

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-03-11 13:15:44 +01:00
parent 1ca95442b9
commit 6d4f9010d4
318 changed files with 350 additions and 351 deletions

View File

@@ -0,0 +1,260 @@
'use client';
import { useEffect } from 'react';
import { api, handleError } from '@/app/_trpc/client';
import { Button } from '@/components/ui/button';
import { CheckboxInput } from '@/components/ui/checkbox';
import { Combobox } from '@/components/ui/combobox';
import {
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAppParams } from '@/hooks/useAppParams';
import { clipboard } from '@/utils/clipboard';
import { zodResolver } from '@hookform/resolvers/zod';
import { Copy, SaveIcon } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import type { SubmitHandler } from 'react-hook-form';
import { Controller, useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
const validation = z.object({
name: z.string().min(1),
domain: z.string().optional(),
withSecret: z.boolean().optional(),
projectId: z.string(),
});
type IForm = z.infer<typeof validation>;
export default function AddClient() {
const { organizationId, projectId } = useAppParams();
const router = useRouter();
const form = useForm<IForm>({
resolver: zodResolver(validation),
defaultValues: {
withSecret: false,
name: '',
domain: '',
projectId,
},
});
const mutation = api.client.create2.useMutation({
onError: handleError,
onSuccess() {
toast.success('Client created');
router.refresh();
},
});
const query = api.project.list.useQuery({
organizationId,
});
const onSubmit: SubmitHandler<IForm> = (values) => {
mutation.mutate({
name: values.name,
domain: values.withSecret ? undefined : values.domain,
projectId: values.projectId,
organizationId,
});
};
const watch = useWatch({
control: form.control,
name: 'withSecret',
});
return (
<ModalContent>
{mutation.isSuccess ? (
<>
<ModalHeader
title="Success"
text={
<>
{mutation.data.clientSecret
? 'Use your client id and secret with our SDK to send events to us. '
: 'Use your client id with our SDK to send events to us. '}
See our{' '}
<Link href="https//openpanel.dev/docs" className="underline">
documentation
</Link>
</>
}
/>
<div className="grid gap-4">
<button
className="mt-4 text-left"
onClick={() => clipboard(mutation.data.clientId)}
>
<Label>Client ID</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{mutation.data.clientId}
<Copy size={16} />
</div>
</button>
{mutation.data.clientSecret ? (
<button
className="mt-4 text-left"
onClick={() => clipboard(mutation.data.clientId)}
>
<Label>Secret</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{mutation.data.clientSecret}
<Copy size={16} />
</div>
</button>
) : (
<div className="mt-4 text-left">
<Label>Cors settings</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{mutation.data.cors}
</div>
<div className="text-sm italic mt-1">
You can update cors settings{' '}
<Link className="underline" href="/qwe/qwe/">
here
</Link>
</div>
</div>
)}
</div>
<DialogFooter>
<Button
type="button"
variant={'secondary'}
onClick={() => popModal()}
>
Close
</Button>
</DialogFooter>
</>
) : (
<>
<ModalHeader title="Create a client" />
<form
className="flex flex-col gap-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<div>
<Label>Client name</Label>
<Input
placeholder="Eg. My App Client"
error={form.formState.errors.name?.message}
{...form.register('name')}
/>
</div>
<Controller
name="withSecret"
control={form.control}
render={({ field }) => (
<CheckboxInput
defaultChecked={!field.value}
onCheckedChange={(checked) => {
field.onChange(!checked);
}}
>
This is a website
</CheckboxInput>
)}
/>
<div>
<Label>Your domain name</Label>
<Input
placeholder="https://...."
error={form.formState.errors.domain?.message}
{...form.register('domain')}
disabled={watch}
/>
</div>
<div>
<Controller
control={form.control}
name="projectId"
render={({ field }) => {
return (
<div>
<Label>Project</Label>
<Combobox
{...field}
className="w-full"
onChange={(value) => {
field.onChange(value);
}}
items={
query.data?.map((item) => ({
value: item.id,
label: item.name,
})) ?? []
}
placeholder="Select a project"
/>
</div>
);
}}
/>
</div>
<DialogFooter>
<Button
type="button"
variant={'secondary'}
onClick={() => popModal()}
>
Cancel
</Button>
<Button
type="submit"
icon={SaveIcon}
loading={mutation.isLoading}
>
Create
</Button>
</DialogFooter>
</form>
</>
)}
</ModalContent>
);
}
{
/* <div>
<div className="text-lg">
Select your framework and we'll generate a client for you.
</div>
<div className="flex flex-wrap gap-2 mt-8">
<FeatureButton
name="React"
logo="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png"
/>
<FeatureButton
name="React Native"
logo="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png"
/>
<FeatureButton
name="Next.js"
logo="https://static-00.iconduck.com/assets.00/nextjs-icon-512x512-y563b8iq.png"
/>
<FeatureButton
name="Remix"
logo="https://www.datocms-assets.com/205/1642515307-square-logo.svg"
/>
<FeatureButton
name="Vue"
logo="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ0UhQnp6TUPCwAr3ruTEwBDiTN5HLAWaoUD3AJIgtepQ&s"
/>
<FeatureButton
name="HTML"
logo="https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/240px-HTML5_logo_and_wordmark.svg.png"
/>
</div>
</div> */
}

View File

@@ -0,0 +1,74 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
const validator = z.object({
name: z.string().min(1, 'Required'),
});
type IForm = z.infer<typeof validator>;
export default function AddDashboard() {
const { projectId, organizationId: organizationSlug } = useAppParams();
const router = useRouter();
const { register, handleSubmit, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
name: '',
},
});
const mutation = api.dashboard.create.useMutation({
onError: handleError,
onSuccess() {
router.refresh();
toast('Success', {
description: 'Dashboard created.',
});
popModal();
},
});
return (
<ModalContent>
<ModalHeader title="Add dashboard" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit(({ name }) => {
mutation.mutate({
name,
projectId,
organizationSlug,
});
})}
>
<InputWithLabel
label="Name"
placeholder="Name of the dashboard"
{...register('name')}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Create
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,72 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
const validator = z.object({
name: z.string().min(1),
});
type IForm = z.infer<typeof validator>;
interface AddProjectProps {
organizationId: string;
}
export default function AddProject({ organizationId }: AddProjectProps) {
const router = useRouter();
const mutation = api.project.create.useMutation({
onError: handleError,
onSuccess() {
router.refresh();
toast('Success', {
description: 'Project created! Lets create a client for it 🤘',
});
popModal();
},
});
const { register, handleSubmit, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
name: '',
},
});
return (
<ModalContent>
<ModalHeader title="Create project" />
<form
onSubmit={handleSubmit((values) => {
mutation.mutate({
...values,
organizationId,
});
})}
>
<div className="flex flex-col gap-4">
<InputWithLabel
label="Name"
placeholder="Name"
{...register('name')}
/>
</div>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Create
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,68 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { useAppParams } from '@/hooks/useAppParams';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { zCreateReference } from '@mixan/validation';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
type IForm = z.infer<typeof zCreateReference>;
export default function AddReference() {
const { projectId } = useAppParams();
const router = useRouter();
const { register, handleSubmit, formState } = useForm<IForm>({
resolver: zodResolver(zCreateReference),
defaultValues: {
title: '',
description: '',
projectId,
datetime: new Date().toISOString(),
},
});
const mutation = api.reference.create.useMutation({
onError: handleError,
onSuccess() {
router.refresh();
toast('Success', {
description: 'Reference created.',
});
popModal();
},
});
return (
<ModalContent>
<ModalHeader title="Add reference" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit((values) => mutation.mutate(values))}
>
<InputWithLabel label="Title" {...register('title')} />
<InputWithLabel label="Description" {...register('description')} />
<InputWithLabel label="Datetime" {...register('datetime')} />
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Create
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,47 @@
'use client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { Button } from '@/components/ui/button';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
export interface ConfirmProps {
title: string;
text: string;
onConfirm: () => void;
onCancel?: () => void;
}
export default function Confirm({
title,
text,
onConfirm,
onCancel,
}: ConfirmProps) {
return (
<ModalContent>
<ModalHeader title={title} />
<p>{text}</p>
<ButtonContainer>
<Button
variant="outline"
onClick={() => {
popModal('Confirm');
onCancel?.();
}}
>
Cancel
</Button>
<Button
onClick={() => {
popModal('Confirm');
onConfirm();
}}
>
Yes
</Button>
</ButtonContainer>
</ModalContent>
);
}

View File

@@ -0,0 +1,84 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { IServiceClient } from '@mixan/db';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
type EditClientProps = IServiceClient;
const validator = z.object({
id: z.string().min(1),
name: z.string().min(1),
cors: z.string().min(1),
});
type IForm = z.infer<typeof validator>;
export default function EditClient({ id, name, cors }: EditClientProps) {
const router = useRouter();
const { register, handleSubmit, reset, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
id,
name,
cors,
},
});
const mutation = api.client.update.useMutation({
onError: handleError,
onSuccess() {
reset();
toast('Success', {
description: 'Client updated.',
});
popModal();
router.refresh();
},
});
return (
<ModalContent>
<ModalHeader title="Edit client" />
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
})}
>
<div className="flex flex-col gap-4">
<InputWithLabel
label="Name"
placeholder="Name"
{...register('name')}
defaultValue={name}
/>
<InputWithLabel
label="Cors"
placeholder="Cors"
{...register('cors')}
defaultValue={cors}
/>
</div>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Save
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,74 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { IServiceDashboard } from '@mixan/db';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
type EditDashboardProps = Exclude<IServiceDashboard, null>;
const validator = z.object({
id: z.string().min(1),
name: z.string().min(1),
});
type IForm = z.infer<typeof validator>;
export default function EditDashboard({ id, name }: EditDashboardProps) {
const router = useRouter();
const { register, handleSubmit, reset, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
id,
name,
},
});
const mutation = api.dashboard.update.useMutation({
onError: handleError,
onSuccess() {
reset();
toast('Success', {
description: 'Dashboard updated.',
});
popModal();
router.refresh();
},
});
return (
<ModalContent>
<ModalHeader title="Edit dashboard" />
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
})}
>
<InputWithLabel
label="Name"
placeholder="Name"
{...register('name')}
defaultValue={name}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Update
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,74 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { IServiceProject } from '@mixan/db';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
type EditProjectProps = Exclude<IServiceProject, null>;
const validator = z.object({
id: z.string().min(1),
name: z.string().min(1),
});
type IForm = z.infer<typeof validator>;
export default function EditProject({ id, name }: EditProjectProps) {
const router = useRouter();
const { register, handleSubmit, reset, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
id,
name,
},
});
const mutation = api.project.update.useMutation({
onError: handleError,
onSuccess() {
reset();
router.refresh();
toast('Success', {
description: 'Project updated.',
});
popModal();
},
});
return (
<ModalContent>
<ModalHeader title="Edit project" />
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
})}
>
<InputWithLabel
label="Name"
placeholder="Name"
{...register('name')}
defaultValue={name}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Save
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,47 @@
'use client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { zodResolver } from '@hookform/resolvers/zod';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
const validator = z.object({
name: z.string().min(1),
});
type IForm = z.infer<typeof validator>;
interface EditReportProps {
form: IForm;
onSubmit: SubmitHandler<IForm>;
}
export default function EditReport({ form, onSubmit }: EditReportProps) {
const { register, handleSubmit, reset, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: form,
});
return (
<ModalContent>
<ModalHeader title="Edit report" />
<form onSubmit={handleSubmit(onSubmit)}>
<InputWithLabel label="Name" placeholder="Name" {...register('name')} />
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isDirty}>
Update
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,45 @@
'use client';
import { Button } from '@/components/ui/button';
import { X } from 'lucide-react';
import { popModal } from '..';
interface ModalContentProps {
children: React.ReactNode;
}
export function ModalContent({ children }: ModalContentProps) {
return (
<div className="fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 sm:rounded-lg md:w-full">
{children}
</div>
);
}
interface ModalHeaderProps {
title: string | React.ReactNode;
text?: string | React.ReactNode;
onClose?: (() => void) | false;
}
export function ModalHeader({ title, text, onClose }: ModalHeaderProps) {
return (
<div className="flex justify-between mb-6">
<div>
<div className="font-medium mt-0.5">{title}</div>
{!!text && <div className="text-sm text-muted-foreground">{text}</div>}
</div>
{onClose !== false && (
<Button
variant="ghost"
size="sm"
onClick={() => (onClose ? onClose() : popModal())}
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
)}
</div>
);
}

View File

@@ -0,0 +1,139 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import { useAppParams } from '@/hooks/useAppParams';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter, useSearchParams } from 'next/navigation';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { IChartInput } from '@mixan/validation';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
interface SaveReportProps {
report: IChartInput;
reportId?: string;
}
const validator = z.object({
name: z.string().min(1, 'Required'),
dashboardId: z.string().min(1, 'Required'),
});
type IForm = z.infer<typeof validator>;
export default function SaveReport({ report }: SaveReportProps) {
const router = useRouter();
const { organizationId: organizationSlug, projectId } = useAppParams();
const searchParams = useSearchParams();
const dashboardId = searchParams?.get('dashboardId') ?? undefined;
const save = api.report.save.useMutation({
onError: handleError,
onSuccess(res) {
toast('Success', {
description: 'Report saved.',
});
popModal();
router.push(
`/${organizationSlug}/${projectId}/reports/${
res.id
}?${searchParams?.toString()}`
);
},
});
const { register, handleSubmit, formState, control, setValue } =
useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
name: report.name,
dashboardId,
},
});
const dashboardMutation = api.dashboard.create.useMutation({
onError: handleError,
onSuccess(res) {
setValue('dashboardId', res.id);
dashboardQuery.refetch();
toast('Success', {
description: 'Dashboard created.',
});
},
});
const dashboardQuery = api.dashboard.list.useQuery({
projectId,
});
const dashboards = (dashboardQuery.data ?? []).map((item) => ({
value: item.id,
label: item.name,
}));
return (
<ModalContent>
<ModalHeader title="Create report" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit(({ name, ...values }) => {
save.mutate({
report: {
...report,
name,
},
...values,
});
})}
>
<InputWithLabel
label="Report name"
placeholder="Name"
{...register('name')}
defaultValue={report.name}
/>
<Controller
control={control}
name="dashboardId"
render={({ field }) => {
return (
<div>
<Label>Dashboard</Label>
<Combobox
{...field}
items={dashboards}
placeholder="Select a dashboard"
searchable
onCreate={(value) => {
dashboardMutation.mutate({
projectId,
name: value,
organizationSlug,
});
}}
/>
</div>
);
}}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" disabled={!formState.isValid}>
Save
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,97 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useAppParams } from '@/hooks/useAppParams';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { zShareOverview } from '@mixan/validation';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
const validator = zShareOverview;
type IForm = z.infer<typeof validator>;
export default function ShareOverviewModal() {
const { projectId, organizationId: organizationSlug } = useAppParams();
const router = useRouter();
const { register, handleSubmit, formState, control } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
public: true,
password: '',
projectId,
organizationId: organizationSlug,
},
});
const mutation = api.share.shareOverview.useMutation({
onError: handleError,
onSuccess(res) {
router.refresh();
toast('Success', {
description: `Your overview is now ${
res.public ? 'public' : 'private'
}`,
});
popModal();
},
});
return (
<ModalContent>
<ModalHeader title="Overview access" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
})}
>
<Controller
name="public"
control={control}
render={({ field }) => (
<label
htmlFor="public"
className="flex items-center gap-2 text-sm font-medium leading-none mb-4"
>
<Checkbox
id="public"
ref={field.ref}
onBlur={field.onBlur}
defaultChecked={field.value}
onCheckedChange={(checked) => {
field.onChange(checked);
}}
/>
Make it public!
</label>
)}
/>
<InputWithLabel
label="Password"
placeholder="Make your overview accessable with password"
{...register('password')}
/>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
</Button>
<Button type="submit" loading={mutation.isLoading}>
Update
</Button>
</ButtonContainer>
</form>
</ModalContent>
);
}

View File

@@ -0,0 +1,224 @@
'use client';
import { Suspense, useEffect, useRef, useState } from 'react';
import { Loader } from 'lucide-react';
import mitt from 'mitt';
import dynamic from 'next/dynamic';
import { useOnClickOutside } from 'usehooks-ts';
import type { ConfirmProps } from './Confirm';
const Loading = () => (
<div className="fixed left-0 top-0 z-50 flex h-screen w-screen items-center justify-center overflow-auto bg-backdrop">
<Loader className="mb-8 animate-spin" size={40} />
</div>
);
const modals = {
EditProject: dynamic(() => import('./EditProject'), {
loading: Loading,
}),
EditClient: dynamic(() => import('./EditClient'), {
loading: Loading,
}),
AddProject: dynamic(() => import('./AddProject'), {
loading: Loading,
}),
AddClient: dynamic(() => import('./AddClient'), {
loading: Loading,
}),
Confirm: dynamic(() => import('./Confirm'), {
loading: Loading,
}),
SaveReport: dynamic(() => import('./SaveReport'), {
loading: Loading,
}),
AddDashboard: dynamic(() => import('./AddDashboard'), {
loading: Loading,
}),
EditDashboard: dynamic(() => import('./EditDashboard'), {
loading: Loading,
}),
EditReport: dynamic(() => import('./EditReport'), {
loading: Loading,
}),
ShareOverviewModal: dynamic(() => import('./ShareOverviewModal'), {
loading: Loading,
}),
AddReference: dynamic(() => import('./AddReference'), {
loading: Loading,
}),
};
const emitter = mitt<{
push: {
name: ModalRoutes;
props: Record<string, unknown>;
};
replace: {
name: ModalRoutes;
props: Record<string, unknown>;
};
pop: { name?: ModalRoutes };
unshift: { name: ModalRoutes };
}>();
type ModalRoutes = keyof typeof modals;
interface StateItem {
key: string;
name: ModalRoutes;
props: Record<string, unknown>;
}
interface ModalWrapperProps {
children: React.ReactNode;
name?: ModalRoutes;
isOnTop?: boolean;
}
export function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) {
const ref = useRef<HTMLDivElement>(null);
useOnClickOutside(ref, (event) => {
const target = event.target as HTMLElement;
const isPortal =
typeof target.closest === 'function'
? !!target.closest('[data-radix-popper-content-wrapper]')
: false;
if (isOnTop && !isPortal && name) {
emitter.emit('pop', {
name,
});
}
});
return (
<div className="fixed top-0 z-50 flex h-screen w-screen items-center justify-center overflow-auto">
<div ref={ref} className="w-inherit m-auto py-4">
<Suspense>{children}</Suspense>
</div>
</div>
);
}
export function ModalProvider() {
const [state, setState] = useState<StateItem[]>([]);
useEffect(() => {
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && state.length > 0) {
setState((p) => {
p.pop();
return [...p];
});
}
});
}, [state]);
useEffect(() => {
emitter.on('push', ({ name, props }) => {
setState((p) => [
...p,
{
key: Math.random().toString(),
name,
props,
},
]);
});
emitter.on('replace', ({ name, props }) => {
setState([
{
key: Math.random().toString(),
name,
props,
},
]);
});
emitter.on('pop', ({ name }) => {
setState((items) => {
const match =
name === undefined
? // Pick last item if no name is provided
items.length - 1
: items.findLastIndex((item) => item.name === name);
return items.filter((_, index) => index !== match);
});
});
emitter.on('unshift', ({ name }) => {
setState((items) => {
const match = items.findIndex((item) => item.name === name);
return items.filter((_, index) => index !== match);
});
});
return () => emitter.all.clear();
});
return (
<>
{!!state.length && (
<div className="fixed top-0 left-0 right-0 bottom-0 bg-[rgba(0,0,0,0.2)] z-50"></div>
)}
{state.map((item, index) => {
const Modal = modals[item.name];
return (
<ModalWrapper
key={item.key}
name={item.name}
isOnTop={state.length - 1 === index}
>
{/* @ts-expect-error */}
<Modal {...item.props} />
</ModalWrapper>
);
})}
</>
);
}
type GetComponentProps<T> = T extends
| React.ComponentType<infer P>
| React.Component<infer P>
? P
: never;
type OrUndefined<T> = T extends Record<string, never> ? undefined : T;
export const pushModal = <
T extends StateItem['name'],
B extends OrUndefined<GetComponentProps<(typeof modals)[T]>>,
>(
name: T,
...rest: B extends undefined ? [] : [B]
) =>
emitter.emit('push', {
name,
// @ts-expect-error
props: Array.isArray(rest) && rest[0] ? rest[0] : {},
});
export const replaceModal = <
T extends StateItem['name'],
B extends OrUndefined<GetComponentProps<(typeof modals)[T]>>,
>(
name: T,
...rest: B extends undefined ? [] : [B]
) =>
emitter.emit('replace', {
name,
// @ts-expect-error
props: Array.isArray(rest) && rest[0] ? rest[0] : {},
});
export const popModal = (name?: StateItem['name']) =>
emitter.emit('pop', {
name,
});
export const unshiftModal = (name: StateItem['name']) =>
emitter.emit('unshift', {
name,
});
export const showConfirm = (props: ConfirmProps) => pushModal('Confirm', props);