Add.tsx

32.1 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 { NoteEditorInline, Toolbar } from "./NoteEditor";6import { GeneratorDrawer } from "../components/GeneratorDrawer";78interface AddProps {9  entry?: VaultEntry;10  entries?: VaultEntry[];11  autoOpenGenerator?: boolean;12  onBack: () => void;13  onSave: (entry?: VaultEntry) => void | Promise<void>;14}1516export function AddView(props: AddProps) {17  const [title, setTitle] = createSignal(props.entry?.title ?? "");18  const [username, setUsername] = createSignal(props.entry?.username ?? "");19  const [password, setPassword] = createSignal(props.entry?.password ?? "");20  const [url, setUrl] = createSignal(props.entry?.url ?? "");21  const [totp, setTotp] = createSignal(props.entry?.totp ?? "");22  const [notes, setNotes] = createSignal(props.entry?.notes ?? "");23  const [saving, setSaving] = createSignal(false);24  const [error, setError] = createSignal("");25  const [passwordStrength, setPasswordStrength] = createSignal<number | null>(null);26  const [zxcvbnFn, setZxcvbnFn] = createSignal<((pwd: string) => { score: number }) | null>(null);27  const [tags, setTags] = createSignal<string[]>(props.entry?.tags ?? []);28  const [tagInput, setTagInput] = createSignal("");29  const [showTagSuggestions, setShowTagSuggestions] = createSignal(false);30  const [showGenerator, setShowGenerator] = createSignal(props.autoOpenGenerator ?? false);31  const [showPassword, setShowPassword] = createSignal(false);32  const [showTotp, setShowTotp] = createSignal(!!(props.entry?.totp));33  const [showNotes, setShowNotes] = createSignal(!!(props.entry?.notes));34  const [email, setEmail] = createSignal((props.entry as VaultEntry & { email?: string })?.email ?? "");35  const [activeIdentityField, setActiveIdentityField] = createSignal<"username" | "email" | null>(null);36  const [currentTabUrl, setCurrentTabUrl] = createSignal("");3738  // Mutable refs for keyboard navigation between inputs and suggestion lists.39  // Not signals — focus state doesn't need to be reactive.40  let usernameInputEl: HTMLInputElement | undefined;41  let emailInputEl: HTMLInputElement | undefined;42  let usernameSuggestEl: HTMLDivElement | undefined;43  let emailSuggestEl: HTMLDivElement | undefined;44  let suppressIdentityOpen = false;4546  function openIdentityField(field: "username" | "email") {47    if (suppressIdentityOpen) { suppressIdentityOpen = false; return; }48    setActiveIdentityField(field);49  }5051  const allIdentities = createMemo(() => {52    const emailMap = new Map<string, number>();53    const usernameMap = new Map<string, number>();54    for (const entry of props.entries ?? []) {55      const uname = entry.username?.trim() ?? "";56      const em = entry.email?.trim() ?? "";57      if (uname) {58        if (uname.includes("@")) emailMap.set(uname, (emailMap.get(uname) ?? 0) + 1);59        else usernameMap.set(uname, (usernameMap.get(uname) ?? 0) + 1);60      }61      if (em) emailMap.set(em, (emailMap.get(em) ?? 0) + 1);62    }63    const result: Array<{ value: string; count: number; type: "email" | "username" }> = [];64    const seen = new Set<string>();65    for (const v of new Set([...emailMap.keys(), ...usernameMap.keys()])) {66      if (seen.has(v)) continue;67      seen.add(v);68      const ec = emailMap.get(v) ?? 0;69      const uc = usernameMap.get(v) ?? 0;70      result.push({ value: v, count: Math.max(ec, uc), type: ec >= uc ? "email" : "username" });71    }72    return result.sort((a, b) => b.count - a.count);73  });7475  const identitySuggestions = createMemo(() => {76    const field = activeIdentityField();77    if (!field) return [];78    const input = (field === "username" ? username() : email()).toLowerCase();79    return allIdentities()80      .filter(s => s.type === field && (!input || s.value.toLowerCase().includes(input)))81      .slice(0, 8);82  });8384  const isNoteEntry = () => props.entry?.type === "note";85  const isCardEntry = () => props.entry?.type === "card";86  const [selectedType, setSelectedType] = createSignal<"login" | "note" | "card">(87    isNoteEntry() ? "note" : isCardEntry() ? "card" : "login"88  );8990  // Card signals91  const [cardNickname, setCardNickname] = createSignal(props.entry?.cardNickname ?? "");92  const [cardholderName, setCardholderName] = createSignal(props.entry?.cardholderName ?? "");93  const [cardNumber, setCardNumber] = createSignal(props.entry?.cardNumber ?? "");94  const [expMonth, setExpMonth] = createSignal(props.entry?.expMonth ?? "");95  const [expYear, setExpYear] = createSignal(props.entry?.expYear ?? "");96  const [cvc, setCvc] = createSignal(props.entry?.cvc ?? "");97  const [showCvc, setShowCvc] = createSignal(false);98  const [cardNumberFocused, setCardNumberFocused] = createSignal(false);99  const [noteEditorEl, setNoteEditorEl] = createSignal<HTMLDivElement | null>(null);100101  function noteExec(cmd: string, val?: string) {102    document.execCommand(cmd, false, val);103    noteEditorEl()?.focus();104  }105106  function getCardNetwork(num: string): string {107    const n = num.replace(/\s/g, '');108    if (/^4/.test(n)) return 'Visa';109    if (/^5[1-5]|^2[2-7]/.test(n)) return 'Mastercard';110    if (/^3[47]/.test(n)) return 'Amex';111    if (/^6(?:011|5)/.test(n)) return 'Discover';112    return '';113  }114115  function formatCardNumberDisplay(raw: string, focused: boolean): string {116    const n = raw.replace(/\s/g, '');117    if (!focused && n.length >= 4) return '•••• •••• •••• ' + n.slice(-4);118    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(' '));119    return n.replace(/(\d{4})(?=\d)/g, '$1 ').trim();120  }121122  const canSave = () => {123    if (!title().trim()) return false;124    if (selectedType() === "login" && !password().trim()) return false;125    if (selectedType() === "card" && (!cardholderName().trim() || !cardNumber().trim())) return false;126    return true;127  };128129  const allTags = createMemo(() => {130    const tagSet = new Set<string>();131    for (const entry of props.entries ?? []) {132      for (const tag of entry.tags ?? []) tagSet.add(tag);133    }134    return Array.from(tagSet).sort();135  });136137  const tagSuggestions = createMemo(() => {138    const input = tagInput().toLowerCase().trim();139    if (!input) return [];140    return allTags().filter(t =>141      t.toLowerCase().includes(input) && !tags().includes(t)142    ).slice(0, 5);143  });144145  function addTag(tag: string) {146    const n = tag.toLowerCase().trim();147    if (!n || n.length > 32 || tags().includes(n) || tags().length >= 10) return;148    setTags([...tags(), n]);149  }150151  function removeTag(tag: string) {152    setTags(tags().filter(t => t !== tag));153  }154155  function handleTagKeyDown(e: KeyboardEvent) {156    if (e.key === "Enter" || e.key === ",") {157      e.preventDefault();158      if (tagInput()) { addTag(tagInput()); setTagInput(""); setShowTagSuggestions(false); }159    } else if (e.key === "Backspace" && !tagInput() && tags().length > 0) {160      removeTag(tags()[tags().length - 1]);161    }162  }163164  // Strength check165  createEffect(async () => {166    const pwd = password();167    if (pwd.length < 4) { setPasswordStrength(null); return; }168    try {169      if (!zxcvbnFn()) {170        const mod = await import("zxcvbn");171        setZxcvbnFn(() => mod.default);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() === "note"209          ? "title is required"210          : selectedType() === "card"211          ? "cardholder name and card number are required"212          : "title and password are required"213      );214      return;215    }216217    setSaving(true);218    setError("");219220    const payload: Record<string, unknown> = {221      type: selectedType(),222      title: title().trim(),223      notes: notes().trim() || undefined,224      tags: tags().length > 0 ? tags() : undefined,225    };226227    if (selectedType() === "login") {228      payload.username = username().trim();229      payload.email = email().trim() || undefined;230      payload.password = password();231      payload.url = url().trim();232      payload.totp = getNormalizedTotp();233    }234235    if (selectedType() === "card") {236      const raw = cardNumber().replace(/\s/g, '');237      payload.cardholderName = cardholderName().trim();238      payload.cardNumber = raw;239      payload.expMonth = expMonth().trim();240      payload.expYear = expYear().trim();241      payload.cvc = cvc().trim();242      payload.cardNickname = cardNickname().trim() || undefined;243      const n = raw;244      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';245      payload.last4 = raw.slice(-4);246    }247248    if (props.entry) {249      const res = await sendMessage({ type: "UPDATE_ENTRY", payload: { id: props.entry.id, patch: payload } });250      const result = res as { ok: boolean; error?: string };251      if (!result.ok) { setError(result.error ?? "could not update entry"); setSaving(false); return; }252      await props.onSave({ ...props.entry, ...payload } as VaultEntry);253      return;254    }255256    const res = await sendMessage({ type: "ADD_ENTRY", payload });257    const result = res as { ok: boolean; data?: VaultEntry; error?: string };258    if (!result.ok) {259      if (result.error === "vault locked") {260        setError("vault is locked — tap the lock icon to re-enter your master password");261      } else {262        setError(result.error ?? "could not save entry");263      }264      setSaving(false);265      return;266    }267    await props.onSave(result.data);268  }269270  const strengthLabel = () => {271    const s = passwordStrength();272    if (s === null) return null;273    return ["weak", "weak", "fair", "good", "strong"][s] as string;274  };275276  return (277    <div class="peach-overlay-view ov-enter-right" style="display:flex">278      <div class="peach-overlay-header">279        <button280          class="peach-btn peach-btn--ghost peach-btn--sm peach-overlay-action"281          onClick={props.onBack}282        >283          cancel284        </button>285        <span class="peach-overlay-title">286          {props.entry ? "edit entry" : "new entry"}287        </span>288        <button289          class="peach-btn peach-btn--accent peach-btn--sm peach-overlay-action"290          onClick={() => void handleSave()}291          disabled={saving() || !canSave()}292        >293          {saving() ? "saving…" : props.entry ? "save" : "create"}294        </button>295      </div>296297      {/* ── Body — mirrors Entry.tsx field-card structure ── */}298      <div class="peach-entry-body peach-entry-body--new">299300        {/* Type toggle */}301        <Show when={!props.entry}>302          <div class="peach-new-type-row">303            <button304              class={`peach-new-type-btn ${selectedType() === "login" ? "is-active" : ""}`}305              onClick={() => setSelectedType("login")}306            >login</button>307            <button308              class={`peach-new-type-btn ${selectedType() === "note" ? "is-active" : ""}`}309              onClick={() => setSelectedType("note")}310            >note</button>311            <button312              class={`peach-new-type-btn ${selectedType() === "card" ? "is-active" : ""}`}313              onClick={() => setSelectedType("card")}314            >card</button>315          </div>316        </Show>317318        {/* Note formatting toolbar — own row so it never overflows */}319        <Show when={selectedType() === "note"}>320          <Toolbar exec={noteExec} class="peach-note-toolbar-body" />321        </Show>322323        {/* Title */}324        <div class="peach-new-title-wrap">325          <input326            class="peach-new-title-input"327            placeholder={selectedType() === "note" ? "note title" : "entry name"}328            autocomplete="off"329            value={title()}330            onInput={(e) => setTitle((e.currentTarget as HTMLInputElement).value)}331            onKeyDown={(e) => { if (e.key === "Enter") void handleSave(); }}332          />333        </div>334335        {/* ── Login fields ── */}336        <Show when={selectedType() === "login"}>337          <div class="peach-domain">338            <div class="peach-domain-edit-row">339              <input340                class="peach-domain-value peach-domain-value--edit"341                placeholder="domain.com"342                autocomplete="off"343                value={url()}344                onInput={(e) => setUrl((e.currentTarget as HTMLInputElement).value)}345              />346              <Show when={currentTabUrl()}>347                <button348                  class="peach-domain-url-btn"349                  type="button"350                  onClick={() => setUrl(currentTabUrl())}351                  title="Insert current page URL"352                >353                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">354                    <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" />355                    <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" />356                  </svg>357                </button>358              </Show>359            </div>360          </div>361362          <section class="peach-fields">363            {/* Username */}364            <div class="peach-field-card">365              <span class="peach-label">username</span>366              <div class="peach-field-value-row">367                <input368                  ref={(el) => (usernameInputEl = el)}369                  class="peach-field-value peach-field-value--edit"370                  placeholder="johndoe"371                  autocomplete="off"372                  value={username()}373                  onInput={(e) => setUsername((e.currentTarget as HTMLInputElement).value)}374                  onFocus={() => openIdentityField("username")}375                  onBlur={(e) => {376                    if (usernameSuggestEl?.contains(e.relatedTarget as Node)) return;377                    setTimeout(() => { if (activeIdentityField() === "username") setActiveIdentityField(null); }, 150);378                  }}379                  onKeyDown={(e) => {380                    if (activeIdentityField() !== "username") return;381                    if (e.key === "ArrowDown") {382                      e.preventDefault();383                      usernameSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();384                    } else if (e.key === "Escape") {385                      e.preventDefault();386                      setActiveIdentityField(null);387                    }388                  }}389                />390              </div>391              <Show when={activeIdentityField() === "username" && identitySuggestions().length > 0}>392                <IdentitySuggestList393                  listRef={(el) => (usernameSuggestEl = el)}394                  inputRef={() => usernameInputEl}395                  suggestions={identitySuggestions()}396                  onPick={(v) => { setUsername(v); setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}397                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}398                />399              </Show>400            </div>401402            {/* Email */}403            <div class="peach-field-card">404              <span class="peach-label">email</span>405              <div class="peach-field-value-row">406                <input407                  ref={(el) => (emailInputEl = el)}408                  class="peach-field-value peach-field-value--edit"409                  type="email"410                  placeholder="[email protected]"411                  autocomplete="off"412                  value={email()}413                  onInput={(e) => setEmail((e.currentTarget as HTMLInputElement).value)}414                  onFocus={() => openIdentityField("email")}415                  onBlur={(e) => {416                    if (emailSuggestEl?.contains(e.relatedTarget as Node)) return;417                    setTimeout(() => { if (activeIdentityField() === "email") setActiveIdentityField(null); }, 150);418                  }}419                  onKeyDown={(e) => {420                    if (activeIdentityField() !== "email") return;421                    if (e.key === "ArrowDown") {422                      e.preventDefault();423                      emailSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();424                    } else if (e.key === "Escape") {425                      e.preventDefault();426                      setActiveIdentityField(null);427                    }428                  }}429                />430              </div>431              <Show when={activeIdentityField() === "email" && identitySuggestions().length > 0}>432                <IdentitySuggestList433                  listRef={(el) => (emailSuggestEl = el)}434                  inputRef={() => emailInputEl}435                  suggestions={identitySuggestions()}436                  onPick={(v) => { setEmail(v); setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}437                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}438                />439              </Show>440            </div>441442            {/* Password */}443            <div class="peach-field-card">444              <span class="peach-label">password</span>445              <Show when={!showGenerator()}>446                <div class="peach-password-edit-row">447                  <input448                    class="peach-field-value peach-field-value--edit"449                    type={showPassword() ? "text" : "password"}450                    placeholder="password"451                    autocomplete="new-password"452                    value={password()}453                    onInput={(e) => setPassword((e.currentTarget as HTMLInputElement).value)}454                  />455                  <button456                    class="peach-inline-action peach-password-toggle-btn"457                    type="button"458                    onClick={() => setShowPassword(!showPassword())}459                    aria-label={showPassword() ? "Hide password" : "Show password"}460                  >461                    <Show462                      when={showPassword()}463                      fallback={464                        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">465                          <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" />466                          <circle cx="7" cy="5" r="1.75" />467                        </svg>468                      }469                    >470                      <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">471                        <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />472                        <path d="M3.5 5.5L2.5 7.5" />473                        <path d="M7 6.5V8.5" />474                        <path d="M10.5 5.5L11.5 7.5" />475                      </svg>476                    </Show>477                  </button>478                </div>479              </Show>480481              {/* Strength */}482              <Show when={strengthLabel() !== null}>483                <div class="peach-strength-hairline">484                  <div class="peach-strength-hairline-track">485                    <div486                      class="peach-strength-hairline-fill"487                      style={{488                        width: ["25%","40%","60%","80%","100%"][passwordStrength()!],489                        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()!],490                      }}491                    />492                  </div>493                  <span class="peach-strength-label">{strengthLabel()}</span>494                </div>495              </Show>496497              {/* Generator toggle */}498              <button499                class="peach-generate-toggle-link"500                type="button"501                onClick={() => { setShowGenerator(!showGenerator()); }}502              >503                {showGenerator() ? "☰ hide generator" : "⚙ generate"}504              </button>505              <GeneratorDrawer506                compact507                open={showGenerator()}508                onChange={(pw) => setPassword(pw)}509                onUse={(pw) => { setPassword(pw); setShowGenerator(false); }}510              />511            </div>512513            {/* 2FA — optional */}514            <Show when={showTotp() || totp()}>515              <div class="peach-field-card">516                <span class="peach-label">2fa secret</span>517                <div class="peach-field-value-row">518                  <input519                    class="peach-field-value peach-field-value--edit"520                    placeholder="BASE32 or otpauth:// URI"521                    autocomplete="off"522                    value={totp()}523                    onInput={(e) => setTotp((e.currentTarget as HTMLInputElement).value)}524                  />525                </div>526              </div>527            </Show>528          </section>529        </Show>530531        {/* ── Card fields ── */}532        <Show when={selectedType() === "card"}>533          <section class="peach-fields">534            {/* Nickname */}535            <div class="peach-field-card">536              <span class="peach-label">nickname</span>537              <div class="peach-field-value-row">538                <input class="peach-field-value peach-field-value--edit" placeholder="Personal Visa"539                  autocomplete="off" value={cardNickname()}540                  onInput={(e) => setCardNickname((e.currentTarget as HTMLInputElement).value)} />541              </div>542            </div>543            {/* Cardholder name */}544            <div class="peach-field-card">545              <span class="peach-label">cardholder name</span>546              <div class="peach-field-value-row">547                <input class="peach-field-value peach-field-value--edit" placeholder="Jane Smith"548                  autocomplete="cc-name" value={cardholderName()}549                  onInput={(e) => setCardholderName((e.currentTarget as HTMLInputElement).value)} />550              </div>551            </div>552            {/* Card number */}553            <div class="peach-field-card">554              <span class="peach-label">555                card number556                <Show when={getCardNetwork(cardNumber())}>557                  <span class="peach-card-network-badge">{getCardNetwork(cardNumber())}</span>558                </Show>559              </span>560              <div class="peach-field-value-row">561                <input class="peach-field-value peach-field-value--edit peach-card-number"562                  placeholder="•••• •••• •••• ••••"563                  autocomplete="cc-number" inputmode="numeric" maxLength={19}564                  value={formatCardNumberDisplay(cardNumber(), cardNumberFocused())}565                  onFocus={() => setCardNumberFocused(true)}566                  onBlur={() => setCardNumberFocused(false)}567                  onInput={(e) => {568                    const raw = (e.currentTarget as HTMLInputElement).value.replace(/\s/g, '');569                    setCardNumber(raw);570                  }} />571              </div>572            </div>573            {/* Expiry */}574            <div class="peach-field-card">575              <span class="peach-label">expiry</span>576              <div class="peach-card-expiry-row">577                <input class="peach-field-value peach-field-value--edit" placeholder="MM"578                  autocomplete="cc-exp-month" inputmode="numeric" maxLength={2} style="width:56px"579                  value={expMonth()}580                  onInput={(e) => setExpMonth((e.currentTarget as HTMLInputElement).value)} />581                <span class="peach-card-expiry-sep">/</span>582                <input class="peach-field-value peach-field-value--edit" placeholder="YYYY"583                  autocomplete="cc-exp-year" inputmode="numeric" maxLength={4} style="width:72px"584                  value={expYear()}585                  onInput={(e) => setExpYear((e.currentTarget as HTMLInputElement).value)} />586              </div>587            </div>588            {/* CVC */}589            <div class="peach-field-card">590              <span class="peach-label">CVC</span>591              <div class="peach-field-value-row">592                <input class="peach-field-value peach-field-value--edit"593                  type={showCvc() ? "text" : "password"} placeholder="•••"594                  autocomplete="cc-csc" inputmode="numeric" maxLength={4}595                  value={cvc()}596                  onInput={(e) => setCvc((e.currentTarget as HTMLInputElement).value)} />597                <button class="peach-inline-action peach-password-toggle-btn" type="button"598                  onClick={() => setShowCvc(!showCvc())} aria-label={showCvc() ? "Hide CVC" : "Show CVC"}>599                  <Show when={showCvc()} fallback={600                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">601                      <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" />602                      <circle cx="7" cy="5" r="1.75" />603                    </svg>604                  }>605                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">606                      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />607                    </svg>608                  </Show>609                </button>610              </div>611            </div>612          </section>613        </Show>614615        {/* ── Note content ── */}616        <Show when={selectedType() === "note"}>617          <div class="peach-note-body">618            <NoteEditorInline619              initialContent={notes()}620              onContentChange={setNotes}621              onReady={(el) => setNoteEditorEl(el)}622            />623          </div>624        </Show>625626        {/* ── Login notes ── */}627        <Show when={selectedType() === "login" && (showNotes() || notes())}>628          <div class="peach-field-card" style="margin:0 12px">629            <span class="peach-label">notes</span>630            <textarea631              class="peach-new-textarea"632              placeholder="anything worth remembering"633              value={notes()}634              onInput={(e) => setNotes((e.currentTarget as HTMLTextAreaElement).value)}635            />636          </div>637        </Show>638639        {/* ── "+ add" optional field links ── */}640        <div class="peach-entry-add-links">641          <Show when={selectedType() === "login" && !showTotp() && !totp()}>642            <button class="peach-add-field-link" type="button" onClick={() => setShowTotp(true)}>643              + add 2FA644            </button>645          </Show>646          <Show when={selectedType() === "login" && !showNotes() && !notes()}>647            <button class="peach-add-field-link" type="button" onClick={() => setShowNotes(true)}>648              + add notes649            </button>650          </Show>651        </div>652653        {/* ── Tags ── */}654        <div class="peach-field-card" style="margin:4px 12px 12px">655          <span class="peach-label">tags</span>656          <div class="peach-tag-input-wrap">657            <For each={tags()}>658              {(tag) => (659                <span class="peach-tag-chip">660                  {tag}661                  <button class="peach-tag-chip-remove" onClick={() => removeTag(tag)} aria-label={`Remove ${tag}`}>×</button>662                </span>663              )}664            </For>665            <input666              class="peach-tag-input"667              placeholder={tags().length === 0 ? "add tags…" : ""}668              value={tagInput()}669              onInput={(e) => { setTagInput((e.currentTarget as HTMLInputElement).value); setShowTagSuggestions(true); }}670              onKeyDown={handleTagKeyDown}671              onFocus={() => setShowTagSuggestions(true)}672              onBlur={() => setTimeout(() => setShowTagSuggestions(false), 150)}673              style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"674            />675          </div>676          <Show when={showTagSuggestions() && tagSuggestions().length > 0}>677            <div class="peach-tag-suggestions" style="margin-top:4px;">678              <For each={tagSuggestions()}>679                {(s) => (680                  <button681                    class="peach-tag-suggestion"682                    onMouseDown={() => { addTag(s); setTagInput(""); setShowTagSuggestions(false); }}683                  >{s}</button>684                )}685              </For>686            </div>687          </Show>688        </div>689690        <Show when={error()}>691          <p class="peach-hint peach-hint-error" style="margin:0 16px 12px">{error()}</p>692        </Show>693694      </div>695    </div>696  );697}698699interface IdentitySuggestListProps {700  suggestions: Array<{ value: string; count: number; type: "email" | "username" }>;701  onPick: (value: string) => void;702  onClose?: () => void;703  listRef?: (el: HTMLDivElement) => void;704  inputRef?: () => HTMLInputElement | undefined;705}706707export function IdentitySuggestList(props: IdentitySuggestListProps) {708  const [collapsed, setCollapsed] = createSignal(false);709  const ChevronIcon = () => (710    <svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">711      <path d="M1 1L5 5L9 1" />712    </svg>713  );714715  function handleRowKeyDown(e: KeyboardEvent, value: string) {716    const row = e.currentTarget as HTMLElement;717    if (e.key === "ArrowDown") {718      e.preventDefault();719      (row.nextElementSibling as HTMLElement | null)?.focus();720    } else if (e.key === "ArrowUp") {721      e.preventDefault();722      const prev = row.previousElementSibling as HTMLElement | null;723      if (prev) prev.focus();724      else props.inputRef?.()?.focus();725    } else if (e.key === "Enter" || e.key === " ") {726      e.preventDefault();727      props.onPick(value);728    } else if (e.key === "Escape") {729      e.preventDefault();730      props.onClose?.();731    }732  }733734  return (735    <div class="peach-identity-suggestions" ref={props.listRef}>736      <div class="peach-identity-filter-row" style="justify-content:flex-end">737        <button738          class={`peach-identity-collapse-btn${collapsed() ? " is-collapsed" : ""}`}739          type="button"740          onMouseDown={(e) => { e.preventDefault(); setCollapsed(c => !c); }}741          aria-label={collapsed() ? "Show suggestions" : "Hide suggestions"}742        >743          <ChevronIcon />744        </button>745      </div>746      <div class={`peach-identity-rows${collapsed() ? " is-collapsed" : ""}`}>747        <div class="peach-identity-rows-inner">748          <For each={props.suggestions}>749            {(s) => (750              <button751                class="peach-identity-suggestion"752                type="button"753                onMouseDown={(e) => { e.preventDefault(); props.onPick(s.value); }}754                onKeyDown={(e) => handleRowKeyDown(e, s.value)}755              >756                <span class="peach-identity-suggestion-value">{s.value}</span>757                <span class="peach-identity-suggestion-meta">{s.count}×</span>758              </button>759            )}760          </For>761        </div>762      </div>763    </div>764  );765}