<!DOCTYPE html>
<html lang="zh-CN" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<meta name="theme-color" content="#1e1e1e">
<meta name="apple-mobile-web-app-capable" content="yes">
<title>PassForge · 高级密码工具</title>
<style>
/* ==================== 基础重置与兼容层 ==================== */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--radius: 12px; --transition: 0.3s ease;
--safe-bottom: env(safe-area-inset-bottom, 0px);
--font-main: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
--font-mono: 'Courier New', Consolas, 'Liberation Mono', monospace;
/* 默认回退 (dark) */
--bg-body: #121212; --bg-card: #1e1e1e; --bg-input: #2c2c2c;
--text-primary: #ffffff; --text-secondary: #a0a0a0;
--accent: #646cff; --border: #333333;
--shadow: 0 8px 32px rgba(0,0,0,0.4);
--settings-bg: #252525; --overlay: rgba(0,0,0,0.5);
}
/* ==================== 六大主题定义 ==================== */
[data-theme="dark"] {
--bg-body: #121212; --bg-card: #1e1e1e; --bg-input: #2c2c2c;
--text-primary: #fff; --text-secondary: #a0a0a0;
--accent: #646cff; --border: #333; --shadow: 0 8px 32px rgba(0,0,0,.4);
--settings-bg: #252525; --overlay: rgba(0,0,0,.6);
}
[data-theme="light"] {
--bg-body: #f5f7fa; --bg-card: #fff; --bg-input: #f0f2f5;
--text-primary: #1a1a1a; --text-secondary: #666;
--accent: #4f46e5; --border: #e5e7eb; --shadow: 0 8px 32px rgba(0,0,0,.08);
--settings-bg: #fff; --overlay: rgba(0,0,0,.3);
}
[data-theme="cyber"] {
--bg-body: #0b0c15; --bg-card: #13141f; --bg-input: #1c1d2b;
--text-primary: #00ff9d; --text-secondary: #00b8ff;
--accent: #ff0055; --border: #2a2b3d; --shadow: 0 0 20px rgba(0,255,157,.1);
--settings-bg: #181926; --overlay: rgba(0,0,0,.7);
}
[data-theme="forest"] {
--bg-body: #0d1f0d; --bg-card: #162816; --bg-input: #1e3a1e;
--text-primary: #c8e6c9; --text-secondary: #81c784;
--accent: #66bb6a; --border: #2e5830; --shadow: 0 8px 32px rgba(0,40,0,.4);
--settings-bg: #1a301a; --overlay: rgba(0,20,0,.6);
}
[data-theme="ocean"] {
--bg-body: #0a1929; --bg-card: #0f2744; --bg-input: #163560;
--text-primary: #b3e5fc; --text-secondary: #4fc3f7;
--accent: #29b6f6; --border: #1e4976; --shadow: 0 8px 32px rgba(0,30,80,.4);
--settings-bg: #122d4d; --overlay: rgba(0,15,40,.6);
}
[data-theme="eye-care"] {
--bg-body: #c7edcc; --bg-card: #daf5de; --bg-input: #b8e0be;
--text-primary: #2e4a32; --text-secondary: #5a7d60;
--accent: #4caf50; --border: #a5d6a7; --shadow: 0 8px 32px rgba(0,60,0,.08);
--settings-bg: #d0ecd4; --overlay: rgba(0,30,0,.25);
}
@supports (color: oklch(0.5 0.2 240)) {
[data-theme="forest"] { --accent: oklch(0.72 0.18 145); }
[data-theme="ocean"] { --accent: oklch(0.75 0.15 220); }
}
/* ==================== 全局布局 ==================== */
body {
font-family: var(--font-main); background: var(--bg-body); color: var(--text-primary);
display: flex; justify-content: center; align-items: center;
min-height: 100vh; min-height: 100dvh; padding: 16px;
transition: background var(--transition), color var(--transition);
-webkit-tap-highlight-color: transparent; touch-action: manipulation;
}
.container {
width: 100%; max-width: 500px; background: var(--bg-card);
padding: 28px; border-radius: var(--radius); border: 1px solid var(--border);
box-shadow: var(--shadow); transition: all var(--transition);
padding-bottom: calc(28px + var(--safe-bottom)); position: relative; z-index: 1;
}
/* ==================== 头部 ==================== */
header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
h1 { font-size: 1.3rem; font-weight: 700; letter-spacing: -.5px; }
.header-actions { display: flex; gap: 8px; }
.icon-btn {
background: none; border: none; color: var(--text-secondary);
cursor: pointer; font-size: 1.1rem; padding: 8px; border-radius: 8px;
transition: all 0.2s; min-width: 36px; min-height: 36px;
display: flex; align-items: center; justify-content: center; line-height: 1;
}
.icon-btn:hover, .icon-btn:focus-visible { color: var(--accent); background: rgba(100,108,255,.1); }
/* ==================== 密码显示区 ==================== */
.password-display { position: relative; margin-bottom: 16px; }
.pwd-input {
width: 100%; padding: 16px 90px 16px 18px;
font-size: 1.15rem; font-family: var(--font-mono);
background: var(--bg-input); border: 2px solid transparent;
border-radius: var(--radius); color: var(--text-primary);
transition: border-color 0.2s; letter-spacing: .5px; word-break: break-all; line-height: 1.4;
}
.pwd-input:focus { border-color: var(--accent); outline: none; }
.pwd-actions {
position: absolute; right: 8px; top: 50%; transform: translateY(-50%); display: flex; gap: 2px;
}
/* ==================== 控制面板 ==================== */
.controls { display: grid; gap: 14px; margin-bottom: 20px; }
.length-control { display: flex; align-items: center; gap: 12px; }
.length-control label { font-size: .85rem; color: var(--text-secondary); white-space: nowrap; min-width: 32px; }
input[type="range"] {
flex: 1; -webkit-appearance: none; appearance: none;
height: 6px; background: var(--bg-input); border-radius: 3px; cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none; width: 24px; height: 24px;
background: var(--accent); border-radius: 50%; box-shadow: 0 2px 8px rgba(0,0,0,.3); cursor: grab;
}
input[type="range"]:active::-webkit-slider-thumb { cursor: grabbing; }
.len-val { min-width: 36px; text-align: center; font-weight: 700; font-size: .95rem; }
.options { display: flex; flex-wrap: wrap; gap: 8px; }
.chip {
display: flex; align-items: center; gap: 5px; font-size: .8rem;
color: var(--text-secondary); padding: 7px 14px; background: var(--bg-input);
border-radius: 20px; cursor: pointer; user-select: none;
transition: all 0.2s; border: 1px solid transparent; min-height: 36px;
}
.chip:has(input:checked) { border-color: var(--accent); color: var(--accent); background: rgba(100,108,255,.08); }
.chip input { accent-color: var(--accent); cursor: pointer; width: 16px; height: 16px; }
.advanced-toggle {
font-size: .8rem; color: var(--text-secondary); cursor: pointer;
padding: 6px 0; display: flex; align-items: center; gap: 4px;
user-select: none; border: none; background: none;
}
.advanced-toggle:hover { color: var(--accent); }
.advanced-toggle .arrow { transition: transform 0.2s; display: inline-block; }
.advanced-toggle.open .arrow { transform: rotate(90deg); }
.advanced-panel { max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s; opacity: 0; }
.advanced-panel.open { max-height: 200px; opacity: 1; margin-top: 8px; }
.custom-symbols {
width: 100%; padding: 10px 14px; margin-top: 8px;
background: var(--bg-input); border: 1px solid var(--border);
border-radius: 8px; color: var(--text-primary); font-size: .85rem;
font-family: var(--font-mono); resize: none;
}
.custom-symbols:focus { border-color: var(--accent); outline: none; }
.generate-btn {
width: 100%; padding: 14px; margin-top: 4px;
background: var(--accent); color: #fff; border: none;
border-radius: var(--radius); font-size: 1rem; font-weight: 600;
cursor: pointer; transition: all 0.2s; min-height: 48px;
position: relative; overflow: hidden;
}
.generate-btn:hover { filter: brightness(1.1); transform: translateY(-1px); }
.generate-btn:active { transform: translateY(0); filter: brightness(.95); }
.generate-btn .ripple {
position: absolute; border-radius: 50%; background: rgba(255,255,255,.3);
transform: scale(0); animation: rippleAnim .6s ease-out; pointer-events: none;
}
@keyframes rippleAnim { to { transform: scale(4); opacity: 0; } }
/* ==================== 安全度分析 ==================== */
.analysis-panel { margin-top: 20px; padding-top: 18px; border-top: 1px solid var(--border); }
.stats-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 14px; }
.stat-item { display: flex; flex-direction: column; gap: 2px; }
.stat-label { font-size: .75rem; color: var(--text-secondary); }
.stat-value { font-size: .9rem; font-weight: 600; font-family: var(--font-mono); }
.progress-container { margin-top: 14px; }
.progress-header { display: flex; justify-content: space-between; margin-bottom: 6px; font-size: .78rem; }
.strength-text { font-weight: 700; text-transform: uppercase; letter-spacing: .5px; transition: color 0.3s; }
.progress-track { width: 100%; height: 10px; background: var(--bg-input); border-radius: 5px; overflow: hidden; }
.progress-fill {
height: 100%; width: 0%; border-radius: 5px;
transition: width .5s cubic-bezier(.4,0,.2,1), background-color .4s ease;
}
/* ==================== 历史记录 ==================== */
.history-section { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--border); }
.history-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.history-title { font-size: .8rem; color: var(--text-secondary); }
.clear-history {
font-size: .72rem; color: var(--text-secondary); background: none;
border: none; cursor: pointer; padding: 4px 8px; border-radius: 4px;
}
.clear-history:hover { color: #ef4444; background: rgba(239,68,68,.1); }
.history-list { display: flex; flex-direction: column; gap: 6px; max-height: 140px; overflow-y: auto; }
.history-item {
display: flex; justify-content: space-between; align-items: center;
padding: 8px 12px; background: var(--bg-input); border-radius: 8px;
font-family: var(--font-mono); font-size: .78rem; cursor: pointer;
transition: all 0.2s; word-break: break-all; min-height: 36px;
}
.history-item:hover { background: rgba(100,108,255,.08); }
.history-meta { font-size: .65rem; color: var(--text-secondary); white-space: nowrap; margin-left: 8px; }
/* ==================== ⭐ 设置面板 (抽屉) ==================== */
.settings-overlay {
position: fixed; inset: 0; background: var(--overlay); z-index: 998;
opacity: 0; visibility: hidden; transition: all 0.3s ease;
backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
}
.settings-overlay.open { opacity: 1; visibility: visible; }
.settings-drawer {
position: fixed; top: 0; right: 0; bottom: 0;
width: 320px; max-width: 85vw; background: var(--settings-bg);
z-index: 999; transform: translateX(100%); transition: transform 0.35s cubic-bezier(.4,0,.2,1);
display: flex; flex-direction: column; border-left: 1px solid var(--border);
box-shadow: -8px 0 32px rgba(0,0,0,.3);
}
.settings-drawer.open { transform: translateX(0); }
.settings-header {
display: flex; justify-content: space-between; align-items: center;
padding: 24px 24px 16px; border-bottom: 1px solid var(--border); flex-shrink: 0;
}
.settings-header h2 { font-size: 1.15rem; font-weight: 700; }
.close-settings {
background: none; border: none; color: var(--text-secondary);
font-size: 1.3rem; cursor: pointer; padding: 6px; border-radius: 8px;
min-width: 36px; min-height: 36px; display: flex; align-items: center; justify-content: center;
}
.close-settings:hover { color: var(--text-primary); background: rgba(128,128,128,.1); }
.settings-body { flex: 1; overflow-y: auto; padding: 20px 24px; }
.setting-group { margin-bottom: 28px; }
.setting-group-title {
font-size: .72rem; text-transform: uppercase; letter-spacing: 1.5px;
color: var(--text-secondary); margin-bottom: 14px; font-weight: 600;
}
/* 主题网格 */
.theme-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
.theme-card {
position: relative; border: 2px solid var(--border); border-radius: 12px;
padding: 14px 8px 10px; cursor: pointer; transition: all 0.2s;
display: flex; flex-direction: column; align-items: center; gap: 8px;
background: transparent; min-height: 80px; justify-content: center;
}
.theme-card:hover { border-color: var(--text-secondary); }
.theme-card.active { border-color: var(--accent); background: rgba(100,108,255,.06); }
.theme-card.active::after {
content: '✓'; position: absolute; top: 4px; right: 6px;
font-size: .65rem; color: var(--accent); font-weight: 700;
}
.theme-preview {
width: 28px; height: 28px; border-radius: 50%; border: 1px solid rgba(128,128,128,.3);
flex-shrink: 0;
}
.theme-name { font-size: .7rem; color: var(--text-secondary); text-align: center; line-height: 1.2; }
.theme-card.active .theme-name { color: var(--accent); font-weight: 600; }
/* 预览色块 */
.tp-dark { background: linear-gradient(135deg, #1e1e1e 50%, #646cff 50%); }
.tp-light { background: linear-gradient(135deg, #fff 50%, #4f46e5 50%); }
.tp-cyber { background: linear-gradient(135deg, #13141f 50%, #ff0055 50%); }
.tp-forest { background: linear-gradient(135deg, #162816 50%, #66bb6a 50%); }
.tp-ocean { background: linear-gradient(135deg, #0f2744 50%, #29b6f6 50%); }
.tp-eye { background: linear-gradient(135deg, #c7edcc 50%, #4caf50 50%); }
/* 设置项开关 */
.setting-row {
display: flex; justify-content: space-between; align-items: center;
padding: 12px 0; border-bottom: 1px solid var(--border);
}
.setting-row:last-child { border-bottom: none; }
.setting-row-label { font-size: .88rem; }
.setting-row-desc { font-size: .72rem; color: var(--text-secondary); margin-top: 2px; }
/* Toggle Switch */
.toggle { position: relative; width: 44px; height: 24px; flex-shrink: 0; }
.toggle input { opacity: 0; width: 0; height: 0; }
.toggle-slider {
position: absolute; inset: 0; background: var(--bg-input); border-radius: 12px;
cursor: pointer; transition: 0.3s; border: 1px solid var(--border);
}
.toggle-slider::before {
content: ''; position: absolute; width: 18px; height: 18px;
left: 2px; bottom: 2px; background: var(--text-secondary);
border-radius: 50%; transition: 0.3s;
}
.toggle input:checked + .toggle-slider { background: var(--accent); border-color: var(--accent); }
.toggle input:checked + .toggle-slider::before { transform: translateX(20px); background: #fff; }
.settings-footer {
padding: 16px 24px; border-top: 1px solid var(--border);
font-size: .7rem; color: var(--text-secondary); text-align: center; flex-shrink: 0;
}
/* ==================== Toast ==================== */
.toast {
position: fixed; bottom: calc(30px + var(--safe-bottom)); left: 50%;
transform: translateX(-50%) translateY(20px); background: var(--accent); color: #fff;
padding: 10px 24px; border-radius: 20px; font-size: .85rem; opacity: 0;
transition: all 0.3s; pointer-events: none; z-index: 1000; white-space: nowrap;
}
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
/* ==================== 响应式 & 无障碍 ==================== */
@media (max-width: 480px) {
.container { padding: 20px 16px; padding-bottom: calc(20px + var(--safe-bottom)); border-radius: 0; border: none; }
body { align-items: flex-start; padding: 0; }
.settings-drawer { width: 100%; max-width: 100%; }
.theme-grid { grid-template-columns: repeat(3, 1fr); gap: 8px; }
.theme-card { padding: 10px 6px 8px; min-height: 72px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; }
}
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button:focus:not(:focus-visible), input:focus:not(:focus-visible) { outline: none; }
</style>
</head>
<body>
<!-- ===== 主界面 ===== -->
<div class="container" role="main">
<header>
<h1>🔐 PassForge</h1>
<div class="header-actions">
<button class="icon-btn" id="settingsBtn" onclick="openSettings()" aria-label="打开设置" title="设置">⚙️</button>
</div>
</header>
<div class="password-display">
<input type="password" id="pwdInput" class="pwd-input" placeholder="生成或输入密码..." autocomplete="off" spellcheck="false" aria-label="密码" inputmode="text">
<div class="pwd-actions">
<button class="icon-btn" id="toggleVisBtn" onclick="toggleVisibility()" aria-label="显示密码" title="显示/隐藏">👁️</button>
<button class="icon-btn" onclick="copyPassword()" aria-label="复制密码" title="复制">📋</button>
</div>
</div>
<div class="controls">
<div class="length-control">
<label for="lenRange">长度</label>
<input type="range" id="lenRange" min="4" max="64" value="16">
<span class="len-val" id="lenVal" aria-live="polite">16</span>
</div>
<div class="options" role="group" aria-label="字符类型">
<label class="chip"><input type="checkbox" id="optUpper" checked> A-Z</label>
<label class="chip"><input type="checkbox" id="optLower" checked> a-z</label>
<label class="chip"><input type="checkbox" id="optNum" checked> 0-9</label>
<label class="chip"><input type="checkbox" id="optSym" checked> !@#$</label>
</div>
<button class="advanced-toggle" id="advToggle" onclick="toggleAdvanced()" aria-expanded="false">
<span class="arrow">▶</span> 高级选项
</button>
<div class="advanced-panel" id="advPanel">
<label class="chip" style="margin-bottom:8px"><input type="checkbox" id="optNoAmbiguous"> 排除易混淆 (0O1lI)</label>
<label class="stat-label" for="customSymbols" style="display:block;margin-bottom:4px">自定义符号集</label>
<textarea id="customSymbols" class="custom-symbols" rows="2" placeholder="留空使用默认: !@#$%^&*()_+-=[]{}|;:,.<>?"></textarea>
</div>
<button class="generate-btn" id="genBtn" onclick="handleGenerate(event)">⚡ 生成新密码</button>
</div>
<div class="analysis-panel" aria-live="polite">
<div class="stats-grid">
<div class="stat-item"><span class="stat-label">信息熵</span><span class="stat-value" id="entropyVal">0 bits</span></div>
<div class="stat-item"><span class="stat-label">字符集</span><span class="stat-value" id="charsetVal">0</span></div>
<div class="stat-item"><span class="stat-label">组合数</span><span class="stat-value" id="comboVal">0</span></div>
<div class="stat-item"><span class="stat-label">破解时间</span><span class="stat-value" id="crackTimeVal">-</span></div>
</div>
<div class="progress-container">
<div class="progress-header">
<span class="stat-label">安全等级</span>
<span class="strength-text" id="strengthText">等待输入</span>
</div>
<div class="progress-track" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div class="progress-fill" id="progressFill"></div>
</div>
</div>
</div>
<div class="history-section">
<div class="history-header">
<span class="history-title">📜 最近生成 (仅存本地)</span>
<button class="clear-history" onclick="clearHistory()">清除</button>
</div>
<div class="history-list" id="historyList" role="list"></div>
</div>
</div>
<!-- ===== ⭐ 设置面板 ===== -->
<div class="settings-overlay" id="settingsOverlay" onclick="closeSettings()"></div>
<aside class="settings-drawer" id="settingsDrawer" role="dialog" aria-label="设置面板" aria-modal="true">
<div class="settings-header">
<h2>⚙️ 设置</h2>
<button class="close-settings" onclick="closeSettings()" aria-label="关闭设置">✕</button>
</div>
<div class="settings-body">
<!-- 主题选择 -->
<div class="setting-group">
<div class="setting-group-title">外观主题</div>
<div class="theme-grid" id="themeGrid" role="radiogroup" aria-label="主题选择">
<button class="theme-card active" data-theme="dark" onclick="setTheme('dark')" role="radio" aria-checked="true">
<div class="theme-preview tp-dark"></div>
<span class="theme-name">暗黑</span>
</button>
<button class="theme-card" data-theme="light" onclick="setTheme('light')" role="radio" aria-checked="false">
<div class="theme-preview tp-light"></div>
<span class="theme-name">极简白</span>
</button>
<button class="theme-card" data-theme="cyber" onclick="setTheme('cyber')" role="radio" aria-checked="false">
<div class="theme-preview tp-cyber"></div>
<span class="theme-name">赛博朋克</span>
</button>
<button class="theme-card" data-theme="forest" onclick="setTheme('forest')" role="radio" aria-checked="false">
<div class="theme-preview tp-forest"></div>
<span class="theme-name">🌲 森林</span>
</button>
<button class="theme-card" data-theme="ocean" onclick="setTheme('ocean')" role="radio" aria-checked="false">
<div class="theme-preview tp-ocean"></div>
<span class="theme-name">🌊 海洋</span>
</button>
<button class="theme-card" data-theme="eye-care" onclick="setTheme('eye-care')" role="radio" aria-checked="false">
<div class="theme-preview tp-eye"></div>
<span class="theme-name">🍃 护眼</span>
</button>
</div>
</div>
<!-- 行为设置 -->
<div class="setting-group">
<div class="setting-group-title">行为偏好</div>
<div class="setting-row">
<div>
<div class="setting-row-label">自动生成</div>
<div class="setting-row-desc">打开页面时自动生成密码</div>
</div>
<label class="toggle">
<input type="checkbox" id="settingAutoGen" checked onchange="saveSetting('autoGen', this.checked)">
<span class="toggle-slider"></span>
</label>
</div>
<div class="setting-row">
<div>
<div class="setting-row-label">保存历史</div>
<div class="setting-row-desc">在本地保留最近生成的密码</div>
</div>
<label class="toggle">
<input type="checkbox" id="settingSaveHistory" checked onchange="toggleHistorySetting(this.checked)">
<span class="toggle-slider"></span>
</label>
</div>
<div class="setting-row">
<div>
<div class="setting-row-label">跟随系统主题</div>
<div class="setting-row-desc">自动切换亮色/暗色模式</div>
</div>
<label class="toggle">
<input type="checkbox" id="settingFollowSystem" onchange="toggleFollowSystem(this.checked)">
<span class="toggle-slider"></span>
</label>
</div>
</div>
<!-- 关于 -->
<div class="setting-group">
<div class="setting-group-title">关于</div>
<div class="setting-row" style="border:none;flex-direction:column;align-items:flex-start;gap:6px">
<div class="setting-row-label">PassForge v2.0</div>
<div class="setting-row-desc">纯前端密码工具,零网络请求<br>所有数据仅存储在您的浏览器中<br>使用 crypto.getRandomValues 安全随机源</div>
</div>
</div>
</div>
<div class="settings-footer">按 ESC 关闭设置面板</div>
</aside>
<div class="toast" id="toast" role="status" aria-live="assertive"></div>
<script>
/* ==================== 兼容层 ==================== */
const SecureRandom = (() => {
if (typeof crypto !== 'undefined' && crypto.getRandomValues)
return { getValues(a) { return crypto.getRandomValues(a); }, isSecure: true };
return {
getValues(a) { for(let i=0;i<a.length;i++) a[i]=Math.floor(Math.random()*4294967296); return a; },
isSecure: false
};
})();
const Storage = (() => {
try { localStorage.setItem('__t','__t'); localStorage.removeItem('__t'); return localStorage; }
catch { const m={}; return { getItem:k=>m[k]||null, setItem:(k,v)=>{m[k]=v}, removeItem:k=>{delete m[k]} }; }
})();
/* ==================== 常量 ==================== */
const DEFAULT_SYMBOLS = '!@#$%^&*()_+-=[]{}|;:,.<>?';
const AMBIGUOUS = '0O1lI|';
const HISTORY_KEY = 'pf_history';
const SETTINGS_KEY = 'pf_settings';
const MAX_HISTORY = 5;
const VALID_THEMES = ['dark','light','cyber','forest','ocean','eye-care'];
const THEME_COLORS = { dark:'#1e1e1e', light:'#fff', cyber:'#13141f', forest:'#162816', ocean:'#0f2744', 'eye-care':'#c7edcc' };
let passwordVisible = false;
let settings = { theme:'dark', autoGen:true, saveHistory:true, followSystem:false };
const $ = id => document.getElementById(id);
/* ==================== 设置系统 ==================== */
function loadSettings() {
try {
const saved = JSON.parse(Storage.getItem(SETTINGS_KEY));
if (saved) settings = { ...settings, ...saved };
} catch {}
// 应用设置到UI
$('settingAutoGen').checked = settings.autoGen;
$('settingSaveHistory').checked = settings.saveHistory;
$('settingFollowSystem').checked = settings.followSystem;
// 跟随系统优先
if (settings.followSystem) applySystemTheme();
else applyTheme(settings.theme);
}
function saveSetting(key, value) {
settings[key] = value;
Storage.setItem(SETTINGS_KEY, JSON.stringify(settings));
}
function openSettings() {
$('settingsOverlay').classList.add('open');
$('settingsDrawer').classList.add('open');
$('settingsDrawer').querySelector('.close-settings').focus();
document.body.style.overflow = 'hidden';
}
function closeSettings() {
$('settingsOverlay').classList.remove('open');
$('settingsDrawer').classList.remove('open');
document.body.style.overflow = '';
$('settingsBtn').focus();
}
// ESC 关闭
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && $('settingsDrawer').classList.contains('open')) closeSettings();
});
/* ==================== 主题系统 ==================== */
function setTheme(theme) {
if (!VALID_THEMES.includes(theme)) return;
settings.theme = theme;
settings.followSystem = false;
$('settingFollowSystem').checked = false;
saveSetting('theme', theme);
saveSetting('followSystem', false);
applyTheme(theme);
}
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
document.querySelectorAll('.theme-card').forEach(c => {
const isActive = c.dataset.theme === theme;
c.classList.toggle('active', isActive);
c.setAttribute('aria-checked', isActive);
});
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.content = THEME_COLORS[theme] || THEME_COLORS.dark;
}
function toggleFollowSystem(enabled) {
settings.followSystem = enabled;
saveSetting('followSystem', enabled);
if (enabled) applySystemTheme();
else applyTheme(settings.theme);
}
function applySystemTheme() {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(prefersDark ? 'dark' : 'light');
}
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (settings.followSystem) applySystemTheme();
});
function toggleHistorySetting(enabled) {
saveSetting('saveHistory', enabled);
if (!enabled) { clearHistory(); showToast('历史已关闭并清除'); }
else renderHistory();
}
/* ==================== 密码可见性 ==================== */
function toggleVisibility() {
passwordVisible = !passwordVisible;
$('pwdInput').type = passwordVisible ? 'text' : 'password';
$('toggleVisBtn').textContent = passwordVisible ? '🙈' : '👁️';
$('toggleVisBtn').setAttribute('aria-label', passwordVisible ? '隐藏密码' : '显示密码');
}
/* ==================== 高级选项 ==================== */
function toggleAdvanced() {
const btn = $('advToggle'), panel = $('advPanel');
const isOpen = panel.classList.toggle('open');
btn.classList.toggle('open', isOpen);
btn.setAttribute('aria-expanded', isOpen);
}
/* ==================== 字符集 & 生成 ==================== */
function buildCharset() {
let upper='ABCDEFGHIJKLMNOPQRSTUVWXYZ', lower='abcdefghijklmnopqrstuvwxyz', num='0123456789';
let sym = $('customSymbols').value.trim() || DEFAULT_SYMBOLS;
if ($('optNoAmbiguous').checked) {
const f = s => [...s].filter(c => !AMBIGUOUS.includes(c)).join('');
upper=f(upper); lower=f(lower); num=f(num); sym=f(sym);
}
let pool = '';
if ($('optUpper').checked) pool += upper;
if ($('optLower').checked) pool += lower;
if ($('optNum').checked) pool += num;
if ($('optSym').checked) pool += sym;
return [...new Set(pool)].join('');
}
function handleGenerate(e) {
if (e?.currentTarget) {
const btn=e.currentTarget, rect=btn.getBoundingClientRect(), ripple=document.createElement('span');
ripple.className='ripple';
const sz=Math.max(rect.width,rect.height);
Object.assign(ripple.style,{width:sz+'px',height:sz+'px',left:(e.clientX-rect.left-sz/2)+'px',top:(e.clientY-rect.top-sz/2)+'px'});
btn.appendChild(ripple); setTimeout(()=>ripple.remove(),600);
}
generatePassword();
}
function generatePassword() {
const pool = buildCharset();
if (!pool) { showToast('⚠️ 请至少选择一种字符类型'); return; }
const len = parseInt($('lenRange').value);
const arr = new Uint32Array(len);
SecureRandom.getValues(arr);
let pwd = '';
for (let i=0;i<len;i++) pwd += pool[arr[i]%pool.length];
$('pwdInput').value = pwd;
analyzePassword(pwd);
if (settings.saveHistory) addToHistory(pwd);
}
/* ==================== 安全分析 ==================== */
function analyzePassword(pwd) {
if (!pwd) { resetAnalysis(); return; }
let ps = 0;
if (/[a-z]/.test(pwd)) ps+=26;
if (/[A-Z]/.test(pwd)) ps+=26;
if (/[0-9]/.test(pwd)) ps+=10;
if (/[^a-zA-Z0-9]/.test(pwd)) ps+=32;
const entropy = ps>0 ? pwd.length*Math.log2(ps) : 0;
let combo='0';
if (ps>0) { const lc=pwd.length*Math.log10(ps); combo=lc>15?`10^${lc.toFixed(0)}`:Math.pow(ps,pwd.length).toExponential(1); }
const secs = ps>0 ? Math.pow(ps,pwd.length)/1e10/2 : 0;
let score = Math.min(100,Math.max(0,(entropy-20)/0.8));
if (pwd.length<8 && ps<=36) score=Math.min(score,25);
if (/(.)\1{2,}/.test(pwd)) score=Math.max(0,score-15);
$('entropyVal').textContent=`${entropy.toFixed(1)} bits`;
$('charsetVal').textContent=ps;
$('comboVal').textContent=combo;
$('crackTimeVal').textContent=formatCrackTime(secs);
updateProgressBar(score);
}
function updateProgressBar(score) {
$('progressFill').style.width=`${score}%`;
$('progressFill').parentElement.setAttribute('aria-valuenow',Math.round(score));
const levels=[
{max:25,color:'#ef4444',label:'极弱·秒破'},{max:45,color:'#f97316',label:'较弱·分钟级'},
{max:65,color:'#eab308',label:'中等·小时级'},{max:85,color:'#22c55e',label:'强·世纪级'},
{max:101,color:'#059669',label:'极强·宇宙级'}
];
const lv=levels.find(l=>score<l.max)||levels[4];
$('progressFill').style.backgroundColor=lv.color;
$('strengthText').textContent=lv.label;
$('strengthText').style.color=lv.color;
}
function resetAnalysis() {
$('entropyVal').textContent='0 bits'; $('charsetVal').textContent='0';
$('comboVal').textContent='0'; $('crackTimeVal').textContent='-';
$('strengthText').textContent='等待输入'; $('strengthText').style.color='var(--text-secondary)';
$('progressFill').style.width='0%'; $('progressFill').style.backgroundColor='transparent';
}
function formatCrackTime(s) {
if (!isFinite(s)||s>3.154e16) return '∞ 天文数字';
if (s<.001) return '瞬间'; if (s<1) return `${(s*1000).toFixed(0)}ms`;
if (s<60) return `${s.toFixed(1)}秒`; if (s<3600) return `${(s/60).toFixed(1)}分钟`;
if (s<86400) return `${(s/3600).toFixed(1)}小时`; if (s<3.154e7) return `${(s/86400).toFixed(0)}天`;
if (s<3.154e10) return `${(s/3.154e7).toFixed(0)}年`; if (s<3.154e13) return `${(s/3.154e10).toFixed(0)}千年`;
return `${(s/3.154e13).toFixed(0)}万年`;
}
/* ==================== 历史记录 ==================== */
function getHistory() { try{return JSON.parse(Storage.getItem(HISTORY_KEY))||[];}catch{return [];} }
function addToHistory(pwd) {
let list=getHistory().filter(h=>h.pwd!==pwd);
list.unshift({pwd,time:Date.now(),len:pwd.length});
if (list.length>MAX_HISTORY) list=list.slice(0,MAX_HISTORY);
Storage.setItem(HISTORY_KEY,JSON.stringify(list)); renderHistory();
}
function clearHistory() { Storage.removeItem(HISTORY_KEY); renderHistory(); showToast('历史已清除'); }
function renderHistory() {
const list=settings.saveHistory?getHistory():[];
if (!list.length) { $('historyList').innerHTML='<div style="font-size:.78rem;color:var(--text-secondary);padding:8px;text-align:center">暂无记录</div>'; return; }
$('historyList').innerHTML=list.map((h,i)=>{
const m=h.pwd.length>20?h.pwd.slice(0,10)+'…'+h.pwd.slice(-6):h.pwd;
return `<div class="history-item" tabindex="0" onclick="useHistory(${i})" onkeydown="if(event.key==='Enter')useHistory(${i})">
<span>${escHtml(m)}</span><span class="history-meta">${h.len}位·${timeAgo(h.time)}</span></div>`;
}).join('');
}
function useHistory(i) { const l=getHistory(); if(l[i]){$('pwdInput').value=l[i].pwd;analyzePassword(l[i].pwd);showToast('已填入');} }
function timeAgo(ts) { const d=Date.now()-ts; if(d<6e4)return'刚刚';if(d<36e5)return`${d/6e4|0}分钟前`;if(d<864e5)return`${d/36e5|0}小时前`;return`${d/864e5|0}天前`; }
function escHtml(s) { const d=document.createElement('div');d.textContent=s;return d.innerHTML; }
/* ==================== 复制 & Toast ==================== */
function copyPassword() {
const t=$('pwdInput').value; if(!t){showToast('⚠️ 无内容');return;}
if(navigator.clipboard?.writeText) navigator.clipboard.writeText(t).then(()=>showToast('✅ 已复制'));
else {$('pwdInput').select();document.execCommand('copy');showToast('✅ 已复制');}
}
let toastTimer;
function showToast(msg) { const t=$('toast');t.textContent=msg;t.classList.add('show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>t.classList.remove('show'),2200); }
/* ==================== 事件绑定 ==================== */
$('lenRange').addEventListener('input',()=>{$('lenVal').textContent=$('lenRange').value;});
$('pwdInput').addEventListener('input',()=>analyzePassword($('pwdInput').value));
['optUpper','optLower','optNum','optSym','optNoAmbiguous'].forEach(id=>$(id).addEventListener('change',()=>{if($('pwdInput').value)analyzePassword($('pwdInput').value);}));
$('customSymbols').addEventListener('input',()=>{if($('pwdInput').value)analyzePassword($('pwdInput').value);});
document.addEventListener('keydown',e=>{
if((e.ctrlKey||e.metaKey)&&e.key==='Enter'){e.preventDefault();generatePassword();}
if((e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key==='C'){e.preventDefault();copyPassword();}
});
/* ==================== 初始化 ==================== */
window.addEventListener('DOMContentLoaded',()=>{
loadSettings();
renderHistory();
if(settings.autoGen) generatePassword();
if(!SecureRandom.isSecure) showToast('⚠️ 当前环境不支持安全随机数');
});
</script>
</body>
</html>
index.html
index.html