Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

5.8 KB
Raw Blame
import { type ComponentProps, type ReactNode } from "react";
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import {
  isSettingsPageShown,
  PagedSettingsContainer,
} from "@/src/components/PagedSettingsContainer";
import ContainerPage from "@/src/components/layouts/ContainerPage";
import { Badge } from "@/src/components/design-system/Badge/Badge";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
import { OrganizationDropdownMenu } from "@/src/components/OrganizationDropdownMenu/OrganizationDropdownMenu";
import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
import { useAccountSettingsPages } from "@/src/features/account/AccountSettingsPage";
import { useQueryOrganization } from "@/src/features/organizations/hooks";
import { useOrganizationSettingsPages } from "@/src/features/organizations/OrganizationSettingsPage";
import { accountSettingsPath } from "@/src/features/settings/accountSettingsPath";

type SettingsScope = "account" | "organization";

type SettingsPageProps = { scope: SettingsScope };

type SettingsPageEntry = ComponentProps<
  typeof PagedSettingsContainer
>["pages"][number];

const ACCOUNT_SECTION = "Account Settings";
const ORGANIZATION_SECTION = "Organization";

export function SettingsPage({ scope }: SettingsPageProps) {
  const router = useRouter();
  const organization = useQueryOrganization();
  const accountPages = useAccountSettingsPages();
  const organizationPages = useOrganizationSettingsPages();

  const pages = buildSettingsPages({
    scope,
    organizationId: organization?.id,
    accountPages,
    organizationPages,
  });

  const activeSlug =
    typeof router.query.page === "string" ? router.query.page : undefined;
  const fullHeight =
    scope === "organization" &&
    (activeSlug === "ai-gateway-models" ||
      activeSlug === "ai-gateway" ||
      activeSlug === "ai-gateway-api-keys");

  if (scope === "organization" && !organization) {
    return (
      <ContainerPage headerProps={{ title: "Settings" }}>
        <NoDataOrLoading isLoading />
      </ContainerPage>
    );
  }

  return (
    <ContainerPage
      headerProps={{ title: "Settings" }}
      extendRight={fullHeight}
      fullHeight={fullHeight}
    >
      <PagedSettingsContainer
        activeSlug={activeSlug}
        pages={pages}
        fullHeight={fullHeight}
        sectionHeaders={organizationSectionHeaders(organization?.id, pages)}
        sectionBadges={{
          "AI Gateway": (
            <Badge text="Beta" color="blue" size="sm" font="mono" />
          ),
        }}
      />
    </ContainerPage>
  );
}

/** Labels the org section; offers an org picker only when no org is in context */
function OrganizationSectionHeader() {
  const session = useSession();
  const organization = useQueryOrganization();
  const organizations = session.data?.user?.organizations;

  return (
    <div className="flex flex-col gap-1">
      <span className="text-foreground flex h-8 items-center px-2 text-xs font-bold">
        Org Settings
      </span>
      {organization ? null : (
        <OrganizationDropdownMenu
          {...(organizations
            ? { state: "loaded", organizations }
            : { state: "loading" })}
          canCreateOrganizations={!!session.data?.user?.canCreateOrganizations}
          getOrgPath={accountSettingsPath}
        >
          {({ getTriggerProps }) => (
            <button
              type="button"
              className="border-border bg-background text-foreground hover:bg-muted flex h-8 w-full items-center justify-between gap-1 rounded-md border px-2 text-sm whitespace-nowrap"
              {...getTriggerProps()}
            >
              <span>Select organization</span>
              <DropdownIndicator size="sm" nudge />
            </button>
          )}
        </OrganizationDropdownMenu>
      )}
    </div>
  );
}

const organizationSettingsPath = (organizationId: string, slug: string) =>
  `/organization/${organizationId}/settings${slug === "index" ? "" : `/${slug}`}`;

/**
 * Merges account and organization settings into one nav. Pages owned by the
 * other route become internal links, so each route only renders its own
 * content while the nav looks the same on both.
 */
export function buildSettingsPages({
  scope,
  organizationId,
  accountPages,
  organizationPages,
}: {
  scope: SettingsScope;
  organizationId: string | undefined;
  accountPages: SettingsPageEntry[];
  organizationPages: SettingsPageEntry[];
}): SettingsPageEntry[] {
  const account = accountPages.map((page): SettingsPageEntry => {
    const base = { ...page, section: ACCOUNT_SECTION };
    if (scope === "account" || !("content" in page)) return base;
    return {
      title: page.title,
      slug: page.slug,
      section: ACCOUNT_SECTION,
      show: page.show,
      href: accountSettingsPath(organizationId),
      internal: true,
    };
  });

  const organization = organizationPages.map((page): SettingsPageEntry => {
    if (scope === "organization" || !("content" in page) || !organizationId)
      return page;
    return {
      title: page.title,
      slug: page.slug,
      section: page.section,
      show: page.show,
      disabledReason: page.disabledReason,
      href: organizationSettingsPath(organizationId, page.slug),
      internal: true,
    };
  });

  return [...account, ...organization];
}

/** organizationSectionHeaders labels the org section unless the selected org shows none of its pages */
function organizationSectionHeaders(
  organizationId: string | undefined,
  pages: SettingsPageEntry[],
): Record<string, ReactNode> {
  const showsOrganizationPage = pages.some(
    (page) =>
      page.section === ORGANIZATION_SECTION && isSettingsPageShown(page),
  );
  if (organizationId && !showsOrganizationPage) return {};
  return { [ORGANIZATION_SECTION]: <OrganizationSectionHeader /> };
}