♻️ Update domain picker component to accept default values

This commit is contained in:
Fred KISSIE
2025-12-10 21:15:26 +01:00
parent c56574e431
commit fbd3802e46
2 changed files with 118 additions and 146 deletions

View File

@@ -1,8 +1,6 @@
"use client"; "use client";
import { useState, useEffect, useCallback } from "react"; import { Alert, AlertDescription } from "@/components/ui/alert";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Command, Command,
@@ -13,45 +11,40 @@ import {
CommandList, CommandList,
CommandSeparator CommandSeparator
} from "@/components/ui/command"; } from "@/components/ui/command";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { import {
Popover, Popover,
PopoverContent, PopoverContent,
PopoverTrigger PopoverTrigger
} from "@/components/ui/popover"; } from "@/components/ui/popover";
import { import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
AlertCircle,
CheckCircle2,
Building2,
Zap,
Check,
ChevronsUpDown,
ArrowUpDown
} from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { createApiClient, formatAxiosError } from "@/lib/api";
import { useEnvContext } from "@/hooks/useEnvContext"; import { useEnvContext } from "@/hooks/useEnvContext";
import { toast } from "@/hooks/useToast"; import { toast } from "@/hooks/useToast";
import { ListDomainsResponse } from "@server/routers/domain/listDomains"; import { createApiClient } from "@/lib/api";
import { CheckDomainAvailabilityResponse } from "@server/routers/domain/types";
import { AxiosResponse } from "axios";
import { cn } from "@/lib/cn"; import { cn } from "@/lib/cn";
import { useTranslations } from "next-intl";
import { build } from "@server/build";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { import {
sanitizeInputRaw,
finalizeSubdomainSanitize, finalizeSubdomainSanitize,
validateByDomainType, isValidSubdomainStructure,
isValidSubdomainStructure sanitizeInputRaw,
validateByDomainType
} from "@/lib/subdomain-utils"; } from "@/lib/subdomain-utils";
import { orgQueries } from "@app/lib/queries";
import { build } from "@server/build";
import { CheckDomainAvailabilityResponse } from "@server/routers/domain/types";
import { useQuery } from "@tanstack/react-query";
import { AxiosResponse } from "axios";
import {
AlertCircle,
Building2,
Check,
CheckCircle2,
ChevronsUpDown,
Zap
} from "lucide-react";
import { useTranslations } from "next-intl";
import { toUnicode } from "punycode"; import { toUnicode } from "punycode";
import { useCallback, useEffect, useMemo, useState } from "react";
type OrganizationDomain = {
domainId: string;
baseDomain: string;
verified: boolean;
type: "ns" | "cname" | "wildcard";
};
type AvailableOption = { type AvailableOption = {
domainNamespaceId: string; domainNamespaceId: string;
@@ -69,7 +62,7 @@ type DomainOption = {
domainNamespaceId?: string; domainNamespaceId?: string;
}; };
interface DomainPicker2Props { interface DomainPickerProps {
orgId: string; orgId: string;
onDomainChange?: (domainInfo: { onDomainChange?: (domainInfo: {
domainId: string; domainId: string;
@@ -81,51 +74,45 @@ interface DomainPicker2Props {
}) => void; }) => void;
cols?: number; cols?: number;
hideFreeDomain?: boolean; hideFreeDomain?: boolean;
defaultSubdomain?: string;
defaultBaseDomain?: string;
} }
export default function DomainPicker2({ export default function DomainPicker({
orgId, orgId,
onDomainChange, onDomainChange,
cols = 2, cols = 2,
hideFreeDomain = false hideFreeDomain = false,
}: DomainPicker2Props) { defaultSubdomain,
defaultBaseDomain
}: DomainPickerProps) {
const { env } = useEnvContext(); const { env } = useEnvContext();
const api = createApiClient({ env }); const api = createApiClient({ env });
const t = useTranslations(); const t = useTranslations();
const { data = [], isLoading: loadingDomains } = useQuery(
orgQueries.domains({ orgId })
);
console.log({ defaultSubdomain, defaultBaseDomain });
if (!env.flags.usePangolinDns) { if (!env.flags.usePangolinDns) {
hideFreeDomain = true; hideFreeDomain = true;
} }
const [subdomainInput, setSubdomainInput] = useState<string>(""); const [subdomainInput, setSubdomainInput] = useState(
defaultSubdomain ?? ""
);
const [selectedBaseDomain, setSelectedBaseDomain] = const [selectedBaseDomain, setSelectedBaseDomain] =
useState<DomainOption | null>(null); useState<DomainOption | null>(null);
const [availableOptions, setAvailableOptions] = useState<AvailableOption[]>( const [availableOptions, setAvailableOptions] = useState<AvailableOption[]>(
[] []
); );
const [organizationDomains, setOrganizationDomains] = useState<
OrganizationDomain[]
>([]);
const [loadingDomains, setLoadingDomains] = useState(false);
const [open, setOpen] = useState(false);
// Provided domain search states // memoized to prevent reruning the effect that selects the initial domain indefinitely
const [userInput, setUserInput] = useState<string>(""); // removing this will break and cause an infinite rerender
const [isChecking, setIsChecking] = useState(false); const organizationDomains = useMemo(() => {
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc"); return data
const [providedDomainsShown, setProvidedDomainsShown] = useState(3);
const [selectedProvidedDomain, setSelectedProvidedDomain] =
useState<AvailableOption | null>(null);
useEffect(() => {
const loadOrganizationDomains = async () => {
setLoadingDomains(true);
try {
const response = await api.get<
AxiosResponse<ListDomainsResponse>
>(`/org/${orgId}/domains`);
if (response.status === 200) {
const domains = response.data.data.domains
.filter( .filter(
(domain) => (domain) =>
domain.type === "ns" || domain.type === "ns" ||
@@ -137,12 +124,25 @@ export default function DomainPicker2({
baseDomain: toUnicode(domain.baseDomain), baseDomain: toUnicode(domain.baseDomain),
type: domain.type as "ns" | "cname" | "wildcard" type: domain.type as "ns" | "cname" | "wildcard"
})); }));
setOrganizationDomains(domains); }, [data]);
// Auto-select first available domain const [open, setOpen] = useState(false);
if (domains.length > 0) {
// Select the first organization domain // Provided domain search states
const firstOrgDomain = domains[0]; const [userInput, setUserInput] = useState<string>("");
const [isChecking, setIsChecking] = useState(false);
const [providedDomainsShown, setProvidedDomainsShown] = useState(3);
const [selectedProvidedDomain, setSelectedProvidedDomain] =
useState<AvailableOption | null>(null);
useEffect(() => {
if (!loadingDomains) {
if (organizationDomains.length > 0) {
// Select the first organization domain or the one provided from props
const firstOrgDomain =
organizationDomains.find(
(domain) => domain.baseDomain === defaultBaseDomain
) ?? organizationDomains[0];
const domainOption: DomainOption = { const domainOption: DomainOption = {
id: `org-${firstOrgDomain.domainId}`, id: `org-${firstOrgDomain.domainId}`,
domain: firstOrgDomain.baseDomain, domain: firstOrgDomain.baseDomain,
@@ -177,20 +177,12 @@ export default function DomainPicker2({
setSelectedBaseDomain(freeDomainOption); setSelectedBaseDomain(freeDomainOption);
} }
} }
} catch (error) { }, [
console.error("Failed to load organization domains:", error); hideFreeDomain,
toast({ loadingDomains,
variant: "destructive", organizationDomains,
title: t("domainPickerError"), defaultBaseDomain
description: t("domainPickerErrorLoadDomains") ]);
});
} finally {
setLoadingDomains(false);
}
};
loadOrganizationDomains();
}, [orgId, api, hideFreeDomain]);
const checkAvailability = useCallback( const checkAvailability = useCallback(
async (input: string) => { async (input: string) => {
@@ -256,37 +248,6 @@ export default function DomainPicker2({
} }
}, [userInput, debouncedCheckAvailability, selectedBaseDomain]); }, [userInput, debouncedCheckAvailability, selectedBaseDomain]);
const generateDropdownOptions = (): DomainOption[] => {
const options: DomainOption[] = [];
organizationDomains.forEach((orgDomain) => {
options.push({
id: `org-${orgDomain.domainId}`,
domain: orgDomain.baseDomain,
type: "organization",
verified: orgDomain.verified,
domainType: orgDomain.type,
domainId: orgDomain.domainId
});
});
if ((build === "saas" || build === "enterprise") && !hideFreeDomain) {
const domainOptionText =
build === "enterprise"
? t("domainPickerProvidedDomain")
: t("domainPickerFreeProvidedDomain");
options.push({
id: "provided-search",
domain: domainOptionText,
type: "provided-search"
});
}
return options;
};
const dropdownOptions = generateDropdownOptions();
const finalizeSubdomain = (sub: string, base: DomainOption): string => { const finalizeSubdomain = (sub: string, base: DomainOption): string => {
const sanitized = finalizeSubdomainSanitize(sub); const sanitized = finalizeSubdomainSanitize(sub);
@@ -440,8 +401,7 @@ export default function DomainPicker2({
selectedBaseDomain?.type === "provided-search"; selectedBaseDomain?.type === "provided-search";
const sortedAvailableOptions = [...availableOptions].sort((a, b) => { const sortedAvailableOptions = [...availableOptions].sort((a, b) => {
const comparison = a.fullDomain.localeCompare(b.fullDomain); return a.fullDomain.localeCompare(b.fullDomain);
return sortOrder === "asc" ? comparison : -comparison;
}); });
const displayedProvidedOptions = sortedAvailableOptions.slice( const displayedProvidedOptions = sortedAvailableOptions.slice(
@@ -518,16 +478,16 @@ export default function DomainPicker2({
className="w-full justify-between" className="w-full justify-between"
> >
{selectedBaseDomain ? ( {selectedBaseDomain ? (
<div className="flex items-center space-x-2 min-w-0 flex-1"> <div className="flex items-center gap-x-2 min-w-0 flex-1">
{selectedBaseDomain.type === {selectedBaseDomain.type ===
"organization" ? null : ( "organization" ? null : (
<Zap className="h-4 w-4 flex-shrink-0" /> <Zap className="h-4 w-4 shrink-0" />
)} )}
<span className="truncate"> <span className="truncate">
{selectedBaseDomain.domain} {selectedBaseDomain.domain}
</span> </span>
{selectedBaseDomain.verified && ( {selectedBaseDomain.verified && (
<CheckCircle2 className="h-3 w-3 text-green-500 flex-shrink-0" /> <CheckCircle2 className="h-3 w-3 text-green-500 shrink-0" />
)} )}
</div> </div>
) : ( ) : (

View File

@@ -16,6 +16,7 @@ import { remote } from "./api";
import { durationToMs } from "./durationToMs"; import { durationToMs } from "./durationToMs";
import type { QueryRequestAnalyticsResponse } from "@server/routers/auditLogs"; import type { QueryRequestAnalyticsResponse } from "@server/routers/auditLogs";
import type { ListResourceNamesResponse } from "@server/routers/resource"; import type { ListResourceNamesResponse } from "@server/routers/resource";
import type { ListDomainsResponse } from "@server/routers/domain";
export type ProductUpdate = { export type ProductUpdate = {
link: string | null; link: string | null;
@@ -139,6 +140,17 @@ export const orgQueries = {
>(`/org/${orgId}/sites`, { signal }); >(`/org/${orgId}/sites`, { signal });
return res.data.data.sites; return res.data.data.sites;
} }
}),
domains: ({ orgId }: { orgId: string }) =>
queryOptions({
queryKey: ["ORG", orgId, "DOMAINS"] as const,
queryFn: async ({ signal, meta }) => {
const res = await meta!.api.get<
AxiosResponse<ListDomainsResponse>
>(`/org/${orgId}/domains`, { signal });
return res.data.data.domains;
}
}) })
}; };