chat: Copy response and Copy message answer Copied or say they could not (with an older-copy fallback); a typed message keeps its line breaks (#3731, #3720)
This commit is contained in:
1 parent
e61b7024cf
commit
c7899f9c89
4 files changed
+73
-4
No files matched your search
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copy text for the person. The browser clipboard call can be refused (the desktop web view asks for permission, or has no clipboard
|
||||
* object); the older copy command through a hidden field still works there. The answer is always a toast: "Copied", or one plain
|
||||
* sentence and what to do next (#3731).
|
||||
*/
|
||||
export interface ClipboardDeps {
|
||||
clipboard?: { writeText(text: string): Promise<void> } | null;
|
||||
legacyCopy?: (text: string) => boolean;
|
||||
toast: (tone: 'success' | 'warn', title: string, body?: string) => void;
|
||||
}
|
||||
|
||||
function legacyCopy(text: string): boolean {
|
||||
if (typeof document === 'undefined') return false;
|
||||
const field = document.createElement('textarea');
|
||||
field.value = text;
|
||||
field.setAttribute('readonly', '');
|
||||
field.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
|
||||
document.body.appendChild(field);
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
try {
|
||||
field.select();
|
||||
return document.execCommand('copy');
|
||||
} catch { return false; }
|
||||
finally { field.remove(); active?.focus?.(); }
|
||||
}
|
||||
|
||||
export async function copyText(text: string, label: string, deps: ClipboardDeps): Promise<boolean> {
|
||||
const clipboard = deps.clipboard === undefined ? (typeof navigator === 'undefined' ? null : navigator.clipboard) : deps.clipboard;
|
||||
let done = false;
|
||||
try { if (clipboard) { await clipboard.writeText(text); done = true; } } catch { /* the fallback is next */ }
|
||||
if (!done) { try { done = (deps.legacyCopy ?? legacyCopy)(text); } catch { done = false; } }
|
||||
if (done) deps.toast('success', 'Copied', label);
|
||||
else deps.toast('warn', 'Couldn’t copy', 'Select the text and copy it with Ctrl+C.');
|
||||
return done;
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import { Btn, Icon, IconBtn, ErrorNotice, type IconName } from '../components/ui
|
||||
import { composerCap, scrollBehavior } from '../lib/responsive';
|
||||
import { relTime, cx, duration, tokens, tps } from '../lib/format';
|
||||
import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store';
|
||||
import { copyText } from '../lib/clipboard';
|
||||
import { getSlashCommands } from '../lib/commands';
|
||||
import { useLocation } from '../lib/router';
|
||||
import { composerSends } from '../lib/shortcut-bindings';
|
||||
@@ -616,11 +617,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
|
||||
const [sentTime, setSentTime] = useState(() => relTime(m.at));
|
||||
if (m.role === 'user') {
|
||||
return (<div className="st-msg st-msg--user" onMouseEnter={() => setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}>
|
||||
<div className="st-bubble">{tr(m.photos?.length ? <ChatPhotos photos={m.photos}/> : null)}{m.markdown ? <Markdown text={m.content} onOpenLink={onOpenLink} imageSession={activeSession}/> : m.content}</div>
|
||||
<div className="st-bubble">{tr(m.photos?.length ? <ChatPhotos photos={m.photos}/> : null)}{m.markdown ? <Markdown text={m.content} onOpenLink={onOpenLink} imageSession={activeSession}/> : <span className="st-bubble__text">{m.content}</span>}</div>
|
||||
<div className="st-msg__meta">
|
||||
<time dateTime={m.at} title={tr(new Date(m.at).toLocaleString(localeTag()))}>{tr(sentTime)}</time>
|
||||
<span className="st-msg__actions">
|
||||
<IconBtn name="copy" title={tr("Copy message")} onClick={() => void navigator.clipboard.writeText(m.content)}/>
|
||||
<IconBtn name="copy" title={tr("Copy message")} onClick={() => void copyText(m.content, 'Message', { toast: pushToast })}/>
|
||||
<IconBtn name="refresh" title={tr("Rewind to here")} disabled={streaming} onClick={() => {
|
||||
const prompt = rewindTo(m.id);
|
||||
if (prompt !== null)
|
||||
@@ -659,11 +660,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
|
||||
{tr(!m.streaming && !m.timeSkipId && (m.content || m.error) ? (<div className="st-msg__meta">
|
||||
<span className="st-msg__actions">
|
||||
{tr(isLast ? <>
|
||||
<IconBtn name="copy" title={tr("Copy response")} onClick={() => void navigator.clipboard.writeText(m.content)}/>
|
||||
<IconBtn name="copy" title={tr("Copy response")} onClick={() => void copyText(m.content, 'Response', { toast: pushToast })}/>
|
||||
<IconBtn name="refresh" title={tr("Ask again")} onClick={() => void retryLast(m.id)}/>
|
||||
</> : null)}
|
||||
<MessageMenu label={tr("More response actions")}>
|
||||
{tr(!isLast ? <><button role="menuitem" className="menu__item" onClick={() => void navigator.clipboard.writeText(m.content)}>{tr("Copy response")}</button><button role="menuitem" className="menu__item" onClick={() => void retryLast(m.id)}>{tr("Ask again")}</button></> : null)}
|
||||
{tr(!isLast ? <><button role="menuitem" className="menu__item" onClick={() => void copyText(m.content, 'Response', { toast: pushToast })}>{tr("Copy response")}</button><button role="menuitem" className="menu__item" onClick={() => void retryLast(m.id)}>{tr("Ask again")}</button></> : null)}
|
||||
{tr(isLast ? <button role="menuitem" className="menu__item" onClick={() => void continueLast()}>{tr("Continue")}</button> : null)}
|
||||
<button role="menuitem" className="menu__item" onClick={() => branchFrom(m.id)}>{tr("Branch from here")}</button>
|
||||
{tr(m.tokens || m.tps || m.durationMs ? <p className="xs muted response-stats">{tr(m.tokens ? `${tokens(m.tokens)} tokens` : '')}{tr(m.tps ? ` · ${tps(m.tps)} tok/s` : '')}{tr(m.durationMs ? ` · ${duration(m.durationMs)}` : '')}{tr(m.demo ? ' · Example' : '')}</p> : null)}
|
||||
|
||||
@@ -7517,3 +7517,6 @@ textarea {
|
||||
.md-math-block .md-math--display { margin: 0; }
|
||||
.md-math .katex { font-size: 1.08em; }
|
||||
.md-math .katex-display { margin: 0; }
|
||||
|
||||
/* A message the person typed keeps its line breaks (#3720). */
|
||||
.st-bubble__text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
@@ -0,0 +1,30 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { transform } from 'esbuild';
|
||||
|
||||
const { code } = await transform(await readFile(new URL('../src/lib/clipboard.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
|
||||
const { copyText } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
const toasts = () => { const list = []; return { list, toast: (...a) => list.push(a) }; };
|
||||
|
||||
test('Copy says Copied when the clipboard takes the text (#3731)', async () => {
|
||||
const t = toasts(); let got = '';
|
||||
assert.equal(await copyText('hello', 'Response', { clipboard: { writeText: async v => { got = v; } }, toast: t.toast }), true);
|
||||
assert.equal(got, 'hello'); assert.equal(t.list[0][0], 'success');
|
||||
});
|
||||
test('a refused clipboard falls back to the older copy command', async () => {
|
||||
const t = toasts(); let got = '';
|
||||
assert.equal(await copyText('x', 'Response', { clipboard: { writeText: async () => { throw new Error('denied'); } }, legacyCopy: v => { got = v; return true; }, toast: t.toast }), true);
|
||||
assert.equal(got, 'x'); assert.equal(t.list[0][0], 'success');
|
||||
});
|
||||
test('when nothing works the person is told, never left with a silent click', async () => {
|
||||
const t = toasts();
|
||||
assert.equal(await copyText('x', 'Response', { clipboard: null, legacyCopy: () => false, toast: t.toast }), false);
|
||||
assert.equal(t.list.length, 1); assert.equal(t.list[0][0], 'warn'); assert.match(t.list[0][2], /Ctrl\+C/);
|
||||
});
|
||||
test('the typed message keeps its line breaks (#3720) and the chat uses the shared copy', async () => {
|
||||
const css = await readFile(new URL('../src/styles/app.css', import.meta.url), 'utf8');
|
||||
assert.match(css, /\.st-bubble__text\s*\{[^}]*white-space:\s*pre-wrap/);
|
||||
const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(chat, /void navigator\.clipboard\.writeText/);
|
||||
});
|
||||
Reference in new issue
Block a user