mirror of
https://github.com/EnixCoda/Gitako.git
synced 2026-03-11 08:54:44 +00:00
chore: remove leading space when copy file
This commit is contained in:
parent
fbc67c68f4
commit
c057fb389f
2 changed files with 22 additions and 9 deletions
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue