mirror of
https://github.com/fosrl/pangolin.git
synced 2026-04-15 22:36:37 +00:00
Merge branch 'dev' into private-site-ha
This commit is contained in:
@@ -1,56 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import IdpAutoProvisionUsersDescription from "@app/components/IdpAutoProvisionUsersDescription";
|
||||
import { FormDescription } from "@app/components/ui/form";
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { RadioGroup, RadioGroupItem } from "@app/components/ui/radio-group";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from "@app/components/ui/select";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Control, FieldValues, Path } from "react-hook-form";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { MappingBuilderRule, RoleMappingMode } from "@app/lib/idpRoleMapping";
|
||||
import RoleMappingConfigFields from "@app/components/RoleMappingConfigFields";
|
||||
|
||||
type Role = {
|
||||
roleId: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type AutoProvisionConfigWidgetProps<T extends FieldValues> = {
|
||||
control: Control<T>;
|
||||
type AutoProvisionConfigWidgetProps = {
|
||||
autoProvision: boolean;
|
||||
onAutoProvisionChange: (checked: boolean) => void;
|
||||
roleMappingMode: "role" | "expression";
|
||||
onRoleMappingModeChange: (mode: "role" | "expression") => void;
|
||||
roleMappingMode: RoleMappingMode;
|
||||
onRoleMappingModeChange: (mode: RoleMappingMode) => void;
|
||||
roles: Role[];
|
||||
roleIdFieldName: Path<T>;
|
||||
roleMappingFieldName: Path<T>;
|
||||
fixedRoleNames: string[];
|
||||
onFixedRoleNamesChange: (roleNames: string[]) => void;
|
||||
mappingBuilderClaimPath: string;
|
||||
onMappingBuilderClaimPathChange: (claimPath: string) => void;
|
||||
mappingBuilderRules: MappingBuilderRule[];
|
||||
onMappingBuilderRulesChange: (rules: MappingBuilderRule[]) => void;
|
||||
rawExpression: string;
|
||||
onRawExpressionChange: (expression: string) => void;
|
||||
};
|
||||
|
||||
export default function AutoProvisionConfigWidget<T extends FieldValues>({
|
||||
control,
|
||||
export default function AutoProvisionConfigWidget({
|
||||
autoProvision,
|
||||
onAutoProvisionChange,
|
||||
roleMappingMode,
|
||||
onRoleMappingModeChange,
|
||||
roles,
|
||||
roleIdFieldName,
|
||||
roleMappingFieldName
|
||||
}: AutoProvisionConfigWidgetProps<T>) {
|
||||
fixedRoleNames,
|
||||
onFixedRoleNamesChange,
|
||||
mappingBuilderClaimPath,
|
||||
onMappingBuilderClaimPathChange,
|
||||
mappingBuilderRules,
|
||||
onMappingBuilderRulesChange,
|
||||
rawExpression,
|
||||
onRawExpressionChange
|
||||
}: AutoProvisionConfigWidgetProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
|
||||
return (
|
||||
@@ -63,114 +58,26 @@ export default function AutoProvisionConfigWidget<T extends FieldValues>({
|
||||
onCheckedChange={onAutoProvisionChange}
|
||||
disabled={!isPaidUser(tierMatrix.autoProvisioning)}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("idpAutoProvisionUsersDescription")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{autoProvision && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<FormLabel className="mb-2">
|
||||
{t("roleMapping")}
|
||||
</FormLabel>
|
||||
<FormDescription className="mb-4">
|
||||
{t("roleMappingDescription")}
|
||||
</FormDescription>
|
||||
|
||||
<RadioGroup
|
||||
value={roleMappingMode}
|
||||
onValueChange={onRoleMappingModeChange}
|
||||
className="flex space-x-6"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="role" id="role-mode" />
|
||||
<label
|
||||
htmlFor="role-mode"
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{t("selectRole")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="expression"
|
||||
id="expression-mode"
|
||||
/>
|
||||
<label
|
||||
htmlFor="expression-mode"
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{t("roleMappingExpression")}
|
||||
</label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{roleMappingMode === "role" ? (
|
||||
<FormField
|
||||
control={control}
|
||||
name={roleIdFieldName}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<Select
|
||||
onValueChange={(value) =>
|
||||
field.onChange(Number(value))
|
||||
}
|
||||
value={field.value?.toString()}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue
|
||||
placeholder={t(
|
||||
"selectRolePlaceholder"
|
||||
)}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{roles.map((role) => (
|
||||
<SelectItem
|
||||
key={role.roleId}
|
||||
value={role.roleId.toString()}
|
||||
>
|
||||
{role.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
{t("selectRoleDescription")}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<FormField
|
||||
control={control}
|
||||
name={roleMappingFieldName}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
defaultValue={field.value || ""}
|
||||
value={field.value || ""}
|
||||
placeholder={t(
|
||||
"roleMappingExpressionPlaceholder"
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("roleMappingExpressionDescription")}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<RoleMappingConfigFields
|
||||
fieldIdPrefix="org-idp-auto-provision"
|
||||
showFreeformRoleNamesHint={false}
|
||||
roleMappingMode={roleMappingMode}
|
||||
onRoleMappingModeChange={onRoleMappingModeChange}
|
||||
roles={roles}
|
||||
fixedRoleNames={fixedRoleNames}
|
||||
onFixedRoleNamesChange={onFixedRoleNamesChange}
|
||||
mappingBuilderClaimPath={mappingBuilderClaimPath}
|
||||
onMappingBuilderClaimPathChange={
|
||||
onMappingBuilderClaimPathChange
|
||||
}
|
||||
mappingBuilderRules={mappingBuilderRules}
|
||||
onMappingBuilderRulesChange={onMappingBuilderRulesChange}
|
||||
rawExpression={rawExpression}
|
||||
onRawExpressionChange={onRawExpressionChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -154,7 +154,7 @@ export default function CreateDomainForm({
|
||||
|
||||
const punycodePreview = useMemo(() => {
|
||||
if (!baseDomain) return "";
|
||||
const punycode = toPunycode(baseDomain);
|
||||
const punycode = toPunycode(baseDomain.toLowerCase());
|
||||
return punycode !== baseDomain.toLowerCase() ? punycode : "";
|
||||
}, [baseDomain]);
|
||||
|
||||
@@ -239,21 +239,24 @@ export default function CreateDomainForm({
|
||||
className="space-y-4"
|
||||
id="create-domain-form"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<StrategySelect
|
||||
options={domainOptions}
|
||||
defaultValue={field.value}
|
||||
onChange={field.onChange}
|
||||
cols={1}
|
||||
/>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{build != "oss" && env.flags.usePangolinDns ? (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<StrategySelect
|
||||
options={domainOptions}
|
||||
defaultValue={field.value}
|
||||
onChange={field.onChange}
|
||||
cols={1}
|
||||
/>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="baseDomain"
|
||||
|
||||
@@ -69,6 +69,7 @@ import {
|
||||
import AccessTokenSection from "@app/components/AccessTokenUsage";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { toUnicode } from "punycode";
|
||||
import { ResourceSelector, type SelectedResource } from "./resource-selector";
|
||||
|
||||
type FormProps = {
|
||||
open: boolean;
|
||||
@@ -99,18 +100,21 @@ export default function CreateShareLinkForm({
|
||||
orgQueries.resources({ orgId: org?.org.orgId ?? "" })
|
||||
);
|
||||
|
||||
const resources = useMemo(
|
||||
() =>
|
||||
allResources
|
||||
.filter((r) => r.http)
|
||||
.map((r) => ({
|
||||
resourceId: r.resourceId,
|
||||
name: r.name,
|
||||
niceId: r.niceId,
|
||||
resourceUrl: `${r.ssl ? "https://" : "http://"}${toUnicode(r.fullDomain || "")}/`
|
||||
})),
|
||||
[allResources]
|
||||
);
|
||||
const [selectedResource, setSelectedResource] =
|
||||
useState<SelectedResource | null>(null);
|
||||
|
||||
// const resources = useMemo(
|
||||
// () =>
|
||||
// allResources
|
||||
// .filter((r) => r.http)
|
||||
// .map((r) => ({
|
||||
// resourceId: r.resourceId,
|
||||
// name: r.name,
|
||||
// niceId: r.niceId,
|
||||
// resourceUrl: `${r.ssl ? "https://" : "http://"}${toUnicode(r.fullDomain || "")}/`
|
||||
// })),
|
||||
// [allResources]
|
||||
// );
|
||||
|
||||
const formSchema = z.object({
|
||||
resourceId: z.number({ message: t("shareErrorSelectResource") }),
|
||||
@@ -199,15 +203,11 @@ export default function CreateShareLinkForm({
|
||||
setAccessToken(token.accessToken);
|
||||
setAccessTokenId(token.accessTokenId);
|
||||
|
||||
const resource = resources.find(
|
||||
(r) => r.resourceId === values.resourceId
|
||||
);
|
||||
|
||||
onCreated?.({
|
||||
accessTokenId: token.accessTokenId,
|
||||
resourceId: token.resourceId,
|
||||
resourceName: values.resourceName,
|
||||
resourceNiceId: resource ? resource.niceId : "",
|
||||
resourceNiceId: selectedResource ? selectedResource.niceId : "",
|
||||
title: token.title,
|
||||
createdAt: token.createdAt,
|
||||
expiresAt: token.expiresAt
|
||||
@@ -217,11 +217,6 @@ export default function CreateShareLinkForm({
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
function getSelectedResourceName(id: number) {
|
||||
const resource = resources.find((r) => r.resourceId === id);
|
||||
return `${resource?.name}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Credenza
|
||||
@@ -241,7 +236,7 @@ export default function CreateShareLinkForm({
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-y-4 px-1">
|
||||
{!link && (
|
||||
<Form {...form}>
|
||||
<form
|
||||
@@ -269,10 +264,8 @@ export default function CreateShareLinkForm({
|
||||
"text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{field.value
|
||||
? getSelectedResourceName(
|
||||
field.value
|
||||
)
|
||||
{selectedResource?.name
|
||||
? selectedResource.name
|
||||
: t(
|
||||
"resourceSelect"
|
||||
)}
|
||||
@@ -281,59 +274,34 @@ export default function CreateShareLinkForm({
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0">
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder={t(
|
||||
"resourceSearch"
|
||||
)}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{t(
|
||||
"resourcesNotFound"
|
||||
)}
|
||||
</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{resources.map(
|
||||
(
|
||||
r
|
||||
) => (
|
||||
<CommandItem
|
||||
value={`${r.name}:${r.resourceId}`}
|
||||
key={
|
||||
r.resourceId
|
||||
}
|
||||
onSelect={() => {
|
||||
form.setValue(
|
||||
"resourceId",
|
||||
r.resourceId
|
||||
);
|
||||
form.setValue(
|
||||
"resourceName",
|
||||
r.name
|
||||
);
|
||||
form.setValue(
|
||||
"resourceUrl",
|
||||
r.resourceUrl
|
||||
);
|
||||
}}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
r.resourceId ===
|
||||
field.value
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{`${r.name}`}
|
||||
</CommandItem>
|
||||
)
|
||||
)}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
<ResourceSelector
|
||||
orgId={
|
||||
org.org
|
||||
.orgId
|
||||
}
|
||||
selectedResource={
|
||||
selectedResource
|
||||
}
|
||||
onSelectResource={(
|
||||
r
|
||||
) => {
|
||||
form.setValue(
|
||||
"resourceId",
|
||||
r.resourceId
|
||||
);
|
||||
form.setValue(
|
||||
"resourceName",
|
||||
r.name
|
||||
);
|
||||
form.setValue(
|
||||
"resourceUrl",
|
||||
`${r.ssl ? "https://" : "http://"}${toUnicode(r.fullDomain || "")}/`
|
||||
);
|
||||
setSelectedResource(
|
||||
r
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
|
||||
427
src/components/CreateSiteProvisioningKeyCredenza.tsx
Normal file
427
src/components/CreateSiteProvisioningKeyCredenza.tsx
Normal file
@@ -0,0 +1,427 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Credenza,
|
||||
CredenzaBody,
|
||||
CredenzaClose,
|
||||
CredenzaContent,
|
||||
CredenzaDescription,
|
||||
CredenzaFooter,
|
||||
CredenzaHeader,
|
||||
CredenzaTitle
|
||||
} from "@app/components/Credenza";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { CreateSiteProvisioningKeyResponse } from "@server/routers/siteProvisioning/types";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import CopyTextBox from "@app/components/CopyTextBox";
|
||||
import {
|
||||
DateTimePicker,
|
||||
DateTimeValue
|
||||
} from "@app/components/DateTimePicker";
|
||||
|
||||
const FORM_ID = "create-site-provisioning-key-form";
|
||||
|
||||
type CreateSiteProvisioningKeyCredenzaProps = {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
orgId: string;
|
||||
};
|
||||
|
||||
export default function CreateSiteProvisioningKeyCredenza({
|
||||
open,
|
||||
setOpen,
|
||||
orgId
|
||||
}: CreateSiteProvisioningKeyCredenzaProps) {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [created, setCreated] =
|
||||
useState<CreateSiteProvisioningKeyResponse | null>(null);
|
||||
|
||||
const createFormSchema = z
|
||||
.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(1, {
|
||||
message: t("nameMin", { len: 1 })
|
||||
})
|
||||
.max(255, {
|
||||
message: t("nameMax", { len: 255 })
|
||||
}),
|
||||
unlimitedBatchSize: z.boolean(),
|
||||
maxBatchSize: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1, { message: t("provisioningKeysMaxBatchSizeInvalid") })
|
||||
.max(1_000_000, {
|
||||
message: t("provisioningKeysMaxBatchSizeInvalid")
|
||||
}),
|
||||
validUntil: z.string().optional(),
|
||||
approveNewSites: z.boolean()
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
const v = data.validUntil;
|
||||
if (v == null || v.trim() === "") {
|
||||
return;
|
||||
}
|
||||
if (Number.isNaN(Date.parse(v))) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: t("provisioningKeysValidUntilInvalid"),
|
||||
path: ["validUntil"]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type CreateFormValues = z.infer<typeof createFormSchema>;
|
||||
|
||||
const form = useForm<CreateFormValues>({
|
||||
resolver: zodResolver(createFormSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
unlimitedBatchSize: false,
|
||||
maxBatchSize: 100,
|
||||
validUntil: "",
|
||||
approveNewSites: true
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setCreated(null);
|
||||
form.reset({
|
||||
name: "",
|
||||
unlimitedBatchSize: false,
|
||||
maxBatchSize: 100,
|
||||
validUntil: "",
|
||||
approveNewSites: true
|
||||
});
|
||||
}
|
||||
}, [open, form]);
|
||||
|
||||
async function onSubmit(data: CreateFormValues) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api
|
||||
.put<AxiosResponse<CreateSiteProvisioningKeyResponse>>(
|
||||
`/org/${orgId}/site-provisioning-key`,
|
||||
{
|
||||
name: data.name,
|
||||
maxBatchSize: data.unlimitedBatchSize
|
||||
? null
|
||||
: data.maxBatchSize,
|
||||
validUntil:
|
||||
data.validUntil == null ||
|
||||
data.validUntil.trim() === ""
|
||||
? undefined
|
||||
: data.validUntil,
|
||||
approveNewSites: data.approveNewSites
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("provisioningKeysErrorCreate"),
|
||||
description: formatAxiosError(e)
|
||||
});
|
||||
});
|
||||
|
||||
if (res && res.status === 201) {
|
||||
setCreated(res.data.data);
|
||||
router.refresh();
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const credential = created && created.siteProvisioningKey;
|
||||
|
||||
const unlimitedBatchSize = form.watch("unlimitedBatchSize");
|
||||
|
||||
return (
|
||||
<Credenza open={open} onOpenChange={setOpen}>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{created
|
||||
? t("provisioningKeysList")
|
||||
: t("provisioningKeysCreate")}
|
||||
</CredenzaTitle>
|
||||
{!created && (
|
||||
<CredenzaDescription>
|
||||
{t("provisioningKeysCreateDescription")}
|
||||
</CredenzaDescription>
|
||||
)}
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
{!created && (
|
||||
<Form {...form}>
|
||||
<form
|
||||
id={FORM_ID}
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="maxBatchSize"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t(
|
||||
"provisioningKeysMaxBatchSize"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={1_000_000}
|
||||
autoComplete="off"
|
||||
disabled={unlimitedBatchSize}
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
onBlur={field.onBlur}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
field.onChange(
|
||||
v === ""
|
||||
? 100
|
||||
: Number(v)
|
||||
);
|
||||
}}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="unlimitedBatchSize"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center gap-3 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
id="provisioning-unlimited-batch"
|
||||
checked={field.value}
|
||||
onCheckedChange={(c) =>
|
||||
field.onChange(
|
||||
c === true
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel
|
||||
htmlFor="provisioning-unlimited-batch"
|
||||
className="cursor-pointer font-normal !mt-0"
|
||||
>
|
||||
{t(
|
||||
"provisioningKeysUnlimitedBatchSize"
|
||||
)}
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="validUntil"
|
||||
render={({ field }) => {
|
||||
const dateTimeValue: DateTimeValue =
|
||||
(() => {
|
||||
if (!field.value) return {};
|
||||
const d = new Date(field.value);
|
||||
if (isNaN(d.getTime()))
|
||||
return {};
|
||||
const hours = d
|
||||
.getHours()
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const minutes = d
|
||||
.getMinutes()
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const seconds = d
|
||||
.getSeconds()
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
return {
|
||||
date: d,
|
||||
time: `${hours}:${minutes}:${seconds}`
|
||||
};
|
||||
})();
|
||||
|
||||
return (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t(
|
||||
"provisioningKeysValidUntil"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker
|
||||
value={dateTimeValue}
|
||||
onChange={(value) => {
|
||||
if (!value.date) {
|
||||
field.onChange(
|
||||
""
|
||||
);
|
||||
return;
|
||||
}
|
||||
const d = new Date(
|
||||
value.date
|
||||
);
|
||||
if (value.time) {
|
||||
const [h, m, s] =
|
||||
value.time.split(
|
||||
":"
|
||||
);
|
||||
d.setHours(
|
||||
parseInt(
|
||||
h,
|
||||
10
|
||||
),
|
||||
parseInt(
|
||||
m,
|
||||
10
|
||||
),
|
||||
parseInt(
|
||||
s || "0",
|
||||
10
|
||||
)
|
||||
);
|
||||
}
|
||||
field.onChange(
|
||||
d.toISOString()
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"provisioningKeysValidUntilHint"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="approveNewSites"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-start gap-3 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
id="provisioning-approve-new-sites"
|
||||
checked={field.value}
|
||||
onCheckedChange={(c) =>
|
||||
field.onChange(
|
||||
c === true
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="flex flex-col gap-1">
|
||||
<FormLabel
|
||||
htmlFor="provisioning-approve-new-sites"
|
||||
className="cursor-pointer font-normal !mt-0"
|
||||
>
|
||||
{t(
|
||||
"provisioningKeysApproveNewSites"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"provisioningKeysApproveNewSitesDescription"
|
||||
)}
|
||||
</FormDescription>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
)}
|
||||
|
||||
{created && credential && (
|
||||
<div className="space-y-4">
|
||||
<Alert variant="neutral">
|
||||
<InfoIcon className="h-4 w-4" />
|
||||
<AlertTitle className="font-semibold">
|
||||
{t("provisioningKeysSave")}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t("provisioningKeysSaveDescription")}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<CopyTextBox text={credential} />
|
||||
</div>
|
||||
)}
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
{!created ? (
|
||||
<>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button
|
||||
type="submit"
|
||||
form={FORM_ID}
|
||||
loading={loading}
|
||||
disabled={loading}
|
||||
>
|
||||
{t("generate")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="default">{t("done")}</Button>
|
||||
</CredenzaClose>
|
||||
)}
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
);
|
||||
}
|
||||
@@ -79,6 +79,7 @@ interface DomainPickerProps {
|
||||
defaultFullDomain?: string | null;
|
||||
defaultSubdomain?: string | null;
|
||||
defaultDomainId?: string | null;
|
||||
warnOnProvidedDomain?: boolean;
|
||||
}
|
||||
|
||||
export default function DomainPicker({
|
||||
@@ -88,7 +89,8 @@ export default function DomainPicker({
|
||||
hideFreeDomain = false,
|
||||
defaultSubdomain,
|
||||
defaultFullDomain,
|
||||
defaultDomainId
|
||||
defaultDomainId,
|
||||
warnOnProvidedDomain = false
|
||||
}: DomainPickerProps) {
|
||||
const { env } = useEnvContext();
|
||||
const api = createApiClient({ env });
|
||||
@@ -689,6 +691,14 @@ export default function DomainPicker({
|
||||
|
||||
{showProvidedDomainSearch && (
|
||||
<div className="space-y-4">
|
||||
{warnOnProvidedDomain && (
|
||||
<Alert variant="warning">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t("domainPickerRemoteExitNodeWarning")}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{isChecking && (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<div className="flex items-center space-x-2 text-sm text-muted-foreground">
|
||||
|
||||
@@ -18,7 +18,7 @@ import { resourceQueries } from "@app/lib/queries";
|
||||
import { ListSitesResponse } from "@server/routers/site";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { useState, useTransition } from "react";
|
||||
import {
|
||||
cleanForFQDN,
|
||||
InternalResourceForm,
|
||||
@@ -49,10 +49,9 @@ export default function EditInternalResourceDialog({
|
||||
const t = useTranslations();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const queryClient = useQueryClient();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitting, startTransition] = useTransition();
|
||||
|
||||
async function handleSubmit(values: InternalResourceFormValues) {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
let data = { ...values };
|
||||
if (data.mode === "host" && isHostname(data.destination)) {
|
||||
@@ -70,6 +69,7 @@ export default function EditInternalResourceDialog({
|
||||
name: data.name,
|
||||
siteId: data.siteId,
|
||||
mode: data.mode,
|
||||
niceId: data.niceId,
|
||||
destination: data.destination,
|
||||
alias:
|
||||
data.alias &&
|
||||
@@ -127,8 +127,6 @@ export default function EditInternalResourceDialog({
|
||||
),
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +160,9 @@ export default function EditInternalResourceDialog({
|
||||
orgId={orgId}
|
||||
siteResourceId={resource.id}
|
||||
formId="edit-internal-resource-form"
|
||||
onSubmit={handleSubmit}
|
||||
onSubmit={(values) =>
|
||||
startTransition(() => handleSubmit(values))
|
||||
}
|
||||
/>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
|
||||
385
src/components/EditSiteProvisioningKeyCredenza.tsx
Normal file
385
src/components/EditSiteProvisioningKeyCredenza.tsx
Normal file
@@ -0,0 +1,385 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Credenza,
|
||||
CredenzaBody,
|
||||
CredenzaClose,
|
||||
CredenzaContent,
|
||||
CredenzaDescription,
|
||||
CredenzaFooter,
|
||||
CredenzaHeader,
|
||||
CredenzaTitle
|
||||
} from "@app/components/Credenza";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { UpdateSiteProvisioningKeyResponse } from "@server/routers/siteProvisioning/types";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
DateTimePicker,
|
||||
DateTimeValue
|
||||
} from "@app/components/DateTimePicker";
|
||||
|
||||
const FORM_ID = "edit-site-provisioning-key-form";
|
||||
|
||||
export type EditableSiteProvisioningKey = {
|
||||
id: string;
|
||||
name: string;
|
||||
maxBatchSize: number | null;
|
||||
validUntil: string | null;
|
||||
approveNewSites: boolean;
|
||||
};
|
||||
|
||||
type EditSiteProvisioningKeyCredenzaProps = {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
orgId: string;
|
||||
provisioningKey: EditableSiteProvisioningKey | null;
|
||||
};
|
||||
|
||||
export default function EditSiteProvisioningKeyCredenza({
|
||||
open,
|
||||
setOpen,
|
||||
orgId,
|
||||
provisioningKey
|
||||
}: EditSiteProvisioningKeyCredenzaProps) {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const editFormSchema = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
unlimitedBatchSize: z.boolean(),
|
||||
maxBatchSize: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1, { message: t("provisioningKeysMaxBatchSizeInvalid") })
|
||||
.max(1_000_000, {
|
||||
message: t("provisioningKeysMaxBatchSizeInvalid")
|
||||
}),
|
||||
validUntil: z.string().optional(),
|
||||
approveNewSites: z.boolean()
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
const v = data.validUntil;
|
||||
if (v == null || v.trim() === "") {
|
||||
return;
|
||||
}
|
||||
if (Number.isNaN(Date.parse(v))) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: t("provisioningKeysValidUntilInvalid"),
|
||||
path: ["validUntil"]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type EditFormValues = z.infer<typeof editFormSchema>;
|
||||
|
||||
const form = useForm<EditFormValues>({
|
||||
resolver: zodResolver(editFormSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
unlimitedBatchSize: false,
|
||||
maxBatchSize: 100,
|
||||
validUntil: "",
|
||||
approveNewSites: true
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !provisioningKey) {
|
||||
return;
|
||||
}
|
||||
form.reset({
|
||||
name: provisioningKey.name,
|
||||
unlimitedBatchSize: provisioningKey.maxBatchSize == null,
|
||||
maxBatchSize: provisioningKey.maxBatchSize ?? 100,
|
||||
validUntil: provisioningKey.validUntil ?? "",
|
||||
approveNewSites: provisioningKey.approveNewSites
|
||||
});
|
||||
}, [open, provisioningKey, form]);
|
||||
|
||||
async function onSubmit(data: EditFormValues) {
|
||||
if (!provisioningKey) {
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api
|
||||
.patch<
|
||||
AxiosResponse<UpdateSiteProvisioningKeyResponse>
|
||||
>(
|
||||
`/org/${orgId}/site-provisioning-key/${provisioningKey.id}`,
|
||||
{
|
||||
maxBatchSize: data.unlimitedBatchSize
|
||||
? null
|
||||
: data.maxBatchSize,
|
||||
validUntil:
|
||||
data.validUntil == null ||
|
||||
data.validUntil.trim() === ""
|
||||
? ""
|
||||
: data.validUntil,
|
||||
approveNewSites: data.approveNewSites
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("provisioningKeysUpdateError"),
|
||||
description: formatAxiosError(e)
|
||||
});
|
||||
});
|
||||
|
||||
if (res && res.status === 200) {
|
||||
toast({
|
||||
title: t("provisioningKeysUpdated"),
|
||||
description: t("provisioningKeysUpdatedDescription")
|
||||
});
|
||||
setOpen(false);
|
||||
router.refresh();
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const unlimitedBatchSize = form.watch("unlimitedBatchSize");
|
||||
|
||||
if (!provisioningKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Credenza open={open} onOpenChange={setOpen}>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>{t("provisioningKeysEdit")}</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("provisioningKeysEditDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id={FORM_ID}
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
disabled
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="maxBatchSize"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("provisioningKeysMaxBatchSize")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={1_000_000}
|
||||
autoComplete="off"
|
||||
disabled={unlimitedBatchSize}
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
onBlur={field.onBlur}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
field.onChange(
|
||||
v === ""
|
||||
? 100
|
||||
: Number(v)
|
||||
);
|
||||
}}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="unlimitedBatchSize"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center gap-3 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
id="provisioning-edit-unlimited-batch"
|
||||
checked={field.value}
|
||||
onCheckedChange={(c) =>
|
||||
field.onChange(c === true)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel
|
||||
htmlFor="provisioning-edit-unlimited-batch"
|
||||
className="cursor-pointer font-normal !mt-0"
|
||||
>
|
||||
{t(
|
||||
"provisioningKeysUnlimitedBatchSize"
|
||||
)}
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="approveNewSites"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-start gap-3 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
id="provisioning-edit-approve-new-sites"
|
||||
checked={field.value}
|
||||
onCheckedChange={(c) =>
|
||||
field.onChange(c === true)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="flex flex-col gap-1">
|
||||
<FormLabel
|
||||
htmlFor="provisioning-edit-approve-new-sites"
|
||||
className="cursor-pointer font-normal !mt-0"
|
||||
>
|
||||
{t(
|
||||
"provisioningKeysApproveNewSites"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"provisioningKeysApproveNewSitesDescription"
|
||||
)}
|
||||
</FormDescription>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="validUntil"
|
||||
render={({ field }) => {
|
||||
const dateTimeValue: DateTimeValue =
|
||||
(() => {
|
||||
if (!field.value) return {};
|
||||
const d = new Date(field.value);
|
||||
if (isNaN(d.getTime())) return {};
|
||||
const hours = d
|
||||
.getHours()
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const minutes = d
|
||||
.getMinutes()
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const seconds = d
|
||||
.getSeconds()
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
return {
|
||||
date: d,
|
||||
time: `${hours}:${minutes}:${seconds}`
|
||||
};
|
||||
})();
|
||||
|
||||
return (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("provisioningKeysValidUntil")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker
|
||||
value={dateTimeValue}
|
||||
onChange={(value) => {
|
||||
if (!value.date) {
|
||||
field.onChange("");
|
||||
return;
|
||||
}
|
||||
const d = new Date(
|
||||
value.date
|
||||
);
|
||||
if (value.time) {
|
||||
const [h, m, s] =
|
||||
value.time.split(
|
||||
":"
|
||||
);
|
||||
d.setHours(
|
||||
parseInt(h, 10),
|
||||
parseInt(m, 10),
|
||||
parseInt(
|
||||
s || "0",
|
||||
10
|
||||
)
|
||||
);
|
||||
}
|
||||
field.onChange(
|
||||
d.toISOString()
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("provisioningKeysValidUntilHint")}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button
|
||||
type="submit"
|
||||
form={FORM_ID}
|
||||
loading={loading}
|
||||
disabled={loading}
|
||||
>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
);
|
||||
}
|
||||
773
src/components/HttpDestinationCredenza.tsx
Normal file
773
src/components/HttpDestinationCredenza.tsx
Normal file
@@ -0,0 +1,773 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Credenza,
|
||||
CredenzaBody,
|
||||
CredenzaClose,
|
||||
CredenzaContent,
|
||||
CredenzaDescription,
|
||||
CredenzaFooter,
|
||||
CredenzaHeader,
|
||||
CredenzaTitle
|
||||
} from "@app/components/Credenza";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { Label } from "@app/components/ui/label";
|
||||
import { Switch } from "@app/components/ui/switch";
|
||||
import { HorizontalTabs } from "@app/components/HorizontalTabs";
|
||||
import { RadioGroup, RadioGroupItem } from "@app/components/ui/radio-group";
|
||||
import { Textarea } from "@app/components/ui/textarea";
|
||||
import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { build } from "@server/build";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type AuthType = "none" | "bearer" | "basic" | "custom";
|
||||
|
||||
export type PayloadFormat = "json_array" | "ndjson" | "json_single";
|
||||
|
||||
export interface HttpConfig {
|
||||
name: string;
|
||||
url: string;
|
||||
authType: AuthType;
|
||||
bearerToken?: string;
|
||||
basicCredentials?: string;
|
||||
customHeaderName?: string;
|
||||
customHeaderValue?: string;
|
||||
headers: Array<{ key: string; value: string }>;
|
||||
format: PayloadFormat;
|
||||
useBodyTemplate: boolean;
|
||||
bodyTemplate?: string;
|
||||
}
|
||||
|
||||
export interface Destination {
|
||||
destinationId: number;
|
||||
orgId: string;
|
||||
type: string;
|
||||
config: string;
|
||||
enabled: boolean;
|
||||
sendAccessLogs: boolean;
|
||||
sendActionLogs: boolean;
|
||||
sendConnectionLogs: boolean;
|
||||
sendRequestLogs: boolean;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const defaultHttpConfig = (): HttpConfig => ({
|
||||
name: "",
|
||||
url: "",
|
||||
authType: "none",
|
||||
bearerToken: "",
|
||||
basicCredentials: "",
|
||||
customHeaderName: "",
|
||||
customHeaderValue: "",
|
||||
headers: [],
|
||||
format: "json_array",
|
||||
useBodyTemplate: false,
|
||||
bodyTemplate: ""
|
||||
});
|
||||
|
||||
export function parseHttpConfig(raw: string): HttpConfig {
|
||||
try {
|
||||
return { ...defaultHttpConfig(), ...JSON.parse(raw) };
|
||||
} catch {
|
||||
return defaultHttpConfig();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Headers editor ─────────────────────────────────────────────────────────────
|
||||
|
||||
interface HeadersEditorProps {
|
||||
headers: Array<{ key: string; value: string }>;
|
||||
onChange: (headers: Array<{ key: string; value: string }>) => void;
|
||||
}
|
||||
|
||||
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
const addRow = () => onChange([...headers, { key: "", value: "" }]);
|
||||
|
||||
const removeRow = (i: number) =>
|
||||
onChange(headers.filter((_, idx) => idx !== i));
|
||||
|
||||
const updateRow = (i: number, field: "key" | "value", val: string) => {
|
||||
const next = [...headers];
|
||||
next[i] = { ...next[i], [field]: val };
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{headers.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("httpDestNoHeadersConfigured")}
|
||||
</p>
|
||||
)}
|
||||
{headers.map((h, i) => (
|
||||
<div key={i} className="flex gap-2 items-center">
|
||||
<Input
|
||||
value={h.key}
|
||||
onChange={(e) => updateRow(i, "key", e.target.value)}
|
||||
placeholder={t("httpDestHeaderNamePlaceholder")}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={h.value}
|
||||
onChange={(e) =>
|
||||
updateRow(i, "value", e.target.value)
|
||||
}
|
||||
placeholder={t("httpDestHeaderValuePlaceholder")}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeRow(i)}
|
||||
className="shrink-0 h-9 w-9"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addRow}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
{t("httpDestAddHeader")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Component ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface HttpDestinationCredenzaProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
editing: Destination | null;
|
||||
orgId: string;
|
||||
onSaved: () => void;
|
||||
}
|
||||
|
||||
export function HttpDestinationCredenza({
|
||||
open,
|
||||
onOpenChange,
|
||||
editing,
|
||||
orgId,
|
||||
onSaved
|
||||
}: HttpDestinationCredenzaProps) {
|
||||
const api = createApiClient(useEnvContext());
|
||||
const t = useTranslations();
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [cfg, setCfg] = useState<HttpConfig>(defaultHttpConfig());
|
||||
const [sendAccessLogs, setSendAccessLogs] = useState(false);
|
||||
const [sendActionLogs, setSendActionLogs] = useState(false);
|
||||
const [sendConnectionLogs, setSendConnectionLogs] = useState(false);
|
||||
const [sendRequestLogs, setSendRequestLogs] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setCfg(
|
||||
editing ? parseHttpConfig(editing.config) : defaultHttpConfig()
|
||||
);
|
||||
setSendAccessLogs(editing?.sendAccessLogs ?? false);
|
||||
setSendActionLogs(editing?.sendActionLogs ?? false);
|
||||
setSendConnectionLogs(editing?.sendConnectionLogs ?? false);
|
||||
setSendRequestLogs(editing?.sendRequestLogs ?? false);
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
const update = (patch: Partial<HttpConfig>) =>
|
||||
setCfg((prev) => ({ ...prev, ...patch }));
|
||||
|
||||
const urlError: string | null = (() => {
|
||||
const raw = cfg.url.trim();
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = new URL(raw);
|
||||
if (
|
||||
parsed.protocol !== "http:" &&
|
||||
parsed.protocol !== "https:"
|
||||
) {
|
||||
return t("httpDestUrlErrorHttpRequired");
|
||||
}
|
||||
if (build === "saas" && parsed.protocol !== "https:") {
|
||||
return t("httpDestUrlErrorHttpsRequired");
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return t("httpDestUrlErrorInvalid");
|
||||
}
|
||||
})();
|
||||
|
||||
const isValid =
|
||||
cfg.name.trim() !== "" &&
|
||||
cfg.url.trim() !== "" &&
|
||||
urlError === null;
|
||||
|
||||
async function handleSave() {
|
||||
if (!isValid) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = {
|
||||
type: "http",
|
||||
config: JSON.stringify(cfg),
|
||||
sendAccessLogs,
|
||||
sendActionLogs,
|
||||
sendConnectionLogs,
|
||||
sendRequestLogs
|
||||
};
|
||||
if (editing) {
|
||||
await api.post(
|
||||
`/org/${orgId}/event-streaming-destination/${editing.destinationId}`,
|
||||
payload
|
||||
);
|
||||
toast({ title: t("httpDestUpdatedSuccess") });
|
||||
} else {
|
||||
await api.put(
|
||||
`/org/${orgId}/event-streaming-destination`,
|
||||
payload
|
||||
);
|
||||
toast({ title: t("httpDestCreatedSuccess") });
|
||||
}
|
||||
onSaved();
|
||||
onOpenChange(false);
|
||||
} catch (e) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: editing
|
||||
? t("httpDestUpdateFailed")
|
||||
: t("httpDestCreateFailed"),
|
||||
description: formatAxiosError(
|
||||
e,
|
||||
t("streamingUnexpectedError")
|
||||
)
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Credenza open={open} onOpenChange={onOpenChange}>
|
||||
<CredenzaContent className="sm:max-w-2xl">
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{editing
|
||||
? t("httpDestEditTitle")
|
||||
: t("httpDestAddTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{editing
|
||||
? t("httpDestEditDescription")
|
||||
: t("httpDestAddDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
|
||||
<CredenzaBody>
|
||||
<HorizontalTabs
|
||||
clientSide
|
||||
items={[
|
||||
{ title: t("httpDestTabSettings"), href: "" },
|
||||
{ title: t("httpDestTabHeaders"), href: "" },
|
||||
{ title: t("httpDestTabBody"), href: "" },
|
||||
{ title: t("httpDestTabLogs"), href: "" }
|
||||
]}
|
||||
>
|
||||
{/* ── Settings tab ────────────────────────────── */}
|
||||
<div className="space-y-6 mt-4 p-1">
|
||||
{/* Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dest-name">{t("name")}</Label>
|
||||
<Input
|
||||
id="dest-name"
|
||||
placeholder={t("httpDestNamePlaceholder")}
|
||||
value={cfg.name}
|
||||
onChange={(e) =>
|
||||
update({ name: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* URL */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dest-url">
|
||||
{t("httpDestUrlLabel")}
|
||||
</Label>
|
||||
<Input
|
||||
id="dest-url"
|
||||
placeholder="https://example.com/webhook"
|
||||
value={cfg.url}
|
||||
onChange={(e) =>
|
||||
update({ url: e.target.value })
|
||||
}
|
||||
/>
|
||||
{urlError && (
|
||||
<p className="text-xs text-destructive">
|
||||
{urlError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Authentication */}
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="font-medium block">
|
||||
{t("httpDestAuthTitle")}
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
{t("httpDestAuthDescription")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<RadioGroup
|
||||
value={cfg.authType}
|
||||
onValueChange={(v) =>
|
||||
update({ authType: v as AuthType })
|
||||
}
|
||||
className="gap-2"
|
||||
>
|
||||
{/* None */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3 transition-colors">
|
||||
<RadioGroupItem
|
||||
value="none"
|
||||
id="auth-none"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="auth-none"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestAuthNoneTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestAuthNoneDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bearer */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<RadioGroupItem
|
||||
value="bearer"
|
||||
id="auth-bearer"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="flex-1 space-y-3">
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="auth-bearer"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestAuthBearerTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestAuthBearerDescription")}
|
||||
</p>
|
||||
</div>
|
||||
{cfg.authType === "bearer" && (
|
||||
<Input
|
||||
placeholder={t("httpDestAuthBearerPlaceholder")}
|
||||
value={
|
||||
cfg.bearerToken ?? ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
bearerToken:
|
||||
e.target.value
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Basic */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<RadioGroupItem
|
||||
value="basic"
|
||||
id="auth-basic"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="flex-1 space-y-3">
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="auth-basic"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestAuthBasicTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestAuthBasicDescription")}
|
||||
</p>
|
||||
</div>
|
||||
{cfg.authType === "basic" && (
|
||||
<Input
|
||||
placeholder={t("httpDestAuthBasicPlaceholder")}
|
||||
value={
|
||||
cfg.basicCredentials ??
|
||||
""
|
||||
}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
basicCredentials:
|
||||
e.target.value
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<RadioGroupItem
|
||||
value="custom"
|
||||
id="auth-custom"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="flex-1 space-y-3">
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="auth-custom"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestAuthCustomTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestAuthCustomDescription")}
|
||||
</p>
|
||||
</div>
|
||||
{cfg.authType === "custom" && (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder={t("httpDestAuthCustomHeaderNamePlaceholder")}
|
||||
value={
|
||||
cfg.customHeaderName ??
|
||||
""
|
||||
}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
customHeaderName:
|
||||
e.target
|
||||
.value
|
||||
})
|
||||
}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
placeholder={t("httpDestAuthCustomHeaderValuePlaceholder")}
|
||||
value={
|
||||
cfg.customHeaderValue ??
|
||||
""
|
||||
}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
customHeaderValue:
|
||||
e.target
|
||||
.value
|
||||
})
|
||||
}
|
||||
className="flex-1"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Headers tab ──────────────────────────────── */}
|
||||
<div className="space-y-6 mt-4 p-1">
|
||||
<div>
|
||||
<label className="font-medium block">
|
||||
{t("httpDestCustomHeadersTitle")}
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
{t("httpDestCustomHeadersDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={cfg.headers}
|
||||
onChange={(headers) => update({ headers })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Body tab ─────────────────────────── */}
|
||||
<div className="space-y-6 mt-4 p-1">
|
||||
<div>
|
||||
<label className="font-medium block">
|
||||
{t("httpDestBodyTemplateTitle")}
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
{t("httpDestBodyTemplateDescription")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id="use-body-template"
|
||||
checked={cfg.useBodyTemplate}
|
||||
onCheckedChange={(v) =>
|
||||
update({ useBodyTemplate: v })
|
||||
}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="use-body-template"
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{t("httpDestEnableBodyTemplate")}
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{cfg.useBodyTemplate && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="body-template">
|
||||
{t("httpDestBodyTemplateLabel")}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="body-template"
|
||||
placeholder={
|
||||
'{\n "event": "{{event}}",\n "timestamp": "{{timestamp}}",\n "data": {{data}}\n}'
|
||||
}
|
||||
value={cfg.bodyTemplate ?? ""}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
bodyTemplate: e.target.value
|
||||
})
|
||||
}
|
||||
className="font-mono text-xs min-h-45 resize-y"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("httpDestBodyTemplateHint")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Payload Format */}
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="font-medium block">
|
||||
{t("httpDestPayloadFormatTitle")}
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
{t("httpDestPayloadFormatDescription")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<RadioGroup
|
||||
value={cfg.format ?? "json_array"}
|
||||
onValueChange={(v) =>
|
||||
update({
|
||||
format: v as PayloadFormat
|
||||
})
|
||||
}
|
||||
className="gap-2"
|
||||
>
|
||||
{/* JSON Array */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3 transition-colors">
|
||||
<RadioGroupItem
|
||||
value="json_array"
|
||||
id="fmt-json-array"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="fmt-json-array"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestFormatJsonArrayTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestFormatJsonArrayDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* NDJSON */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3 transition-colors">
|
||||
<RadioGroupItem
|
||||
value="ndjson"
|
||||
id="fmt-ndjson"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="fmt-ndjson"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestFormatNdjsonTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestFormatNdjsonDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Single event per request */}
|
||||
<div className="flex items-start gap-3 rounded-md border p-3 transition-colors">
|
||||
<RadioGroupItem
|
||||
value="json_single"
|
||||
id="fmt-json-single"
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="fmt-json-single"
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{t("httpDestFormatSingleTitle")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestFormatSingleDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Logs tab ──────────────────────────────────── */}
|
||||
<div className="space-y-6 mt-4 p-1">
|
||||
<div>
|
||||
<label className="font-medium block">
|
||||
{t("httpDestLogTypesTitle")}
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
{t("httpDestLogTypesDescription")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<Checkbox
|
||||
id="log-access"
|
||||
checked={sendAccessLogs}
|
||||
onCheckedChange={(v) =>
|
||||
setSendAccessLogs(v === true)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="log-access"
|
||||
className="text-sm font-medium cursor-pointer"
|
||||
>
|
||||
{t("httpDestAccessLogsTitle")}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestAccessLogsDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<Checkbox
|
||||
id="log-action"
|
||||
checked={sendActionLogs}
|
||||
onCheckedChange={(v) =>
|
||||
setSendActionLogs(v === true)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="log-action"
|
||||
className="text-sm font-medium cursor-pointer"
|
||||
>
|
||||
{t("httpDestActionLogsTitle")}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestActionLogsDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<Checkbox
|
||||
id="log-connection"
|
||||
checked={sendConnectionLogs}
|
||||
onCheckedChange={(v) =>
|
||||
setSendConnectionLogs(v === true)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="log-connection"
|
||||
className="text-sm font-medium cursor-pointer"
|
||||
>
|
||||
{t("httpDestConnectionLogsTitle")}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestConnectionLogsDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3 rounded-md border p-3">
|
||||
<Checkbox
|
||||
id="log-request"
|
||||
checked={sendRequestLogs}
|
||||
onCheckedChange={(v) =>
|
||||
setSendRequestLogs(v === true)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="log-request"
|
||||
className="text-sm font-medium cursor-pointer"
|
||||
>
|
||||
{t("httpDestRequestLogsTitle")}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("httpDestRequestLogsDescription")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</HorizontalTabs>
|
||||
</CredenzaBody>
|
||||
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={saving}
|
||||
>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
</CredenzaClose>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
disabled={!isValid || saving}
|
||||
>
|
||||
{editing ? t("httpDestSaveChanges") : t("httpDestCreateDestination")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
);
|
||||
}
|
||||
29
src/components/IdpAutoProvisionUsersDescription.tsx
Normal file
29
src/components/IdpAutoProvisionUsersDescription.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
const AUTO_PROVISION_DOCS_URL =
|
||||
"https://docs.pangolin.net/manage/identity-providers/auto-provisioning";
|
||||
|
||||
type IdpAutoProvisionUsersDescriptionProps = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function IdpAutoProvisionUsersDescription({
|
||||
className
|
||||
}: IdpAutoProvisionUsersDescriptionProps) {
|
||||
const t = useTranslations();
|
||||
return (
|
||||
<span className={className}>
|
||||
{t("idpAutoProvisionUsersDescription")}{" "}
|
||||
<a
|
||||
href={AUTO_PROVISION_DOCS_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{t("learnMore")}
|
||||
</a>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
|
||||
import { InfoIcon, ExternalLink } from "lucide-react";
|
||||
import { StrategySelect } from "@app/components/StrategySelect";
|
||||
import IdpAutoProvisionUsersDescription from "@app/components/IdpAutoProvisionUsersDescription";
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { Badge } from "@app/components/ui/badge";
|
||||
import { useTranslations } from "next-intl";
|
||||
@@ -163,9 +164,6 @@ export function IdpCreateWizard({
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("idpAutoProvisionUsersDescription")}
|
||||
</span>
|
||||
</form>
|
||||
</Form>
|
||||
</SettingsSectionForm>
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { HorizontalTabs } from "@app/components/HorizontalTabs";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { StrategySelect } from "@app/components/StrategySelect";
|
||||
import { Tag, TagInput } from "@app/components/tags/tag-input";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "@app/components/ui/command";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -32,24 +27,24 @@ import {
|
||||
SelectValue
|
||||
} from "@app/components/ui/select";
|
||||
import { Switch } from "@app/components/ui/switch";
|
||||
import { getUserDisplayName } from "@app/lib/getUserDisplayName";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { getUserDisplayName } from "@app/lib/getUserDisplayName";
|
||||
import { orgQueries, resourceQueries } from "@app/lib/queries";
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { ListSitesResponse } from "@server/routers/site";
|
||||
import { UserType } from "@server/types/UserTypes";
|
||||
import { Check, ChevronsUpDown, ExternalLink } from "lucide-react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronsUpDown, ExternalLink } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { HorizontalTabs } from "@app/components/HorizontalTabs";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { StrategySelect } from "@app/components/StrategySelect";
|
||||
import { SitesSelector, type Selectedsite } from "./site-selector";
|
||||
import { CaretSortIcon } from "@radix-ui/react-icons";
|
||||
import { MachinesSelector } from "./machines-selector";
|
||||
|
||||
// --- Helpers (shared) ---
|
||||
|
||||
@@ -132,6 +127,7 @@ export type InternalResourceData = {
|
||||
siteName: string;
|
||||
mode: "host" | "cidr";
|
||||
siteId: number;
|
||||
niceId: string;
|
||||
destination: string;
|
||||
alias?: string | null;
|
||||
tcpPortRangeString?: string | null;
|
||||
@@ -149,6 +145,7 @@ export type InternalResourceFormValues = {
|
||||
mode: "host" | "cidr";
|
||||
destination: string;
|
||||
alias?: string | null;
|
||||
niceId?: string;
|
||||
tcpPortRangeString?: string | null;
|
||||
udpPortRangeString?: string | null;
|
||||
disableIcmp?: boolean;
|
||||
@@ -243,6 +240,12 @@ export function InternalResourceForm({
|
||||
: undefined
|
||||
),
|
||||
alias: z.string().nullish(),
|
||||
niceId: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(255)
|
||||
.regex(/^[a-zA-Z0-9-]+$/)
|
||||
.optional(),
|
||||
tcpPortRangeString: createPortRangeStringSchema(t),
|
||||
udpPortRangeString: createPortRangeStringSchema(t),
|
||||
disableIcmp: z.boolean().optional(),
|
||||
@@ -250,7 +253,14 @@ export function InternalResourceForm({
|
||||
authDaemonPort: z.number().int().positive().optional().nullable(),
|
||||
roles: z.array(tagSchema).optional(),
|
||||
users: z.array(tagSchema).optional(),
|
||||
clients: z.array(tagSchema).optional()
|
||||
clients: z
|
||||
.array(
|
||||
z.object({
|
||||
clientId: z.number(),
|
||||
name: z.string()
|
||||
})
|
||||
)
|
||||
.optional()
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof formSchema>;
|
||||
@@ -259,7 +269,7 @@ export function InternalResourceForm({
|
||||
|
||||
const rolesQuery = useQuery(orgQueries.roles({ orgId }));
|
||||
const usersQuery = useQuery(orgQueries.users({ orgId }));
|
||||
const clientsQuery = useQuery(orgQueries.clients({ orgId }));
|
||||
const clientsQuery = useQuery(orgQueries.machineClients({ orgId }));
|
||||
const resourceRolesQuery = useQuery({
|
||||
...resourceQueries.siteResourceRoles({
|
||||
siteResourceId: siteResourceId ?? 0
|
||||
@@ -317,12 +327,9 @@ export function InternalResourceForm({
|
||||
}));
|
||||
}
|
||||
if (clientsData) {
|
||||
existingClients = (
|
||||
clientsData as { clientId: number; name: string }[]
|
||||
).map((c) => ({
|
||||
id: c.clientId.toString(),
|
||||
text: c.name
|
||||
}));
|
||||
existingClients = [
|
||||
...(clientsData as { clientId: number; name: string }[])
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,6 +394,7 @@ export function InternalResourceForm({
|
||||
disableIcmp: resource.disableIcmp ?? false,
|
||||
authDaemonMode: resource.authDaemonMode ?? "site",
|
||||
authDaemonPort: resource.authDaemonPort ?? null,
|
||||
niceId: resource.niceId,
|
||||
roles: [],
|
||||
users: [],
|
||||
clients: []
|
||||
@@ -407,6 +415,10 @@ export function InternalResourceForm({
|
||||
clients: []
|
||||
};
|
||||
|
||||
const [selectedSite, setSelectedSite] = useState<Selectedsite>(
|
||||
availableSites[0]
|
||||
);
|
||||
|
||||
const form = useForm<FormData>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues
|
||||
@@ -528,9 +540,15 @@ export function InternalResourceForm({
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit((values) =>
|
||||
onSubmit(values as InternalResourceFormValues)
|
||||
)}
|
||||
onSubmit={form.handleSubmit((values) => {
|
||||
onSubmit({
|
||||
...values,
|
||||
clients: (values.clients ?? []).map((c) => ({
|
||||
id: c.clientId.toString(),
|
||||
text: c.name
|
||||
}))
|
||||
});
|
||||
})}
|
||||
className="space-y-6"
|
||||
id={formId}
|
||||
>
|
||||
@@ -548,6 +566,21 @@ export function InternalResourceForm({
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{variant === "edit" && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="niceId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("identifier")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="siteId"
|
||||
@@ -578,46 +611,15 @@ export function InternalResourceForm({
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-full p-0">
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder={t("searchSites")}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{t("noSitesFound")}
|
||||
</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{availableSites.map(
|
||||
(site) => (
|
||||
<CommandItem
|
||||
key={
|
||||
site.siteId
|
||||
}
|
||||
value={
|
||||
site.name
|
||||
}
|
||||
onSelect={() =>
|
||||
field.onChange(
|
||||
site.siteId
|
||||
)
|
||||
}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
field.value ===
|
||||
site.siteId
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{site.name}
|
||||
</CommandItem>
|
||||
)
|
||||
)}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
<SitesSelector
|
||||
orgId={orgId}
|
||||
selectedSite={selectedSite}
|
||||
filterTypes={["newt"]}
|
||||
onSelectSite={(site) => {
|
||||
setSelectedSite(site);
|
||||
field.onChange(site.siteId);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
@@ -627,8 +629,7 @@ export function InternalResourceForm({
|
||||
</div>
|
||||
|
||||
<HorizontalTabs
|
||||
clientSide={true}
|
||||
defaultTab={0}
|
||||
clientSide
|
||||
items={[
|
||||
{
|
||||
title: t(
|
||||
@@ -645,7 +646,7 @@ export function InternalResourceForm({
|
||||
: [{ title: t("sshAccess"), href: "#" }])
|
||||
]}
|
||||
>
|
||||
<div className="space-y-4 mt-4">
|
||||
<div className="space-y-4 mt-4 p-1">
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<label className="font-medium block">
|
||||
@@ -1016,7 +1017,7 @@ export function InternalResourceForm({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 mt-4">
|
||||
<div className="space-y-4 mt-4 p-1">
|
||||
<div className="mb-8">
|
||||
<label className="font-medium block">
|
||||
{t("editInternalResourceDialogAccessControl")}
|
||||
@@ -1136,48 +1137,73 @@ export function InternalResourceForm({
|
||||
<FormLabel>
|
||||
{t("machineClients")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
{...field}
|
||||
activeTagIndex={
|
||||
activeClientsTagIndex
|
||||
}
|
||||
setActiveTagIndex={
|
||||
setActiveClientsTagIndex
|
||||
}
|
||||
placeholder={
|
||||
t(
|
||||
"accessClientSelect"
|
||||
) ||
|
||||
"Select machine clients"
|
||||
}
|
||||
size="sm"
|
||||
tags={
|
||||
form.getValues()
|
||||
.clients ?? []
|
||||
}
|
||||
setTags={(newClients) =>
|
||||
form.setValue(
|
||||
"clients",
|
||||
newClients as [
|
||||
Tag,
|
||||
...Tag[]
|
||||
]
|
||||
)
|
||||
}
|
||||
enableAutocomplete={
|
||||
true
|
||||
}
|
||||
autocompleteOptions={
|
||||
allClients
|
||||
}
|
||||
allowDuplicates={false}
|
||||
restrictTagsToAutocompleteOptions={
|
||||
true
|
||||
}
|
||||
sortTags={true}
|
||||
/>
|
||||
</FormControl>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<FormControl>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className={cn(
|
||||
"justify-between w-full",
|
||||
"text-muted-foreground pl-1.5"
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1",
|
||||
"overflow-x-auto"
|
||||
)}
|
||||
>
|
||||
{(
|
||||
field.value ??
|
||||
[]
|
||||
).map(
|
||||
(
|
||||
client
|
||||
) => (
|
||||
<span
|
||||
key={
|
||||
client.clientId
|
||||
}
|
||||
className={cn(
|
||||
"bg-muted-foreground/20 font-normal text-foreground rounded-sm",
|
||||
"py-1 px-1.5 text-xs"
|
||||
)}
|
||||
>
|
||||
{
|
||||
client.name
|
||||
}
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
<span className="pl-1">
|
||||
{t(
|
||||
"accessClientSelect"
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0">
|
||||
<MachinesSelector
|
||||
selectedMachines={
|
||||
field.value ??
|
||||
[]
|
||||
}
|
||||
orgId={orgId}
|
||||
onSelectMachines={(
|
||||
machines
|
||||
) => {
|
||||
form.setValue(
|
||||
"clients",
|
||||
machines
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
@@ -1189,7 +1215,7 @@ export function InternalResourceForm({
|
||||
|
||||
{/* SSH Access tab */}
|
||||
{!disableEnterpriseFeatures && mode !== "cidr" && (
|
||||
<div className="space-y-4 mt-4">
|
||||
<div className="space-y-4 mt-4 p-1">
|
||||
<PaidFeaturesAlert tiers={tierMatrix.sshPam} />
|
||||
<div className="mb-8">
|
||||
<label className="font-medium block">
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { ExtendedColumnDef } from "@app/components/ui/data-table";
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -21,13 +20,14 @@ import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useTranslations } from "next-intl";
|
||||
import moment from "moment";
|
||||
import { useRouter } from "next/navigation";
|
||||
import UserRoleBadges from "@app/components/UserRoleBadges";
|
||||
|
||||
export type InvitationRow = {
|
||||
id: string;
|
||||
email: string;
|
||||
expiresAt: string;
|
||||
role: string;
|
||||
roleId: number;
|
||||
roleLabels: string[];
|
||||
roleIds: number[];
|
||||
};
|
||||
|
||||
type InvitationsTableProps = {
|
||||
@@ -90,9 +90,13 @@ export default function InvitationsTable({
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "role",
|
||||
id: "roles",
|
||||
accessorFn: (row) => row.roleLabels.join(", "),
|
||||
friendlyName: t("role"),
|
||||
header: () => <span className="p-3">{t("role")}</span>
|
||||
header: () => <span className="p-3">{t("role")}</span>,
|
||||
cell: ({ row }) => (
|
||||
<UserRoleBadges roleLabels={row.original.roleLabels} />
|
||||
)
|
||||
},
|
||||
{
|
||||
id: "dots",
|
||||
|
||||
@@ -93,7 +93,7 @@ export function LayoutMobileMenu({
|
||||
)
|
||||
}
|
||||
>
|
||||
<span className="flex-shrink-0 mr-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 flex items-center justify-center text-muted-foreground mr-3">
|
||||
<Server className="h-4 w-4" />
|
||||
</span>
|
||||
<span className="flex-1">
|
||||
|
||||
@@ -169,8 +169,8 @@ export function LayoutSidebar({
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0",
|
||||
!isSidebarCollapsed && "mr-2"
|
||||
"flex-shrink-0 w-5 h-5 flex items-center justify-center text-muted-foreground",
|
||||
!isSidebarCollapsed && "mr-3"
|
||||
)}
|
||||
>
|
||||
<Server className="h-4 w-4" />
|
||||
@@ -222,36 +222,34 @@ export function LayoutSidebar({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="w-full border-t border-border mb-3" />
|
||||
|
||||
<div className="p-4 pt-1 flex flex-col shrink-0">
|
||||
<div className="pt-1 flex flex-col shrink-0 gap-2 w-full border-t border-border">
|
||||
{canShowProductUpdates && (
|
||||
<div className="mb-3 empty:mb-0">
|
||||
<div className="px-4">
|
||||
<ProductUpdates isCollapsed={isSidebarCollapsed} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{build === "enterprise" && (
|
||||
<div className="mb-3 empty:mb-0">
|
||||
<div className="px-4">
|
||||
<SidebarLicenseButton
|
||||
isCollapsed={isSidebarCollapsed}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{build === "oss" && (
|
||||
<div className="mb-3 empty:mb-0">
|
||||
<div className="px-4">
|
||||
<SupporterStatus isCollapsed={isSidebarCollapsed} />
|
||||
</div>
|
||||
)}
|
||||
{build === "saas" && (
|
||||
<div className="mb-3 empty:mb-0">
|
||||
<div className="px-4">
|
||||
<SidebarSupportButton
|
||||
isCollapsed={isSidebarCollapsed}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!isSidebarCollapsed && (
|
||||
<div className="space-y-2">
|
||||
<div className="px-4 space-y-2 pb-4">
|
||||
{loadFooterLinks() ? (
|
||||
<>
|
||||
{loadFooterLinks()!.map((link, index) => (
|
||||
|
||||
@@ -12,6 +12,8 @@ import clsx from "clsx";
|
||||
import { useTransition } from "react";
|
||||
import { Locale } from "@/i18n/config";
|
||||
import { setUserLocale } from "@/services/locale";
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
|
||||
type Props = {
|
||||
defaultValue: string;
|
||||
@@ -25,12 +27,17 @@ export default function LocaleSwitcherSelect({
|
||||
label
|
||||
}: Props) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const api = createApiClient(useEnvContext());
|
||||
|
||||
function onChange(value: string) {
|
||||
const locale = value as Locale;
|
||||
startTransition(() => {
|
||||
setUserLocale(locale);
|
||||
});
|
||||
// Persist locale to the database (fire-and-forget)
|
||||
api.post("/user/locale", { locale }).catch(() => {
|
||||
// Silently ignore errors — cookie is already set as fallback
|
||||
});
|
||||
}
|
||||
|
||||
const selected = items.find((item) => item.value === defaultValue);
|
||||
|
||||
@@ -540,7 +540,7 @@ export default function MachineClientsTable({
|
||||
columns={columns}
|
||||
rows={machineClients}
|
||||
tableId="machine-clients"
|
||||
searchPlaceholder={t("resourcesSearch")}
|
||||
searchPlaceholder={t("machinesSearch")}
|
||||
onAdd={() =>
|
||||
startNavigation(() =>
|
||||
router.push(`/${orgId}/settings/clients/machine/create`)
|
||||
|
||||
117
src/components/OrgRolesTagField.tsx
Normal file
117
src/components/OrgRolesTagField.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Tag, TagInput } from "@app/components/tags/tag-input";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import type { FieldValues, Path, UseFormReturn } from "react-hook-form";
|
||||
|
||||
export type RoleTag = {
|
||||
id: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
type OrgRolesTagFieldProps<TFieldValues extends FieldValues> = {
|
||||
form: Pick<UseFormReturn<TFieldValues>, "control" | "getValues" | "setValue">;
|
||||
/** Field in the form that holds Tag[] (role tags). Default: `"roles"`. */
|
||||
name?: Path<TFieldValues>;
|
||||
label: string;
|
||||
placeholder: string;
|
||||
allRoleOptions: Tag[];
|
||||
supportsMultipleRolesPerUser: boolean;
|
||||
showMultiRolePaywallMessage: boolean;
|
||||
paywallMessage: string;
|
||||
loading?: boolean;
|
||||
activeTagIndex: number | null;
|
||||
setActiveTagIndex: Dispatch<SetStateAction<number | null>>;
|
||||
};
|
||||
|
||||
export default function OrgRolesTagField<TFieldValues extends FieldValues>({
|
||||
form,
|
||||
name = "roles" as Path<TFieldValues>,
|
||||
label,
|
||||
placeholder,
|
||||
allRoleOptions,
|
||||
supportsMultipleRolesPerUser,
|
||||
showMultiRolePaywallMessage,
|
||||
paywallMessage,
|
||||
loading = false,
|
||||
activeTagIndex,
|
||||
setActiveTagIndex
|
||||
}: OrgRolesTagFieldProps<TFieldValues>) {
|
||||
const t = useTranslations();
|
||||
|
||||
function setRoleTags(updater: Tag[] | ((prev: Tag[]) => Tag[])) {
|
||||
const prev = form.getValues(name) as Tag[];
|
||||
const nextValue =
|
||||
typeof updater === "function" ? updater(prev) : updater;
|
||||
const next = supportsMultipleRolesPerUser
|
||||
? nextValue
|
||||
: nextValue.length > 1
|
||||
? [nextValue[nextValue.length - 1]]
|
||||
: nextValue;
|
||||
|
||||
if (
|
||||
!supportsMultipleRolesPerUser &&
|
||||
next.length === 0 &&
|
||||
prev.length > 0
|
||||
) {
|
||||
form.setValue(name, [prev[prev.length - 1]] as never, {
|
||||
shouldDirty: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (next.length === 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("accessRoleErrorAdd"),
|
||||
description: t("accessRoleSelectPlease")
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
form.setValue(name, next as never, { shouldDirty: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={name}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-col items-start">
|
||||
<FormLabel>{label}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
{...field}
|
||||
activeTagIndex={activeTagIndex}
|
||||
setActiveTagIndex={setActiveTagIndex}
|
||||
placeholder={placeholder}
|
||||
size="sm"
|
||||
tags={field.value}
|
||||
setTags={setRoleTags}
|
||||
enableAutocomplete={true}
|
||||
autocompleteOptions={allRoleOptions}
|
||||
allowDuplicates={false}
|
||||
restrictTagsToAutocompleteOptions={true}
|
||||
sortTags={true}
|
||||
disabled={loading}
|
||||
/>
|
||||
</FormControl>
|
||||
{showMultiRolePaywallMessage && (
|
||||
<FormDescription>{paywallMessage}</FormDescription>
|
||||
)}
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import { usePathname, useRouter } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useUserContext } from "@app/hooks/useUserContext";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { build } from "@server/build";
|
||||
|
||||
interface OrgSelectorProps {
|
||||
orgId?: string;
|
||||
@@ -50,6 +51,11 @@ export function OrgSelector({
|
||||
|
||||
const selectedOrg = orgs?.find((org) => org.orgId === orgId);
|
||||
|
||||
let canCreateOrg = !env.flags.disableUserCreateOrg || user.serverAdmin;
|
||||
if (build === "saas" && user.type !== "internal") {
|
||||
canCreateOrg = false;
|
||||
}
|
||||
|
||||
const sortedOrgs = useMemo(() => {
|
||||
if (!orgs?.length) return orgs ?? [];
|
||||
return [...orgs].sort((a, b) => {
|
||||
@@ -161,7 +167,7 @@ export function OrgSelector({
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
{(!env.flags.disableUserCreateOrg || user.serverAdmin) && (
|
||||
{canCreateOrg && (
|
||||
<div className="p-2 border-t border-border">
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
473
src/components/PendingSitesTable.tsx
Normal file
473
src/components/PendingSitesTable.tsx
Normal file
@@ -0,0 +1,473 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@app/components/ui/badge";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from "@app/components/ui/dropdown-menu";
|
||||
import { InfoPopup } from "@app/components/ui/info-popup";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useNavigationContext } from "@app/hooks/useNavigationContext";
|
||||
import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { build } from "@server/build";
|
||||
import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { type PaginationState } from "@tanstack/react-table";
|
||||
import {
|
||||
ArrowDown01Icon,
|
||||
ArrowUp10Icon,
|
||||
ArrowUpRight,
|
||||
Check,
|
||||
ChevronsUpDownIcon,
|
||||
MoreHorizontal
|
||||
} from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { useDebouncedCallback } from "use-debounce";
|
||||
import z from "zod";
|
||||
import { ColumnFilterButton } from "./ColumnFilterButton";
|
||||
import {
|
||||
ControlledDataTable,
|
||||
type ExtendedColumnDef
|
||||
} from "./ui/controlled-data-table";
|
||||
import { SiteRow } from "./SitesTable";
|
||||
|
||||
type PendingSitesTableProps = {
|
||||
sites: SiteRow[];
|
||||
pagination: PaginationState;
|
||||
orgId: string;
|
||||
rowCount: number;
|
||||
};
|
||||
|
||||
export default function PendingSitesTable({
|
||||
sites,
|
||||
orgId,
|
||||
pagination,
|
||||
rowCount
|
||||
}: PendingSitesTableProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const {
|
||||
navigate: filter,
|
||||
isNavigating: isFiltering,
|
||||
searchParams
|
||||
} = useNavigationContext();
|
||||
|
||||
const [isRefreshing, startTransition] = useTransition();
|
||||
const [approvingIds, setApprovingIds] = useState<Set<number>>(new Set());
|
||||
|
||||
const api = createApiClient(useEnvContext());
|
||||
const t = useTranslations();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
const canUseSiteProvisioning =
|
||||
isPaidUser(tierMatrix[TierFeature.SiteProvisioningKeys]) &&
|
||||
build !== "oss";
|
||||
|
||||
const booleanSearchFilterSchema = z
|
||||
.enum(["true", "false"])
|
||||
.optional()
|
||||
.catch(undefined);
|
||||
|
||||
function handleFilterChange(
|
||||
column: string,
|
||||
value: string | undefined | null
|
||||
) {
|
||||
const sp = new URLSearchParams(searchParams);
|
||||
sp.delete(column);
|
||||
sp.delete("page");
|
||||
|
||||
if (value) {
|
||||
sp.set(column, value);
|
||||
}
|
||||
startTransition(() => router.push(`${pathname}?${sp.toString()}`));
|
||||
}
|
||||
|
||||
function refreshData() {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: t("refreshError"),
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function approveSite(siteId: number) {
|
||||
setApprovingIds((prev) => new Set(prev).add(siteId));
|
||||
try {
|
||||
await api.post(`/site/${siteId}`, { status: "approved" });
|
||||
toast({
|
||||
title: t("success"),
|
||||
description: t("siteApproveSuccess"),
|
||||
variant: "default"
|
||||
});
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("siteApproveError"),
|
||||
description: formatAxiosError(e, t("siteApproveError"))
|
||||
});
|
||||
} finally {
|
||||
setApprovingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(siteId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ExtendedColumnDef<SiteRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
enableHiding: false,
|
||||
header: () => {
|
||||
const nameOrder = getSortDirection("name", searchParams);
|
||||
const Icon =
|
||||
nameOrder === "asc"
|
||||
? ArrowDown01Icon
|
||||
: nameOrder === "desc"
|
||||
? ArrowUp10Icon
|
||||
: ChevronsUpDownIcon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="p-3"
|
||||
onClick={() => toggleSort("name")}
|
||||
>
|
||||
{t("name")}
|
||||
<Icon className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "niceId",
|
||||
accessorKey: "nice",
|
||||
friendlyName: t("identifier"),
|
||||
enableHiding: true,
|
||||
header: () => {
|
||||
return <span className="p-3">{t("identifier")}</span>;
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
return <span>{row.original.nice || "-"}</span>;
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "online",
|
||||
friendlyName: t("online"),
|
||||
header: () => {
|
||||
return (
|
||||
<ColumnFilterButton
|
||||
options={[
|
||||
{ value: "true", label: t("online") },
|
||||
{ value: "false", label: t("offline") }
|
||||
]}
|
||||
selectedValue={booleanSearchFilterSchema.parse(
|
||||
searchParams.get("online")
|
||||
)}
|
||||
onValueChange={(value) =>
|
||||
handleFilterChange("online", value)
|
||||
}
|
||||
searchPlaceholder={t("searchPlaceholder")}
|
||||
emptyMessage={t("emptySearchOptions")}
|
||||
label={t("online")}
|
||||
className="p-3"
|
||||
/>
|
||||
);
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const originalRow = row.original;
|
||||
if (
|
||||
originalRow.type == "newt" ||
|
||||
originalRow.type == "wireguard"
|
||||
) {
|
||||
if (originalRow.online) {
|
||||
return (
|
||||
<span className="text-green-500 flex items-center space-x-2">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
|
||||
<span>{t("online")}</span>
|
||||
</span>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<span className="text-neutral-500 flex items-center space-x-2">
|
||||
<div className="w-2 h-2 bg-gray-500 rounded-full"></div>
|
||||
<span>{t("offline")}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
} else {
|
||||
return <span>-</span>;
|
||||
}
|
||||
}
|
||||
},
|
||||
// {
|
||||
// accessorKey: "mbIn",
|
||||
// friendlyName: t("dataIn"),
|
||||
// header: () => {
|
||||
// const dataInOrder = getSortDirection(
|
||||
// "megabytesIn",
|
||||
// searchParams
|
||||
// );
|
||||
// const Icon =
|
||||
// dataInOrder === "asc"
|
||||
// ? ArrowDown01Icon
|
||||
// : dataInOrder === "desc"
|
||||
// ? ArrowUp10Icon
|
||||
// : ChevronsUpDownIcon;
|
||||
// return (
|
||||
// <Button
|
||||
// variant="ghost"
|
||||
// onClick={() => toggleSort("megabytesIn")}
|
||||
// >
|
||||
// {t("dataIn")}
|
||||
// <Icon className="ml-2 h-4 w-4" />
|
||||
// </Button>
|
||||
// );
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// accessorKey: "mbOut",
|
||||
// friendlyName: t("dataOut"),
|
||||
// header: () => {
|
||||
// const dataOutOrder = getSortDirection(
|
||||
// "megabytesOut",
|
||||
// searchParams
|
||||
// );
|
||||
// const Icon =
|
||||
// dataOutOrder === "asc"
|
||||
// ? ArrowDown01Icon
|
||||
// : dataOutOrder === "desc"
|
||||
// ? ArrowUp10Icon
|
||||
// : ChevronsUpDownIcon;
|
||||
// return (
|
||||
// <Button
|
||||
// variant="ghost"
|
||||
// onClick={() => toggleSort("megabytesOut")}
|
||||
// >
|
||||
// {t("dataOut")}
|
||||
// <Icon className="ml-2 h-4 w-4" />
|
||||
// </Button>
|
||||
// );
|
||||
// }
|
||||
// },
|
||||
{
|
||||
accessorKey: "type",
|
||||
friendlyName: t("type"),
|
||||
header: () => {
|
||||
return <span className="p-3">{t("type")}</span>;
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const originalRow = row.original;
|
||||
|
||||
if (originalRow.type === "newt") {
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
<Badge variant="secondary">
|
||||
<div className="flex items-center space-x-1">
|
||||
<span>Newt</span>
|
||||
{originalRow.newtVersion && (
|
||||
<span>v{originalRow.newtVersion}</span>
|
||||
)}
|
||||
</div>
|
||||
</Badge>
|
||||
{originalRow.newtUpdateAvailable && (
|
||||
<InfoPopup
|
||||
info={t("newtUpdateAvailableInfo")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (originalRow.type === "wireguard") {
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Badge variant="secondary">WireGuard</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (originalRow.type === "local") {
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Badge variant="secondary">Local</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "exitNode",
|
||||
friendlyName: t("exitNode"),
|
||||
header: () => {
|
||||
return <span className="p-3">{t("exitNode")}</span>;
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const originalRow = row.original;
|
||||
if (!originalRow.exitNodeName) {
|
||||
return "-";
|
||||
}
|
||||
|
||||
const isCloudNode =
|
||||
build == "saas" &&
|
||||
originalRow.exitNodeName &&
|
||||
[
|
||||
"mercury",
|
||||
"venus",
|
||||
"earth",
|
||||
"mars",
|
||||
"jupiter",
|
||||
"saturn",
|
||||
"uranus",
|
||||
"neptune",
|
||||
"pluto"
|
||||
].includes(originalRow.exitNodeName.toLowerCase());
|
||||
|
||||
if (isCloudNode) {
|
||||
const capitalizedName =
|
||||
originalRow.exitNodeName.charAt(0).toUpperCase() +
|
||||
originalRow.exitNodeName.slice(1).toLowerCase();
|
||||
return (
|
||||
<Badge variant="secondary">
|
||||
Pangolin {capitalizedName}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (originalRow.remoteExitNodeId) {
|
||||
return (
|
||||
<Link
|
||||
href={`/${originalRow.orgId}/settings/remote-exit-nodes/${originalRow.remoteExitNodeId}`}
|
||||
>
|
||||
<Button variant="outline">
|
||||
{originalRow.exitNodeName}
|
||||
<ArrowUpRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return <span>{originalRow.exitNodeName}</span>;
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "address",
|
||||
header: () => {
|
||||
return <span className="p-3">{t("address")}</span>;
|
||||
},
|
||||
cell: ({ row }: { row: any }) => {
|
||||
const originalRow = row.original;
|
||||
return originalRow.address ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
<span>{originalRow.address}</span>
|
||||
</div>
|
||||
) : (
|
||||
"-"
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
enableHiding: false,
|
||||
header: () => <span className="p-3"></span>,
|
||||
cell: ({ row }) => {
|
||||
const siteRow = row.original;
|
||||
const isApproving = approvingIds.has(siteRow.id);
|
||||
return (
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Open menu</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<Link
|
||||
className="block w-full"
|
||||
href={`/${siteRow.orgId}/settings/sites/${siteRow.nice}`}
|
||||
>
|
||||
<DropdownMenuItem>
|
||||
{t("viewSettings")}
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={isApproving}
|
||||
onClick={() => approveSite(siteRow.id)}
|
||||
>
|
||||
<Check className="mr-2 w-4 h-4" />
|
||||
{t("approve")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
function toggleSort(column: string) {
|
||||
const newSearch = getNextSortOrder(column, searchParams);
|
||||
|
||||
filter({
|
||||
searchParams: newSearch
|
||||
});
|
||||
}
|
||||
|
||||
const handlePaginationChange = (newPage: PaginationState) => {
|
||||
searchParams.set("page", (newPage.pageIndex + 1).toString());
|
||||
searchParams.set("pageSize", newPage.pageSize.toString());
|
||||
filter({
|
||||
searchParams
|
||||
});
|
||||
};
|
||||
|
||||
const handleSearchChange = useDebouncedCallback((query: string) => {
|
||||
searchParams.set("query", query);
|
||||
searchParams.delete("page");
|
||||
filter({
|
||||
searchParams
|
||||
});
|
||||
}, 300);
|
||||
|
||||
return (
|
||||
<ControlledDataTable
|
||||
columns={columns}
|
||||
rows={sites}
|
||||
tableId="pending-sites-table"
|
||||
searchPlaceholder={t("searchSitesProgress")}
|
||||
pagination={pagination}
|
||||
onPaginationChange={handlePaginationChange}
|
||||
searchQuery={searchParams.get("query")?.toString()}
|
||||
onSearch={handleSearchChange}
|
||||
onRefresh={refreshData}
|
||||
isRefreshing={isRefreshing || isFiltering}
|
||||
refreshButtonDisabled={!canUseSiteProvisioning}
|
||||
rowCount={rowCount}
|
||||
columnVisibility={{
|
||||
niceId: false,
|
||||
nice: false,
|
||||
exitNode: false,
|
||||
address: false
|
||||
}}
|
||||
enableColumnVisibility
|
||||
stickyLeftColumn="name"
|
||||
stickyRightColumn="actions"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ function getActionsCategories(root: boolean) {
|
||||
[t("actionGetOrg")]: "getOrg",
|
||||
[t("actionUpdateOrg")]: "updateOrg",
|
||||
[t("actionGetOrgUser")]: "getOrgUser",
|
||||
[t("actionResetSiteBandwidth")]: "resetSiteBandwidth",
|
||||
[t("actionInviteUser")]: "inviteUser",
|
||||
[t("actionRemoveInvitation")]: "removeInvitation",
|
||||
[t("actionListInvitations")]: "listInvitations",
|
||||
@@ -94,7 +95,8 @@ function getActionsCategories(root: boolean) {
|
||||
[t("actionListRole")]: "listRoles",
|
||||
[t("actionUpdateRole")]: "updateRole",
|
||||
[t("actionListAllowedRoleResources")]: "listRoleResources",
|
||||
[t("actionAddUserRole")]: "addUserRole"
|
||||
[t("actionAddUserRole")]: "addUserRole",
|
||||
[t("actionRemoveUserRole")]: "removeUserRole"
|
||||
},
|
||||
"Access Token": {
|
||||
[t("actionGenerateAccessToken")]: "generateAccessToken",
|
||||
|
||||
@@ -192,13 +192,13 @@ function ProductUpdatesListPopup({
|
||||
<div
|
||||
className={cn(
|
||||
"relative z-1 cursor-pointer block group",
|
||||
"rounded-md border border-primary/30 bg-linear-to-br dark:from-primary/20 from-primary/20 via-background to-background p-2 py-3 w-full flex flex-col gap-2 text-sm",
|
||||
"rounded-md border bg-secondary p-2 py-3 w-full flex flex-col gap-2 text-sm",
|
||||
"transition duration-300 ease-in-out",
|
||||
"data-closed:opacity-0 data-closed:translate-y-full"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<BellIcon className="flex-none size-4 text-primary" />
|
||||
<BellIcon className="flex-none size-4" />
|
||||
<div className="flex justify-between items-center flex-1">
|
||||
<p className="font-medium text-start">
|
||||
{t("productUpdateWhatsNew")}
|
||||
@@ -346,13 +346,13 @@ function NewVersionAvailable({
|
||||
rel="noopener noreferrer"
|
||||
className={cn(
|
||||
"relative z-2 group cursor-pointer block",
|
||||
"rounded-md border border-primary/30 bg-linear-to-br dark:from-primary/20 from-primary/20 via-background to-background p-2 py-3 w-full flex flex-col gap-2 text-sm",
|
||||
"rounded-md border bg-secondary p-2 py-3 w-full flex flex-col gap-2 text-sm",
|
||||
"transition duration-300 ease-in-out",
|
||||
"data-closed:opacity-0 data-closed:translate-y-full"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RocketIcon className="flex-none size-4 text-primary" />
|
||||
<RocketIcon className="flex-none size-4" />
|
||||
<p className="font-medium flex-1">
|
||||
{t("pangolinUpdateAvailable")}
|
||||
</p>
|
||||
|
||||
@@ -32,15 +32,15 @@ type RegenerateInvitationFormProps = {
|
||||
invitation: {
|
||||
id: string;
|
||||
email: string;
|
||||
roleId: number;
|
||||
role: string;
|
||||
roleIds: number[];
|
||||
roleLabels: string[];
|
||||
} | null;
|
||||
onRegenerate: (updatedInvitation: {
|
||||
id: string;
|
||||
email: string;
|
||||
expiresAt: string;
|
||||
role: string;
|
||||
roleId: number;
|
||||
roleLabels: string[];
|
||||
roleIds: number[];
|
||||
}) => void;
|
||||
};
|
||||
|
||||
@@ -94,7 +94,7 @@ export default function RegenerateInvitationForm({
|
||||
try {
|
||||
const res = await api.post(`/org/${org.org.orgId}/create-invite`, {
|
||||
email: invitation.email,
|
||||
roleId: invitation.roleId,
|
||||
roleIds: invitation.roleIds,
|
||||
validHours,
|
||||
sendEmail,
|
||||
regenerate: true
|
||||
@@ -127,9 +127,11 @@ export default function RegenerateInvitationForm({
|
||||
onRegenerate({
|
||||
id: invitation.id,
|
||||
email: invitation.email,
|
||||
expiresAt: res.data.data.expiresAt,
|
||||
role: invitation.role,
|
||||
roleId: invitation.roleId
|
||||
expiresAt: new Date(
|
||||
res.data.data.expiresAt
|
||||
).toISOString(),
|
||||
roleLabels: invitation.roleLabels,
|
||||
roleIds: invitation.roleIds
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
|
||||
471
src/components/RoleMappingConfigFields.tsx
Normal file
471
src/components/RoleMappingConfigFields.tsx
Normal file
@@ -0,0 +1,471 @@
|
||||
"use client";
|
||||
|
||||
import { FormLabel, FormDescription } from "@app/components/ui/form";
|
||||
import { RadioGroup, RadioGroupItem } from "@app/components/ui/radio-group";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Tag, TagInput } from "@app/components/tags/tag-input";
|
||||
import {
|
||||
createMappingBuilderRule,
|
||||
MappingBuilderRule,
|
||||
RoleMappingMode
|
||||
} from "@app/lib/idpRoleMapping";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { build } from "@server/build";
|
||||
|
||||
export type RoleMappingRoleOption = {
|
||||
roleId: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type RoleMappingConfigFieldsProps = {
|
||||
roleMappingMode: RoleMappingMode;
|
||||
onRoleMappingModeChange: (mode: RoleMappingMode) => void;
|
||||
roles: RoleMappingRoleOption[];
|
||||
fixedRoleNames: string[];
|
||||
onFixedRoleNamesChange: (roleNames: string[]) => void;
|
||||
mappingBuilderClaimPath: string;
|
||||
onMappingBuilderClaimPathChange: (claimPath: string) => void;
|
||||
mappingBuilderRules: MappingBuilderRule[];
|
||||
onMappingBuilderRulesChange: (rules: MappingBuilderRule[]) => void;
|
||||
rawExpression: string;
|
||||
onRawExpressionChange: (expression: string) => void;
|
||||
/** Unique prefix for radio `id`/`htmlFor` when multiple instances exist on one page. */
|
||||
fieldIdPrefix?: string;
|
||||
/** When true, show extra hint for global default policies (no org role list). */
|
||||
showFreeformRoleNamesHint?: boolean;
|
||||
};
|
||||
|
||||
export default function RoleMappingConfigFields({
|
||||
roleMappingMode,
|
||||
onRoleMappingModeChange,
|
||||
roles,
|
||||
fixedRoleNames,
|
||||
onFixedRoleNamesChange,
|
||||
mappingBuilderClaimPath,
|
||||
onMappingBuilderClaimPathChange,
|
||||
mappingBuilderRules,
|
||||
onMappingBuilderRulesChange,
|
||||
rawExpression,
|
||||
onRawExpressionChange,
|
||||
fieldIdPrefix = "role-mapping",
|
||||
showFreeformRoleNamesHint = false
|
||||
}: RoleMappingConfigFieldsProps) {
|
||||
const t = useTranslations();
|
||||
const { env } = useEnvContext();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
const [activeFixedRoleTagIndex, setActiveFixedRoleTagIndex] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
|
||||
const supportsMultipleRolesPerUser = isPaidUser(tierMatrix.fullRbac);
|
||||
const showSingleRoleDisclaimer =
|
||||
!env.flags.disableEnterpriseFeatures &&
|
||||
!isPaidUser(tierMatrix.fullRbac);
|
||||
|
||||
const restrictToOrgRoles = roles.length > 0;
|
||||
|
||||
const roleOptions = useMemo(
|
||||
() =>
|
||||
roles.map((role) => ({
|
||||
id: role.name,
|
||||
text: role.name
|
||||
})),
|
||||
[roles]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!supportsMultipleRolesPerUser &&
|
||||
mappingBuilderRules.length > 1
|
||||
) {
|
||||
onMappingBuilderRulesChange([mappingBuilderRules[0]]);
|
||||
}
|
||||
}, [
|
||||
supportsMultipleRolesPerUser,
|
||||
mappingBuilderRules,
|
||||
onMappingBuilderRulesChange
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!supportsMultipleRolesPerUser && fixedRoleNames.length > 1) {
|
||||
onFixedRoleNamesChange([fixedRoleNames[0]]);
|
||||
}
|
||||
}, [
|
||||
supportsMultipleRolesPerUser,
|
||||
fixedRoleNames,
|
||||
onFixedRoleNamesChange
|
||||
]);
|
||||
|
||||
const fixedRadioId = `${fieldIdPrefix}-fixed-roles-mode`;
|
||||
const builderRadioId = `${fieldIdPrefix}-mapping-builder-mode`;
|
||||
const rawRadioId = `${fieldIdPrefix}-raw-expression-mode`;
|
||||
|
||||
const mappingBuilderShowsRemoveColumn =
|
||||
supportsMultipleRolesPerUser || mappingBuilderRules.length > 1;
|
||||
|
||||
/** Same template on header + rows so 1fr/1.75fr columns line up (auto third col differs per row otherwise). */
|
||||
const mappingRulesGridClass = mappingBuilderShowsRemoveColumn
|
||||
? "md:grid md:grid-cols-[minmax(0,1fr)_minmax(0,1.75fr)_6rem] md:gap-x-3"
|
||||
: "md:grid md:grid-cols-[minmax(0,1fr)_minmax(0,1.75fr)] md:gap-x-3";
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<FormLabel className="mb-2">{t("roleMapping")}</FormLabel>
|
||||
<FormDescription className="mb-4">
|
||||
{t("roleMappingDescription")}
|
||||
</FormDescription>
|
||||
|
||||
<RadioGroup
|
||||
value={roleMappingMode}
|
||||
onValueChange={onRoleMappingModeChange}
|
||||
className="flex flex-wrap gap-x-6 gap-y-2"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="fixedRoles" id={fixedRadioId} />
|
||||
<label
|
||||
htmlFor={fixedRadioId}
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{t("roleMappingModeFixedRoles")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="mappingBuilder"
|
||||
id={builderRadioId}
|
||||
/>
|
||||
<label
|
||||
htmlFor={builderRadioId}
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{t("roleMappingModeMappingBuilder")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="rawExpression" id={rawRadioId} />
|
||||
<label
|
||||
htmlFor={rawRadioId}
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{t("roleMappingModeRawExpression")}
|
||||
</label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{showSingleRoleDisclaimer && (
|
||||
<FormDescription className="mt-3">
|
||||
{build === "saas"
|
||||
? t("singleRolePerUserPlanNotice")
|
||||
: t("singleRolePerUserEditionNotice")}
|
||||
</FormDescription>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{roleMappingMode === "fixedRoles" && (
|
||||
<div className="space-y-2 min-w-0 max-w-full">
|
||||
<TagInput
|
||||
tags={fixedRoleNames.map((name) => ({
|
||||
id: name,
|
||||
text: name
|
||||
}))}
|
||||
setTags={(nextTags) => {
|
||||
const prevTags = fixedRoleNames.map((name) => ({
|
||||
id: name,
|
||||
text: name
|
||||
}));
|
||||
const next =
|
||||
typeof nextTags === "function"
|
||||
? nextTags(prevTags)
|
||||
: nextTags;
|
||||
|
||||
let names = [
|
||||
...new Set(next.map((tag) => tag.text))
|
||||
];
|
||||
|
||||
if (!supportsMultipleRolesPerUser) {
|
||||
if (
|
||||
names.length === 0 &&
|
||||
fixedRoleNames.length > 0
|
||||
) {
|
||||
onFixedRoleNamesChange([
|
||||
fixedRoleNames[
|
||||
fixedRoleNames.length - 1
|
||||
]!
|
||||
]);
|
||||
return;
|
||||
}
|
||||
if (names.length > 1) {
|
||||
names = [names[names.length - 1]!];
|
||||
}
|
||||
}
|
||||
|
||||
onFixedRoleNamesChange(names);
|
||||
}}
|
||||
activeTagIndex={activeFixedRoleTagIndex}
|
||||
setActiveTagIndex={setActiveFixedRoleTagIndex}
|
||||
placeholder={
|
||||
restrictToOrgRoles
|
||||
? t("roleMappingFixedRolesPlaceholderSelect")
|
||||
: t("roleMappingFixedRolesPlaceholderFreeform")
|
||||
}
|
||||
enableAutocomplete={restrictToOrgRoles}
|
||||
autocompleteOptions={roleOptions}
|
||||
restrictTagsToAutocompleteOptions={restrictToOrgRoles}
|
||||
allowDuplicates={false}
|
||||
sortTags={true}
|
||||
size="sm"
|
||||
/>
|
||||
<FormDescription>
|
||||
{showFreeformRoleNamesHint
|
||||
? t("roleMappingFixedRolesDescriptionDefaultPolicy")
|
||||
: t("roleMappingFixedRolesDescriptionSameForAll")}
|
||||
</FormDescription>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{roleMappingMode === "mappingBuilder" && (
|
||||
<div className="space-y-4 min-w-0 max-w-full">
|
||||
<div className="space-y-2">
|
||||
<FormLabel>{t("roleMappingClaimPath")}</FormLabel>
|
||||
<Input
|
||||
value={mappingBuilderClaimPath}
|
||||
onChange={(e) =>
|
||||
onMappingBuilderClaimPathChange(e.target.value)
|
||||
}
|
||||
placeholder={t("roleMappingClaimPathPlaceholder")}
|
||||
/>
|
||||
<FormDescription>
|
||||
{t("roleMappingClaimPathDescription")}
|
||||
</FormDescription>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div
|
||||
className={`hidden ${mappingRulesGridClass} md:items-end`}
|
||||
>
|
||||
<FormLabel className="min-w-0">
|
||||
{t("roleMappingMatchValue")}
|
||||
</FormLabel>
|
||||
<FormLabel className="min-w-0">
|
||||
{t("roleMappingAssignRoles")}
|
||||
</FormLabel>
|
||||
{mappingBuilderShowsRemoveColumn ? (
|
||||
<span aria-hidden className="min-w-0" />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{mappingBuilderRules.map((rule, index) => (
|
||||
<BuilderRuleRow
|
||||
key={rule.id ?? `mapping-rule-${index}`}
|
||||
mappingRulesGridClass={mappingRulesGridClass}
|
||||
fieldIdPrefix={`${fieldIdPrefix}-rule-${index}`}
|
||||
roleOptions={roleOptions}
|
||||
restrictToOrgRoles={restrictToOrgRoles}
|
||||
showFreeformRoleNamesHint={
|
||||
showFreeformRoleNamesHint
|
||||
}
|
||||
supportsMultipleRolesPerUser={
|
||||
supportsMultipleRolesPerUser
|
||||
}
|
||||
showRemoveButton={mappingBuilderShowsRemoveColumn}
|
||||
rule={rule}
|
||||
onChange={(nextRule) => {
|
||||
const nextRules = mappingBuilderRules.map(
|
||||
(row, i) =>
|
||||
i === index ? nextRule : row
|
||||
);
|
||||
onMappingBuilderRulesChange(nextRules);
|
||||
}}
|
||||
onRemove={() => {
|
||||
const nextRules =
|
||||
mappingBuilderRules.filter(
|
||||
(_, i) => i !== index
|
||||
);
|
||||
onMappingBuilderRulesChange(
|
||||
nextRules.length
|
||||
? nextRules
|
||||
: [createMappingBuilderRule()]
|
||||
);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{supportsMultipleRolesPerUser ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
onMappingBuilderRulesChange([
|
||||
...mappingBuilderRules,
|
||||
createMappingBuilderRule()
|
||||
]);
|
||||
}}
|
||||
>
|
||||
{t("roleMappingAddMappingRule")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{roleMappingMode === "rawExpression" && (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
value={rawExpression}
|
||||
onChange={(e) => onRawExpressionChange(e.target.value)}
|
||||
placeholder={t("roleMappingExpressionPlaceholder")}
|
||||
/>
|
||||
<FormDescription>
|
||||
{supportsMultipleRolesPerUser
|
||||
? t("roleMappingRawExpressionResultDescription")
|
||||
: t(
|
||||
"roleMappingRawExpressionResultDescriptionSingleRole"
|
||||
)}
|
||||
</FormDescription>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BuilderRuleRow({
|
||||
rule,
|
||||
roleOptions,
|
||||
restrictToOrgRoles,
|
||||
showFreeformRoleNamesHint,
|
||||
fieldIdPrefix,
|
||||
mappingRulesGridClass,
|
||||
supportsMultipleRolesPerUser,
|
||||
showRemoveButton,
|
||||
onChange,
|
||||
onRemove
|
||||
}: {
|
||||
rule: MappingBuilderRule;
|
||||
roleOptions: Tag[];
|
||||
restrictToOrgRoles: boolean;
|
||||
showFreeformRoleNamesHint: boolean;
|
||||
fieldIdPrefix: string;
|
||||
mappingRulesGridClass: string;
|
||||
supportsMultipleRolesPerUser: boolean;
|
||||
showRemoveButton: boolean;
|
||||
onChange: (rule: MappingBuilderRule) => void;
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [activeTagIndex, setActiveTagIndex] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`grid gap-3 min-w-0 ${mappingRulesGridClass} md:items-start`}
|
||||
>
|
||||
<div className="space-y-1 min-w-0">
|
||||
<FormLabel className="text-xs md:hidden">
|
||||
{t("roleMappingMatchValue")}
|
||||
</FormLabel>
|
||||
<Input
|
||||
id={`${fieldIdPrefix}-match`}
|
||||
value={rule.matchValue}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
...rule,
|
||||
matchValue: e.target.value
|
||||
})
|
||||
}
|
||||
placeholder={t("roleMappingMatchValuePlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1 min-w-0 w-full max-w-full">
|
||||
<FormLabel className="text-xs md:hidden">
|
||||
{t("roleMappingAssignRoles")}
|
||||
</FormLabel>
|
||||
<div className="min-w-0 max-w-full">
|
||||
<TagInput
|
||||
tags={rule.roleNames.map((name) => ({
|
||||
id: name,
|
||||
text: name
|
||||
}))}
|
||||
setTags={(nextTags) => {
|
||||
const prevRoleTags = rule.roleNames.map(
|
||||
(name) => ({
|
||||
id: name,
|
||||
text: name
|
||||
})
|
||||
);
|
||||
const next =
|
||||
typeof nextTags === "function"
|
||||
? nextTags(prevRoleTags)
|
||||
: nextTags;
|
||||
|
||||
let names = [
|
||||
...new Set(next.map((tag) => tag.text))
|
||||
];
|
||||
|
||||
if (!supportsMultipleRolesPerUser) {
|
||||
if (
|
||||
names.length === 0 &&
|
||||
rule.roleNames.length > 0
|
||||
) {
|
||||
onChange({
|
||||
...rule,
|
||||
roleNames: [
|
||||
rule.roleNames[
|
||||
rule.roleNames.length - 1
|
||||
]!
|
||||
]
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (names.length > 1) {
|
||||
names = [names[names.length - 1]!];
|
||||
}
|
||||
}
|
||||
|
||||
onChange({
|
||||
...rule,
|
||||
roleNames: names
|
||||
});
|
||||
}}
|
||||
activeTagIndex={activeTagIndex}
|
||||
setActiveTagIndex={setActiveTagIndex}
|
||||
placeholder={
|
||||
restrictToOrgRoles
|
||||
? t("roleMappingAssignRoles")
|
||||
: t("roleMappingAssignRolesPlaceholderFreeform")
|
||||
}
|
||||
enableAutocomplete={restrictToOrgRoles}
|
||||
autocompleteOptions={roleOptions}
|
||||
restrictTagsToAutocompleteOptions={restrictToOrgRoles}
|
||||
allowDuplicates={false}
|
||||
sortTags={true}
|
||||
size="sm"
|
||||
styleClasses={{
|
||||
inlineTagsContainer: "min-w-0 max-w-full"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{showFreeformRoleNamesHint && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("roleMappingBuilderFreeformRowHint")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{showRemoveButton ? (
|
||||
<div className="flex min-w-0 justify-end md:justify-start md:pt-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-9 shrink-0 px-2"
|
||||
onClick={onRemove}
|
||||
>
|
||||
{t("roleMappingRemoveRule")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
322
src/components/SiteProvisioningKeysTable.tsx
Normal file
322
src/components/SiteProvisioningKeysTable.tsx
Normal file
@@ -0,0 +1,322 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
DataTable,
|
||||
ExtendedColumnDef
|
||||
} from "@app/components/ui/data-table";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from "@app/components/ui/dropdown-menu";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import CreateSiteProvisioningKeyCredenza from "@app/components/CreateSiteProvisioningKeyCredenza";
|
||||
import EditSiteProvisioningKeyCredenza from "@app/components/EditSiteProvisioningKeyCredenza";
|
||||
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { formatAxiosError } from "@app/lib/api";
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import moment from "moment";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { build } from "@server/build";
|
||||
import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
|
||||
export type SiteProvisioningKeyRow = {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
createdAt: string;
|
||||
lastUsed: string | null;
|
||||
maxBatchSize: number | null;
|
||||
numUsed: number;
|
||||
validUntil: string | null;
|
||||
approveNewSites: boolean;
|
||||
};
|
||||
|
||||
type SiteProvisioningKeysTableProps = {
|
||||
keys: SiteProvisioningKeyRow[];
|
||||
orgId: string;
|
||||
};
|
||||
|
||||
export default function SiteProvisioningKeysTable({
|
||||
keys,
|
||||
orgId
|
||||
}: SiteProvisioningKeysTableProps) {
|
||||
const router = useRouter();
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [selected, setSelected] = useState<SiteProvisioningKeyRow | null>(
|
||||
null
|
||||
);
|
||||
const [rows, setRows] = useState<SiteProvisioningKeyRow[]>(keys);
|
||||
const api = createApiClient(useEnvContext());
|
||||
const t = useTranslations();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
const canUseSiteProvisioning =
|
||||
isPaidUser(tierMatrix[TierFeature.SiteProvisioningKeys]) &&
|
||||
build !== "oss";
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [editingKey, setEditingKey] =
|
||||
useState<SiteProvisioningKeyRow | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setRows(keys);
|
||||
}, [keys]);
|
||||
|
||||
const refreshData = async () => {
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: t("refreshError"),
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteKey = async (siteProvisioningKeyId: string) => {
|
||||
try {
|
||||
await api.delete(
|
||||
`/org/${orgId}/site-provisioning-key/${siteProvisioningKeyId}`
|
||||
);
|
||||
router.refresh();
|
||||
setIsDeleteModalOpen(false);
|
||||
setSelected(null);
|
||||
setRows((prev) => prev.filter((row) => row.id !== siteProvisioningKeyId));
|
||||
} catch (e) {
|
||||
console.error(t("provisioningKeysErrorDelete"), e);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("provisioningKeysErrorDelete"),
|
||||
description: formatAxiosError(
|
||||
e,
|
||||
t("provisioningKeysErrorDeleteMessage")
|
||||
)
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ExtendedColumnDef<SiteProvisioningKeyRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
enableHiding: false,
|
||||
friendlyName: t("name"),
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
column.toggleSorting(column.getIsSorted() === "asc")
|
||||
}
|
||||
>
|
||||
{t("name")}
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "key",
|
||||
friendlyName: t("key"),
|
||||
header: () => <span className="p-3">{t("key")}</span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return <span className="font-mono">{r.key}</span>;
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "maxBatchSize",
|
||||
friendlyName: t("provisioningKeysMaxBatchSize"),
|
||||
header: () => (
|
||||
<span className="p-3">{t("provisioningKeysMaxBatchSize")}</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return (
|
||||
<span>
|
||||
{r.maxBatchSize == null
|
||||
? t("provisioningKeysMaxBatchUnlimited")
|
||||
: r.maxBatchSize}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "numUsed",
|
||||
friendlyName: t("provisioningKeysNumUsed"),
|
||||
header: () => (
|
||||
<span className="p-3">{t("provisioningKeysNumUsed")}</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return <span>{r.numUsed}</span>;
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "validUntil",
|
||||
friendlyName: t("provisioningKeysValidUntil"),
|
||||
header: () => (
|
||||
<span className="p-3">{t("provisioningKeysValidUntil")}</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return (
|
||||
<span>
|
||||
{r.validUntil
|
||||
? moment(r.validUntil).format("lll")
|
||||
: t("provisioningKeysNoExpiry")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "lastUsed",
|
||||
friendlyName: t("provisioningKeysLastUsed"),
|
||||
header: () => (
|
||||
<span className="p-3">{t("provisioningKeysLastUsed")}</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return (
|
||||
<span>
|
||||
{r.lastUsed
|
||||
? moment(r.lastUsed).format("lll")
|
||||
: t("provisioningKeysNeverUsed")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
friendlyName: t("createdAt"),
|
||||
header: () => <span className="p-3">{t("createdAt")}</span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return <span>{moment(r.createdAt).format("lll")}</span>;
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
enableHiding: false,
|
||||
header: () => <span className="p-3"></span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">
|
||||
{t("openMenu")}
|
||||
</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
disabled={!canUseSiteProvisioning}
|
||||
onClick={() => {
|
||||
setEditingKey(r);
|
||||
setEditOpen(true);
|
||||
}}
|
||||
>
|
||||
{t("edit")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
disabled={!canUseSiteProvisioning}
|
||||
onClick={() => {
|
||||
setSelected(r);
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<span className="text-red-500">
|
||||
{t("delete")}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<CreateSiteProvisioningKeyCredenza
|
||||
open={createOpen}
|
||||
setOpen={setCreateOpen}
|
||||
orgId={orgId}
|
||||
/>
|
||||
|
||||
<EditSiteProvisioningKeyCredenza
|
||||
open={editOpen}
|
||||
setOpen={(v) => {
|
||||
setEditOpen(v);
|
||||
if (!v) {
|
||||
setEditingKey(null);
|
||||
}
|
||||
}}
|
||||
orgId={orgId}
|
||||
provisioningKey={editingKey}
|
||||
/>
|
||||
|
||||
{selected && (
|
||||
<ConfirmDeleteDialog
|
||||
open={isDeleteModalOpen}
|
||||
setOpen={(val) => {
|
||||
setIsDeleteModalOpen(val);
|
||||
if (!val) {
|
||||
setSelected(null);
|
||||
}
|
||||
}}
|
||||
dialog={
|
||||
<div className="space-y-2">
|
||||
<p>{t("provisioningKeysQuestionRemove")}</p>
|
||||
<p>{t("provisioningKeysMessageRemove")}</p>
|
||||
</div>
|
||||
}
|
||||
buttonText={t("provisioningKeysDeleteConfirm")}
|
||||
onConfirm={async () => deleteKey(selected.id)}
|
||||
string={selected.name}
|
||||
title={t("provisioningKeysDelete")}
|
||||
/>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
persistPageSize="Org-provisioning-keys-table"
|
||||
title={t("provisioningKeys")}
|
||||
searchPlaceholder={t("searchProvisioningKeys")}
|
||||
searchColumn="name"
|
||||
onAdd={() => {
|
||||
if (canUseSiteProvisioning) {
|
||||
setCreateOpen(true);
|
||||
}
|
||||
}}
|
||||
addButtonDisabled={!canUseSiteProvisioning}
|
||||
onRefresh={refreshData}
|
||||
isRefreshing={isRefreshing}
|
||||
refreshButtonDisabled={!canUseSiteProvisioning}
|
||||
addButtonText={t("provisioningKeysAdd")}
|
||||
enableColumnVisibility={true}
|
||||
stickyLeftColumn="name"
|
||||
stickyRightColumn="actions"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -342,7 +342,8 @@ export default function SitesTable({
|
||||
"jupiter",
|
||||
"saturn",
|
||||
"uranus",
|
||||
"neptune"
|
||||
"neptune",
|
||||
"pluto"
|
||||
].includes(originalRow.exitNodeName.toLowerCase());
|
||||
|
||||
if (isCloudNode) {
|
||||
|
||||
@@ -770,7 +770,7 @@ export default function UserDevicesTable({
|
||||
columns={columns}
|
||||
rows={userClients || []}
|
||||
tableId="user-clients"
|
||||
searchPlaceholder={t("resourcesSearch")}
|
||||
searchPlaceholder={t("userDevicesSearch")}
|
||||
onRefresh={refreshData}
|
||||
isRefreshing={isRefreshing || isFiltering}
|
||||
enableColumnVisibility
|
||||
|
||||
69
src/components/UserRoleBadges.tsx
Normal file
69
src/components/UserRoleBadges.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Badge, badgeVariants } from "@app/components/ui/badge";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger
|
||||
} from "@app/components/ui/popover";
|
||||
import { cn } from "@app/lib/cn";
|
||||
|
||||
const MAX_ROLE_BADGES = 3;
|
||||
|
||||
export default function UserRoleBadges({
|
||||
roleLabels
|
||||
}: {
|
||||
roleLabels: string[];
|
||||
}) {
|
||||
const visible = roleLabels.slice(0, MAX_ROLE_BADGES);
|
||||
const overflow = roleLabels.slice(MAX_ROLE_BADGES);
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{visible.map((label, i) => (
|
||||
<Badge key={`${label}-${i}`} variant="secondary">
|
||||
{label}
|
||||
</Badge>
|
||||
))}
|
||||
{overflow.length > 0 && (
|
||||
<OverflowRolesPopover labels={overflow} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OverflowRolesPopover({ labels }: { labels: string[] }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
badgeVariants({ variant: "secondary" }),
|
||||
"border-dashed"
|
||||
)}
|
||||
onMouseEnter={() => setOpen(true)}
|
||||
onMouseLeave={() => setOpen(false)}
|
||||
>
|
||||
+{labels.length}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
side="top"
|
||||
className="w-auto max-w-xs p-2"
|
||||
onMouseEnter={() => setOpen(true)}
|
||||
onMouseLeave={() => setOpen(false)}
|
||||
>
|
||||
<ul className="space-y-1 text-sm">
|
||||
{labels.map((label, i) => (
|
||||
<li key={`${label}-${i}`}>{label}</li>
|
||||
))}
|
||||
</ul>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useUserContext } from "@app/hooks/useUserContext";
|
||||
import { useTranslations } from "next-intl";
|
||||
import IdpTypeBadge from "./IdpTypeBadge";
|
||||
import UserRoleBadges from "./UserRoleBadges";
|
||||
|
||||
export type UserRow = {
|
||||
id: string;
|
||||
@@ -36,7 +37,7 @@ export type UserRow = {
|
||||
type: string;
|
||||
idpVariant: string | null;
|
||||
status: string;
|
||||
role: string;
|
||||
roleLabels: string[];
|
||||
isOwner: boolean;
|
||||
};
|
||||
|
||||
@@ -124,7 +125,8 @@ export default function UsersTable({ users: u }: UsersTableProps) {
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "role",
|
||||
id: "role",
|
||||
accessorFn: (row) => row.roleLabels.join(", "),
|
||||
friendlyName: t("role"),
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
@@ -140,13 +142,7 @@ export default function UsersTable({ users: u }: UsersTableProps) {
|
||||
);
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const userRow = row.original;
|
||||
|
||||
return (
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<span>{userRow.role}</span>
|
||||
</div>
|
||||
);
|
||||
return <UserRoleBadges roleLabels={row.original.roleLabels} />;
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
87
src/components/idp/OidcIdpProviderTypeSelect.tsx
Normal file
87
src/components/idp/OidcIdpProviderTypeSelect.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
StrategySelect,
|
||||
type StrategyOption
|
||||
} from "@app/components/StrategySelect";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import type { IdpOidcProviderType } from "@app/lib/idp/oidcIdpProviderDefaults";
|
||||
import { useTranslations } from "next-intl";
|
||||
import Image from "next/image";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
type Props = {
|
||||
value: IdpOidcProviderType;
|
||||
onTypeChange: (type: IdpOidcProviderType) => void;
|
||||
};
|
||||
|
||||
export function OidcIdpProviderTypeSelect({ value, onTypeChange }: Props) {
|
||||
const t = useTranslations();
|
||||
const { env } = useEnvContext();
|
||||
const hideTemplates = env.flags.disableEnterpriseFeatures;
|
||||
|
||||
useEffect(() => {
|
||||
if (hideTemplates && (value === "google" || value === "azure")) {
|
||||
onTypeChange("oidc");
|
||||
}
|
||||
}, [hideTemplates, value, onTypeChange]);
|
||||
|
||||
const options: ReadonlyArray<StrategyOption<IdpOidcProviderType>> =
|
||||
useMemo(() => {
|
||||
const base: StrategyOption<IdpOidcProviderType>[] = [
|
||||
{
|
||||
id: "oidc",
|
||||
title: "OAuth2/OIDC",
|
||||
description: t("idpOidcDescription")
|
||||
}
|
||||
];
|
||||
if (hideTemplates) {
|
||||
return base;
|
||||
}
|
||||
return [
|
||||
...base,
|
||||
{
|
||||
id: "google",
|
||||
title: t("idpGoogleTitle"),
|
||||
description: t("idpGoogleDescription"),
|
||||
icon: (
|
||||
<Image
|
||||
src="/idp/google.png"
|
||||
alt={t("idpGoogleAlt")}
|
||||
width={24}
|
||||
height={24}
|
||||
className="rounded"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
id: "azure",
|
||||
title: t("idpAzureTitle"),
|
||||
description: t("idpAzureDescription"),
|
||||
icon: (
|
||||
<Image
|
||||
src="/idp/azure.png"
|
||||
alt={t("idpAzureAlt")}
|
||||
width={24}
|
||||
height={24}
|
||||
className="rounded"
|
||||
/>
|
||||
)
|
||||
}
|
||||
];
|
||||
}, [hideTemplates, t]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-2">
|
||||
<span className="text-sm font-medium">{t("idpType")}</span>
|
||||
</div>
|
||||
<StrategySelect
|
||||
value={value}
|
||||
options={options}
|
||||
onChange={onTypeChange}
|
||||
cols={3}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
108
src/components/machines-selector.tsx
Normal file
108
src/components/machines-selector.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import type { ListClientsResponse } from "@server/routers/client";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useDebounce } from "use-debounce";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "./ui/command";
|
||||
import { cn } from "@app/lib/cn";
|
||||
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
export type SelectedMachine = Pick<
|
||||
ListClientsResponse["clients"][number],
|
||||
"name" | "clientId"
|
||||
>;
|
||||
|
||||
export type MachineSelectorProps = {
|
||||
orgId: string;
|
||||
selectedMachines?: SelectedMachine[];
|
||||
onSelectMachines: (machine: SelectedMachine[]) => void;
|
||||
};
|
||||
|
||||
export function MachinesSelector({
|
||||
orgId,
|
||||
selectedMachines = [],
|
||||
onSelectMachines
|
||||
}: MachineSelectorProps) {
|
||||
const t = useTranslations();
|
||||
const [machineSearchQuery, setMachineSearchQuery] = useState("");
|
||||
|
||||
const [debouncedValue] = useDebounce(machineSearchQuery, 150);
|
||||
|
||||
const { data: machines = [] } = useQuery(
|
||||
orgQueries.machineClients({ orgId, perPage: 10, query: debouncedValue })
|
||||
);
|
||||
|
||||
// always include the selected machines in the list of machines shown (if the user isn't searching)
|
||||
const machinesShown = useMemo(() => {
|
||||
const allMachines: Array<SelectedMachine> = [...machines];
|
||||
if (debouncedValue.trim().length === 0) {
|
||||
for (const machine of selectedMachines) {
|
||||
if (
|
||||
!allMachines.find((mc) => mc.clientId === machine.clientId)
|
||||
) {
|
||||
allMachines.unshift(machine);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return allMachines;
|
||||
}, [machines, selectedMachines, debouncedValue]);
|
||||
|
||||
const selectedMachinesIds = new Set(
|
||||
selectedMachines.map((m) => m.clientId)
|
||||
);
|
||||
|
||||
return (
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder={t("machineSearch")}
|
||||
value={machineSearchQuery}
|
||||
onValueChange={setMachineSearchQuery}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("machineNotFound")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{machinesShown.map((m) => (
|
||||
<CommandItem
|
||||
value={`${m.name}:${m.clientId}`}
|
||||
key={m.clientId}
|
||||
onSelect={() => {
|
||||
let newMachineClients = [];
|
||||
if (selectedMachinesIds.has(m.clientId)) {
|
||||
newMachineClients = selectedMachines.filter(
|
||||
(mc) => mc.clientId !== m.clientId
|
||||
);
|
||||
} else {
|
||||
newMachineClients = [
|
||||
...selectedMachines,
|
||||
m
|
||||
];
|
||||
}
|
||||
onSelectMachines(newMachineClients);
|
||||
}}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedMachinesIds.has(m.clientId)
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{`${m.name}`}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
@@ -10,14 +10,14 @@ import {
|
||||
import { CheckboxWithLabel } from "./ui/checkbox";
|
||||
import { OptionSelect, type OptionSelectOption } from "./OptionSelect";
|
||||
import { useState } from "react";
|
||||
import { FaCubes, FaDocker, FaWindows } from "react-icons/fa";
|
||||
import { Terminal } from "lucide-react";
|
||||
import { FaApple, FaCubes, FaDocker, FaLinux, FaWindows } from "react-icons/fa";
|
||||
import { SiKubernetes, SiNixos } from "react-icons/si";
|
||||
|
||||
export type CommandItem = string | { title: string; command: string };
|
||||
|
||||
const PLATFORMS = [
|
||||
"unix",
|
||||
"linux",
|
||||
"macos",
|
||||
"docker",
|
||||
"kubernetes",
|
||||
"podman",
|
||||
@@ -43,7 +43,7 @@ export function NewtSiteInstallCommands({
|
||||
const t = useTranslations();
|
||||
|
||||
const [acceptClients, setAcceptClients] = useState(true);
|
||||
const [platform, setPlatform] = useState<Platform>("unix");
|
||||
const [platform, setPlatform] = useState<Platform>("linux");
|
||||
const [architecture, setArchitecture] = useState(
|
||||
() => getArchitectures(platform)[0]
|
||||
);
|
||||
@@ -54,8 +54,68 @@ export function NewtSiteInstallCommands({
|
||||
: "";
|
||||
|
||||
const commandList: Record<Platform, Record<string, CommandItem[]>> = {
|
||||
unix: {
|
||||
All: [
|
||||
linux: {
|
||||
Run: [
|
||||
{
|
||||
title: t("install"),
|
||||
command: `curl -fsSL https://static.pangolin.net/get-newt.sh | bash`
|
||||
},
|
||||
{
|
||||
title: t("run"),
|
||||
command: `newt --id ${id} --secret ${secret} --endpoint ${endpoint}${acceptClientsFlag}`
|
||||
}
|
||||
],
|
||||
"Systemd Service": [
|
||||
{
|
||||
title: t("install"),
|
||||
command: `curl -fsSL https://static.pangolin.net/get-newt.sh | bash`
|
||||
},
|
||||
{
|
||||
title: t("envFile"),
|
||||
command: `# Create the directory and environment file
|
||||
sudo install -d -m 0755 /etc/newt
|
||||
sudo tee /etc/newt/newt.env > /dev/null << 'EOF'
|
||||
NEWT_ID=${id}
|
||||
NEWT_SECRET=${secret}
|
||||
PANGOLIN_ENDPOINT=${endpoint}${!acceptClients ? `
|
||||
DISABLE_CLIENTS=true` : ""}
|
||||
EOF
|
||||
sudo chmod 600 /etc/newt/newt.env`
|
||||
},
|
||||
{
|
||||
title: t("serviceFile"),
|
||||
command: `sudo tee /etc/systemd/system/newt.service > /dev/null << 'EOF'
|
||||
[Unit]
|
||||
Description=Newt
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
EnvironmentFile=/etc/newt/newt.env
|
||||
ExecStart=/usr/local/bin/newt
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
UMask=0077
|
||||
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF`
|
||||
},
|
||||
{
|
||||
title: t("enableAndStart"),
|
||||
command: `sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now newt`
|
||||
}
|
||||
]
|
||||
},
|
||||
macos: {
|
||||
Run: [
|
||||
{
|
||||
title: t("install"),
|
||||
command: `curl -fsSL https://static.pangolin.net/get-newt.sh | bash`
|
||||
@@ -131,7 +191,7 @@ WantedBy=default.target`
|
||||
]
|
||||
},
|
||||
nixos: {
|
||||
All: [
|
||||
Flake: [
|
||||
`nix run 'nixpkgs#fosrl-newt' -- --id ${id} --secret ${secret} --endpoint ${endpoint}${acceptClientsFlag}`
|
||||
]
|
||||
}
|
||||
@@ -172,9 +232,9 @@ WantedBy=default.target`
|
||||
|
||||
<OptionSelect<string>
|
||||
label={
|
||||
["docker", "podman"].includes(platform)
|
||||
? t("method")
|
||||
: t("architecture")
|
||||
platform === "windows"
|
||||
? t("architecture")
|
||||
: t("method")
|
||||
}
|
||||
options={getArchitectures(platform).map((arch) => ({
|
||||
value: arch,
|
||||
@@ -261,8 +321,10 @@ function getPlatformIcon(platformName: Platform) {
|
||||
switch (platformName) {
|
||||
case "windows":
|
||||
return <FaWindows className="h-4 w-4 mr-2" />;
|
||||
case "unix":
|
||||
return <Terminal className="h-4 w-4 mr-2" />;
|
||||
case "linux":
|
||||
return <FaLinux className="h-4 w-4 mr-2" />;
|
||||
case "macos":
|
||||
return <FaApple className="h-4 w-4 mr-2" />;
|
||||
case "docker":
|
||||
return <FaDocker className="h-4 w-4 mr-2" />;
|
||||
case "kubernetes":
|
||||
@@ -272,7 +334,7 @@ function getPlatformIcon(platformName: Platform) {
|
||||
case "nixos":
|
||||
return <SiNixos className="h-4 w-4 mr-2" />;
|
||||
default:
|
||||
return <Terminal className="h-4 w-4 mr-2" />;
|
||||
return <FaLinux className="h-4 w-4 mr-2" />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,8 +342,10 @@ function getPlatformName(platformName: Platform) {
|
||||
switch (platformName) {
|
||||
case "windows":
|
||||
return "Windows";
|
||||
case "unix":
|
||||
return "Unix & macOS";
|
||||
case "linux":
|
||||
return "Linux";
|
||||
case "macos":
|
||||
return "macOS";
|
||||
case "docker":
|
||||
return "Docker";
|
||||
case "kubernetes":
|
||||
@@ -291,14 +355,16 @@ function getPlatformName(platformName: Platform) {
|
||||
case "nixos":
|
||||
return "NixOS";
|
||||
default:
|
||||
return "Unix / macOS";
|
||||
return "Linux";
|
||||
}
|
||||
}
|
||||
|
||||
function getArchitectures(platform: Platform) {
|
||||
switch (platform) {
|
||||
case "unix":
|
||||
return ["All"];
|
||||
case "linux":
|
||||
return ["Run", "Systemd Service"];
|
||||
case "macos":
|
||||
return ["Run"];
|
||||
case "windows":
|
||||
return ["x64"];
|
||||
case "docker":
|
||||
@@ -308,8 +374,8 @@ function getArchitectures(platform: Platform) {
|
||||
case "podman":
|
||||
return ["Podman Quadlet", "Podman Run"];
|
||||
case "nixos":
|
||||
return ["All"];
|
||||
return ["Flake"];
|
||||
default:
|
||||
return ["x64"];
|
||||
return ["Run"];
|
||||
}
|
||||
}
|
||||
|
||||
97
src/components/resource-selector.tsx
Normal file
97
src/components/resource-selector.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "./ui/command";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import type { ListResourcesResponse } from "@server/routers/resource";
|
||||
import { useDebounce } from "use-debounce";
|
||||
|
||||
export type SelectedResource = Pick<
|
||||
ListResourcesResponse["resources"][number],
|
||||
"name" | "resourceId" | "fullDomain" | "niceId" | "ssl"
|
||||
>;
|
||||
|
||||
export type ResourceSelectorProps = {
|
||||
orgId: string;
|
||||
selectedResource?: SelectedResource | null;
|
||||
onSelectResource: (resource: SelectedResource) => void;
|
||||
};
|
||||
|
||||
export function ResourceSelector({
|
||||
orgId,
|
||||
selectedResource,
|
||||
onSelectResource
|
||||
}: ResourceSelectorProps) {
|
||||
const t = useTranslations();
|
||||
const [resourceSearchQuery, setResourceSearchQuery] = useState("");
|
||||
|
||||
const [debouncedSearchQuery] = useDebounce(resourceSearchQuery, 150);
|
||||
|
||||
const { data: resources = [] } = useQuery(
|
||||
orgQueries.resources({
|
||||
orgId: orgId,
|
||||
query: debouncedSearchQuery,
|
||||
perPage: 10
|
||||
})
|
||||
);
|
||||
|
||||
// always include the selected resource in the list of resources shown
|
||||
const resourcesShown = useMemo(() => {
|
||||
const allResources: Array<SelectedResource> = [...resources];
|
||||
if (
|
||||
debouncedSearchQuery.trim().length === 0 &&
|
||||
selectedResource &&
|
||||
!allResources.find(
|
||||
(resource) =>
|
||||
resource.resourceId === selectedResource?.resourceId
|
||||
)
|
||||
) {
|
||||
allResources.unshift(selectedResource);
|
||||
}
|
||||
return allResources;
|
||||
}, [debouncedSearchQuery, resources, selectedResource]);
|
||||
|
||||
return (
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder={t("resourceSearch")}
|
||||
value={resourceSearchQuery}
|
||||
onValueChange={setResourceSearchQuery}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("resourcesNotFound")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{resourcesShown.map((r) => (
|
||||
<CommandItem
|
||||
value={`${r.name}:${r.resourceId}`}
|
||||
key={r.resourceId}
|
||||
onSelect={() => {
|
||||
onSelectResource(r);
|
||||
}}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
r.resourceId ===
|
||||
selectedResource?.resourceId
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{`${r.name}`}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { cn } from "@app/lib/cn";
|
||||
import type { DockerState } from "@app/lib/docker";
|
||||
import { parseHostTarget } from "@app/lib/parseHostTarget";
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import { CaretSortIcon } from "@radix-ui/react-icons";
|
||||
import type { ListSitesResponse } from "@server/routers/site";
|
||||
import { type ListTargetsResponse } from "@server/routers/target";
|
||||
import type { ArrayElement } from "@server/types/ArrayElement";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useMemo, useState } from "react";
|
||||
import { ContainersSelector } from "./ContainersSelector";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
@@ -20,7 +23,7 @@ import {
|
||||
import { Input } from "./ui/input";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger } from "./ui/select";
|
||||
import { useEffect } from "react";
|
||||
import { SitesSelector } from "./site-selector";
|
||||
|
||||
type SiteWithUpdateAvailable = ListSitesResponse["sites"][number];
|
||||
|
||||
@@ -36,14 +39,14 @@ export type LocalTarget = Omit<
|
||||
export type ResourceTargetAddressItemProps = {
|
||||
getDockerStateForSite: (siteId: number) => DockerState;
|
||||
updateTarget: (targetId: number, data: Partial<LocalTarget>) => void;
|
||||
sites: SiteWithUpdateAvailable[];
|
||||
orgId: string;
|
||||
proxyTarget: LocalTarget;
|
||||
isHttp: boolean;
|
||||
refreshContainersForSite: (siteId: number) => void;
|
||||
};
|
||||
|
||||
export function ResourceTargetAddressItem({
|
||||
sites,
|
||||
orgId,
|
||||
getDockerStateForSite,
|
||||
updateTarget,
|
||||
proxyTarget,
|
||||
@@ -52,9 +55,23 @@ export function ResourceTargetAddressItem({
|
||||
}: ResourceTargetAddressItemProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
const selectedSite = sites.find(
|
||||
(site) => site.siteId === proxyTarget.siteId
|
||||
);
|
||||
const [selectedSite, setSelectedSite] = useState<Pick<
|
||||
SiteWithUpdateAvailable,
|
||||
"name" | "siteId" | "type"
|
||||
> | null>(() => {
|
||||
if (
|
||||
proxyTarget.siteName &&
|
||||
proxyTarget.siteType &&
|
||||
proxyTarget.siteId
|
||||
) {
|
||||
return {
|
||||
name: proxyTarget.siteName,
|
||||
siteId: proxyTarget.siteId,
|
||||
type: proxyTarget.siteType
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const handleContainerSelectForTarget = (
|
||||
hostname: string,
|
||||
@@ -70,28 +87,23 @@ export function ResourceTargetAddressItem({
|
||||
return (
|
||||
<div className="flex items-center w-full" key={proxyTarget.targetId}>
|
||||
<div className="flex items-center w-full justify-start py-0 space-x-2 px-0 cursor-default border border-input rounded-md">
|
||||
{selectedSite &&
|
||||
selectedSite.type === "newt" &&
|
||||
(() => {
|
||||
const dockerState = getDockerStateForSite(
|
||||
selectedSite.siteId
|
||||
);
|
||||
return (
|
||||
<ContainersSelector
|
||||
site={selectedSite}
|
||||
containers={dockerState.containers}
|
||||
isAvailable={dockerState.isAvailable}
|
||||
onContainerSelect={
|
||||
handleContainerSelectForTarget
|
||||
}
|
||||
onRefresh={() =>
|
||||
refreshContainersForSite(
|
||||
selectedSite.siteId
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
{selectedSite && selectedSite.type === "newt" && (
|
||||
<ContainersSelector
|
||||
site={selectedSite}
|
||||
containers={
|
||||
getDockerStateForSite(selectedSite.siteId)
|
||||
.containers
|
||||
}
|
||||
isAvailable={
|
||||
getDockerStateForSite(selectedSite.siteId)
|
||||
.isAvailable
|
||||
}
|
||||
onContainerSelect={handleContainerSelectForTarget}
|
||||
onRefresh={() =>
|
||||
refreshContainersForSite(selectedSite.siteId)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
@@ -113,39 +125,18 @@ export function ResourceTargetAddressItem({
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-45">
|
||||
<Command>
|
||||
<CommandInput placeholder={t("siteSearch")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("siteNotFound")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{sites.map((site) => (
|
||||
<CommandItem
|
||||
key={site.siteId}
|
||||
value={`${site.siteId}:${site.name}`}
|
||||
onSelect={() =>
|
||||
updateTarget(
|
||||
proxyTarget.targetId,
|
||||
{
|
||||
siteId: site.siteId
|
||||
}
|
||||
)
|
||||
}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
site.siteId ===
|
||||
proxyTarget.siteId
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{site.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
<SitesSelector
|
||||
orgId={orgId}
|
||||
selectedSite={selectedSite}
|
||||
onSelectSite={(site) => {
|
||||
updateTarget(proxyTarget.targetId, {
|
||||
siteId: site.siteId,
|
||||
siteType: site.type,
|
||||
siteName: site.name
|
||||
});
|
||||
setSelectedSite(site);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
|
||||
96
src/components/site-selector.tsx
Normal file
96
src/components/site-selector.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import type { ListSitesResponse } from "@server/routers/site";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useMemo, useState } from "react";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "./ui/command";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useDebounce } from "use-debounce";
|
||||
|
||||
export type Selectedsite = Pick<
|
||||
ListSitesResponse["sites"][number],
|
||||
"name" | "siteId" | "type"
|
||||
>;
|
||||
|
||||
export type SitesSelectorProps = {
|
||||
orgId: string;
|
||||
selectedSite?: Selectedsite | null;
|
||||
onSelectSite: (selected: Selectedsite) => void;
|
||||
filterTypes?: string[];
|
||||
};
|
||||
|
||||
export function SitesSelector({
|
||||
orgId,
|
||||
selectedSite,
|
||||
onSelectSite,
|
||||
filterTypes
|
||||
}: SitesSelectorProps) {
|
||||
const t = useTranslations();
|
||||
const [siteSearchQuery, setSiteSearchQuery] = useState("");
|
||||
const [debouncedQuery] = useDebounce(siteSearchQuery, 150);
|
||||
|
||||
const { data: sites = [] } = useQuery(
|
||||
orgQueries.sites({
|
||||
orgId,
|
||||
query: debouncedQuery,
|
||||
perPage: 10
|
||||
})
|
||||
);
|
||||
|
||||
// always include the selected site in the list of sites shown
|
||||
const sitesShown = useMemo(() => {
|
||||
const allSites: Array<Selectedsite> = filterTypes
|
||||
? sites.filter((s) => filterTypes.includes(s.type))
|
||||
: [...sites];
|
||||
if (
|
||||
debouncedQuery.trim().length === 0 &&
|
||||
selectedSite &&
|
||||
!allSites.find((site) => site.siteId === selectedSite?.siteId)
|
||||
) {
|
||||
allSites.unshift(selectedSite);
|
||||
}
|
||||
return allSites;
|
||||
}, [debouncedQuery, sites, selectedSite, filterTypes]);
|
||||
|
||||
return (
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder={t("siteSearch")}
|
||||
value={siteSearchQuery}
|
||||
onValueChange={(v) => setSiteSearchQuery(v)}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("siteNotFound")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{sitesShown.map((site) => (
|
||||
<CommandItem
|
||||
key={site.siteId}
|
||||
value={`${site.siteId}:${site.name}`}
|
||||
onSelect={() => {
|
||||
onSelectSite(site);
|
||||
}}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
site.siteId === selectedSite?.siteId
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{site.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,23 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
// import { Command, CommandList, CommandItem, CommandGroup, CommandEmpty } from '../ui/command';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { TagInputStyleClassesProps, type Tag as TagType } from "./tag-input";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "../ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
PopoverTrigger
|
||||
} from "../ui/popover";
|
||||
import { Button } from "../ui/button";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Check } from "lucide-react";
|
||||
|
||||
type AutocompleteProps = {
|
||||
tags: TagType[];
|
||||
@@ -20,6 +33,8 @@ type AutocompleteProps = {
|
||||
inlineTags?: boolean;
|
||||
classStyleProps: TagInputStyleClassesProps["autoComplete"];
|
||||
usePortal?: boolean;
|
||||
/** Narrows the dropdown list from the main field (cmdk search filters further). */
|
||||
filterQuery?: string;
|
||||
};
|
||||
|
||||
export const Autocomplete: React.FC<AutocompleteProps> = ({
|
||||
@@ -35,10 +50,10 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
|
||||
inlineTags,
|
||||
children,
|
||||
classStyleProps,
|
||||
usePortal
|
||||
usePortal,
|
||||
filterQuery = ""
|
||||
}) => {
|
||||
const triggerContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
const popoverContentRef = useRef<HTMLDivElement | null>(null);
|
||||
const t = useTranslations();
|
||||
@@ -46,17 +61,21 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
|
||||
const [popoverWidth, setPopoverWidth] = useState<number>(0);
|
||||
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
const [popooverContentTop, setPopoverContentTop] = useState<number>(0);
|
||||
const [selectedIndex, setSelectedIndex] = useState<number>(-1);
|
||||
const [commandResetKey, setCommandResetKey] = useState(0);
|
||||
|
||||
// Dynamically calculate the top position for the popover content
|
||||
useEffect(() => {
|
||||
if (!triggerContainerRef.current || !triggerRef.current) return;
|
||||
setPopoverContentTop(
|
||||
triggerContainerRef.current?.getBoundingClientRect().bottom -
|
||||
triggerRef.current?.getBoundingClientRect().bottom
|
||||
const visibleOptions = useMemo(() => {
|
||||
const q = filterQuery.trim().toLowerCase();
|
||||
if (!q) return autocompleteOptions;
|
||||
return autocompleteOptions.filter((option) =>
|
||||
option.text.toLowerCase().includes(q)
|
||||
);
|
||||
}, [tags]);
|
||||
}, [autocompleteOptions, filterQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPopoverOpen) {
|
||||
setCommandResetKey((k) => k + 1);
|
||||
}
|
||||
}, [isPopoverOpen]);
|
||||
|
||||
// Close the popover when clicking outside of it
|
||||
useEffect(() => {
|
||||
@@ -135,36 +154,6 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
|
||||
if (userOnBlur) userOnBlur(event);
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (!isPopoverOpen) return;
|
||||
|
||||
switch (event.key) {
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
setSelectedIndex((prevIndex) =>
|
||||
prevIndex <= 0
|
||||
? autocompleteOptions.length - 1
|
||||
: prevIndex - 1
|
||||
);
|
||||
break;
|
||||
case "ArrowDown":
|
||||
event.preventDefault();
|
||||
setSelectedIndex((prevIndex) =>
|
||||
prevIndex === autocompleteOptions.length - 1
|
||||
? 0
|
||||
: prevIndex + 1
|
||||
);
|
||||
break;
|
||||
case "Enter":
|
||||
event.preventDefault();
|
||||
if (selectedIndex !== -1) {
|
||||
toggleTag(autocompleteOptions[selectedIndex]);
|
||||
setSelectedIndex(-1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const toggleTag = (option: TagType) => {
|
||||
// Check if the tag already exists in the array
|
||||
const index = tags.findIndex((tag) => tag.text === option.text);
|
||||
@@ -197,18 +186,25 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
|
||||
}
|
||||
}
|
||||
}
|
||||
setSelectedIndex(-1);
|
||||
};
|
||||
|
||||
const childrenWithProps = React.cloneElement(
|
||||
children as React.ReactElement<any>,
|
||||
{
|
||||
onKeyDown: handleKeyDown,
|
||||
onFocus: handleInputFocus,
|
||||
onBlur: handleInputBlur,
|
||||
ref: inputRef
|
||||
const child = children as React.ReactElement<
|
||||
React.InputHTMLAttributes<HTMLInputElement> & {
|
||||
ref?: React.Ref<HTMLInputElement>;
|
||||
}
|
||||
);
|
||||
>;
|
||||
const userOnKeyDown = child.props.onKeyDown;
|
||||
|
||||
const childrenWithProps = React.cloneElement(child, {
|
||||
onKeyDown: userOnKeyDown,
|
||||
onFocus: handleInputFocus,
|
||||
onBlur: handleInputBlur,
|
||||
ref: inputRef
|
||||
} as Partial<
|
||||
React.InputHTMLAttributes<HTMLInputElement> & {
|
||||
ref?: React.Ref<HTMLInputElement>;
|
||||
}
|
||||
>);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -222,132 +218,105 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
|
||||
onOpenChange={handleOpenChange}
|
||||
modal={usePortal}
|
||||
>
|
||||
<div
|
||||
className="relative h-full flex items-center rounded-md border border-input bg-transparent pr-3"
|
||||
ref={triggerContainerRef}
|
||||
>
|
||||
{childrenWithProps}
|
||||
<PopoverTrigger asChild ref={triggerRef}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
role="combobox"
|
||||
className={cn(
|
||||
`hover:bg-transparent ${!inlineTags ? "ml-auto" : ""}`,
|
||||
classStyleProps?.popoverTrigger
|
||||
)}
|
||||
onClick={() => {
|
||||
setIsPopoverOpen(!isPopoverOpen);
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={`lucide lucide-chevron-down h-4 w-4 shrink-0 opacity-50 ${isPopoverOpen ? "rotate-180" : "rotate-0"}`}
|
||||
<PopoverAnchor asChild>
|
||||
<div
|
||||
className="relative h-full flex items-center rounded-md border border-input bg-transparent pr-3"
|
||||
ref={triggerContainerRef}
|
||||
>
|
||||
{childrenWithProps}
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
role="combobox"
|
||||
className={cn(
|
||||
`hover:bg-transparent ${!inlineTags ? "ml-auto" : ""}`,
|
||||
classStyleProps?.popoverTrigger
|
||||
)}
|
||||
onClick={() => {
|
||||
setIsPopoverOpen(!isPopoverOpen);
|
||||
}}
|
||||
>
|
||||
<path d="m6 9 6 6 6-6"></path>
|
||||
</svg>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</div>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={`lucide lucide-chevron-down h-4 w-4 shrink-0 opacity-50 ${isPopoverOpen ? "rotate-180" : "rotate-0"}`}
|
||||
>
|
||||
<path d="m6 9 6 6 6-6"></path>
|
||||
</svg>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</div>
|
||||
</PopoverAnchor>
|
||||
<PopoverContent
|
||||
ref={popoverContentRef}
|
||||
side="bottom"
|
||||
align="start"
|
||||
forceMount
|
||||
className={cn(
|
||||
`p-0 relative`,
|
||||
"p-0",
|
||||
classStyleProps?.popoverContent
|
||||
)}
|
||||
style={{
|
||||
top: `${popooverContentTop}px`,
|
||||
marginLeft: `calc(-${popoverWidth}px + 36px)`,
|
||||
width: `${popoverWidth}px`,
|
||||
minWidth: `${popoverWidth}px`,
|
||||
zIndex: 9999
|
||||
}}
|
||||
>
|
||||
<div
|
||||
<Command
|
||||
key={commandResetKey}
|
||||
className={cn(
|
||||
"max-h-[300px] overflow-y-auto overflow-x-hidden",
|
||||
classStyleProps?.commandList
|
||||
"rounded-lg border-0 shadow-none",
|
||||
classStyleProps?.command
|
||||
)}
|
||||
style={{
|
||||
minHeight: "68px"
|
||||
}}
|
||||
key={autocompleteOptions.length}
|
||||
>
|
||||
{autocompleteOptions.length > 0 ? (
|
||||
<div
|
||||
key={autocompleteOptions.length}
|
||||
role="group"
|
||||
className={cn(
|
||||
"overflow-y-auto overflow-hidden p-1 text-foreground",
|
||||
classStyleProps?.commandGroup
|
||||
)}
|
||||
style={{
|
||||
minHeight: "68px"
|
||||
}}
|
||||
<CommandInput
|
||||
placeholder={t("searchPlaceholder")}
|
||||
className="h-9"
|
||||
/>
|
||||
<CommandList
|
||||
className={cn(
|
||||
"max-h-[300px]",
|
||||
classStyleProps?.commandList
|
||||
)}
|
||||
>
|
||||
<CommandEmpty>{t("noResults")}</CommandEmpty>
|
||||
<CommandGroup
|
||||
className={classStyleProps?.commandGroup}
|
||||
>
|
||||
<span className="text-muted-foreground font-medium text-sm py-1.5 px-2 pb-2">
|
||||
Suggestions
|
||||
</span>
|
||||
<div role="separator" className="py-0.5" />
|
||||
{autocompleteOptions.map((option, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
{visibleOptions.map((option) => {
|
||||
const isChosen = tags.some(
|
||||
(tag) => tag.text === option.text
|
||||
);
|
||||
return (
|
||||
<div
|
||||
<CommandItem
|
||||
key={option.id}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 hover:bg-accent",
|
||||
isSelected &&
|
||||
"bg-accent text-accent-foreground",
|
||||
classStyleProps?.commandItem
|
||||
)}
|
||||
data-value={option.text}
|
||||
onClick={() => toggleTag(option)}
|
||||
value={`${option.text} ${option.id}`}
|
||||
onSelect={() => toggleTag(option)}
|
||||
className={classStyleProps?.commandItem}
|
||||
>
|
||||
<div className="w-full flex items-center gap-2">
|
||||
{option.text}
|
||||
{tags.some(
|
||||
(tag) =>
|
||||
tag.text === option.text
|
||||
) && (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="lucide lucide-check"
|
||||
>
|
||||
<path d="M20 6 9 17l-5-5"></path>
|
||||
</svg>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4 shrink-0",
|
||||
isChosen
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
/>
|
||||
{option.text}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-6 text-center text-sm">
|
||||
{t("noResults")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo } from "react";
|
||||
import React from "react";
|
||||
import { Input } from "../ui/input";
|
||||
import { Button } from "../ui/button";
|
||||
import { type VariantProps } from "class-variance-authority";
|
||||
@@ -434,14 +434,6 @@ const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(
|
||||
// const filteredAutocompleteOptions = autocompleteFilter
|
||||
// ? autocompleteOptions?.filter((option) => autocompleteFilter(option.text))
|
||||
// : autocompleteOptions;
|
||||
const filteredAutocompleteOptions = useMemo(() => {
|
||||
return (autocompleteOptions || []).filter((option) =>
|
||||
option.text
|
||||
.toLowerCase()
|
||||
.includes(inputValue ? inputValue.toLowerCase() : "")
|
||||
);
|
||||
}, [inputValue, autocompleteOptions]);
|
||||
|
||||
const displayedTags = sortTags ? [...tags].sort() : tags;
|
||||
|
||||
const truncatedTags = truncate
|
||||
@@ -571,9 +563,9 @@ const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(
|
||||
tags={tags}
|
||||
setTags={setTags}
|
||||
setInputValue={setInputValue}
|
||||
autocompleteOptions={
|
||||
filteredAutocompleteOptions as Tag[]
|
||||
}
|
||||
autocompleteOptions={(autocompleteOptions ||
|
||||
[]) as Tag[]}
|
||||
filterQuery={inputValue}
|
||||
setTagCount={setTagCount}
|
||||
maxTags={maxTags}
|
||||
onTagAdd={onTagAdd}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
PopoverTrigger
|
||||
} from "../ui/popover";
|
||||
import { TagInputStyleClassesProps, type Tag as TagType } from "./tag-input";
|
||||
import { TagList, TagListProps } from "./tag-list";
|
||||
import { Button } from "../ui/button";
|
||||
@@ -33,33 +38,27 @@ export const TagPopover: React.FC<TagPopoverProps> = ({
|
||||
...tagProps
|
||||
}) => {
|
||||
const triggerContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||
const popoverContentRef = useRef<HTMLDivElement | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const [popoverWidth, setPopoverWidth] = useState<number>(0);
|
||||
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
const [sideOffset, setSideOffset] = useState<number>(0);
|
||||
|
||||
const t = useTranslations();
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
if (triggerContainerRef.current && triggerRef.current) {
|
||||
if (triggerContainerRef.current) {
|
||||
setPopoverWidth(triggerContainerRef.current.offsetWidth);
|
||||
setSideOffset(
|
||||
triggerContainerRef.current.offsetWidth -
|
||||
triggerRef?.current?.offsetWidth
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
handleResize(); // Call on mount and layout changes
|
||||
handleResize();
|
||||
|
||||
window.addEventListener("resize", handleResize); // Adjust on window resize
|
||||
window.addEventListener("resize", handleResize);
|
||||
return () => window.removeEventListener("resize", handleResize);
|
||||
}, [triggerContainerRef, triggerRef]);
|
||||
}, []);
|
||||
|
||||
// Close the popover when clicking outside of it
|
||||
useEffect(() => {
|
||||
@@ -135,52 +134,54 @@ export const TagPopover: React.FC<TagPopoverProps> = ({
|
||||
onOpenChange={handleOpenChange}
|
||||
modal={usePortal}
|
||||
>
|
||||
<div
|
||||
className="relative flex items-center rounded-md border border-input bg-transparent pr-3"
|
||||
ref={triggerContainerRef}
|
||||
>
|
||||
{React.cloneElement(children as React.ReactElement<any>, {
|
||||
onFocus: handleInputFocus,
|
||||
onBlur: handleInputBlur,
|
||||
ref: inputRef
|
||||
})}
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
role="combobox"
|
||||
className={cn(
|
||||
`hover:bg-transparent`,
|
||||
classStyleProps?.popoverClasses?.popoverTrigger
|
||||
)}
|
||||
onClick={() => setIsPopoverOpen(!isPopoverOpen)}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={`lucide lucide-chevron-down h-4 w-4 shrink-0 opacity-50 ${isPopoverOpen ? "rotate-180" : "rotate-0"}`}
|
||||
<PopoverAnchor asChild>
|
||||
<div
|
||||
className="relative flex items-center rounded-md border border-input bg-transparent pr-3"
|
||||
ref={triggerContainerRef}
|
||||
>
|
||||
{React.cloneElement(children as React.ReactElement<any>, {
|
||||
onFocus: handleInputFocus,
|
||||
onBlur: handleInputBlur,
|
||||
ref: inputRef
|
||||
})}
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
role="combobox"
|
||||
className={cn(
|
||||
`hover:bg-transparent`,
|
||||
classStyleProps?.popoverClasses?.popoverTrigger
|
||||
)}
|
||||
onClick={() => setIsPopoverOpen(!isPopoverOpen)}
|
||||
>
|
||||
<path d="m6 9 6 6 6-6"></path>
|
||||
</svg>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</div>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={`lucide lucide-chevron-down h-4 w-4 shrink-0 opacity-50 ${isPopoverOpen ? "rotate-180" : "rotate-0"}`}
|
||||
>
|
||||
<path d="m6 9 6 6 6-6"></path>
|
||||
</svg>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</div>
|
||||
</PopoverAnchor>
|
||||
<PopoverContent
|
||||
ref={popoverContentRef}
|
||||
align="start"
|
||||
side="bottom"
|
||||
className={cn(
|
||||
`w-full space-y-3`,
|
||||
classStyleProps?.popoverClasses?.popoverContent
|
||||
)}
|
||||
style={{
|
||||
marginLeft: `-${sideOffset}px`,
|
||||
width: `${popoverWidth}px`
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "@app/lib/cn";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-0",
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors outline-none focus:outline-none focus-visible:outline-none focus-visible:ring-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
|
||||
@@ -69,6 +69,7 @@ type ControlledDataTableProps<TData, TValue> = {
|
||||
onAdd?: () => void;
|
||||
onRefresh?: () => void;
|
||||
isRefreshing?: boolean;
|
||||
refreshButtonDisabled?: boolean;
|
||||
isNavigatingToAddPage?: boolean;
|
||||
searchPlaceholder?: string;
|
||||
filters?: DataTableFilter[];
|
||||
@@ -91,6 +92,7 @@ export function ControlledDataTable<TData, TValue>({
|
||||
onAdd,
|
||||
onRefresh,
|
||||
isRefreshing,
|
||||
refreshButtonDisabled = false,
|
||||
searchPlaceholder = "Search...",
|
||||
filters,
|
||||
filterDisplayMode = "label",
|
||||
@@ -335,7 +337,7 @@ export function ControlledDataTable<TData, TValue>({
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
disabled={isRefreshing || refreshButtonDisabled}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-0 sm:mr-2 h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`}
|
||||
|
||||
@@ -171,8 +171,10 @@ type DataTableProps<TData, TValue> = {
|
||||
title?: string;
|
||||
addButtonText?: string;
|
||||
onAdd?: () => void;
|
||||
addButtonDisabled?: boolean;
|
||||
onRefresh?: () => void;
|
||||
isRefreshing?: boolean;
|
||||
refreshButtonDisabled?: boolean;
|
||||
searchPlaceholder?: string;
|
||||
searchColumn?: string;
|
||||
defaultSort?: {
|
||||
@@ -203,8 +205,10 @@ export function DataTable<TData, TValue>({
|
||||
title,
|
||||
addButtonText,
|
||||
onAdd,
|
||||
addButtonDisabled = false,
|
||||
onRefresh,
|
||||
isRefreshing,
|
||||
refreshButtonDisabled = false,
|
||||
searchPlaceholder = "Search...",
|
||||
searchColumn = "name",
|
||||
defaultSort,
|
||||
@@ -622,7 +626,7 @@ export function DataTable<TData, TValue>({
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
disabled={isRefreshing || refreshButtonDisabled}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-0 sm:mr-2 h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`}
|
||||
@@ -635,7 +639,7 @@ export function DataTable<TData, TValue>({
|
||||
)}
|
||||
{onAdd && addButtonText && (
|
||||
<div>
|
||||
<Button onClick={onAdd}>
|
||||
<Button onClick={onAdd} disabled={addButtonDisabled}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{addButtonText}
|
||||
</Button>
|
||||
|
||||
Reference in New Issue
Block a user