-
Notifications
You must be signed in to change notification settings - Fork 240
/
paste.ts
51 lines (44 loc) 路 1.25 KB
/
paste.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import {fireEvent} from '@testing-library/dom'
import {Config, UserEvent} from '../setup'
import {
createDataTransfer,
getSpaceUntilMaxLength,
prepareInput,
isEditable,
readDataTransferFromClipboard,
} from '../utils'
export async function paste(
this: UserEvent,
clipboardData?: DataTransfer | string,
) {
const doc = this[Config].document
const target = doc.activeElement ?? /* istanbul ignore next */ doc.body
const data: DataTransfer =
(typeof clipboardData === 'string'
? getClipboardDataFromString(clipboardData)
: clipboardData) ??
(await readDataTransferFromClipboard(doc).catch(() => {
throw new Error(
'`userEvent.paste()` without `clipboardData` requires the `ClipboardAPI` to be available.',
)
}))
return pasteImpl(target, data)
}
function pasteImpl(target: Element, clipboardData: DataTransfer) {
fireEvent.paste(target, {
clipboardData,
})
if (isEditable(target)) {
const data = clipboardData
.getData('text')
.substr(0, getSpaceUntilMaxLength(target))
if (data) {
prepareInput(data, target, 'insertFromPaste')?.commit()
}
}
}
function getClipboardDataFromString(text: string) {
const dt = createDataTransfer()
dt.setData('text', text)
return dt
}