Merge "FauxRequest: don’t override getValues()"
[lhc/web/wiklou.git] / resources / src / mediawiki.htmlform.checker.js
1 ( function () {
2
3 // FIXME: mw.htmlform.Element also sets this to empty object
4 mw.htmlform = {};
5
6 /**
7 * @class mw.htmlform.Checker
8 */
9
10 /**
11 * A helper class to add validation to non-OOUI HtmlForm fields.
12 *
13 * @constructor
14 * @param {jQuery} $element Form field generated by HTMLForm
15 * @param {Function} validator Validation callback
16 * @param {string} validator.value Value of the form field to be validated
17 * @param {jQuery.Promise} validator.return The promise should be resolved
18 * with an object with two properties: Boolean 'valid' to indicate success
19 * or failure of validation, and an array 'messages' to be passed to
20 * setErrors() on failure.
21 */
22 mw.htmlform.Checker = function ( $element, validator ) {
23 this.validator = validator;
24 this.$element = $element;
25
26 this.$errorBox = $element.next( '.error' );
27 if ( !this.$errorBox.length ) {
28 this.$errorBox = $( '<span>' );
29 this.$errorBox.hide();
30 $element.after( this.$errorBox );
31 }
32
33 this.currentValue = this.$element.val();
34 };
35
36 /**
37 * Attach validation events to the form element
38 *
39 * @param {jQuery} [$extraElements] Additional elements to listen for change
40 * events on.
41 * @return {mw.htmlform.Checker}
42 * @chainable
43 */
44 mw.htmlform.Checker.prototype.attach = function ( $extraElements ) {
45 var $e,
46 // We need to hook to all of these events to be sure we are
47 // notified of all changes to the value of an <input type=text>
48 // field.
49 events = 'keyup keydown change mouseup cut paste focus blur';
50
51 $e = this.$element;
52 if ( $extraElements ) {
53 $e = $e.add( $extraElements );
54 }
55 $e.on( events, mw.util.debounce( 1000, this.validate.bind( this ) ) );
56
57 return this;
58 };
59
60 /**
61 * Validate the form element
62 * @return {jQuery.Promise}
63 */
64 mw.htmlform.Checker.prototype.validate = function () {
65 var currentRequestInternal,
66 that = this,
67 value = this.$element.val();
68
69 // Abort any pending requests.
70 if ( this.currentRequest && this.currentRequest.abort ) {
71 this.currentRequest.abort();
72 }
73
74 if ( value === '' ) {
75 this.currentValue = value;
76 this.setErrors( true, [] );
77 return;
78 }
79
80 this.currentRequest = currentRequestInternal = this.validator( value )
81 .done( function ( info ) {
82 var forceReplacement = value !== that.currentValue;
83
84 // Another request was fired in the meantime, the result we got here is no longer current.
85 // This shouldn't happen as we abort pending requests, but you never know.
86 if ( that.currentRequest !== currentRequestInternal ) {
87 return;
88 }
89 // If we're here, then the current request has finished, avoid calling .abort() needlessly.
90 that.currentRequest = undefined;
91
92 that.currentValue = value;
93
94 that.setErrors( info.valid, info.messages, forceReplacement );
95 } ).fail( function () {
96 that.currentValue = null;
97 that.setErrors( true, [] );
98 } );
99
100 return currentRequestInternal;
101 };
102
103 /**
104 * Display errors associated with the form element
105 * @param {boolean} valid Whether the input is still valid regardless of the messages
106 * @param {Array} errors Error messages. Each error message will be appended to a
107 * `<span>` or `<li>`, as with jQuery.append().
108 * @param {boolean} [forceReplacement] Set true to force a visual replacement even
109 * if the errors are the same. Ignored if errors are empty.
110 * @return {mw.htmlform.Checker}
111 * @chainable
112 */
113 mw.htmlform.Checker.prototype.setErrors = function ( valid, errors, forceReplacement ) {
114 var $oldErrorBox, tagName, showFunc, text, replace,
115 $errorBox = this.$errorBox;
116
117 if ( errors.length === 0 ) {
118 // FIXME: Use CSS transition
119 // eslint-disable-next-line no-jquery/no-slide
120 $errorBox.slideUp( function () {
121 $errorBox
122 .removeAttr( 'class' )
123 .empty();
124 } );
125 } else {
126 // Match behavior of HTMLFormField::formatErrors(), <span> or <ul>
127 // depending on the count.
128 tagName = errors.length === 1 ? 'span' : 'ul';
129
130 // We have to animate the replacement if we're changing the tag. We
131 // also want to if told to by the caller (i.e. to make it visually
132 // obvious that the changed field value gives the same error) or if
133 // the error text changes (because it makes more sense than
134 // changing the text with no animation).
135 replace = (
136 forceReplacement || $errorBox.length > 1 ||
137 $errorBox[ 0 ].tagName.toLowerCase() !== tagName
138 );
139 if ( !replace ) {
140 text = $( '<' + tagName + '>' )
141 .append( errors.map( function ( e ) {
142 return errors.length === 1 ? e : $( '<li>' ).append( e );
143 } ) );
144 if ( text.text() !== $errorBox.text() ) {
145 replace = true;
146 }
147 }
148
149 $oldErrorBox = $errorBox;
150 if ( replace ) {
151 this.$errorBox = $errorBox = $( '<' + tagName + '>' );
152 $errorBox.hide();
153 $oldErrorBox.after( this.$errorBox );
154 }
155
156 showFunc = function () {
157 if ( $oldErrorBox !== $errorBox ) {
158 $oldErrorBox
159 .removeAttr( 'class' )
160 .detach();
161 }
162 // FIXME: Use CSS transition
163 // eslint-disable-next-line no-jquery/no-slide
164 $errorBox
165 .attr( 'class', valid ? 'warning' : 'error' )
166 .empty()
167 .append( errors.map( function ( e ) {
168 return errors.length === 1 ? e : $( '<li>' ).append( e );
169 } ) )
170 .slideDown();
171 };
172 if (
173 $oldErrorBox !== $errorBox &&
174 // eslint-disable-next-line no-jquery/no-class-state
175 ( $oldErrorBox.hasClass( 'error' ) || $oldErrorBox.hasClass( 'warning' ) )
176 ) {
177 // eslint-disable-next-line no-jquery/no-slide
178 $oldErrorBox.slideUp( showFunc );
179 } else {
180 showFunc();
181 }
182 }
183
184 return this;
185 };
186
187 }() );