Debian Codegraph @

resources/src/mediawiki.htmlform/multiselect.js

raw symbols SCIP
1 /*
2 * HTMLForm enhancements:
3 * Convert multiselect fields from checkboxes to Chosen selector when requested.
4 */
5
6 function convertCheckboxesWidgetToTags( fieldLayout ) {
7 const checkboxesWidget = fieldLayout.fieldWidget;
8 const checkboxesOptions = checkboxesWidget.checkboxMultiselectWidget.getItems();
9 const menuTagOptions = checkboxesOptions.map( ( option ) => new OO.ui.MenuOptionWidget( {
10 data: option.getData(),
11 label: option.getLabel(),
12 disabled: option.disabled // Don't take the state of parent elements into account.
13 } ) );
14 const fieldData = checkboxesWidget.data || {};
15 const menuTagWidget = new OO.ui.MenuTagMultiselectWidget( {
16 $overlay: true,
17 menu: {
18 items: menuTagOptions
19 },
20 disabled: checkboxesWidget.isDisabled(),
21 placeholder: fieldData.placeholder || ''
22 } );
23 menuTagWidget.setValue( checkboxesWidget.getValue() );
24
25 menuTagOptions.forEach( ( option ) => {
26 if ( option.disabled ) {
27 const tagItem = menuTagWidget.findItemFromData( option.getData() );
28 // When this disabled option is selected by default.
29 if ( tagItem ) {
30 tagItem.setFixed( true );
31 }
32 }
33 } );
34
35 // Data from TagMultiselectWidget will not be submitted with the form, so keep the original
36 // CheckboxMultiselectInputWidget up-to-date.
37 menuTagWidget.on( 'change', () => {
38 checkboxesWidget.setValue( menuTagWidget.getValue() );
39 } );
40 // Synchronize the disable state for submission, and set the proper state of the label.
41 menuTagWidget.on( 'disable', ( isDisabled ) => {
42 checkboxesWidget.setDisabled( isDisabled );
43 } );
44 // Change the connected fieldWidget to the new one, so other scripts can infuse the layout
45 // and make changes to this widget.
46 fieldLayout.fieldWidget = menuTagWidget;
47
48 // Hide original widget and add new one in its place.
49 checkboxesWidget.toggle( false );
50 checkboxesWidget.$element.after( menuTagWidget.$element );
51 }
52
53 mw.hook( 'htmlform.enhance' ).add( ( $root ) => {
54 const $dropdowns = $root.find( '.mw-htmlform-dropdown:not(.oo-ui-widget)' );
55 if ( $dropdowns.length ) {
56 $dropdowns.each( function () {
57 const $el = $( this );
58 if ( $el.is( '[data-ooui]' ) ) {
59 // Avoid kicks in multiple times and causing a mess
60 if ( $el.find( '.oo-ui-menuTagMultiselectWidget' ).length ) {
61 return;
62 }
63 // Load 'oojs-ui-widgets' for TagMultiselectWidget
64 const modules = [ 'mediawiki.htmlform.ooui', 'oojs-ui-widgets' ];
65 const data = $el.data( 'mw-modules' );
66 if ( data ) {
67 // We can trust this value, 'data-mw-*' attributes are banned from user content in Sanitizer
68 const extraModules = data.split( ',' );
69 modules.push( ...extraModules );
70 }
71 mw.loader.using( modules, () => {
72 convertCheckboxesWidgetToTags( OO.ui.FieldLayout.static.infuse( $el ) );
73 } );
74 }
75 } );
76 }
77 } );