User:Qwerfjkl/scripts/sectionLink.js

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('wgNamespaceNumber') >= 0 &&
$.when($.ready, mw.loader.using('mediawiki.util')).then(function copySectLink() {
	let handler = e => {
		e.preventDefault();
		let text = (e.data ? '#' + e.data.replace(
			/[\[\]\{\|\}]/g,
			s => '&#' + s.codePointAt(0) + ';'
		) : '').replace(/_/g, ' ');
		text = text.replace(/#/, '');
		navigator.clipboard.writeText(text).then(() => {
			mw.notify(`Copied "${text}"`);
		}, () => {
			let $input = $('<input>', {
				type: 'text',
				value: text,
				readonly: '',
				style: 'position:absolute;left:-999px'
			}).appendTo(document.body);
			$input[0].select();
			document.execCommand('copy');
			$input.remove();
			mw.notify(`Probably copied "${text}"`);
		});
	};
	let isMobile = mw.config.get('skin') === 'minerva';
	if (isMobile) {
		mw.loader.addStyleTag(`.copysectlink::before{background-image:url("data:image/svg+xml,%3Csvg width='20' height='20' version='1.1' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%2354595d'%3E%3Cpath d='M16 0H5v2h11v14h2V2a2 2 0 0 0-2-2z'/%3E%3Cpath d='m4 20h9c1.1 0 2-0.9 2-2v-13c0-1.1-0.9-2-2-2h-9c-1.1 0-2 0.9-2 2v13c0 1.1 0.9 2 2 2zm0-15h9v13h-9z'/%3E%3C/g%3E%3C/svg%3E")} .collapsible-heading:not(.open-block) .copysectlink{visibility:hidden} .mw-editsection{white-space:nowrap}`);
	}
	let addButton = function () {
		let isFirst = this.tagName === 'H1';
		let hn = isFirst ? this : this.parentElement;
		if (hn.querySelector('.copysectlink')) return;
		let $button = $('<a>', {
			class: 'copysectlink',
			href: mw.util.getUrl() + (isFirst ? '' : '#' + this.id),
			role: 'button',
			text: 'copy'
		}).click(!isFirst && this.id, handler);
		if (isMobile) {
			$button.addClass('mw-ui-icon mw-ui-icon-element').attr('title', 'Copy');
			let wrapper = hn.querySelector('.mw-editsection');
			if (wrapper) {
				$button.prependTo(wrapper);
			} else {
				$button.appendTo(hn);
			}
		} else {
			let bracket = hn.querySelector('.mw-editsection-bracket:last-child');
			if (bracket) {
				bracket.insertAdjacentText('beforebegin', ' | ');
			} else {
				bracket = $('<span>').addClass('mw-editsection').append(
					$('<span>', { class: 'mw-editsection-bracket', text: '[' }),
					$('<span>', { class: 'mw-editsection-bracket', text: ']' })
				).appendTo(hn).children()[1];
			}
			$button.insertBefore(bracket);
		}
	};
	addButton.call(document.querySelector('h1'));
	if (mw.config.get('wgAction') !== 'view') return;
	mw.hook('wikipage.content').add($content => {
		$content.find('.mw-headline').each(addButton);
	});
});