Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(lemon-ui): add a copy button to error and warning toasts (#86272)

Alessandro Pogliaghi906ebd5213da
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 90d3b4c1fce3..513ce11fd2c0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4385,25 +4385,25 @@ snapshots:
lemon-ui-lemon-text-area-markdown--lemon-text-markdown-with-text--light:
hash: v1.k794b7964.2a0bb72ced637238cfc496b82b4f9fb848c7af10d49fd6085acd2925363b67e8.mHXsr6MVeOP2d5GGAs3VwuQ6kPgsj2A1UmohZ8F6yvo
lemon-ui-lemon-toast--billing-error--dark:
- hash: v1.k794b7964.c004c4e644ae0d098d6ded2eedca2805f4daee3bc089ba2d5bed2e50a67aa49a.kNV9DQ-T9ZQgiANz3qEClYU7IMUMQcuDzyCxqAA8zig
+ hash: v1.k794b7964.5da9c7bd53e4abb187399898f25a23ce8ced2d774f698c8a924ec2e154735aea.kzKa6tePw16XYNP0JNkqr0zY7bhGuxd_AaGizrrUrh8
lemon-ui-lemon-toast--billing-error--light:
- hash: v1.k794b7964.862d4d3df03255d032be44c95fe0e2f9e9c0ca8e1eac8ed405714fb7e243a0eb.bDtW5E6WEwkeM7FzYfjy1QBwwU690WtxBSH6nGqK7vI
+ hash: v1.k794b7964.cf189dec2258bd206d131ff1e99bc8cba48295d0fb4913d858d2b187a35811ec.mW58dBj9TPtYgJbJA2B40DAoMXkNLGrPvo11MUG5lkc
lemon-ui-lemon-toast--error-with-incident-note--dark:
- hash: v1.k794b7964.36b9789b1edb271c630de390abc50b6a0163e37e20249f18d17eeafd066957d3.BYP3avrTzdgOjH7cXT0n8cCFCRX-h8Uh8mkVcQNHvRw
+ hash: v1.k794b7964.1c601ff99ec62768254d37d7453e6b02071de2bf96df39d4ea47c734bc9d0035.ezD5TEDT6BIROQhjSuw1MSU2O6j8Zjai7vN33EgCQxk
lemon-ui-lemon-toast--error-with-incident-note--light:
- hash: v1.k794b7964.a77835eae9ec263614704c9a43ec4747561864806359ab77f7b352187503c61f.gNg59OgrxN0qsLhpQAxnOYY8M-lsPvoLrwDLK-n7Ps0
+ hash: v1.k794b7964.2a92f3b983c1c6410b7bc866499c809ecef38757d1e6280163399c0b721f280b.QIynsokAr1mX-4Zxhs_XPyovCbFAjZl6O51lbx5mh9U
lemon-ui-lemon-toast--toast-types--dark:
hash: v1.k794b7964.9a93f03c8391bc2cb5cd7a3000cdc5050ed923f81d74fb3e29ee771f90278422.ajdcd7vnsE7Hf3vWO7kBMxQQ4lwbOJL9LXIogck1o1s
lemon-ui-lemon-toast--toast-types--light:
- hash: v1.k794b7964.6a12b2fc8bd803c89cb1fd0770da58ee6361d07eb1d86a47e8e9f98a5d43a77e.zGKrMMDe0jeGRad0O5Cq39ZoresS-H5MQkg7TGUbdi8
+ hash: v1.k794b7964.546cd43b6f655af91a15a63f68ac3925d904c8f5f86eb80dd470c0a37a63390c.hqOGIq9E9CeCAiSyny_O7Vrt7EwO3aDvU_jbYnqAAuY
lemon-ui-lemon-toast--with-button--dark:
hash: v1.k794b7964.5b5e4581b58ca0efd6691bac898bbf2fa483c46a16aa2351f6b3da4fb8e5c626.Qh4J06OAPRGJ9XDlJAcIZQEVCjPJGfz9wytyNxpB3q4
lemon-ui-lemon-toast--with-button--light:
hash: v1.k794b7964.2820eea139a246bed0ed8abf08a959f7c51f5a66e667469731be30d089971f88.P1FtguqStg4ftmd6oYGvfcsMUcUx5IVwYYRVeXklG7Q
lemon-ui-lemon-toast--with-progress--dark:
- hash: v1.k794b7964.dbf1967abfc641fec4b8376d32228f23ee49d2f709834f0bd47f304b76f2eb4f.UCeori0uSu6H3XMw1s1jzevelkfrnFQdTcBnqF8GhzI
+ hash: v1.k794b7964.0b60fab2524eb78c94c14a00add1e816a140257f978b9c49c01b274b8b6e4427.6G0t08wkCp89tZnLjyoLXSngFgdNghZ-VrKGzT4VT0g
lemon-ui-lemon-toast--with-progress--light:
- hash: v1.k794b7964.14135d92cccfcb8e6425297f76f6966efe27b8f37cdce9e6ff881445490b45c9.1A7tp_1ylmlSbBFEiPchUzv97ys3_JnbM8hYRGLSmK4
+ hash: v1.k794b7964.2dd225a8bed617fb276ea6541e0af08dfadec2b3075e0230aa66943b5ea9067f.v8ST7rAT0juXM7wcbUdq2Dz8kecpbO4rcromY2LTjPY
lemon-ui-lemon-tree--default--dark:
hash: v1.k794b7964.71802645c8ade36774f37c73fdf79c43a632dc75882fdc92654bea8b74fea746.yUS68trt1jBQFXHLI3wGxtFDhHiPynq1yskrvf6aELY
lemon-ui-lemon-tree--default--light:
diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx
new file mode 100644
index 000000000000..2ff406eef714
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx
@@ -0,0 +1,37 @@
+import { act, fireEvent, render } from '@testing-library/react'
+
+import { GET_HELP_BUTTON, ToastContent } from './LemonToast'
+
+describe('LemonToast', () => {
+ const writeText = jest.fn((_text: string) => Promise.resolve())
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ Object.assign(navigator, { clipboard: { writeText } })
+ })
+
+ // The copy button reads the rendered message out of the DOM, so it copies whatever sits inside the
+ // message element. Widening that element to cover the action button would silently append "Get help"
+ // to every error someone pastes elsewhere.
+ it('copies the message without the action button label', async () => {
+ const { container } = render(
+ <ToastContent type="error" message="Load experiment failed" button={GET_HELP_BUTTON} />
+ )
+
+ fireEvent.click(container.querySelector('[data-attr="toast-copy-button"]')!)
+ await act(async () => {})
+
+ expect(writeText).toHaveBeenCalledWith('Load experiment failed')
+ })
+
+ it.each([
+ ['error', true],
+ ['warning', true],
+ ['info', false],
+ ['success', false],
+ ] as const)('renders the copy button on a %s toast: %s', (type, expected) => {
+ const { container } = render(<ToastContent type={type} message="A message" />)
+
+ expect(!!container.querySelector('[data-attr="toast-copy-button"]')).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
index 382416032024..346d474d3ac2 100644
--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
@@ -1,11 +1,13 @@
import posthog from 'posthog-js'
+import { useRef } from 'react'
import { toast, type ToastOptions, type UpdateOptions } from 'react-toastify'
-import { IconCheckCircle, IconInfo, IconWarning, IconX } from '@posthog/icons'
+import { IconCheckCircle, IconCopy, IconInfo, IconWarning, IconX } from '@posthog/icons'
import { getIncidentStatus, STATUS_PAGE_BASE } from 'lib/components/HelpMenu/incidentStatus'
import { isChristmas } from 'lib/holidays'
import { hashCodeForString } from 'lib/utils/strings'
+import { writeToClipboard } from 'lib/utils/writeToClipboard'
import { IconErrorOutline, IconGift } from '../icons'
import { LemonButton } from '../LemonButton'
@@ -86,10 +88,57 @@ export function ToastActionButton({
)
}
+/**
+ * The outcome is reported here rather than through `lib/utils/copyToClipboard`, which would make this
+ * module and that one require each other. Both sides share the clipboard mechanics through
+ * `writeToClipboard`, so the plain-HTTP fallback the toolbar depends on stays in one place.
+ *
+ * The notice is an info toast because an error or warning would carry a copy button of its own, and
+ * clicking it would fail the same way.
+ */
+async function copyMessage(text: string): Promise<void> {
+ const outcome = await writeToClipboard(text)
+ if (outcome === 'copied') {
+ lemonToast.info('Copied message to clipboard', { icon: <IconCopy /> })
+ return
+ }
+ lemonToast.info('Could not reach the clipboard. Select the message and copy it manually.')
+}
+
+function ToastCopyButton({ getMessageText }: { getMessageText: () => string }): JSX.Element {
+ return (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ noPadding
+ // `.Toastify__toast-body button` sets a 0.75rem side margin sized for the action button,
+ // which costs the message a line of wrapping at the toast's fixed 26rem width.
+ className="shrink-0 !mx-2"
+ icon={<IconCopy />}
+ tooltip="Copy message"
+ onClick={() => void copyMessage(getMessageText())}
+ data-attr="toast-copy-button"
+ />
+ )
+}
+
export function ToastContent({ type, message, button, id }: ToastContentProps): JSX.Element {
+ const messageRef = useRef<HTMLSpanElement>(null)
+
return (
<div className="flex items-center" data-attr={`${type}-toast`}>
- <span className="grow overflow-hidden text-ellipsis">{message}</span>
+ <span ref={messageRef} className="grow min-w-0 overflow-hidden text-ellipsis">
+ {message}
+ </span>
+ {/* Only on the types whose text people take elsewhere, so confirmations keep their full width. */}
+ {(type === 'error' || type === 'warning') && (
+ // innerText breaks at block boundaries, so a message that renders the incident note under
+ // itself copies as two lines. textContent would run them together, and is the fallback
+ // only because jsdom does not implement innerText.
+ <ToastCopyButton
+ getMessageText={() => messageRef.current?.innerText ?? messageRef.current?.textContent ?? ''}
+ />
+ )}
{button && <ToastActionButton button={button} toastId={id} />}
</div>
)
diff --git a/frontend/src/lib/utils/copyToClipboard.tsx b/frontend/src/lib/utils/copyToClipboard.tsx
index 83dc3a0221a0..a908136e5e5c 100644
--- a/frontend/src/lib/utils/copyToClipboard.tsx
+++ b/frontend/src/lib/utils/copyToClipboard.tsx
@@ -1,62 +1,27 @@
import { IconCopy } from '@posthog/icons'
import { lemonToast } from '@posthog/lemon-ui'
+import { writeToClipboard } from 'lib/utils/writeToClipboard'
+
export async function copyToClipboard(
value: string,
description: string = 'text',
{ silent = false, html }: { silent?: boolean; html?: string } = {}
): Promise<boolean> {
- if (!navigator.clipboard) {
+ const outcome = await writeToClipboard(value, html)
+
+ if (outcome === 'unavailable') {
lemonToast.warning('Oops! Clipboard capabilities are only available over HTTPS or on localhost')
return false
}
-
- const notifySuccess = (): void => {
- if (silent) {
- return
- }
+ if (outcome === 'failed') {
+ lemonToast.error(`Could not copy ${description} to clipboard`)
+ return false
+ }
+ if (!silent) {
lemonToast.info(`Copied ${description} to clipboard`, {
icon: <IconCopy />,
})
}
-
- // Writing both formats lets a paste target that understands HTML keep the formatting, while
- // plain-text targets still receive `value`. Browser support for `text/html` in a ClipboardItem
- // is not universal, so a failure here falls through to the plain-text write below rather than
- // failing the copy.
- if (html && typeof ClipboardItem !== 'undefined' && navigator.clipboard.write) {
- try {
- await navigator.clipboard.write([
- new ClipboardItem({
- 'text/html': new Blob([html], { type: 'text/html' }),
- 'text/plain': new Blob([value], { type: 'text/plain' }),
- }),
- ])
- notifySuccess()
- return true
- } catch {
- // Fall through to the plain-text paths.
- }
- }
-
- try {
- await navigator.clipboard.writeText(value)
- notifySuccess()
- return true
- } catch {
- // If the Clipboard API fails, fallback to textarea method
- try {
- const textArea = document.createElement('textarea')
- textArea.value = value
- document.body.appendChild(textArea)
- textArea.select()
- document.execCommand('copy')
- document.body.removeChild(textArea)
- notifySuccess()
- return true
- } catch (err) {
- lemonToast.error(`Could not copy ${description} to clipboard: ${err}`)
- return false
- }
- }
+ return true
}
diff --git a/frontend/src/lib/utils/writeToClipboard.test.ts b/frontend/src/lib/utils/writeToClipboard.test.ts
new file mode 100644
index 000000000000..168fcab78d98
--- /dev/null
+++ b/frontend/src/lib/utils/writeToClipboard.test.ts
@@ -0,0 +1,66 @@
+import { writeToClipboard } from './writeToClipboard'
+
+describe('writeToClipboard', () => {
+ const originalClipboard = navigator.clipboard
+ const execCommand = jest.fn(() => true)
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ document.execCommand = execCommand as unknown as typeof document.execCommand
+ })
+
+ afterEach(() => {
+ Object.defineProperty(navigator, 'clipboard', { value: originalClipboard, configurable: true })
+ })
+
+ function setClipboard(clipboard: unknown): void {
+ Object.defineProperty(navigator, 'clipboard', { value: clipboard, configurable: true })
+ }
+
+ // The toolbar runs inside customer pages served over plain HTTP, where navigator.clipboard does not
+ // exist at all, and inside embedded contexts where writeText rejects. Both fall through to the
+ // selection route, so dropping it would leave every copy control in the toolbar doing nothing.
+ it.each([
+ ['the Clipboard API writes', { writeText: jest.fn(() => Promise.resolve()) }, true, 'copied', 0],
+ ['the Clipboard API is absent', undefined, true, 'copied', 1],
+ [
+ 'the Clipboard API rejects',
+ { writeText: jest.fn(() => Promise.reject(new Error('denied'))) },
+ true,
+ 'copied',
+ 1,
+ ],
+ ['the Clipboard API is absent and the fallback fails', undefined, false, 'unavailable', 1],
+ [
+ 'the Clipboard API rejects and the fallback fails',
+ { writeText: jest.fn(() => Promise.reject(new Error('denied'))) },
+ false,
+ 'failed',
+ 1,
+ ],
+ ])('returns %s -> %s', async (_description, clipboard, fallbackWorks, expected, expectedFallbackCalls) => {
+ setClipboard(clipboard)
+ if (!fallbackWorks) {
+ execCommand.mockImplementation(() => {
+ throw new Error('not allowed')
+ })
+ }
+
+ await expect(writeToClipboard('some text')).resolves.toBe(expected)
+ expect(execCommand).toHaveBeenCalledTimes(expectedFallbackCalls)
+ })
+
+ // Browsers do not all accept text/html in a ClipboardItem, so a rich copy that a browser refuses has
+ // to land as plain text rather than reporting failure.
+ it.each([
+ ['lands', () => Promise.resolve(), 0],
+ ['is refused', () => Promise.reject(new Error('unsupported')), 1],
+ ])('writes plain text when the rich write %s', async (_description, write, expectedWriteTextCalls) => {
+ Object.defineProperty(globalThis, 'ClipboardItem', { value: class {}, configurable: true })
+ const writeText = jest.fn(() => Promise.resolve())
+ setClipboard({ write: jest.fn(write), writeText })
+
+ await expect(writeToClipboard('some text', '<b>some text</b>')).resolves.toBe('copied')
+ expect(writeText).toHaveBeenCalledTimes(expectedWriteTextCalls)
+ })
+})
diff --git a/frontend/src/lib/utils/writeToClipboard.ts b/frontend/src/lib/utils/writeToClipboard.ts
new file mode 100644
index 000000000000..8e924d42dc4e
--- /dev/null
+++ b/frontend/src/lib/utils/writeToClipboard.ts
@@ -0,0 +1,56 @@
+/**
+ * `copied` — the text is on the clipboard, by any route.
+ * `unavailable` — the browser exposes no Clipboard API, which is the plain-HTTP case the toolbar runs in.
+ * `failed` — a write was attempted and did not land.
+ */
+export type ClipboardWriteOutcome = 'copied' | 'unavailable' | 'failed'
+
+/**
+ * Writes to the clipboard with no user-facing feedback, so callers that report through a toast can use it
+ * without depending on the toast module.
+ */
+export async function writeToClipboard(value: string, html?: string): Promise<ClipboardWriteOutcome> {
+ if (!navigator.clipboard) {
+ return writeThroughSelection(value) ? 'copied' : 'unavailable'
+ }
+
+ // Writing both formats lets a paste target that understands HTML keep the formatting, while
+ // plain-text targets still receive `value`. Browser support for `text/html` in a ClipboardItem
+ // is not universal, so a failure here falls through to the plain-text write below rather than
+ // failing the copy.
+ if (html && typeof ClipboardItem !== 'undefined' && navigator.clipboard.write) {
+ try {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'text/html': new Blob([html], { type: 'text/html' }),
+ 'text/plain': new Blob([value], { type: 'text/plain' }),
+ }),
+ ])
+ return 'copied'
+ } catch {
+ // Fall through to the plain-text paths.
+ }
+ }
+
+ try {
+ await navigator.clipboard.writeText(value)
+ return 'copied'
+ } catch {
+ return writeThroughSelection(value) ? 'copied' : 'failed'
+ }
+}
+
+/** The pre-Clipboard-API route. Still the only one that works over plain HTTP and in some embedded contexts. */
+function writeThroughSelection(value: string): boolean {
+ try {
+ const textArea = document.createElement('textarea')
+ textArea.value = value
+ document.body.appendChild(textArea)
+ textArea.select()
+ document.execCommand('copy')
+ document.body.removeChild(textArea)
+ return true
+ } catch {
+ return false
+ }
+}