chore: remove leading space when copy file

This commit is contained in:
EnixCoda 2020-11-11 17:13:29 +08:00
parent fbc67c68f4
commit c057fb389f
No known key found for this signature in database
GPG key ID: 0C1A07377913A1DD
2 changed files with 22 additions and 9 deletions

View file

@ -34,7 +34,7 @@ export function CopyFileButton(props: React.PropsWithChildren<Props>) {
function copyCode() {
const codeElement = getCodeElement()
if (codeElement) {
setContent(copyElementContent(codeElement) ? contents.success : contents.error)
setContent(copyElementContent(codeElement, true) ? contents.success : contents.error)
}
}
element.addEventListener('click', copyCode)

View file

@ -73,16 +73,29 @@ export function scrollToRepoContent() {
/**
* copy content of a DOM element to clipboard
*/
export function copyElementContent(element: Element): boolean {
let selection = window.getSelection()
if (selection) selection.removeAllRanges()
export function copyElementContent(element: Element, trimLeadingSpace?: boolean): boolean {
window.getSelection()?.removeAllRanges()
const range = document.createRange()
range.selectNode(element)
selection = window.getSelection()
if (selection) selection.addRange(range)
if (trimLeadingSpace) {
// Leading spaces can be produced by embedded DOM structures
let realWrapper: Element | null = element
while (realWrapper?.childElementCount === 1) realWrapper = realWrapper?.firstElementChild
if (realWrapper?.childElementCount && realWrapper.childElementCount > 1) {
const first = realWrapper.firstElementChild
const last = realWrapper.lastElementChild
if (first && last) {
range.selectNode(first)
range.setEndAfter(last)
}
}
} else {
range.selectNode(element)
}
window.getSelection()?.addRange(range)
const isCopySuccessful = document.execCommand('copy')
selection = window.getSelection()
if (selection) selection.removeAllRanges()
window.getSelection()?.removeAllRanges()
return isCopySuccessful
}