-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathcode.js
More file actions
77 lines (64 loc) 路 2.46 KB
/
Copy pathcode.js
File metadata and controls
77 lines (64 loc) 路 2.46 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { $, $$, setVar, calcTextWidth } from './util.js';
const snippetNode = $('#snippet');
const setupLines = (node, config) => {
$$(':scope > br', node).forEach((row) => (row.outerHTML = '<div> </div>'));
const rows = $$(':scope > div', node);
setVar('line-number-width', calcTextWidth(rows.length + config.startLine));
rows.forEach((row, idx) => {
const newRow = document.createElement('div');
newRow.classList.add('line');
row.replaceWith(newRow);
if (config.showLineNumbers) {
const lineNum = document.createElement('div');
lineNum.classList.add('line-number');
lineNum.textContent = idx + 1 + config.startLine;
newRow.appendChild(lineNum);
}
const span = document.createElement('span');
span.textContent = ' ';
row.appendChild(span);
const lineCodeDiv = document.createElement('div');
lineCodeDiv.classList.add('line-code');
const lineCode = document.createElement('span');
lineCode.innerHTML = row.innerHTML;
lineCodeDiv.appendChild(lineCode);
newRow.appendChild(lineCodeDiv);
});
};
const stripInitialIndent = (node) => {
const regIndent = /^\s+/u;
const initialSpans = $$(':scope > div > span:first-child', node);
if (initialSpans.some((span) => !regIndent.test(span.textContent))) return;
const minIndent = Math.min(
...initialSpans.map((span) => span.textContent.match(regIndent)[0].length)
);
initialSpans.forEach((span) => (span.textContent = span.textContent.slice(minIndent)));
};
const isEmptyLine = (node) => node.innerText.match(/^\s*$/);
const trimEmptyLines = (node, config) => {
while(isEmptyLine(node.firstChild)) {
node.removeChild(node.firstChild);
if(config.realLineNumbers) config.startLine++;
}
while(isEmptyLine(node.lastChild)) node.removeChild(node.lastChild);
}
const getClipboardHtml = (clip) => {
const html = clip.getData('text/html');
if (html) return html;
const text = clip
.getData('text/plain')
.split('\n')
.map((line) => `<div>${line}</div>`)
.join('');
return `<div>${text}</div>`;
};
export const pasteCode = (config, clipboard) => {
snippetNode.innerHTML = getClipboardHtml(clipboard);
const code = $('div', snippetNode);
snippetNode.style.fontSize = code.style.fontSize;
snippetNode.style.lineHeight = code.style.lineHeight;
snippetNode.innerHTML = code.innerHTML;
stripInitialIndent(snippetNode);
if(config.trimEmptyLines) trimEmptyLines(snippetNode, config);
setupLines(snippetNode, config);
};