Add.tsx

31.7 KB · raw

1import { createSignal, createMemo, createEffect, For, Show, onMount, onCleanup } from "solid-js";2import type { VaultEntry } from "../../shared/types";3import { sendMessage } from "../App";4import { parseOtpauthURI } from "../../crypto/totp";5import { GeneratorDrawer } from "../components/GeneratorDrawer";67interface AddProps {8  entry?: VaultEntry;9  entries?: VaultEntry[];10  autoOpenGenerator?: boolean;11  onBack: () => void;12  onSave: (entry?: VaultEntry) => void | Promise<void>;13}1415export function AddView(props: AddProps) {16  const [title, setTitle] = createSignal(props.entry?.title ?? "");17  const [username, setUsername] = createSignal(props.entry?.username ?? "");18  const [password, setPassword] = createSignal(props.entry?.password ?? "");19  const [url, setUrl] = createSignal(props.entry?.url ?? "");20  const [totp, setTotp] = createSignal(props.entry?.totp ?? "");21  const [notes, setNotes] = createSignal(props.entry?.notes ?? "");22  const [saving, setSaving] = createSignal(false);23  const [error, setError] = createSignal("");24  const [passwordStrength, setPasswordStrength] = createSignal<number | null>(null);25  const [zxcvbnFn, setZxcvbnFn] = createSignal<((pwd: string) => { score: number }) | null>(null);26  const [tags, setTags] = createSignal<string[]>(props.entry?.tags ?? []);27  const [tagInput, setTagInput] = createSignal("");28  const [showTagSuggestions, setShowTagSuggestions] = createSignal(false);29  const [showGenerator, setShowGenerator] = createSignal(props.autoOpenGenerator ?? false);30  const [showPassword, setShowPassword] = createSignal(false);31  const [showTotp, setShowTotp] = createSignal(!!(props.entry?.totp));32  const [showNotes, setShowNotes] = createSignal(!!(props.entry?.notes));33  const [email, setEmail] = createSignal((props.entry as VaultEntry & { email?: string })?.email ?? "");34  const [activeIdentityField, setActiveIdentityField] = createSignal<"username" | "email" | null>(null);35  const [currentTabUrl, setCurrentTabUrl] = createSignal("");3637  // Mutable refs for keyboard navigation between inputs and suggestion lists.38  // Not signals — focus state doesn't need to be reactive.39  let usernameInputEl: HTMLInputElement | undefined;40  let emailInputEl: HTMLInputElement | undefined;41  let usernameSuggestEl: HTMLDivElement | undefined;42  let emailSuggestEl: HTMLDivElement | undefined;43  let suppressIdentityOpen = false;4445  function openIdentityField(field: "username" | "email") {46    if (suppressIdentityOpen) { suppressIdentityOpen = false; return; }47    setActiveIdentityField(field);48  }4950  const allIdentities = createMemo(() => {51    const emailMap = new Map<string, number>();52    const usernameMap = new Map<string, number>();53    for (const entry of props.entries ?? []) {54      const uname = entry.username?.trim() ?? "";55      const em = entry.email?.trim() ?? "";56      if (uname) {57        if (uname.includes("@")) emailMap.set(uname, (emailMap.get(uname) ?? 0) + 1);58        else usernameMap.set(uname, (usernameMap.get(uname) ?? 0) + 1);59      }60      if (em) emailMap.set(em, (emailMap.get(em) ?? 0) + 1);61    }62    const result: Array<{ value: string; count: number; type: "email" | "username" }> = [];63    const seen = new Set<string>();64    for (const v of new Set([...emailMap.keys(), ...usernameMap.keys()])) {65      if (seen.has(v)) continue;66      seen.add(v);67      const ec = emailMap.get(v) ?? 0;68      const uc = usernameMap.get(v) ?? 0;69      result.push({ value: v, count: Math.max(ec, uc), type: ec >= uc ? "email" : "username" });70    }71    return result.sort((a, b) => b.count - a.count);72  });7374  const identitySuggestions = createMemo(() => {75    const field = activeIdentityField();76    if (!field) return [];77    const input = (field === "username" ? username() : email()).toLowerCase();78    return allIdentities()79      .filter(s => s.type === field && (!input || s.value.toLowerCase().includes(input)))80      .slice(0, 8);81  });8283  const isCardEntry = () => props.entry?.type === "card";84  const [selectedType, setSelectedType] = createSignal<"login" | "card">(85    isCardEntry() ? "card" : "login"86  );8788  // Card signals89  const [cardNickname, setCardNickname] = createSignal(props.entry?.cardNickname ?? "");90  const [cardholderName, setCardholderName] = createSignal(props.entry?.cardholderName ?? "");91  const [cardNumber, setCardNumber] = createSignal(props.entry?.cardNumber ?? "");92  const [expMonth, setExpMonth] = createSignal(props.entry?.expMonth ?? "");93  const [expYear, setExpYear] = createSignal(props.entry?.expYear ?? "");94  const [cvc, setCvc] = createSignal(props.entry?.cvc ?? "");95  const [showCvc, setShowCvc] = createSignal(false);96  const [cardNumberFocused, setCardNumberFocused] = createSignal(false);97  function getCardNetwork(num: string): string {98    const n = num.replace(/\s/g, '');99    if (/^4/.test(n)) return 'Visa';100    if (/^5[1-5]|^2[2-7]/.test(n)) return 'Mastercard';101    if (/^3[47]/.test(n)) return 'Amex';102    if (/^6(?:011|5)/.test(n)) return 'Discover';103    return '';104  }105106  function formatCardNumberDisplay(raw: string, focused: boolean): string {107    const n = raw.replace(/\s/g, '');108    if (!focused && n.length >= 4) return '•••• •••• •••• ' + n.slice(-4);109    if (/^3[47]/.test(n)) return n.replace(/(\d{4})(\d{1,6})?(\d{1,5})?/, (_, a, b, c) => [a, b, c].filter(Boolean).join(' '));110    return n.replace(/(\d{4})(?=\d)/g, '$1 ').trim();111  }112113  const canSave = () => {114    if (!title().trim()) return false;115    if (selectedType() === "card" && (!cardholderName().trim() || !cardNumber().trim())) return false;116    return true;117  };118119  const allTags = createMemo(() => {120    const tagSet = new Set<string>();121    for (const entry of props.entries ?? []) {122      for (const tag of entry.tags ?? []) tagSet.add(tag);123    }124    return Array.from(tagSet).sort();125  });126127  const tagSuggestions = createMemo(() => {128    const input = tagInput().toLowerCase().trim();129    if (!input) return [];130    return allTags().filter(t =>131      t.toLowerCase().includes(input) && !tags().includes(t)132    ).slice(0, 5);133  });134135  function addTag(tag: string) {136    const n = tag.toLowerCase().trim();137    if (!n || n.length > 32 || tags().includes(n) || tags().length >= 10) return;138    setTags([...tags(), n]);139  }140141  function removeTag(tag: string) {142    setTags(tags().filter(t => t !== tag));143  }144145  function handleTagKeyDown(e: KeyboardEvent) {146    if (e.key === "Enter" || e.key === ",") {147      e.preventDefault();148      if (tagInput()) { addTag(tagInput()); setTagInput(""); setShowTagSuggestions(false); }149    } else if (e.key === "Backspace" && !tagInput() && tags().length > 0) {150      removeTag(tags()[tags().length - 1]);151    }152  }153154  // Strength check155  createEffect(async () => {156    const pwd = password();157    if (pwd.length < 4) { setPasswordStrength(null); return; }158    try {159      if (!zxcvbnFn()) {160        // Replaces the unmaintained `zxcvbn` package (LV-8; see Lock.tsx).161        const [{ zxcvbn, zxcvbnOptions }, common, en] = await Promise.all([162          import("@zxcvbn-ts/core"),163          import("@zxcvbn-ts/language-common"),164          import("@zxcvbn-ts/language-en"),165        ]);166        zxcvbnOptions.setOptions({167          translations: en.translations,168          graphs: common.adjacencyGraphs,169          dictionary: { ...common.dictionary, ...en.dictionary },170        });171        setZxcvbnFn(() => (pwd: string) => zxcvbn(pwd));172      }173      const fn = zxcvbnFn();174      if (fn) setPasswordStrength(fn(pwd).score);175    } catch {176      setPasswordStrength(pwd.length >= 16 ? 3 : pwd.length >= 12 ? 2 : 1);177    }178  });179180  onMount(() => {181    const el = document.querySelector(".peach-new-title-input") as HTMLInputElement | null;182    if (el) el.focus();183    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {184      const tabUrl = tabs[0]?.url;185      if (tabUrl && tabUrl.startsWith("http")) setCurrentTabUrl(tabUrl);186    });187    // Keep the vault alive while the form is open — the auto-lock alarm fires on188    // a timer and doesn't know the user is actively filling in a new entry.189    const keepAlive = setInterval(() => {190      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});191    }, 30_000);192    onCleanup(() => clearInterval(keepAlive));193  });194195  function getNormalizedTotp(): string | undefined {196    const value = totp().trim();197    if (!value) return undefined;198    if (value.startsWith("otpauth://")) {199      const parsed = parseOtpauthURI(value);200      return parsed?.secret ?? value;201    }202    return value;203  }204205  async function handleSave() {206    if (!canSave()) {207      setError(208        selectedType() === "card"209          ? "cardholder name and card number are required"210          : "title is required"211      );212      return;213    }214215    setSaving(true);216    setError("");217218    const payload: Record<string, unknown> = {219      type: selectedType(),220      title: title().trim(),221      notes: notes().trim() || undefined,222      tags: tags().length > 0 ? tags() : undefined,223    };224225    if (selectedType() === "login") {226      payload.username = username().trim();227      payload.email = email().trim() || undefined;228      payload.password = password();229      payload.url = url().trim();230      payload.totp = getNormalizedTotp();231    }232233    if (selectedType() === "card") {234      const raw = cardNumber().replace(/\s/g, '');235      payload.cardholderName = cardholderName().trim();236      payload.cardNumber = raw;237      payload.expMonth = expMonth().trim();238      payload.expYear = expYear().trim();239      payload.cvc = cvc().trim();240      payload.cardNickname = cardNickname().trim() || undefined;241      const n = raw;242      payload.network = /^4/.test(n) ? 'visa' : /^5[1-5]|^2[2-7]/.test(n) ? 'mastercard' : /^3[47]/.test(n) ? 'amex' : /^6(?:011|5)/.test(n) ? 'discover' : 'unknown';243      payload.last4 = raw.slice(-4);244    }245246    if (props.entry) {247      const res = await sendMessage({ type: "UPDATE_ENTRY", payload: { id: props.entry.id, patch: payload } });248      const result = res as { ok: boolean; error?: string };249      if (!result.ok) { setError(result.error ?? "could not update entry"); setSaving(false); return; }250      await props.onSave({ ...props.entry, ...payload } as VaultEntry);251      return;252    }253254    const res = await sendMessage({ type: "ADD_ENTRY", payload });255    const result = res as { ok: boolean; data?: VaultEntry; error?: string };256    if (!result.ok) {257      // Fixed strings only — raw background errors must not reach the UI.258      if (result.error === "vault_locked") {259        setError("vault is locked — tap the lock icon to re-enter your master password");260      } else {261        // Fixed strings only — raw background errors must not reach the UI.262        const SAFE_ERRORS = new Set([263          "title is required",264          "cardholder name and card number are required",265          "invalid passkey credential",266          "pro_required",267        ]);268        setError(269          result.error !== undefined && SAFE_ERRORS.has(result.error)270            ? result.error271            : "could not save entry",272        );273      }274      setSaving(false);275      return;276    }277    await props.onSave(result.data);278  }279280  const strengthLabel = () => {281    const s = passwordStrength();282    if (s === null) return null;283    return ["weak", "weak", "fair", "good", "strong"][s] as string;284  };285286  return (287    <div class="peach-overlay-view ov-enter-right" style="display:flex">288      <div class="peach-overlay-header">289        <button290          class="peach-btn peach-btn--ghost peach-btn--sm peach-overlay-action"291          onClick={props.onBack}292        >293          cancel294        </button>295        <span class="peach-overlay-title">296          {props.entry ? "edit entry" : "new entry"}297        </span>298        <button299          class="peach-btn peach-btn--accent peach-btn--sm peach-overlay-action"300          onClick={() => void handleSave()}301          disabled={saving() || !canSave()}302        >303          {saving() ? "saving…" : props.entry ? "save" : "create"}304        </button>305      </div>306307      {/* ── Body — mirrors Entry.tsx field-card structure ── */}308      <div class="peach-entry-body peach-entry-body--new">309310        {/* Type toggle */}311        <Show when={!props.entry}>312          <div class="peach-new-type-row">313            <button314              class={`peach-new-type-btn ${selectedType() === "login" ? "is-active" : ""}`}315              onClick={() => setSelectedType("login")}316            >login</button>317            <button318              class={`peach-new-type-btn ${selectedType() === "card" ? "is-active" : ""}`}319              onClick={() => setSelectedType("card")}320            >card</button>321          </div>322        </Show>323324        {/* Title */}325        <div class="peach-new-title-wrap">326          <input327            class="peach-new-title-input"328            placeholder="entry name"329            autocomplete="off"330            value={title()}331            onInput={(e) => setTitle((e.currentTarget as HTMLInputElement).value)}332            onKeyDown={(e) => { if (e.key === "Enter") void handleSave(); }}333          />334        </div>335336        {/* ── Login fields ── */}337        <Show when={selectedType() === "login"}>338          <div class="peach-domain">339            <div class="peach-domain-edit-row">340              <input341                class="peach-domain-value peach-domain-value--edit"342                placeholder="domain.com"343                autocomplete="off"344                value={url()}345                onInput={(e) => setUrl((e.currentTarget as HTMLInputElement).value)}346              />347              <Show when={currentTabUrl()}>348                <button349                  class="peach-domain-url-btn"350                  type="button"351                  onClick={() => setUrl(currentTabUrl())}352                  title="Insert current page URL"353                >354                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">355                    <path d="M4.5 7.5a3 3 0 0 0 4.243 0L10.5 5.75a3 3 0 0 0-4.243-4.243L5.5 2.26" />356                    <path d="M7.5 4.5a3 3 0 0 0-4.243 0L1.5 6.25a3 3 0 0 0 4.243 4.243L6.5 9.74" />357                  </svg>358                </button>359              </Show>360            </div>361          </div>362363          <section class="peach-fields">364            {/* Username */}365            <div class="peach-field-card">366              <span class="peach-label">username</span>367              <div class="peach-field-value-row">368                <input369                  ref={(el) => (usernameInputEl = el)}370                  class="peach-field-value peach-field-value--edit"371                  placeholder="johndoe"372                  autocomplete="off"373                  value={username()}374                  onInput={(e) => setUsername((e.currentTarget as HTMLInputElement).value)}375                  onFocus={() => openIdentityField("username")}376                  onBlur={(e) => {377                    if (usernameSuggestEl?.contains(e.relatedTarget as Node)) return;378                    setTimeout(() => { if (activeIdentityField() === "username") setActiveIdentityField(null); }, 150);379                  }}380                  onKeyDown={(e) => {381                    if (activeIdentityField() !== "username") return;382                    if (e.key === "ArrowDown") {383                      e.preventDefault();384                      usernameSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();385                    } else if (e.key === "Escape") {386                      e.preventDefault();387                      setActiveIdentityField(null);388                    }389                  }}390                />391              </div>392              <Show when={activeIdentityField() === "username" && identitySuggestions().length > 0}>393                <IdentitySuggestList394                  listRef={(el) => (usernameSuggestEl = el)}395                  inputRef={() => usernameInputEl}396                  suggestions={identitySuggestions()}397                  onPick={(v) => { setUsername(v); setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}398                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}399                />400              </Show>401            </div>402403            {/* Email */}404            <div class="peach-field-card">405              <span class="peach-label">email</span>406              <div class="peach-field-value-row">407                <input408                  ref={(el) => (emailInputEl = el)}409                  class="peach-field-value peach-field-value--edit"410                  type="email"411                  placeholder="[email protected]"412                  autocomplete="off"413                  value={email()}414                  onInput={(e) => setEmail((e.currentTarget as HTMLInputElement).value)}415                  onFocus={() => openIdentityField("email")}416                  onBlur={(e) => {417                    if (emailSuggestEl?.contains(e.relatedTarget as Node)) return;418                    setTimeout(() => { if (activeIdentityField() === "email") setActiveIdentityField(null); }, 150);419                  }}420                  onKeyDown={(e) => {421                    if (activeIdentityField() !== "email") return;422                    if (e.key === "ArrowDown") {423                      e.preventDefault();424                      emailSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();425                    } else if (e.key === "Escape") {426                      e.preventDefault();427                      setActiveIdentityField(null);428                    }429                  }}430                />431              </div>432              <Show when={activeIdentityField() === "email" && identitySuggestions().length > 0}>433                <IdentitySuggestList434                  listRef={(el) => (emailSuggestEl = el)}435                  inputRef={() => emailInputEl}436                  suggestions={identitySuggestions()}437                  onPick={(v) => { setEmail(v); setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}438                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}439                />440              </Show>441            </div>442443            {/* Password */}444            <div class="peach-field-card">445              <span class="peach-label">password</span>446              <Show when={!showGenerator()}>447                <div class="peach-password-edit-row">448                  <input449                    class="peach-field-value peach-field-value--edit"450                    type={showPassword() ? "text" : "password"}451                    placeholder="password"452                    autocomplete="new-password"453                    value={password()}454                    onInput={(e) => setPassword((e.currentTarget as HTMLInputElement).value)}455                  />456                  <button457                    class="peach-inline-action peach-password-toggle-btn"458                    type="button"459                    onClick={() => setShowPassword(!showPassword())}460                    aria-label={showPassword() ? "Hide password" : "Show password"}461                  >462                    <Show463                      when={showPassword()}464                      fallback={465                        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">466                          <path d="M1 5C1 5 2.8 1 7 1C11.2 1 13 5 13 5C13 5 11.2 9 7 9C2.8 9 1 5 1 5Z" />467                          <circle cx="7" cy="5" r="1.75" />468                        </svg>469                      }470                    >471                      <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">472                        <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />473                        <path d="M3.5 5.5L2.5 7.5" />474                        <path d="M7 6.5V8.5" />475                        <path d="M10.5 5.5L11.5 7.5" />476                      </svg>477                    </Show>478                  </button>479                </div>480              </Show>481482              {/* Strength */}483              <Show when={strengthLabel() !== null}>484                <div class="peach-strength-hairline">485                  <div class="peach-strength-hairline-track">486                    <div487                      class="peach-strength-hairline-fill"488                      style={{489                        width: ["25%","40%","60%","80%","100%"][passwordStrength()!],490                        background: ["rgba(220,80,60,0.65)","rgba(220,80,60,0.65)","rgba(200,140,60,0.6)","rgba(180,162,100,0.55)","rgba(150,175,110,0.6)"][passwordStrength()!],491                      }}492                    />493                  </div>494                  <span class="peach-strength-label">{strengthLabel()}</span>495                </div>496              </Show>497498              {/* Generator toggle */}499              <button500                class="peach-generate-toggle-link"501                type="button"502                onClick={() => { setShowGenerator(!showGenerator()); }}503              >504                {showGenerator() ? "☰ hide generator" : "⚙ generate"}505              </button>506              <GeneratorDrawer507                compact508                open={showGenerator()}509                onChange={(pw) => setPassword(pw)}510                onUse={(pw) => { setPassword(pw); setShowGenerator(false); }}511              />512            </div>513514            {/* 2FA — optional */}515            <Show when={showTotp() || totp()}>516              <div class="peach-field-card">517                <span class="peach-label">2fa secret</span>518                <div class="peach-field-value-row">519                  <input520                    class="peach-field-value peach-field-value--edit"521                    placeholder="BASE32 or otpauth:// URI"522                    autocomplete="off"523                    value={totp()}524                    onInput={(e) => setTotp((e.currentTarget as HTMLInputElement).value)}525                  />526                </div>527              </div>528            </Show>529          </section>530        </Show>531532        {/* ── Card fields ── */}533        <Show when={selectedType() === "card"}>534          <section class="peach-fields">535            {/* Nickname */}536            <div class="peach-field-card">537              <span class="peach-label">nickname</span>538              <div class="peach-field-value-row">539                <input class="peach-field-value peach-field-value--edit" placeholder="Personal Visa"540                  autocomplete="off" value={cardNickname()}541                  onInput={(e) => setCardNickname((e.currentTarget as HTMLInputElement).value)} />542              </div>543            </div>544            {/* Cardholder name */}545            <div class="peach-field-card">546              <span class="peach-label">cardholder name</span>547              <div class="peach-field-value-row">548                <input class="peach-field-value peach-field-value--edit" placeholder="Jane Smith"549                  autocomplete="cc-name" value={cardholderName()}550                  onInput={(e) => setCardholderName((e.currentTarget as HTMLInputElement).value)} />551              </div>552            </div>553            {/* Card number */}554            <div class="peach-field-card">555              <span class="peach-label">556                card number557                <Show when={getCardNetwork(cardNumber())}>558                  <span class="peach-card-network-badge">{getCardNetwork(cardNumber())}</span>559                </Show>560              </span>561              <div class="peach-field-value-row">562                <input class="peach-field-value peach-field-value--edit peach-card-number"563                  placeholder="•••• •••• •••• ••••"564                  autocomplete="cc-number" inputmode="numeric" maxLength={19}565                  value={formatCardNumberDisplay(cardNumber(), cardNumberFocused())}566                  onFocus={() => setCardNumberFocused(true)}567                  onBlur={() => setCardNumberFocused(false)}568                  onInput={(e) => {569                    const raw = (e.currentTarget as HTMLInputElement).value.replace(/\s/g, '');570                    setCardNumber(raw);571                  }} />572              </div>573            </div>574            {/* Expiry */}575            <div class="peach-field-card">576              <span class="peach-label">expiry</span>577              <div class="peach-card-expiry-row">578                <input class="peach-field-value peach-field-value--edit" placeholder="MM"579                  autocomplete="cc-exp-month" inputmode="numeric" maxLength={2} style="width:56px"580                  value={expMonth()}581                  onInput={(e) => setExpMonth((e.currentTarget as HTMLInputElement).value)} />582                <span class="peach-card-expiry-sep">/</span>583                <input class="peach-field-value peach-field-value--edit" placeholder="YYYY"584                  autocomplete="cc-exp-year" inputmode="numeric" maxLength={4} style="width:72px"585                  value={expYear()}586                  onInput={(e) => setExpYear((e.currentTarget as HTMLInputElement).value)} />587              </div>588            </div>589            {/* CVC */}590            <div class="peach-field-card">591              <span class="peach-label">CVC</span>592              <div class="peach-field-value-row">593                <input class="peach-field-value peach-field-value--edit"594                  type={showCvc() ? "text" : "password"} placeholder="•••"595                  autocomplete="cc-csc" inputmode="numeric" maxLength={4}596                  value={cvc()}597                  onInput={(e) => setCvc((e.currentTarget as HTMLInputElement).value)} />598                <button class="peach-inline-action peach-password-toggle-btn" type="button"599                  onClick={() => setShowCvc(!showCvc())} aria-label={showCvc() ? "Hide CVC" : "Show CVC"}>600                  <Show when={showCvc()} fallback={601                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">602                      <path d="M1 5C1 5 2.8 1 7 1C11.2 1 13 5 13 5C13 5 11.2 9 7 9C2.8 9 1 5 1 5Z" />603                      <circle cx="7" cy="5" r="1.75" />604                    </svg>605                  }>606                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">607                      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />608                    </svg>609                  </Show>610                </button>611              </div>612            </div>613          </section>614        </Show>615616        {/* ── Login notes ── */}617        <Show when={selectedType() === "login" && (showNotes() || notes())}>618          <div class="peach-field-card" style="margin:0 12px">619            <span class="peach-label">notes</span>620            <textarea621              class="peach-new-textarea"622              placeholder="anything worth remembering"623              value={notes()}624              onInput={(e) => setNotes((e.currentTarget as HTMLTextAreaElement).value)}625            />626          </div>627        </Show>628629        {/* ── "+ add" optional field links ── */}630        <div class="peach-entry-add-links">631          <Show when={selectedType() === "login" && !showTotp() && !totp()}>632            <button class="peach-add-field-link" type="button" onClick={() => setShowTotp(true)}>633              + add 2FA634            </button>635          </Show>636          <Show when={selectedType() === "login" && !showNotes() && !notes()}>637            <button class="peach-add-field-link" type="button" onClick={() => setShowNotes(true)}>638              + add notes639            </button>640          </Show>641        </div>642643        {/* ── Tags ── */}644        <div class="peach-field-card" style="margin:4px 12px 12px">645          <span class="peach-label">tags</span>646          <div class="peach-tag-input-wrap">647            <For each={tags()}>648              {(tag) => (649                <span class="peach-tag-chip">650                  {tag}651                  <button class="peach-tag-chip-remove" onClick={() => removeTag(tag)} aria-label={`Remove ${tag}`}>×</button>652                </span>653              )}654            </For>655            <input656              class="peach-tag-input"657              placeholder={tags().length === 0 ? "add tags…" : ""}658              value={tagInput()}659              onInput={(e) => { setTagInput((e.currentTarget as HTMLInputElement).value); setShowTagSuggestions(true); }}660              onKeyDown={handleTagKeyDown}661              onFocus={() => setShowTagSuggestions(true)}662              onBlur={() => setTimeout(() => setShowTagSuggestions(false), 150)}663              style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"664            />665          </div>666          <Show when={showTagSuggestions() && tagSuggestions().length > 0}>667            <div class="peach-tag-suggestions" style="margin-top:4px;">668              <For each={tagSuggestions()}>669                {(s) => (670                  <button671                    class="peach-tag-suggestion"672                    onMouseDown={() => { addTag(s); setTagInput(""); setShowTagSuggestions(false); }}673                  >{s}</button>674                )}675              </For>676            </div>677          </Show>678        </div>679680        <Show when={error()}>681          <p class="peach-hint peach-hint-error" style="margin:0 16px 12px">{error()}</p>682        </Show>683684      </div>685    </div>686  );687}688689interface IdentitySuggestListProps {690  suggestions: Array<{ value: string; count: number; type: "email" | "username" }>;691  onPick: (value: string) => void;692  onClose?: () => void;693  listRef?: (el: HTMLDivElement) => void;694  inputRef?: () => HTMLInputElement | undefined;695}696697export function IdentitySuggestList(props: IdentitySuggestListProps) {698  const [collapsed, setCollapsed] = createSignal(false);699  const ChevronIcon = () => (700    <svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">701      <path d="M1 1L5 5L9 1" />702    </svg>703  );704705  function handleRowKeyDown(e: KeyboardEvent, value: string) {706    const row = e.currentTarget as HTMLElement;707    if (e.key === "ArrowDown") {708      e.preventDefault();709      (row.nextElementSibling as HTMLElement | null)?.focus();710    } else if (e.key === "ArrowUp") {711      e.preventDefault();712      const prev = row.previousElementSibling as HTMLElement | null;713      if (prev) prev.focus();714      else props.inputRef?.()?.focus();715    } else if (e.key === "Enter" || e.key === " ") {716      e.preventDefault();717      props.onPick(value);718    } else if (e.key === "Escape") {719      e.preventDefault();720      props.onClose?.();721    }722  }723724  return (725    <div class="peach-identity-suggestions" ref={props.listRef}>726      <div class="peach-identity-filter-row" style="justify-content:flex-end">727        <button728          class={`peach-identity-collapse-btn${collapsed() ? " is-collapsed" : ""}`}729          type="button"730          onMouseDown={(e) => { e.preventDefault(); setCollapsed(c => !c); }}731          aria-label={collapsed() ? "Show suggestions" : "Hide suggestions"}732        >733          <ChevronIcon />734        </button>735      </div>736      <div class={`peach-identity-rows${collapsed() ? " is-collapsed" : ""}`}>737        <div class="peach-identity-rows-inner">738          <For each={props.suggestions}>739            {(s) => (740              <button741                class="peach-identity-suggestion"742                type="button"743                onMouseDown={(e) => { e.preventDefault(); props.onPick(s.value); }}744                onKeyDown={(e) => handleRowKeyDown(e, s.value)}745              >746                <span class="peach-identity-suggestion-value">{s.value}</span>747                <span class="peach-identity-suggestion-meta">{s.count}×</span>748              </button>749            )}750          </For>751        </div>752      </div>753    </div>754  );755}