Skip to content

Commit 4b5ddc0

Browse files
committed
partially switched codeblocks JS asset from jQuery
1 parent c5dfe3e commit 4b5ddc0

1 file changed

Lines changed: 53 additions & 20 deletions

File tree

app/assets/javascripts/codeblocks.js

Lines changed: 53 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,62 @@
11
document.addEventListener('DOMContentLoaded', () => {
2-
const buttonTemplate = `<button class="copy-button button is-muted is-outlined has-margin-2">Copy</button>`;
2+
/**
3+
* @param {string} content
4+
* @returns {HTMLButtonElement}
5+
*/
6+
const createCopyButton = (content, isSmall = false) => {
7+
const button = document.createElement('button');
8+
button.classList.add('copy-button', 'button', 'is-muted', 'is-outlined', 'has-margin-2');
9+
button.textContent = 'Copy';
10+
11+
if (isSmall) {
12+
button.classList.add('is-small');
13+
}
14+
15+
button.addEventListener('click', async () => {
16+
const originalButtonText = button.textContent;
17+
18+
try {
19+
await navigator.clipboard.writeText(content);
20+
button.textContent = 'Copied!';
21+
}
22+
catch (e) {
23+
console.warn(e);
24+
button.textContent = 'Failed!';
25+
}
26+
finally {
27+
setTimeout(() => {
28+
button.textContent = originalButtonText;
29+
}, 2000);
30+
}
31+
});
32+
33+
return button;
34+
};
35+
36+
/**
37+
* @param {HTMLElement} element
38+
* @returns {HTMLDivElement}
39+
*/
40+
const wrapRelative = (element) => {
41+
const wrapper = document.createElement('div');
42+
wrapper.style.position = 'relative';
43+
wrapper.append(element.cloneNode(true));
44+
element.replaceWith(wrapper);
45+
return wrapper;
46+
};
47+
48+
if (!window.isSecureContext) {
49+
return;
50+
}
351

452
$('.post--content pre > code')
553
.parent()
6-
.each(function () {
7-
const $button = $(buttonTemplate);
54+
.each(function (_, element) {
855
const $content = $(this).text();
956
const numLines = $content.trim().split(/\r?\n/).length;
1057

11-
if (numLines <= 1) {
12-
$button.addClass('is-small');
13-
}
14-
15-
$(this)
16-
.wrap('<div style="position:relative;"></div>')
17-
.parent()
18-
.prepend(
19-
$button.click(function () {
20-
navigator.clipboard.writeText($content);
21-
$(this).text('Copied!');
22-
setTimeout(() => {
23-
$(this).text('Copy');
24-
}, 2000);
25-
}),
26-
);
58+
const button = createCopyButton($content, numLines <= 1);
59+
const wrapper = wrapRelative(element);
60+
wrapper.prepend(button);
2761
});
2862
});
29-

0 commit comments

Comments
 (0)