User:RZuo/CopyCodeBlock.js
Jump to navigation
Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
Documentation for this user script can be added at User:RZuo/CopyCodeBlock. |
//<nowiki>
/**
* This script adds a xx-large button at the top right corner of each code block (created in wikitext
* via <pre>...</pre>, <syntaxhighlight>...</syntaxhighlight>, <poem>...</poem>, or a line beginning with a space,
* or the entirety of a Lua, CSS, or JavaScript page) that copies the content of the block when clicked.
*
* @author https://en.wikipedia.org/wiki/User:Nardog/CopyCodeBlock.js by Nardog
* @author modified by RoyZuo
**/
mw.config.get('wgAction') !== 'history' &&
(function copyCodeBlock() {
let copy = pre => {
let sel = window.getSelection();
sel.removeAllRanges();
let range = document.createRange();
range.selectNodeContents(pre);
sel.addRange(range);
let copied;
try {
copied = document.execCommand('copy');
} catch (e) {}
if (copied) {
mw.notify('COPIED', { type: 'success' });
} else {
mw.notify('Copy failed', { type: 'error' });
}
};
let addButtons = $pres => {
$pres.addClass('copycodeblock-block').append(function () {
return new OO.ui.ButtonWidget({
classes: ['copycodeblock'],
framed: false,
icon: 'copy',
label: 'Copy to clipboard',
}).on('click', copy, [this]).$element;
});
};
let run;
mw.hook('wikipage.content').add($content => {
let $pres = $content.find('pre, .poem');
if (!$pres.length) return;
if (run) {
addButtons($pres);
return;
}
run = true;
mw.loader.addStyleTag('.copycodeblock-block{position:relative} .copycodeblock{position:absolute;top:0;right:0;font-size:xx-large}');
mw.loader.using(['oojs-ui-core', 'oojs-ui.styles.icons-editing-advanced'], () => {
addButtons($pres);
});
});
}());
//</nowiki>