Merge "resources: Add caching for faster runs and offline use"
[lhc/web/wiklou.git] / resources / src / mediawiki.widgets.visibleLengthLimit / mediawiki.widgets.visibleLengthLimit.js
1 ( function () {
2
3 var byteLength = require( 'mediawiki.String' ).byteLength,
4 codePointLength = require( 'mediawiki.String' ).codePointLength;
5
6 /**
7 * @class mw.widgets
8 */
9
10 /**
11 * Add a visible byte limit label to a TextInputWidget.
12 *
13 * Uses jQuery#byteLimit to enforce the limit.
14 *
15 * @param {OO.ui.TextInputWidget} textInputWidget Text input widget
16 * @param {number} [limit] Byte limit, defaults to $input's maxlength
17 * @param {Function} [filterFunction] Function to call on the string before assessing the length.
18 */
19 mw.widgets.visibleByteLimit = function ( textInputWidget, limit, filterFunction ) {
20 limit = limit || +textInputWidget.$input.attr( 'maxlength' );
21 if ( !filterFunction || typeof filterFunction !== 'function' ) {
22 filterFunction = undefined;
23 }
24
25 function updateCount() {
26 var value = textInputWidget.getValue(),
27 remaining;
28 if ( filterFunction ) {
29 value = filterFunction( value );
30 }
31 remaining = limit - byteLength( value );
32 if ( remaining > 99 ) {
33 remaining = '';
34 } else {
35 remaining = mw.language.convertNumber( remaining );
36 }
37 textInputWidget.setLabel( remaining );
38 }
39 textInputWidget.on( 'change', updateCount );
40 // Initialise value
41 updateCount();
42
43 // Actually enforce limit
44 textInputWidget.$input.byteLimit( limit, filterFunction );
45 };
46
47 /**
48 * Add a visible codepoint (character) limit label to a TextInputWidget.
49 *
50 * Uses jQuery#codePointLimit to enforce the limit.
51 *
52 * @param {OO.ui.TextInputWidget} textInputWidget Text input widget
53 * @param {number} [limit] Code point limit, defaults to $input's maxlength
54 * @param {Function} [filterFunction] Function to call on the string before assessing the length.
55 */
56 mw.widgets.visibleCodePointLimit = function ( textInputWidget, limit, filterFunction ) {
57 limit = limit || +textInputWidget.$input.attr( 'maxlength' );
58 if ( !filterFunction || typeof filterFunction !== 'function' ) {
59 filterFunction = undefined;
60 }
61
62 function updateCount() {
63 var value = textInputWidget.getValue(),
64 remaining;
65 if ( filterFunction ) {
66 value = filterFunction( value );
67 }
68 remaining = limit - codePointLength( value );
69 if ( remaining > 99 ) {
70 remaining = '';
71 } else {
72 remaining = mw.language.convertNumber( remaining );
73 }
74 textInputWidget.setLabel( remaining );
75 }
76 textInputWidget.on( 'change', updateCount );
77 // Initialise value
78 updateCount();
79
80 // Actually enforce limit
81 textInputWidget.$input.codePointLimit( limit, filterFunction );
82 };
83
84 }() );