1142 lines
47 KiB
JavaScript
1142 lines
47 KiB
JavaScript
window.__ModuleLoader__.load({
|
||
id: "dsh-better-chat",
|
||
factory: (require) => {
|
||
var module = { exports: {} };
|
||
var exports = module.exports;
|
||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||
let _deepseek_ai_dsh_client_store = require("@deepseek-ai/dsh-client-store");
|
||
let react = require("react");
|
||
let react_jsx_runtime = require("react/jsx-runtime");
|
||
// src/client/chat/bindings.ts
|
||
/** 「始终允许」的默认键帽;单列出来,展开时不会沾上 `null` 带来的可选键。 */
|
||
const DEFAULT_ALWAYS = {
|
||
key: "Enter",
|
||
primary: true,
|
||
shift: false,
|
||
alt: false
|
||
};
|
||
const DEFAULT_BINDINGS = {
|
||
allow: {
|
||
key: "Enter",
|
||
primary: false,
|
||
shift: false,
|
||
alt: false
|
||
},
|
||
always: DEFAULT_ALWAYS,
|
||
reject: {
|
||
key: "Escape",
|
||
primary: false,
|
||
shift: false,
|
||
alt: false
|
||
}
|
||
};
|
||
/** 设置页保存快捷键后派发的窗口事件;提示与判定都靠实时 getter,无需重启。 */
|
||
const BINDINGS_CHANGED_EVENT = "better-chat:bindings-changed";
|
||
/** 每个动作允许的基础键:允许类只能用 Enter,拒绝只能用 Esc。 */
|
||
function baseKeyFor(action) {
|
||
return action === "reject" ? "Escape" : "Enter";
|
||
}
|
||
/** 展示用键帽文案,例如 Enter / Ctrl+Enter / Shift+Alt+Enter / Esc。 */
|
||
function bindingKeycap(binding, mac) {
|
||
const parts = [];
|
||
if (binding.primary) parts.push(mac ? "Cmd" : "Ctrl");
|
||
if (binding.shift) parts.push("Shift");
|
||
if (binding.alt) parts.push("Alt");
|
||
parts.push(binding.key === "Escape" ? "Esc" : binding.key);
|
||
return parts.join("+");
|
||
}
|
||
/** 纯判定:按键事件是否命中这条绑定(修饰键必须完全一致)。 */
|
||
function bindingMatches(binding, event) {
|
||
const primary = Boolean(event.ctrlKey) || Boolean(event.metaKey);
|
||
return event.key === binding.key && primary === binding.primary && Boolean(event.shiftKey) === binding.shift && Boolean(event.altKey) === binding.alt;
|
||
}
|
||
/** 是否是不带任何修饰键的裸键(Enter / Esc)。 */
|
||
function isPlainBinding(binding) {
|
||
return Boolean(binding) && !binding.primary && !binding.shift && !binding.alt;
|
||
}
|
||
/** 两条绑定是否相同。 */
|
||
function bindingsEqual(left, right) {
|
||
if (!left || !right) return left === right;
|
||
return left.key === right.key && left.primary === right.primary && left.shift === right.shift && left.alt === right.alt;
|
||
}
|
||
function booleanOrFalse(value) {
|
||
return value === true;
|
||
}
|
||
/** 校验并收敛一条绑定;形状不对时返回 undefined。 */
|
||
function normalizeBinding(value) {
|
||
if (!value || typeof value !== "object") return void 0;
|
||
const record = value;
|
||
if (record.key !== "Enter" && record.key !== "Escape") return void 0;
|
||
return {
|
||
key: record.key,
|
||
primary: booleanOrFalse(record.primary),
|
||
shift: booleanOrFalse(record.shift),
|
||
alt: booleanOrFalse(record.alt)
|
||
};
|
||
}
|
||
/**
|
||
* 把持久化快照收敛成合法绑定;`{ bindings: ... }` 或内层对象都接受。
|
||
* 缺失/非法/冲突的项回落到默认值,保证任何旧快照都能用。
|
||
*/
|
||
function normalizeBindings(value) {
|
||
const inner = value && typeof value === "object" && "bindings" in value ? value.bindings : value;
|
||
const record = inner && typeof inner === "object" ? inner : {};
|
||
const allowRaw = normalizeBinding(record.allow);
|
||
const rejectRaw = normalizeBinding(record.reject);
|
||
const allow = allowRaw && allowRaw.key === "Enter" ? allowRaw : { ...DEFAULT_BINDINGS.allow };
|
||
const reject = rejectRaw && rejectRaw.key === "Escape" ? rejectRaw : { ...DEFAULT_BINDINGS.reject };
|
||
const alwaysRaw = "always" in record ? record.always : DEFAULT_ALWAYS;
|
||
const alwaysParsed = alwaysRaw === null ? null : normalizeBinding(alwaysRaw);
|
||
const out = {
|
||
allow,
|
||
always: alwaysRaw === null ? null : alwaysParsed && alwaysParsed.key === "Enter" ? alwaysParsed : { ...DEFAULT_ALWAYS },
|
||
reject
|
||
};
|
||
if (out.always && (!hasModifier(out.always) || bindingsEqual(out.allow, out.always))) {
|
||
out.allow = { ...DEFAULT_BINDINGS.allow };
|
||
out.always = { ...DEFAULT_ALWAYS };
|
||
}
|
||
if (out.always && bindingsEqual(out.reject, out.always)) out.reject = { ...DEFAULT_BINDINGS.reject };
|
||
if (bindingsEqual(out.allow, out.reject)) {
|
||
out.allow = { ...DEFAULT_BINDINGS.allow };
|
||
out.reject = { ...DEFAULT_BINDINGS.reject };
|
||
}
|
||
return out;
|
||
}
|
||
function hasModifier(binding) {
|
||
return binding.primary || binding.shift || binding.alt;
|
||
}
|
||
/**
|
||
* 保存前的校验:基础键是否匹配动作、始终允许是否有修饰键、是否与其他动作冲突。
|
||
*/
|
||
function validateBinding(action, binding, current) {
|
||
if (binding.key !== baseKeyFor(action)) return "key";
|
||
if (action === "always" && !hasModifier(binding)) return "modifier";
|
||
const others = [];
|
||
if (action !== "allow") others.push(current.allow);
|
||
if (action !== "always" && current.always) others.push(current.always);
|
||
if (action !== "reject") others.push(current.reject);
|
||
if (others.some((other) => bindingsEqual(other, binding))) return "conflict";
|
||
return "ok";
|
||
}
|
||
// src/client/chat/approval-keys.ts
|
||
/**
|
||
* 功能一:审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。
|
||
*
|
||
* 背景(@deepseek-ai/dsh-client-ui-approval):官方审批卡自带键盘处理
|
||
* —— Enter 批准(单次)、Esc 拒绝 —— 但 keydown 挂在卡片根节点上,且
|
||
* 要求焦点先落在卡片内。审批弹出时焦点往往还在对话区,按回车毫无反应。
|
||
*
|
||
* 本模块补两件事,不改官方任何逻辑:
|
||
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片详情区。
|
||
* 2. 焦点不在卡片内时兜底路由:document 捕获阶段拦 keydown,点击卡片
|
||
* 操作行里的按钮 —— 回车点「允许(单次)」,Esc 点「拒绝」。
|
||
*/
|
||
const CARD_SELECTOR$1 = "[data-approval-key]";
|
||
const SCROLL_SELECTOR = "[data-approval-scroll]";
|
||
const EDITABLE_SELECTOR = "input, textarea, select, [contenteditable=\"true\"], [contenteditable=\"\"]";
|
||
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
|
||
function actionButtons(card) {
|
||
return [...card.querySelectorAll("button")].filter((button) => !button.closest(SCROLL_SELECTOR));
|
||
}
|
||
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
|
||
function findPendingCard(doc) {
|
||
for (const card of doc.querySelectorAll(CARD_SELECTOR$1)) {
|
||
if (card.getAttribute("aria-busy") === "true") continue;
|
||
const buttons = actionButtons(card);
|
||
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card;
|
||
}
|
||
return null;
|
||
}
|
||
/**
|
||
* 纯判定:这次 keydown 是否应该路由到审批卡。
|
||
*
|
||
* 默认绑定:Enter → 允许(单次)、Ctrl/Cmd+Enter → 始终允许、Esc → 拒绝;
|
||
* 绑定可由设置页改写(见 bindings.ts),基础键固定 Enter/Escape,只调修饰键。
|
||
* 官方卡片本身对带修饰键的按键不作答,所以带修饰键的绑定即使在卡内也由
|
||
* 本插件处理;裸 Enter/Esc 在卡内交给官方。
|
||
*
|
||
* @returns 'allow' | 'reject' | 'always' | null
|
||
*/
|
||
function decideKeyAction(input) {
|
||
const { repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card, hasAlways } = input;
|
||
if (!card) return null;
|
||
if (defaultPrevented) return null;
|
||
if (repeat || isComposing || keyCode === 229) return null;
|
||
if (target && typeof target.closest === "function" && target.closest(EDITABLE_SELECTOR) !== null) return null;
|
||
const bindings = input.bindings ?? DEFAULT_BINDINGS;
|
||
const candidates = [
|
||
["allow", bindings.allow],
|
||
["always", hasAlways ? bindings.always : null],
|
||
["reject", bindings.reject]
|
||
];
|
||
for (const [action, binding] of candidates) {
|
||
if (!binding || !bindingMatches(binding, input)) continue;
|
||
if (isPlainBinding(binding)) {
|
||
if (activeElement && card.contains(activeElement)) return null;
|
||
if (binding.key === "Enter" && target && typeof target.closest === "function" && target.closest("button, a[href], [role=\"button\"]") !== null) return null;
|
||
}
|
||
return action;
|
||
}
|
||
return null;
|
||
}
|
||
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
|
||
function shouldAutoFocus(activeElement, card) {
|
||
if (!activeElement) return true;
|
||
if (activeElement === card.ownerDocument?.body) return true;
|
||
if (card.contains(activeElement)) return false;
|
||
if (typeof activeElement.closest === "function" && activeElement.closest(EDITABLE_SELECTOR) !== null) return false;
|
||
return true;
|
||
}
|
||
/** 安装审批键盘增强,返回卸载函数。 */
|
||
function install(doc, getBindings) {
|
||
const focusedCards = /* @__PURE__ */ new WeakSet();
|
||
const tryAutoFocus = () => {
|
||
const card = findPendingCard(doc);
|
||
if (!card || focusedCards.has(card)) return;
|
||
focusedCards.add(card);
|
||
if (!shouldAutoFocus(doc.activeElement, card)) return;
|
||
const region = card.querySelector(SCROLL_SELECTOR);
|
||
if (region && typeof region.focus === "function") region.focus();
|
||
};
|
||
const observer = new MutationObserver(tryAutoFocus);
|
||
observer.observe(doc.documentElement, {
|
||
childList: true,
|
||
subtree: true
|
||
});
|
||
tryAutoFocus();
|
||
const onKeyDown = (event) => {
|
||
const card = findPendingCard(doc);
|
||
if (!card) return;
|
||
const buttons = actionButtons(card);
|
||
const hasAlways = buttons.length >= 3 && !buttons[2].disabled;
|
||
const action = decideKeyAction({
|
||
key: event.key,
|
||
ctrlKey: event.ctrlKey,
|
||
metaKey: event.metaKey,
|
||
altKey: event.altKey,
|
||
shiftKey: event.shiftKey,
|
||
repeat: event.repeat,
|
||
isComposing: event.isComposing,
|
||
keyCode: event.keyCode,
|
||
defaultPrevented: event.defaultPrevented,
|
||
target: event.target,
|
||
activeElement: doc.activeElement,
|
||
card,
|
||
hasAlways,
|
||
bindings: getBindings?.() ?? DEFAULT_BINDINGS
|
||
});
|
||
if (!action) return;
|
||
const button = action === "allow" ? buttons[1] : action === "always" ? buttons[2] : buttons[0];
|
||
if (!button || button.disabled) return;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
button.click();
|
||
};
|
||
doc.addEventListener("keydown", onKeyDown, true);
|
||
return () => {
|
||
observer.disconnect();
|
||
doc.removeEventListener("keydown", onKeyDown, true);
|
||
};
|
||
}
|
||
// src/client/chat/bindings-store.ts
|
||
/**
|
||
* 聊天增强的持久化设置:审批卡快捷键。存储键 `dsh.better-chat.v1`,由宿主
|
||
* 客户端 store 的 persist 机制写入配置,重启后仍在。
|
||
*/
|
||
const CHAT_PREFS_KEY = "dsh.better-chat.v1";
|
||
function createChatStore() {
|
||
return (0, _deepseek_ai_dsh_client_store.defineStore)({
|
||
init: () => ({ bindings: normalizeBindings(void 0) }),
|
||
persist: CHAT_PREFS_KEY,
|
||
actions: {
|
||
setApprovalBinding: (draft, action, binding) => {
|
||
draft.bindings = normalizeBindings({
|
||
...draft.bindings,
|
||
[action]: binding
|
||
});
|
||
},
|
||
resetApprovalBindings: (draft) => {
|
||
draft.bindings = normalizeBindings(void 0);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
/** 从设置实例读取当前绑定;旧快照/非法值自动回落默认。 */
|
||
function currentBindings(prefs) {
|
||
try {
|
||
return normalizeBindings(prefs?.getSnapshot());
|
||
} catch {
|
||
return normalizeBindings(void 0);
|
||
}
|
||
}
|
||
// src/client/chat/key-hint.ts
|
||
/**
|
||
* 审批卡键盘提示:在操作行左侧显示「Enter 允许(单次) · Ctrl+Enter
|
||
* 始终允许 · Esc 拒绝」的键帽提示,文案直接取卡片按钮的实际文字。
|
||
*
|
||
* 提示只是说明,不参与点击:pointer-events: none、aria-hidden,且只挂在
|
||
* 卡片操作行里(详情滚动区之外)。React 重渲染把提示冲掉时,MutationObserver
|
||
* 会按按钮文案的签名重新挂回去;卡片作答后(aria-busy)立即移除。
|
||
*/
|
||
const HINT_ATTR = "data-better-chat-keyhint";
|
||
const CARD_SELECTOR = "[data-approval-key]";
|
||
const SEPARATOR = "·";
|
||
/** 纯判定:当前平台是否用 Cmd 代替 Ctrl(只影响提示文案)。 */
|
||
function isMacPlatform(platform) {
|
||
return typeof platform === "string" && /Mac|iPhone|iPad|iPod/.test(platform);
|
||
}
|
||
/**
|
||
* 纯函数:根据卡片上实际存在的按钮文案与当前绑定,生成提示的分段。
|
||
* 「始终允许」被关掉(binding 为 null)时就不显示这一段。
|
||
*/
|
||
function hintParts(labels, mac, bindings = DEFAULT_BINDINGS) {
|
||
const parts = [];
|
||
if (labels.allow) parts.push({
|
||
key: bindingKeycap(bindings.allow, mac),
|
||
label: labels.allow
|
||
});
|
||
if (labels.always && bindings.always) parts.push({
|
||
key: bindingKeycap(bindings.always, mac),
|
||
label: labels.always
|
||
});
|
||
if (labels.reject) parts.push({
|
||
key: bindingKeycap(bindings.reject, mac),
|
||
label: labels.reject
|
||
});
|
||
return parts;
|
||
}
|
||
/** 纯函数:提示内容的签名,用于判断是否需要重建。 */
|
||
function hintSignature(parts) {
|
||
return parts.map((part) => `${part.key}=${part.label}`).join("|");
|
||
}
|
||
const HINT_CSS = [
|
||
"margin-right:auto",
|
||
"display:inline-flex",
|
||
"flex-wrap:wrap",
|
||
"align-items:center",
|
||
"gap:6px",
|
||
"font-size:12px",
|
||
"line-height:18px",
|
||
"color:var(--dsw-alias-label-tertiary,#8b919b)",
|
||
"user-select:none",
|
||
"pointer-events:none"
|
||
].join(";");
|
||
const KEYCAP_CSS = [
|
||
"display:inline-flex",
|
||
"align-items:center",
|
||
"justify-content:center",
|
||
"height:18px",
|
||
"padding:0 5px",
|
||
"border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35))",
|
||
"border-bottom-width:2px",
|
||
"border-radius:5px",
|
||
"background:var(--dsw-alias-bg-module-platform,rgba(127,127,127,.08))",
|
||
"font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace)",
|
||
"font-size:11px",
|
||
"line-height:1",
|
||
"letter-spacing:.2px"
|
||
].join(";");
|
||
const PAIR_CSS = "display:inline-flex;align-items:center;gap:5px";
|
||
const SEPARATOR_CSS = "opacity:.45;margin:0 2px";
|
||
function labelOf(button) {
|
||
if (!button) return void 0;
|
||
const text = button.textContent?.trim();
|
||
return text ? text : void 0;
|
||
}
|
||
function buildHint(doc, parts) {
|
||
const hint = doc.createElement("div");
|
||
hint.setAttribute(HINT_ATTR, "");
|
||
hint.setAttribute("role", "note");
|
||
hint.setAttribute("aria-hidden", "true");
|
||
hint.style.cssText = HINT_CSS;
|
||
parts.forEach((part, index) => {
|
||
if (index > 0) {
|
||
const separator = doc.createElement("span");
|
||
separator.textContent = SEPARATOR;
|
||
separator.style.cssText = SEPARATOR_CSS;
|
||
hint.append(separator);
|
||
}
|
||
const pair = doc.createElement("span");
|
||
pair.style.cssText = PAIR_CSS;
|
||
const keycap = doc.createElement("span");
|
||
keycap.textContent = part.key;
|
||
keycap.style.cssText = KEYCAP_CSS;
|
||
const label = doc.createElement("span");
|
||
label.textContent = part.label;
|
||
pair.append(keycap, label);
|
||
hint.append(pair);
|
||
});
|
||
return hint;
|
||
}
|
||
function removeHints(doc) {
|
||
for (const hint of doc.querySelectorAll(`[${HINT_ATTR}]`)) hint.remove();
|
||
}
|
||
/** 安装审批卡键盘提示,返回卸载函数。 */
|
||
function installKeyHints(doc, options = {}) {
|
||
const mac = isMacPlatform(options.platform ?? doc.defaultView?.navigator?.platform);
|
||
const getBindings = options.getBindings ?? (() => DEFAULT_BINDINGS);
|
||
let disposed = false;
|
||
const syncCard = (card) => {
|
||
const buttons = actionButtons(card);
|
||
const existing = card.querySelector(`[${HINT_ATTR}]`);
|
||
if (card.getAttribute("aria-busy") === "true" || buttons.length < 2 || buttons[0].disabled || buttons[1].disabled) {
|
||
existing?.remove();
|
||
return;
|
||
}
|
||
const always = buttons.length >= 3 && !buttons[2].disabled ? buttons[2] : void 0;
|
||
const parts = hintParts({
|
||
allow: labelOf(buttons[1]),
|
||
always: labelOf(always),
|
||
reject: labelOf(buttons[0])
|
||
}, mac, getBindings());
|
||
if (parts.length === 0) {
|
||
existing?.remove();
|
||
return;
|
||
}
|
||
const signature = hintSignature(parts);
|
||
if (existing && existing.getAttribute("data-signature") === signature) return;
|
||
existing?.remove();
|
||
const row = buttons[0].parentElement;
|
||
if (!row) return;
|
||
const hint = buildHint(doc, parts);
|
||
hint.setAttribute("data-signature", signature);
|
||
row.insertBefore(hint, row.firstChild);
|
||
};
|
||
const sync = () => {
|
||
if (disposed) return;
|
||
const cards = doc.querySelectorAll(CARD_SELECTOR);
|
||
if (cards.length === 0) {
|
||
removeHints(doc);
|
||
return;
|
||
}
|
||
for (const card of cards) syncCard(card);
|
||
};
|
||
const observer = new MutationObserver(sync);
|
||
observer.observe(doc.documentElement, {
|
||
childList: true,
|
||
subtree: true,
|
||
attributes: true,
|
||
attributeFilter: ["aria-busy", "disabled"]
|
||
});
|
||
const view = doc.defaultView;
|
||
view?.addEventListener?.(BINDINGS_CHANGED_EVENT, sync);
|
||
sync();
|
||
return () => {
|
||
disposed = true;
|
||
observer.disconnect();
|
||
view?.removeEventListener?.(BINDINGS_CHANGED_EVENT, sync);
|
||
removeHints(doc);
|
||
};
|
||
}
|
||
// src/client/chat/permission-policy.ts
|
||
/** 自动审查的预设机器值。 */
|
||
const AUTO_REVIEW_PRESET = "auto";
|
||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
||
const FULL_ACCESS_LABELS = ["完全权限", "Full access"];
|
||
/** 已处理会话 id 的浏览器持久化键,避免刷新后覆盖用户手动改过的权限。 */
|
||
const HANDLED_STORAGE_KEY = "dsh.better-chat.permission-handled.v1";
|
||
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
||
function isFullAccessLabel(text) {
|
||
if (typeof text !== "string") return false;
|
||
const trimmed = text.trim();
|
||
return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label));
|
||
}
|
||
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
|
||
function shouldAutoSwitch(preset, alreadyHandled) {
|
||
return preset !== void 0 && preset !== null && preset !== "auto" && !alreadyHandled;
|
||
}
|
||
/**
|
||
* 防御式枚举宿主的 live 会话:
|
||
* 1. `keys() + binding()`(测试桩或旧形状)
|
||
* 2. DSH 0.2.2 `ClientSessions`:`scopes` Map 与 `list.getSnapshot()`(`ids` / `byId`)配合 `binding(id)`
|
||
* 3. `list()` 函数回退
|
||
* 服务形状对不上时安静返回空数组,绝不抛错。
|
||
*/
|
||
function liveSessions(sessions) {
|
||
const out = [];
|
||
if (!sessions || typeof sessions !== "object") return out;
|
||
try {
|
||
if (typeof sessions.keys === "function" && typeof sessions.binding === "function") {
|
||
for (const id of sessions.keys()) {
|
||
const live = sessions.binding(id)?.session;
|
||
if (live) out.push({
|
||
id,
|
||
live
|
||
});
|
||
}
|
||
return out;
|
||
}
|
||
if (typeof sessions.binding === "function" || sessions.scopes instanceof Map) {
|
||
const seen = /* @__PURE__ */ new Set();
|
||
const addCandidate = (id) => {
|
||
if (typeof id !== "string" || !id || seen.has(id)) return;
|
||
const live = (typeof sessions.binding === "function" ? sessions.binding(id)?.session : void 0) ?? (sessions.scopes instanceof Map ? sessions.scopes.get(id)?.binding?.session : void 0);
|
||
if (live) {
|
||
seen.add(id);
|
||
out.push({
|
||
id,
|
||
live
|
||
});
|
||
}
|
||
};
|
||
if (sessions.scopes instanceof Map) for (const id of sessions.scopes.keys()) addCandidate(id);
|
||
const listSnap = typeof sessions.list?.getSnapshot === "function" ? sessions.list.getSnapshot() : void 0;
|
||
if (Array.isArray(listSnap?.ids)) for (const id of listSnap.ids) addCandidate(id);
|
||
if (listSnap?.byId && typeof listSnap.byId === "object") for (const id of Object.keys(listSnap.byId)) addCandidate(id);
|
||
if (out.length > 0 || typeof sessions.list !== "function") return out;
|
||
}
|
||
if (typeof sessions.list === "function") {
|
||
for (const session of sessions.list() ?? []) if (session && session.sessionId) out.push({
|
||
id: session.sessionId,
|
||
live: session
|
||
});
|
||
}
|
||
} catch {}
|
||
return out;
|
||
}
|
||
/**
|
||
* 读会话当前的权限预设值(投影不可用时返回 undefined)。
|
||
* 兼容 DSH 0.2.2 的 `{ currentValue: string }` 投影视图与直接返回字符串的测试桩。
|
||
*/
|
||
function currentPreset(live) {
|
||
try {
|
||
const snap = live?.projections?.faceOf?.("permissions")?.getSnapshot?.();
|
||
if (typeof snap === "string") return snap;
|
||
if (snap && typeof snap === "object" && typeof snap.currentValue === "string") return snap.currentValue;
|
||
return;
|
||
} catch {
|
||
return;
|
||
}
|
||
}
|
||
/**
|
||
* 判定会话是否允许执行首次默认自动审查切换:
|
||
* - 已有对话内容的会话(`blank === false`)不改;
|
||
* - 子代理会话(`origin === 'subagent'`)不改;
|
||
* - 其余空白新建会话(以及未提供 blank 元数据的轻量测试桩)允许首次切换。
|
||
*/
|
||
function isAutoSwitchEligible(id, live, sessions) {
|
||
try {
|
||
if (live?.getSnapshot?.()?.blank === false) return false;
|
||
const summary = sessions?.list?.getSnapshot?.()?.byId?.[id];
|
||
if (summary?.blank === false) return false;
|
||
if (summary?.origin === "subagent") return false;
|
||
} catch {}
|
||
return true;
|
||
}
|
||
function loadHandledIds(doc) {
|
||
const set = /* @__PURE__ */ new Set();
|
||
try {
|
||
const raw = (doc?.defaultView?.localStorage)?.getItem?.(HANDLED_STORAGE_KEY);
|
||
if (typeof raw === "string" && raw) {
|
||
const parsed = JSON.parse(raw);
|
||
if (Array.isArray(parsed)) {
|
||
for (const item of parsed) if (typeof item === "string" && item) set.add(item);
|
||
}
|
||
}
|
||
} catch {}
|
||
return set;
|
||
}
|
||
function saveHandledIds(doc, set) {
|
||
try {
|
||
const storage = doc?.defaultView?.localStorage;
|
||
if (!storage?.setItem) return;
|
||
const items = [...set].slice(-500);
|
||
storage.setItem(HANDLED_STORAGE_KEY, JSON.stringify(items));
|
||
} catch {}
|
||
}
|
||
/**
|
||
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
||
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
||
* @returns 摘掉的个数
|
||
*/
|
||
function pruneFullAccess(doc) {
|
||
let removed = 0;
|
||
for (const option of doc.querySelectorAll("option")) if (isFullAccessLabel(option.textContent)) {
|
||
option.remove();
|
||
removed++;
|
||
}
|
||
for (const item of doc.querySelectorAll("[role=\"listbox\"] [role=\"option\"], [role=\"menu\"] [role=\"menuitem\"]")) if (isFullAccessLabel(item.textContent)) {
|
||
item.remove();
|
||
removed++;
|
||
}
|
||
return removed;
|
||
}
|
||
const defaultTimers = {
|
||
setInterval: (fn, ms) => setInterval(fn, ms),
|
||
clearInterval: (id) => clearInterval(id),
|
||
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
||
clearTimeout: (id) => clearTimeout(id)
|
||
};
|
||
/**
|
||
* 安装权限策略:
|
||
* 1. 观察 DOM、摘掉「完全权限」选项;
|
||
* 2. 观察/轮询空白新建会话,首次见到时自动切到 `auto`(自动审查)。
|
||
* @returns 卸载函数
|
||
*/
|
||
function installPermissionPolicy(doc, getSessions, timers = defaultTimers) {
|
||
let disposed = false;
|
||
let scanTimer = 0;
|
||
const setTimerInterval = timers.setInterval ?? defaultTimers.setInterval;
|
||
const clearTimerInterval = timers.clearInterval ?? defaultTimers.clearInterval;
|
||
const scheduleScan = () => {
|
||
if (disposed || scanTimer) return;
|
||
scanTimer = timers.setTimeout(() => {
|
||
scanTimer = 0;
|
||
if (!disposed) pruneFullAccess(doc);
|
||
}, 120);
|
||
};
|
||
const observer = new MutationObserver(scheduleScan);
|
||
if (doc.body) observer.observe(doc.body, {
|
||
childList: true,
|
||
subtree: true
|
||
});
|
||
pruneFullAccess(doc);
|
||
const handled = loadHandledIds(doc);
|
||
const inFlight = /* @__PURE__ */ new Set();
|
||
const projectionUnsubs = /* @__PURE__ */ new Map();
|
||
let listUnsub;
|
||
const markHandled = (id) => {
|
||
if (!handled.has(id)) {
|
||
handled.add(id);
|
||
saveHandledIds(doc, handled);
|
||
}
|
||
const unsub = projectionUnsubs.get(id);
|
||
if (unsub) {
|
||
projectionUnsubs.delete(id);
|
||
try {
|
||
unsub();
|
||
} catch {}
|
||
}
|
||
};
|
||
const watchProjection = (id, live) => {
|
||
if (projectionUnsubs.has(id) || handled.has(id)) return;
|
||
const face = live?.projections?.faceOf?.("permissions");
|
||
if (typeof face?.subscribe !== "function") return;
|
||
try {
|
||
const unsub = face.subscribe(() => {
|
||
if (!disposed) tick();
|
||
});
|
||
if (typeof unsub === "function") projectionUnsubs.set(id, unsub);
|
||
} catch {}
|
||
};
|
||
const tick = async () => {
|
||
if (disposed || typeof getSessions !== "function") return;
|
||
let sessions;
|
||
try {
|
||
sessions = getSessions();
|
||
} catch {
|
||
return;
|
||
}
|
||
if (!listUnsub && typeof sessions?.list?.subscribe === "function") try {
|
||
listUnsub = sessions.list.subscribe(() => {
|
||
if (!disposed) tick();
|
||
});
|
||
} catch {}
|
||
for (const { id, live } of liveSessions(sessions)) {
|
||
if (handled.has(id) || inFlight.has(id)) continue;
|
||
if (!isAutoSwitchEligible(id, live, sessions)) {
|
||
markHandled(id);
|
||
continue;
|
||
}
|
||
const preset = currentPreset(live);
|
||
if (!shouldAutoSwitch(preset, handled.has(id))) {
|
||
if (preset !== void 0 && preset !== null) markHandled(id);
|
||
else watchProjection(id, live);
|
||
continue;
|
||
}
|
||
markHandled(id);
|
||
if (typeof live?.command !== "function") continue;
|
||
inFlight.add(id);
|
||
try {
|
||
const result = await live.command(`/permission ${AUTO_REVIEW_PRESET}`);
|
||
if (!result?.ok) console.info("[dsh-better-chat] auto review not applied for session", id, result?.error?.code ?? "");
|
||
} catch {
|
||
console.info("[dsh-better-chat] auto review switch failed for session", id);
|
||
} finally {
|
||
inFlight.delete(id);
|
||
}
|
||
}
|
||
};
|
||
const intervalId = typeof getSessions === "function" ? setTimerInterval(() => {
|
||
tick();
|
||
}, 2500) : 0;
|
||
if (typeof getSessions === "function") tick();
|
||
return () => {
|
||
disposed = true;
|
||
observer.disconnect();
|
||
if (scanTimer) timers.clearTimeout(scanTimer);
|
||
if (intervalId) clearTimerInterval(intervalId);
|
||
if (listUnsub) {
|
||
try {
|
||
listUnsub();
|
||
} catch {}
|
||
listUnsub = void 0;
|
||
}
|
||
for (const unsub of projectionUnsubs.values()) try {
|
||
unsub();
|
||
} catch {}
|
||
projectionUnsubs.clear();
|
||
};
|
||
}
|
||
// src/client/chat/store-update.ts
|
||
/**
|
||
* 功能三:插件商店「更新」按钮。
|
||
*
|
||
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有「有新版本」
|
||
* 标签、没有按钮。这里补一个真按钮:数据与动作都走宿主自己的远程服务
|
||
* ——pluginMarket 查索引和安装状态,pluginManager.installBundle 按索引
|
||
* 给出的精确 spec 覆盖安装——与官方安装流程同一套接口,不模拟点击、
|
||
* 不动官方状态。
|
||
*
|
||
* 服务经子插件声明 inject 取用:主插件保持自己的 inject,商店功能不
|
||
* 依赖这些服务;未启用实验性插件索引时子插件不生效,本功能静默关闭。
|
||
*/
|
||
const UPDATE_LABELS = ["有新版本", "Update available"];
|
||
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
|
||
function localizedTitle(title, lang) {
|
||
if (typeof title === "string") return title;
|
||
if (!title || typeof title !== "object") return "";
|
||
const record = title;
|
||
const chain = [
|
||
lang,
|
||
lang && lang.split("-")[0],
|
||
"zh-CN",
|
||
"en"
|
||
];
|
||
for (const key of chain) if (key && typeof record[key] === "string" && record[key]) return record[key];
|
||
const values = Object.values(record);
|
||
return typeof values[0] === "string" ? values[0] : "";
|
||
}
|
||
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
|
||
function pickUpdates(searchResults, lang) {
|
||
const updates = [];
|
||
for (const result of searchResults ?? []) {
|
||
const entries = result?.value?.entries ?? result?.entries ?? [];
|
||
for (const entry of entries) {
|
||
if (entry?.installation?.status !== "update-available") continue;
|
||
const versions = entry.versions ?? [];
|
||
const version = versions.find((candidate) => candidate.version === entry.defaultVersion) ?? versions[0];
|
||
const spec = version?.install?.spec;
|
||
if (!entry.name || !version?.version || !spec) continue;
|
||
updates.push({
|
||
name: entry.name,
|
||
title: localizedTitle(entry.title, lang) || entry.name,
|
||
installedVersion: entry.installation.installedVersion ?? "",
|
||
version: version.version,
|
||
spec,
|
||
registry: version.install.registry
|
||
});
|
||
}
|
||
}
|
||
return updates;
|
||
}
|
||
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
|
||
async function runUpdate(remote, update, makeRequestId) {
|
||
const requestId = makeRequestId ? makeRequestId() : "better-chat-update-" + Date.now();
|
||
return remote.pluginManager.installBundle(update.spec, {
|
||
enabled: true,
|
||
requestId,
|
||
...update.registry ? { registry: update.registry } : {}
|
||
});
|
||
}
|
||
/**
|
||
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
|
||
* 同时包含插件标题、且文本总量还像一行的祖先。
|
||
*/
|
||
function findUpdateRow(doc, title) {
|
||
for (const element of doc.querySelectorAll("button")) {
|
||
if (!UPDATE_LABELS.includes(element.textContent?.trim() ?? "")) continue;
|
||
let node = element;
|
||
for (let depth = 0; depth < 6 && node; depth++) {
|
||
node = node.parentElement;
|
||
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
|
||
function makeUpdateClickHandler(doc, getRemote, update, button) {
|
||
return async (event) => {
|
||
event?.preventDefault?.();
|
||
event?.stopPropagation?.();
|
||
const view = doc.defaultView;
|
||
const ask = view?.confirm ?? globalThis.confirm;
|
||
const message = "更新「" + update.title + "」" + (update.installedVersion ? " " + update.installedVersion : "") + " → " + update.version + "?\n会直接覆盖安装新版,插件数据保留。";
|
||
if (ask && !ask.call(view ?? globalThis, message)) return;
|
||
button.disabled = true;
|
||
button.textContent = "更新中…";
|
||
try {
|
||
const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? void 0);
|
||
if (result?.value?.application === "applied") button.textContent = "已更新,重启 DSH 后生效";
|
||
else {
|
||
console.error("[dsh-better-chat] update failed for", update.name, result?.value?.error ?? result);
|
||
button.disabled = false;
|
||
button.textContent = "更新失败,点此重试";
|
||
}
|
||
} catch (error) {
|
||
console.error("[dsh-better-chat] update failed for", update.name, error);
|
||
button.disabled = false;
|
||
button.textContent = "更新失败,点此重试";
|
||
}
|
||
};
|
||
}
|
||
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
|
||
function installStoreUpdateButtons(doc, getRemote, timers = {
|
||
setInterval: (fn, ms) => setInterval(fn, ms),
|
||
clearInterval: (id) => clearInterval(id)
|
||
}) {
|
||
let disposed = false;
|
||
let updates = [];
|
||
const decorate = () => {
|
||
for (const update of updates) {
|
||
const row = findUpdateRow(doc, update.title);
|
||
if (!row || row.querySelector("[data-better-chat-update]")) continue;
|
||
const button = doc.createElement("button");
|
||
button.type = "button";
|
||
button.setAttribute("data-better-chat-update", update.name);
|
||
button.textContent = "更新到 " + update.version;
|
||
button.style.cssText = "flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer";
|
||
button.addEventListener("click", makeUpdateClickHandler(doc, getRemote, update, button));
|
||
row.appendChild(button);
|
||
}
|
||
};
|
||
const refresh = async () => {
|
||
try {
|
||
const remote = getRemote();
|
||
if (!remote?.pluginMarket || !remote?.pluginManager) return;
|
||
const indexes = await remote.pluginMarket.listIndexes();
|
||
const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean);
|
||
const results = [];
|
||
for (const url of urls) results.push(await remote.pluginMarket.search(url, {
|
||
sort: { kind: "index" },
|
||
offset: 0,
|
||
limit: 100
|
||
}));
|
||
if (disposed) return;
|
||
updates = pickUpdates(results, doc.documentElement?.lang || "zh-CN");
|
||
decorate();
|
||
} catch {}
|
||
};
|
||
const observer = new MutationObserver(() => decorate());
|
||
observer.observe(doc.documentElement, {
|
||
childList: true,
|
||
subtree: true
|
||
});
|
||
const timer = timers.setInterval(() => {
|
||
refresh();
|
||
}, 3e4);
|
||
refresh();
|
||
return () => {
|
||
disposed = true;
|
||
observer.disconnect();
|
||
timers.clearInterval(timer);
|
||
};
|
||
}
|
||
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
|
||
const storeUpdatePlugin = {
|
||
name: "dsh-better-chat-store-update",
|
||
inject: [
|
||
"remote",
|
||
"remote.pluginMarket",
|
||
"remote.pluginManager"
|
||
],
|
||
apply(childCtx) {
|
||
childCtx.effect(() => installStoreUpdateButtons(document, () => childCtx.remote), "dsh-better-chat: store update buttons");
|
||
}
|
||
};
|
||
// src/client/settings-copy.ts
|
||
const en = {
|
||
nav: "Better Chat",
|
||
openTitle: "Open deliverables in built-in panel",
|
||
openDescription: "Off by default: chips and inline file mentions open in the system app. Turn this on to preview them in the right Sidebar, matching official chat. Reveal and folder actions still use the system file manager.",
|
||
glassTitle: "Translucent frosted glass",
|
||
glassDescription: "Off by default: reading chrome stays opaque, matching the current Host look. Turn this on to let wallpaper and skins show through the panel; path and count chips stay clear until hover or focus.",
|
||
foldTitle: "Auto-fold process",
|
||
foldDescription: "Default on: collapses earlier steps when new thoughts appear. Turn off to keep all thinking and tools expanded in full.",
|
||
foldNone: "Off",
|
||
foldStandard: "On",
|
||
foldSummary: "Summary",
|
||
shortcutTitle: "Approval card shortcuts",
|
||
shortcutDescription: "Click a keycap and press the new combination. Allow-type actions use Enter, reject uses Esc; modifiers are free. Esc alone cancels while recording. Stored in the plugin config.",
|
||
shortcutAllow: "Allow once",
|
||
shortcutAlways: "Always allow",
|
||
shortcutReject: "Reject",
|
||
shortcutRecording: "Press keys…",
|
||
shortcutDisabled: "Not set",
|
||
shortcutDisable: "Clear",
|
||
shortcutReset: "Restore defaults",
|
||
shortcutErrorKey: "Allow actions must use Enter; reject must use Esc.",
|
||
shortcutErrorModifier: "Always allow needs at least one modifier key.",
|
||
shortcutErrorConflict: "That combination is already used by another action."
|
||
};
|
||
const zh = {
|
||
nav: "Better Chat",
|
||
openTitle: "在内置面板中打开产物",
|
||
openDescription: "默认关闭:产物芯片和正文中的文件提及会用系统应用打开。打开后与官方对话一致,在右侧栏预览。访达 / 资源管理器中的显示与打开所在文件夹不受此开关控制。",
|
||
glassTitle: "半透明毛玻璃",
|
||
glassDescription: "默认关闭:阅读栏保持不透明,和现在的 Host 观感一致。打开后透出宿主壁纸与皮肤;路径、行数等标签静止时透明,悬停或聚焦才显出轮廓。",
|
||
foldTitle: "自动折叠过程",
|
||
foldDescription: "默认开启:新思考产生时自动折叠此前步骤。关闭后全程展开,完整保留原始思考与工具流。",
|
||
foldNone: "关闭",
|
||
foldStandard: "开启",
|
||
foldSummary: "摘要",
|
||
shortcutTitle: "审批卡快捷键",
|
||
shortcutDescription: "点键帽后按下新的组合键。允许类只能用 Enter,拒绝只能用 Esc,修饰键随意;录制时单独按 Esc 取消。保存在插件配置里,重启后仍在。",
|
||
shortcutAllow: "允许(单次)",
|
||
shortcutAlways: "始终允许",
|
||
shortcutReject: "拒绝",
|
||
shortcutRecording: "按下组合键…",
|
||
shortcutDisabled: "未设置",
|
||
shortcutDisable: "清除",
|
||
shortcutReset: "恢复默认",
|
||
shortcutErrorKey: "允许类动作只能用 Enter,拒绝只能用 Esc。",
|
||
shortcutErrorModifier: "「始终允许」至少需要一个修饰键(Ctrl/Shift/Alt)。",
|
||
shortcutErrorConflict: "这个组合键已经被另一个动作占用。"
|
||
};
|
||
function settingsLanguage(tag) {
|
||
return (tag ?? "").toLowerCase().startsWith("zh") ? "zh" : "en";
|
||
}
|
||
function settingsCopyFor(tag) {
|
||
return settingsLanguage(tag) === "zh" ? zh : en;
|
||
}
|
||
// \0dshx-css-module:src/client/SettingsSection.module.css.mjs
|
||
const css = ".TSdzRq_section{flex-direction:column;gap:28px;width:100%;max-width:720px;display:flex}.TSdzRq_row{border-bottom:.5px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}.TSdzRq_rowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:24px;display:flex}.TSdzRq_title{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}.TSdzRq_desc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}.TSdzRq_switch{background:var(--dsw-alias-bg-module-platform);cursor:pointer;border:none;border-radius:12px;flex:none;width:40px;height:24px;padding:0;position:relative}.TSdzRq_switch:after{content:\"\";background:var(--dsw-alias-label-primary);border-radius:50%;width:18px;height:18px;transition:transform .16s;position:absolute;top:3px;left:3px}.TSdzRq_switch[data-on]:after{transform:translate(16px)}.TSdzRq_switch[data-on]{background:var(--dsw-alias-state-business-primary)}.TSdzRq_block{flex-direction:column;gap:10px;display:flex}.TSdzRq_actions{gap:8px;display:flex}.TSdzRq_button{border:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-module-platform);height:32px;color:var(--dsw-alias-label-primary);font:inherit;cursor:pointer;border-radius:8px;padding:0 12px;font-size:13px}.TSdzRq_button:hover{background:var(--dsw-alias-interactive-bg-hover)}.TSdzRq_button:disabled{opacity:.6;cursor:default}.TSdzRq_segment{background:var(--dsw-alias-bg-module-platform);border-radius:10px;gap:2px;width:100%;margin-top:8px;padding:2px;display:flex}.TSdzRq_segmentStop{min-width:0;height:32px;color:var(--dsw-alias-label-secondary);font:inherit;cursor:pointer;background:0 0;border:0;border-radius:8px;flex:1 1 0;padding:0 8px;font-size:12px;line-height:18px}.TSdzRq_segmentStop[data-on]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 0 0 .5px var(--dsw-alias-border-l2)}.TSdzRq_slider{width:100%;accent-color:var(--dsw-alias-state-business-primary);margin:10px 0 0}.TSdzRq_keyActions{flex:none;align-items:center;gap:8px;display:flex}.TSdzRq_keyButton{border:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);min-width:96px;height:32px;color:var(--dsw-alias-label-primary);font-family:var(--ds-font-family-code,ui-monospace, SFMono-Regular, Consolas, monospace);cursor:pointer;border-radius:8px;padding:0 12px;font-size:12px;line-height:20px}.TSdzRq_keyButton:hover{border-color:var(--dsw-alias-border-l3)}.TSdzRq_keyButton[data-recording]{border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);background:var(--dsw-alias-bg-module-platform)}.TSdzRq_error{color:var(--dsw-alias-state-error-primary,#d1483c);margin:0;font-size:12px;line-height:18px}";
|
||
const tagId = "dsh-better-chat/SettingsSection.module.css";
|
||
if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
|
||
const tag = document.createElement("style");
|
||
tag.dataset.plugin = "dsh-better-chat";
|
||
tag.dataset.pluginCss = tagId;
|
||
tag.textContent = css;
|
||
document.head.appendChild(tag);
|
||
}
|
||
var SettingsSection_module_css_default = {
|
||
"actions": "TSdzRq_actions",
|
||
"block": "TSdzRq_block",
|
||
"button": "TSdzRq_button",
|
||
"desc": "TSdzRq_desc",
|
||
"error": "TSdzRq_error",
|
||
"keyActions": "TSdzRq_keyActions",
|
||
"keyButton": "TSdzRq_keyButton",
|
||
"row": "TSdzRq_row",
|
||
"rowText": "TSdzRq_rowText",
|
||
"section": "TSdzRq_section",
|
||
"segment": "TSdzRq_segment",
|
||
"segmentStop": "TSdzRq_segmentStop",
|
||
"slider": "TSdzRq_slider",
|
||
"switch": "TSdzRq_switch",
|
||
"title": "TSdzRq_title"
|
||
};
|
||
// src/client/SettingsSection.tsx
|
||
function text(props, copy, key) {
|
||
if (typeof props.t === "function") try {
|
||
const value = props.t(key);
|
||
if (typeof value === "string" && value.length > 0 && value !== key) return value;
|
||
} catch {}
|
||
return copy[key];
|
||
}
|
||
function SettingsSection(props) {
|
||
const copy = props.copy ?? settingsCopyFor(props.languageTag);
|
||
const chat = props.chat;
|
||
const chatSnap = (0, react.useSyncExternalStore)(chat?.subscribe ?? (() => () => {}), () => chat?.getSnapshot() ?? { bindings: void 0 }, () => ({ bindings: void 0 }));
|
||
const bindings = normalizeBindings(chatSnap);
|
||
const mac = typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
|
||
const [recording, setRecording] = (0, react.useState)(null);
|
||
const [keyError, setKeyError] = (0, react.useState)();
|
||
const announceBindings = (0, react.useCallback)(() => {
|
||
if (typeof window === "undefined") return;
|
||
window.dispatchEvent(new CustomEvent(BINDINGS_CHANGED_EVENT));
|
||
}, []);
|
||
(0, react.useEffect)(() => {
|
||
if (!recording || !chat) return;
|
||
const onKey = (event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
if (event.key === "Escape" && recording !== "reject" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||
setRecording(null);
|
||
setKeyError(void 0);
|
||
return;
|
||
}
|
||
const key = event.key === "Enter" ? "Enter" : event.key === "Escape" ? "Escape" : void 0;
|
||
if (!key) {
|
||
setKeyError(copy.shortcutErrorKey);
|
||
return;
|
||
}
|
||
const binding = {
|
||
key,
|
||
primary: event.ctrlKey || event.metaKey,
|
||
shift: event.shiftKey,
|
||
alt: event.altKey
|
||
};
|
||
const verdict = validateBinding(recording, binding, bindings);
|
||
if (verdict === "key") {
|
||
setKeyError(copy.shortcutErrorKey);
|
||
return;
|
||
}
|
||
if (verdict === "modifier") {
|
||
setKeyError(copy.shortcutErrorModifier);
|
||
return;
|
||
}
|
||
if (verdict === "conflict") {
|
||
setKeyError(copy.shortcutErrorConflict);
|
||
return;
|
||
}
|
||
chat.actions.setApprovalBinding(recording, binding);
|
||
announceBindings();
|
||
setRecording(null);
|
||
setKeyError(void 0);
|
||
};
|
||
window.addEventListener("keydown", onKey, true);
|
||
return () => window.removeEventListener("keydown", onKey, true);
|
||
}, [
|
||
recording,
|
||
chat,
|
||
chatSnap,
|
||
copy,
|
||
bindings,
|
||
announceBindings
|
||
]);
|
||
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
||
className: SettingsSection_module_css_default.section,
|
||
"data-better-chat-settings": true,
|
||
children: chat ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
|
||
className: SettingsSection_module_css_default.block,
|
||
"data-better-chat-shortcuts": true,
|
||
children: [
|
||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
||
className: SettingsSection_module_css_default.title,
|
||
children: text(props, copy, "shortcutTitle")
|
||
}),
|
||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||
className: SettingsSection_module_css_default.desc,
|
||
children: text(props, copy, "shortcutDescription")
|
||
}),
|
||
[
|
||
[
|
||
"allow",
|
||
"shortcutAllow",
|
||
bindings.allow
|
||
],
|
||
[
|
||
"always",
|
||
"shortcutAlways",
|
||
bindings.always
|
||
],
|
||
[
|
||
"reject",
|
||
"shortcutReject",
|
||
bindings.reject
|
||
]
|
||
].map(([action, title, binding]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||
className: SettingsSection_module_css_default.row,
|
||
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
||
className: SettingsSection_module_css_default.rowText,
|
||
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
||
className: SettingsSection_module_css_default.title,
|
||
children: text(props, copy, title)
|
||
})
|
||
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||
className: SettingsSection_module_css_default.keyActions,
|
||
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
||
type: "button",
|
||
className: SettingsSection_module_css_default.keyButton,
|
||
"data-recording": recording === action || void 0,
|
||
onClick: () => {
|
||
setKeyError(void 0);
|
||
setRecording(action);
|
||
},
|
||
children: recording === action ? text(props, copy, "shortcutRecording") : binding ? bindingKeycap(binding, mac) : text(props, copy, "shortcutDisabled")
|
||
}), action === "always" && binding ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
||
type: "button",
|
||
className: SettingsSection_module_css_default.button,
|
||
onClick: () => {
|
||
chat.actions.setApprovalBinding("always", null);
|
||
announceBindings();
|
||
setKeyError(void 0);
|
||
},
|
||
children: text(props, copy, "shortcutDisable")
|
||
}) : null]
|
||
})]
|
||
}, action)),
|
||
keyError ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||
className: SettingsSection_module_css_default.error,
|
||
"data-better-chat-key-error": true,
|
||
children: keyError
|
||
}) : null,
|
||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
||
className: SettingsSection_module_css_default.actions,
|
||
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
||
type: "button",
|
||
className: SettingsSection_module_css_default.button,
|
||
onClick: () => {
|
||
chat.actions.resetApprovalBindings();
|
||
announceBindings();
|
||
setRecording(null);
|
||
setKeyError(void 0);
|
||
},
|
||
children: text(props, copy, "shortcutReset")
|
||
})
|
||
})
|
||
]
|
||
}) : null
|
||
});
|
||
}
|
||
// src/client/settings.tsx
|
||
function languageTag(ctx) {
|
||
const snap = (ctx.get?.("locale") ?? ctx.locale)?.getSnapshot?.();
|
||
return snap?.locale ?? snap?.language ?? (typeof document !== "undefined" ? document.documentElement.lang : void 0) ?? (typeof navigator !== "undefined" ? navigator.language : void 0);
|
||
}
|
||
/** Own locale namespace and settings-section id (chat-only, independent of any display plugin). */
|
||
const SETTINGS_LOCALE_NS = "better-chat";
|
||
const SETTINGS_SECTION_ID = "better-chat";
|
||
function installBetterChatSettings(ctx, chat) {
|
||
const locale = ctx.get?.("locale") ?? ctx.locale;
|
||
if (locale?.register) ctx.effect(() => locale.register(SETTINGS_LOCALE_NS, {
|
||
zh,
|
||
en
|
||
}), "dsh-better-chat: settings copy");
|
||
const injected = () => ({
|
||
chat,
|
||
copy: settingsCopyFor(languageTag(ctx)),
|
||
languageTag: languageTag(ctx)
|
||
});
|
||
const slots = ctx.slots;
|
||
slots.inject("settings.section", () => slots.register({
|
||
name: "settings.section",
|
||
id: SETTINGS_SECTION_ID,
|
||
order: 40,
|
||
label: () => locale?.bind?.(SETTINGS_LOCALE_NS)?.("nav") || settingsCopyFor(languageTag(ctx)).nav,
|
||
locale: locale?.bind ? SETTINGS_LOCALE_NS : void 0,
|
||
inject: injected
|
||
}, SettingsSection));
|
||
}
|
||
// src/client/index.tsx
|
||
const name = "dsh-better-chat";
|
||
/** 聊天增强本身不额外依赖宿主服务;保留服务注入列表以兼容既有宿主。 */
|
||
const inject = [
|
||
"slots",
|
||
"sessions",
|
||
"conversation",
|
||
"uiConversation",
|
||
"remote",
|
||
"remote.session"
|
||
];
|
||
function apply(ctx) {
|
||
const chatPrefs = createChatStore().create();
|
||
const getBindings = () => currentBindings(chatPrefs);
|
||
ctx.effect(() => install(document, getBindings), "dsh-better-chat: approval key routing");
|
||
ctx.effect(() => installKeyHints(document, { getBindings }), "dsh-better-chat: approval key hints");
|
||
ctx.effect(() => installPermissionPolicy(document, () => ctx.sessions), "dsh-better-chat: permission policy (no full access, auto review by default)");
|
||
try {
|
||
ctx.plugin(storeUpdatePlugin);
|
||
} catch {}
|
||
installBetterChatSettings(ctx, chatPrefs);
|
||
}
|
||
exports.apply = apply;
|
||
exports.inject = inject;
|
||
exports.name = name;
|
||
return module.exports;
|
||
}
|
||
});
|
||
|
||
//# sourceMappingURL=client.js.map
|