Skip to content

Commit

Permalink
feat(copyTextToClipboard): 可设置复制容器类名
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 10, 2021
1 parent 9c26c2b commit 5231b8d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/utils/copyTextToClipboard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,19 @@ import { copyTextToClipboard } from './copyTextToClipboard'

describe('copyTextToClipboard', () => {
document.execCommand = () => true
document.body.removeChild = () => true as any

test('复制成功', () => {
expect(copyTextToClipboard('123')).toBeTrue()
})

test('可设置容器类名', () => {
expect(document.querySelector('.x-copy')?.tagName).toBeNil()
expect(
copyTextToClipboard('1234', {
containerClass: 'x-copy',
}),
).toBeTrue()
expect(document.querySelector('.x-copy')?.tagName).toBe('TEXTAREA')
})
})
17 changes: 16 additions & 1 deletion src/utils/copyTextToClipboard.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
export interface CopyTextToClipboardOptions {
/**
* 复制容器的类名。
*/
containerClass?: string
}

/**
* 复制文本到剪切板。
*
* @param text 要复制的文本
* @param options 选项
* @returns 返回是否复制成功
*/
export function copyTextToClipboard(text: string): boolean {
export function copyTextToClipboard(
text: string,
options?: CopyTextToClipboardOptions,
): boolean {
// https://github.com/sindresorhus/copy-text-to-clipboard/blob/master/index.js
const element = document.createElement('textarea')

Expand All @@ -19,6 +30,10 @@ export function copyTextToClipboard(text: string): boolean {
element.style.left = '-9999px'
element.style.fontSize = '12pt' // Prevent zooming on iOS

if (options?.containerClass) {
element.className = options.containerClass
}

const selection = document.getSelection()!
let originalRange: Range | undefined
if (selection.rangeCount > 0) {
Expand Down

0 comments on commit 5231b8d

Please sign in to comment.