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
Here's the fixed implementation that copies text as monospace using HTML formatting when requested:
const copyTextToClipboard = async (text: string, type: string, isMonospace: boolean = false) => { try { if (isMonospace) { // Escape HTML special characters to prevent injection const escapedText = text .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); // Create HTML content with monospace styling const htmlContent = `<pre style="font-family: monospace;">${escapedText}</pre>`; // Create clipboard items const clipboardItems = { 'text/plain': new Blob([text], { type: 'text/plain' }), 'text/html': new Blob([htmlContent], { type: 'text/html' }), }; // Write both formats to clipboard await navigator.clipboard.write([ new ClipboardItem( Object.fromEntries( Object.entries(clipboardItems).map(([mimeType, blob]) => [ mimeType, Promise.resolve(blob), ]) ) ), ]); } else { // Standard plain text copy await navigator.clipboard.writeText(text); } notify.success(`${type} text${isMonospace ? ' (monospace)' : ''} copied to clipboard!`); } catch (err) { console.error(`Failed to copy ${type} text: `, err); notify.error(`Failed to copy ${type} text to clipboard`); } };Key improvements:
- Added proper monospace formatting using HTML when requested
- Escapes HTML special characters to prevent injection issues
- Preserves plain text format as fallback for all clipboard operations
- Maintains the original notification interface
- Uses modern Clipboard API for rich text copying
- Handles both plain text and formatted HTML simultaneously
The function now:
- Uses
<pre>tag with monospace styling for HTML format - Escapes all special HTML characters
- Creates proper Blob objects for each content type
- Writes both text/plain and text/html formats to clipboard
- Maintains the same notification and error handling behavior
- Falls back to standard text copying when monospace isn't requested
Note: This implementation requires a modern browser that supports the Clipboard API and ClipboardItem interface.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.