Jump to content

User:Nardog/CopyCodeBlock.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Nardog (talk | contribs) at 12:58, 7 April 2023 (Created page with '(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'); } else { mw.notify('Copy failed', { type: 'error' }); } }; let addButtons = $pres => { $pres.addClass('copycodeblock-block').e...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
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.
(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');
		} else {
			mw.notify('Copy failed', { type: 'error' });
		}
	};
	let addButtons = $pres => {
		$pres.addClass('copycodeblock-block').each(function () {
			new OO.ui.ButtonWidget({
				classes: ['copycodeblock'],
				framed: false,
				icon: 'copy',
				title: 'Copy to clipboard',
			}).on('click', copy, [this]).$element.appendTo(this);
		});
	};
	let run;
	mw.hook('wikipage.content').add($content => {
		let $pres = $content.find('pre');
		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{display:none}');
		mw.loader.using(['oojs-ui-core', 'oojs-ui.styles.icons-editing-advanced'], () => {
			addButtons($pres);
		});
	});
}());