Skip to content

Open source CapCut alternative.

TypeScript
26.6 KB
Raw Blame
"use client";

import { useEffect, useMemo, useState } from "react";
import { ChevronDown } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { OUTPUT_SPACES, type OutputSpace } from "@donkeycut/effects-kit";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import {
  DEFAULT_EXPORT_FPS,
  EXPORT_AUDIO,
  EXPORT_CODECS,
  EXPORT_CONTAINERS,
  EXPORT_FRAME_RATES,
  EXPORT_QUALITIES,
  EXPORT_QUICK_PRESETS,
  choiceSettings,
  estimateExportBytes,
  fixedRate,
  formatSizeEstimate,
  quickPresetOf,
  resolutionOptions,
  resolveResolution,
  selectionRange,
  type ExportChoice,
  type ExportCodec,
  type ExportContainer,
  type ExportSettings,
} from "@/cut/lib/exportClient";
import { useCutMode } from "@/cut/lib/backend/hooks";
import { downloadText } from "@/cut/lib/download";
import { deliverySpan, exportBaseName } from "@/cut/lib/exportDelivery";
import { canRenderInBrowser, sourceExportProfile, sourceFrameRateKey, type SourceExportProfile } from "@/cut/lib/exportRender";
import { useExports } from "@/cut/lib/exportStore";
import { projectDuration, useEditor } from "@/cut/lib/store";
import { subtitleFiles } from "@/cut/lib/subtitleFile";
import { formatTime } from "@/cut/lib/time";
import { CUT_LOUDNESS, LOUDNESS_CHOICES, loudnessSettings, type LoudnessId } from "@/cut/lib/loudnessSettings";
import { planStems } from "@/cut/lib/stems";
import { cn } from "@/lib/utils";

/** A file format the menu offers: a container carrying a codec. A codec that
 * demands a container of its own is only offered with it. */
const FORMATS = EXPORT_CONTAINERS.flatMap((c) =>
  EXPORT_CODECS.filter((k) => !k.container || k.container === c.id).map((k) => ({
    id: `${c.id}-${k.id}`,
    container: c.id as ExportContainer,
    codec: k.id as ExportCodec,
    label: `${c.label} (${k.label})`,
  }))
);

/** The quality tiers in slider order, lightest on the left. */
const QUALITY_RUNGS = [...EXPORT_QUALITIES].reverse();

// Just a launcher: pick a preset or set every axis yourself, hand the cut to
// the engine, and close. Every export — progress, queue position, the
// finished file — is tracked in the app-wide exports dock, so starting one
// never blocks starting another.
export function ExportDialog() {
  const t = useTranslations("editor.exportDialog");
  const locale = useLocale();
  const setExportOpen = useEditor((s) => s.setExportOpen);
  const aspect = useEditor((s) => s.aspect);
  const clips = useEditor((s) => s.clips);
  const assets = useEditor((s) => s.assets);
  const audioClips = useEditor((s) => s.audioClips);
  const overlays = useEditor((s) => s.overlays);
  const subtitles = useEditor((s) => s.subtitles);
  const multiSelection = useEditor((s) => s.multiSelection);
  const projectName = useEditor((s) => s.projectName);
  // The delivery's color space is the project's own setting: it decides what
  // every clip converts to, so it lives on the document rather than in this
  // dialog's choice.
  const colorSpace = useEditor((s) => s.colorSpace);
  const setColorSpace = useEditor((s) => s.setColorSpace);
  const hdr = colorSpace !== "sdr";
  const duration = useMemo(
    () => projectDuration({ clips, audioClips, overlays }),
    [clips, audioClips, overlays]
  );
  const resolutions = useMemo(
    () => resolutionOptions(aspect, clips, assets, { audioClips, overlays, subtitles }),
    [aspect, clips, assets, audioClips, overlays, subtitles]
  );
  // The size rungs in slider order, smallest on the left, largest on the right.
  const rungs = useMemo(() => [...resolutions].reverse(), [resolutions]);
  const [choice, setChoice] = useState<ExportChoice>(EXPORT_QUICK_PRESETS[1].choice);
  // The field's own text, so a decimal in progress ("1.") survives the parse.
  const [mbpsText, setMbpsText] = useState("");
  // Custom is a tile of its own: picked by click, it stays lit whatever the
  // options add up to, until a preset tile is clicked.
  const [customPicked, setCustomPicked] = useState(false);
  const [moreOpen, setMoreOpen] = useState(false);
  // The file's name, the project's until typed over.
  const [name, setName] = useState(projectName);
  // What stretch of the timeline the file carries.
  const [rangeMode, setRangeMode] = useState<"all" | "selection">("all");
  // A captions file beside the video.
  const [withCaptions, setWithCaptions] = useState(false);
  // The loudness the mix is mastered to, starting on the account's default.
  const [loudness, setLoudness] = useState<LoudnessId>(() => CUT_LOUDNESS.defaultTarget);
  // A zip of one WAV per lane beside the video.
  const [withStems, setWithStems] = useState(false);
  const canStem = useMemo(() => planStems({ clips, audioClips, assets }).length > 0, [clips, audioClips, assets]);
  const stems = withStems && canStem;
  // The footage's frame rate, read from the sources once the dialog opens;
  // a "source" frame-rate choice resolves to it. Undefined while the probe
  // runs, null for a cut with no readable video. The probe re-runs only when
  // the set of sources it reads changes — an upload ticking its progress
  // through the assets list leaves it alone — and a superseded probe closes
  // its readers.
  const probeKey = sourceFrameRateKey({ clips, assets });
  const [probe, setProbe] = useState<({ key: string } & SourceExportProfile) | null>(null);
  useEffect(() => {
    const abort = new AbortController();
    const s = useEditor.getState();
    void sourceExportProfile({ clips: s.clips, assets: s.assets }, (a) => a.url, { signal: abort.signal }).then(
      (profile) => {
        if (!abort.signal.aborted) setProbe({ key: probeKey, ...profile });
      }
    );
    return () => abort.abort();
  }, [probeKey]);
  const probing = probe?.key !== probeKey;
  const sourceFps = probing ? undefined : probe.fps;
  const selection = useMemo(
    () => selectionRange({ multiSelection, clips, audioClips, overlays, subtitles }),
    [multiSelection, clips, audioClips, overlays, subtitles]
  );
  const range = rangeMode === "selection" && selection ? selection : undefined;
  const span = deliverySpan(range, duration);
  const preset = customPicked ? null : quickPresetOf(choice, resolutions);
  // The file's base name. It rides in the settings only when typed over: the
  // engine names a file after the project itself, so an untouched name asks
  // nothing extra of it.
  const baseName = exportBaseName(name || projectName);
  const typedName = baseName !== exportBaseName(projectName);
  const settings = useMemo<ExportSettings>(
    () => {
      const chosen = choiceSettings(choice, resolutions, sourceFps ?? DEFAULT_EXPORT_FPS,
        !probing && probe ? { ...probe, ...(audioClips.length > 0 ? { audioBitrate: undefined, audioSampleRate: undefined, audioChannels: undefined } : {}) } : undefined);
      return {
        ...chosen,
        // H.264 is 8-bit: an HDR delivery takes HEVC in its place, whatever
        // the preset or the probe asked for.
        ...(hdr && chosen.codec === "h264" ? { codec: "hevc" as const, copySource: false } : {}),
        ...(typedName ? { name: baseName } : {}),
        ...(range ? { range } : {}),
        ...loudnessSettings(loudness),
        ...(stems ? { stems: true } : {}),
      };
    },
    [choice, resolutions, sourceFps, probe, probing, audioClips.length, typedName, baseName, range, hdr, loudness, stems]
  );
  const set = (patch: Partial<ExportChoice>) => setChoice((c) => ({ ...c, ...patch }));
  const captionFiles = useMemo(
    () => subtitleFiles(subtitles, baseName, range),
    [subtitles, baseName, range]
  );
  // A "source" rate is not known until the probe answers; the button waits.
  const waiting = probing && (choice.fps === "source" || choice.resolution === "source");

  // A browser-resident project renders in this tab when it can, and on the
  // cloud worker when it can't; ask up front which it is, so the dialog says
  // where the render is going.
  const cutMode = useCutMode();
  const [browserFits, setBrowserFits] = useState(true);
  const inTab = cutMode !== "browser" || browserFits;
  useEffect(() => {
    if (cutMode !== "browser") return;
    let alive = true;
    const s = useEditor.getState();
    void canRenderInBrowser(
      {
        aspect: s.aspect,
        assets: s.assets,
        clips: s.clips,
        audioClips: s.audioClips,
        overlays: s.overlays,
        subtitles: s.subtitles,
        background: s.background,
        colorSpace: s.colorSpace,
      },
      settings,
      s.colorSpace ?? "sdr"
    ).then((ok) => {
      if (alive) setBrowserFits(ok);
    });
    return () => {
      alive = false;
    };
  }, [cutMode, settings]);

  const run = () => {
    const s = useEditor.getState();
    if (!s.projectId) return;
    void useExports.getState().start(
      s.projectId,
      {
        aspect: s.aspect,
        assets: s.assets,
        clips: s.clips,
        audioClips: s.audioClips,
        overlays: s.overlays,
        subtitles: s.subtitles,
        background: s.background,
        colorSpace: s.colorSpace,
      },
      settings,
      baseName
    );
    // The captions file is made here and saved at once; the video follows
    // through the dock when its render lands.
    if (withCaptions) {
      for (const f of captionFiles) downloadText(f.text, f.name, "application/x-subrip");
    }
    setExportOpen(false); // the dock takes it from here
  };

  const sizeEstimate = formatSizeEstimate(estimateExportBytes(settings, span), locale);
  // The rung names: the source frame reads in the page's language, the fixed
  // sizes ("4K", "1080p") read as they are.
  const rungLabel = (r: { id: string; label: string }) => (r.id === "source" ? t("source") : r.label);
  // A loudness target by name, with its level beside it ("Social · −14 LUFS").
  const loudnessName = (id: LoudnessId) =>
    id === "off"
      ? t(`loudness.${id}`)
      : t("loudnessTarget", {
          name: t(`loudness.${id}`),
          lufs: String(CUT_LOUDNESS.targets[id]).replace("-", "−"),
        });
  // ProRes encodes at one rate per profile, so the quality scale and the
  // typed bitrate have nothing to act on.
  const prores = fixedRate(settings.codec);
  const resolution = resolveResolution(resolutions, choice.resolution);
  const rungIndex = Math.max(0, rungs.findIndex((r) => r.id === resolution.id));
  const qualityIndex = Math.max(0, QUALITY_RUNGS.findIndex((q) => q.id === choice.quality));
  const customRate = !prores && !!choice.bitrateMbps;
  // The format the choice adds up to, once the container has been fitted to
  // what the codec and audio need.
  const formatId = `${settings.container}-${settings.codec}`;

  return (
    <Dialog open onOpenChange={(o) => !o && setExportOpen(false)}>
      <DialogContent className="gap-0 p-0 sm:max-w-lg">
        <DialogHeader className="px-6 pt-6 pb-4">
          <DialogTitle className="text-xl">{t("title")}</DialogTitle>
        </DialogHeader>

        <DialogBody className="mx-0 my-0 flex flex-col gap-6 px-6 pt-1 pb-6">
          <div className="grid grid-cols-6 gap-1.5 max-sm:grid-cols-3" role="radiogroup" aria-label={t("presetGroup")}>
            {EXPORT_QUICK_PRESETS.map((p) => (
              <PresetTile
                key={p.id}
                checked={preset === p.id}
                label={t(`quickPresets.${p.id}.label`)}
                title={t(`quickPresets.${p.id}.detail`)}
                onClick={() => {
                  setMbpsText("");
                  setCustomPicked(false);
                  setChoice({ ...p.choice });
                }}
              />
            ))}
            <PresetTile
              checked={preset === null}
              label={t("custom")}
              title={t("customHint")}
              onClick={() => setCustomPicked(true)}
            />
          </div>

          <Scale
            label={t("resolution")}
            value={
              resolution.upscale
                ? t("sizeUpscaled", { width: settings.width, height: settings.height })
                : t("size", { width: settings.width, height: settings.height })
            }
            index={rungIndex}
            stops={rungs.map((r) => ({
              label: rungLabel(r),
              title: r.upscale
                ? t("sizeUpscaledFromSource", { width: r.width, height: r.height })
                : t("size", { width: r.width, height: r.height }),
            }))}
            onIndex={(i) => set({ resolution: rungs[i]!.id })}
          />

          {/* ProRes fixes its own bitrate, so the scale stays put and greys out. */}
          <Scale
            label={t("quality")}
            value={customRate ? t("customRateValue", { mbps: choice.bitrateMbps ?? 0, size: sizeEstimate }) : sizeEstimate}
            index={customRate ? null : qualityIndex}
            disabled={prores}
            stops={QUALITY_RUNGS.map((q) => ({ label: t(`qualities.${q.id}.label`), title: t(`qualities.${q.id}.detail`) }))}
            onIndex={(i) => {
              setMbpsText("");
              set({ quality: QUALITY_RUNGS[i]!.id, bitrateMbps: undefined });
            }}
          />

          <div className="flex flex-col gap-3">
            <Field label={t("fileName")}>
              <Input
                aria-label={t("fileName")}
                className="h-8 w-48 text-sm"
                value={name}
                placeholder={projectName}
                onChange={(e) => setName(e.target.value)}
              />
            </Field>
            {selection && (
              <Field label={t("range")}>
                <Select value={rangeMode} onValueChange={(v) => setRangeMode(v as "all" | "selection")}>
                  <SelectTrigger className="w-fit min-w-32" aria-label={t("range")}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent align="end">
                    <SelectItem value="all">{t("wholeVideo")}</SelectItem>
                    <SelectItem
                      value="selection"
                      title={t("selectionHint")}
                    >
                      {t("selectionRange", { start: formatTime(selection.start), end: formatTime(selection.end) })}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </Field>
            )}
            <Field label={t("frameRate")}>
              <Select
                value={String(choice.fps)}
                onValueChange={(v) => set({ fps: v === "source" ? "source" : Number(v) })}
              >
                <SelectTrigger className="w-fit min-w-32" aria-label={t("frameRate")}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent align="end">
                  <SelectItem value="source" title={t("sourceRateHint")}>
                    {probing
                      ? t("sourceReading")
                      : t("sourceRate", { fps: Number((sourceFps ?? DEFAULT_EXPORT_FPS).toFixed(3)) })}
                  </SelectItem>
                  {EXPORT_FRAME_RATES.map((f) => (
                    <SelectItem key={f} value={String(f)}>
                      {t("fps", { fps: f })}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field label={t("format")}>
              <Select
                value={formatId}
                onValueChange={(v) => {
                  const f = FORMATS.find((x) => x.id === v);
                  if (!f) return;
                  if (fixedRate(f.codec)) setMbpsText("");
                  set({
                    container: f.container,
                    codec: f.codec,
                    sourceCodec: false,
                    ...(fixedRate(f.codec) ? { bitrateMbps: undefined } : {}),
                    // MP4 cannot carry PCM either; picking it turns the audio to AAC.
                    ...(f.container === "mp4" && choice.audioCodec === "pcm" ? { audioCodec: "aac" } : {}),
                  });
                }}
              >
                <SelectTrigger className="w-fit min-w-32" aria-label={t("format")}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent align="end">
                  {FORMATS.map((f) => (
                    <SelectItem key={f.id} value={f.id} title={t(`codecs.${f.codec}`)} disabled={hdr && f.codec === "h264"}>
                      {f.label}
                      {hdr && f.codec === "h264" ? ` · ${t("eightBit")}` : ""}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field label={t("color")}>
              <Select value={colorSpace} onValueChange={(v) => setColorSpace(v as OutputSpace)}>
                <SelectTrigger className="w-fit min-w-32" aria-label={t("color")}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent align="end">
                  {OUTPUT_SPACES.map((o) => (
                    <SelectItem key={o.id} value={o.id}>
                      {t(`colorSpaces.${o.id}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field label={t("audio")}>
              <Select
                value={choice.audioCodec}
                onValueChange={(v) =>
                  set({
                    audioCodec: v as ExportChoice["audioCodec"],
                    ...(v === "pcm" ? { container: "mov" } : {}),
                  })
                }
              >
                <SelectTrigger className="w-32" aria-label={t("audio")}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent align="end">
                  {EXPORT_AUDIO.map((a) => (
                    <SelectItem key={a.id} value={a.id} title={t(`audioCodecs.${a.id}`)}>
                      {a.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field
              label={t("loudnessLabel")}
              hint={
                loudness === "off"
                  ? undefined
                  : t("loudnessHint", { ceiling: String(CUT_LOUDNESS.truePeakCeiling).replace("-", "−") })
              }
            >
              <Select value={loudness} onValueChange={(v) => setLoudness(v as LoudnessId)}>
                <SelectTrigger className="w-fit min-w-32" aria-label={t("loudnessLabel")}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent align="end">
                  {LOUDNESS_CHOICES.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {loudnessName(c.id)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
          </div>

          <Collapsible open={moreOpen} onOpenChange={setMoreOpen} className="flex flex-col gap-3">
            <CollapsibleTrigger className="flex items-center justify-between text-sm text-muted-foreground transition-colors hover:text-foreground">
              {t("moreSettings")}
              <ChevronDown className={cn("size-4 transition-transform", moreOpen && "rotate-180")} />
            </CollapsibleTrigger>
            <CollapsibleContent className="flex flex-col gap-3">
              <Field
                label={t("customBitrate")}
                hint={t("customBitrateHint")}
              >
                <label
                  className={cn(
                    "flex h-8 items-center gap-1 rounded-lg border border-input pr-2.5 pl-2.5",
                    prores && "cursor-not-allowed opacity-40"
                  )}
                >
                  <Input
                    type="number"
                    inputMode="decimal"
                    min={0.5}
                    max={MAX_MBPS}
                    step={0.5}
                    placeholder={t("auto")}
                    aria-label={t("bitrateLabel")}
                    disabled={prores}
                    className="h-6 w-16 border-0 bg-transparent px-0 text-sm shadow-none [appearance:textfield] focus-visible:ring-0 disabled:cursor-not-allowed [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
                    value={mbpsText}
                    onChange={(e) => {
                      setMbpsText(e.target.value);
                      const v = Math.min(Number(e.target.value), MAX_MBPS);
                      set({ bitrateMbps: v > 0 ? v : undefined });
                    }}
                  />
                  <span className="text-xs text-muted-foreground">{t("mbps")}</span>
                </label>
              </Field>
              {canStem && (
                <Field
                  label={t("stems")}
                  hint={t("stemsHint")}
                >
                  <Switch
                    aria-label={t("exportStems")}
                    checked={withStems}
                    onCheckedChange={(v) => setWithStems(v === true)}
                  />
                </Field>
              )}
              {captionFiles.length > 0 && (
                <Field
                  label={t("captionsFile")}
                  hint={t("captionsFileHint")}
                >
                  <Switch
                    aria-label={t("saveCaptionsFile")}
                    checked={withCaptions}
                    onCheckedChange={(v) => setWithCaptions(v === true)}
                  />
                </Field>
              )}
            </CollapsibleContent>
          </Collapsible>

          {!inTab && (
            <p className="text-xs leading-relaxed text-muted-foreground">
              {t("cloudRender", { kind: prores ? "prores" : hdr ? "hdr" : "other" })}
            </p>
          )}
        </DialogBody>

        <DialogFooter className="mx-0 mb-0 flex-col gap-3 rounded-b-xl bg-muted/40 px-6 py-5 sm:flex-col">
          <div className="flex items-center justify-between gap-3 text-sm text-muted-foreground">
            <span className="truncate">
              {t("size", { width: settings.width, height: settings.height })} · {t("fps", { fps: settings.fps })} ·{" "}
              {FORMATS.find((f) => f.id === formatId)?.label ?? formatId} · {settings.audioCodec.toUpperCase()}
              {hdr ? ` · ${t(`colorSpaces.${colorSpace}`)}` : ""}
              {range ? ` · ${formatTime(span)}` : ""}
              {settings.loudness !== undefined ? ` · ${t("lufs", { lufs: String(settings.loudness).replace("-", "−") })}` : ""}
              {stems ? ` · ${t("stemsTag")}` : ""}
            </span>
            <span className="shrink-0 tabular-nums">{sizeEstimate}</span>
          </div>
          <Button className="h-11 w-full text-base" onClick={run} disabled={waiting}>
            {waiting ? t("reading") : t("exportVideo")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

/** The most a typed bitrate can ask for. */
const MAX_MBPS = 200;

// One preset in the row across the top: its name, with what it stands for
// in the tooltip. "Custom" is the tile that lights when the options match no
// preset, and the one a click lands on to start from the options as they are.
function PresetTile({
  checked,
  label,
  title,
  onClick,
}: {
  checked: boolean;
  label: string;
  title?: string;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      role="radio"
      aria-checked={checked}
      title={title}
      className={cn(
        "flex h-8 min-w-0 items-center justify-center rounded-lg border px-1.5 text-xs font-medium whitespace-nowrap transition-colors",
        checked
          ? "border-primary bg-primary/10 text-foreground"
          : "border-transparent bg-muted/60 text-muted-foreground hover:bg-muted hover:text-foreground"
      )}
      onClick={onClick}
    >
      <span className="truncate">{label}</span>
    </button>
  );
}

/**
 * A slider over a few named stops: the label on the left, what the pick
 * adds up to on the right, and the stop names under the track, each one a
 * click away. `index` null means the value sits off the scale (a typed
 * bitrate), so no stop lights.
 */
function Scale({
  label,
  value,
  index,
  stops,
  disabled,
  onIndex,
}: {
  label: string;
  value: string;
  index: number | null;
  stops: { label: string; title?: string }[];
  disabled?: boolean;
  onIndex: (i: number) => void;
}) {
  const t = useTranslations("editor.exportDialog");
  const last = Math.max(0, stops.length - 1);
  return (
    <div className={cn("flex flex-col gap-1", disabled && "opacity-40")}>
      <div className="flex items-center justify-between gap-3">
        <span className="text-sm">{label}</span>
        <span className="truncate text-sm tabular-nums text-muted-foreground">{value}</span>
      </div>
      <Slider
        aria-label={label}
        min={0}
        max={last}
        step={1}
        disabled={disabled || stops.length < 2}
        value={index ?? 0}
        onValueChange={(v) => onIndex(Array.isArray(v) ? v[0]! : v)}
      />
      <div className="relative h-4" role="radiogroup" aria-label={t("scalePresets", { label })}>
        {stops.map((s, i) => (
          <button
            key={s.label}
            type="button"
            role="radio"
            aria-checked={index === i}
            title={s.title}
            disabled={disabled}
            className={cn(
              "absolute top-0 text-xs whitespace-nowrap transition-colors",
              i === 0 ? "left-0" : i === last ? "right-0" : "-translate-x-1/2",
              index === i ? "text-foreground" : "text-muted-foreground hover:text-foreground"
            )}
            style={i === 0 || i === last ? undefined : { left: `${(i / last) * 100}%` }}
            onClick={() => onIndex(i)}
          >
            {s.label}
          </button>
        ))}
      </div>
    </div>
  );
}

// A labeled control on one line: the name on the left, the menu on the
// right, and an explanation under it when the control needs one.
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div className="flex flex-col gap-1">
      <div className="flex items-center justify-between gap-3">
        <span className="text-sm">{label}</span>
        {children}
      </div>
      {hint && <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p>}
    </div>
  );
}