Debian Codegraph @

skins/Vector/resources/skins.vector.clientPreferences/clientPreferences.js

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /**
2 * @typedef {Object} ClientPreference
3 * @property {string[]} options that are valid for this client preference
4 * @property {string} preferenceKey for registered users.
5 * @property {string} betaMessage whether to show a notice indicating this feature is in beta.
6 * @property {string} [type] defaults to radio. Supported: radio, switch
7 * @property {Function} [callback] callback executed after a client preference has been modified.
8 */
9
10 /**
11 * @typedef {Object} UserPreferencesApi
12 * @property {Function} saveOptions
13 */
14 /**
15 * @typedef {Object} PreferenceOption
16 * @property {string} label
17 * @property {string} value
18 */
19
20 /**
21 * Get the list of client preferences that are active on the page, including hidden.
22 *
23 * @return {string[]} of active client preferences
24 */
25 function getClientPreferences() {
26 return Array.from( document.documentElement.classList ).filter(
27 ( className ) => className.match( /-clientpref-/ )
28 ).map( ( className ) => className.split( '-clientpref-' )[ 0 ] );
29 }
30
31 /**
32 * Check if the feature is excluded from the current page.
33 *
34 * @param {string} featureName
35 * @return {boolean}
36 */
37 function isFeatureExcluded( featureName ) {
38 return document.documentElement.classList.contains( featureName + '-clientpref--excluded' );
39 }
40
41 /**
42 * Get the list of client preferences that are active on the page and not hidden.
43 *
44 * @param {Record<string,ClientPreference>} config
45 * @return {string[]} of user facing client preferences
46 */
47 function getVisibleClientPreferences( config ) {
48 const active = getClientPreferences();
49 // Order should be based on key in config.json
50 return Object.keys( config ).filter( ( key ) => active.indexOf( key ) > -1 );
51 }
52
53 /**
54 * @param {string} featureName
55 * @param {string} value
56 * @param {Record<string,ClientPreference>} config
57 * @param {UserPreferencesApi} [userPreferences]
58 */
59 function toggleDocClassAndSave( featureName, value, config, userPreferences ) {
60 const pref = config[ featureName ];
61 const callback = pref.callback || ( () => {} );
62 if ( mw.user.isNamed() ) {
63 // FIXME: Ideally this would be done in mw.user.clientprefs API.
64 // mw.user.clientPrefs.get is marked as being only stable for anonymous and temporary users.
65 // So instead we have to keep track of all the different possible values and remove them
66 // before adding the new class.
67 config[ featureName ].options.forEach( ( possibleValue ) => {
68 document.documentElement.classList.remove( `${ featureName }-clientpref-${ possibleValue }` );
69 } );
70 document.documentElement.classList.add( `${ featureName }-clientpref-${ value }` );
71 // Client preferences often change the layout of the page significantly, so emit
72 // a window resize event for other apps that need to update (T374092).
73 window.dispatchEvent( new Event( 'resize' ) );
74 // Ideally this should be taken care of via a single core helper function.
75 mw.util.debounce( () => {
76 userPreferences = userPreferences || new mw.Api();
77 userPreferences.saveOptions( { [ pref.preferenceKey ]: value } ).then( () => {
78 callback();
79 } );
80 }, 100 )();
81 // END FIXME.
82 } else {
83 // This case is much simpler, the API transparently takes care of classes as well as storage
84 mw.user.clientPrefs.set( featureName, value );
85 callback();
86 }
87 }
88
89 /**
90 * @param {string} featureName
91 * @param {string} value
92 * @return {string}
93 */
94 const getInputId = ( featureName, value ) => `skin-client-pref-${ featureName }-value-${ value }`;
95
96 /**
97 * @param {string} type
98 * @param {string} featureName
99 * @param {string} value
100 * @return {HTMLInputElement}
101 */
102 function makeInputElement( type, featureName, value ) {
103 const input = document.createElement( 'input' );
104 const name = `skin-client-pref-${ featureName }-group`;
105 const id = getInputId( featureName, value );
106 input.name = name;
107 input.id = id;
108 input.type = type;
109 if ( type === 'checkbox' ) {
110 input.checked = value === '1';
111 } else {
112 input.value = value;
113 }
114 input.setAttribute( 'data-event-name', id );
115 return input;
116 }
117
118 /**
119 * @param {string} featureName
120 * @param {string} value
121 * @return {HTMLLabelElement}
122 */
123 function makeLabelElement( featureName, value ) {
124 const label = document.createElement( 'label' );
125 // eslint-disable-next-line mediawiki/msg-doc
126 label.textContent = mw.msg( `${ featureName }-${ value }-label` );
127 label.setAttribute( 'for', getInputId( featureName, value ) );
128 return label;
129 }
130
131 /**
132 * Create an element that informs users that a feature is not functional
133 * on a given page. This message is hidden by default and made visible in
134 * CSS if a specific exclusion class exists.
135 *
136 * @param {string} featureName
137 * @return {HTMLElement}
138 */
139 function makeExclusionNotice( featureName ) {
140 const p = document.createElement( 'p' );
141 // eslint-disable-next-line mediawiki/msg-doc
142 const noticeMessage = mw.message( `${ featureName }-exclusion-notice` );
143 p.classList.add( 'exclusion-notice', `${ featureName }-exclusion-notice` );
144 p.textContent = noticeMessage.text();
145 return p;
146 }
147
148 /**
149 * @return {HTMLElement}
150 */
151 function makeBetaInfoTag() {
152 const infoTag = document.createElement( 'span' );
153 // custom style to avoid moving heading bottom border.
154 const infoTagText = document.createElement( 'span' );
155 infoTagText.textContent = mw.message( 'vector-night-mode-beta-tag' ).text();
156 infoTag.appendChild( infoTagText );
157 return infoTag;
158 }
159
160 /**
161 * @param {Element} parent
162 * @param {string} featureName
163 * @param {string} value
164 * @param {string} currentValue
165 * @param {Record<string,ClientPreference>} config
166 * @param {UserPreferencesApi} userPreferences
167 */
168 function appendRadioToggle( parent, featureName, value, currentValue, config, userPreferences ) {
169 const input = makeInputElement( 'radio', featureName, value );
170 input.classList.add( 'cdx-radio__input' );
171 if ( currentValue === value ) {
172 input.checked = true;
173 }
174
175 if ( isFeatureExcluded( featureName ) ) {
176 input.disabled = true;
177 }
178
179 const icon = document.createElement( 'span' );
180 icon.classList.add( 'cdx-radio__icon' );
181 const label = makeLabelElement( featureName, value );
182 label.classList.add( 'cdx-radio__label' );
183 const container = document.createElement( 'div' );
184 container.classList.add( 'cdx-radio' );
185 container.appendChild( input );
186 container.appendChild( icon );
187 container.appendChild( label );
188 parent.appendChild( container );
189 input.addEventListener( 'change', () => {
190 toggleDocClassAndSave( featureName, value, config, userPreferences );
191 } );
192 }
193
194 /**
195 * @param {HTMLElement} betaMessageElement
196 */
197 function makeFeedbackLink( betaMessageElement ) {
198 if ( !mw.msg( 'vector-night-mode-issue-reporting-notice-url' ) ) {
199 return;
200 }
201 const pageWikiLink = `[https://${ window.location.hostname + mw.util.getUrl( mw.config.get( 'wgPageName' ) ) } ${ mw.config.get( 'wgTitle' ) }]`;
202 const preloadTitle = mw.message( 'vector-night-mode-issue-reporting-preload-title', pageWikiLink ).text();
203 const link = mw.msg( 'vector-night-mode-issue-reporting-notice-url', window.location.host, preloadTitle );
204 const linkLabel = mw.message( 'vector-night-mode-issue-reporting-link-label' ).text();
205 const anchor = document.createElement( 'a' );
206 anchor.setAttribute( 'href', link );
207 anchor.setAttribute( 'target', '_blank' );
208 anchor.setAttribute( 'title', mw.msg( 'vector-night-mode-issue-reporting-notice-tooltip' ) );
209 anchor.textContent = linkLabel;
210
211 /**
212 * Shows the success message after clicking the beta feedback link.
213 * Note: event.stopPropagation(); is required to show the success message
214 * without closing the Appearance menu when it's in a dropdown.
215 *
216 * @param {Event} event
217 */
218 const showSuccessFeedback = function ( event ) {
219 event.stopPropagation();
220 const icon = document.createElement( 'span' );
221 icon.classList.add( 'vector-icon', 'vector-icon--heart' );
222 anchor.textContent = mw.msg( 'vector-night-mode-issue-reporting-link-notification' );
223 anchor.classList.add( 'skin-theme-beta-notice-success' );
224 anchor.prepend( icon );
225 anchor.removeEventListener( 'click', showSuccessFeedback );
226 };
227 anchor.addEventListener( 'click', ( event ) => showSuccessFeedback( event ) );
228 betaMessageElement.appendChild( anchor );
229 }
230
231 /**
232 * @param {Element} form
233 * @param {string} featureName
234 * @param {HTMLElement} labelElement
235 * @param {string} currentValue
236 * @param {Record<string,ClientPreference>} config
237 * @param {UserPreferencesApi} userPreferences
238 */
239 function appendToggleSwitch(
240 form, featureName, labelElement, currentValue, config, userPreferences
241 ) {
242 const input = makeInputElement( 'checkbox', featureName, currentValue );
243 input.classList.add( 'cdx-toggle-switch__input' );
244 const switcher = document.createElement( 'span' );
245 switcher.classList.add( 'cdx-toggle-switch__switch' );
246 const grip = document.createElement( 'span' );
247 grip.classList.add( 'cdx-toggle-switch__switch__grip' );
248 switcher.appendChild( grip );
249 const label = labelElement || makeLabelElement( featureName, currentValue );
250 label.classList.add( 'cdx-toggle-switch__label' );
251 const toggleSwitch = document.createElement( 'span' );
252 toggleSwitch.classList.add( 'cdx-toggle-switch' );
253 toggleSwitch.appendChild( input );
254 toggleSwitch.appendChild( switcher );
255 toggleSwitch.appendChild( label );
256 input.addEventListener( 'change', () => {
257 toggleDocClassAndSave( featureName, input.checked ? '1' : '0', config, userPreferences );
258 } );
259 form.appendChild( toggleSwitch );
260 }
261
262 /**
263 * @param {string} className
264 * @return {Element}
265 */
266 function createRow( className ) {
267 const row = document.createElement( 'div' );
268 row.setAttribute( 'class', className );
269 return row;
270 }
271
272 /**
273 * Get the label for the feature.
274 *
275 * @param {string} featureName
276 * @return {MwMessage}
277 */
278 // eslint-disable-next-line mediawiki/msg-doc
279 const getFeatureLabelMsg = ( featureName ) => mw.message( `${ featureName }-name` );
280
281 /**
282 * adds a toggle button
283 *
284 * @param {string} featureName
285 * @param {Record<string,ClientPreference>} config
286 * @param {UserPreferencesApi} userPreferences
287 * @return {Element|null}
288 */
289 function makeControl( featureName, config, userPreferences ) {
290 const pref = config[ featureName ];
291 const isExcluded = isFeatureExcluded( featureName );
292
293 if ( !pref ) {
294 return null;
295 }
296 const currentValue = mw.user.clientPrefs.get( featureName );
297 // The client preference was invalid. This shouldn't happen unless a gadget
298 // or script has modified the documentElement or client preference is excluded.
299 if ( typeof currentValue === 'boolean' && !isExcluded ) {
300 return null;
301 }
302 const row = createRow( '' );
303 const form = document.createElement( 'form' );
304 const type = pref.type || 'radio';
305 switch ( type ) {
306 case 'radio':
307 pref.options.forEach( ( value ) => {
308 appendRadioToggle(
309 form, featureName, value, String( currentValue ), config, userPreferences
310 );
311 } );
312 break;
313 case 'switch': {
314 const labelElement = document.createElement( 'label' );
315 labelElement.textContent = getFeatureLabelMsg( featureName ).text();
316 appendToggleSwitch(
317 form, featureName, labelElement, String( currentValue ), config, userPreferences
318 );
319 break;
320 } default:
321 throw new Error( 'Unknown client preference! Only switch or radio are supported.' );
322 }
323 row.appendChild( form );
324
325 if ( isExcluded ) {
326 const exclusionNotice = makeExclusionNotice( featureName );
327 row.appendChild( exclusionNotice );
328 }
329 return row;
330 }
331
332 /**
333 * @param {Element} parent
334 * @param {string} featureName
335 * @param {Record<string,ClientPreference>} config
336 * @param {UserPreferencesApi} userPreferences
337 */
338 function makeClientPreference( parent, featureName, config, userPreferences ) {
339 const labelMsg = getFeatureLabelMsg( featureName );
340 // If the user is not debugging messages and no language exists,
341 // exit as its a hidden client preference.
342 if ( !labelMsg.exists() && mw.config.get( 'wgUserLanguage' ) !== 'qqx' ) {
343 return;
344 } else {
345 const id = `skin-client-prefs-${ featureName }`;
346 // @ts-ignore TODO: upstream patch URL
347 const portlet = mw.util.addPortlet( id, labelMsg.text() );
348
349 if ( config[ featureName ].betaMessage ) {
350 const betaInfoTag = makeBetaInfoTag();
351 if ( !portlet.querySelector( '.vector-menu-heading span' ) ) {
352 portlet.querySelector( '.vector-menu-heading' ).textContent += ' ';
353 portlet.querySelector( '.vector-menu-heading' ).appendChild( betaInfoTag );
354 }
355 }
356
357 const labelElement = portlet.querySelector( 'label' );
358
359 // Add additional description for mobile
360 // eslint-disable-next-line mediawiki/msg-doc
361 const descriptionMsg = mw.message( `${ featureName }-description` );
362 if ( descriptionMsg.exists() ) {
363 const desc = document.createElement( 'span' );
364 desc.classList.add( 'skin-client-pref-description' );
365 desc.textContent = descriptionMsg.text();
366 if ( labelElement && labelElement.parentNode ) {
367 labelElement.appendChild( desc );
368 }
369 }
370
371 // Add exclusion notice for desktop
372 // eslint-disable-next-line mediawiki/msg-doc
373 const exclusionNoticeMsg = mw.message( `${ featureName }-exclusion-notice` );
374 if ( exclusionNoticeMsg.exists() ) {
375 const content = portlet.querySelector( '.vector-menu-content' );
376 const notice = document.createElement( 'span' );
377 notice.classList.add( 'skin-client-pref-exclusion-notice' );
378 notice.textContent = exclusionNoticeMsg.text();
379 if ( content ) {
380 content.appendChild( notice );
381 }
382 }
383
384 parent.appendChild( portlet );
385 const row = makeControl( featureName, config, userPreferences );
386 if ( row ) {
387 const tmp = mw.util.addPortletLink( id, '', '' );
388 // create a dummy link
389 if ( tmp ) {
390 const link = tmp.querySelector( 'a' );
391 if ( link ) {
392 link.replaceWith( row );
393 }
394 }
395
396 if ( config[ featureName ].betaMessage && !isFeatureExcluded( featureName ) ) {
397 const betaMessageElement = document.createElement( 'span' );
398 betaMessageElement.id = `${ featureName }-beta-notice`;
399 // per requirements: only logged in users can report errors (T372754)
400 if ( !mw.user.isAnon() ) {
401 makeFeedbackLink( betaMessageElement );
402 }
403 row.appendChild( betaMessageElement );
404 }
405 }
406 }
407 }
408
409 /**
410 * Fills the client side preference dropdown with controls.
411 *
412 * @param {string} selector of element to fill with client preferences
413 * @param {Record<string,ClientPreference>} config
414 * @param {UserPreferencesApi} [userPreferences]
415 * @return {Promise<Node>}
416 */
417 function render( selector, config, userPreferences ) {
418 const node = document.querySelector( selector );
419 if ( !node ) {
420 return Promise.reject();
421 }
422 return new Promise( ( resolve ) => {
423 getVisibleClientPreferences( config ).forEach( ( pref ) => {
424 userPreferences = userPreferences || new mw.Api();
425 makeClientPreference( node, pref, config, userPreferences );
426 } );
427 mw.requestIdleCallback( () => {
428 resolve( node );
429 } );
430 } );
431 }
432
433 /**
434 * @param {string} clickSelector what to click
435 * @param {string} renderSelector where to render
436 * @param {Record<string,ClientPreference>} config
437 * @param {UserPreferencesApi} [userPreferences]
438 */
439 function bind( clickSelector, renderSelector, config, userPreferences ) {
440 let enhanced = false;
441 const chk = /** @type {HTMLInputElement} */ (
442 document.querySelector( clickSelector )
443 );
444 if ( !chk ) {
445 return;
446 }
447 if ( !userPreferences ) {
448 userPreferences = new mw.Api();
449 }
450 if ( chk.checked ) {
451 render( renderSelector, config, userPreferences );
452 enhanced = true;
453 } else {
454 chk.addEventListener( 'input', () => {
455 if ( enhanced ) {
456 return;
457 }
458 render( renderSelector, config, userPreferences );
459 enhanced = true;
460 } );
461 }
462 }
463 module.exports = {
464 bind,
465 toggleDocClassAndSave,
466 render
467 };