aboutsummaryrefslogtreecommitdiffstats
path: root/resources/src/mediawiki.htmlform/cloner.js
blob: 3ead1916efac2f138152c32275395fb686232000 (plain) (blame)
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
/*
 * HTMLForm enhancements:
 * Add/remove cloner clones without having to resubmit the form.
 */

let cloneCounter = 0;

/**
 * Appends a new row with fields to the cloner.
 *
 * @ignore
 * @param {jQuery} $createButton
 */
function appendToCloner( $createButton ) {
	const $ul = $createButton.prev( 'ul.mw-htmlform-cloner-ul' ),

		cloneRegex = new RegExp( mw.util.escapeRegExp( $ul.data( 'uniqueId' ) ), 'g' ),
		// Assume the ids that need to be made unique will start with 'ooui-php-'. See T274533
		inputIdRegex = new RegExp( /(ooui-php-[0-9]*)/, 'gm' );

	++cloneCounter;
	const html = $ul.data( 'template' )
		.replace( cloneRegex, 'clone' + cloneCounter )
		.replace( inputIdRegex, '$1-clone' + cloneCounter );

	const $li = $( '<li>' )
		.addClass( 'mw-htmlform-cloner-li' )
		.html( html )
		.appendTo( $ul );

	mw.hook( 'htmlform.enhance' ).fire( $li );
}

mw.hook( 'htmlform.enhance' ).add( ( $root ) => {
	const $deleteElement = $root.find( '.mw-htmlform-cloner-delete-button' ),
		$createElement = $root.find( '.mw-htmlform-cloner-create-button' );

	$deleteElement.each( function () {
		const $element = $( this );

		// eslint-disable-next-line no-jquery/no-class-state
		if ( $element.hasClass( 'oo-ui-widget' ) ) {
			const deleteButton = OO.ui.infuse( $element );
			deleteButton.on( 'click', () => {
				deleteButton.$element.closest( 'li.mw-htmlform-cloner-li' ).remove();
			} );
		} else {
			// eslint-disable-next-line no-jquery/no-sizzle
			$element.filter( ':input' ).on( 'click', function ( e ) {
				e.preventDefault();
				$( this ).closest( 'li.mw-htmlform-cloner-li' ).remove();
			} );
		}
	} );

	$createElement.each( function () {
		const $element = $( this );

		// eslint-disable-next-line no-jquery/no-class-state
		if ( $element.hasClass( 'oo-ui-widget' ) ) {
			const createButton = OO.ui.infuse( $element );
			createButton.on( 'click', () => {
				appendToCloner( createButton.$element );
			} );
		} else {
			// eslint-disable-next-line no-jquery/no-sizzle
			$element.filter( ':input' ).on( 'click', function ( e ) {
				e.preventDefault();
				appendToCloner( $( this ) );
			} );
		}
	} );
} );