1import { createSignal, createMemo, createEffect, For, Show, onMount } 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));3435 const isNoteEntry = () => props.entry?.type === "note";36 const isCardEntry = () => props.entry?.type === "card";37 const [selectedType, setSelectedType] = createSignal<"login" | "note" | "card">(38 isNoteEntry() ? "note" : isCardEntry() ? "card" : "login"39 );4041 42 const [cardNickname, setCardNickname] = createSignal(props.entry?.cardNickname ?? "");43 const [cardholderName, setCardholderName] = createSignal(props.entry?.cardholderName ?? "");44 const [cardNumber, setCardNumber] = createSignal(props.entry?.cardNumber ?? "");45 const [expMonth, setExpMonth] = createSignal(props.entry?.expMonth ?? "");46 const [expYear, setExpYear] = createSignal(props.entry?.expYear ?? "");47 const [cvc, setCvc] = createSignal(props.entry?.cvc ?? "");48 const [showCvc, setShowCvc] = createSignal(false);49 const [cardNumberFocused, setCardNumberFocused] = createSignal(false);50 const [noteEditorEl, setNoteEditorEl] = createSignal<HTMLDivElement | null>(null);5152 function noteExec(cmd: string, val?: string) {53 document.execCommand(cmd, false, val);54 noteEditorEl()?.focus();55 }5657 function getCardNetwork(num: string): string {58 const n = num.replace(/\s/g, '');59 if (/^4/.test(n)) return 'Visa';60 if (/^5[1-5]|^2[2-7]/.test(n)) return 'Mastercard';61 if (/^3[47]/.test(n)) return 'Amex';62 if (/^6(?:011|5)/.test(n)) return 'Discover';63 return '';64 }6566 function formatCardNumberDisplay(raw: string, focused: boolean): string {67 const n = raw.replace(/\s/g, '');68 if (!focused && n.length >= 4) return '•••• •••• •••• ' + n.slice(-4);69 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(' '));70 return n.replace(/(\d{4})(?=\d)/g, '$1 ').trim();71 }7273 const canSave = () => {74 if (!title().trim()) return false;75 if (selectedType() === "login" && !password().trim()) return false;76 if (selectedType() === "card" && (!cardholderName().trim() || !cardNumber().trim())) return false;77 return true;78 };7980 const allTags = createMemo(() => {81 const tagSet = new Set<string>();82 for (const entry of props.entries ?? []) {83 for (const tag of entry.tags ?? []) tagSet.add(tag);84 }85 return Array.from(tagSet).sort();86 });8788 const tagSuggestions = createMemo(() => {89 const input = tagInput().toLowerCase().trim();90 if (!input) return [];91 return allTags().filter(t =>92 t.toLowerCase().includes(input) && !tags().includes(t)93 ).slice(0, 5);94 });9596 function addTag(tag: string) {97 const n = tag.toLowerCase().trim();98 if (!n || n.length > 32 || tags().includes(n) || tags().length >= 10) return;99 setTags([...tags(), n]);100 }101102 function removeTag(tag: string) {103 setTags(tags().filter(t => t !== tag));104 }105106 function handleTagKeyDown(e: KeyboardEvent) {107 if (e.key === "Enter" || e.key === ",") {108 e.preventDefault();109 if (tagInput()) { addTag(tagInput()); setTagInput(""); setShowTagSuggestions(false); }110 } else if (e.key === "Backspace" && !tagInput() && tags().length > 0) {111 removeTag(tags()[tags().length - 1]);112 }113 }114115 116 createEffect(async () => {117 const pwd = password();118 if (pwd.length < 4) { setPasswordStrength(null); return; }119 try {120 if (!zxcvbnFn()) {121 const mod = await import("zxcvbn");122 setZxcvbnFn(() => mod.default);123 }124 const fn = zxcvbnFn();125 if (fn) setPasswordStrength(fn(pwd).score);126 } catch {127 setPasswordStrength(pwd.length >= 16 ? 3 : pwd.length >= 12 ? 2 : 1);128 }129 });130131 onMount(() => {132 const el = document.querySelector(".peach-new-title-input") as HTMLInputElement | null;133 if (el) el.focus();134 });135136 function getNormalizedTotp(): string | undefined {137 const value = totp().trim();138 if (!value) return undefined;139 if (value.startsWith("otpauth://")) {140 const parsed = parseOtpauthURI(value);141 return parsed?.secret ?? value;142 }143 return value;144 }145146 async function handleSave() {147 if (!canSave()) {148 setError(149 selectedType() === "note"150 ? "title is required"151 : selectedType() === "card"152 ? "cardholder name and card number are required"153 : "title and password are required"154 );155 return;156 }157158 setSaving(true);159 setError("");160161 const payload: Record<string, unknown> = {162 type: selectedType(),163 title: title().trim(),164 notes: notes().trim() || undefined,165 tags: tags().length > 0 ? tags() : undefined,166 };167168 if (selectedType() === "login") {169 payload.username = username().trim();170 payload.password = password();171 payload.url = url().trim();172 payload.totp = getNormalizedTotp();173 }174175 if (selectedType() === "card") {176 const raw = cardNumber().replace(/\s/g, '');177 payload.cardholderName = cardholderName().trim();178 payload.cardNumber = raw;179 payload.expMonth = expMonth().trim();180 payload.expYear = expYear().trim();181 payload.cvc = cvc().trim();182 payload.cardNickname = cardNickname().trim() || undefined;183 const n = raw;184 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';185 payload.last4 = raw.slice(-4);186 }187188 if (props.entry) {189 const res = await sendMessage({ type: "UPDATE_ENTRY", payload: { id: props.entry.id, patch: payload } });190 const result = res as { ok: boolean; error?: string };191 if (!result.ok) { setError(result.error ?? "could not update entry"); setSaving(false); return; }192 await props.onSave({ ...props.entry, ...payload } as VaultEntry);193 return;194 }195196 const res = await sendMessage({ type: "ADD_ENTRY", payload });197 const result = res as { ok: boolean; data?: VaultEntry; error?: string };198 if (!result.ok) { setError(result.error ?? "could not save entry"); setSaving(false); return; }199 await props.onSave(result.data);200 }201202 const strengthLabel = () => {203 const s = passwordStrength();204 if (s === null) return null;205 return ["weak", "weak", "fair", "good", "strong"][s] as string;206 };207208 return (209 <div class="peach-overlay-view ov-enter-right" style="display:flex">210 <div class="peach-overlay-header">211 <button212 class="peach-btn peach-btn--ghost peach-btn--sm peach-overlay-action"213 onClick={props.onBack}214 >215 cancel216 </button>217 <span class="peach-overlay-title">218 {props.entry ? "edit entry" : "new entry"}219 </span>220 <button221 class="peach-btn peach-btn--accent peach-btn--sm peach-overlay-action"222 onClick={() => void handleSave()}223 disabled={saving() || !canSave()}224 >225 {saving() ? "saving…" : props.entry ? "save" : "create"}226 </button>227 </div>228229 {}230 <div class="peach-entry-body peach-entry-body--new">231232 {}233 <Show when={!props.entry}>234 <div class="peach-new-type-row">235 <button236 class={`peach-new-type-btn ${selectedType() === "login" ? "is-active" : ""}`}237 onClick={() => setSelectedType("login")}238 >login</button>239 <button240 class={`peach-new-type-btn ${selectedType() === "note" ? "is-active" : ""}`}241 onClick={() => setSelectedType("note")}242 >note</button>243 <button244 class={`peach-new-type-btn ${selectedType() === "card" ? "is-active" : ""}`}245 onClick={() => setSelectedType("card")}246 >card</button>247 </div>248 </Show>249250 {}251 <Show when={selectedType() === "note"}>252 <Toolbar exec={noteExec} class="peach-note-toolbar-body" />253 </Show>254255 {}256 <div class="peach-new-title-wrap">257 <input258 class="peach-new-title-input"259 placeholder={selectedType() === "note" ? "note title" : "entry name"}260 autocomplete="off"261 value={title()}262 onInput={(e) => setTitle((e.currentTarget as HTMLInputElement).value)}263 onKeyDown={(e) => { if (e.key === "Enter") void handleSave(); }}264 />265 </div>266267 {}268 <Show when={selectedType() === "login"}>269 <div class="peach-domain">270 <input271 class="peach-domain-value peach-domain-value--edit"272 placeholder="domain.com"273 autocomplete="off"274 value={url()}275 onInput={(e) => setUrl((e.currentTarget as HTMLInputElement).value)}276 />277 </div>278279 <section class="peach-fields">280 {}281 <div class="peach-field-card">282 <span class="peach-label">username</span>283 <div class="peach-field-value-row">284 <input285 class="peach-field-value peach-field-value--edit"286 placeholder="username or email"287 autocomplete="off"288 value={username()}289 onInput={(e) => setUsername((e.currentTarget as HTMLInputElement).value)}290 />291 </div>292 </div>293294 {}295 <div class="peach-field-card">296 <span class="peach-label">password</span>297 <div class="peach-password-edit-row">298 <input299 class="peach-field-value peach-field-value--edit"300 type={showPassword() ? "text" : "password"}301 placeholder="password"302 autocomplete="new-password"303 value={password()}304 onInput={(e) => setPassword((e.currentTarget as HTMLInputElement).value)}305 />306 <button307 class="peach-inline-action peach-password-toggle-btn"308 type="button"309 onClick={() => setShowPassword(!showPassword())}310 aria-label={showPassword() ? "Hide password" : "Show password"}311 >312 <Show313 when={showPassword()}314 fallback={315 <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">316 <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" />317 <circle cx="7" cy="5" r="1.75" />318 </svg>319 }320 >321 <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">322 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />323 <path d="M3.5 5.5L2.5 7.5" />324 <path d="M7 6.5V8.5" />325 <path d="M10.5 5.5L11.5 7.5" />326 </svg>327 </Show>328 </button>329 </div>330331 {}332 <Show when={strengthLabel() !== null}>333 <div class="peach-strength-hairline">334 <div class="peach-strength-hairline-track">335 <div336 class="peach-strength-hairline-fill"337 style={{338 width: ["25%","40%","60%","80%","100%"][passwordStrength()!],339 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()!],340 }}341 />342 </div>343 <span class="peach-strength-label">{strengthLabel()}</span>344 </div>345 </Show>346347 {}348 <button349 class="peach-generate-toggle-link"350 type="button"351 onClick={() => { setShowGenerator(!showGenerator()); }}352 >353 {showGenerator() ? "☰ hide generator" : "⚙ generate"}354 </button>355 <GeneratorDrawer356 compact357 open={showGenerator()}358 onUse={(pw) => { setPassword(pw); setShowGenerator(false); }}359 />360 </div>361362 {}363 <Show when={showTotp() || totp()}>364 <div class="peach-field-card">365 <span class="peach-label">2fa secret</span>366 <div class="peach-field-value-row">367 <input368 class="peach-field-value peach-field-value--edit"369 placeholder="BASE32 or otpauth:// URI"370 autocomplete="off"371 value={totp()}372 onInput={(e) => setTotp((e.currentTarget as HTMLInputElement).value)}373 />374 </div>375 </div>376 </Show>377 </section>378 </Show>379380 {}381 <Show when={selectedType() === "card"}>382 <section class="peach-fields">383 {}384 <div class="peach-field-card">385 <span class="peach-label">nickname</span>386 <div class="peach-field-value-row">387 <input class="peach-field-value peach-field-value--edit" placeholder="Personal Visa"388 autocomplete="off" value={cardNickname()}389 onInput={(e) => setCardNickname((e.currentTarget as HTMLInputElement).value)} />390 </div>391 </div>392 {}393 <div class="peach-field-card">394 <span class="peach-label">cardholder name</span>395 <div class="peach-field-value-row">396 <input class="peach-field-value peach-field-value--edit" placeholder="Jane Smith"397 autocomplete="cc-name" value={cardholderName()}398 onInput={(e) => setCardholderName((e.currentTarget as HTMLInputElement).value)} />399 </div>400 </div>401 {}402 <div class="peach-field-card">403 <span class="peach-label">404 card number405 <Show when={getCardNetwork(cardNumber())}>406 <span class="peach-card-network-badge">{getCardNetwork(cardNumber())}</span>407 </Show>408 </span>409 <div class="peach-field-value-row">410 <input class="peach-field-value peach-field-value--edit peach-card-number"411 placeholder="•••• •••• •••• ••••"412 autocomplete="cc-number" inputmode="numeric" maxLength={19}413 value={formatCardNumberDisplay(cardNumber(), cardNumberFocused())}414 onFocus={() => setCardNumberFocused(true)}415 onBlur={() => setCardNumberFocused(false)}416 onInput={(e) => {417 const raw = (e.currentTarget as HTMLInputElement).value.replace(/\s/g, '');418 setCardNumber(raw);419 }} />420 </div>421 </div>422 {}423 <div class="peach-field-card">424 <span class="peach-label">expiry</span>425 <div class="peach-card-expiry-row">426 <input class="peach-field-value peach-field-value--edit" placeholder="MM"427 autocomplete="cc-exp-month" inputmode="numeric" maxLength={2} style="width:56px"428 value={expMonth()}429 onInput={(e) => setExpMonth((e.currentTarget as HTMLInputElement).value)} />430 <span class="peach-card-expiry-sep">/</span>431 <input class="peach-field-value peach-field-value--edit" placeholder="YYYY"432 autocomplete="cc-exp-year" inputmode="numeric" maxLength={4} style="width:72px"433 value={expYear()}434 onInput={(e) => setExpYear((e.currentTarget as HTMLInputElement).value)} />435 </div>436 </div>437 {}438 <div class="peach-field-card">439 <span class="peach-label">CVC</span>440 <div class="peach-field-value-row">441 <input class="peach-field-value peach-field-value--edit"442 type={showCvc() ? "text" : "password"} placeholder="•••"443 autocomplete="cc-csc" inputmode="numeric" maxLength={4}444 value={cvc()}445 onInput={(e) => setCvc((e.currentTarget as HTMLInputElement).value)} />446 <button class="peach-inline-action peach-password-toggle-btn" type="button"447 onClick={() => setShowCvc(!showCvc())} aria-label={showCvc() ? "Hide CVC" : "Show CVC"}>448 <Show when={showCvc()} fallback={449 <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">450 <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" />451 <circle cx="7" cy="5" r="1.75" />452 </svg>453 }>454 <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">455 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />456 </svg>457 </Show>458 </button>459 </div>460 </div>461 </section>462 </Show>463464 {}465 <Show when={selectedType() === "note"}>466 <div class="peach-note-body">467 <NoteEditorInline468 initialContent={notes()}469 onContentChange={setNotes}470 onReady={(el) => setNoteEditorEl(el)}471 />472 </div>473 </Show>474475 {}476 <Show when={selectedType() === "login" && (showNotes() || notes())}>477 <div class="peach-field-card" style="margin:0 12px">478 <span class="peach-label">notes</span>479 <textarea480 class="peach-new-textarea"481 placeholder="anything worth remembering"482 value={notes()}483 onInput={(e) => setNotes((e.currentTarget as HTMLTextAreaElement).value)}484 />485 </div>486 </Show>487488 {}489 <div class="peach-entry-add-links">490 <Show when={selectedType() === "login" && !showTotp() && !totp()}>491 <button class="peach-add-field-link" type="button" onClick={() => setShowTotp(true)}>492 + add 2FA493 </button>494 </Show>495 <Show when={selectedType() === "login" && !showNotes() && !notes()}>496 <button class="peach-add-field-link" type="button" onClick={() => setShowNotes(true)}>497 + add notes498 </button>499 </Show>500 </div>501502 {}503 <div class="peach-field-card" style="margin:4px 12px 12px">504 <span class="peach-label">tags</span>505 <div class="peach-tag-input-wrap">506 <For each={tags()}>507 {(tag) => (508 <span class="peach-tag-chip">509 {tag}510 <button class="peach-tag-chip-remove" onClick={() => removeTag(tag)} aria-label={`Remove ${tag}`}>×</button>511 </span>512 )}513 </For>514 <input515 class="peach-tag-input"516 placeholder={tags().length === 0 ? "add tags…" : ""}517 value={tagInput()}518 onInput={(e) => { setTagInput((e.currentTarget as HTMLInputElement).value); setShowTagSuggestions(true); }}519 onKeyDown={handleTagKeyDown}520 onFocus={() => setShowTagSuggestions(true)}521 onBlur={() => setTimeout(() => setShowTagSuggestions(false), 150)}522 style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"523 />524 </div>525 <Show when={showTagSuggestions() && tagSuggestions().length > 0}>526 <div class="peach-tag-suggestions" style="margin-top:4px;">527 <For each={tagSuggestions()}>528 {(s) => (529 <button530 class="peach-tag-suggestion"531 onMouseDown={() => { addTag(s); setTagInput(""); setShowTagSuggestions(false); }}532 >{s}</button>533 )}534 </For>535 </div>536 </Show>537 </div>538539 <Show when={error()}>540 <p class="peach-hint peach-hint-error" style="margin:0 16px 12px">{error()}</p>541 </Show>542543 </div>544 </div>545 );546}