Merge pull request #2034 from Fredkiss3/refactor/domain-picker-default-value

refactor:  Update `<DomainPicker />` to accept default values
This commit is contained in:
Milo Schwartz
2025-12-17 07:40:46 -08:00
committed by GitHub
5 changed files with 268 additions and 223 deletions

View File

@@ -16,7 +16,7 @@ import {
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { useResourceContext } from "@app/hooks/useResourceContext"; import { useResourceContext } from "@app/hooks/useResourceContext";
import { ListSitesResponse } from "@server/routers/site"; import { ListSitesResponse } from "@server/routers/site";
import { useEffect, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { AxiosResponse } from "axios"; import { AxiosResponse } from "axios";
import { useParams, useRouter } from "next/navigation"; import { useParams, useRouter } from "next/navigation";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
@@ -90,8 +90,15 @@ export default function GeneralForm() {
const [resourceFullDomain, setResourceFullDomain] = useState( const [resourceFullDomain, setResourceFullDomain] = useState(
`${resource.ssl ? "https" : "http"}://${toUnicode(resource.fullDomain || "")}` `${resource.ssl ? "https" : "http"}://${toUnicode(resource.fullDomain || "")}`
); );
const resourceFullDomainName = useMemo(() => {
const url = new URL(resourceFullDomain);
return url.hostname;
}, [resourceFullDomain]);
const [selectedDomain, setSelectedDomain] = useState<{ const [selectedDomain, setSelectedDomain] = useState<{
domainId: string; domainId: string;
domainNamespaceId?: string;
subdomain?: string; subdomain?: string;
fullDomain: string; fullDomain: string;
baseDomain: string; baseDomain: string;
@@ -225,7 +232,8 @@ export default function GeneralForm() {
niceId: data.niceId, niceId: data.niceId,
subdomain: data.subdomain, subdomain: data.subdomain,
fullDomain: updated.fullDomain, fullDomain: updated.fullDomain,
proxyPort: data.proxyPort proxyPort: data.proxyPort,
domainId: data.domainId
// ...(!resource.http && { // ...(!resource.http && {
// enableProxy: data.enableProxy // enableProxy: data.enableProxy
// }) // })
@@ -488,13 +496,27 @@ export default function GeneralForm() {
<DomainPicker <DomainPicker
orgId={orgId as string} orgId={orgId as string}
cols={1} cols={1}
defaultSubdomain={
form.getValues("subdomain") ??
resource.subdomain
}
defaultDomainId={
form.getValues("domainId") ??
resource.domainId
}
defaultFullDomain={resourceFullDomainName}
onDomainChange={(res) => { onDomainChange={(res) => {
const selected = { const selected =
domainId: res.domainId, res === null
subdomain: res.subdomain, ? null
fullDomain: res.fullDomain, : {
baseDomain: res.baseDomain domainId: res.domainId,
}; subdomain: res.subdomain,
fullDomain: res.fullDomain,
baseDomain: res.baseDomain,
domainNamespaceId:
res.domainNamespaceId
};
setSelectedDomain(selected); setSelectedDomain(selected);
}} }}
/> />

View File

@@ -1396,6 +1396,8 @@ export default function Page() {
<DomainPicker <DomainPicker
orgId={orgId as string} orgId={orgId as string}
onDomainChange={(res) => { onDomainChange={(res) => {
if (!res) return;
httpForm.setValue( httpForm.setValue(
"subdomain", "subdomain",
res.subdomain res.subdomain

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,128 +62,146 @@ type DomainOption = {
domainNamespaceId?: string; domainNamespaceId?: string;
}; };
interface DomainPicker2Props { interface DomainPickerProps {
orgId: string; orgId: string;
onDomainChange?: (domainInfo: { onDomainChange?: (
domainId: string; domainInfo: {
domainNamespaceId?: string; domainId: string;
type: "organization" | "provided"; domainNamespaceId?: string;
subdomain?: string; type: "organization" | "provided";
fullDomain: string; subdomain?: string;
baseDomain: string; fullDomain: string;
}) => void; baseDomain: string;
} | null
) => void;
cols?: number; cols?: number;
hideFreeDomain?: boolean; hideFreeDomain?: boolean;
defaultFullDomain?: string | null;
defaultSubdomain?: string | null;
defaultDomainId?: string | null;
} }
export default function DomainPicker2({ export default function DomainPicker({
orgId, orgId,
onDomainChange, onDomainChange,
cols = 2, cols = 2,
hideFreeDomain = false hideFreeDomain = false,
}: DomainPicker2Props) { defaultSubdomain,
defaultFullDomain,
defaultDomainId
}: 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 })
);
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[] // memoized to prevent reruning the effect that selects the initial domain indefinitely
>([]); // removing this will break and cause an infinite rerender
const [loadingDomains, setLoadingDomains] = useState(false); const organizationDomains = useMemo(() => {
return data
.filter(
(domain) =>
domain.type === "ns" ||
domain.type === "cname" ||
domain.type === "wildcard"
)
.map((domain) => ({
...domain,
baseDomain: toUnicode(domain.baseDomain),
type: domain.type as "ns" | "cname" | "wildcard"
}));
}, [data]);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
// Provided domain search states // Provided domain search states
const [userInput, setUserInput] = useState<string>(""); const [userInput, setUserInput] = useState<string>(defaultSubdomain ?? "");
const [isChecking, setIsChecking] = useState(false); const [isChecking, setIsChecking] = useState(false);
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
const [providedDomainsShown, setProvidedDomainsShown] = useState(3); const [providedDomainsShown, setProvidedDomainsShown] = useState(3);
const [selectedProvidedDomain, setSelectedProvidedDomain] = const [selectedProvidedDomain, setSelectedProvidedDomain] =
useState<AvailableOption | null>(null); useState<AvailableOption | null>(null);
useEffect(() => { useEffect(() => {
const loadOrganizationDomains = async () => { if (!loadingDomains) {
setLoadingDomains(true); let domainOptionToSelect: DomainOption | null = null;
try { if (organizationDomains.length > 0) {
const response = await api.get< // Select the first organization domain or the one provided from props
AxiosResponse<ListDomainsResponse> let firstOrExistingDomain = organizationDomains.find(
>(`/org/${orgId}/domains`); (domain) => domain.domainId === defaultDomainId
if (response.status === 200) { );
const domains = response.data.data.domains // if no default Domain
.filter( if (!defaultDomainId) {
(domain) => firstOrExistingDomain = organizationDomains[0];
domain.type === "ns" ||
domain.type === "cname" ||
domain.type === "wildcard"
)
.map((domain) => ({
...domain,
baseDomain: toUnicode(domain.baseDomain),
type: domain.type as "ns" | "cname" | "wildcard"
}));
setOrganizationDomains(domains);
// Auto-select first available domain
if (domains.length > 0) {
// Select the first organization domain
const firstOrgDomain = domains[0];
const domainOption: DomainOption = {
id: `org-${firstOrgDomain.domainId}`,
domain: firstOrgDomain.baseDomain,
type: "organization",
verified: firstOrgDomain.verified,
domainType: firstOrgDomain.type,
domainId: firstOrgDomain.domainId
};
setSelectedBaseDomain(domainOption);
onDomainChange?.({
domainId: firstOrgDomain.domainId,
type: "organization",
subdomain: undefined,
fullDomain: firstOrgDomain.baseDomain,
baseDomain: firstOrgDomain.baseDomain
});
} else if (
(build === "saas" || build === "enterprise") &&
!hideFreeDomain
) {
// If no organization domains, select the provided domain option
const domainOptionText =
build === "enterprise"
? t("domainPickerProvidedDomain")
: t("domainPickerFreeProvidedDomain");
const freeDomainOption: DomainOption = {
id: "provided-search",
domain: domainOptionText,
type: "provided-search"
};
setSelectedBaseDomain(freeDomainOption);
}
} }
} catch (error) {
console.error("Failed to load organization domains:", error);
toast({
variant: "destructive",
title: t("domainPickerError"),
description: t("domainPickerErrorLoadDomains")
});
} finally {
setLoadingDomains(false);
}
};
loadOrganizationDomains(); if (firstOrExistingDomain) {
}, [orgId, api, hideFreeDomain]); domainOptionToSelect = {
id: `org-${firstOrExistingDomain.domainId}`,
domain: firstOrExistingDomain.baseDomain,
type: "organization",
verified: firstOrExistingDomain.verified,
domainType: firstOrExistingDomain.type,
domainId: firstOrExistingDomain.domainId
};
onDomainChange?.({
domainId: firstOrExistingDomain.domainId,
type: "organization",
subdomain:
firstOrExistingDomain.type !== "cname"
? defaultSubdomain || undefined
: undefined,
fullDomain: firstOrExistingDomain.baseDomain,
baseDomain: firstOrExistingDomain.baseDomain
});
}
}
if (
!domainOptionToSelect &&
build !== "oss" &&
!hideFreeDomain &&
defaultDomainId !== undefined
) {
// If no organization domains, select the provided domain option
const domainOptionText =
build === "enterprise"
? t("domainPickerProvidedDomain")
: t("domainPickerFreeProvidedDomain");
// free domain option
domainOptionToSelect = {
id: "provided-search",
domain: domainOptionText,
type: "provided-search"
};
}
setSelectedBaseDomain(domainOptionToSelect);
}
}, [
loadingDomains,
organizationDomains,
defaultSubdomain,
hideFreeDomain,
defaultDomainId
]);
const checkAvailability = useCallback( const checkAvailability = useCallback(
async (input: string) => { async (input: string) => {
@@ -256,37 +267,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);
@@ -383,6 +363,9 @@ export default function DomainPicker2({
setSelectedProvidedDomain(null); setSelectedProvidedDomain(null);
} }
console.log({
setSelectedBaseDomain: option
});
setSelectedBaseDomain(option); setSelectedBaseDomain(option);
setOpen(false); setOpen(false);
@@ -393,15 +376,21 @@ export default function DomainPicker2({
const fullDomain = sub ? `${sub}.${option.domain}` : option.domain; const fullDomain = sub ? `${sub}.${option.domain}` : option.domain;
onDomainChange?.({ if (option.type === "provided-search") {
domainId: option.domainId || "", onDomainChange?.(null); // prevent the modal from closing with `<subdomain>.Free Provided domain`
domainNamespaceId: option.domainNamespaceId, } else {
type: onDomainChange?.({
option.type === "provided-search" ? "provided" : "organization", domainId: option.domainId || "",
subdomain: sub || undefined, domainNamespaceId: option.domainNamespaceId,
fullDomain, type: "organization",
baseDomain: option.domain subdomain:
}); option.domainType !== "cname"
? sub || undefined
: undefined,
fullDomain,
baseDomain: option.domain
});
}
}; };
const handleProvidedDomainSelect = (option: AvailableOption) => { const handleProvidedDomainSelect = (option: AvailableOption) => {
@@ -440,14 +429,22 @@ 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(
0, 0,
providedDomainsShown providedDomainsShown
); );
console.log({
displayedProvidedOptions
});
const selectedDomainNamespaceId =
selectedProvidedDomain?.domainNamespaceId ??
displayedProvidedOptions.find(
(opt) => opt.fullDomain === defaultFullDomain
)?.domainNamespaceId;
const hasMoreProvided = const hasMoreProvided =
sortedAvailableOptions.length > providedDomainsShown; sortedAvailableOptions.length > providedDomainsShown;
@@ -518,16 +515,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>
) : ( ) : (
@@ -733,10 +730,8 @@ export default function DomainPicker2({
{!isChecking && sortedAvailableOptions.length > 0 && ( {!isChecking && sortedAvailableOptions.length > 0 && (
<div className="space-y-3"> <div className="space-y-3">
<RadioGroup <RadioGroup
value={ value={selectedDomainNamespaceId || ""}
selectedProvidedDomain?.domainNamespaceId || defaultValue={selectedDomainNamespaceId}
""
}
onValueChange={(value) => { onValueChange={(value) => {
const option = const option =
displayedProvidedOptions.find( displayedProvidedOptions.find(
@@ -749,47 +744,50 @@ export default function DomainPicker2({
}} }}
className={`grid gap-2 grid-cols-1 sm:grid-cols-${cols}`} className={`grid gap-2 grid-cols-1 sm:grid-cols-${cols}`}
> >
{displayedProvidedOptions.map((option) => ( {displayedProvidedOptions.map((option) => {
<label const isSelected =
key={option.domainNamespaceId} selectedDomainNamespaceId ===
htmlFor={option.domainNamespaceId} option.domainNamespaceId;
data-state={ return (
selectedProvidedDomain?.domainNamespaceId === <label
option.domainNamespaceId key={option.domainNamespaceId}
? "checked" htmlFor={option.domainNamespaceId}
: "unchecked" data-state={
} isSelected
className={cn( ? "checked"
"relative flex rounded-lg border p-3 transition-colors cursor-pointer", : "unchecked"
selectedProvidedDomain?.domainNamespaceId === }
option.domainNamespaceId className={cn(
? "border-primary bg-primary/10" "relative flex rounded-lg border p-3 transition-colors cursor-pointer",
: "border-input hover:bg-accent" isSelected
)} ? "border-primary bg-primary/10"
> : "border-input hover:bg-accent"
<RadioGroupItem )}
value={option.domainNamespaceId} >
id={option.domainNamespaceId} <RadioGroupItem
className="absolute left-3 top-3 h-4 w-4 border-primary text-primary" value={option.domainNamespaceId}
/> id={option.domainNamespaceId}
<div className="flex items-center justify-between pl-7 flex-1"> className="absolute left-3 top-3 h-4 w-4 border-primary text-primary"
<div> />
<p className="font-mono text-sm"> <div className="flex items-center justify-between pl-7 flex-1">
{option.fullDomain} <div>
</p> <p className="font-mono text-sm">
<p className="text-xs text-muted-foreground"> {option.fullDomain}
{t( </p>
"domainPickerNamespace", <p className="text-xs text-muted-foreground">
{ {t(
namespace: "domainPickerNamespace",
option.domainNamespaceId {
} namespace:
)} option.domainNamespaceId
</p> }
)}
</p>
</div>
</div> </div>
</div> </label>
</label> );
))} })}
</RadioGroup> </RadioGroup>
{hasMoreProvided && ( {hasMoreProvided && (
<Button <Button

View File

@@ -510,13 +510,24 @@ const AuthPageSettings = forwardRef<AuthPageSettingsRef, AuthPageSettingsProps>(
hideFreeDomain={true} hideFreeDomain={true}
orgId={org?.org.orgId as string} orgId={org?.org.orgId as string}
cols={1} cols={1}
defaultDomainId={
form.getValues("authPageDomainId") ??
loginPage?.domainId
}
defaultSubdomain={
form.getValues("authPageSubdomain") ??
loginPage?.subdomain
}
onDomainChange={(res) => { onDomainChange={(res) => {
const selected = { const selected =
domainId: res.domainId, res === null
subdomain: res.subdomain, ? null
fullDomain: res.fullDomain, : {
baseDomain: res.baseDomain domainId: res.domainId,
}; subdomain: res.subdomain,
fullDomain: res.fullDomain,
baseDomain: res.baseDomain
};
setSelectedDomain(selected); setSelectedDomain(selected);
}} }}
/> />

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;
}
}) })
}; };