All files / mobile.startup Toggler.js

85.26% Statements 81/95
67.3% Branches 35/52
80% Functions 12/15
86.17% Lines 81/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308  1x 1x 1x         1x 1x                                                   11x 11x 11x 11x 11x                 44x       11x 11x       11x     44x                         19x 1x     18x   18x   18x 18x 18x 18x 17x 17x     18x 18x   18x 18x 3x   3x   15x 15x                 18x                   18x                   18x           18x                           2x 2x   2x       2x   2x     2x     2x   2x   2x                           11x 22x 22x 22x 22x     22x 22x 22x             3x 3x   3x 3x     22x               22x 22x 22x       22x   22x 22x                         22x   22x         4x                   11x   11x 11x                                       11x 11x   11x           11x 11x   11x                       22x 2x   2x         1x  
const
	util = require( './util' ),
	escapeSelector = util.escapeSelector,
	arrowOptions = {
		icon: 'expand',
		isSmall: true,
		additionalClassNames: 'indicator'
	},
	Icon = require( './Icon' );
const isCollapsedByDefault = require( './isCollapsedByDefault.js' );
 
/**
 * @typedef {Object} ToggledEvent
 * @prop {boolean} expanded True if section is opened, false if closed.
 * @prop {Page} page
 * @prop {jQuery.Object} $heading
 * @memberof module:mobile.startup
 * @ignore
 */
 
/**
 * A class for enabling toggling
 *
 * Toggling can be disabled on a sepcific heading by adding the
 * collapsible-heading-disabled class.
 */
class Toggler {
	/**
	 * @param {Object} options
	 * @param {OO.EventEmitter} options.eventBus Object used to emit section-toggled events.
	 * @param {jQuery.Object} options.$container to apply toggling to
	 * @param {string} options.prefix a prefix to use for the id.
	 * @param {Page} options.page to allow storage of session for future visits
	 */
	constructor( options ) {
		this.eventBus = options.eventBus;
		this.$container = options.$container;
		this.prefix = options.prefix;
		this.page = options.page;
		this._enable();
	}
 
	/**
	 * Check if sections should be collapsed by default
	 *
	 * @return {boolean}
	 */
	isCollapsedByDefault() {
		if ( this._isCollapsedByDefault === undefined ) {
			// Thess classes override site settings and user preferences. For example:
			// * ...-collapsed used on talk pages by DiscussionTools. (T321618, T322628)
			// * ...-expanded used in previews (T336572)
			const $override = this.$container.closest( '.collapsible-headings-collapsed, .collapsible-headings-expanded' );
			Iif ( $override.length ) {
				this._isCollapsedByDefault = $override.hasClass( 'collapsible-headings-collapsed' );
			} else {
				// Check site config
				this._isCollapsedByDefault = isCollapsedByDefault();
			}
		}
		return this._isCollapsedByDefault;
	}
 
	/**
	 * Given a heading, toggle it and any of its children
	 *
	 * @memberof Toggler
	 * @instance
	 * @param {jQuery.Object} $heading A heading belonging to a section
	 * @param {boolean} fromSaved Section is being toggled from a saved state
	 * @return {boolean}
	 */
	toggle( $heading, fromSaved ) {
		if ( !fromSaved && $heading.hasClass( 'collapsible-heading-disabled' ) ) {
			return false;
		}
 
		const wasExpanded = $heading.is( '.open-block' );
 
		$heading.toggleClass( 'open-block' );
 
		arrowOptions.rotation = wasExpanded ? 0 : 180;
		const newIndicator = new Icon( arrowOptions );
		const $indicatorElement = $heading.data( 'indicator' );
		if ( $indicatorElement ) {
			$indicatorElement.replaceWith( newIndicator.$el );
			$heading.data( 'indicator', newIndicator.$el );
		}
 
		const $headingLabel = $heading.find( '.mw-headline' );
		$headingLabel.attr( 'aria-expanded', !wasExpanded );
 
		const $content = $heading.next();
		if ( $content.hasClass( 'open-block' ) ) {
			$content.removeClass( 'open-block' );
			// jquery doesn't allow custom values for the hidden attribute it seems.
			$content.get( 0 ).setAttribute( 'hidden', 'until-found' );
		} else {
			$content.addClass( 'open-block' );
			$content.removeAttr( 'hidden' );
		}
 
		/* T239418 We consider this event as a low-priority one and emit it asynchronously.
		This ensures that any logic associated with section toggling is async and not contributing
		directly to a slow click/press event handler.
 
		Currently costly reflow-inducing viewport size computation is being done for lazy-loaded
		images by the main listener to this event. */
		mw.requestIdleCallback( () => {
			/**
			 * Global event emitted after a section has been toggled
			 *
			 * @event ~section-toggled
			 * @type {ToggledEvent}
			 * @memberof module:mobile.startup~Toggler
			 * @ignore
			 */
 
			this.eventBus.emit( 'section-toggled', {
				expanded: wasExpanded,
				$heading
			} );
			/**
			 * Internal for use inside ExternalGuidance.
			 *
			 * @event ~'mobileFrontend.section-toggled'
			 * @memberof Hooks
			 */
			mw.hook( 'mobileFrontend.section-toggled' ).fire( {
				expanded: wasExpanded,
				$heading
			} );
		} );
 
		return true;
	}
 
	/**
	 * Reveals an element and its parent section as identified by it's id
	 *
	 * @memberof Toggler
	 * @instance
	 * @param {string} id An element ID within the $container
	 * @return {boolean} Target ID was found
	 */
	reveal( id ) {
		let $target;
		// jQuery will throw for hashes containing certain characters which can break toggling
		try {
			$target = this.$container.find( '#' + escapeSelector( id ) );
		} catch ( e ) {}
		Iif ( !$target || !$target.length ) {
			return false;
		}
 
		let $heading = $target.parents( '.collapsible-heading' );
		// The heading is not a section heading, check if in a content block!
		Iif ( !$heading.length ) {
			$heading = $target.parents( '.collapsible-block' ).prev( '.collapsible-heading' );
		}
		Iif ( $heading.length && !$heading.hasClass( 'open-block' ) ) {
			this.toggle( $heading );
		}
		Eif ( $heading.length ) {
			// scroll again after opening section (opening section makes the page longer)
			window.scrollTo( 0, $target.offset().top );
		}
		return true;
	}
 
	/**
	 * Enables section toggling in a given container.
	 *
	 * @memberof Toggler
	 * @instance
	 * @private
	 */
	_enable() {
 
		// FIXME This should use .find() instead of .children(), some extensions like Wikibase
		// want to toggle other headlines than direct descendants of $container. (T95889)
		this.$container.children( '.section-heading' ).each( ( i, headingEl ) => {
			const $heading = this.$container.find( headingEl ),
				$headingLabel = $heading.find( '.mw-headline' ),
				$indicator = $heading.find( '.indicator' ),
				id = this.prefix + 'collapsible-block-' + i;
			// Be sure there is a `section` wrapping the section content.
			// Otherwise, collapsible sections for this page is not enabled.
			Eif ( $heading.next().is( 'section' ) ) {
				const $content = $heading.next( 'section' );
				$heading
					.addClass( 'collapsible-heading ' )
					.data( 'section-number', i )
					.on( 'click', ( ev ) => {
						// don't toggle, if the click target was a link
						// (a link in a section heading)
						// See T117880
						const clickedLink = ev.target.closest( 'a' );
						Eif ( !clickedLink || !clickedLink.href ) {
							// prevent taps/clicks on edit button after toggling (T58209)
							ev.preventDefault();
							this.toggle( $heading );
						}
					} );
				$headingLabel
					.attr( {
						tabindex: 0,
						role: 'button',
						'aria-controls': id,
						'aria-expanded': 'false'
					} );
 
				arrowOptions.rotation = !this.isCollapsedByDefault() ? 180 : 0;
				const indicator = new Icon( arrowOptions );
				Iif ( $indicator.length ) {
					// replace the existing indicator
					$indicator.replaceWith( indicator.$el );
				} else {
					indicator.prependTo( $heading );
				}
				$heading.data( 'indicator', indicator.$el );
				$content
					.addClass( 'collapsible-block' )
					.eq( 0 )
					.attr( {
						// We need to give each content block a unique id as that's
						// the only way we can tell screen readers what element we're
						// referring to via `aria-controls`.
						id
					} )
					.on( 'beforematch', () => this.toggle( $heading ) )
					.addClass( 'collapsible-block-js' )
					.get( 0 ).setAttribute( 'hidden', 'until-found' );
 
				enableKeyboardActions( this, $heading );
 
				if ( !this.isCollapsedByDefault() ) {
					// Expand sections by default on wide screen devices
					// or if the expand sections setting is set.
					// The wide screen logic for determining whether to collapse sections initially
					// should be kept in sync with mobileoptions#initLocalStorageElements().
					this.toggle( $heading );
				}
			}
		} );
 
		/**
		 * Checks the existing hash and toggles open any section that contains the fragment.
		 *
		 * @method
		 */
		const checkHash = () => {
			// eslint-disable-next-line no-restricted-properties
			let hash = window.location.hash;
			Iif ( hash.indexOf( '#' ) === 0 ) {
				hash = hash.slice( 1 );
				// Per https://html.spec.whatwg.org/multipage/browsing-the-web.html#target-element
				// we try the raw fragment first, then the percent-decoded fragment.
				if ( !this.reveal( hash ) ) {
					const decodedHash = mw.util.percentDecodeFragment( hash );
					if ( decodedHash ) {
						this.reveal( decodedHash );
					}
				}
			}
		};
 
		/**
		 * Checks the value of wgInternalRedirectTargetUrl and sets the hash if present.
		 * checkHash() will reveal the collapsed section that contains it afterwards.
		 *
		 * @method
		 */
		function checkInternalRedirectAndHash() {
			const internalRedirect = mw.config.get( 'wgInternalRedirectTargetUrl' ),
				internalRedirectHash = internalRedirect ? internalRedirect.split( '#' )[1] : false;
 
			Iif ( internalRedirectHash ) {
				// eslint-disable-next-line no-restricted-properties
				window.location.hash = internalRedirectHash;
			}
		}
 
		checkInternalRedirectAndHash();
		checkHash();
 
		util.getWindow().on( 'hashchange', () => checkHash() );
	}
}
 
/**
 * Enables toggling via enter and space keys
 *
 * @param {Toggler} toggler instance.
 * @param {jQuery.Object} $heading
 * @ignore
 */
function enableKeyboardActions( toggler, $heading ) {
	$heading.on( 'keypress', ( ev ) => {
		Eif ( ev.which === 13 || ev.which === 32 ) {
			// Only handle keypresses on the "Enter" or "Space" keys
			toggler.toggle( $heading );
		}
	} ).find( 'a' ).on( 'keypress mouseup', ( ev ) => ev.stopPropagation() );
}
 
module.exports = Toggler;