User:BDavis (WMF)/Scripts/AccessKeyDeDup.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * De-duplicate access keys.
 * 
 * Adapted from code by [[User:Jdlrobson]] shared on [[phab:T336211]].
 * 
 * Copyright (c) 2024 Wikimedia Foundation and contributors.
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
(function () {
	const activeKeys = {};
	const isVisible = ( node ) => node.offsetParent !== null; // original inverted this test
	const accessKeyNodes = Array.from( document.querySelectorAll( "[accesskey]" ) );

	accessKeyNodes.forEach( (node) => {
		const key = node.getAttribute( "accesskey" );
		node.dataset.accessKey = key;
		if ( isVisible( node ) && !activeKeys[ key ] ) {
			activeKeys[key] = node;
		} else {
			node.removeAttribute( "accesskey" );
		}
	} );
	console.log( "Access keys", activeKeys );

	window.onresize = (event) => {
		accessKeyNodes.forEach( ( node ) => {
			const key = node.dataset.accessKey;
			if ( !isVisible( node ) ) {
				if ( activeKeys[ key ] === node ) {
					activeKeys[ key ] = null;
					node.removeAttribute( "accesskey" );
				}
			} else if ( !activeKeys[ key ] ) {
				activeKeys[ key ] = node;
				node.setAttribute( "accesskey", key );
			}
		} );
		console.log( "Access keys", activeKeys );
	};
}());