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:39, 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(async function() {
					try {
						if (button.isDisabled()) return;
						var canRead = await navigator.permissions.query({ name: 'clipboard-read' });
						var clipboardData;
						if (canRead.state == "prompt") {
							button.setLabel("Awaiting clipboard permissions...");
							await navigator.clipboard.readText();
						}
						clipboardData = await navigator.clipboard.readText();
						var value = $pre.text();
						if (clipboardData == undefined || value != clipboardData) {
							await navigator.clipboard.writeText(value);
						}
						afterSuccess();
					} catch (e) {
						console.error(e);
						alert("Copy failed.");
					}
				});
				$pre.addClass('copycodeblock-block').append(button.$element);
			})
		});
	});
}());