From c057fb389f4f6967e86e439eb59e4d1851cd7250 Mon Sep 17 00:00:00 2001 From: EnixCoda Date: Wed, 11 Nov 2020 17:13:29 +0800 Subject: [PATCH] chore: remove leading space when copy file --- src/platforms/GitHub/CopyFileButton.tsx | 2 +- src/utils/DOMHelper.ts | 29 ++++++++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/platforms/GitHub/CopyFileButton.tsx b/src/platforms/GitHub/CopyFileButton.tsx index d7ec994..753191b 100644 --- a/src/platforms/GitHub/CopyFileButton.tsx +++ b/src/platforms/GitHub/CopyFileButton.tsx @@ -34,7 +34,7 @@ export function CopyFileButton(props: React.PropsWithChildren) { 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) diff --git a/src/utils/DOMHelper.ts b/src/utils/DOMHelper.ts index a6bfdcc..38f9fcd 100644 --- a/src/utils/DOMHelper.ts +++ b/src/utils/DOMHelper.ts @@ -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 }