typescript, fix (copy text as monospace to clipboard): const copyTextToClipboard = async…
- User
typescript, fix (copy text as monospace to clipboard): const copyTextToClipboard = async (text: string, type: string, isMonospace: boolean = false) => { try { await navigator.clipboard.writeText(text); notify.success(
${type} text copied to clipboard!); } catch (err) { console.error(Failed to copy ${type} text:, err); notify.error(Failed to copy ${type} text to clipboard); } }; - Assistant
To make the clipboard content monospaced, you need to preserve the font formatting. However, the
clipboard.writeText()method only lets you copy plain text — it cannot control how the pasted content is displayed (like using monospace). For rich text (e.g., HTML or styled), you must usenavigator.clipboard.write()with aClipboardItem.Here’s how you can modify your function to support copying as monospace by writing HTML content when
isMonospaceistrue:const copyTextToClipboard = async ( text: string, type: string, isMonospace: boolean = false ) => { try { if (!navigator.clipboard) { throw new Error("Clipboard API not supported"); } if (isMonospace && navigator.clipboard.write) { const html = `<pre style="font-family: monospace;">${escapeHtml(text)}</pre>`; const blob = new Blob([html], { type: "text/html" }); const item = new ClipboardItem({ "text/html": blob }); await navigator.clipboard.write([item]); } else { await navigator.clipboard.writeText(text); } notify.success(`${type} text copied to clipboard!`); } catch (err) { console.error(`Failed to copy ${type} text: `, err); notify.error(`Failed to copy ${type} text to clipboard`); } }; // Helper to escape HTML characters const escapeHtml = (text: string): string => text.replace(/[&<>"']/g, (char) => { const escapeMap: { [key: string]: string } = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }; return escapeMap[char] || char; });🔍 Explanation:
- Monospace Trick: A
<pre>tag with CSSfont-family: monospacewill render the copied content with monospace font if pasted into a rich-text editor (e.g., Gmail, Word, etc.). - Plain Text Fallback: If
isMonospaceisfalse, it just copies regular text. - HTML Escaping: Prevents HTML injection when copying code.
✅ Note: Rich HTML copying only works in contexts that support the
ClipboardItemAPI (modern browsers) and may not behave as expected when pasted into plain-text editors (e.g., Notepad). - Monospace Trick: A
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.