({ children, language, codeText }: { children: ReactNode; language: string; codeText: string })
| 11 | } |
| 12 | |
| 13 | function CodeBlock({ children, language, codeText }: { children: ReactNode; language: string; codeText: string }): JSX.Element { |
| 14 | const [copy, setCopy] = useState<{ text: string; status: 'idle' | 'copying' | 'copied' | 'failed' }>({ text: '', status: 'idle' }); |
| 15 | const copyTicket = useRef(0); |
| 16 | const status = copy.text === codeText ? copy.status : 'idle'; |
| 17 | const copyCode = async (): Promise<void> => { |
| 18 | const ticket = ++copyTicket.current; |
| 19 | setCopy({ text: codeText, status: 'copying' }); |
| 20 | try { |
| 21 | if (!navigator.clipboard?.writeText) throw new Error('Clipboard unavailable'); |
| 22 | await navigator.clipboard.writeText(codeText); |
| 23 | if (ticket === copyTicket.current) setCopy({ text: codeText, status: 'copied' }); |
| 24 | } catch { |
| 25 | if (ticket === copyTicket.current) setCopy({ text: codeText, status: 'failed' }); |
| 26 | } |
| 27 | }; |
| 28 | return <div className="cbm-chat-code-block"> |
| 29 | <div className="cbm-chat-code-header"><span className="cbm-chat-code-language">{language}</span><div> |
| 30 | {status === 'failed' && <span className="cbm-chat-code-copy-error" role="status">Copy unavailable</span>} |
| 31 | <button type="button" aria-label="Copy code" disabled={status === 'copying'} onClick={() => { void copyCode(); }}>{status === 'copied' ? 'Copied' : status === 'copying' ? 'Copying…' : 'Copy'}</button> |
| 32 | </div></div> |
| 33 | <pre tabIndex={0} aria-label={`${language} code`}>{children}</pre> |
| 34 | </div>; |
| 35 | } |
| 36 | |
| 37 | const components: Components = { |
| 38 | a: ({ href, children, title }) => { |
nothing calls this directly
no test coverage detected