Skip to content

Commit b893463

Browse files
committed
feat: 聊天界面增加代码复制按钮
1 parent d5330da commit b893463

File tree

3 files changed

+52
-6
lines changed

3 files changed

+52
-6
lines changed

package-lock.json

Lines changed: 4 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,6 @@
299299
"dependencies": {
300300
"iconv-lite": "^0.6.3",
301301
"jschardet": "^3.1.4",
302-
"openai": "^4.81.0"
302+
"openai": "^4.85.2"
303303
}
304304
}

src/chatPanel.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,26 @@ export class ChatPanel {
140140
padding: 2px 4px;
141141
border-radius: 3px;
142142
}
143+
.copy-btn {
144+
position: absolute;
145+
right: 8px;
146+
top: 8px;
147+
padding: 4px 8px;
148+
background: #616161;
149+
border: none;
150+
color: white;
151+
cursor: pointer;
152+
border-radius: 4px;
153+
font-size: 0.8em;
154+
transition: opacity 0.3s;
155+
}
156+
.copy-btn:hover {
157+
background: #757575;
158+
}
159+
.model pre {
160+
position: relative;
161+
padding-top: 30px !important;
162+
}
143163
.katex {
144164
color: white !important;
145165
background-color: transparent !important;
@@ -192,6 +212,32 @@ export class ChatPanel {
192212
const input = document.getElementById('input');
193213
const sendButton = document.getElementById('send');
194214
const stopButton = document.getElementById('stop');
215+
216+
function addCopyButtons() {
217+
document.querySelectorAll('pre').forEach(pre => {
218+
if (pre.querySelector('.copy-btn')) return;
219+
220+
const button = document.createElement('button');
221+
button.className = 'copy-btn';
222+
button.textContent = 'Copy';
223+
224+
button.addEventListener('click', (event) => {
225+
// 通过事件目标找到最近的 pre 元素
226+
const preElement = event.target.closest('pre');
227+
// 获取 pre 元素下的第一个 code 元素内容
228+
const code = preElement.querySelector('code').textContent;
229+
230+
navigator.clipboard.writeText(code).then(() => {
231+
event.target.textContent = 'Copied!';
232+
setTimeout(() => {
233+
event.target.textContent = 'Copy';
234+
}, 2000);
235+
});
236+
});
237+
238+
pre.appendChild(button);
239+
});
240+
}
195241
196242
// 初始化代码高亮
197243
hljs.configure({ ignoreUnescapedHTML: true });
@@ -239,6 +285,7 @@ export class ChatPanel {
239285
throwOnError: false
240286
});
241287
288+
addCopyButtons();
242289
// 重新高亮代码块
243290
hljs.highlightAll();
244291
} else {

0 commit comments

Comments
 (0)