freezmo/components/ProvidersSection.tsx
Martin Dvorak 84a94581dc Key fields: keep the browser's password UI away, fix the keyboard layout
"Trying to use a different provider on the web app glitches out completely" -
an iPhone photo of the first-run gate with iOS's saved-password sheet laid
over it ("password for proxmox...") and the provider field stuck under the
keyboard.

- The key fields (gate, Settings, provider rows) were type=password with
  autocomplete=off, which iOS/Safari and 1Password/LastPass read as a login.
  They now carry autoComplete="new-password", data-form-type="other",
  data-lpignore="true", autoCorrect/autoCapitalize=off and inputMode=text:
  the mask stays, the password overlay goes. The custom base URL gets
  inputMode=url and the same hints.
- The gate's keyboard handling scrolled to the Continue button instead of the
  field being edited, so with the provider rows open the keyboard covered the
  input and the locked wrapper could not be scrolled to it. The wrapper is
  user-scrollable again, alignment anchors on the focused element (Continue
  is the fallback), and the corner controls hide while the keyboard is up
  rather than landing on the card.

providers-test drives a fake visualViewport (340px, installed before mount)
and pins the three layout contracts plus the hardening attributes. All 16
suites green, contrast clean. Version 0.7.2, SW v94.
2026-10-16 10:12:20 +00:00

253 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useState } from "react";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import { localeHeader } from "@/lib/i18n";
import { PROVIDERS } from "@/lib/providers";
import {
clearProviderKey,
modelsFor,
providerHeaders,
saveProviderKey,
setCustomBaseUrl,
setGeneration,
setProviderModels,
useProviders,
} from "@/lib/providers-client";
import { cn } from "@/lib/utils";
/**
* Settings → Providers: bring-your-own keys for the cloud model providers.
*
* Keys live in this browser only — never on the server, never in a backup or
* the sync payload — and travel with each model call so the self-hosted app
* can reach the provider on the user's behalf. A key can also take over study
* generation (decks, homework, grading), and every enabled provider's models
* show up in the chat picker.
*/
export function ProvidersSection() {
const { t } = useI18n();
const state = useProviders();
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [busy, setBusy] = useState<string | null>(null);
const [status, setStatus] = useState<Record<string, string>>({});
const refresh = async (id: string) => {
setBusy(id);
try {
const response = await fetch("/api/providers", { headers: { ...providerHeaders(id), ...localeHeader() } });
const body = (await response.json().catch(() => null)) as { models?: string[]; error?: string } | null;
if (!response.ok || !body?.models) {
setStatus((previous) => ({ ...previous, [id]: body?.error ?? t("providers.testFailed") }));
return;
}
const models = body.models;
setProviderModels(id, models);
setStatus((previous) => ({
...previous,
[id]: t("providers.modelCount", { n: String(models.length) }),
}));
} catch {
setStatus((previous) => ({ ...previous, [id]: t("providers.testFailed") }));
} finally {
setBusy(null);
}
};
const save = (id: string) => {
const key = (drafts[id] ?? "").trim();
if (!key) return;
saveProviderKey(id, key);
setDrafts((previous) => ({ ...previous, [id]: "" }));
haptic("toggle");
void refresh(id);
};
const enabled = PROVIDERS.filter((provider) => state.keys[provider.id]);
const generation = state.generation;
return (
<section className="mb-4 space-y-3 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-3">
<div>
<h3 className="text-sm font-semibold text-[var(--text)]">{t("providers.title")}</h3>
<p className="mt-0.5 text-[11.5px] leading-snug text-[var(--text-subtle)]">{t("providers.note")}</p>
</div>
{PROVIDERS.map((provider) => {
const saved = Boolean(state.keys[provider.id]);
const listed = state.models[provider.id] ?? [];
return (
<div key={provider.id} className="space-y-1.5 border-t border-[var(--hairline-soft)] pt-2.5">
<div className="flex items-center justify-between gap-2">
<span className="text-[13px] font-semibold text-[var(--text)]">{provider.label}</span>
{provider.docs ? (
<a
href={provider.docs}
target="_blank"
rel="noreferrer"
className="text-[11.5px] font-medium text-accent-600 underline decoration-dotted dark:text-accent-300"
>
{t("providers.getKey")}
</a>
) : null}
</div>
{provider.id === "custom" ? (
<input
value={state.customBaseUrl}
onChange={(event) => setCustomBaseUrl(event.target.value)}
placeholder={t("providers.baseUrlPlaceholder")}
aria-label={t("providers.baseUrl")}
autoComplete="off"
autoCorrect="off"
spellCheck={false}
inputMode="url"
data-form-type="other"
className="w-full rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2 text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-subtle)] focus:border-accent-400"
/>
) : null}
<div className="flex items-center gap-2">
<input
type="password"
value={drafts[provider.id] ?? ""}
onChange={(event) => setDrafts((previous) => ({ ...previous, [provider.id]: event.target.value }))}
onKeyDown={(event) => {
if (event.key === "Enter") save(provider.id);
}}
placeholder={saved ? t("providers.keySaved") : provider.keyHint}
aria-label={`${provider.label} ${t("providers.key")}`}
/* See the gate: an API key must not raise the browser's
saved-password UI ("new-password" + the data hints). */
autoComplete="new-password"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
inputMode="text"
enterKeyHint="done"
data-form-type="other"
data-lpignore="true"
className="min-w-0 flex-1 rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2 text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-subtle)] focus:border-accent-400"
/>
<button
type="button"
onClick={() => save(provider.id)}
disabled={!(drafts[provider.id] ?? "").trim()}
className="btn-secondary h-9 shrink-0 px-3 text-[12.5px] disabled:opacity-50"
>
{t("providers.saveKey")}
</button>
{saved ? (
<>
<button
type="button"
onClick={() => void refresh(provider.id)}
disabled={busy === provider.id}
aria-label={t("providers.test")}
title={t("providers.test")}
className="grid size-9 shrink-0 place-items-center rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] text-[var(--text-muted)] transition hover:text-[var(--text)] disabled:opacity-50"
>
↻
</button>
<button
type="button"
onClick={() => {
clearProviderKey(provider.id);
if (generation?.provider === provider.id) setGeneration(null);
haptic("tap");
}}
aria-label={t("providers.remove")}
title={t("providers.remove")}
className="grid size-9 shrink-0 place-items-center rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] text-[var(--text-muted)] transition hover:text-rose-600 disabled:opacity-50"
>
×
</button>
</>
) : null}
</div>
{status[provider.id] ?? (saved && listed.length > 0 ? t("providers.modelCount", { n: String(listed.length) }) : null) ? (
<p
className={cn(
"text-[11.5px] leading-snug",
status[provider.id] && !status[provider.id].includes(String(listed.length))
? "text-rose-600 dark:text-rose-300"
: "text-[var(--text-subtle)]",
)}
>
{status[provider.id] ?? t("providers.modelCount", { n: String(listed.length) })}
</p>
) : null}
</div>
);
})}
{enabled.length > 0 ? (
<div className="space-y-2 border-t border-[var(--hairline-soft)] pt-2.5">
<span className="block text-[13px] font-semibold text-[var(--text)]">{t("providers.generation")}</span>
<p className="text-[11.5px] leading-snug text-[var(--text-subtle)]">{t("providers.generationNote")}</p>
<div className="flex flex-wrap items-center gap-2">
<select
aria-label={t("providers.generation")}
value={generation?.provider ?? ""}
onChange={(event) => {
const id = event.target.value;
if (!id) {
setGeneration(null);
return;
}
const models = modelsFor(state, id);
setGeneration({ provider: id, textModel: models[0] ?? "", visionModel: models[0] ?? "" });
haptic("toggle");
}}
className="min-w-0 rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2 text-[12.5px] text-[var(--text)] outline-none"
>
<option value="">{t("providers.serverDefault")}</option>
{enabled.map((provider) => (
<option key={provider.id} value={provider.id}>
{provider.label}
</option>
))}
</select>
{generation ? (
<>
<select
aria-label={t("providers.textModel")}
value={generation.textModel}
onChange={(event) =>
setGeneration({ ...generation, textModel: event.target.value, visionModel: generation.visionModel || event.target.value })
}
className="min-w-0 max-w-[46%] rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2 text-[12.5px] text-[var(--text)] outline-none"
>
{(modelsFor(state, generation.provider).length > 0 ? modelsFor(state, generation.provider) : [generation.textModel]).map(
(model) => (
<option key={model} value={model}>
{model}
</option>
),
)}
</select>
<select
aria-label={t("providers.visionModel")}
value={generation.visionModel}
onChange={(event) => setGeneration({ ...generation, visionModel: event.target.value })}
className="min-w-0 max-w-[46%] rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2 text-[12.5px] text-[var(--text)] outline-none"
>
{(modelsFor(state, generation.provider).length > 0 ? modelsFor(state, generation.provider) : [generation.visionModel]).map(
(model) => (
<option key={model} value={model}>
{model}
</option>
),
)}
</select>
</>
) : null}
</div>
</div>
) : null}
</section>
);
}