Open
feat: #15 剪切板历史置顶固定 + Alt+1~9 快捷键直达 #2
grape_botAdd on Oct 20
feat: #15 剪切板历史置顶固定 + Alt+1~9 快捷键直达 #2
Open
grape_botAdd on Oct 20
Merged fromfeat/issue-15intomain
Total: 8 files changed+548-33
@@ -4,6 +4,12 @@
4 * recorder.ts feeds it from page copy/cut events and the polled system4 * recorder.ts feeds it from page copy/cut events and the polled system
5 * clipboard, and the panel (panel.tsx) renders it. The composer trigger5 * clipboard, and the panel (panel.tsx) renders it. The composer trigger
6 * matcher lives here too, so the input hub imports one small module.6 * matcher lives here too, so the input hub imports one small module.
7+ *
8+ * Entries are kept in a stable display order: pinned entries first (by
9+ * pinnedAt ascending, which is exactly the Alt+1..9 slot order), then the
10+ * regular area newest-first capped at MAX_ENTRIES. Pinning never participates
11+ * in the regular-area trim, so a pinned snippet survives any amount of new
12+ * copies (Issue #15).
7 */13 */
8 14 
9/** Where a recorded entry came from. */15/** Where a recorded entry came from. */
@@ -18,11 +24,17 @@ export interface ClipboardEntry {
18 readonly time: number24 readonly time: number
19 /** Present when the text was cut down to the storage cap. */25 /** Present when the text was cut down to the storage cap. */
20 readonly truncated?: boolean26 readonly truncated?: boolean
27+ /** Present when the entry is pinned to the top of the list. */
28+ readonly pinned?: boolean
29+ /** Pin time (epoch ms) — the fixed slot order (Alt+1..9) key. */
30+ readonly pinnedAt?: number
21}31}
22 32 
23const STORAGE_KEY = 'dsh-clipboard-history'33const STORAGE_KEY = 'dsh-clipboard-history'
24const MAX_ENTRIES = 20034const MAX_ENTRIES = 200
25const MAX_ENTRY_CHARS = 20_00035const MAX_ENTRY_CHARS = 20_000
36+/** Pinned cap: aligned with the Alt+1..9 shortcuts (Issue #15). */
37+export const MAX_PINNED = 9
26 38 
27/** Trigger phrases that open the clipboard panel instead of sending a message. */39/** Trigger phrases that open the clipboard panel instead of sending a message. */
28const CLIPBOARD_TRIGGERS: ReadonlySet<string> = new Set([40const CLIPBOARD_TRIGGERS: ReadonlySet<string> = new Set([
@@ -39,10 +51,30 @@ const listeners = new Set<() => void>()
39function isEntry(value: unknown): value is ClipboardEntry {51function isEntry(value: unknown): value is ClipboardEntry {
40 if (typeof value !== 'object' || value === null) return false52 if (typeof value !== 'object' || value === null) return false
41 const record = value as Record<string, unknown>53 const record = value as Record<string, unknown>
42- return typeof record.id === 'string'54+ if (typeof record.id !== 'string') return false
43- && (record.kind === 'copy' || record.kind === 'cut' || record.kind === 'external')55+ if (record.kind !== 'copy' && record.kind !== 'cut' && record.kind !== 'external') return false
44- && typeof record.text === 'string'56+ if (typeof record.text !== 'string') return false
45- && typeof record.time === 'number'57+ if (typeof record.time !== 'number') return false
58+ // pinned/pinnedAt are optional so pre-pin legacy entries keep loading.
59+ if (record.pinned !== undefined && typeof record.pinned !== 'boolean') return false
60+ if (record.pinnedAt !== undefined && typeof record.pinnedAt !== 'number') return false
61+ return true
62+}
63+ 
64+/**
65+ * Canonical display/storage order: pinned entries first by pinnedAt ascending
66+ * (stable Alt+N slot order), then regular entries newest-first. The regular
67+ * area alone is capped at MAX_ENTRIES — pinning is exempt from that trim.
68+ */
69+function orderEntries(list: readonly ClipboardEntry[]): ClipboardEntry[] {
70+ const pinned = list
71+ .filter(entry => entry.pinned === true)
72+ .sort((a, b) => (a.pinnedAt ?? a.time) - (b.pinnedAt ?? b.time))
73+ const regular = list
74+ .filter(entry => entry.pinned !== true)
75+ .sort((a, b) => b.time - a.time)
76+ .slice(0, MAX_ENTRIES)
77+ return [...pinned, ...regular]
46}78}
47 79 
48function load(): ClipboardEntry[] {80function load(): ClipboardEntry[] {
@@ -52,7 +84,7 @@ function load(): ClipboardEntry[] {
52 if (raw === null) return []84 if (raw === null) return []
53 const parsed: unknown = JSON.parse(raw)85 const parsed: unknown = JSON.parse(raw)
54 if (!Array.isArray(parsed)) return []86 if (!Array.isArray(parsed)) return []
55- return parsed.filter(isEntry).slice(0, MAX_ENTRIES)87+ return orderEntries(parsed.filter(isEntry))
56 } catch {88 } catch {
57 return []89 return []
58 }90 }
@@ -63,9 +95,12 @@ function persist(): void {
63 try {95 try {
64 localStorage.setItem(STORAGE_KEY, JSON.stringify(entries))96 localStorage.setItem(STORAGE_KEY, JSON.stringify(entries))
65 } catch {97 } catch {
66- // Storage quota: keep roughly half the history and retry once; beyond98+ // Storage quota: shed roughly half of the regular area and retry once,
67- // that the in-memory view stays authoritative for the session.99+ // keeping every pinned entry; beyond that the in-memory view stays
68- entries = entries.slice(0, Math.max(1, Math.floor(entries.length / 2)))100+ // authoritative for the session.
101+ const pinned = entries.filter(entry => entry.pinned === true)
102+ const regular = entries.filter(entry => entry.pinned !== true)
103+ entries = orderEntries([...pinned, ...regular.slice(0, Math.max(1, Math.floor(regular.length / 2)))])
69 try {104 try {
70 localStorage.setItem(STORAGE_KEY, JSON.stringify(entries))105 localStorage.setItem(STORAGE_KEY, JSON.stringify(entries))
71 } catch {106 } catch {
@@ -86,16 +121,22 @@ export function subscribeClipboardHistory(listener: () => void): () => void {
86 }121 }
87}122}
88 123 
89-/** Current history, newest first (stable reference between mutations). */124+/** Current history: pinned area (Alt+1..9 order) first, then newest first. */
90export function getClipboardHistory(): readonly ClipboardEntry[] {125export function getClipboardHistory(): readonly ClipboardEntry[] {
91 return entries126 return entries
92}127}
93 128 
129+/** Pinned entries only, by pinnedAt ascending — index i maps to Alt+(i+1). */
130+export function getPinnedEntries(): readonly ClipboardEntry[] {
131+ return entries.filter(entry => entry.pinned === true)
132+}
133+ 
94/**134/**
95 * Record one clipboard snapshot. Global dedupe: text already present anywhere135 * Record one clipboard snapshot. Global dedupe: text already present anywhere
96 * in the history never stacks a duplicate row — the existing entry moves to136 * in the history never stacks a duplicate row — the existing entry moves to
97- * the top with a fresh time and kind instead, so the list only ever grows137+ * the top of the regular area with a fresh time and kind instead, so the list
98- * with genuinely new content.138+ * only ever grows with genuinely new content. A dedupe hit on a pinned entry
139+ * only refreshes its time/kind in place: the pin and its slot never move.
99 */140 */
100export function recordClipboardEntry(kind: ClipboardEntryKind, rawText: string): void {141export function recordClipboardEntry(kind: ClipboardEntryKind, rawText: string): void {
101 const text = rawText.replaceAll('\r\n', '\n')142 const text = rawText.replaceAll('\r\n', '\n')
@@ -106,8 +147,15 @@ export function recordClipboardEntry(kind: ClipboardEntryKind, rawText: string):
106 if (existingIndex >= 0) {147 if (existingIndex >= 0) {
107 const existing = entries[existingIndex]148 const existing = entries[existingIndex]
108 if (existing !== undefined) {149 if (existing !== undefined) {
109- const moved: ClipboardEntry = { ...existing, kind, time: Date.now() }150+ if (existing.pinned === true) {
110- entries = [moved, ...entries.filter((_, index) => index !== existingIndex)]151+ // Reuse the pinned entry: refresh metadata only, keep its slot.
152+ entries = orderEntries(entries.map((entry, index) => (
153+ index === existingIndex ? { ...existing, kind, time: Date.now() } : entry
154+ )))
155+ } else {
156+ const moved: ClipboardEntry = { ...existing, kind, time: Date.now() }
157+ entries = orderEntries([moved, ...entries.filter((_, index) => index !== existingIndex)])
158+ }
111 }159 }
112 emit()160 emit()
113 persist()161 persist()
@@ -121,11 +169,43 @@ export function recordClipboardEntry(kind: ClipboardEntryKind, rawText: string):
121 time: Date.now(),169 time: Date.now(),
122 ...(truncated ? { truncated: true } : {}),170 ...(truncated ? { truncated: true } : {}),
123 }171 }
124- entries = [entry, ...entries].slice(0, MAX_ENTRIES)172+ entries = orderEntries([entry, ...entries])
125 emit()173 emit()
126 persist()174 persist()
127}175}
128 176 
177+/**
178+ * Pin or unpin one entry by id. Pinning appends it to the end of the pinned
179+ * area (next free Alt+N slot); unpinning returns it to the top of the regular
180+ * area. Returns false without mutating when the pin cap would be exceeded —
181+ * callers surface the "unpin something first" hint. Unknown ids are a no-op.
182+ */
183+export function togglePinEntry(id: string): boolean {
184+ const index = entries.findIndex(entry => entry.id === id)
185+ if (index < 0) return false
186+ const existing = entries[index]
187+ if (existing === undefined) return false
188+ if (existing.pinned === true) {
189+ const rest: Omit<ClipboardEntry, 'pinned' | 'pinnedAt'> = {
190+ id: existing.id,
191+ kind: existing.kind,
192+ text: existing.text,
193+ truncated: existing.truncated,
194+ time: Date.now(),
195+ }
196+ // Back to the regular area, newest first.
197+ const unpinned: ClipboardEntry = { ...rest }
198+ entries = orderEntries([unpinned, ...entries.filter((_, i) => i !== index)])
199+ } else {
200+ if (getPinnedEntries().length >= MAX_PINNED) return false
201+ const pinned: ClipboardEntry = { ...existing, pinned: true, pinnedAt: Date.now() }
202+ entries = orderEntries(entries.map((entry, i) => (i === index ? pinned : entry)))
203+ }
204+ emit()
205+ persist()
206+ return true
207+}
208+ 
129/** Remove one entry by id; unknown ids are a no-op. */209/** Remove one entry by id; unknown ids are a no-op. */
130export function removeClipboardEntry(id: string): void {210export function removeClipboardEntry(id: string): void {
131 const next = entries.filter(entry => entry.id !== id)211 const next = entries.filter(entry => entry.id !== id)
@@ -213,6 +213,77 @@
213 -webkit-user-select: text;213 -webkit-user-select: text;
214}214}
215 215 
216+/* --- Pinned area (Issue #15) --- */
217+ 
218+.sectionLabel {
219+ display: flex;
220+ align-items: baseline;
221+ gap: 8px;
222+ padding: 2px 2px 0;
223+ color: #6f6f74;
224+ font-size: 11px;
225+ font-weight: 600;
226+ white-space: nowrap;
227+}
228+ 
229+.sectionHint {
230+ color: #8a8a8e;
231+ font-size: 11px;
232+ font-weight: 400;
233+ overflow: hidden;
234+ text-overflow: ellipsis;
235+}
236+ 
237+.sectionDivider {
238+ margin: 4px 0;
239+ border-top: 1px dashed rgb(0 0 0 / 15%);
240+}
241+ 
242+.pinnedEntry {
243+ border-color: rgb(224 138 30 / 45%);
244+ background: rgb(224 138 30 / 8%);
245+}
246+ 
247+.ordinalBadge {
248+ flex-shrink: 0;
249+ min-width: 18px;
250+ padding: 1px 5px;
251+ border-radius: 6px;
252+ background: #e08a1e;
253+ color: #ffffff;
254+ font-size: 11px;
255+ font-weight: 700;
256+ text-align: center;
257+}
258+ 
259+.pinBtn {
260+ display: inline-flex;
261+ align-items: center;
262+}
263+ 
264+.pinBtnOn {
265+ color: #b06f12;
266+}
267+ 
268+.pinBtn:disabled {
269+ color: #b0b0b5;
270+ cursor: not-allowed;
271+}
272+ 
273+.pinBtn:disabled:hover {
274+ background: transparent;
275+}
276+ 
277+.pinLimit {
278+ padding: 4px 8px;
279+ border: 1px solid rgb(224 138 30 / 45%);
280+ border-radius: 8px;
281+ background: rgb(224 138 30 / 8%);
282+ color: #b06f12;
283+ font-size: 12px;
284+ text-align: center;
285+}
286+ 
216.footer {287.footer {
217 padding: 7px 16px;288 padding: 7px 16px;
218 border-top: 1px solid rgb(0 0 0 / 8%);289 border-top: 1px solid rgb(0 0 0 / 8%);
@@ -254,4 +325,27 @@
254 .mini:hover {325 .mini:hover {
255 background: rgb(110 156 246 / 16%);326 background: rgb(110 156 246 / 16%);
256 }327 }
328+ 
329+ .sectionLabel {
330+ color: #9aa0a6;
331+ }
332+ 
333+ .sectionDivider {
334+ border-top-color: rgb(255 255 255 / 18%);
335+ }
336+ 
337+ .pinnedEntry,
338+ .pinLimit {
339+ border-color: rgb(224 138 30 / 50%);
340+ background: rgb(224 138 30 / 14%);
341+ }
342+ 
343+ .pinBtnOn,
344+ .pinLimit {
345+ color: #e8b56a;
346+ }
347+ 
348+ .pinBtn:disabled {
349+ color: #6f6f74;
350+ }
257}351}
@@ -7,14 +7,17 @@
7 * Recording is delegated to recorder.ts; entries persist browser-locally via7 * Recording is delegated to recorder.ts; entries persist browser-locally via
8 * history.ts, and the window position persists through localStorage.8 * history.ts, and the window position persists through localStorage.
9 */9 */
10-import { useRef, useState, useSyncExternalStore, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'10+import { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
11import { createRoot, type Root } from 'react-dom/client'11import { createRoot, type Root } from 'react-dom/client'
12import { writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'12import { writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
13import {13import {
14 clearClipboardHistory,14 clearClipboardHistory,
15 getClipboardHistory,15 getClipboardHistory,
16+ getPinnedEntries,
17+ MAX_PINNED,
16 removeClipboardEntry,18 removeClipboardEntry,
17 subscribeClipboardHistory,19 subscribeClipboardHistory,
20+ togglePinEntry,
18 type ClipboardEntry,21 type ClipboardEntry,
19 type ClipboardEntryKind,22 type ClipboardEntryKind,
20} from './history.ts'23} from './history.ts'
@@ -41,6 +44,11 @@ const T = ZH
41 copyBack: '复制',44 copyBack: '复制',
42 copied: '已复制',45 copied: '已复制',
43 remove: '删除',46 remove: '删除',
47+ pin: '固定',
48+ unpin: '取消固定',
49+ pinnedSection: '已固定',
50+ pinnedLimit: `已达固定上限(${String(MAX_PINNED)}),请先取消部分固定`,
51+ pinnedHint: '面板打开时可用 Alt+1~9 直接复制对应固定项',
44 empty: '还没有记录 — 在任意应用里复制或剪切内容,这里会实时出现。',52 empty: '还没有记录 — 在任意应用里复制或剪切内容,这里会实时出现。',
45 hint: '记录仅保存在本浏览器 · 不影响下方页面操作 · 在输入框输入「打开剪切板」可随时打开',53 hint: '记录仅保存在本浏览器 · 不影响下方页面操作 · 在输入框输入「打开剪切板」可随时打开',
46 count: (n: number): string => `${String(n)} 条记录`,54 count: (n: number): string => `${String(n)} 条记录`,
@@ -60,6 +68,11 @@ const T = ZH
60 copyBack: 'Copy',68 copyBack: 'Copy',
61 copied: 'Copied',69 copied: 'Copied',
62 remove: 'Delete',70 remove: 'Delete',
71+ pin: 'Pin',
72+ unpin: 'Unpin',
73+ pinnedSection: 'Pinned',
74+ pinnedLimit: `Pin limit reached (${String(MAX_PINNED)}) — unpin something first`,
75+ pinnedHint: 'With the panel open, Alt+1–9 copies the matching pinned entry',
63 empty: 'Nothing yet — copy or cut anywhere, and it shows up here in real time.',76 empty: 'Nothing yet — copy or cut anywhere, and it shows up here in real time.',
64 hint: 'Entries stay in this browser only · the page below stays usable · type 打开剪切板 in the composer to reopen',77 hint: 'Entries stay in this browser only · the page below stays usable · type 打开剪切板 in the composer to reopen',
65 count: (n: number): string => `${String(n)} entries`,78 count: (n: number): string => `${String(n)} entries`,
@@ -188,6 +201,49 @@ function statusText(access: SystemClipboardAccess): string {
188 }201 }
189}202}
190 203 
204+interface EntryRowProps {
205+ readonly entry: ClipboardEntry
206+ /** 1-based pinned slot (Alt+N) — undefined for regular entries. */
207+ readonly ordinal?: number
208+ readonly copied: boolean
209+ readonly pinnedFull: boolean
210+ readonly onCopy: () => void
211+ readonly onPin: () => void
212+ readonly onRemove: () => void
213+}
214+ 
215+function EntryRow({ entry, ordinal, copied, pinnedFull, onCopy, onPin, onRemove }: EntryRowProps) {
216+ const pinned = entry.pinned === true
217+ return (
218+ <article className={`${css.entry} ${pinned ? css.pinnedEntry : ''}`}>
219+ <div className={css.entryHead}>
220+ {ordinal !== undefined && <span className={css.ordinalBadge} aria-label={`Alt+${String(ordinal)}`}>{String(ordinal)}</span>}
221+ <span className={`${css.badge} ${badgeClass(entry.kind)}`}>{T.kinds[entry.kind]}</span>
222+ <time className={css.time}>{formatTime(entry.time)}</time>
223+ <div className={css.entryActions}>
224+ <button type="button" className={css.mini} onClick={onCopy}>
225+ {copied ? T.copied : T.copyBack}
226+ </button>
227+ <button
228+ type="button"
229+ className={`${css.mini} ${css.pinBtn} ${pinned ? css.pinBtnOn : ''}`}
230+ disabled={!pinned && pinnedFull}
231+ title={pinned ? T.unpin : pinnedFull ? T.pinnedLimit : T.pin}
232+ aria-pressed={pinned}
233+ onClick={onPin}
234+ >
235+ {pinned ? `📌 ${T.unpin}` : `📌 ${T.pin}`}
236+ </button>
237+ <button type="button" className={css.mini} onClick={onRemove}>
238+ {T.remove}
239+ </button>
240+ </div>
241+ </div>
242+ <div className={css.text}>{entry.text}{entry.truncated === true ? '…' : ''}</div>
243+ </article>
244+ )
245+}
246+ 
191function ClipboardPanel() {247function ClipboardPanel() {
192 const open = useSyncExternalStore(subscribeVisibility, isVisible)248 const open = useSyncExternalStore(subscribeVisibility, isVisible)
193 const entries = useSyncExternalStore(subscribeClipboardHistory, getClipboardHistory)249 const entries = useSyncExternalStore(subscribeClipboardHistory, getClipboardHistory)
@@ -242,8 +298,6 @@ function ClipboardPanel() {
242 if (final !== null) savePanelPosition(final)298 if (final !== null) savePanelPosition(final)
243 }299 }
244 300 
245- if (!open) return null
246- 
247 const copyBack = (entry: ClipboardEntry) => {301 const copyBack = (entry: ClipboardEntry) => {
248 const mark = () => {302 const mark = () => {
249 setCopiedId(entry.id)303 setCopiedId(entry.id)
@@ -256,6 +310,31 @@ function ClipboardPanel() {
256 })310 })
257 }311 }
258 312 
313+ // Alt+1..9 pastes the matching pinned entry while the panel is open
314+ // (Issue #15). The listener only lives while open, so the page keeps its
315+ // own Alt shortcuts when the window is closed.
316+ useEffect(() => {
317+ if (!open) return
318+ const onKeyDown = (event: KeyboardEvent) => {
319+ if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
320+ const code = event.code
321+ const match = /^(?:Digit|Numpad)([1-9])$/.exec(code)
322+ if (match === null) return
323+ const pinned = getPinnedEntries()
324+ const entry = pinned[Number(match[1]) - 1]
325+ if (entry === undefined) return
326+ event.preventDefault()
327+ copyBack(entry)
328+ }
329+ window.addEventListener('keydown', onKeyDown)
330+ return () => {
331+ window.removeEventListener('keydown', onKeyDown)
332+ }
333+ // entries keeps the pinned set current without a stale closure.
334+ }, [open, entries])
335+ 
336+ if (!open) return null
337+ 
259 const clearAll = () => {338 const clearAll = () => {
260 if (entries.length === 0) return339 if (entries.length === 0) return
261 // Two-step affordance instead of a blocking confirm() dialog.340 // Two-step affordance instead of a blocking confirm() dialog.
@@ -271,6 +350,10 @@ function ClipboardPanel() {
271 }, 2_500)350 }, 2_500)
272 }351 }
273 352 
353+ // Storage order already keeps pinned (Alt+N slot order) before regular.
354+ const pinnedEntries = entries.filter(entry => entry.pinned === true)
355+ const regularEntries = entries.filter(entry => entry.pinned !== true)
356+ 
274 return (357 return (
275 <div358 <div
276 ref={cardRef}359 ref={cardRef}
@@ -310,23 +393,43 @@ function ClipboardPanel() {
310 <div className={css.list}>393 <div className={css.list}>
311 {entries.length === 0394 {entries.length === 0
312 ? <div className={css.empty}>{T.empty}</div>395 ? <div className={css.empty}>{T.empty}</div>
313- : entries.map(entry => (396+ : <>
314- <article key={entry.id} className={css.entry}>397+ {pinnedEntries.length > 0 && (
315- <div className={css.entryHead}>398+ <div className={css.sectionLabel}>
316- <span className={`${css.badge} ${badgeClass(entry.kind)}`}>{T.kinds[entry.kind]}</span>399+ <span>📌 {T.pinnedSection}</span>
317- <time className={css.time}>{formatTime(entry.time)}</time>400+ <span className={css.sectionHint}>{T.pinnedHint}</span>
318- <div className={css.entryActions}>
319- <button type="button" className={css.mini} onClick={() => { copyBack(entry) }}>
320- {copiedId === entry.id ? T.copied : T.copyBack}
321- </button>
322- <button type="button" className={css.mini} onClick={() => { removeClipboardEntry(entry.id) }}>
323- {T.remove}
324- </button>
325- </div>
326 </div>401 </div>
327- <div className={css.text}>{entry.text}{entry.truncated === true ? '…' : ''}</div>402+ )}
328- </article>403+ {pinnedEntries.map((entry, index) => (
329- ))}404+ <EntryRow
405+ key={entry.id}
406+ entry={entry}
407+ ordinal={index + 1}
408+ copied={copiedId === entry.id}
409+ pinnedFull={pinnedEntries.length >= MAX_PINNED}
410+ onCopy={() => { copyBack(entry) }}
411+ onPin={() => { togglePinEntry(entry.id) }}
412+ onRemove={() => { removeClipboardEntry(entry.id) }}
413+ />
414+ ))}
415+ {pinnedEntries.length >= MAX_PINNED && (
416+ <div className={css.pinLimit}>{T.pinnedLimit}</div>
417+ )}
418+ {regularEntries.length > 0 && pinnedEntries.length > 0 && (
419+ <div className={css.sectionDivider} aria-hidden="true" />
420+ )}
421+ {regularEntries.map(entry => (
422+ <EntryRow
423+ key={entry.id}
424+ entry={entry}
425+ copied={copiedId === entry.id}
426+ pinnedFull={pinnedEntries.length >= MAX_PINNED}
427+ onCopy={() => { copyBack(entry) }}
428+ onPin={() => { togglePinEntry(entry.id) }}
429+ onRemove={() => { removeClipboardEntry(entry.id) }}
430+ />
431+ ))}
432+ </>}
330 </div>433 </div>
331 <footer className={css.footer}>{T.hint}</footer>434 <footer className={css.footer}>{T.hint}</footer>
332 </div>435 </div>
@@ -0,0 +1,44 @@
1+# Plan — Issue #15
2+ 
3+## 方案概述
4+扩展 `ClipboardEntry` 增加 `pinned`/`pinnedAt`;`history.ts` 新增 `togglePinEntry`/`getPinnedEntries` 并改造去重与自动清理;`panel.tsx` 增加固定区 UI、图钉按钮、Alt+1~9 键盘监听;`panel.module.css` 增加固定区/图钉样式。
5+ 
6+## 关键设计决策(承自 Spec)
7+| 决策 | 选择 | 理由 |
8+|------|------|------|
9+| 固定项上限 | 9 | 对齐 Alt+1~9 |
10+| 固定区排序 | pinnedAt 升序 | 序号稳定,Alt+N 映射可预期 |
11+| 去重命中固定项 | 仅更新 time/kind,位置不动 | 固定项不应被动摇 |
12+| 旧数据兼容 | isEntry 放宽 + 读取兜底 | pinned 可选字段,无破坏性 |
13+| MAX_ENTRIES 语义 | 仅约束普通区 | 固定项不参与自动清理 |
14+ 
15+## 数据形态
16+```ts
17+interface ClipboardEntry {
18+ id; kind; text; time; truncated?
19+ pinned?: boolean // 固定标记
20+ pinnedAt?: number // 固定时间(epoch ms),固定区排序键
21+}
22+```
23+存储顺序恒为:`[固定区(pinnedAt 升序), 普通区(time 降序,≤ MAX_ENTRIES)]`,渲染即存储序。
24+ 
25+## 模块改动
26+1. **assets/history.ts**
27+ - `MAX_PINNED = 9`;`isEntry` 放宽(pinned 可选,存在时须为 boolean;pinnedAt 存在时须为 number)
28+ - 内部 `orderEntries()` 统一排序;`load()` 兼容旧数据并按序规整
29+ - `recordClipboardEntry` 去重:命中固定项 → 原位更新 kind/time(不移动);新条目 → 普通区受 MAX_ENTRIES、固定区不计入
30+ - `togglePinEntry(id): boolean`:固定(检查上限)/取消固定;超限返回 false
31+ - `getPinnedEntries(): readonly ClipboardEntry[]`(pinnedAt 升序)
32+ - `persist()` 配额降级时优先保住固定项
33+2. **assets/panel.tsx**
34+ - 列表分两段:固定区(序号徽章 1~9 + 图钉标记)+ 普通区
35+ - entry 操作区增加图钉按钮;固定满 9 时未固定项的图钉置灰 + title 提示
36+ - `useEffect` 在 open 时注册 window `keydown`:Alt+1~9(含小键盘)→ `writeClipboard` + copied 标记 + `preventDefault`
37+3. **assets/panel.module.css**:`.pinnedEntry`、`.pinBtn`、`.ordinalBadge`、`.sectionLabel`、`.sectionDivider` 及暗色适配
38+ 
39+## 测试方案
40+`scripts/test-history.mjs`(node --experimental-strip-types 直跑 history.ts,localStorage 内存 shim)覆盖:固定/取消、固定区排序、上限 9 拒绝、去重复用固定项(位置不变)、MAX_ENTRIES 不清理固定项、旧数据加载兼容、删除/清空不破坏固定区。
41+ 
42+## 风险
43+- Alt+数字与浏览器/页面已有快捷键冲突 → 仅在面板 open 时监听并 preventDefault,关闭即移除
44+- 旧 localStorage 数据无 pinned → isEntry 放宽 + load 规整,无迁移脚本
@@ -0,0 +1,27 @@
1+# Spec — Issue #15 置顶固定 + Alt+1~9 快捷键(P1)
2+ 
3+> 来源:Issue #15 Spec 评论(issue agent 发布,developability: ready)。本文件为开发侧落版。
4+ 
5+## Objective
6+为剪切板历史增加「置顶固定」与「Alt+1~9 快捷键直达」:高频内容成为稳定入口,不被新条目挤下、不参与自动清理;键盘操作者一键粘贴固定项。
7+ 
8+## Scope(In)
9+1. 单条记录「固定/取消固定」图钉按钮
10+2. 固定项置顶显示、带序号 1~9 与图钉视觉标记,与普通项分区
11+3. 固定项不参与 `MAX_ENTRIES` 自动清理
12+4. 再次复制相同内容时复用已有固定项(仅更新 time/kind,位置不动)
13+5. 固定上限 `MAX_PINNED=9`(对齐 Alt+1~9),超限置灰并提示
14+6. 面板打开时 Alt+1~9 粘贴对应固定项(writeClipboard + 已复制标记)
15+7. 固定状态 localStorage 持久化;旧数据(无 pinned 字段)兼容
16+ 
17+## Out of Scope
18+- 按来源应用筛选(Web 平台限制,P2 另起 Spec)
19+- #14 的分组/排序/独立面板/标签页
20+ 
21+## Acceptance Criteria
22+- [ ] 图钉按钮可固定/取消固定,固定项置顶且带视觉标记
23+- [ ] 固定项不参与 MAX_ENTRIES 清理;重复内容复用固定项(位置不变)
24+- [ ] 上限 9,超限置灰并提示「先取消部分固定」
25+- [ ] Alt+1~9 粘贴固定项 + 已复制标记
26+- [ ] localStorage 持久化 + 旧数据兼容
27+- [ ] 现有功能(记录/去重/删除/清空/拖拽/授权)不受影响
@@ -0,0 +1,11 @@
1+# Tasks — Issue #15
2+ 
3+- [x] T1 history.ts:ClipboardEntry 扩 pinned/pinnedAt,MAX_PINNED=9,isEntry 放宽
4+- [x] T2 history.ts:orderEntries/load 规整,存储序 = 固定区(pinnedAt 升序)+普通区(time 降序)
5+- [x] T3 history.ts:recordClipboardEntry 去重命中固定项原位更新;普通区 MAX_ENTRIES 清理不含固定项
6+- [x] T4 history.ts:togglePinEntry(上限拒绝)、getPinnedEntries;persist 配额降级保护固定区
7+- [x] T5 panel.module.css:固定区/图钉/序号徽章样式 + 暗色适配
8+- [x] T6 panel.tsx:固定区渲染(序号 1~9)、图钉按钮(超限置灰+提示)
9+- [x] T7 panel.tsx:open 时 Alt+1~9 keydown → writeClipboard + copied 标记
10+- [x] T8 scripts/test-history.mjs:存储层全用例(排序/上限/去重/清理/旧数据兼容)
11+- [x] T9 自审查 + 提交 + PR
@@ -0,0 +1,31 @@
1+/**
2+ * Legacy-data load test (Issue #15): pre-pin localStorage payload must load
3+ * through the same validation path. Runs in its own process because the store
4+ * module snapshots storage once at import time.
5+ * Run: node --experimental-strip-types scripts/test-history-legacy.mjs
6+ */
7+import assert from 'node:assert/strict'
8+ 
9+const backing = new Map()
10+globalThis.localStorage = {
11+ getItem: (key) => (backing.has(key) ? backing.get(key) : null),
12+ setItem: (key, value) => { backing.set(key, String(value)) },
13+ removeItem: (key) => { backing.delete(key) },
14+}
15+ 
16+backing.set('dsh-clipboard-history', JSON.stringify([
17+ { id: 'x1', kind: 'copy', text: 'old', time: 1000 }, // legacy, no pinned fields
18+ { id: 'x2', kind: 'copy', text: 'older', time: 500 },
19+ { id: 'x3', kind: 'copy', text: 'pinned-old', time: 100, pinned: true, pinnedAt: 7 },
20+ { id: 'bad', kind: 'copy', text: 42, time: 1 }, // invalid → dropped
21+ { id: 'badpin', kind: 'copy', text: 'bad-pin', time: 2, pinned: 'yes' }, // invalid pin type → dropped
22+]))
23+ 
24+const { getClipboardHistory, getPinnedEntries } = await import('../assets/history.ts')
25+const list = getClipboardHistory()
26+assert.deepEqual(list.map(entry => entry.text), ['pinned-old', 'old', 'older'])
27+assert.equal(list[0].pinned, true)
28+assert.equal(list[1].pinned, undefined)
29+assert.deepEqual(getPinnedEntries().map(entry => entry.text), ['pinned-old'])
30+console.log('ok - legacy persisted data (no/malformed pinned fields) loads with compat')
31+console.log('1 test passed')
@@ -0,0 +1,125 @@
1+/**
2+ * Store-level tests for the pinned-history feature (Issue #15).
3+ * Run: node --experimental-strip-types scripts/test-history.mjs
4+ * Covers: pin/unpin ordering, MAX_PINNED cap, dedupe reuse of pinned entries,
5+ * MAX_ENTRIES trim exemption for pinned, legacy data compat, remove/clear.
6+ */
7+import assert from 'node:assert/strict'
8+ 
9+// In-memory localStorage shim — must exist before the store module loads.
10+const backing = new Map()
11+globalThis.localStorage = {
12+ getItem: (key) => (backing.has(key) ? backing.get(key) : null),
13+ setItem: (key, value) => { backing.set(key, String(value)) },
14+ removeItem: (key) => { backing.delete(key) },
15+}
16+ 
17+const store = await import('../assets/history.ts')
18+const {
19+ recordClipboardEntry,
20+ togglePinEntry,
21+ getPinnedEntries,
22+ getClipboardHistory,
23+ removeClipboardEntry,
24+ clearClipboardHistory,
25+ MAX_PINNED,
26+} = store
27+ 
28+let passed = 0
29+function test(name, fn) {
30+ backing.clear()
31+ clearClipboardHistory()
32+ fn()
33+ passed += 1
34+ console.log(`ok - ${name}`)
35+}
36+ 
37+const ids = (list) => list.map(entry => entry.id)
38+const texts = (list) => list.map(entry => entry.text)
39+const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
40+ 
41+test('pin/unpin: pinned area first, pinnedAt ascending, unpin returns to regular top', () => {
42+ for (const text of ['a', 'b', 'c']) { recordClipboardEntry('copy', text); sleep(2) }
43+ const [c, b, a] = getClipboardHistory() // newest first: [c, b, a]
44+ assert.equal(togglePinEntry(a.id), true) // pin oldest → slot 1
45+ sleep(2)
46+ assert.equal(togglePinEntry(b.id), true) // slot 2
47+ assert.deepEqual(texts(getClipboardHistory()), ['a', 'b', 'c'])
48+ assert.deepEqual(texts(getPinnedEntries()), ['a', 'b'])
49+ assert.equal(getClipboardHistory()[0].pinned, true)
50+ assert.equal(togglePinEntry(a.id), true) // unpin
51+ assert.deepEqual(texts(getPinnedEntries()), ['b'])
52+ assert.deepEqual(texts(getClipboardHistory()), ['b', 'a', 'c']) // a back to regular top
53+})
54+ 
55+test('MAX_PINNED cap: 10th pin rejected, unpin frees a slot', () => {
56+ for (let i = 1; i <= 10; i++) { recordClipboardEntry('copy', `t${i}`); sleep(2) }
57+ const list = getClipboardHistory()
58+ for (const entry of list.slice(0, MAX_PINNED)) assert.equal(togglePinEntry(entry.id), true)
59+ const rejected = list[MAX_PINNED]
60+ assert.equal(togglePinEntry(rejected.id), false)
61+ assert.equal(getPinnedEntries().length, MAX_PINNED)
62+ assert.equal(togglePinEntry(getPinnedEntries()[0].id), true) // unpin one
63+ assert.equal(togglePinEntry(rejected.id), true) // now fits
64+})
65+ 
66+test('dedupe on pinned entry: refreshes time/kind in place, slot never moves', () => {
67+ recordClipboardEntry('copy', 'a'); sleep(2)
68+ recordClipboardEntry('copy', 'b'); sleep(2)
69+ const [b, a] = getClipboardHistory() // newest first: [b, a]
70+ assert.equal(togglePinEntry(a.id), true) // [a(p), b]
71+ assert.equal(togglePinEntry(b.id), true) // [a(p), b(p)]
72+ sleep(2)
73+ const before = texts(getClipboardHistory())
74+ recordClipboardEntry('cut', 'a') // dedupe hits pinned a
75+ const after = getClipboardHistory()
76+ assert.deepEqual(texts(after), before) // order unchanged
77+ assert.equal(after[0].kind, 'cut') // metadata refreshed
78+ assert.equal(after[0].pinned, true)
79+ assert.equal(getPinnedEntries().length, 2)
80+})
81+ 
82+test('MAX_ENTRIES trim spares pinned entries', () => {
83+ recordClipboardEntry('copy', 'keep-me')
84+ const keep = getClipboardHistory()[0]
85+ assert.equal(togglePinEntry(keep.id), true)
86+ for (let i = 0; i < 250; i++) recordClipboardEntry('copy', `noise-${i}`)
87+ const list = getClipboardHistory()
88+ assert.equal(list[0].id, keep.id)
89+ assert.equal(list[0].pinned, true)
90+ assert.equal(list.length, 201) // 1 pinned + 200 regular
91+ const regular = list.filter(entry => entry.pinned !== true)
92+ assert.equal(regular.length, 200)
93+})
94+ 
95+test('persisted shape round-trips with pinned flags (localStorage compat)', () => {
96+ recordClipboardEntry('copy', 'a'); sleep(2)
97+ const a = getClipboardHistory()[0]
98+ togglePinEntry(a.id)
99+ const raw = JSON.parse(backing.get('dsh-clipboard-history'))
100+ assert.equal(raw[0].pinned, true)
101+ assert.equal(typeof raw[0].pinnedAt, 'number')
102+})
103+ 
104+test('remove and clear still work around pinned entries', () => {
105+ recordClipboardEntry('copy', 'a'); sleep(2)
106+ recordClipboardEntry('copy', 'b')
107+ const [b, a] = getClipboardHistory() // newest first: [b, a]
108+ togglePinEntry(a.id)
109+ removeClipboardEntry(b.id)
110+ assert.deepEqual(texts(getClipboardHistory()), ['a'])
111+ removeClipboardEntry(a.id) // removing a pinned entry is allowed
112+ assert.deepEqual(texts(getClipboardHistory()), [])
113+ recordClipboardEntry('copy', 'c')
114+ clearClipboardHistory()
115+ assert.deepEqual(texts(getClipboardHistory()), [])
116+})
117+ 
118+test('unknown ids: togglePin/remove are safe no-ops', () => {
119+ recordClipboardEntry('copy', 'a')
120+ assert.equal(togglePinEntry('nope'), false)
121+ removeClipboardEntry('nope')
122+ assert.equal(getClipboardHistory().length, 1)
123+})
124+ 
125+console.log(`\n${passed} tests passed`)