Add.tsx

31.3 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      if (result.error === "vault_locked") {258        setError("vault is locked — tap the lock icon to re-enter your master password");259      } else {260        setError(result.error ?? "could not save entry");261      }262      setSaving(false);263      return;264    }265    await props.onSave(result.data);266  }267268  const strengthLabel = () => {269    const s = passwordStrength();270    if (s === null) return null;271    return ["weak", "weak", "fair", "good", "strong"][s] as string;272  };273274  return (275    <div class="peach-overlay-view ov-enter-right" style="display:flex">276      <div class="peach-overlay-header">277        <button278          class="peach-btn peach-btn--ghost peach-btn--sm peach-overlay-action"279          onClick={props.onBack}280        >281          cancel282        </button>283        <span class="peach-overlay-title">284          {props.entry ? "edit entry" : "new entry"}285        </span>286        <button287          class="peach-btn peach-btn--accent peach-btn--sm peach-overlay-action"288          onClick={() => void handleSave()}289          disabled={saving() || !canSave()}290        >291          {saving() ? "saving…" : props.entry ? "save" : "create"}292        </button>293      </div>294295      {/* ── Body — mirrors Entry.tsx field-card structure ── */}296      <div class="peach-entry-body peach-entry-body--new">297298        {/* Type toggle */}299        <Show when={!props.entry}>300          <div class="peach-new-type-row">301            <button302              class={`peach-new-type-btn ${selectedType() === "login" ? "is-active" : ""}`}303              onClick={() => setSelectedType("login")}304            >login</button>305            <button306              class={`peach-new-type-btn ${selectedType() === "card" ? "is-active" : ""}`}307              onClick={() => setSelectedType("card")}308            >card</button>309          </div>310        </Show>311312        {/* Title */}313        <div class="peach-new-title-wrap">314          <input315            class="peach-new-title-input"316            placeholder="entry name"317            autocomplete="off"318            value={title()}319            onInput={(e) => setTitle((e.currentTarget as HTMLInputElement).value)}320            onKeyDown={(e) => { if (e.key === "Enter") void handleSave(); }}321          />322        </div>323324        {/* ── Login fields ── */}325        <Show when={selectedType() === "login"}>326          <div class="peach-domain">327            <div class="peach-domain-edit-row">328              <input329                class="peach-domain-value peach-domain-value--edit"330                placeholder="domain.com"331                autocomplete="off"332                value={url()}333                onInput={(e) => setUrl((e.currentTarget as HTMLInputElement).value)}334              />335              <Show when={currentTabUrl()}>336                <button337                  class="peach-domain-url-btn"338                  type="button"339                  onClick={() => setUrl(currentTabUrl())}340                  title="Insert current page URL"341                >342                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">343                    <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" />344                    <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" />345                  </svg>346                </button>347              </Show>348            </div>349          </div>350351          <section class="peach-fields">352            {/* Username */}353            <div class="peach-field-card">354              <span class="peach-label">username</span>355              <div class="peach-field-value-row">356                <input357                  ref={(el) => (usernameInputEl = el)}358                  class="peach-field-value peach-field-value--edit"359                  placeholder="johndoe"360                  autocomplete="off"361                  value={username()}362                  onInput={(e) => setUsername((e.currentTarget as HTMLInputElement).value)}363                  onFocus={() => openIdentityField("username")}364                  onBlur={(e) => {365                    if (usernameSuggestEl?.contains(e.relatedTarget as Node)) return;366                    setTimeout(() => { if (activeIdentityField() === "username") setActiveIdentityField(null); }, 150);367                  }}368                  onKeyDown={(e) => {369                    if (activeIdentityField() !== "username") return;370                    if (e.key === "ArrowDown") {371                      e.preventDefault();372                      usernameSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();373                    } else if (e.key === "Escape") {374                      e.preventDefault();375                      setActiveIdentityField(null);376                    }377                  }}378                />379              </div>380              <Show when={activeIdentityField() === "username" && identitySuggestions().length > 0}>381                <IdentitySuggestList382                  listRef={(el) => (usernameSuggestEl = el)}383                  inputRef={() => usernameInputEl}384                  suggestions={identitySuggestions()}385                  onPick={(v) => { setUsername(v); setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}386                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}387                />388              </Show>389            </div>390391            {/* Email */}392            <div class="peach-field-card">393              <span class="peach-label">email</span>394              <div class="peach-field-value-row">395                <input396                  ref={(el) => (emailInputEl = el)}397                  class="peach-field-value peach-field-value--edit"398                  type="email"399                  placeholder="[email protected]"400                  autocomplete="off"401                  value={email()}402                  onInput={(e) => setEmail((e.currentTarget as HTMLInputElement).value)}403                  onFocus={() => openIdentityField("email")}404                  onBlur={(e) => {405                    if (emailSuggestEl?.contains(e.relatedTarget as Node)) return;406                    setTimeout(() => { if (activeIdentityField() === "email") setActiveIdentityField(null); }, 150);407                  }}408                  onKeyDown={(e) => {409                    if (activeIdentityField() !== "email") return;410                    if (e.key === "ArrowDown") {411                      e.preventDefault();412                      emailSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();413                    } else if (e.key === "Escape") {414                      e.preventDefault();415                      setActiveIdentityField(null);416                    }417                  }}418                />419              </div>420              <Show when={activeIdentityField() === "email" && identitySuggestions().length > 0}>421                <IdentitySuggestList422                  listRef={(el) => (emailSuggestEl = el)}423                  inputRef={() => emailInputEl}424                  suggestions={identitySuggestions()}425                  onPick={(v) => { setEmail(v); setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}426                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}427                />428              </Show>429            </div>430431            {/* Password */}432            <div class="peach-field-card">433              <span class="peach-label">password</span>434              <Show when={!showGenerator()}>435                <div class="peach-password-edit-row">436                  <input437                    class="peach-field-value peach-field-value--edit"438                    type={showPassword() ? "text" : "password"}439                    placeholder="password"440                    autocomplete="new-password"441                    value={password()}442                    onInput={(e) => setPassword((e.currentTarget as HTMLInputElement).value)}443                  />444                  <button445                    class="peach-inline-action peach-password-toggle-btn"446                    type="button"447                    onClick={() => setShowPassword(!showPassword())}448                    aria-label={showPassword() ? "Hide password" : "Show password"}449                  >450                    <Show451                      when={showPassword()}452                      fallback={453                        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">454                          <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" />455                          <circle cx="7" cy="5" r="1.75" />456                        </svg>457                      }458                    >459                      <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">460                        <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />461                        <path d="M3.5 5.5L2.5 7.5" />462                        <path d="M7 6.5V8.5" />463                        <path d="M10.5 5.5L11.5 7.5" />464                      </svg>465                    </Show>466                  </button>467                </div>468              </Show>469470              {/* Strength */}471              <Show when={strengthLabel() !== null}>472                <div class="peach-strength-hairline">473                  <div class="peach-strength-hairline-track">474                    <div475                      class="peach-strength-hairline-fill"476                      style={{477                        width: ["25%","40%","60%","80%","100%"][passwordStrength()!],478                        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()!],479                      }}480                    />481                  </div>482                  <span class="peach-strength-label">{strengthLabel()}</span>483                </div>484              </Show>485486              {/* Generator toggle */}487              <button488                class="peach-generate-toggle-link"489                type="button"490                onClick={() => { setShowGenerator(!showGenerator()); }}491              >492                {showGenerator() ? "☰ hide generator" : "⚙ generate"}493              </button>494              <GeneratorDrawer495                compact496                open={showGenerator()}497                onChange={(pw) => setPassword(pw)}498                onUse={(pw) => { setPassword(pw); setShowGenerator(false); }}499              />500            </div>501502            {/* 2FA — optional */}503            <Show when={showTotp() || totp()}>504              <div class="peach-field-card">505                <span class="peach-label">2fa secret</span>506                <div class="peach-field-value-row">507                  <input508                    class="peach-field-value peach-field-value--edit"509                    placeholder="BASE32 or otpauth:// URI"510                    autocomplete="off"511                    value={totp()}512                    onInput={(e) => setTotp((e.currentTarget as HTMLInputElement).value)}513                  />514                </div>515              </div>516            </Show>517          </section>518        </Show>519520        {/* ── Card fields ── */}521        <Show when={selectedType() === "card"}>522          <section class="peach-fields">523            {/* Nickname */}524            <div class="peach-field-card">525              <span class="peach-label">nickname</span>526              <div class="peach-field-value-row">527                <input class="peach-field-value peach-field-value--edit" placeholder="Personal Visa"528                  autocomplete="off" value={cardNickname()}529                  onInput={(e) => setCardNickname((e.currentTarget as HTMLInputElement).value)} />530              </div>531            </div>532            {/* Cardholder name */}533            <div class="peach-field-card">534              <span class="peach-label">cardholder name</span>535              <div class="peach-field-value-row">536                <input class="peach-field-value peach-field-value--edit" placeholder="Jane Smith"537                  autocomplete="cc-name" value={cardholderName()}538                  onInput={(e) => setCardholderName((e.currentTarget as HTMLInputElement).value)} />539              </div>540            </div>541            {/* Card number */}542            <div class="peach-field-card">543              <span class="peach-label">544                card number545                <Show when={getCardNetwork(cardNumber())}>546                  <span class="peach-card-network-badge">{getCardNetwork(cardNumber())}</span>547                </Show>548              </span>549              <div class="peach-field-value-row">550                <input class="peach-field-value peach-field-value--edit peach-card-number"551                  placeholder="•••• •••• •••• ••••"552                  autocomplete="cc-number" inputmode="numeric" maxLength={19}553                  value={formatCardNumberDisplay(cardNumber(), cardNumberFocused())}554                  onFocus={() => setCardNumberFocused(true)}555                  onBlur={() => setCardNumberFocused(false)}556                  onInput={(e) => {557                    const raw = (e.currentTarget as HTMLInputElement).value.replace(/\s/g, '');558                    setCardNumber(raw);559                  }} />560              </div>561            </div>562            {/* Expiry */}563            <div class="peach-field-card">564              <span class="peach-label">expiry</span>565              <div class="peach-card-expiry-row">566                <input class="peach-field-value peach-field-value--edit" placeholder="MM"567                  autocomplete="cc-exp-month" inputmode="numeric" maxLength={2} style="width:56px"568                  value={expMonth()}569                  onInput={(e) => setExpMonth((e.currentTarget as HTMLInputElement).value)} />570                <span class="peach-card-expiry-sep">/</span>571                <input class="peach-field-value peach-field-value--edit" placeholder="YYYY"572                  autocomplete="cc-exp-year" inputmode="numeric" maxLength={4} style="width:72px"573                  value={expYear()}574                  onInput={(e) => setExpYear((e.currentTarget as HTMLInputElement).value)} />575              </div>576            </div>577            {/* CVC */}578            <div class="peach-field-card">579              <span class="peach-label">CVC</span>580              <div class="peach-field-value-row">581                <input class="peach-field-value peach-field-value--edit"582                  type={showCvc() ? "text" : "password"} placeholder="•••"583                  autocomplete="cc-csc" inputmode="numeric" maxLength={4}584                  value={cvc()}585                  onInput={(e) => setCvc((e.currentTarget as HTMLInputElement).value)} />586                <button class="peach-inline-action peach-password-toggle-btn" type="button"587                  onClick={() => setShowCvc(!showCvc())} aria-label={showCvc() ? "Hide CVC" : "Show CVC"}>588                  <Show when={showCvc()} fallback={589                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">590                      <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" />591                      <circle cx="7" cy="5" r="1.75" />592                    </svg>593                  }>594                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">595                      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />596                    </svg>597                  </Show>598                </button>599              </div>600            </div>601          </section>602        </Show>603604        {/* ── Login notes ── */}605        <Show when={selectedType() === "login" && (showNotes() || notes())}>606          <div class="peach-field-card" style="margin:0 12px">607            <span class="peach-label">notes</span>608            <textarea609              class="peach-new-textarea"610              placeholder="anything worth remembering"611              value={notes()}612              onInput={(e) => setNotes((e.currentTarget as HTMLTextAreaElement).value)}613            />614          </div>615        </Show>616617        {/* ── "+ add" optional field links ── */}618        <div class="peach-entry-add-links">619          <Show when={selectedType() === "login" && !showTotp() && !totp()}>620            <button class="peach-add-field-link" type="button" onClick={() => setShowTotp(true)}>621              + add 2FA622            </button>623          </Show>624          <Show when={selectedType() === "login" && !showNotes() && !notes()}>625            <button class="peach-add-field-link" type="button" onClick={() => setShowNotes(true)}>626              + add notes627            </button>628          </Show>629        </div>630631        {/* ── Tags ── */}632        <div class="peach-field-card" style="margin:4px 12px 12px">633          <span class="peach-label">tags</span>634          <div class="peach-tag-input-wrap">635            <For each={tags()}>636              {(tag) => (637                <span class="peach-tag-chip">638                  {tag}639                  <button class="peach-tag-chip-remove" onClick={() => removeTag(tag)} aria-label={`Remove ${tag}`}>×</button>640                </span>641              )}642            </For>643            <input644              class="peach-tag-input"645              placeholder={tags().length === 0 ? "add tags…" : ""}646              value={tagInput()}647              onInput={(e) => { setTagInput((e.currentTarget as HTMLInputElement).value); setShowTagSuggestions(true); }}648              onKeyDown={handleTagKeyDown}649              onFocus={() => setShowTagSuggestions(true)}650              onBlur={() => setTimeout(() => setShowTagSuggestions(false), 150)}651              style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"652            />653          </div>654          <Show when={showTagSuggestions() && tagSuggestions().length > 0}>655            <div class="peach-tag-suggestions" style="margin-top:4px;">656              <For each={tagSuggestions()}>657                {(s) => (658                  <button659                    class="peach-tag-suggestion"660                    onMouseDown={() => { addTag(s); setTagInput(""); setShowTagSuggestions(false); }}661                  >{s}</button>662                )}663              </For>664            </div>665          </Show>666        </div>667668        <Show when={error()}>669          <p class="peach-hint peach-hint-error" style="margin:0 16px 12px">{error()}</p>670        </Show>671672      </div>673    </div>674  );675}676677interface IdentitySuggestListProps {678  suggestions: Array<{ value: string; count: number; type: "email" | "username" }>;679  onPick: (value: string) => void;680  onClose?: () => void;681  listRef?: (el: HTMLDivElement) => void;682  inputRef?: () => HTMLInputElement | undefined;683}684685export function IdentitySuggestList(props: IdentitySuggestListProps) {686  const [collapsed, setCollapsed] = createSignal(false);687  const ChevronIcon = () => (688    <svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">689      <path d="M1 1L5 5L9 1" />690    </svg>691  );692693  function handleRowKeyDown(e: KeyboardEvent, value: string) {694    const row = e.currentTarget as HTMLElement;695    if (e.key === "ArrowDown") {696      e.preventDefault();697      (row.nextElementSibling as HTMLElement | null)?.focus();698    } else if (e.key === "ArrowUp") {699      e.preventDefault();700      const prev = row.previousElementSibling as HTMLElement | null;701      if (prev) prev.focus();702      else props.inputRef?.()?.focus();703    } else if (e.key === "Enter" || e.key === " ") {704      e.preventDefault();705      props.onPick(value);706    } else if (e.key === "Escape") {707      e.preventDefault();708      props.onClose?.();709    }710  }711712  return (713    <div class="peach-identity-suggestions" ref={props.listRef}>714      <div class="peach-identity-filter-row" style="justify-content:flex-end">715        <button716          class={`peach-identity-collapse-btn${collapsed() ? " is-collapsed" : ""}`}717          type="button"718          onMouseDown={(e) => { e.preventDefault(); setCollapsed(c => !c); }}719          aria-label={collapsed() ? "Show suggestions" : "Hide suggestions"}720        >721          <ChevronIcon />722        </button>723      </div>724      <div class={`peach-identity-rows${collapsed() ? " is-collapsed" : ""}`}>725        <div class="peach-identity-rows-inner">726          <For each={props.suggestions}>727            {(s) => (728              <button729                class="peach-identity-suggestion"730                type="button"731                onMouseDown={(e) => { e.preventDefault(); props.onPick(s.value); }}732                onKeyDown={(e) => handleRowKeyDown(e, s.value)}733              >734                <span class="peach-identity-suggestion-value">{s.value}</span>735                <span class="peach-identity-suggestion-meta">{s.count}×</span>736              </button>737            )}738          </For>739        </div>740      </div>741    </div>742  );743}