ADD CROSS DOMAIN SUPPORT

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-06-26 22:35:29 +02:00
parent a0c8199474
commit 41143ca5f8
26 changed files with 514 additions and 126 deletions

View File

@@ -33,6 +33,10 @@ export function EventDetails({ event, open, setOpen }: Props) {
const [, setEvents] = useEventQueryNamesFilter({ shallow: false });
const common = [
{
name: 'Origin',
value: event.origin,
},
{
name: 'Duration',
value: event.duration ? round(event.duration / 1000, 1) : undefined,
@@ -154,7 +158,7 @@ export function EventDetails({ event, open, setOpen }: Props) {
{properties.map((item) => (
<KeyValue
key={item.name}
name={item.name}
name={item.name.replace(/^__/, '')}
value={item.value}
onClick={() => {
setFilter(

View File

@@ -83,9 +83,9 @@ export default function ListProjects({ projects, clients }: ListProjectsProps) {
Client ID: ...{item.id.slice(-12)}
</Tooltiper>
<div className="text-muted-foreground">
{item.secret
? 'Secret: Hidden'
: `Website: ${item.cors}`}
{item.cors &&
item.cors !== '*' &&
`Website: ${item.cors}`}
</div>
<div className="absolute right-4 top-4">
<ClientActions {...item} />

View File

@@ -1,7 +1,7 @@
'use client';
import { ButtonContainer } from '@/components/button-container';
import { InputWithLabel } from '@/components/forms/input-with-label';
import CopyInput from '@/components/forms/copy-input';
import { LinkButton } from '@/components/ui/button';
import { useClientSecret } from '@/hooks/useClientSecret';
import { LockIcon } from 'lucide-react';
@@ -36,13 +36,13 @@ const Connect = ({ project }: Props) => {
</OnboardingDescription>
}
>
<div className="bg-def-200 flex flex-col gap-4 rounded-xl border p-4 md:p-6">
<div className="flex flex-col gap-4 rounded-xl border p-4 md:p-6">
<div className="flex items-center gap-2 text-2xl capitalize">
<LockIcon />
Credentials
</div>
<InputWithLabel label="Client ID" disabled value={client.id} />
<InputWithLabel label="Client Secret" disabled value={secret} />
<CopyInput label="Client ID" value={client.id} />
<CopyInput label="Secret" value={secret} />
</div>
{project.types.map((type) => {
const Component = {

View File

@@ -1,5 +1,3 @@
import { cookies } from 'next/headers';
import { getCurrentOrganizations, getProjectWithClients } from '@openpanel/db';
import OnboardingConnect from './onboarding-connect';

View File

@@ -4,7 +4,8 @@ import { useEffect } from 'react';
import AnimateHeight from '@/components/animate-height';
import { ButtonContainer } from '@/components/button-container';
import { CheckboxItem } from '@/components/forms/checkbox-item';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import TagInput from '@/components/forms/tag-input';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
@@ -155,11 +156,41 @@ const Tracking = ({
>
<AnimateHeight open={isWebsite && !isApp}>
<div className="p-4 pl-14">
<InputWithLabel
label="Domain"
placeholder="https://example.com"
error={form.formState.errors.domain?.message}
{...form.register('domain')}
<Controller
name="domain"
control={form.control}
render={({ field }) => (
<WithLabel
label="Domain(s)"
error={form.formState.errors.domain?.message}
>
<TagInput
{...field}
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) =>
tag === '*' ? 'Allow domains' : tag
}
onChange={(newValue) => {
field.onChange(
newValue
.map((item) => {
const trimmed = item.trim();
if (
trimmed.startsWith('http://') ||
trimmed.startsWith('https://') ||
trimmed === '*'
) {
return trimmed;
}
return `https://${trimmed}`;
})
.join(',')
);
}}
/>
</WithLabel>
)}
/>
</div>
</AnimateHeight>

View File

@@ -1,9 +1,9 @@
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { clipboard } from '@/utils/clipboard';
import { Copy, RocketIcon } from 'lucide-react';
import { RocketIcon } from 'lucide-react';
import type { IServiceClient } from '@openpanel/db';
import CopyInput from '../forms/copy-input';
import { Label } from '../ui/label';
type Props = IServiceClient;
@@ -11,25 +11,10 @@ type Props = IServiceClient;
export function CreateClientSuccess({ id, secret, cors }: Props) {
return (
<div className="grid gap-4">
<button className="text-left" onClick={() => clipboard(id)}>
<Label>Client ID</Label>
<div className="flex items-center justify-between rounded border-input bg-background p-2 px-3 font-mono text-sm">
{id}
<Copy size={16} />
</div>
</button>
<CopyInput label="Client ID" value={id} />
{secret && (
<div className="w-full">
<button
className="w-full text-left"
onClick={() => clipboard(secret)}
>
<Label>Client secret</Label>
<div className="flex items-center justify-between rounded border-input bg-background p-2 px-3 font-mono text-sm">
{secret}
<Copy size={16} />
</div>
</button>
<CopyInput label="Secret" value={secret} />
{cors && (
<p className="mt-1 text-xs text-muted-foreground">
You will only need the secret if you want to send server events.
@@ -40,7 +25,7 @@ export function CreateClientSuccess({ id, secret, cors }: Props) {
{cors && (
<div className="text-left">
<Label>CORS settings</Label>
<div className="flex items-center justify-between rounded border-input bg-background p-2 px-3 font-mono text-sm">
<div className="flex items-center justify-between rounded border-input bg-def-200 p-2 px-3 font-mono text-sm">
{cors}
</div>
</div>

View File

@@ -0,0 +1,28 @@
import { clipboard } from '@/utils/clipboard';
import { cn } from '@/utils/cn';
import { CopyIcon } from 'lucide-react';
import { Label } from '../ui/label';
type Props = {
label: React.ReactNode;
value: string;
className?: string;
};
const CopyInput = ({ label, value, className }: Props) => {
return (
<button
className={cn('w-full text-left', className)}
onClick={() => clipboard(value)}
>
{!!label && <Label>{label}</Label>}
<div className="flex items-center justify-between rounded border-input bg-def-200 p-2 px-3 font-mono text-sm">
{value}
<CopyIcon size={16} />
</div>
</button>
);
};
export default CopyInput;

View File

@@ -6,39 +6,56 @@ import type { InputProps } from '../ui/input';
import { Label } from '../ui/label';
import { Tooltiper } from '../ui/tooltip';
type InputWithLabelProps = InputProps & {
type WithLabel = {
children: React.ReactNode;
label: string;
error?: string | undefined;
info?: string;
className?: string;
};
type InputWithLabelProps = InputProps & Omit<WithLabel, 'children'>;
export const WithLabel = ({
children,
className,
label,
info,
error,
}: WithLabel) => {
return (
<div className={className}>
<div className="mb-2 flex items-end justify-between">
<Label
className="mb-0 flex flex-1 shrink-0 items-center gap-1 whitespace-nowrap"
htmlFor={label}
>
{label}
{info && (
<Tooltiper content={info}>
<InfoIcon size={14} />
</Tooltiper>
)}
</Label>
{error && (
<Tooltiper asChild content={error}>
<div className="flex items-center gap-1 text-sm leading-none text-destructive">
Issues
<BanIcon size={14} />
</div>
</Tooltiper>
)}
</div>
{children}
</div>
);
};
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
({ label, className, info, ...props }, ref) => {
(props, ref) => {
return (
<div className={className}>
<div className="mb-2 flex items-end justify-between">
<Label
className="mb-0 flex flex-1 shrink-0 items-center gap-1 whitespace-nowrap"
htmlFor={label}
>
{label}
{info && (
<Tooltiper content={info}>
<InfoIcon size={14} />
</Tooltiper>
)}
</Label>
{props.error && (
<Tooltiper asChild content={props.error}>
<div className="flex items-center gap-1 text-sm leading-none text-destructive">
Issues
<BanIcon size={14} />
</div>
</Tooltiper>
)}
</div>
<Input ref={ref} id={label} {...props} />
</div>
<WithLabel {...props}>
<Input ref={ref} id={props.label} {...props} />
</WithLabel>
);
}
);

View File

@@ -0,0 +1,139 @@
// Based on Christin Alares tag input component (https://github.com/christianalares/seventy-seven)
import type { ElementRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { cn } from '@/utils/cn';
import { useAnimate } from 'framer-motion';
import { XIcon } from 'lucide-react';
type Props = {
placeholder: string;
value: string[];
error?: string;
className?: string;
onChange: (value: string[]) => void;
renderTag?: (tag: string) => string;
};
const TagInput = ({
value: propValue,
onChange,
renderTag,
placeholder,
error,
}: Props) => {
const value = (
Array.isArray(propValue) ? propValue : propValue ? [propValue] : []
).filter(Boolean);
const [isMarkedForDeletion, setIsMarkedForDeletion] = useState(false);
const inputRef = useRef<ElementRef<'input'>>(null);
const [inputValue, setInputValue] = useState('');
const [scope, animate] = useAnimate();
const appendTag = (tag: string) => {
onChange([...value, tag]);
};
const removeTag = (tag: string) => {
onChange(value.filter((t) => t !== tag));
inputRef.current?.focus();
};
useEffect(() => {
if (inputValue.length > 0) {
setIsMarkedForDeletion(false);
}
}, [inputValue]);
return (
<div
ref={scope}
className={cn(
'inline-flex w-full flex-wrap items-center gap-2 rounded-md border border-input p-1 px-3 ring-offset-background has-[input:focus]:ring-2 has-[input:focus]:ring-ring has-[input:focus]:ring-offset-1',
!!error && 'border-destructive'
)}
>
{value.map((tag, i) => {
const isCreating = false;
return (
<span
data-tag={tag}
key={tag}
className={cn(
'inline-flex items-center gap-2 rounded bg-def-200 px-2 py-1 text-sm',
isMarkedForDeletion &&
i === value.length - 1 &&
'bg-destructive-foreground ring-2 ring-destructive/50 ring-offset-1',
isCreating && 'opacity-60'
)}
>
{renderTag ? renderTag(tag) : tag}
<Button
size="icon"
variant="outline"
className="h-4 w-4 rounded-full"
onClick={() => removeTag(tag)}
>
<span className="sr-only">Remove tag</span>
<XIcon name="close" className="size-3" />
</Button>
</span>
);
})}
<input
ref={inputRef}
placeholder={`${placeholder}`}
className="min-w-20 flex-1 py-1 text-sm focus-visible:outline-none"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
const tagAlreadyExists = value.some(
(tag) => tag.toLowerCase() === inputValue.toLowerCase()
);
if (inputValue) {
if (tagAlreadyExists) {
animate(
`span[data-tag="${inputValue.toLowerCase()}"]`,
{
scale: [1, 1.3, 1],
},
{
duration: 0.3,
}
);
return;
}
appendTag(inputValue);
setInputValue('');
}
}
if (e.key === 'Backspace' && inputValue === '') {
if (!isMarkedForDeletion) {
setIsMarkedForDeletion(true);
return;
}
const last = value[value.length - 1];
if (last) {
removeTag(last);
}
setIsMarkedForDeletion(false);
setInputValue('');
}
}}
/>
</div>
);
};
export default TagInput;

View File

@@ -12,7 +12,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
'block h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
className
)}
{...props}
@@ -29,9 +29,14 @@ Checkbox.displayName = CheckboxPrimitive.Root.displayName;
const CheckboxInput = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>((props, ref) => (
<label className="flex min-h-10 cursor-pointer select-none items-center gap-4 rounded-md border border-border px-3">
<Checkbox ref={ref} {...props} />
>(({ className, ...props }, ref) => (
<label
className={cn(
'flex min-h-10 cursor-pointer select-none gap-4 rounded-md border border-border px-3 py-[0.5rem]',
className
)}
>
<Checkbox ref={ref} {...props} className="relative top-0.5" />
<div className="text-sm font-medium">{props.children}</div>
</label>
));

View File

@@ -20,10 +20,10 @@ export function KeyValue({ href, onClick, name, value }: KeyValueProps) {
)}
{...{ href, onClick }}
>
<div className="bg-black/5 p-1 px-2">{name}</div>
<div className="bg-black/5 p-1 px-2 capitalize">{name}</div>
<div
className={cn(
'text-highlight overflow-hidden text-ellipsis whitespace-nowrap bg-card p-1 px-2 font-mono',
'overflow-hidden text-ellipsis whitespace-nowrap bg-card p-1 px-2 font-mono text-highlight',
clickable && 'group-hover:underline'
)}
>

View File

@@ -3,7 +3,9 @@
import { useState } from 'react';
import AnimateHeight from '@/components/animate-height';
import { CreateClientSuccess } from '@/components/clients/create-client-success';
import TagInput from '@/components/forms/tag-input';
import { Button, buttonVariants } from '@/components/ui/button';
import { CheckboxInput } from '@/components/ui/checkbox';
import { Combobox } from '@/components/ui/combobox';
import { DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
@@ -25,9 +27,10 @@ import { ModalContent, ModalHeader } from './Modal/Container';
const validation = z.object({
name: z.string().min(1),
cors: z.string().url().or(z.literal('')),
cors: z.string().min(1).or(z.literal('')),
projectId: z.string(),
type: z.enum(['read', 'write', 'root']),
crossDomain: z.boolean().optional(),
});
type IForm = z.infer<typeof validation>;
@@ -45,6 +48,7 @@ export default function AddClient(props: Props) {
cors: '',
projectId: props.projectId ?? projectId,
type: 'write',
crossDomain: undefined,
},
});
const [hasDomain, setHasDomain] = useState(true);
@@ -59,12 +63,19 @@ export default function AddClient(props: Props) {
organizationSlug,
});
const onSubmit: SubmitHandler<IForm> = (values) => {
if (hasDomain && values.cors === '') {
return form.setError('cors', {
type: 'required',
message: 'Please add a domain',
});
}
mutation.mutate({
name: values.name,
cors: hasDomain ? values.cors : null,
projectId: values.projectId,
organizationSlug,
type: values.type,
crossDomain: values.crossDomain,
});
};
@@ -132,14 +143,59 @@ export default function AddClient(props: Props) {
<div>
<Label className="flex items-center justify-between">
<span>Domain</span>
<span>Domain(s)</span>
<Switch checked={hasDomain} onCheckedChange={setHasDomain} />
</Label>
<AnimateHeight open={hasDomain}>
<Input
placeholder="https://example.com"
error={form.formState.errors.cors?.message}
{...form.register('cors')}
<Controller
name="cors"
control={form.control}
render={({ field }) => (
<TagInput
{...field}
error={form.formState.errors.cors?.message}
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) => (tag === '*' ? 'Allow domains' : tag)}
onChange={(newValue) => {
field.onChange(
newValue
.map((item) => {
const trimmed = item.trim();
if (
trimmed.startsWith('http://') ||
trimmed.startsWith('https://') ||
trimmed === '*'
) {
return trimmed;
}
return `https://${trimmed}`;
})
.join(',')
);
}}
/>
)}
/>
<Controller
name="crossDomain"
control={form.control}
render={({ field }) => {
return (
<CheckboxInput
className="mt-4"
ref={field.ref}
onBlur={field.onBlur}
defaultChecked={field.value}
onCheckedChange={field.onChange}
>
<div>Enable cross domain support</div>
<div className="font-normal text-muted-foreground">
This will let you track users across multiple domains
</div>
</CheckboxInput>
);
}}
/>
</AnimateHeight>
</div>

View File

@@ -1,10 +1,12 @@
import { ButtonContainer } from '@/components/button-container';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import TagInput from '@/components/forms/tag-input';
import { Button } from '@/components/ui/button';
import { CheckboxInput } from '@/components/ui/checkbox';
import { api, handleError } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
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';
@@ -19,20 +21,28 @@ const validator = z.object({
id: z.string().min(1),
name: z.string().min(1),
cors: z.string().nullable(),
crossDomain: z.boolean().optional(),
});
type IForm = z.infer<typeof validator>;
export default function EditClient({ id, name, cors }: EditClientProps) {
export default function EditClient({
id,
name,
cors,
crossDomain,
}: EditClientProps) {
const router = useRouter();
const { register, handleSubmit, reset, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
id,
name,
cors,
},
});
const { register, handleSubmit, reset, formState, control, setError } =
useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
id,
name,
cors,
crossDomain,
},
});
const mutation = api.client.update.useMutation({
onError: handleError,
@@ -51,6 +61,13 @@ export default function EditClient({ id, name, cors }: EditClientProps) {
<ModalHeader title="Edit client" />
<form
onSubmit={handleSubmit((values) => {
if (!values.cors) {
return setError('cors', {
type: 'required',
message: 'Please add a domain',
});
}
mutation.mutate(values);
})}
>
@@ -60,10 +77,61 @@ export default function EditClient({ id, name, cors }: EditClientProps) {
placeholder="Name"
{...register('name')}
/>
<InputWithLabel
label="Cors"
placeholder="Cors"
{...register('cors')}
<Controller
name="cors"
control={control}
render={({ field }) => (
<WithLabel
label="Domain(s)"
error={formState.errors.cors?.message}
>
<TagInput
{...field}
error={formState.errors.cors?.message}
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) => (tag === '*' ? 'Allow domains' : tag)}
onChange={(newValue) => {
field.onChange(
newValue
.map((item) => {
const trimmed = item.trim();
if (
trimmed.startsWith('http://') ||
trimmed.startsWith('https://') ||
trimmed === '*'
) {
return trimmed;
}
return `https://${trimmed}`;
})
.join(',')
);
}}
/>
</WithLabel>
)}
/>
<Controller
name="crossDomain"
control={control}
render={({ field }) => {
return (
<CheckboxInput
ref={field.ref}
onBlur={field.onBlur}
defaultChecked={field.value}
onCheckedChange={field.onChange}
>
<div>Enable cross domain support</div>
<div className="font-normal text-muted-foreground">
This will let you track users across multiple domains
</div>
</CheckboxInput>
);
}}
/>
</div>
<ButtonContainer>