Add.tsx

32.0 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() === "card" && (!cardholderName().trim() || !cardNumber().trim())) return false;125    return true;126  };127128  const allTags = createMemo(() => {129    const tagSet = new Set<string>();130    for (const entry of props.entries ?? []) {131      for (const tag of entry.tags ?? []) tagSet.add(tag);132    }133    return Array.from(tagSet).sort();134  });135136  const tagSuggestions = createMemo(() => {137    const input = tagInput().toLowerCase().trim();138    if (!input) return [];139    return allTags().filter(t =>140      t.toLowerCase().includes(input) && !tags().includes(t)141    ).slice(0, 5);142  });143144  function addTag(tag: string) {145    const n = tag.toLowerCase().trim();146    if (!n || n.length > 32 || tags().includes(n) || tags().length >= 10) return;147    setTags([...tags(), n]);148  }149150  function removeTag(tag: string) {151    setTags(tags().filter(t => t !== tag));152  }153154  function handleTagKeyDown(e: KeyboardEvent) {155    if (e.key === "Enter" || e.key === ",") {156      e.preventDefault();157      if (tagInput()) { addTag(tagInput()); setTagInput(""); setShowTagSuggestions(false); }158    } else if (e.key === "Backspace" && !tagInput() && tags().length > 0) {159      removeTag(tags()[tags().length - 1]);160    }161  }162163  // Strength check164  createEffect(async () => {165    const pwd = password();166    if (pwd.length < 4) { setPasswordStrength(null); return; }167    try {168      if (!zxcvbnFn()) {169        const mod = await import("zxcvbn");170        setZxcvbnFn(() => mod.default);171      }172      const fn = zxcvbnFn();173      if (fn) setPasswordStrength(fn(pwd).score);174    } catch {175      setPasswordStrength(pwd.length >= 16 ? 3 : pwd.length >= 12 ? 2 : 1);176    }177  });178179  onMount(() => {180    const el = document.querySelector(".peach-new-title-input") as HTMLInputElement | null;181    if (el) el.focus();182    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {183      const tabUrl = tabs[0]?.url;184      if (tabUrl && tabUrl.startsWith("http")) setCurrentTabUrl(tabUrl);185    });186    // Keep the vault alive while the form is open — the auto-lock alarm fires on187    // a timer and doesn't know the user is actively filling in a new entry.188    const keepAlive = setInterval(() => {189      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});190    }, 30_000);191    onCleanup(() => clearInterval(keepAlive));192  });193194  function getNormalizedTotp(): string | undefined {195    const value = totp().trim();196    if (!value) return undefined;197    if (value.startsWith("otpauth://")) {198      const parsed = parseOtpauthURI(value);199      return parsed?.secret ?? value;200    }201    return value;202  }203204  async function handleSave() {205    if (!canSave()) {206      setError(207        selectedType() === "note"208          ? "title is required"209          : selectedType() === "card"210          ? "cardholder name and card number are required"211          : "title is required"212      );213      return;214    }215216    setSaving(true);217    setError("");218219    const payload: Record<string, unknown> = {220      type: selectedType(),221      title: title().trim(),222      notes: notes().trim() || undefined,223      tags: tags().length > 0 ? tags() : undefined,224    };225226    if (selectedType() === "login") {227      payload.username = username().trim();228      payload.email = email().trim() || undefined;229      payload.password = password();230      payload.url = url().trim();231      payload.totp = getNormalizedTotp();232    }233234    if (selectedType() === "card") {235      const raw = cardNumber().replace(/\s/g, '');236      payload.cardholderName = cardholderName().trim();237      payload.cardNumber = raw;238      payload.expMonth = expMonth().trim();239      payload.expYear = expYear().trim();240      payload.cvc = cvc().trim();241      payload.cardNickname = cardNickname().trim() || undefined;242      const n = raw;243      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';244      payload.last4 = raw.slice(-4);245    }246247    if (props.entry) {248      const res = await sendMessage({ type: "UPDATE_ENTRY", payload: { id: props.entry.id, patch: payload } });249      const result = res as { ok: boolean; error?: string };250      if (!result.ok) { setError(result.error ?? "could not update entry"); setSaving(false); return; }251      await props.onSave({ ...props.entry, ...payload } as VaultEntry);252      return;253    }254255    const res = await sendMessage({ type: "ADD_ENTRY", payload });256    const result = res as { ok: boolean; data?: VaultEntry; error?: string };257    if (!result.ok) {258      if (result.error === "vault_locked") {259        setError("vault is locked — tap the lock icon to re-enter your master password");260      } else {261        setError(result.error ?? "could not save entry");262      }263      setSaving(false);264      return;265    }266    await props.onSave(result.data);267  }268269  const strengthLabel = () => {270    const s = passwordStrength();271    if (s === null) return null;272    return ["weak", "weak", "fair", "good", "strong"][s] as string;273  };274275  return (276    <div class="peach-overlay-view ov-enter-right" style="display:flex">277      <div class="peach-overlay-header">278        <button279          class="peach-btn peach-btn--ghost peach-btn--sm peach-overlay-action"280          onClick={props.onBack}281        >282          cancel283        </button>284        <span class="peach-overlay-title">285          {props.entry ? "edit entry" : "new entry"}286        </span>287        <button288          class="peach-btn peach-btn--accent peach-btn--sm peach-overlay-action"289          onClick={() => void handleSave()}290          disabled={saving() || !canSave()}291        >292          {saving() ? "saving…" : props.entry ? "save" : "create"}293        </button>294      </div>295296      {/* ── Body — mirrors Entry.tsx field-card structure ── */}297      <div class="peach-entry-body peach-entry-body--new">298299        {/* Type toggle */}300        <Show when={!props.entry}>301          <div class="peach-new-type-row">302            <button303              class={`peach-new-type-btn ${selectedType() === "login" ? "is-active" : ""}`}304              onClick={() => setSelectedType("login")}305            >login</button>306            <button307              class={`peach-new-type-btn ${selectedType() === "note" ? "is-active" : ""}`}308              onClick={() => setSelectedType("note")}309            >note</button>310            <button311              class={`peach-new-type-btn ${selectedType() === "card" ? "is-active" : ""}`}312              onClick={() => setSelectedType("card")}313            >card</button>314          </div>315        </Show>316317        {/* Note formatting toolbar — own row so it never overflows */}318        <Show when={selectedType() === "note"}>319          <Toolbar exec={noteExec} class="peach-note-toolbar-body" />320        </Show>321322        {/* Title */}323        <div class="peach-new-title-wrap">324          <input325            class="peach-new-title-input"326            placeholder={selectedType() === "note" ? "note title" : "entry name"}327            autocomplete="off"328            value={title()}329            onInput={(e) => setTitle((e.currentTarget as HTMLInputElement).value)}330            onKeyDown={(e) => { if (e.key === "Enter") void handleSave(); }}331          />332        </div>333334        {/* ── Login fields ── */}335        <Show when={selectedType() === "login"}>336          <div class="peach-domain">337            <div class="peach-domain-edit-row">338              <input339                class="peach-domain-value peach-domain-value--edit"340                placeholder="domain.com"341                autocomplete="off"342                value={url()}343                onInput={(e) => setUrl((e.currentTarget as HTMLInputElement).value)}344              />345              <Show when={currentTabUrl()}>346                <button347                  class="peach-domain-url-btn"348                  type="button"349                  onClick={() => setUrl(currentTabUrl())}350                  title="Insert current page URL"351                >352                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">353                    <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" />354                    <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" />355                  </svg>356                </button>357              </Show>358            </div>359          </div>360361          <section class="peach-fields">362            {/* Username */}363            <div class="peach-field-card">364              <span class="peach-label">username</span>365              <div class="peach-field-value-row">366                <input367                  ref={(el) => (usernameInputEl = el)}368                  class="peach-field-value peach-field-value--edit"369                  placeholder="johndoe"370                  autocomplete="off"371                  value={username()}372                  onInput={(e) => setUsername((e.currentTarget as HTMLInputElement).value)}373                  onFocus={() => openIdentityField("username")}374                  onBlur={(e) => {375                    if (usernameSuggestEl?.contains(e.relatedTarget as Node)) return;376                    setTimeout(() => { if (activeIdentityField() === "username") setActiveIdentityField(null); }, 150);377                  }}378                  onKeyDown={(e) => {379                    if (activeIdentityField() !== "username") return;380                    if (e.key === "ArrowDown") {381                      e.preventDefault();382                      usernameSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();383                    } else if (e.key === "Escape") {384                      e.preventDefault();385                      setActiveIdentityField(null);386                    }387                  }}388                />389              </div>390              <Show when={activeIdentityField() === "username" && identitySuggestions().length > 0}>391                <IdentitySuggestList392                  listRef={(el) => (usernameSuggestEl = el)}393                  inputRef={() => usernameInputEl}394                  suggestions={identitySuggestions()}395                  onPick={(v) => { setUsername(v); setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}396                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; usernameInputEl?.focus(); }}397                />398              </Show>399            </div>400401            {/* Email */}402            <div class="peach-field-card">403              <span class="peach-label">email</span>404              <div class="peach-field-value-row">405                <input406                  ref={(el) => (emailInputEl = el)}407                  class="peach-field-value peach-field-value--edit"408                  type="email"409                  placeholder="[email protected]"410                  autocomplete="off"411                  value={email()}412                  onInput={(e) => setEmail((e.currentTarget as HTMLInputElement).value)}413                  onFocus={() => openIdentityField("email")}414                  onBlur={(e) => {415                    if (emailSuggestEl?.contains(e.relatedTarget as Node)) return;416                    setTimeout(() => { if (activeIdentityField() === "email") setActiveIdentityField(null); }, 150);417                  }}418                  onKeyDown={(e) => {419                    if (activeIdentityField() !== "email") return;420                    if (e.key === "ArrowDown") {421                      e.preventDefault();422                      emailSuggestEl?.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();423                    } else if (e.key === "Escape") {424                      e.preventDefault();425                      setActiveIdentityField(null);426                    }427                  }}428                />429              </div>430              <Show when={activeIdentityField() === "email" && identitySuggestions().length > 0}>431                <IdentitySuggestList432                  listRef={(el) => (emailSuggestEl = el)}433                  inputRef={() => emailInputEl}434                  suggestions={identitySuggestions()}435                  onPick={(v) => { setEmail(v); setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}436                  onClose={() => { setActiveIdentityField(null); suppressIdentityOpen = true; emailInputEl?.focus(); }}437                />438              </Show>439            </div>440441            {/* Password */}442            <div class="peach-field-card">443              <span class="peach-label">password</span>444              <Show when={!showGenerator()}>445                <div class="peach-password-edit-row">446                  <input447                    class="peach-field-value peach-field-value--edit"448                    type={showPassword() ? "text" : "password"}449                    placeholder="password"450                    autocomplete="new-password"451                    value={password()}452                    onInput={(e) => setPassword((e.currentTarget as HTMLInputElement).value)}453                  />454                  <button455                    class="peach-inline-action peach-password-toggle-btn"456                    type="button"457                    onClick={() => setShowPassword(!showPassword())}458                    aria-label={showPassword() ? "Hide password" : "Show password"}459                  >460                    <Show461                      when={showPassword()}462                      fallback={463                        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">464                          <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" />465                          <circle cx="7" cy="5" r="1.75" />466                        </svg>467                      }468                    >469                      <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">470                        <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />471                        <path d="M3.5 5.5L2.5 7.5" />472                        <path d="M7 6.5V8.5" />473                        <path d="M10.5 5.5L11.5 7.5" />474                      </svg>475                    </Show>476                  </button>477                </div>478              </Show>479480              {/* Strength */}481              <Show when={strengthLabel() !== null}>482                <div class="peach-strength-hairline">483                  <div class="peach-strength-hairline-track">484                    <div485                      class="peach-strength-hairline-fill"486                      style={{487                        width: ["25%","40%","60%","80%","100%"][passwordStrength()!],488                        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()!],489                      }}490                    />491                  </div>492                  <span class="peach-strength-label">{strengthLabel()}</span>493                </div>494              </Show>495496              {/* Generator toggle */}497              <button498                class="peach-generate-toggle-link"499                type="button"500                onClick={() => { setShowGenerator(!showGenerator()); }}501              >502                {showGenerator() ? "☰ hide generator" : "⚙ generate"}503              </button>504              <GeneratorDrawer505                compact506                open={showGenerator()}507                onChange={(pw) => setPassword(pw)}508                onUse={(pw) => { setPassword(pw); setShowGenerator(false); }}509              />510            </div>511512            {/* 2FA — optional */}513            <Show when={showTotp() || totp()}>514              <div class="peach-field-card">515                <span class="peach-label">2fa secret</span>516                <div class="peach-field-value-row">517                  <input518                    class="peach-field-value peach-field-value--edit"519                    placeholder="BASE32 or otpauth:// URI"520                    autocomplete="off"521                    value={totp()}522                    onInput={(e) => setTotp((e.currentTarget as HTMLInputElement).value)}523                  />524                </div>525              </div>526            </Show>527          </section>528        </Show>529530        {/* ── Card fields ── */}531        <Show when={selectedType() === "card"}>532          <section class="peach-fields">533            {/* Nickname */}534            <div class="peach-field-card">535              <span class="peach-label">nickname</span>536              <div class="peach-field-value-row">537                <input class="peach-field-value peach-field-value--edit" placeholder="Personal Visa"538                  autocomplete="off" value={cardNickname()}539                  onInput={(e) => setCardNickname((e.currentTarget as HTMLInputElement).value)} />540              </div>541            </div>542            {/* Cardholder name */}543            <div class="peach-field-card">544              <span class="peach-label">cardholder name</span>545              <div class="peach-field-value-row">546                <input class="peach-field-value peach-field-value--edit" placeholder="Jane Smith"547                  autocomplete="cc-name" value={cardholderName()}548                  onInput={(e) => setCardholderName((e.currentTarget as HTMLInputElement).value)} />549              </div>550            </div>551            {/* Card number */}552            <div class="peach-field-card">553              <span class="peach-label">554                card number555                <Show when={getCardNetwork(cardNumber())}>556                  <span class="peach-card-network-badge">{getCardNetwork(cardNumber())}</span>557                </Show>558              </span>559              <div class="peach-field-value-row">560                <input class="peach-field-value peach-field-value--edit peach-card-number"561                  placeholder="•••• •••• •••• ••••"562                  autocomplete="cc-number" inputmode="numeric" maxLength={19}563                  value={formatCardNumberDisplay(cardNumber(), cardNumberFocused())}564                  onFocus={() => setCardNumberFocused(true)}565                  onBlur={() => setCardNumberFocused(false)}566                  onInput={(e) => {567                    const raw = (e.currentTarget as HTMLInputElement).value.replace(/\s/g, '');568                    setCardNumber(raw);569                  }} />570              </div>571            </div>572            {/* Expiry */}573            <div class="peach-field-card">574              <span class="peach-label">expiry</span>575              <div class="peach-card-expiry-row">576                <input class="peach-field-value peach-field-value--edit" placeholder="MM"577                  autocomplete="cc-exp-month" inputmode="numeric" maxLength={2} style="width:56px"578                  value={expMonth()}579                  onInput={(e) => setExpMonth((e.currentTarget as HTMLInputElement).value)} />580                <span class="peach-card-expiry-sep">/</span>581                <input class="peach-field-value peach-field-value--edit" placeholder="YYYY"582                  autocomplete="cc-exp-year" inputmode="numeric" maxLength={4} style="width:72px"583                  value={expYear()}584                  onInput={(e) => setExpYear((e.currentTarget as HTMLInputElement).value)} />585              </div>586            </div>587            {/* CVC */}588            <div class="peach-field-card">589              <span class="peach-label">CVC</span>590              <div class="peach-field-value-row">591                <input class="peach-field-value peach-field-value--edit"592                  type={showCvc() ? "text" : "password"} placeholder="•••"593                  autocomplete="cc-csc" inputmode="numeric" maxLength={4}594                  value={cvc()}595                  onInput={(e) => setCvc((e.currentTarget as HTMLInputElement).value)} />596                <button class="peach-inline-action peach-password-toggle-btn" type="button"597                  onClick={() => setShowCvc(!showCvc())} aria-label={showCvc() ? "Hide CVC" : "Show CVC"}>598                  <Show when={showCvc()} fallback={599                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">600                      <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" />601                      <circle cx="7" cy="5" r="1.75" />602                    </svg>603                  }>604                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">605                      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />606                    </svg>607                  </Show>608                </button>609              </div>610            </div>611          </section>612        </Show>613614        {/* ── Note content ── */}615        <Show when={selectedType() === "note"}>616          <div class="peach-note-body">617            <NoteEditorInline618              initialContent={notes()}619              onContentChange={setNotes}620              onReady={(el) => setNoteEditorEl(el)}621            />622          </div>623        </Show>624625        {/* ── Login notes ── */}626        <Show when={selectedType() === "login" && (showNotes() || notes())}>627          <div class="peach-field-card" style="margin:0 12px">628            <span class="peach-label">notes</span>629            <textarea630              class="peach-new-textarea"631              placeholder="anything worth remembering"632              value={notes()}633              onInput={(e) => setNotes((e.currentTarget as HTMLTextAreaElement).value)}634            />635          </div>636        </Show>637638        {/* ── "+ add" optional field links ── */}639        <div class="peach-entry-add-links">640          <Show when={selectedType() === "login" && !showTotp() && !totp()}>641            <button class="peach-add-field-link" type="button" onClick={() => setShowTotp(true)}>642              + add 2FA643            </button>644          </Show>645          <Show when={selectedType() === "login" && !showNotes() && !notes()}>646            <button class="peach-add-field-link" type="button" onClick={() => setShowNotes(true)}>647              + add notes648            </button>649          </Show>650        </div>651652        {/* ── Tags ── */}653        <div class="peach-field-card" style="margin:4px 12px 12px">654          <span class="peach-label">tags</span>655          <div class="peach-tag-input-wrap">656            <For each={tags()}>657              {(tag) => (658                <span class="peach-tag-chip">659                  {tag}660                  <button class="peach-tag-chip-remove" onClick={() => removeTag(tag)} aria-label={`Remove ${tag}`}>×</button>661                </span>662              )}663            </For>664            <input665              class="peach-tag-input"666              placeholder={tags().length === 0 ? "add tags…" : ""}667              value={tagInput()}668              onInput={(e) => { setTagInput((e.currentTarget as HTMLInputElement).value); setShowTagSuggestions(true); }}669              onKeyDown={handleTagKeyDown}670              onFocus={() => setShowTagSuggestions(true)}671              onBlur={() => setTimeout(() => setShowTagSuggestions(false), 150)}672              style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"673            />674          </div>675          <Show when={showTagSuggestions() && tagSuggestions().length > 0}>676            <div class="peach-tag-suggestions" style="margin-top:4px;">677              <For each={tagSuggestions()}>678                {(s) => (679                  <button680                    class="peach-tag-suggestion"681                    onMouseDown={() => { addTag(s); setTagInput(""); setShowTagSuggestions(false); }}682                  >{s}</button>683                )}684              </For>685            </div>686          </Show>687        </div>688689        <Show when={error()}>690          <p class="peach-hint peach-hint-error" style="margin:0 16px 12px">{error()}</p>691        </Show>692693      </div>694    </div>695  );696}697698interface IdentitySuggestListProps {699  suggestions: Array<{ value: string; count: number; type: "email" | "username" }>;700  onPick: (value: string) => void;701  onClose?: () => void;702  listRef?: (el: HTMLDivElement) => void;703  inputRef?: () => HTMLInputElement | undefined;704}705706export function IdentitySuggestList(props: IdentitySuggestListProps) {707  const [collapsed, setCollapsed] = createSignal(false);708  const ChevronIcon = () => (709    <svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">710      <path d="M1 1L5 5L9 1" />711    </svg>712  );713714  function handleRowKeyDown(e: KeyboardEvent, value: string) {715    const row = e.currentTarget as HTMLElement;716    if (e.key === "ArrowDown") {717      e.preventDefault();718      (row.nextElementSibling as HTMLElement | null)?.focus();719    } else if (e.key === "ArrowUp") {720      e.preventDefault();721      const prev = row.previousElementSibling as HTMLElement | null;722      if (prev) prev.focus();723      else props.inputRef?.()?.focus();724    } else if (e.key === "Enter" || e.key === " ") {725      e.preventDefault();726      props.onPick(value);727    } else if (e.key === "Escape") {728      e.preventDefault();729      props.onClose?.();730    }731  }732733  return (734    <div class="peach-identity-suggestions" ref={props.listRef}>735      <div class="peach-identity-filter-row" style="justify-content:flex-end">736        <button737          class={`peach-identity-collapse-btn${collapsed() ? " is-collapsed" : ""}`}738          type="button"739          onMouseDown={(e) => { e.preventDefault(); setCollapsed(c => !c); }}740          aria-label={collapsed() ? "Show suggestions" : "Hide suggestions"}741        >742          <ChevronIcon />743        </button>744      </div>745      <div class={`peach-identity-rows${collapsed() ? " is-collapsed" : ""}`}>746        <div class="peach-identity-rows-inner">747          <For each={props.suggestions}>748            {(s) => (749              <button750                class="peach-identity-suggestion"751                type="button"752                onMouseDown={(e) => { e.preventDefault(); props.onPick(s.value); }}753                onKeyDown={(e) => handleRowKeyDown(e, s.value)}754              >755                <span class="peach-identity-suggestion-value">{s.value}</span>756                <span class="peach-identity-suggestion-meta">{s.count}×</span>757              </button>758            )}759          </For>760        </div>761      </div>762    </div>763  );764}