123456789101112import { ACCENT_COLORS, type PasswordPolicy } from "../shared/types";13import { generateSmartPassword } from "../shared/generate";14import { detectPasswordPolicy } from "./policy";1516let accentHex = "#E8956D";17let popupTheme: "dark" | "light" = "dark";18chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {19 const data = resp?.data;20 const name = data?.accentColor ?? "peach";21 accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";22 popupTheme = data?.theme === "light" ? "light" : "dark";23});2425262728function withAlpha(hex: string, alpha: string): string {29 30 31 32 return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;33}3435export interface SelectorEntry {36 id: string;37 title: string;38 username?: string;39 url?: string;40 hasTotp?: boolean;41}4243interface SelectorOptions {44 domain?: string;45 searchableEntries?: SelectorEntry[];46 47 isSignup?: boolean;48 4950515253 onFillFields?: (username: string, password: string) => void;54 5556575859 locked?: boolean;60 61626364 onUnlocked?: () => void;65 6667686970 onDismiss?: () => void;71}7273function getDomainFromUrl(url: string): string {74 try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }75}7677function keySvgStr(): string {78 return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="rgba(240,232,216,0.35)" stroke-width="0.95" stroke-linecap="round"><rect x="2" y="5.5" width="8" height="6" rx="1.5"/><path d="M4 5.5V4.25A2 2 0 0 1 6 2.25A2 2 0 0 1 8 4.25V5.5"/></svg>`;79}8081function plusSvgStr(): string {82 return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>`;83}8485function peachIconSvg(): string {86 87 88 89 return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 64 64" fill="none" aria-hidden="true"><path d="M32 54C16 54 8 44 8 31C8 18 17 10 27 10C28 7 30 5.5 32 5.5C34 5.5 36 7 37 10C47 10 56 18 56 31C56 44 48 54 32 54Z" fill="#D96830"/><path d="M37 8.5C40.5 3.5 48 5 46 10.5C42 11 37 8.5 37 8.5Z" fill="#7B9060"/></svg>`;90}9192function genSvgStr(): string {93 return `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round"><path d="M9.5 2A4.5 4.5 0 1 0 10.5 5.5"/><path d="M8.5 2H9.5V1"/></svg>`;94}9596function checkSvgStr(): string {97 return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="#7B9060" stroke-width="1.5" stroke-linecap="round"><path d="M4 10.5L8 14.5L16 6.5"/></svg>`;98}99100function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {101 const { hostname, origin } = location;102 const parts = hostname.split(".");103 const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",104 "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",105 "oidc", "federation", "saml", "cas", "ldap"];106 const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());107 const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;108 const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);109 return { origin, title, loginSubdomain };110}111112113114115116117export function showRememberSiteToast(118 pageDomain: string,119 entryId: string,120): void {121 const host = document.createElement("div");122 host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";123 host.style.setProperty("--peach-accent", accentHex);124 const shadow = host.attachShadow({ mode: "closed" });125126 const style = document.createElement("style");127 style.textContent = `128 .bar {129 display:flex;align-items:center;gap:10px;padding:10px 14px;130 background:#131109;border:1px solid rgba(240,232,216,0.09);131 border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);132 font-family:Inter,sans-serif;white-space:nowrap;133 animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;134 }135 @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }136 .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }137 .yes {138 padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;139 background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;140 }141 .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }142 .no {143 padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;144 background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;145 }146 `;147 shadow.appendChild(style);148149 const bar = document.createElement("div"); bar.className = "bar";150 const txt = document.createElement("span"); txt.className = "txt";151 txt.textContent = `Remember ${pageDomain} for this entry?`;152 const yesBtn = document.createElement("button"); yesBtn.className = "yes";153 yesBtn.textContent = "Remember";154 yesBtn.addEventListener("click", async () => {155 await chrome.runtime.sendMessage({156 type: "ADD_ADDITIONAL_URL",157 payload: { id: entryId, url: location.origin },158 });159 host.remove();160 });161 const noBtn = document.createElement("button"); noBtn.className = "no";162 noBtn.textContent = "Not now";163 noBtn.addEventListener("click", () => host.remove());164 bar.append(txt, yesBtn, noBtn);165 shadow.appendChild(bar);166 document.body.appendChild(host);167 setTimeout(() => host.remove(), 9000);168}169170function generatePasswordForSite(policy: PasswordPolicy = {}): string {171 return generateSmartPassword(policy);172}173174export function observeAnchorPosition(175 anchorEl: HTMLElement,176 onUpdate: () => void177): () => void {178 let rafId = 0;179 let burstUntil = 0;180181 const runUpdate = () => {182 rafId = 0;183 onUpdate();184 if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);185 };186 const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };187 const scheduleBurst = (ms = 220) => {188 burstUntil = Math.max(burstUntil, performance.now() + ms);189 scheduleUpdate();190 };191192 const resizeObserver = new ResizeObserver(() => scheduleBurst());193 resizeObserver.observe(anchorEl);194 if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);195196 const mutationObserver = new MutationObserver(() => scheduleBurst());197 mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });198 if (anchorEl.parentElement) {199 mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });200 }201202 const onScroll = () => scheduleUpdate();203 window.addEventListener("scroll", onScroll, true);204 window.addEventListener("resize", onScroll);205 window.visualViewport?.addEventListener("resize", onScroll);206 window.visualViewport?.addEventListener("scroll", onScroll);207 anchorEl.addEventListener("focus", () => scheduleBurst());208 anchorEl.addEventListener("input", () => scheduleBurst());209210 scheduleBurst(260);211212 return () => {213 if (rafId) cancelAnimationFrame(rafId);214 resizeObserver.disconnect();215 mutationObserver.disconnect();216 window.removeEventListener("scroll", onScroll, true);217 window.removeEventListener("resize", onScroll);218 window.visualViewport?.removeEventListener("resize", onScroll);219 window.visualViewport?.removeEventListener("scroll", onScroll);220 };221}222223export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {224 const button = document.createElement("button");225 button.type = "button";226 button.setAttribute("aria-label", "Peach autofill");227 button.title = "Fill with Peach";228 button.innerHTML = peachIconSvg();229 230 231 232 233 button.style.cssText = `234 position: fixed; z-index: 2147483646;235 width: 26px; height: 26px; cursor: pointer;236 pointer-events: auto; border: none; padding: 3px;237 display: inline-flex; align-items: center; justify-content: center;238 background: transparent; border-radius: 999px;239 transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;240 opacity: 0;241 `;242 button.addEventListener("mouseenter", () => {243 button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;244 button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;245 button.style.transform = "scale(1.08)";246 });247 button.addEventListener("mouseleave", () => {248 button.style.background = "transparent";249 button.style.boxShadow = "none";250 button.style.transform = "none";251 });252 button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });253 button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });254255 document.body.appendChild(button);256257 function updatePosition() {258 const rect = field.getBoundingClientRect();259 if (rect.width === 0 || rect.height === 0) {260 button.style.opacity = "0"; button.style.pointerEvents = "none";261 return;262 }263 const sz = 26;264 const inset = Math.max(5, Math.min(10, rect.height * 0.22));265 const top = rect.top + rect.height / 2 - sz / 2;266 267 268 const minLeft = rect.left + 4;269 const left = Math.max(minLeft, rect.right - sz - inset);270 271 if (rect.width < 40) {272 button.style.opacity = "0"; button.style.pointerEvents = "none";273 return;274 }275 button.style.top = `${top}px`;276 button.style.left = `${left}px`;277 button.style.opacity = "1"; button.style.pointerEvents = "auto";278 }279 updatePosition();280 requestAnimationFrame(() => { button.style.opacity = "1"; });281 const stopObserving = observeAnchorPosition(field, updatePosition);282 return () => { stopObserving(); button.remove(); };283}284285286287288289290291const SELECTOR_STYLES = `292 :host { all: initial; }293 *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }294295 .peach-inline-popup[data-theme="dark"] {296 --peach-bg: #1a1410;297 --peach-bg-card: #221c16;298 --peach-text: #f5f0ea;299 --peach-text-dim: #8a7a6a;300 --peach-text-muted: #4a3a2a;301 --peach-border: rgba(255,255,255,0.07);302 --peach-input-bg: rgba(255,255,255,0.05);303 --peach-input-border: rgba(255,255,255,0.08);304 }305 .peach-inline-popup[data-theme="light"] {306 --peach-bg: #fdf8f4;307 --peach-bg-card: #f5ede4;308 --peach-text: #1c1310;309 --peach-text-dim: #6b5a4a;310 --peach-text-muted: #a89080;311 --peach-border: rgba(0,0,0,0.08);312 --peach-input-bg: rgba(0,0,0,0.04);313 --peach-input-border: rgba(0,0,0,0.10);314 }315316 .peach-inline-popup {317 background: var(--peach-bg);318 border: 1px solid var(--peach-border-accent, var(--peach-border));319 border-radius: 14px;320 overflow: hidden;321 box-shadow:322 0 8px 40px var(--peach-glow, transparent),323 0 2px 12px rgba(0,0,0,0.5);324 font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;325 animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;326 }327 /* Light theme: shadow against a light page is too strong otherwise — drop both328 the accent glow and the dark drop-shadow opacity to keep the popup elegant. */329 .peach-inline-popup[data-theme="light"] {330 box-shadow:331 0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),332 0 2px 12px rgba(0,0,0,0.12);333 }334 .peach-inline-popup.is-exiting {335 animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;336 pointer-events: none;337 }338339 @keyframes peach-enter {340 0% { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }341 65% { opacity: 1; filter: blur(0); }342 100% { opacity: 1; transform: translateY(0) scale(1); }343 }344 @keyframes peach-exit {345 0% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }346 100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }347 }348 @keyframes peach-slide-in {349 from { opacity: 0; transform: translateX(12px); }350 to { opacity: 1; transform: translateX(0); }351 }352 @keyframes peach-slide-back {353 from { opacity: 0; transform: translateX(-12px); }354 to { opacity: 1; transform: translateX(0); }355 }356 .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }357 .peach-content[data-dir="back"] { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }358359 /* Domain header */360 .domain-header {361 padding: 9px 13px 7px;362 border-bottom: 1px solid var(--peach-border);363 display: flex; align-items: center; justify-content: space-between;364 }365 .domain-eyebrow {366 font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;367 color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;368 }369 .domain-name {370 font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);371 font-family: "IBM Plex Mono", monospace;372 }373374 /* Search */375 .search-wrap {376 padding: 9px 12px 7px;377 border-bottom: 1px solid var(--peach-border);378 }379 .search {380 width: 100%; background: var(--peach-input-bg);381 border: 1px solid var(--peach-input-border);382 border-radius: 7px; color: var(--peach-text); padding: 7px 10px;383 font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;384 transition: border-color 120ms, box-shadow 120ms;385 }386 .search:focus {387 border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);388 box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);389 }390 .search::placeholder { color: var(--peach-text-muted); }391392 /* Results */393 .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }394 .results::-webkit-scrollbar { display: none; }395396 /* Entry rows */397 .entry {398 display: flex; align-items: center; padding: 8px 12px;399 cursor: pointer; border-bottom: 1px solid var(--peach-border);400 transition: background 70ms; position: relative; outline: none;401 }402 .entry:last-child { border-bottom: none; }403 .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }404 .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }405 .entry.focused::before {406 content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;407 width: 2px; border-radius: 2px;408 background: color-mix(in srgb, var(--peach-accent) 55%, transparent);409 }410411 .entry-icon {412 width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;413 background: var(--peach-input-bg); border: 1px solid var(--peach-border);414 display: flex; align-items: center; justify-content: center;415 overflow: hidden; margin-right: 10px;416 }417 .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }418 .entry-icon.is-new {419 background: color-mix(in srgb, var(--peach-accent) 8%, transparent);420 border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);421 color: color-mix(in srgb, var(--peach-accent) 80%, transparent);422 }423424 .entry-info { flex: 1; min-width: 0; }425 .entry-title {426 font-size: 12.5px; color: var(--peach-text);427 white-space: nowrap; overflow: hidden; text-overflow: ellipsis;428 line-height: 1.3;429 }430 .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }431 .entry-sub {432 font-size: 10px; color: var(--peach-text-dim);433 font-family: "IBM Plex Mono", monospace;434 white-space: nowrap; overflow: hidden; text-overflow: ellipsis;435 margin-top: 1px;436 }437438 .totp-badge {439 font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;440 border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);441 color: color-mix(in srgb, var(--peach-accent) 75%, transparent);442 font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;443 }444445 .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }446447 .empty-hint {448 padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);449 font-family: "IBM Plex Mono", monospace;450 }451452 /* Create form */453 .create-form-wrap {454 animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;455 }456 .create-head {457 display: flex; align-items: center; gap: 8px;458 padding: 10px 12px; border-bottom: 1px solid var(--peach-border);459 }460 .back-btn {461 background: transparent; border: none; cursor: pointer;462 color: var(--peach-text-dim); padding: 3px; border-radius: 5px;463 display: flex; align-items: center; line-height: 0;464 transition: color 100ms, background 100ms;465 }466 .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }467 .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }468 .create-body { padding: 12px; display: grid; gap: 9px; }469 .f-group { display: grid; gap: 3px; }470 .f-label {471 font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;472 color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;473 }474 .f-input {475 background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);476 border-radius: 7px; color: var(--peach-text); padding: 7px 10px;477 font-size: 11px; font-family: "IBM Plex Mono", monospace;478 outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;479 }480 .f-input:focus { border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent); }481 .f-input::placeholder { color: var(--peach-text-muted); }482 .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }483 .f-row { display: flex; gap: 6px; }484 .f-row .f-input { flex: 1; min-width: 0; }485 .gen-btn {486 padding: 0 10px; border-radius: 7px; border: none;487 background: color-mix(in srgb, var(--peach-accent) 10%, transparent);488 color: color-mix(in srgb, var(--peach-accent) 80%, transparent);489 font-size: 10px; font-family: "IBM Plex Mono", monospace;490 cursor: pointer; white-space: nowrap; flex-shrink: 0;491 display: flex; align-items: center; gap: 4px;492 transition: background 100ms;493 }494 .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }495 .save-btn {496 width: 100%; padding: 8px; border-radius: 8px; border: none;497 background: var(--peach-accent); color: #fff; font-size: 12px;498 font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;499 transition: background 120ms, box-shadow 120ms, transform 80ms;500 letter-spacing: 0.01em;501 }502 .save-btn:hover {503 background: color-mix(in srgb, var(--peach-accent) 82%, #000);504 box-shadow: 0 4px 20px var(--peach-glow, transparent);505 }506 .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }507 .url-hint {508 font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);509 font-family: "IBM Plex Mono", monospace; font-style: italic;510 }511512 /* Success */513 .success-wrap {514 display: flex; flex-direction: column; align-items: center;515 padding: 24px 16px 20px; gap: 8px;516 animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;517 }518 @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }519 .success-ring {520 width: 40px; height: 40px; border-radius: 50%;521 background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);522 display: flex; align-items: center; justify-content: center;523 }524 .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }525 .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }526527 /* Locked state */528 .locked-wrap {529 display: flex; flex-direction: column; align-items: stretch;530 padding: 14px 13px 13px; gap: 9px;531 }532 .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }533 .locked-icon {534 width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;535 background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);536 display: flex; align-items: center; justify-content: center;537 }538 .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }539 .locked-input {540 width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);541 border-radius: 7px; color: var(--peach-text); padding: 7px 10px;542 font-size: 11px; font-family: "IBM Plex Mono", monospace;543 outline: none; transition: border-color 120ms, box-shadow 120ms;544 }545 .locked-input:focus { border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent); }546 .locked-input::placeholder { color: var(--peach-text-muted); }547 .locked-btn {548 width: 100%; padding: 8px; border-radius: 8px; border: none;549 background: var(--peach-accent); color: #fff; font-size: 12px;550 font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;551 transition: background 120ms;552 letter-spacing: 0.01em;553 box-shadow: 0 2px 16px var(--peach-glow, transparent);554 animation: peach-pulse-glow 2.4s ease-in-out infinite;555 }556 .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }557 .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }558 .locked-error {559 font-size: 10px; color: rgba(220,80,60,0.85);560 font-family: "IBM Plex Mono", monospace;561 }562563 @keyframes peach-pulse-glow {564 0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }565 50% { box-shadow: 0 2px 28px var(--peach-glow, transparent),566 0 0 48px var(--peach-glow, transparent); }567 }568`;569570export function showAutofillSelector(571 anchorEl: HTMLInputElement,572 entries: SelectorEntry[],573 onSelect: (id: string) => void,574 options: SelectorOptions = {}575): () => void {576 const host = document.createElement("div");577 host.style.cssText = "position: absolute; z-index: 2147483647;";578 host.style.setProperty("--peach-accent", accentHex);579 host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));580 host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));581 host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));582 const shadow = host.attachShadow({ mode: "closed" });583584 const style = shadow.appendChild(document.createElement("style"));585 style.textContent = SELECTOR_STYLES;586587 const rect = anchorEl.getBoundingClientRect();588 host.style.top = `${rect.bottom + window.scrollY + 5}px`;589 host.style.left = `${rect.left + window.scrollX}px`;590 591 592 host.style.width = `${Math.max(rect.width, 320)}px`;593594 const container = shadow.appendChild(document.createElement("div"));595 container.className = "peach-inline-popup";596 container.setAttribute("data-theme", popupTheme);597598 const searchableEntries = options.searchableEntries ?? [];599 const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();600601 let query = "";602 let focusedIndex = -1;603 let currentMode: "list" | "create" | "success" = "list";604 let searchInput: HTMLInputElement | null = null;605606 607 const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";608 const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");609 const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";610611 function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {612 const seen = new Set<string>();613 return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });614 }615616 function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {617 const q = value.trim().toLowerCase();618 const deduped = uniqueEntries(source);619 if (!q) return deduped.slice(0, 8);620 return deduped.filter(e =>621 [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)622 ).slice(0, 12);623 }624625 function activeEntries(): SelectorEntry[] {626 627 if (query.trim()) {628 const merged = uniqueEntries([...entries, ...searchableEntries]);629 return filterEntries(merged, query);630 }631 632 if (entries.length > 0) return entries;633 return filterEntries(searchableEntries, "").slice(0, 8);634 }635636 function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {637 const icon = document.createElement("div");638 icon.className = `entry-icon${isNew ? " is-new" : ""}`;639 if (isNew) {640 icon.innerHTML = plusSvgStr();641 } else {642 643 644 645 void url;646 icon.innerHTML = keySvgStr();647 }648 return icon;649 }650651 function renderList() {652 container.innerHTML = "";653 focusedIndex = -1;654 searchInput = null;655656 const current = activeEntries();657658 659 const domHdr = document.createElement("div");660 domHdr.className = "domain-header";661 const eyebrow = document.createElement("div");662 eyebrow.className = "domain-eyebrow";663 eyebrow.textContent = options.isSignup664 ? "Sign up as"665 : entries.length > 0 ? "Saved for this site" : "No saved login";666 const domName = document.createElement("div");667 domName.className = "domain-name";668 domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");669 domHdr.append(eyebrow, domName);670 container.appendChild(domHdr);671672 673 const sw = document.createElement("div"); sw.className = "search-wrap";674 searchInput = document.createElement("input");675 searchInput.className = "search";676 searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";677 searchInput.value = query;678 searchInput.addEventListener("input", () => {679 query = searchInput?.value ?? "";680 renderList();681 searchInput?.focus();682 searchInput?.setSelectionRange(query.length, query.length);683 });684 sw.appendChild(searchInput);685 container.appendChild(sw);686687 688 const results = document.createElement("div");689 results.className = "results";690 container.appendChild(results);691692 if (current.length === 0 && entries.length > 0) {693 694 }695696 for (let i = 0; i < current.length; i++) {697 const e = current[i]!;698 const entryEl = document.createElement("div");699 entryEl.className = "entry";700 entryEl.dataset.id = e.id;701 entryEl.dataset.index = String(i);702 entryEl.setAttribute("tabindex", "-1");703704 entryEl.appendChild(makeEntryIcon(e.url));705706 const info = document.createElement("div"); info.className = "entry-info";707 const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;708 const subEl = document.createElement("div"); subEl.className = "entry-sub";709 const domain = e.url ? getDomainFromUrl(e.url) : "";710 subEl.textContent = domain || e.username || "";711 info.append(titleEl, subEl);712 entryEl.appendChild(info);713714 if (e.hasTotp) {715 const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";716 entryEl.appendChild(badge);717 }718719 entryEl.addEventListener("click", () => {720 if (options.isSignup && options.onFillFields) {721 722 options.onFillFields(e.username ?? "", "");723 dismiss();724 } else {725 onSelect(e.id);726 dismiss();727 }728 });729 results.appendChild(entryEl);730 }731732 733 if (current.length > 0) {734 results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));735 }736737 738 const newEl = document.createElement("div");739 newEl.className = "entry";740 newEl.setAttribute("tabindex", "-1");741 newEl.appendChild(makeEntryIcon(undefined, true));742743 const newInfo = document.createElement("div"); newInfo.className = "entry-info";744 const newTitle = document.createElement("div");745 newTitle.className = "entry-title is-new";746 newTitle.textContent = `New entry for ${sTitle}`;747 const newSub = document.createElement("div");748 newSub.className = "entry-sub";749 newSub.textContent = sOrigin;750 newInfo.append(newTitle, newSub);751 newEl.appendChild(newInfo);752 newEl.addEventListener("click", showCreateForm);753 results.appendChild(newEl);754755 756 if (searchInput) {757 requestAnimationFrame(() => searchInput?.focus());758 }759 }760761 function setFocused(idx: number) {762 const all = container.querySelectorAll<HTMLElement>(".entry");763 all.forEach((el, i) => el.classList.toggle("focused", i === idx));764 focusedIndex = idx;765 if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });766 }767768 async function showCreateForm() {769 currentMode = "create";770 container.innerHTML = "";771772 773 774 775 const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;776 if (!statusRes?.unlocked) {777 renderLocked();778 return;779 }780781 782 783 const sitePolicy = detectPasswordPolicy();784785 const wrap = document.createElement("div");786 wrap.className = "create-form-wrap";787788 789 const head = document.createElement("div"); head.className = "create-head";790 const backBtn = document.createElement("button"); backBtn.className = "back-btn";791 backBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="7" height="12" viewBox="0 0 8 14" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1L1.5 7L6 13"/></svg>`;792 backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });793 const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";794 head.append(backBtn, lbl);795796 797 const body = document.createElement("div"); body.className = "create-body";798799 function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {800 const g = document.createElement("div"); g.className = "f-group";801 const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;802 const inp = document.createElement("input"); inp.className = "f-input";803 g.append(l, inp); return { g, inp };804 }805806 807 const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";808 body.appendChild(tg.g);809810 811 const ug = fGroup("website");812 ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";813 if (loginSubdomain) {814 const h = document.createElement("div"); h.className = "url-hint";815 h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);816 }817 body.appendChild(ug.g);818819 820 const xg = fGroup("username / email");821 xg.inp.value = preUsername; xg.inp.placeholder = "[email protected]";822 xg.inp.setAttribute("autocomplete", "off");823 body.appendChild(xg.g);824825 826 const pg = fGroup("password");827 const pwInp = document.createElement("input"); pwInp.className = "f-input";828 pwInp.type = "text"; pwInp.value = prePassword || generatePasswordForSite(sitePolicy);829 pwInp.style.fontFamily = '"IBM Plex Mono", monospace';830 pwInp.style.letterSpacing = "0.04em";831 pwInp.setAttribute("autocomplete", "off"); pwInp.setAttribute("spellcheck", "false");832 const genBtn = document.createElement("button"); genBtn.className = "gen-btn"; genBtn.type = "button";833 genBtn.innerHTML = genSvgStr() + " regen";834 genBtn.addEventListener("click", () => { pwInp.value = generatePasswordForSite(sitePolicy); });835 const pwRow = document.createElement("div"); pwRow.className = "f-row";836 pwRow.append(pwInp, genBtn); pg.g.appendChild(pwRow);837 body.appendChild(pg.g);838839 840 const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";841 saveBtn.textContent = "Save entry";842 const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";843 function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }844 saveBtn.addEventListener("click", async () => {845 const title = tg.inp.value.trim();846 const pw = pwInp.value.trim();847 const username = xg.inp.value.trim();848 if (!title) {849 tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();850 showFormError("Entry needs a title");851 return;852 }853 if (!pw) {854 pwInp.style.borderColor = "rgba(220,70,60,0.5)"; pwInp.focus();855 showFormError("Entry needs a password");856 return;857 }858 errEl.style.display = "none";859 saveBtn.disabled = true; saveBtn.textContent = "Saving…";860 try {861 const res = await chrome.runtime.sendMessage({862 type: "ADD_ENTRY",863 payload: { title, url: ug.inp.value.trim(), username, password: pw, type: "login" },864 });865 if ((res as { ok?: boolean }).ok) {866 867 if (options.isSignup && options.onFillFields) {868 options.onFillFields(username, pw);869 }870 showSuccess(title);871 } else {872 const errMsg = (res as { error?: string }).error === "vault locked"873 ? "Vault locked — open Peach to save"874 : "Could not save entry";875 showFormError(errMsg);876 saveBtn.disabled = false; saveBtn.textContent = "Save entry";877 }878 } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }879 });880 body.appendChild(saveBtn);881 body.appendChild(errEl);882883 wrap.append(head, body);884 container.appendChild(wrap);885 requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });886 }887888 function showSuccess(title: string) {889 currentMode = "success";890 container.innerHTML = "";891 const wrap = document.createElement("div"); wrap.className = "success-wrap";892 const ring = document.createElement("div"); ring.className = "success-ring";893 ring.innerHTML = checkSvgStr();894 const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;895 const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;896 wrap.append(ring, t, s);897 container.appendChild(wrap);898 setTimeout(() => dismiss(), 1600);899 }900901 function renderLocked() {902 container.innerHTML = "";903904 905 const domHdr = document.createElement("div");906 domHdr.className = "domain-header";907 const eyebrow = document.createElement("div");908 eyebrow.className = "domain-eyebrow";909 eyebrow.textContent = "vault locked";910 const domName = document.createElement("div");911 domName.className = "domain-name";912 domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");913 domHdr.append(eyebrow, domName);914 container.appendChild(domHdr);915916 const wrap = document.createElement("div");917 wrap.className = "locked-wrap";918919 920 const head = document.createElement("div"); head.className = "locked-head";921 const icon = document.createElement("div"); icon.className = "locked-icon";922 icon.innerHTML = keySvgStr();923 const title = document.createElement("div"); title.className = "locked-title";924 title.textContent = "unlock to autofill";925 head.append(icon, title);926927 928 const pwInp = document.createElement("input");929 pwInp.className = "locked-input";930 pwInp.type = "password";931 pwInp.placeholder = "master password";932 pwInp.setAttribute("autocomplete", "current-password");933934 935 const errEl = document.createElement("div");936 errEl.className = "locked-error";937 errEl.style.display = "none";938939 940 const unlockBtn = document.createElement("button");941 unlockBtn.className = "locked-btn";942 unlockBtn.type = "button";943 unlockBtn.textContent = "unlock";944945 async function tryUnlock() {946 const pw = pwInp.value.trim();947 if (!pw) { pwInp.focus(); return; }948 unlockBtn.disabled = true;949 unlockBtn.textContent = "unlocking…";950 errEl.style.display = "none";951 try {952 const res = await chrome.runtime.sendMessage({953 type: "UNLOCK",954 payload: { password: pw },955 });956 if ((res as { ok?: boolean }).ok) {957 dismiss();958 options.onUnlocked?.();959 } else {960 errEl.textContent = "incorrect password";961 errEl.style.display = "block";962 pwInp.value = "";963 pwInp.focus();964 unlockBtn.disabled = false;965 unlockBtn.textContent = "unlock";966 }967 } catch {968 errEl.textContent = "could not reach Peach";969 errEl.style.display = "block";970 unlockBtn.disabled = false;971 unlockBtn.textContent = "unlock";972 }973 }974975 pwInp.addEventListener("keydown", (e) => {976 e.stopPropagation();977 if (e.key === "Enter") void tryUnlock();978 });979 pwInp.addEventListener("keyup", (e) => e.stopPropagation());980 pwInp.addEventListener("keypress", (e) => e.stopPropagation());981 unlockBtn.addEventListener("click", () => void tryUnlock());982983 wrap.append(head, pwInp, errEl, unlockBtn);984 container.appendChild(wrap);985986 987 988 989 990 991 992 const captureKeydown = (e: KeyboardEvent) => {993 if (!host.isConnected) {994 document.removeEventListener("keydown", captureKeydown, true);995 return;996 }997 998 if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;999 1000 e.stopImmediatePropagation();1001 if (e.key === "Escape") { dismiss(true); return; }1002 if (e.key === "Enter") { void tryUnlock(); return; }1003 1004 1005 if (document.activeElement !== host) {1006 pwInp.focus({ preventScroll: true });1007 }1008 };1009 captureKeydownRef = captureKeydown;1010 document.addEventListener("keydown", captureKeydown, true);10111012 1013 1014 pwInp.focus({ preventScroll: true });1015 requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });1016 }10171018 function handleKeyDown(e: KeyboardEvent) {1019 if (options.locked) {1020 if (e.key === "Escape") { e.preventDefault(); dismiss(true); }1021 return;1022 }1023 if (currentMode === "create" || currentMode === "success") {1024 if (e.key === "Escape") { e.preventDefault(); dismiss(true); }1025 return;1026 }1027 const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");1028 const count = allEntryEls.length;1029 if (document.activeElement === searchInput) {1030 if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }1031 if (count === 0) return;1032 if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;1033 }1034 if (count === 0) return;1035 switch (e.key) {1036 case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;1037 case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;1038 case "Enter": {1039 if (focusedIndex >= 0) {1040 const el = allEntryEls[focusedIndex] as HTMLElement;1041 const id = el.dataset.id;1042 if (id) { onSelect(id); dismiss(); }1043 else if (el.classList.contains("is-new") || !id) {1044 1045 showCreateForm();1046 }1047 }1048 break;1049 }1050 case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;1051 }1052 }10531054 document.addEventListener("keydown", handleKeyDown);10551056 document.body.appendChild(host);10571058 function updatePosition() {1059 const r = anchorEl.getBoundingClientRect();1060 host.style.top = `${r.bottom + window.scrollY + 5}px`;1061 host.style.left = `${r.left + window.scrollX}px`;1062 host.style.width = `${Math.max(r.width, 260)}px`;1063 }1064 1065 1066 1067 1068 1069 1070 1071 let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;1072 const stopObserving = observeAnchorPosition(anchorEl, updatePosition);10731074 if (options.locked) {1075 renderLocked();1076 } else {1077 renderList();1078 }10791080 let exitScheduled = false;1081 function dismiss(userAction = false) {1082 1083 1084 1085 if (exitScheduled) return;1086 exitScheduled = true;1087 1088 1089 1090 stopObserving();1091 document.removeEventListener("click", outsideClick, { capture: true });1092 document.removeEventListener("keydown", handleKeyDown);1093 if (captureKeydownRef) {1094 document.removeEventListener("keydown", captureKeydownRef, true);1095 captureKeydownRef = null;1096 }1097 if (userAction) options.onDismiss?.();1098 container.classList.add("is-exiting");1099 setTimeout(() => host.remove(), 130);1100 }11011102 function outsideClick(ev: MouseEvent) {1103 const path = ev.composedPath();1104 1105 1106 1107 if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);1108 }1109 1110 setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);11111112 return dismiss;1113}