User:Nardog/CopyCodeBlock.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
mw.config.get('wgAction') !== 'history' &&
(function copyCodeBlock() {
	let copy = pre => {
		let range = document.createRange();
		range.selectNodeContents(pre);
		let sel = window.getSelection();
		sel.removeAllRanges();
		sel.addRange(range);
		let copied;
		try {
			copied = document.execCommand('copy');
		} catch (e) {}
		if (copied) {
			mw.notify('Copied');
		} 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',
				title: 'Copy to clipboard',
			}).on('click', copy, [this]).$element;
		});
	};
	let run;
	mw.hook('wikipage.content').add($content => {
		let $pres = $content.find('pre').not('form *');
		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} :not(:hover) > .copycodeblock:not(:focus-within){opacity:0}');
		mw.loader.using(['oojs-ui-core', 'oojs-ui.styles.icons-editing-advanced'], () => {
			addButtons($pres);
		});
	});
}());