Jump to content

User:Awesome Aasim/copycodeblock.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Awesome Aasim (talk | contribs) at 04:12, 19 August 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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() {
	$(document).ready(function() {
		let $pres = $("#mw-content-text").find('pre').not('form *');
		if (!$pres.length) return;
		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', 'oojs-ui.styles.icons-interactions'], function() {
			$pres.each(function() {
				let $pre = $(this);
				let button = new OO.ui.ButtonWidget({
					classes: ['copycodeblock'],
					framed: false,
					icon: 'copy',
					title: 'Copy to clipboard',
				});
				function afterSuccess() {
					button.setIcon("checkAll");
					button.setLabel("Copied!");
					window.setTimeout(function() {
						button.setIcon("copy");
						button.setLabel("");
					}, 3000);
				}
				button.$element.click(function() {
					navigator.clipboard.readText().then(function(data) {
						var value = $pre.text();
						if (value == data) {
							afterSuccess();
						} else {
							navigator.clipboard.writeText(value).then(function() {
								afterSuccess();
							}).catch(console.error);
						}
					}).catch(console.error);
				});
				$pre.addClass('copycodeblock-block').append(button.$element);
			})
		});
	});
}());