@@ -54,31 +54,30 @@ import { agentLabel } from "./agent-label"
5454import { attached , imageAttachmentPlaceholderStyle , typeLabel } from "../components/message-file"
5555
5656export async function writeClipboard ( text : string ) : Promise < boolean > {
57- const body = typeof document === "undefined" ? undefined : document . body
58-
59- if ( body ) {
60- const textarea = document . createElement ( "textarea" )
61- textarea . value = text
62- textarea . setAttribute ( "readonly" , "" )
63- textarea . style . position = "fixed"
64- textarea . style . opacity = "0"
65- textarea . style . pointerEvents = "none"
66- body . appendChild ( textarea )
67- textarea . select ( )
68- const copied = document . execCommand ( "copy" )
69- body . removeChild ( textarea )
70-
71- if ( copied ) return true
72- }
73-
74- const clipboard = typeof navigator === "undefined" ? undefined : navigator . clipboard
75-
76- if ( ! clipboard ?. writeText ) return false
77-
78- return clipboard . writeText ( text ) . then (
57+ const written = await navigator . clipboard ?. writeText ( text ) . then (
7958 ( ) => true ,
8059 ( ) => false ,
8160 )
61+
62+ if ( written ) return true
63+ // The textarea sits beside the focused element so a focus trap, such as an open menu's, keeps its selection.
64+ const active = document . activeElement instanceof HTMLElement ? document . activeElement : undefined
65+ const host = active && active !== document . body ? ( active . parentElement ?? document . body ) : document . body
66+ const textarea = document . createElement ( "textarea" )
67+ textarea . value = text
68+ textarea . setAttribute ( "readonly" , "" )
69+ textarea . setAttribute ( "aria-hidden" , "true" )
70+ textarea . tabIndex = - 1
71+ textarea . style . position = "fixed"
72+ textarea . style . opacity = "0"
73+ textarea . style . pointerEvents = "none"
74+ host . appendChild ( textarea )
75+ textarea . select ( )
76+ const copied = document . execCommand ( "copy" )
77+ textarea . remove ( )
78+ active ?. focus ( { preventScroll : true } )
79+
80+ return copied
8281}
8382
8483type MetaItem = { label : string ; variant ?: boolean }
0 commit comments