@huanlin/dsh-plugin-input-history 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +138 -0
- package/lib/client.js.map +1 -1
- package/lib/types/client/dictionaries.d.ts +17 -0
- package/lib/types/client/dictionaries.js +114 -0
- package/lib/types/client/index.js +23 -0
- package/package.json +1 -1
package/lib/client.js
CHANGED
|
@@ -367,6 +367,129 @@ const zh = {
|
|
|
367
367
|
noHistory: "暂无提示词历史"
|
|
368
368
|
};
|
|
369
369
|
|
|
370
|
+
//#endregion
|
|
371
|
+
//#region src/client/dictionaries.ts
|
|
372
|
+
const ja = {
|
|
373
|
+
ariaLabel: "プロンプト履歴のナビゲーション(↑/↓キー)",
|
|
374
|
+
restoredDraft: "編集中の下書きを復元しました",
|
|
375
|
+
noHistory: "プロンプト履歴はまだありません"
|
|
376
|
+
};
|
|
377
|
+
const de = {
|
|
378
|
+
ariaLabel: "Befehlsverlauf-Navigation (Pfeil hoch/runter)",
|
|
379
|
+
restoredDraft: "In Bearbeitung befindlicher Entwurf wiederhergestellt",
|
|
380
|
+
noHistory: "Noch kein Befehlsverlauf vorhanden"
|
|
381
|
+
};
|
|
382
|
+
const fr = {
|
|
383
|
+
ariaLabel: "Navigation dans l'historique des invites (flèche haut/bas)",
|
|
384
|
+
restoredDraft: "Brouillon en cours d'édition restauré",
|
|
385
|
+
noHistory: "Pas encore d'historique d'invites"
|
|
386
|
+
};
|
|
387
|
+
const pt = {
|
|
388
|
+
ariaLabel: "Navegação no histórico de prompts (seta para cima/baixo)",
|
|
389
|
+
restoredDraft: "Rascunho em edição restaurado",
|
|
390
|
+
noHistory: "Ainda não há histórico de prompts"
|
|
391
|
+
};
|
|
392
|
+
const ko = {
|
|
393
|
+
ariaLabel: "프롬프트 기록 탐색 (위/아래 화살표)",
|
|
394
|
+
restoredDraft: "편집 중이던 초안을 복원했습니다",
|
|
395
|
+
noHistory: "아직 프롬프트 기록이 없습니다"
|
|
396
|
+
};
|
|
397
|
+
const ar = {
|
|
398
|
+
ariaLabel: "التنقل في سجل الأوامر (السهم لأعلى/لأسفل)",
|
|
399
|
+
restoredDraft: "تمت استعادة المسودة قيد التحرير",
|
|
400
|
+
noHistory: "لا يوجد سجل أوامر بعد"
|
|
401
|
+
};
|
|
402
|
+
const hi = {
|
|
403
|
+
ariaLabel: "प्रॉम्प्ट इतिहास नेविगेशन (ऊपर/नीचे तीर)",
|
|
404
|
+
restoredDraft: "संपादन में मौजूद ड्राफ्ट पुनर्स्थापित किया गया",
|
|
405
|
+
noHistory: "अभी तक कोई प्रॉम्प्ट इतिहास नहीं"
|
|
406
|
+
};
|
|
407
|
+
const id = {
|
|
408
|
+
ariaLabel: "Navigasi riwayat prompt (panah atas/bawah)",
|
|
409
|
+
restoredDraft: "Draf yang sedang diedit dipulihkan",
|
|
410
|
+
noHistory: "Belum ada riwayat prompt"
|
|
411
|
+
};
|
|
412
|
+
const tr = {
|
|
413
|
+
ariaLabel: "Komut geçmişinde gezinme (yukarı/aşağı ok)",
|
|
414
|
+
restoredDraft: "Düzenlenmekte olan taslak geri yüklendi",
|
|
415
|
+
noHistory: "Henüz komut geçmişi yok"
|
|
416
|
+
};
|
|
417
|
+
const vi = {
|
|
418
|
+
ariaLabel: "Điều hướng lịch sử lệnh (mũi tên lên/xuống)",
|
|
419
|
+
restoredDraft: "Đã khôi phục bản nháp đang soạn",
|
|
420
|
+
noHistory: "Chưa có lịch sử lệnh"
|
|
421
|
+
};
|
|
422
|
+
const th = {
|
|
423
|
+
ariaLabel: "นำทางประวัติคำสั่ง (ลูกศรขึ้น/ลง)",
|
|
424
|
+
restoredDraft: "กู้คืนฉบับร่างที่กำลังแก้ไขแล้ว",
|
|
425
|
+
noHistory: "ยังไม่มีประวัติคำสั่ง"
|
|
426
|
+
};
|
|
427
|
+
const ru = {
|
|
428
|
+
ariaLabel: "Навигация по истории запросов (стрелки вверх/вниз)",
|
|
429
|
+
restoredDraft: "Текущий черновик восстановлен",
|
|
430
|
+
noHistory: "Истории запросов пока нет"
|
|
431
|
+
};
|
|
432
|
+
const it = {
|
|
433
|
+
ariaLabel: "Navigazione cronologia prompt (freccia su/giù)",
|
|
434
|
+
restoredDraft: "Bozza in corso ripristinata",
|
|
435
|
+
noHistory: "Nessuna cronologia prompt finora"
|
|
436
|
+
};
|
|
437
|
+
const nl = {
|
|
438
|
+
ariaLabel: "Navigatie door promptgeschiedenis (pijl omhoog/omlaag)",
|
|
439
|
+
restoredDraft: "Lopende concept hersteld",
|
|
440
|
+
noHistory: "Nog geen promptgeschiedenis"
|
|
441
|
+
};
|
|
442
|
+
const sv = {
|
|
443
|
+
ariaLabel: "Navigera i prompthistorik (pil upp/ner)",
|
|
444
|
+
restoredDraft: "Utkast under arbete återställt",
|
|
445
|
+
noHistory: "Ingen prompthistorik ännu"
|
|
446
|
+
};
|
|
447
|
+
const pl = {
|
|
448
|
+
ariaLabel: "Nawigacja po historii promptów (strzałka w górę/w dół)",
|
|
449
|
+
restoredDraft: "Przywrócono edytowany szkic",
|
|
450
|
+
noHistory: "Brak jeszcze historii promptów"
|
|
451
|
+
};
|
|
452
|
+
const zhHK = {
|
|
453
|
+
ariaLabel: "提示詞歷史導覽(上/下方向鍵)",
|
|
454
|
+
restoredDraft: "已還原正在編輯的草稿",
|
|
455
|
+
noHistory: "暫無提示詞歷史"
|
|
456
|
+
};
|
|
457
|
+
const zhTW = {
|
|
458
|
+
ariaLabel: "提示詞歷史導覽(上/下方向鍵)",
|
|
459
|
+
restoredDraft: "已還原正在編輯的草稿",
|
|
460
|
+
noHistory: "暫無提示詞歷史"
|
|
461
|
+
};
|
|
462
|
+
const zhMO = {
|
|
463
|
+
ariaLabel: "提示詞歷史導覽(上/下方向鍵)",
|
|
464
|
+
restoredDraft: "已還原正在編輯的草稿",
|
|
465
|
+
noHistory: "暫無提示詞歷史"
|
|
466
|
+
};
|
|
467
|
+
/**
|
|
468
|
+
* All override dictionaries, keyed by language id, covering the full key
|
|
469
|
+
* set. Registered with better-locale under the plugin namespace.
|
|
470
|
+
*/
|
|
471
|
+
const dicts = {
|
|
472
|
+
ja,
|
|
473
|
+
de,
|
|
474
|
+
fr,
|
|
475
|
+
pt,
|
|
476
|
+
ko,
|
|
477
|
+
ar,
|
|
478
|
+
hi,
|
|
479
|
+
id,
|
|
480
|
+
tr,
|
|
481
|
+
vi,
|
|
482
|
+
th,
|
|
483
|
+
ru,
|
|
484
|
+
it,
|
|
485
|
+
nl,
|
|
486
|
+
sv,
|
|
487
|
+
pl,
|
|
488
|
+
"zh-HK": zhHK,
|
|
489
|
+
"zh-TW": zhTW,
|
|
490
|
+
"zh-MO": zhMO
|
|
491
|
+
};
|
|
492
|
+
|
|
370
493
|
//#endregion
|
|
371
494
|
//#region src/client/index.ts
|
|
372
495
|
/** Required services: slots + locale. */
|
|
@@ -388,6 +511,21 @@ function apply(ctx) {
|
|
|
388
511
|
zh,
|
|
389
512
|
en
|
|
390
513
|
}), "dsh-plugin-input-history: dictionaries");
|
|
514
|
+
ctx.effect(() => {
|
|
515
|
+
let dispose;
|
|
516
|
+
const sync = () => {
|
|
517
|
+
dispose?.();
|
|
518
|
+
dispose = void 0;
|
|
519
|
+
const store = ctx.get("betterLocale");
|
|
520
|
+
if (store !== void 0) dispose = store.register(NS, dicts);
|
|
521
|
+
};
|
|
522
|
+
sync();
|
|
523
|
+
const unsubscribe = ctx.locale.subscribe(sync);
|
|
524
|
+
return () => {
|
|
525
|
+
unsubscribe();
|
|
526
|
+
dispose?.();
|
|
527
|
+
};
|
|
528
|
+
}, "dsh-plugin-input-history: better-locale override dicts");
|
|
391
529
|
ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
|
|
392
530
|
name: "conversation.composer.dock",
|
|
393
531
|
id: "dsh-plugin-input-history",
|
package/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["capacity: number","parsed: unknown","historyStore: HistoryStore | null","en: Record<InputHistoryKey, string>","zh: Record<InputHistoryKey, string>","navCursor: number | null","savedDraft: string | null"],"sources":["../src/client/history.ts","../src/client/HistoryDock.tsx","../src/client/ime.ts","../src/client/dom.ts","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Prompt history store — pure functions over a string array.\n *\n * The store is a FIFO list of unique prompt strings, persisted to\n * `localStorage`. Newest entries are at the end of the array. The\n * navigation cursor walks backwards from the end (ArrowUp = older,\n * ArrowDown = newer).\n *\n * The functions in this module are pure (no `localStorage` access) so\n * they can be unit-tested without jsdom. The `HistoryStore` class below\n * wires them to `localStorage` with try/catch containment — a quota\n * exception or a disabled storage (private mode) degrades gracefully to\n * an in-memory list that lives for the page lifetime.\n *\n * @module @huanlin/dsh-plugin-input-history/client/history\n */\n\n/** localStorage key (versioned; bump on schema changes to start fresh). */\nexport const STORAGE_KEY = 'dsh-plugin-input-history:v1'\n\n/** Default capacity when none is configured. */\nexport const DEFAULT_CAPACITY = 500\n\n/**\n * Append a prompt to the history.\n *\n * Rules:\n * - Empty / whitespace-only strings are ignored (the InputBar already\n * rejects them at submit, but defensive).\n * - When the new entry equals the most recent one, it is a no-op\n * (avoids stacking duplicates from rapid resends).\n * - When the new entry already exists earlier in the history, that\n * earlier occurrence is removed (recency wins; the prompt moves to\n * the end). This mirrors terminal shell behaviour.\n * - When the array would exceed `capacity`, the oldest entries are\n * dropped from the front (FIFO).\n *\n * @param history - the current history array (newest at end).\n * @param prompt - the prompt to append.\n * @param capacity - the maximum number of entries to retain.\n * @returns the new history array (may be the same reference if no-op).\n */\nexport function appendHistory(\n history: readonly string[],\n prompt: string,\n capacity: number = DEFAULT_CAPACITY,\n): string[] {\n const trimmed = prompt.trim()\n if (trimmed === '') return history as string[]\n // Latest-equal with no earlier duplicate: true no-op (same reference).\n // When an earlier duplicate exists, the filter below removes it so the\n // entry moves to the end (recency wins).\n const lastIndex = history.lastIndexOf(trimmed)\n if (lastIndex !== -1 && lastIndex === history.length - 1 && history.indexOf(trimmed) === lastIndex) {\n return history as string[]\n }\n // Remove any earlier occurrence (recency wins).\n const filtered = history.filter(item => item !== trimmed)\n filtered.push(trimmed)\n // FIFO: drop oldest entries from the front.\n const cap = Math.max(1, capacity)\n if (filtered.length > cap) {\n return filtered.slice(filtered.length - cap)\n }\n return filtered\n}\n\n/**\n * Navigation cursor for walking the history.\n *\n * The cursor is `null` when the user is not navigating (i.e. they are\n * typing a fresh draft). ArrowUp sets it to the last index, then\n * decrements; ArrowDown increments; when it would exceed `history.length\n * - 1`, it returns to `null` (meaning \"restore the in-progress draft\").\n *\n * @param current - the current cursor (null = not navigating).\n * @param total - the total number of history entries.\n * @param dir - `'up'` (older) or `'down'` (newer).\n * @returns the next cursor, or `null` when navigation falls off the\n * newest end (caller should restore the saved draft).\n */\nexport function nextIndex(\n current: number | null,\n total: number,\n dir: 'up' | 'down',\n): number | null {\n if (total === 0) return null\n if (dir === 'up') {\n if (current === null) return total - 1\n if (current <= 0) return 0\n return current - 1\n }\n // dir === 'down'\n if (current === null) return null\n if (current >= total - 1) return null\n return current + 1\n}\n\n/**\n * Read the history entry at a cursor, or `null` when the cursor is null.\n *\n * @param history - the history array.\n * @param cursor - the navigation cursor.\n * @returns the prompt at the cursor, or `null`.\n */\nexport function entryAt(\n history: readonly string[],\n cursor: number | null,\n): string | null {\n if (cursor === null) return null\n if (cursor < 0 || cursor >= history.length) return null\n return history[cursor] ?? null\n}\n\n/**\n * History store bound to `localStorage`.\n *\n * The store reads once on construction (or on `reload()`) and keeps an\n * in-memory copy. Writes go to both memory and `localStorage` inside a\n * try/catch — a quota exception leaves the in-memory copy authoritative\n * for the rest of the page lifetime. This trades cross-tab consistency\n * for resilience: the store never throws on a write, and the worst case\n * is that a tab keeps its own view until refresh.\n *\n * Cross-tab sync is intentionally NOT implemented: prompt history is\n * append-mostly and a stale read across tabs is harmless (the next\n * append corrects it). Listening to the `storage` event would add\n * reactivity that the navigation UI does not need.\n */\nexport class HistoryStore {\n private items: string[]\n private readonly storage: Storage | null\n private readonly key: string\n\n /**\n * @param capacity - maximum entries to retain (FIFO).\n * @param storage - the storage backend (defaults to `localStorage` when available).\n * @param key - the storage key (defaults to {@link STORAGE_KEY}).\n */\n constructor(\n private readonly capacity: number = DEFAULT_CAPACITY,\n storage?: Storage | null,\n key: string = STORAGE_KEY,\n ) {\n this.storage = storage ?? safeLocalStorage()\n this.key = key\n this.items = this.readFromStorage()\n }\n\n /** Current history snapshot (newest at end). */\n get list(): readonly string[] {\n return this.items\n }\n\n /** Number of entries currently stored. */\n get length(): number {\n return this.items.length\n }\n\n /** Reload from storage (e.g. after a suspected external edit). Truncates to the current capacity. */\n reload(): void {\n const loaded = this.readFromStorage()\n const cap = Math.max(1, this.capacity)\n this.items = loaded.length > cap ? loaded.slice(loaded.length - cap) : loaded\n }\n\n /**\n * Append a prompt and persist. See {@link appendHistory} for rules.\n * @returns the new history snapshot.\n */\n append(prompt: string): readonly string[] {\n this.items = appendHistory(this.items, prompt, this.capacity)\n this.writeToStorage()\n return this.items\n }\n\n /** Clear all history (used by tests and a future \"clear\" UI). */\n clear(): void {\n this.items = []\n this.writeToStorage()\n }\n\n private readFromStorage(): string[] {\n if (this.storage === null) return []\n try {\n const raw = this.storage.getItem(this.key)\n if (raw === null) return []\n const parsed: unknown = JSON.parse(raw)\n if (!Array.isArray(parsed)) return []\n return parsed.filter((item): item is string => typeof item === 'string')\n } catch {\n return []\n }\n }\n\n private writeToStorage(): void {\n if (this.storage === null) return\n try {\n this.storage.setItem(this.key, JSON.stringify(this.items))\n } catch {\n // Quota exceeded, private mode, or disabled storage: keep the\n // in-memory copy authoritative for the rest of the page lifetime.\n }\n }\n}\n\n/** Safe accessor for `localStorage` that returns null on any failure. */\nfunction safeLocalStorage(): Storage | null {\n try {\n if (typeof localStorage === 'undefined') return null\n return localStorage\n } catch {\n return null\n }\n}\n","/**\n * HistoryDock — invisible dock entry that collects prompt history.\n *\n * Registers as a `conversation.composer.dock` list entry and renders an\n * `aria-hidden` anchor (zero layout footprint). The dock's only job is\n * history collection: every render reads `props.session.nodes` and\n * appends new user/steering text to the module-scope `HistoryStore`.\n *\n * The keydown listener that drives navigation lives in `apply` (module\n * scope), NOT in this dock — because the dock is session-scoped and\n * DSH treats blank sessions as \"hero\" (ConversationRoot.tsx:79-80),\n * which suppresses the dock entirely (`!hero` guard at line 156).\n * Moving the listener to `apply` ensures it is always attached,\n * regardless of hero/blank/active session state.\n *\n * @module @huanlin/dsh-plugin-input-history/client/HistoryDock\n */\n\nimport { useRef } from 'react'\nimport type { PropsRuntime, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: SlotMap merge for 'conversation.composer.dock' + SessionStandardProps.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { HistoryStore, DEFAULT_CAPACITY } from './history.ts'\n\n/** Full props: dock runtime share + locale seat. */\ntype HistoryDockProps = PropsRuntime<'conversation.composer.dock'> & PropsLocale<'dsh-plugin-input-history'>\n\n/**\n * Module-scope history store, initialized once on first dock mount.\n * Shared with the keydown listener in `apply` via `getHistoryStore()`.\n */\nlet historyStore: HistoryStore | null = null\n\n/** Get the shared history store (initializes lazily on first call). */\nexport function getHistoryStore(): HistoryStore {\n if (historyStore === null) {\n historyStore = new HistoryStore(DEFAULT_CAPACITY)\n }\n return historyStore\n}\n\n/**\n * Render the invisible history-collection dock entry.\n *\n * @param props - dock runtime share (InputZone owner + session kit) + locale seat.\n * @returns an `aria-hidden` anchor with zero layout footprint.\n */\nexport function HistoryDock({ session }: HistoryDockProps) {\n const store = getHistoryStore()\n\n // History collection: diff the last user/steering text against the\n // previously-seen tail and append on change. Runs every render (cheap:\n // O(n) over the tail nodes, breaks early once a user/steering node is\n // found). The store dedupes internally, so re-appends are no-ops.\n const lastSeenTextRef = useRef<string | null>(null)\n const lastText = latestUserOrSteeringText(session.nodes)\n if (lastText !== null && lastText !== lastSeenTextRef.current) {\n lastSeenTextRef.current = lastText\n store.append(lastText)\n }\n\n // `display: none` keeps the anchor out of layout and out of the\n // a11y tree. The dock is purely a lifecycle anchor for history\n // collection; the keydown listener lives in `apply`.\n return <div aria-hidden style={{ display: 'none' }} data-dsh-plugin-input-history=\"\" />\n}\n\n/**\n * Extract the text of the latest `user` or `steering` node from a\n * conversation snapshot's nodes list.\n *\n * Returns the concatenated text of all `type: 'text'` content blocks.\n * Returns `null` when no user/steering node is present (e.g. a fresh\n * session with only a system/context message).\n *\n * @param nodes - the conversation snapshot's `nodes` array.\n */\nfunction latestUserOrSteeringText(\n nodes: ReadonlyArray<{\n kind: string\n content?: ReadonlyArray<{ type: string; text?: string }>\n }>,\n): string | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (node.kind !== 'user' && node.kind !== 'steering') continue\n const content = node.content\n if (content === undefined) continue\n let text = ''\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n text += block.text\n }\n }\n return text\n }\n return null\n}\n","/**\n * IME-composition key guard.\n *\n * While a Chinese/Japanese/Korean input method is composing (the user is\n * picking a candidate from the IME window), every pressed key BELONGS to\n * the input method: arrows move the candidate highlight, Enter/Space\n * confirm the composition, Escape cancels it. Page code must not process\n * those keys — a history-navigation handler that calls `preventDefault()`\n * on ArrowUp/ArrowDown during composition would silently break the IME:\n * candidates stop responding, the composition gets torn apart, and only\n * bare letters come out.\n *\n * The composition signal follows the DSH core convention (InputBar's IME\n * guard, issue #535): `isComposing` for modern engines, keyCode 229 as\n * the legacy signal engines emit without isComposing.\n *\n * @module @huanlin/dsh-plugin-input-history/client/ime\n */\n\n/** The pure decision: is this keyboard event part of an IME composition? */\nexport function isImeComposition(event: { isComposing: boolean; keyCode: number }): boolean {\n return event.isComposing || event.keyCode === 229\n}\n","/**\n * DOM helpers for the composer textarea.\n *\n * The DSH InputBar's textarea is not exposed through any public API —\n * plugins cannot obtain a React ref or a slot-currency handle to it.\n * The two operations this plugin needs (locate the textarea, decide\n * whether the caret is on the first/last line of a multi-line draft) are\n * pure functions over DOM and string state, kept here for unit testing.\n *\n * The locator queries the stable (but undocumented) `data-composer-card`\n * attribute on the composer card root (`InputBar.tsx:629`) and returns\n * the descendant `<textarea>`. The attribute is internal to\n * `@deepseek-ai/dsh-client-ui-conversation` and may change across\n * upstream versions; the locator is the single point to update.\n *\n * @module @huanlin/dsh-plugin-input-history/client/dom\n */\n\n/** Caret line information for a multi-line textarea value. */\nexport interface CursorLineInfo {\n /** 0-based index of the line the caret is on. */\n readonly currentLine: number\n /** Total number of lines in the value (>= 1). */\n readonly totalLines: number\n /** True when the caret is collapsed and on the first line. */\n readonly atFirstLine: boolean\n /** True when the caret is collapsed and on the last line. */\n readonly atLastLine: boolean\n}\n\n/**\n * Compute the caret's line position in a textarea value.\n *\n * Lines are split on `\\n` (the textarea's own line break character). The\n * caret must be collapsed (`selectionStart === selectionEnd`) for the\n * `atFirstLine` / `atLastLine` flags to be true — a non-collapsed\n * selection spanning multiple lines should not trigger history navigation.\n *\n * @param value - the textarea's current value.\n * @param selectionStart - the textarea's `selectionStart`.\n * @param selectionEnd - the textarea's `selectionEnd` (defaults to `selectionStart`).\n * @returns the caret's line information.\n */\nexport function cursorLineInfo(\n value: string,\n selectionStart: number,\n selectionEnd: number = selectionStart,\n): CursorLineInfo {\n // Swap if reversed (the browser allows selectionStart > selectionEnd when\n // the user drags upwards); clamp to value bounds.\n const rawStart = Math.min(selectionStart, selectionEnd)\n const rawEnd = Math.max(selectionStart, selectionEnd)\n const clampedStart = Math.max(0, Math.min(rawStart, value.length))\n const clampedEnd = Math.max(clampedStart, Math.min(rawEnd, value.length))\n const collapsed = clampedStart === clampedEnd\n const lines = value.split('\\n')\n const totalLines = lines.length\n let currentLine = 0\n let runningLength = 0\n for (let i = 0; i < totalLines; i++) {\n const line = lines[i]!\n // The caret at position `p` belongs to line `i` if `p` is in\n // [runningLength, runningLength + line.length + 1) — the `+1` covers\n // the position immediately after the line's last character, which is\n // still on this line (right before the `\\n`). The very end of the\n // value (after the last line's last char) belongs to the last line.\n const lineEnd = runningLength + line.length\n const isLastLine = i === totalLines - 1\n const upperBound = isLastLine ? lineEnd + 1 : lineEnd + 1 // include the `\\n` position\n if (clampedStart >= runningLength && clampedStart < upperBound) {\n currentLine = i\n break\n }\n runningLength = lineEnd + 1 // +1 for the `\\n`\n }\n return {\n currentLine,\n totalLines,\n atFirstLine: collapsed && currentLine === 0,\n atLastLine: collapsed && currentLine === totalLines - 1,\n }\n}\n\n/**\n * Locate the DSH composer textarea in the current document.\n *\n * Walks from the event target up to find the closest `[data-composer-card]`\n * ancestor, then queries the descendant `<textarea>` inside it. Returns\n * `null` when the target is not inside the composer card (e.g. the user\n * is typing in another input or the textarea is momentarily absent).\n *\n * When called without an event target, falls back to a document-wide\n * query — used in tests and ad-hoc probing.\n *\n * @param from - the event target (or any node inside the composer card).\n * @returns the textarea element, or `null` when not found.\n */\nexport function findComposerTextarea(from?: EventTarget | null): HTMLTextAreaElement | null {\n if (typeof document === 'undefined') return null\n if (from === undefined) {\n // No argument: document-wide query.\n return document.querySelector<HTMLTextAreaElement>('[data-composer-card] textarea')\n }\n // `null` or an actual target: do NOT fall back to document-wide query.\n if (from === null) return null\n // `closest` is on Element; EventTarget may be a Text node or other\n // non-Element node. Narrow with an instanceof check.\n const card = from instanceof Element ? from.closest('[data-composer-card]') : null\n if (card !== null) {\n const ta = card.querySelector<HTMLTextAreaElement>('textarea')\n if (ta !== null) return ta\n }\n return null\n}\n","/**\n * Locale dictionaries for dsh-plugin-input-history.\n *\n * The plugin renders nothing visible — the only user-facing copy is the\n * `aria-label` on the invisible dock anchor (for screen readers) and a\n * future settings row label.\n *\n * @module @huanlin/dsh-plugin-input-history/client/locales\n */\n\n/** All copy keys for the dsh-plugin-input-history namespace. */\nexport type InputHistoryKey =\n | 'ariaLabel'\n | 'restoredDraft'\n | 'noHistory'\n\n/** Locale namespace id (matches the cordis.patch.yml plugin id). */\nexport const NS = 'dsh-plugin-input-history'\n\n/** English dictionary. */\nexport const en: Record<InputHistoryKey, string> = {\n ariaLabel: 'Prompt history navigation (ArrowUp/ArrowDown)',\n restoredDraft: 'Restored in-progress draft',\n noHistory: 'No prompt history yet',\n}\n\n/** Chinese dictionary. */\nexport const zh: Record<InputHistoryKey, string> = {\n ariaLabel: '提示词历史导航(上/下方向键)',\n restoredDraft: '已恢复正在编辑的草稿',\n noHistory: '暂无提示词历史',\n}\n","/**\n * dsh-plugin-input-history — browser half.\n *\n * Two registrations:\n * - `conversation.composer.dock` list slot (id `dsh-plugin-input-history`,\n * order 100) — renders an invisible anchor that collects history from\n * `session.nodes` every render. The dock is session-scoped; DSH treats\n * blank sessions as \"hero\" and suppresses the dock, so history\n * collection only runs in active sessions. That is fine: the first\n * message in a blank session is collected after the session becomes\n * active (the message makes it non-blank).\n * - A document-level `keydown` listener attached in `apply` (NOT in the\n * dock component) — this ensures the listener is always active,\n * including in hero/blank mode where the dock is suppressed. The\n * listener uses the native `value` setter + `dispatchEvent('input')`\n * to feed history text into the textarea, which triggers InputBar's\n * `onChange` → `keyboard.setDraft` — the same path the user's typing\n * takes.\n *\n * History is collected from `user` and `steering` conversation nodes as\n * they appear in any session's `ConversationSnapshot`, persisted to\n * `localStorage` (FIFO, 500 entries), and shared across all sessions\n * in the same browser profile.\n *\n * @module @huanlin/dsh-plugin-input-history/client\n */\n\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the shell's SlotMap merge (conversation.composer.dock)\n// + SessionStandardProps (useInput, inputActions).\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { HistoryDock, getHistoryStore } from './HistoryDock.tsx'\nimport { isImeComposition } from './ime.ts'\nimport { cursorLineInfo, findComposerTextarea } from './dom.ts'\nimport { nextIndex, entryAt } from './history.ts'\nimport { en, NS, zh, type InputHistoryKey } from './locales.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** The dock's aria-label + future settings row copy. */\n 'dsh-plugin-input-history': InputHistoryKey\n }\n}\n\n/** Required services: slots + locale. */\nexport const inject = ['slots', 'locale']\n\n/**\n * Navigation cursor + saved draft for the keydown listener. Module-scoped\n * because the listener is attached once in `apply` and must persist across\n * dock mount/unmount cycles.\n */\nlet navCursor: number | null = null\nlet savedDraft: string | null = null\n\n/**\n * Client plugin body: register the dock + attach the keydown listener.\n *\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugin-input-history: dictionaries')\n\n // The dock collects history from session.nodes. It is session-scoped;\n // in hero/blank mode it is suppressed, but the keydown listener below\n // still works (it reads from the module-scope HistoryStore, which\n // persists across dock mount/unmount cycles via localStorage).\n ctx.slots.inject('conversation.composer.dock', () =>\n ctx.slots.register(\n {\n name: 'conversation.composer.dock',\n id: 'dsh-plugin-input-history',\n order: 100,\n locale: NS,\n },\n HistoryDock,\n ),\n )\n\n // Attach the document-level keydown listener. This lives in `apply`\n // (not in the dock component) so it stays active even when the dock is\n // suppressed (hero/blank sessions — ConversationRoot.tsx:79-80 treats\n // blank sessions as hero, and line 156 skips the dock render).\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const handler = (event: KeyboardEvent): void => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return\n if (isImeComposition(event)) return\n if (event.defaultPrevented) return\n const textarea = findComposerTextarea(event.target)\n if (textarea === null) return\n if (event.target !== textarea) return\n // Skip if the textarea is readOnly or disabled — hero mode's\n // workspace-picker trigger, or a submitting machine phase.\n if (textarea.readOnly || textarea.disabled) return\n\n const store = getHistoryStore()\n const history = store.list\n\n // Multi-line boundary check.\n const info = cursorLineInfo(textarea.value, textarea.selectionStart, textarea.selectionEnd)\n if (event.key === 'ArrowUp' && !info.atFirstLine) return\n if (event.key === 'ArrowDown' && !info.atLastLine) return\n\n const dir = event.key === 'ArrowUp' ? 'up' : 'down'\n const next = nextIndex(navCursor, history.length, dir)\n\n // Down off the newest end: restore the saved draft (if any).\n if (next === null) {\n const saved = savedDraft\n navCursor = null\n if (saved !== null) {\n setNativeTextareaValue(textarea, saved)\n savedDraft = null\n }\n event.preventDefault()\n return\n }\n\n // Entering history: save the current draft the first time we\n // navigate away from \"not navigating\".\n if (navCursor === null && savedDraft === null) {\n savedDraft = textarea.value\n }\n\n const entry = entryAt(history, next)\n if (entry === null) return\n navCursor = next\n setNativeTextareaValue(textarea, entry)\n event.preventDefault()\n }\n document.addEventListener('keydown', handler, false)\n return () => {\n document.removeEventListener('keydown', handler, false)\n }\n }, 'dsh-plugin-input-history: keydown listener')\n}\n\n/**\n * Set the textarea value via the native prototype setter and dispatch an\n * `input` event so React's controlled-component onChange fires.\n *\n * React 18 tracks the textarea's value internally; directly assigning\n * `textarea.value = x` does NOT trigger React's onChange because React's\n * value tracker compares against its last-seen value. Using the native\n * prototype setter bypasses React's tracker, and the dispatched `input`\n * event makes React detect the change and run InputBar's `onChange` →\n * `keyboard.setDraft(next)`. This is the same technique used by\n * browser automation libraries (Playwright, Testing Library) to simulate\n * user typing in React controlled inputs.\n *\n * @param textarea - the target textarea element.\n * @param value - the new value to set.\n */\nfunction setNativeTextareaValue(textarea: HTMLTextAreaElement, value: string): void {\n const proto = window.HTMLTextAreaElement.prototype\n const descriptor = Object.getOwnPropertyDescriptor(proto, 'value')\n if (descriptor === undefined || descriptor.set === undefined) {\n // Fallback: direct assignment (may not trigger React onChange in\n // all browsers, but better than nothing).\n textarea.value = value\n return\n }\n descriptor.set.call(textarea, value)\n textarea.dispatchEvent(new Event('input', { bubbles: true }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,cAAc;;AAG3B,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;AAqBhC,SAAgB,cACd,SACA,QACA,WAAmB,kBACT;CACV,MAAM,UAAU,OAAO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AK,YAAa;AAClD,OAAI,MAAM,QAAQ,eAAe,CAAC,KAAK,WAAY;GAEnD,MAAM,MAAM,MAAM,QAAQ,YAAY,OAAO;GAC7C,MAAM,OAAO,UAAU,WAAW,QAAQ,QAAQ,IAAI;AAGtD,OAAI,SAAS,MAAM;IACjB,MAAM,QAAQ;AACd,gBAAY;AACZ,QAAI,UAAU,MAAM;AAClB,4BAAuB,UAAU,MAAM;AACvC,kBAAa;;AAEf,UAAM,gBAAgB;AACtB;;AAKF,OAAI,cAAc,QAAQ,eAAe,KACvC,cAAa,SAAS;GAGxB,MAAM,QAAQ,QAAQ,SAAS,KAAK;AACpC,OAAI,UAAU,KAAM;AACpB,eAAY;AACZ,0BAAuB,UAAU,MAAM;AACvC,SAAM,gBAAgB;;AAExB,WAAS,iBAAiB,WAAW,SAAS,MAAM;AACpD,eAAa;AACX,YAAS,oBAAoB,WAAW,SAAS,MAAM;;IAExD,6CAA6C;;;;;;;;;;;;;;;;;;AAmBlD,SAAS,uBAAuB,UAA+B,OAAqB;CAClF,MAAM,QAAQ,OAAO,oBAAoB;CACzC,MAAM,aAAa,OAAO,yBAAyB,OAAO,QAAQ;AAClE,KAAI,eAAe,UAAa,WAAW,QAAQ,QAAW;AAG5D,WAAS,QAAQ;AACjB;;AAEF,YAAW,IAAI,KAAK,UAAU,MAAM;AACpC,UAAS,cAAc,IAAI,MAAM,SAAS,EAAE,SAAS,MAAM,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["capacity: number","parsed: unknown","historyStore: HistoryStore | null","en: Record<InputHistoryKey, string>","zh: Record<InputHistoryKey, string>","ja: Record<InputHistoryKey, string>","de: Record<InputHistoryKey, string>","fr: Record<InputHistoryKey, string>","pt: Record<InputHistoryKey, string>","ko: Record<InputHistoryKey, string>","ar: Record<InputHistoryKey, string>","hi: Record<InputHistoryKey, string>","id: Record<InputHistoryKey, string>","tr: Record<InputHistoryKey, string>","vi: Record<InputHistoryKey, string>","th: Record<InputHistoryKey, string>","ru: Record<InputHistoryKey, string>","it: Record<InputHistoryKey, string>","nl: Record<InputHistoryKey, string>","sv: Record<InputHistoryKey, string>","pl: Record<InputHistoryKey, string>","zhHK: Record<InputHistoryKey, string>","zhTW: Record<InputHistoryKey, string>","zhMO: Record<InputHistoryKey, string>","dicts: Record<string, Record<InputHistoryKey, string>>","navCursor: number | null","savedDraft: string | null","dispose: (() => void) | undefined"],"sources":["../src/client/history.ts","../src/client/HistoryDock.tsx","../src/client/ime.ts","../src/client/dom.ts","../src/client/locales.ts","../src/client/dictionaries.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Prompt history store — pure functions over a string array.\n *\n * The store is a FIFO list of unique prompt strings, persisted to\n * `localStorage`. Newest entries are at the end of the array. The\n * navigation cursor walks backwards from the end (ArrowUp = older,\n * ArrowDown = newer).\n *\n * The functions in this module are pure (no `localStorage` access) so\n * they can be unit-tested without jsdom. The `HistoryStore` class below\n * wires them to `localStorage` with try/catch containment — a quota\n * exception or a disabled storage (private mode) degrades gracefully to\n * an in-memory list that lives for the page lifetime.\n *\n * @module @huanlin/dsh-plugin-input-history/client/history\n */\n\n/** localStorage key (versioned; bump on schema changes to start fresh). */\nexport const STORAGE_KEY = 'dsh-plugin-input-history:v1'\n\n/** Default capacity when none is configured. */\nexport const DEFAULT_CAPACITY = 500\n\n/**\n * Append a prompt to the history.\n *\n * Rules:\n * - Empty / whitespace-only strings are ignored (the InputBar already\n * rejects them at submit, but defensive).\n * - When the new entry equals the most recent one, it is a no-op\n * (avoids stacking duplicates from rapid resends).\n * - When the new entry already exists earlier in the history, that\n * earlier occurrence is removed (recency wins; the prompt moves to\n * the end). This mirrors terminal shell behaviour.\n * - When the array would exceed `capacity`, the oldest entries are\n * dropped from the front (FIFO).\n *\n * @param history - the current history array (newest at end).\n * @param prompt - the prompt to append.\n * @param capacity - the maximum number of entries to retain.\n * @returns the new history array (may be the same reference if no-op).\n */\nexport function appendHistory(\n history: readonly string[],\n prompt: string,\n capacity: number = DEFAULT_CAPACITY,\n): string[] {\n const trimmed = prompt.trim()\n if (trimmed === '') return history as string[]\n // Latest-equal with no earlier duplicate: true no-op (same reference).\n // When an earlier duplicate exists, the filter below removes it so the\n // entry moves to the end (recency wins).\n const lastIndex = history.lastIndexOf(trimmed)\n if (lastIndex !== -1 && lastIndex === history.length - 1 && history.indexOf(trimmed) === lastIndex) {\n return history as string[]\n }\n // Remove any earlier occurrence (recency wins).\n const filtered = history.filter(item => item !== trimmed)\n filtered.push(trimmed)\n // FIFO: drop oldest entries from the front.\n const cap = Math.max(1, capacity)\n if (filtered.length > cap) {\n return filtered.slice(filtered.length - cap)\n }\n return filtered\n}\n\n/**\n * Navigation cursor for walking the history.\n *\n * The cursor is `null` when the user is not navigating (i.e. they are\n * typing a fresh draft). ArrowUp sets it to the last index, then\n * decrements; ArrowDown increments; when it would exceed `history.length\n * - 1`, it returns to `null` (meaning \"restore the in-progress draft\").\n *\n * @param current - the current cursor (null = not navigating).\n * @param total - the total number of history entries.\n * @param dir - `'up'` (older) or `'down'` (newer).\n * @returns the next cursor, or `null` when navigation falls off the\n * newest end (caller should restore the saved draft).\n */\nexport function nextIndex(\n current: number | null,\n total: number,\n dir: 'up' | 'down',\n): number | null {\n if (total === 0) return null\n if (dir === 'up') {\n if (current === null) return total - 1\n if (current <= 0) return 0\n return current - 1\n }\n // dir === 'down'\n if (current === null) return null\n if (current >= total - 1) return null\n return current + 1\n}\n\n/**\n * Read the history entry at a cursor, or `null` when the cursor is null.\n *\n * @param history - the history array.\n * @param cursor - the navigation cursor.\n * @returns the prompt at the cursor, or `null`.\n */\nexport function entryAt(\n history: readonly string[],\n cursor: number | null,\n): string | null {\n if (cursor === null) return null\n if (cursor < 0 || cursor >= history.length) return null\n return history[cursor] ?? null\n}\n\n/**\n * History store bound to `localStorage`.\n *\n * The store reads once on construction (or on `reload()`) and keeps an\n * in-memory copy. Writes go to both memory and `localStorage` inside a\n * try/catch — a quota exception leaves the in-memory copy authoritative\n * for the rest of the page lifetime. This trades cross-tab consistency\n * for resilience: the store never throws on a write, and the worst case\n * is that a tab keeps its own view until refresh.\n *\n * Cross-tab sync is intentionally NOT implemented: prompt history is\n * append-mostly and a stale read across tabs is harmless (the next\n * append corrects it). Listening to the `storage` event would add\n * reactivity that the navigation UI does not need.\n */\nexport class HistoryStore {\n private items: string[]\n private readonly storage: Storage | null\n private readonly key: string\n\n /**\n * @param capacity - maximum entries to retain (FIFO).\n * @param storage - the storage backend (defaults to `localStorage` when available).\n * @param key - the storage key (defaults to {@link STORAGE_KEY}).\n */\n constructor(\n private readonly capacity: number = DEFAULT_CAPACITY,\n storage?: Storage | null,\n key: string = STORAGE_KEY,\n ) {\n this.storage = storage ?? safeLocalStorage()\n this.key = key\n this.items = this.readFromStorage()\n }\n\n /** Current history snapshot (newest at end). */\n get list(): readonly string[] {\n return this.items\n }\n\n /** Number of entries currently stored. */\n get length(): number {\n return this.items.length\n }\n\n /** Reload from storage (e.g. after a suspected external edit). Truncates to the current capacity. */\n reload(): void {\n const loaded = this.readFromStorage()\n const cap = Math.max(1, this.capacity)\n this.items = loaded.length > cap ? loaded.slice(loaded.length - cap) : loaded\n }\n\n /**\n * Append a prompt and persist. See {@link appendHistory} for rules.\n * @returns the new history snapshot.\n */\n append(prompt: string): readonly string[] {\n this.items = appendHistory(this.items, prompt, this.capacity)\n this.writeToStorage()\n return this.items\n }\n\n /** Clear all history (used by tests and a future \"clear\" UI). */\n clear(): void {\n this.items = []\n this.writeToStorage()\n }\n\n private readFromStorage(): string[] {\n if (this.storage === null) return []\n try {\n const raw = this.storage.getItem(this.key)\n if (raw === null) return []\n const parsed: unknown = JSON.parse(raw)\n if (!Array.isArray(parsed)) return []\n return parsed.filter((item): item is string => typeof item === 'string')\n } catch {\n return []\n }\n }\n\n private writeToStorage(): void {\n if (this.storage === null) return\n try {\n this.storage.setItem(this.key, JSON.stringify(this.items))\n } catch {\n // Quota exceeded, private mode, or disabled storage: keep the\n // in-memory copy authoritative for the rest of the page lifetime.\n }\n }\n}\n\n/** Safe accessor for `localStorage` that returns null on any failure. */\nfunction safeLocalStorage(): Storage | null {\n try {\n if (typeof localStorage === 'undefined') return null\n return localStorage\n } catch {\n return null\n }\n}\n","/**\n * HistoryDock — invisible dock entry that collects prompt history.\n *\n * Registers as a `conversation.composer.dock` list entry and renders an\n * `aria-hidden` anchor (zero layout footprint). The dock's only job is\n * history collection: every render reads `props.session.nodes` and\n * appends new user/steering text to the module-scope `HistoryStore`.\n *\n * The keydown listener that drives navigation lives in `apply` (module\n * scope), NOT in this dock — because the dock is session-scoped and\n * DSH treats blank sessions as \"hero\" (ConversationRoot.tsx:79-80),\n * which suppresses the dock entirely (`!hero` guard at line 156).\n * Moving the listener to `apply` ensures it is always attached,\n * regardless of hero/blank/active session state.\n *\n * @module @huanlin/dsh-plugin-input-history/client/HistoryDock\n */\n\nimport { useRef } from 'react'\nimport type { PropsRuntime, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: SlotMap merge for 'conversation.composer.dock' + SessionStandardProps.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { HistoryStore, DEFAULT_CAPACITY } from './history.ts'\n\n/** Full props: dock runtime share + locale seat. */\ntype HistoryDockProps = PropsRuntime<'conversation.composer.dock'> & PropsLocale<'dsh-plugin-input-history'>\n\n/**\n * Module-scope history store, initialized once on first dock mount.\n * Shared with the keydown listener in `apply` via `getHistoryStore()`.\n */\nlet historyStore: HistoryStore | null = null\n\n/** Get the shared history store (initializes lazily on first call). */\nexport function getHistoryStore(): HistoryStore {\n if (historyStore === null) {\n historyStore = new HistoryStore(DEFAULT_CAPACITY)\n }\n return historyStore\n}\n\n/**\n * Render the invisible history-collection dock entry.\n *\n * @param props - dock runtime share (InputZone owner + session kit) + locale seat.\n * @returns an `aria-hidden` anchor with zero layout footprint.\n */\nexport function HistoryDock({ session }: HistoryDockProps) {\n const store = getHistoryStore()\n\n // History collection: diff the last user/steering text against the\n // previously-seen tail and append on change. Runs every render (cheap:\n // O(n) over the tail nodes, breaks early once a user/steering node is\n // found). The store dedupes internally, so re-appends are no-ops.\n const lastSeenTextRef = useRef<string | null>(null)\n const lastText = latestUserOrSteeringText(session.nodes)\n if (lastText !== null && lastText !== lastSeenTextRef.current) {\n lastSeenTextRef.current = lastText\n store.append(lastText)\n }\n\n // `display: none` keeps the anchor out of layout and out of the\n // a11y tree. The dock is purely a lifecycle anchor for history\n // collection; the keydown listener lives in `apply`.\n return <div aria-hidden style={{ display: 'none' }} data-dsh-plugin-input-history=\"\" />\n}\n\n/**\n * Extract the text of the latest `user` or `steering` node from a\n * conversation snapshot's nodes list.\n *\n * Returns the concatenated text of all `type: 'text'` content blocks.\n * Returns `null` when no user/steering node is present (e.g. a fresh\n * session with only a system/context message).\n *\n * @param nodes - the conversation snapshot's `nodes` array.\n */\nfunction latestUserOrSteeringText(\n nodes: ReadonlyArray<{\n kind: string\n content?: ReadonlyArray<{ type: string; text?: string }>\n }>,\n): string | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (node.kind !== 'user' && node.kind !== 'steering') continue\n const content = node.content\n if (content === undefined) continue\n let text = ''\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n text += block.text\n }\n }\n return text\n }\n return null\n}\n","/**\n * IME-composition key guard.\n *\n * While a Chinese/Japanese/Korean input method is composing (the user is\n * picking a candidate from the IME window), every pressed key BELONGS to\n * the input method: arrows move the candidate highlight, Enter/Space\n * confirm the composition, Escape cancels it. Page code must not process\n * those keys — a history-navigation handler that calls `preventDefault()`\n * on ArrowUp/ArrowDown during composition would silently break the IME:\n * candidates stop responding, the composition gets torn apart, and only\n * bare letters come out.\n *\n * The composition signal follows the DSH core convention (InputBar's IME\n * guard, issue #535): `isComposing` for modern engines, keyCode 229 as\n * the legacy signal engines emit without isComposing.\n *\n * @module @huanlin/dsh-plugin-input-history/client/ime\n */\n\n/** The pure decision: is this keyboard event part of an IME composition? */\nexport function isImeComposition(event: { isComposing: boolean; keyCode: number }): boolean {\n return event.isComposing || event.keyCode === 229\n}\n","/**\n * DOM helpers for the composer textarea.\n *\n * The DSH InputBar's textarea is not exposed through any public API —\n * plugins cannot obtain a React ref or a slot-currency handle to it.\n * The two operations this plugin needs (locate the textarea, decide\n * whether the caret is on the first/last line of a multi-line draft) are\n * pure functions over DOM and string state, kept here for unit testing.\n *\n * The locator queries the stable (but undocumented) `data-composer-card`\n * attribute on the composer card root (`InputBar.tsx:629`) and returns\n * the descendant `<textarea>`. The attribute is internal to\n * `@deepseek-ai/dsh-client-ui-conversation` and may change across\n * upstream versions; the locator is the single point to update.\n *\n * @module @huanlin/dsh-plugin-input-history/client/dom\n */\n\n/** Caret line information for a multi-line textarea value. */\nexport interface CursorLineInfo {\n /** 0-based index of the line the caret is on. */\n readonly currentLine: number\n /** Total number of lines in the value (>= 1). */\n readonly totalLines: number\n /** True when the caret is collapsed and on the first line. */\n readonly atFirstLine: boolean\n /** True when the caret is collapsed and on the last line. */\n readonly atLastLine: boolean\n}\n\n/**\n * Compute the caret's line position in a textarea value.\n *\n * Lines are split on `\\n` (the textarea's own line break character). The\n * caret must be collapsed (`selectionStart === selectionEnd`) for the\n * `atFirstLine` / `atLastLine` flags to be true — a non-collapsed\n * selection spanning multiple lines should not trigger history navigation.\n *\n * @param value - the textarea's current value.\n * @param selectionStart - the textarea's `selectionStart`.\n * @param selectionEnd - the textarea's `selectionEnd` (defaults to `selectionStart`).\n * @returns the caret's line information.\n */\nexport function cursorLineInfo(\n value: string,\n selectionStart: number,\n selectionEnd: number = selectionStart,\n): CursorLineInfo {\n // Swap if reversed (the browser allows selectionStart > selectionEnd when\n // the user drags upwards); clamp to value bounds.\n const rawStart = Math.min(selectionStart, selectionEnd)\n const rawEnd = Math.max(selectionStart, selectionEnd)\n const clampedStart = Math.max(0, Math.min(rawStart, value.length))\n const clampedEnd = Math.max(clampedStart, Math.min(rawEnd, value.length))\n const collapsed = clampedStart === clampedEnd\n const lines = value.split('\\n')\n const totalLines = lines.length\n let currentLine = 0\n let runningLength = 0\n for (let i = 0; i < totalLines; i++) {\n const line = lines[i]!\n // The caret at position `p` belongs to line `i` if `p` is in\n // [runningLength, runningLength + line.length + 1) — the `+1` covers\n // the position immediately after the line's last character, which is\n // still on this line (right before the `\\n`). The very end of the\n // value (after the last line's last char) belongs to the last line.\n const lineEnd = runningLength + line.length\n const isLastLine = i === totalLines - 1\n const upperBound = isLastLine ? lineEnd + 1 : lineEnd + 1 // include the `\\n` position\n if (clampedStart >= runningLength && clampedStart < upperBound) {\n currentLine = i\n break\n }\n runningLength = lineEnd + 1 // +1 for the `\\n`\n }\n return {\n currentLine,\n totalLines,\n atFirstLine: collapsed && currentLine === 0,\n atLastLine: collapsed && currentLine === totalLines - 1,\n }\n}\n\n/**\n * Locate the DSH composer textarea in the current document.\n *\n * Walks from the event target up to find the closest `[data-composer-card]`\n * ancestor, then queries the descendant `<textarea>` inside it. Returns\n * `null` when the target is not inside the composer card (e.g. the user\n * is typing in another input or the textarea is momentarily absent).\n *\n * When called without an event target, falls back to a document-wide\n * query — used in tests and ad-hoc probing.\n *\n * @param from - the event target (or any node inside the composer card).\n * @returns the textarea element, or `null` when not found.\n */\nexport function findComposerTextarea(from?: EventTarget | null): HTMLTextAreaElement | null {\n if (typeof document === 'undefined') return null\n if (from === undefined) {\n // No argument: document-wide query.\n return document.querySelector<HTMLTextAreaElement>('[data-composer-card] textarea')\n }\n // `null` or an actual target: do NOT fall back to document-wide query.\n if (from === null) return null\n // `closest` is on Element; EventTarget may be a Text node or other\n // non-Element node. Narrow with an instanceof check.\n const card = from instanceof Element ? from.closest('[data-composer-card]') : null\n if (card !== null) {\n const ta = card.querySelector<HTMLTextAreaElement>('textarea')\n if (ta !== null) return ta\n }\n return null\n}\n","/**\n * Locale dictionaries for dsh-plugin-input-history.\n *\n * The plugin renders nothing visible — the only user-facing copy is the\n * `aria-label` on the invisible dock anchor (for screen readers) and a\n * future settings row label.\n *\n * @module @huanlin/dsh-plugin-input-history/client/locales\n */\n\n/** All copy keys for the dsh-plugin-input-history namespace. */\nexport type InputHistoryKey =\n | 'ariaLabel'\n | 'restoredDraft'\n | 'noHistory'\n\n/** Locale namespace id (matches the cordis.patch.yml plugin id). */\nexport const NS = 'dsh-plugin-input-history'\n\n/** English dictionary. */\nexport const en: Record<InputHistoryKey, string> = {\n ariaLabel: 'Prompt history navigation (ArrowUp/ArrowDown)',\n restoredDraft: 'Restored in-progress draft',\n noHistory: 'No prompt history yet',\n}\n\n/** Chinese dictionary. */\nexport const zh: Record<InputHistoryKey, string> = {\n ariaLabel: '提示词历史导航(上/下方向键)',\n restoredDraft: '已恢复正在编辑的草稿',\n noHistory: '暂无提示词历史',\n}\n","/**\n * Override dictionaries for the 19 languages better-locale ships. Each\n * dict covers the full `dsh-plugin-input-history` key set (ariaLabel /\n * restoredDraft / noHistory), no placeholders — these are plain strings.\n *\n * Registered with better-locale only (see [index.ts](./index.ts)): the\n * override borrows DSH's English slot, so these render when the user\n * selected an override language AND DSH's active locale is `'en'`. zh-HK /\n * zh-TW / zh-MO have no regional variants for this copy, so the three\n * Traditional Chinese dicts are identical.\n */\n\nimport type { InputHistoryKey } from './locales.ts'\n\nconst ja: Record<InputHistoryKey, string> = {\n ariaLabel: 'プロンプト履歴のナビゲーション(↑/↓キー)',\n restoredDraft: '編集中の下書きを復元しました',\n noHistory: 'プロンプト履歴はまだありません',\n}\n\nconst de: Record<InputHistoryKey, string> = {\n ariaLabel: 'Befehlsverlauf-Navigation (Pfeil hoch/runter)',\n restoredDraft: 'In Bearbeitung befindlicher Entwurf wiederhergestellt',\n noHistory: 'Noch kein Befehlsverlauf vorhanden',\n}\n\nconst fr: Record<InputHistoryKey, string> = {\n ariaLabel: 'Navigation dans l\\'historique des invites (flèche haut/bas)',\n restoredDraft: 'Brouillon en cours d\\'édition restauré',\n noHistory: 'Pas encore d\\'historique d\\'invites',\n}\n\nconst pt: Record<InputHistoryKey, string> = {\n ariaLabel: 'Navegação no histórico de prompts (seta para cima/baixo)',\n restoredDraft: 'Rascunho em edição restaurado',\n noHistory: 'Ainda não há histórico de prompts',\n}\n\nconst ko: Record<InputHistoryKey, string> = {\n ariaLabel: '프롬프트 기록 탐색 (위/아래 화살표)',\n restoredDraft: '편집 중이던 초안을 복원했습니다',\n noHistory: '아직 프롬프트 기록이 없습니다',\n}\n\nconst ar: Record<InputHistoryKey, string> = {\n ariaLabel: 'التنقل في سجل الأوامر (السهم لأعلى/لأسفل)',\n restoredDraft: 'تمت استعادة المسودة قيد التحرير',\n noHistory: 'لا يوجد سجل أوامر بعد',\n}\n\nconst hi: Record<InputHistoryKey, string> = {\n ariaLabel: 'प्रॉम्प्ट इतिहास नेविगेशन (ऊपर/नीचे तीर)',\n restoredDraft: 'संपादन में मौजूद ड्राफ्ट पुनर्स्थापित किया गया',\n noHistory: 'अभी तक कोई प्रॉम्प्ट इतिहास नहीं',\n}\n\nconst id: Record<InputHistoryKey, string> = {\n ariaLabel: 'Navigasi riwayat prompt (panah atas/bawah)',\n restoredDraft: 'Draf yang sedang diedit dipulihkan',\n noHistory: 'Belum ada riwayat prompt',\n}\n\nconst tr: Record<InputHistoryKey, string> = {\n ariaLabel: 'Komut geçmişinde gezinme (yukarı/aşağı ok)',\n restoredDraft: 'Düzenlenmekte olan taslak geri yüklendi',\n noHistory: 'Henüz komut geçmişi yok',\n}\n\nconst vi: Record<InputHistoryKey, string> = {\n ariaLabel: 'Điều hướng lịch sử lệnh (mũi tên lên/xuống)',\n restoredDraft: 'Đã khôi phục bản nháp đang soạn',\n noHistory: 'Chưa có lịch sử lệnh',\n}\n\nconst th: Record<InputHistoryKey, string> = {\n ariaLabel: 'นำทางประวัติคำสั่ง (ลูกศรขึ้น/ลง)',\n restoredDraft: 'กู้คืนฉบับร่างที่กำลังแก้ไขแล้ว',\n noHistory: 'ยังไม่มีประวัติคำสั่ง',\n}\n\nconst ru: Record<InputHistoryKey, string> = {\n ariaLabel: 'Навигация по истории запросов (стрелки вверх/вниз)',\n restoredDraft: 'Текущий черновик восстановлен',\n noHistory: 'Истории запросов пока нет',\n}\n\nconst it: Record<InputHistoryKey, string> = {\n ariaLabel: 'Navigazione cronologia prompt (freccia su/giù)',\n restoredDraft: 'Bozza in corso ripristinata',\n noHistory: 'Nessuna cronologia prompt finora',\n}\n\nconst nl: Record<InputHistoryKey, string> = {\n ariaLabel: 'Navigatie door promptgeschiedenis (pijl omhoog/omlaag)',\n restoredDraft: 'Lopende concept hersteld',\n noHistory: 'Nog geen promptgeschiedenis',\n}\n\nconst sv: Record<InputHistoryKey, string> = {\n ariaLabel: 'Navigera i prompthistorik (pil upp/ner)',\n restoredDraft: 'Utkast under arbete återställt',\n noHistory: 'Ingen prompthistorik ännu',\n}\n\nconst pl: Record<InputHistoryKey, string> = {\n ariaLabel: 'Nawigacja po historii promptów (strzałka w górę/w dół)',\n restoredDraft: 'Przywrócono edytowany szkic',\n noHistory: 'Brak jeszcze historii promptów',\n}\n\nconst zhHK: Record<InputHistoryKey, string> = {\n ariaLabel: '提示詞歷史導覽(上/下方向鍵)',\n restoredDraft: '已還原正在編輯的草稿',\n noHistory: '暫無提示詞歷史',\n}\n\nconst zhTW: Record<InputHistoryKey, string> = {\n ariaLabel: '提示詞歷史導覽(上/下方向鍵)',\n restoredDraft: '已還原正在編輯的草稿',\n noHistory: '暫無提示詞歷史',\n}\n\nconst zhMO: Record<InputHistoryKey, string> = {\n ariaLabel: '提示詞歷史導覽(上/下方向鍵)',\n restoredDraft: '已還原正在編輯的草稿',\n noHistory: '暫無提示詞歷史',\n}\n\n/**\n * All override dictionaries, keyed by language id, covering the full key\n * set. Registered with better-locale under the plugin namespace.\n */\nexport const dicts: Record<string, Record<InputHistoryKey, string>> = {\n ja, de, fr, pt, ko, ar, hi, id, tr, vi, th, ru, it, nl, sv, pl,\n 'zh-HK': zhHK, 'zh-TW': zhTW, 'zh-MO': zhMO,\n}","/**\n * dsh-plugin-input-history — browser half.\n *\n * Two registrations:\n * - `conversation.composer.dock` list slot (id `dsh-plugin-input-history`,\n * order 100) — renders an invisible anchor that collects history from\n * `session.nodes` every render. The dock is session-scoped; DSH treats\n * blank sessions as \"hero\" and suppresses the dock, so history\n * collection only runs in active sessions. That is fine: the first\n * message in a blank session is collected after the session becomes\n * active (the message makes it non-blank).\n * - A document-level `keydown` listener attached in `apply` (NOT in the\n * dock component) — this ensures the listener is always active,\n * including in hero/blank mode where the dock is suppressed. The\n * listener uses the native `value` setter + `dispatchEvent('input')`\n * to feed history text into the textarea, which triggers InputBar's\n * `onChange` → `keyboard.setDraft` — the same path the user's typing\n * takes.\n *\n * History is collected from `user` and `steering` conversation nodes as\n * they appear in any session's `ConversationSnapshot`, persisted to\n * `localStorage` (FIFO, 500 entries), and shared across all sessions\n * in the same browser profile.\n *\n * @module @huanlin/dsh-plugin-input-history/client\n */\n\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the shell's SlotMap merge (conversation.composer.dock)\n// + SessionStandardProps (useInput, inputActions).\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { HistoryDock, getHistoryStore } from './HistoryDock.tsx'\nimport { isImeComposition } from './ime.ts'\nimport { cursorLineInfo, findComposerTextarea } from './dom.ts'\nimport { nextIndex, entryAt } from './history.ts'\nimport { en, NS, zh, type InputHistoryKey } from './locales.ts'\nimport { dicts } from './dictionaries.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** The dock's aria-label + future settings row copy. */\n 'dsh-plugin-input-history': InputHistoryKey\n }\n}\n\n/** Required services: slots + locale. */\nexport const inject = ['slots', 'locale']\n\n/** Structural view of better-locale's override store (optional; no runtime dep). */\ninterface BetterLocaleOverrideStore {\n register(ns: string, dicts: Record<string, Record<string, string>>): () => void\n}\n\n/**\n * Navigation cursor + saved draft for the keydown listener. Module-scoped\n * because the listener is attached once in `apply` and must persist across\n * dock mount/unmount cycles.\n */\nlet navCursor: number | null = null\nlet savedDraft: string | null = null\n\n/**\n * Client plugin body: register the dock + attach the keydown listener.\n *\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugin-input-history: dictionaries')\n\n // better-locale override: register the 19-language dicts so a selected\n // override language (with DSH on 'en') replaces the plugin's copy. The\n // service is optional — no better-locale, no dicts.\n // Activation-order-safe: re-check ctx.get('betterLocale') on every locale\n // revision bump (better-locale bumps on activation + override switch).\n ctx.effect(() => {\n let dispose: (() => void) | undefined\n const sync = (): void => {\n dispose?.()\n dispose = undefined\n const store = ctx.get('betterLocale') as BetterLocaleOverrideStore | undefined\n if (store !== undefined) {\n dispose = store.register(NS, dicts)\n }\n }\n sync()\n const unsubscribe = ctx.locale.subscribe(sync)\n return () => {\n unsubscribe()\n dispose?.()\n }\n }, 'dsh-plugin-input-history: better-locale override dicts')\n\n // The dock collects history from session.nodes. It is session-scoped;\n // in hero/blank mode it is suppressed, but the keydown listener below\n // still works (it reads from the module-scope HistoryStore, which\n // persists across dock mount/unmount cycles via localStorage).\n ctx.slots.inject('conversation.composer.dock', () =>\n ctx.slots.register(\n {\n name: 'conversation.composer.dock',\n id: 'dsh-plugin-input-history',\n order: 100,\n locale: NS,\n },\n HistoryDock,\n ),\n )\n\n // Attach the document-level keydown listener. This lives in `apply`\n // (not in the dock component) so it stays active even when the dock is\n // suppressed (hero/blank sessions — ConversationRoot.tsx:79-80 treats\n // blank sessions as hero, and line 156 skips the dock render).\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const handler = (event: KeyboardEvent): void => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return\n if (isImeComposition(event)) return\n if (event.defaultPrevented) return\n const textarea = findComposerTextarea(event.target)\n if (textarea === null) return\n if (event.target !== textarea) return\n // Skip if the textarea is readOnly or disabled — hero mode's\n // workspace-picker trigger, or a submitting machine phase.\n if (textarea.readOnly || textarea.disabled) return\n\n const store = getHistoryStore()\n const history = store.list\n\n // Multi-line boundary check.\n const info = cursorLineInfo(textarea.value, textarea.selectionStart, textarea.selectionEnd)\n if (event.key === 'ArrowUp' && !info.atFirstLine) return\n if (event.key === 'ArrowDown' && !info.atLastLine) return\n\n const dir = event.key === 'ArrowUp' ? 'up' : 'down'\n const next = nextIndex(navCursor, history.length, dir)\n\n // Down off the newest end: restore the saved draft (if any).\n if (next === null) {\n const saved = savedDraft\n navCursor = null\n if (saved !== null) {\n setNativeTextareaValue(textarea, saved)\n savedDraft = null\n }\n event.preventDefault()\n return\n }\n\n // Entering history: save the current draft the first time we\n // navigate away from \"not navigating\".\n if (navCursor === null && savedDraft === null) {\n savedDraft = textarea.value\n }\n\n const entry = entryAt(history, next)\n if (entry === null) return\n navCursor = next\n setNativeTextareaValue(textarea, entry)\n event.preventDefault()\n }\n document.addEventListener('keydown', handler, false)\n return () => {\n document.removeEventListener('keydown', handler, false)\n }\n }, 'dsh-plugin-input-history: keydown listener')\n}\n\n/**\n * Set the textarea value via the native prototype setter and dispatch an\n * `input` event so React's controlled-component onChange fires.\n *\n * React 18 tracks the textarea's value internally; directly assigning\n * `textarea.value = x` does NOT trigger React's onChange because React's\n * value tracker compares against its last-seen value. Using the native\n * prototype setter bypasses React's tracker, and the dispatched `input`\n * event makes React detect the change and run InputBar's `onChange` →\n * `keyboard.setDraft(next)`. This is the same technique used by\n * browser automation libraries (Playwright, Testing Library) to simulate\n * user typing in React controlled inputs.\n *\n * @param textarea - the target textarea element.\n * @param value - the new value to set.\n */\nfunction setNativeTextareaValue(textarea: HTMLTextAreaElement, value: string): void {\n const proto = window.HTMLTextAreaElement.prototype\n const descriptor = Object.getOwnPropertyDescriptor(proto, 'value')\n if (descriptor === undefined || descriptor.set === undefined) {\n // Fallback: direct assignment (may not trigger React onChange in\n // all browsers, but better than nothing).\n textarea.value = value\n return\n }\n descriptor.set.call(textarea, value)\n textarea.dispatchE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Q,OAAO,oBAAoB;CACzC,MAAM,aAAa,OAAO,yBAAyB,OAAO,QAAQ;AAClE,KAAI,eAAe,UAAa,WAAW,QAAQ,QAAW;AAG5D,WAAS,QAAQ;AACjB;;AAEF,YAAW,IAAI,KAAK,UAAU,MAAM;AACpC,UAAS,cAAc,IAAI,MAAM,SAAS,EAAE,SAAS,MAAM,CAAC,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Override dictionaries for the 19 languages better-locale ships. Each
|
|
3
|
+
* dict covers the full `dsh-plugin-input-history` key set (ariaLabel /
|
|
4
|
+
* restoredDraft / noHistory), no placeholders — these are plain strings.
|
|
5
|
+
*
|
|
6
|
+
* Registered with better-locale only (see [index.ts](./index.ts)): the
|
|
7
|
+
* override borrows DSH's English slot, so these render when the user
|
|
8
|
+
* selected an override language AND DSH's active locale is `'en'`. zh-HK /
|
|
9
|
+
* zh-TW / zh-MO have no regional variants for this copy, so the three
|
|
10
|
+
* Traditional Chinese dicts are identical.
|
|
11
|
+
*/
|
|
12
|
+
import type { InputHistoryKey } from './locales.ts';
|
|
13
|
+
/**
|
|
14
|
+
* All override dictionaries, keyed by language id, covering the full key
|
|
15
|
+
* set. Registered with better-locale under the plugin namespace.
|
|
16
|
+
*/
|
|
17
|
+
export declare const dicts: Record<string, Record<InputHistoryKey, string>>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Override dictionaries for the 19 languages better-locale ships. Each
|
|
3
|
+
* dict covers the full `dsh-plugin-input-history` key set (ariaLabel /
|
|
4
|
+
* restoredDraft / noHistory), no placeholders — these are plain strings.
|
|
5
|
+
*
|
|
6
|
+
* Registered with better-locale only (see [index.ts](./index.ts)): the
|
|
7
|
+
* override borrows DSH's English slot, so these render when the user
|
|
8
|
+
* selected an override language AND DSH's active locale is `'en'`. zh-HK /
|
|
9
|
+
* zh-TW / zh-MO have no regional variants for this copy, so the three
|
|
10
|
+
* Traditional Chinese dicts are identical.
|
|
11
|
+
*/
|
|
12
|
+
const ja = {
|
|
13
|
+
ariaLabel: 'プロンプト履歴のナビゲーション(↑/↓キー)',
|
|
14
|
+
restoredDraft: '編集中の下書きを復元しました',
|
|
15
|
+
noHistory: 'プロンプト履歴はまだありません',
|
|
16
|
+
};
|
|
17
|
+
const de = {
|
|
18
|
+
ariaLabel: 'Befehlsverlauf-Navigation (Pfeil hoch/runter)',
|
|
19
|
+
restoredDraft: 'In Bearbeitung befindlicher Entwurf wiederhergestellt',
|
|
20
|
+
noHistory: 'Noch kein Befehlsverlauf vorhanden',
|
|
21
|
+
};
|
|
22
|
+
const fr = {
|
|
23
|
+
ariaLabel: 'Navigation dans l\'historique des invites (flèche haut/bas)',
|
|
24
|
+
restoredDraft: 'Brouillon en cours d\'édition restauré',
|
|
25
|
+
noHistory: 'Pas encore d\'historique d\'invites',
|
|
26
|
+
};
|
|
27
|
+
const pt = {
|
|
28
|
+
ariaLabel: 'Navegação no histórico de prompts (seta para cima/baixo)',
|
|
29
|
+
restoredDraft: 'Rascunho em edição restaurado',
|
|
30
|
+
noHistory: 'Ainda não há histórico de prompts',
|
|
31
|
+
};
|
|
32
|
+
const ko = {
|
|
33
|
+
ariaLabel: '프롬프트 기록 탐색 (위/아래 화살표)',
|
|
34
|
+
restoredDraft: '편집 중이던 초안을 복원했습니다',
|
|
35
|
+
noHistory: '아직 프롬프트 기록이 없습니다',
|
|
36
|
+
};
|
|
37
|
+
const ar = {
|
|
38
|
+
ariaLabel: 'التنقل في سجل الأوامر (السهم لأعلى/لأسفل)',
|
|
39
|
+
restoredDraft: 'تمت استعادة المسودة قيد التحرير',
|
|
40
|
+
noHistory: 'لا يوجد سجل أوامر بعد',
|
|
41
|
+
};
|
|
42
|
+
const hi = {
|
|
43
|
+
ariaLabel: 'प्रॉम्प्ट इतिहास नेविगेशन (ऊपर/नीचे तीर)',
|
|
44
|
+
restoredDraft: 'संपादन में मौजूद ड्राफ्ट पुनर्स्थापित किया गया',
|
|
45
|
+
noHistory: 'अभी तक कोई प्रॉम्प्ट इतिहास नहीं',
|
|
46
|
+
};
|
|
47
|
+
const id = {
|
|
48
|
+
ariaLabel: 'Navigasi riwayat prompt (panah atas/bawah)',
|
|
49
|
+
restoredDraft: 'Draf yang sedang diedit dipulihkan',
|
|
50
|
+
noHistory: 'Belum ada riwayat prompt',
|
|
51
|
+
};
|
|
52
|
+
const tr = {
|
|
53
|
+
ariaLabel: 'Komut geçmişinde gezinme (yukarı/aşağı ok)',
|
|
54
|
+
restoredDraft: 'Düzenlenmekte olan taslak geri yüklendi',
|
|
55
|
+
noHistory: 'Henüz komut geçmişi yok',
|
|
56
|
+
};
|
|
57
|
+
const vi = {
|
|
58
|
+
ariaLabel: 'Điều hướng lịch sử lệnh (mũi tên lên/xuống)',
|
|
59
|
+
restoredDraft: 'Đã khôi phục bản nháp đang soạn',
|
|
60
|
+
noHistory: 'Chưa có lịch sử lệnh',
|
|
61
|
+
};
|
|
62
|
+
const th = {
|
|
63
|
+
ariaLabel: 'นำทางประวัติคำสั่ง (ลูกศรขึ้น/ลง)',
|
|
64
|
+
restoredDraft: 'กู้คืนฉบับร่างที่กำลังแก้ไขแล้ว',
|
|
65
|
+
noHistory: 'ยังไม่มีประวัติคำสั่ง',
|
|
66
|
+
};
|
|
67
|
+
const ru = {
|
|
68
|
+
ariaLabel: 'Навигация по истории запросов (стрелки вверх/вниз)',
|
|
69
|
+
restoredDraft: 'Текущий черновик восстановлен',
|
|
70
|
+
noHistory: 'Истории запросов пока нет',
|
|
71
|
+
};
|
|
72
|
+
const it = {
|
|
73
|
+
ariaLabel: 'Navigazione cronologia prompt (freccia su/giù)',
|
|
74
|
+
restoredDraft: 'Bozza in corso ripristinata',
|
|
75
|
+
noHistory: 'Nessuna cronologia prompt finora',
|
|
76
|
+
};
|
|
77
|
+
const nl = {
|
|
78
|
+
ariaLabel: 'Navigatie door promptgeschiedenis (pijl omhoog/omlaag)',
|
|
79
|
+
restoredDraft: 'Lopende concept hersteld',
|
|
80
|
+
noHistory: 'Nog geen promptgeschiedenis',
|
|
81
|
+
};
|
|
82
|
+
const sv = {
|
|
83
|
+
ariaLabel: 'Navigera i prompthistorik (pil upp/ner)',
|
|
84
|
+
restoredDraft: 'Utkast under arbete återställt',
|
|
85
|
+
noHistory: 'Ingen prompthistorik ännu',
|
|
86
|
+
};
|
|
87
|
+
const pl = {
|
|
88
|
+
ariaLabel: 'Nawigacja po historii promptów (strzałka w górę/w dół)',
|
|
89
|
+
restoredDraft: 'Przywrócono edytowany szkic',
|
|
90
|
+
noHistory: 'Brak jeszcze historii promptów',
|
|
91
|
+
};
|
|
92
|
+
const zhHK = {
|
|
93
|
+
ariaLabel: '提示詞歷史導覽(上/下方向鍵)',
|
|
94
|
+
restoredDraft: '已還原正在編輯的草稿',
|
|
95
|
+
noHistory: '暫無提示詞歷史',
|
|
96
|
+
};
|
|
97
|
+
const zhTW = {
|
|
98
|
+
ariaLabel: '提示詞歷史導覽(上/下方向鍵)',
|
|
99
|
+
restoredDraft: '已還原正在編輯的草稿',
|
|
100
|
+
noHistory: '暫無提示詞歷史',
|
|
101
|
+
};
|
|
102
|
+
const zhMO = {
|
|
103
|
+
ariaLabel: '提示詞歷史導覽(上/下方向鍵)',
|
|
104
|
+
restoredDraft: '已還原正在編輯的草稿',
|
|
105
|
+
noHistory: '暫無提示詞歷史',
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* All override dictionaries, keyed by language id, covering the full key
|
|
109
|
+
* set. Registered with better-locale under the plugin namespace.
|
|
110
|
+
*/
|
|
111
|
+
export const dicts = {
|
|
112
|
+
ja, de, fr, pt, ko, ar, hi, id, tr, vi, th, ru, it, nl, sv, pl,
|
|
113
|
+
'zh-HK': zhHK, 'zh-TW': zhTW, 'zh-MO': zhMO,
|
|
114
|
+
};
|
|
@@ -29,6 +29,7 @@ import { isImeComposition } from "./ime.js";
|
|
|
29
29
|
import { cursorLineInfo, findComposerTextarea } from "./dom.js";
|
|
30
30
|
import { nextIndex, entryAt } from "./history.js";
|
|
31
31
|
import { en, NS, zh } from "./locales.js";
|
|
32
|
+
import { dicts } from "./dictionaries.js";
|
|
32
33
|
/** Required services: slots + locale. */
|
|
33
34
|
export const inject = ['slots', 'locale'];
|
|
34
35
|
/**
|
|
@@ -45,6 +46,28 @@ let savedDraft = null;
|
|
|
45
46
|
*/
|
|
46
47
|
export function apply(ctx) {
|
|
47
48
|
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugin-input-history: dictionaries');
|
|
49
|
+
// better-locale override: register the 19-language dicts so a selected
|
|
50
|
+
// override language (with DSH on 'en') replaces the plugin's copy. The
|
|
51
|
+
// service is optional — no better-locale, no dicts.
|
|
52
|
+
// Activation-order-safe: re-check ctx.get('betterLocale') on every locale
|
|
53
|
+
// revision bump (better-locale bumps on activation + override switch).
|
|
54
|
+
ctx.effect(() => {
|
|
55
|
+
let dispose;
|
|
56
|
+
const sync = () => {
|
|
57
|
+
dispose?.();
|
|
58
|
+
dispose = undefined;
|
|
59
|
+
const store = ctx.get('betterLocale');
|
|
60
|
+
if (store !== undefined) {
|
|
61
|
+
dispose = store.register(NS, dicts);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
sync();
|
|
65
|
+
const unsubscribe = ctx.locale.subscribe(sync);
|
|
66
|
+
return () => {
|
|
67
|
+
unsubscribe();
|
|
68
|
+
dispose?.();
|
|
69
|
+
};
|
|
70
|
+
}, 'dsh-plugin-input-history: better-locale override dicts');
|
|
48
71
|
// The dock collects history from session.nodes. It is session-scoped;
|
|
49
72
|
// in hero/blank mode it is suppressed, but the keydown listener below
|
|
50
73
|
// still works (it reads from the module-scope HistoryStore, which
|