Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

35.4 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import { resetChatBackground, useBackgroundStore } from "@/features/chat-background";
import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { useChatPreferencesStore } from "@/features/chat";
import { Switch } from "@/components/ui/switch";
import { useSliderDraft } from "@/hooks/use-slider-draft";
import { NumericValueInput } from "@/features/model-picker/components/numeric-value-input";
import { type TranslationKey, useT } from "@/i18n";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import {
  Cancel01Icon,
  Upload01Icon,
} from "@hugeicons/core-free-icons";
import { Folder01Icon } from "@/lib/folder-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { motion, useReducedMotionConfig } from "motion/react";
import {
  useEffect,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";
import {
  CODE_FONT_SIZE_RANGE,
  type CustomModeColors,
  DEFAULT_CUSTOMIZATION,
  MAX_IMPORTED_FONTS,
  MAX_TOTAL_IMPORTED_FONT_DATA_URL_LENGTH,
  type ReduceMotionSetting,
  type SentAttachmentsSetting,
  UI_FONT_SIZE_RANGE,
  isDefaultCustomization,
  useAppearanceCustomStore,
} from "../stores/appearance-custom-store";
import {
  INTERFACE_SCALE_RANGE,
  useInterfaceScaleStore,
} from "../stores/interface-scale-store";
import {
  type Palette,
  type ResolvedTheme,
  usePalette,
  useTheme,
} from "../stores/theme-store";
import { COLOR_THEMES } from "../lib/color-themes";
import {
  GLASS_ELEMENT_OUTLINE,
  useThemeElementOutline,
} from "../lib/element-outline-default";
import { ColorPickerSwatch } from "./color-picker";
import { normalizeSizeInputDraft } from "./size-input-value";

/* ------------------------------- Colors -------------------------------- */
// Mirrors the palette tokens in index.css (foregrounds converted from oklch).
type DefaultModeColors = { [K in keyof CustomModeColors]: string };
const PALETTE_DEFAULT_COLORS: Record<
  Palette,
  Record<ResolvedTheme, DefaultModeColors>
> = COLOR_THEMES;

/** Only the active mode is editable; the other mode's overrides apply when the scheme flips. */
export function ActiveColorControl({
  colorKey,
  label,
}: {
  colorKey: keyof CustomModeColors;
  label: string;
}) {
  const t = useT();
  const { resolved } = useTheme();
  const { palette } = usePalette();
  const override = useAppearanceCustomStore(
    (s) => s.customization.colors[resolved][colorKey],
  );
  const setColor = useAppearanceCustomStore((s) => s.setColor);
  const fallback = PALETTE_DEFAULT_COLORS[palette][resolved][colorKey];
  const value = override ?? fallback;
  return (
    <div className="flex items-center gap-2">
      {override !== null && (
        <Button
          type="button"
          variant="ghost"
          size="sm"
          className="h-7 px-2 text-xs text-muted-foreground"
          onClick={() => setColor(resolved, colorKey, null)}
        >
          {t("settings.appearance.custom.reset")}
        </Button>
      )}
      <ColorPickerSwatch
        value={value}
        onChange={(hex) => setColor(resolved, colorKey, hex)}
        label={label}
      />
    </div>
  );
}

/* ------------------------------ Typography ------------------------------ */
// Mirrors html.client-mac (theme-boot.js), which swaps the sans default to the system font.
const SYSTEM_SANS_NAME = "SF Pro";
const DEFAULT_SANS_NAME =
  typeof document !== "undefined" &&
  document.documentElement.classList.contains("client-mac")
    ? SYSTEM_SANS_NAME
    : "Inter Variable";

const DEFAULT_FONT_NAMES = {
  ui: DEFAULT_SANS_NAME,
  heading: "Hellix",
  chat: DEFAULT_SANS_NAME,
  code: "JetBrains Mono",
} as const;

const BUNDLED_FONTS = [
  "Inter Variable",
  "Hellix",
  "Space Grotesk Variable",
  "Figtree Variable",
  "JetBrains Mono",
  "Fira Code",
] as const;

/* ----------------------------- Device fonts ------------------------------ */
// Probed by canvas measurement when the Local Font Access API is unavailable or denied.
const CANDIDATE_DEVICE_FONTS = [
  "American Typewriter",
  "Andale Mono",
  "Arial",
  "Avenir",
  "Avenir Next",
  "Baskerville",
  "Calibri",
  "Cambria",
  "Candara",
  "Cantarell",
  "Charter",
  "Comic Sans MS",
  "Consolas",
  "Constantia",
  "Corbel",
  "Courier",
  "Courier New",
  "DejaVu Sans",
  "DejaVu Sans Mono",
  "DejaVu Serif",
  "Didot",
  "Fira Sans",
  "Franklin Gothic Medium",
  "Futura",
  "Geneva",
  "Georgia",
  "Gill Sans",
  "Helvetica",
  "Helvetica Neue",
  "Hoefler Text",
  "IBM Plex Mono",
  "IBM Plex Sans",
  "Impact",
  "Inconsolata",
  "Iosevka",
  "Lato",
  "Liberation Mono",
  "Liberation Sans",
  "Liberation Serif",
  "Lucida Grande",
  "Menlo",
  "Monaco",
  "Montserrat",
  "Noto Sans",
  "Noto Serif",
  "Nunito",
  "Open Sans",
  "Optima",
  "Palatino",
  "Roboto",
  "Rockwell",
  "Segoe UI",
  "Seravek",
  "Source Sans Pro",
  "Tahoma",
  "Times",
  "Times New Roman",
  "Trebuchet MS",
  "Ubuntu",
  "Verdana",
];

function detectFontsByMeasurement(candidates: string[]): string[] {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return [];
  const sample = "mmmmmmmmmwwwwwwwlli";
  const baselines = ["monospace", "sans-serif", "serif"].map((base) => {
    ctx.font = `72px ${base}`;
    return { base, width: ctx.measureText(sample).width };
  });
  return candidates.filter((family) =>
    baselines.some(({ base, width }) => {
      ctx.font = `72px "${family}", ${base}`;
      return ctx.measureText(sample).width !== width;
    }),
  );
}

// The system font has no addressable family name, so preview it through the token.
function previewFamily(font: string): string {
  return font === SYSTEM_SANS_NAME
    ? "var(--font-sans-default)"
    : `"${font}", var(--font-sans)`;
}

let deviceFontsCache: string[] | null = null;

async function loadDeviceFonts(): Promise<string[]> {
  if (deviceFontsCache) return deviceFontsCache;
  let families: string[] = [];
  const query = (
    globalThis as {
      queryLocalFonts?: () => Promise<{ family: string }[]>;
    }
  ).queryLocalFonts;
  if (typeof query === "function") {
    try {
      const fonts = await query();
      families = [...new Set(fonts.map((f) => f.family))];
    } catch {
      // permission denied; fall back to measurement probing
    }
  }
  if (families.length === 0) {
    families = detectFontsByMeasurement(CANDIDATE_DEVICE_FONTS);
  }
  deviceFontsCache = families.sort((a, b) => a.localeCompare(b));
  return deviceFontsCache;
}

function FontSelect({
  value,
  defaultFont,
  onCommit,
  ariaLabel,
  className,
}: {
  value: string | null;
  defaultFont: string;
  onCommit: (next: string | null) => void;
  ariaLabel: string;
  className?: string;
}) {
  const t = useT();
  const defaultLabel = `${defaultFont} (${t("settings.appearance.custom.fontDefault")})`;
  const [open, setOpen] = useState(false);
  const [deviceFonts, setDeviceFonts] = useState<string[] | null>(
    deviceFontsCache,
  );
  const importedFonts = useAppearanceCustomStore(
    (s) => s.customization.importedFonts,
  );
  const removeImportedFont = useAppearanceCustomStore(
    (s) => s.removeImportedFont,
  );

  const handleOpenChange = (next: boolean) => {
    setOpen(next);
    // Start inside the click: queryLocalFonts may need transient user activation.
    if (next && deviceFonts === null) {
      void loadDeviceFonts().then(setDeviceFonts);
    }
  };

  const select = (next: string | null) => {
    onCommit(next);
    setOpen(false);
  };

  const folderFonts = useFolderFonts();
  const { inputs: uploadInputs, requestUpload, requestFolder, importFile } =
    useFontImport((name) => select(name));

  const knownNames = new Set<string>([
    ...BUNDLED_FONTS,
    ...importedFonts.map((f) => f.name),
  ]);
  const deviceOnlyFonts = (deviceFonts ?? []).filter((f) => !knownNames.has(f));

  const renderItem = (font: string) => (
    <CommandItem
      key={font}
      value={font}
      onSelect={() => select(font)}
      data-checked={value === font}
      className="cursor-pointer rounded-md"
    >
      <span
        className="min-w-0 truncate"
        style={{ fontFamily: `"${font}", var(--font-sans)` }}
      >
        {font}
      </span>
    </CommandItem>
  );

  return (
    <Popover open={open} onOpenChange={handleOpenChange} modal={true}>
      <PopoverTrigger asChild={true}>
        <button
          type="button"
          aria-label={ariaLabel}
          aria-expanded={open}
          className={cn(
            "flex h-8 w-48 cursor-pointer items-center justify-between gap-1.5 rounded-full border border-border bg-background px-3.5 text-xs outline-none transition-colors hover:bg-accent/50 focus-visible:border-ring dark:focus-visible:border-transparent dark:focus-visible:bg-[rgb(255_255_255_/_calc(0.12*var(--contrast-wash-gain,1)))] dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]",
            className,
          )}
        >
          <span
            className="min-w-0 truncate"
            style={{ fontFamily: previewFamily(value ?? defaultFont) }}
          >
            {value ?? defaultLabel}
          </span>
          <HugeiconsIcon
            icon={ChevronDownStandardIcon}
            strokeWidth={2}
            className="size-4 shrink-0 text-muted-foreground"
          />
        </button>
      </PopoverTrigger>
      <PopoverContent
        align="end"
        className="w-64 gap-0 rounded-lg p-1 font-heading"
      >
        <Command className="rounded-none bg-transparent p-0">
          <CommandInput
            placeholder={t("settings.appearance.custom.fontSearch")}
          />
          <CommandList className="max-h-64 pt-1.5">
            <CommandEmpty>
              {t("settings.appearance.custom.fontNoResults")}
            </CommandEmpty>
            <CommandItem
              value={defaultLabel}
              onSelect={() => select(null)}
              data-checked={value === null}
              className="cursor-pointer rounded-md"
            >
              <span style={{ fontFamily: previewFamily(defaultFont) }}>
                {defaultLabel}
              </span>
            </CommandItem>
            <CommandGroup
              className="p-0"
              heading={t("settings.appearance.custom.fontBundledGroup")}
            >
              {BUNDLED_FONTS.map(renderItem)}
            </CommandGroup>
            {importedFonts.length > 0 && (
              <CommandGroup
                className="p-0"
                heading={t("settings.appearance.custom.fontImportedGroup")}
              >
                {importedFonts.map((font) => (
                  <CommandItem
                    key={font.name}
                    value={font.name}
                    onSelect={() => select(font.name)}
                    data-checked={value === font.name}
                    className="cursor-pointer rounded-md"
                  >
                    <span
                      className="min-w-0 truncate"
                      style={{ fontFamily: `"${font.name}", var(--font-sans)` }}
                    >
                      {font.name}
                    </span>
                    <button
                      type="button"
                      aria-label={`${t("settings.appearance.custom.importFont.remove")}: ${font.name}`}
                      onPointerDown={(e) => e.stopPropagation()}
                      onClick={(e) => {
                        e.stopPropagation();
                        removeImportedFont(font.name);
                      }}
                      className="ml-auto rounded-full p-0.5 text-muted-foreground transition-colors hover:text-foreground"
                    >
                      <HugeiconsIcon icon={Cancel01Icon} className="size-3" />
                    </button>
                  </CommandItem>
                ))}
              </CommandGroup>
            )}
            {folderFonts.some((f) => !knownNames.has(f.name)) && (
              <CommandGroup
                className="p-0"
                heading={t("settings.appearance.custom.fontFolderGroup")}
              >
                {folderFonts
                  .filter((f) => !knownNames.has(f.name))
                  .map(({ name, file }) => (
                    <CommandItem
                      key={`folder-${name}`}
                      value={name}
                      onSelect={() => importFile(file)}
                      className="cursor-pointer rounded-md"
                    >
                      <span className="min-w-0 truncate">{name}</span>
                    </CommandItem>
                  ))}
              </CommandGroup>
            )}
            <CommandGroup
              className="p-0"
              heading={t("settings.appearance.custom.fontDeviceGroup")}
            >
              {deviceFonts === null ? (
                <div className="px-3 py-2 text-xs text-muted-foreground">
                  {t("settings.appearance.custom.fontDeviceLoading")}
                </div>
              ) : (
                deviceOnlyFonts.map(renderItem)
              )}
            </CommandGroup>
          </CommandList>
        </Command>
        <div className="mt-1 flex items-center gap-1 border-t border-border/60 pt-1">
          <button
            type="button"
            onClick={requestUpload}
            className="flex flex-1 cursor-pointer items-center gap-2 whitespace-nowrap rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
          >
            <HugeiconsIcon
              icon={Upload01Icon}
              className="size-4 shrink-0 text-muted-foreground"
            />
            {t("settings.appearance.custom.importFont.upload")}
          </button>
          <div className="h-4 w-px shrink-0 bg-border" />
          <button
            type="button"
            onClick={requestFolder}
            className="flex flex-1 cursor-pointer items-center gap-2 whitespace-nowrap rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
          >
            <HugeiconsIcon
              icon={Folder01Icon}
              className="size-4 shrink-0 text-muted-foreground"
            />
            {t("settings.appearance.custom.importFont.scanFolder")}
          </button>
        </div>
        {uploadInputs}
      </PopoverContent>
    </Popover>
  );
}

export function UiFontRow({ className }: { className?: string }) {
  const t = useT();
  const uiFont = useAppearanceCustomStore((s) => s.customization.uiFont);
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <FontSelect
      value={uiFont}
      defaultFont={DEFAULT_FONT_NAMES.ui}
      onCommit={(next) => patch({ uiFont: next })}
      ariaLabel={t("settings.appearance.custom.uiFont.label")}
      className={className}
    />
  );
}

export function HeadingFontRow({ className }: { className?: string }) {
  const t = useT();
  const headingFont = useAppearanceCustomStore(
    (s) => s.customization.headingFont,
  );
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <FontSelect
      value={headingFont}
      defaultFont={DEFAULT_FONT_NAMES.heading}
      onCommit={(next) => patch({ headingFont: next })}
      ariaLabel={t("settings.appearance.custom.headingFont.label")}
      className={className}
    />
  );
}

export function ChatFontRow({ className }: { className?: string }) {
  const t = useT();
  const chatFont = useAppearanceCustomStore((s) => s.customization.chatFont);
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <FontSelect
      value={chatFont}
      defaultFont={DEFAULT_FONT_NAMES.chat}
      onCommit={(next) => patch({ chatFont: next })}
      ariaLabel={t("settings.appearance.custom.chatFont.label")}
      className={className}
    />
  );
}

export function CodeFontRow({ className }: { className?: string }) {
  const t = useT();
  const codeFont = useAppearanceCustomStore((s) => s.customization.codeFont);
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <FontSelect
      value={codeFont}
      defaultFont={DEFAULT_FONT_NAMES.code}
      onCommit={(next) => patch({ codeFont: next })}
      ariaLabel={t("settings.appearance.custom.codeFont.label")}
      className={className}
    />
  );
}

/* ---------------------------- Imported fonts ---------------------------- */
const FONT_MIME_BY_EXTENSION: Record<string, string> = {
  woff2: "font/woff2",
  woff: "font/woff",
  ttf: "font/ttf",
  otf: "font/otf",
};

const MAX_FONT_FILE_BYTES = Math.floor(1.5 * 1024 * 1024);

// Trailing style words are stripped so Roboto-Bold.ttf matches an installed Roboto.
const FONT_STYLE_SUFFIXES = new Set([
  "regular",
  "bold",
  "italic",
  "light",
  "medium",
  "thin",
  "black",
  "semibold",
  "extrabold",
  "extralight",
  "heavy",
  "book",
  "oblique",
  "normal",
  "variable",
  "vf",
]);

function fontBaseName(fileName: string): string {
  return fileName
    .replace(/\.[^.]+$/, "")
    .replace(/[;{}()<>"']/g, "")
    .replace(/[_-]+/g, " ")
    .trim();
}

function familyCandidates(base: string): string[] {
  const candidates = [base];
  let words = base.split(/\s+/);
  while (
    words.length > 1 &&
    FONT_STYLE_SUFFIXES.has(words[words.length - 1].toLowerCase())
  ) {
    words = words.slice(0, -1);
    candidates.push(words.join(" "));
  }
  return candidates;
}

/* ----------------------------- Folder fonts ----------------------------- */
// Directory-input file handles cannot be persisted, so the scan lives for the session.
type FolderFont = { name: string; file: File };
let folderFontsCache: FolderFont[] = [];
const folderFontsListeners = new Set<() => void>();

function setFolderFonts(next: FolderFont[]) {
  folderFontsCache = next;
  for (const listener of folderFontsListeners) listener();
}

function useFolderFonts(): FolderFont[] {
  return useSyncExternalStore(
    (onChange) => {
      folderFontsListeners.add(onChange);
      return () => folderFontsListeners.delete(onChange);
    },
    () => folderFontsCache,
  );
}

function fontNameFromFile(fileName: string, taken: Set<string>): string {
  const base = fontBaseName(fileName).slice(0, 60) || "Imported font";
  let candidate = base;
  let suffix = 2;
  while (taken.has(candidate)) {
    candidate = `${base} ${suffix}`;
    suffix += 1;
  }
  return candidate;
}

/** Fonts the user already has are selected directly instead of embedding a duplicate. */
function useFontImport(onImported: (name: string) => void) {
  const t = useT();
  const importedFonts = useAppearanceCustomStore(
    (s) => s.customization.importedFonts,
  );
  const addImportedFont = useAppearanceCustomStore((s) => s.addImportedFont);
  const inputRef = useRef<HTMLInputElement>(null);
  const folderRef = useRef<HTMLInputElement>(null);

  const findExisting = (fileName: string): string | null => {
    for (const candidate of familyCandidates(fontBaseName(fileName))) {
      const lower = candidate.toLowerCase();
      const imported = importedFonts.find((f) => f.name.toLowerCase() === lower);
      if (imported) return imported.name;
      const bundled = BUNDLED_FONTS.find((f) => f.toLowerCase() === lower);
      if (bundled) return bundled;
      if (detectFontsByMeasurement([candidate]).length > 0) return candidate;
    }
    return null;
  };

  const importFile = (file: File) => {
    const existing = findExisting(file.name);
    if (existing) {
      toast.info(t("settings.appearance.custom.importFont.alreadyAvailable"));
      onImported(existing);
      return;
    }
    if (importedFonts.length >= MAX_IMPORTED_FONTS) {
      toast.error(t("settings.appearance.custom.importFont.errorLimit"));
      return;
    }
    const extension = file.name.split(".").pop()?.toLowerCase() ?? "";
    const mime = FONT_MIME_BY_EXTENSION[extension];
    if (!mime) {
      toast.error(t("settings.appearance.custom.importFont.errorInvalidType"));
      return;
    }
    if (file.size > MAX_FONT_FILE_BYTES) {
      toast.error(t("settings.appearance.custom.importFont.errorTooLarge"));
      return;
    }
    const reader = new FileReader();
    reader.onerror = () => {
      toast.error(t("settings.appearance.custom.importFont.errorFailed"));
    };
    reader.onload = () => {
      const result = reader.result;
      if (typeof result !== "string") {
        toast.error(t("settings.appearance.custom.importFont.errorFailed"));
        return;
      }
      // Use the extension's MIME so the data URL passes frontend and backend validation.
      const base64 = result.slice(result.indexOf(",") + 1);
      const dataUrl = `data:${mime};base64,${base64}`;
      // Stay under the localStorage quota.
      const existingTotal = importedFonts.reduce(
        (sum, f) => sum + f.dataUrl.length,
        0,
      );
      if (
        existingTotal + dataUrl.length >
        MAX_TOTAL_IMPORTED_FONT_DATA_URL_LENGTH
      ) {
        toast.error(
          t("settings.appearance.custom.importFont.errorStorageFull"),
        );
        return;
      }
      const taken = new Set<string>([
        ...BUNDLED_FONTS,
        ...importedFonts.map((f) => f.name),
      ]);
      const name = fontNameFromFile(file.name, taken);
      const face = new FontFace(name, `url(${dataUrl})`);
      face
        .load()
        .then(() => {
          addImportedFont({ name, dataUrl });
          onImported(name);
        })
        .catch(() => {
          toast.error(t("settings.appearance.custom.importFont.errorFailed"));
        });
    };
    reader.readAsDataURL(file);
  };

  const scanFolder = (files: FileList) => {
    const found: FolderFont[] = [];
    const seen = new Set<string>();
    for (const file of Array.from(files)) {
      const extension = file.name.split(".").pop()?.toLowerCase() ?? "";
      if (!FONT_MIME_BY_EXTENSION[extension]) continue;
      const name = fontBaseName(file.name).slice(0, 60);
      if (!name || seen.has(name.toLowerCase())) continue;
      seen.add(name.toLowerCase());
      found.push({ name, file });
      if (found.length >= 200) break;
    }
    if (found.length === 0) {
      toast.info(t("settings.appearance.custom.importFont.folderNoFonts"));
      return;
    }
    found.sort((a, b) => a.name.localeCompare(b.name));
    setFolderFonts(found);
  };

  const requestUpload = () => inputRef.current?.click();
  const requestFolder = () => folderRef.current?.click();

  const inputs = (
    <>
      <input
        ref={inputRef}
        type="file"
        accept=".woff2,.woff,.ttf,.otf"
        className="hidden"
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (file) importFile(file);
          e.target.value = "";
        }}
      />
      <input
        ref={folderRef}
        type="file"
        className="hidden"
        {...({ webkitdirectory: "", directory: "" } as object)}
        onChange={(e) => {
          if (e.target.files) scanFolder(e.target.files);
          e.target.value = "";
        }}
      />
    </>
  );

  return { inputs, requestUpload, requestFolder, importFile };
}

function SizeInput({
  value,
  range,
  onCommit,
  ariaLabel,
  unit,
}: {
  value: number | null;
  range: { min: number; max: number; default: number };
  onCommit: (next: number | null) => void;
  ariaLabel: string;
  unit: string;
}) {
  const [draft, setDraft] = useState(value === null ? "" : String(value));
  useEffect(() => {
    setDraft(value === null ? "" : String(value));
  }, [value]);
  const commit = () => {
    const normalized = normalizeSizeInputDraft(draft, range);
    if (!normalized) {
      setDraft(value === null ? "" : String(value));
      return;
    }
    setDraft(normalized.draft);
    onCommit(normalized.value);
  };
  return (
    // Tagged so settings search can land on a nested size input.
    <div data-settings-label={ariaLabel} className="flex items-center gap-1.5">
      <Input
        type="number"
        inputMode="numeric"
        min={range.min}
        max={range.max}
        value={draft}
        placeholder={String(range.default)}
        onChange={(e) => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            commit();
            e.currentTarget.blur();
          }
        }}
        aria-label={ariaLabel}
        className="h-8 w-20 text-xs"
      />
      <span className="text-xs text-muted-foreground">{unit}</span>
    </div>
  );
}

export function InterfaceScaleRow() {
  const t = useT();
  const interfaceScale = useInterfaceScaleStore((s) => s.scale);
  const setScale = useInterfaceScaleStore((s) => s.setScale);
  return (
    <SizeInput
      value={interfaceScale}
      range={INTERFACE_SCALE_RANGE}
      onCommit={(next) => setScale(next ?? INTERFACE_SCALE_RANGE.default)}
      ariaLabel={t("settings.appearance.custom.interfaceScale.label")}
      unit="%"
    />
  );
}

export function UiFontSizeRow() {
  const t = useT();
  const uiFontSize = useAppearanceCustomStore(
    (s) => s.customization.uiFontSize,
  );
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <SizeInput
      value={uiFontSize}
      range={UI_FONT_SIZE_RANGE}
      onCommit={(next) => patch({ uiFontSize: next })}
      ariaLabel={t("settings.appearance.custom.uiFontSize.label")}
      unit="px"
    />
  );
}

export function CodeFontSizeRow() {
  const t = useT();
  const codeFontSize = useAppearanceCustomStore(
    (s) => s.customization.codeFontSize,
  );
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <SizeInput
      value={codeFontSize}
      range={CODE_FONT_SIZE_RANGE}
      onCommit={(next) => patch({ codeFontSize: next })}
      ariaLabel={t("settings.appearance.custom.codeFontSize.label")}
      unit="px"
    />
  );
}

export function CodeDisplaySwitch({
  field,
  label,
}: {
  field: "codeLineNumbers" | "codeWordWrap" | "codeLigatures";
  label: string;
}) {
  const checked = useAppearanceCustomStore((s) => s.customization[field]);
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <Switch
      aria-label={label}
      checked={checked}
      onCheckedChange={(next) => patch({ [field]: next })}
    />
  );
}

export function FontSmoothingSwitch() {
  const fontSmoothing = useAppearanceCustomStore(
    (s) => s.customization.fontSmoothing,
  );
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <Switch
      checked={fontSmoothing}
      onCheckedChange={(checked) => patch({ fontSmoothing: checked })}
    />
  );
}

/* ------------------------------ Interface ------------------------------- */
export function ChatWidthSelect() {
  const t = useT();
  const chatWidth = useAppearanceCustomStore((s) => s.customization.chatWidth);
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <Select
      value={chatWidth}
      onValueChange={(value) => {
        if (value === "standard" || value === "wide" || value === "full") {
          patch({ chatWidth: value });
        }
      }}
    >
      <SelectTrigger
        className="w-40"
        aria-label={t("settings.appearance.custom.chatWidth.label")}
      >
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {(["standard", "wide", "full"] as const).map((width) => (
          <SelectItem key={width} value={width}>
            {t(`settings.appearance.custom.chatWidth.${width}`)}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

const SENT_ATTACHMENTS_OPTIONS: SentAttachmentsSetting[] = ["auto", "list", "chips"];

export function SentAttachmentsSelect() {
  const t = useT();
  const value = useAppearanceCustomStore((s) => s.customization.sentAttachments);
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <Select
      value={value}
      onValueChange={(next) => {
        if (next === "auto" || next === "list" || next === "chips") {
          patch({ sentAttachments: next });
        }
      }}
    >
      <SelectTrigger
        className="w-40"
        aria-label={t("settings.appearance.custom.sentAttachments.label")}
      >
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {SENT_ATTACHMENTS_OPTIONS.map((option) => (
          <SelectItem key={option} value={option}>
            {t(`settings.appearance.custom.sentAttachments.${option}`)}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

export function ContrastSliderRow() {
  const t = useT();
  const contrast = useAppearanceCustomStore((s) => s.customization.contrast);
  const patch = useAppearanceCustomStore((s) => s.patch);
  const { draft, sliderProps } = useSliderDraft(contrast, (value) => patch({ contrast: value }));
  return (
    <div className="flex w-64 items-center gap-3">
      <Slider
        className="contrast-slider"
        {...sliderProps}
        min={0}
        max={100}
        step={1}
        aria-label={t("settings.appearance.custom.contrast.label")}
      />
      <NumericValueInput
        value={draft ?? contrast}
        min={0}
        max={100}
        step={1}
        onChange={(value) => patch({ contrast: value })}
        ariaLabel={t("settings.appearance.custom.contrast.label")}
        className="panel-field h-8 w-[calc(84px*var(--ui-space-scale,1))] shrink-0"
        fixedWidth={true}
        size={4}
      />
    </div>
  );
}

export function ElementOutlineSliderRow() {
  const t = useT();
  const { resolved } = useTheme();
  const outline = useAppearanceCustomStore((s) => s.customization.elementOutline);
  const patch = useAppearanceCustomStore((s) => s.patch);
  // Unset starts at the theme's own strength, so the first drag does not jump.
  const themeOutline = useThemeElementOutline(outline === null);
  const value = outline ?? themeOutline ?? GLASS_ELEMENT_OUTLINE[resolved];
  const set = (next: number) => patch({ elementOutline: next });
  const label = t("settings.appearance.custom.elementOutline.label");
  return (
    <div className="flex w-64 items-center gap-3">
      <Slider
        value={[value]}
        min={0}
        max={100}
        step={1}
        onValueChange={(values: number[]) => set(values[0])}
        aria-label={label}
      />
      <NumericValueInput
        value={value}
        min={0}
        max={100}
        step={1}
        onChange={set}
        ariaLabel={label}
        className="panel-field h-8 w-[calc(84px*var(--ui-space-scale,1))] shrink-0"
        fixedWidth={true}
        size={4}
      />
    </div>
  );
}

export function ComposerOutlineSliderRow() {
  const t = useT();
  const outline = useAppearanceCustomStore((s) => s.customization.composerOutline);
  const backgroundOutline = useBackgroundStore((s) => s.value?.outline);
  const patch = useAppearanceCustomStore((s) => s.patch);
  const value = outline ?? backgroundOutline ?? 0;
  const set = (next: number) => patch({ composerOutline: next });
  return (
    <div className="flex w-64 items-center gap-3">
      <Slider
        value={[value]}
        min={0}
        max={100}
        step={1}
        onValueChange={(values: number[]) => set(values[0])}
        aria-label={t("chatBackground.outline")}
      />
      <NumericValueInput
        value={value}
        min={0}
        max={100}
        step={1}
        onChange={set}
        ariaLabel={t("chatBackground.outline")}
        className="panel-field h-8 w-[calc(84px*var(--ui-space-scale,1))] shrink-0"
        fixedWidth={true}
        size={4}
      />
    </div>
  );
}

export function ComposerPositionSliderRow() {
  const t = useT();
  const value = useChatPreferencesStore((s) => s.newChatComposerPosition);
  const set = useChatPreferencesStore((s) => s.setNewChatComposerPosition);
  return (
    <div className="flex w-64 items-center gap-3">
      <Slider
        value={[value]}
        min={0}
        max={100}
        step={1}
        onValueChange={(values: number[]) => set(values[0])}
        aria-label={t("settings.chat.composerPosition")}
      />
      <NumericValueInput
        value={value}
        min={0}
        max={100}
        step={1}
        onChange={set}
        ariaLabel={t("settings.chat.composerPosition")}
        className="panel-field h-8 w-[calc(84px*var(--ui-space-scale,1))] shrink-0"
        fixedWidth={true}
        size={4}
      />
    </div>
  );
}

export function PointerCursorsSwitch() {
  const pointerCursors = useAppearanceCustomStore(
    (s) => s.customization.pointerCursors,
  );
  const patch = useAppearanceCustomStore((s) => s.patch);
  return (
    <Switch
      checked={pointerCursors}
      onCheckedChange={(checked) => patch({ pointerCursors: checked })}
    />
  );
}

const REDUCE_MOTION_OPTIONS: {
  value: ReduceMotionSetting;
  labelKey: TranslationKey;
}[] = [
  {
    value: "system",
    labelKey: "settings.appearance.custom.reduceMotion.system",
  },
  { value: "on", labelKey: "settings.appearance.custom.reduceMotion.on" },
  { value: "off", labelKey: "settings.appearance.custom.reduceMotion.off" },
];

export function ReduceMotionSegmented() {
  const t = useT();
  const reduceMotion = useAppearanceCustomStore(
    (s) => s.customization.reduceMotion,
  );
  const patch = useAppearanceCustomStore((s) => s.patch);
  const reduced = useReducedMotionConfig();
  return (
    <div className="hub-tab-toggle inline-flex h-8 items-center rounded-full">
      {REDUCE_MOTION_OPTIONS.map((opt) => {
        const active = reduceMotion === opt.value;
        return (
          <button
            key={opt.value}
            type="button"
            onClick={() => patch({ reduceMotion: opt.value })}
            aria-pressed={active}
            className={cn(
              "relative flex h-8 items-center rounded-full px-3 text-xs font-medium transition-colors",
              active
                ? "text-foreground"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {active && (
              <motion.span
                layoutId="reduce-motion-pill"
                className="hub-tab-toggle-pill absolute inset-0 rounded-full"
                transition={
                  reduced
                    ? { duration: 0 }
                    : { type: "spring", stiffness: 500, damping: 35, mass: 0.5 }
                }
              />
            )}
            <span className="relative z-10">{t(opt.labelKey)}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ------------------------------- Reset all ------------------------------ */
export function ResetCustomizationButton() {
  const t = useT();
  const customization = useAppearanceCustomStore((s) => s.customization);
  const resetAll = useAppearanceCustomStore((s) => s.resetAll);
  const interfaceScale = useInterfaceScaleStore((s) => s.scale);
  const resetInterfaceScale = useInterfaceScaleStore((s) => s.reset);
  const background = useBackgroundStore((s) => s.value);
  const pristine =
    background === null &&
    isDefaultCustomization(customization) &&
    interfaceScale === INTERFACE_SCALE_RANGE.default;
  return (
    <Button
      type="button"
      variant="outline"
      size="sm"
      disabled={pristine}
      onClick={() => {
        void resetChatBackground();
        resetAll();
        resetInterfaceScale();
      }}
    >
      {t("settings.appearance.custom.resetAll")}
    </Button>
  );
}

export { DEFAULT_CUSTOMIZATION };