-
Notifications
You must be signed in to change notification settings - Fork 8
/
jquery.inputautoexpand.js
470 lines (409 loc) · 11.3 KB
/
jquery.inputautoexpand.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
( function () {
'use strict';
/**
* Rulers used for measuring the input content.
* @property {jQuery}
* @ignore
*/
var $rulerX, $rulerY;
/**
* Initializes the rulers used for measuring the input content.
* @ignore
*/
function initRulers() {
if ( !$rulerX ) {
$rulerX = $( '<div/>' )
.css( {
width: 'auto',
whiteSpace: 'nowrap',
position: 'absolute',
top: '-9999px',
left: '-9999px',
visibility: 'hidden',
display: 'none'
} );
}
if ( !$rulerX.closest( 'body' ).length ) {
$rulerX.appendTo( 'body' );
}
if ( !$rulerY ) {
$rulerY = $( '<textarea style="min-height: 0!important; height: 0!important;"/>' )
.attr( 'tabindex', '-1' )
.css( {
position: 'absolute',
top: '-9999px',
left: '-9999px',
right: 'auto',
bottom: 'auto'
} );
}
if ( !$rulerY.closest( 'body' ).length ) {
$rulerY.appendTo( 'body' );
}
}
/**
* Destroys the rulers.
* @ignore
*/
function destroyRulers() {
if ( $rulerX ) {
$rulerX.remove();
$rulerX = null;
}
if ( $rulerY ) {
$rulerY.remove();
$rulerY.remove();
}
}
/**
* Copy styles that affect spacing from one element to another.
* @ignore
*
* @param {jQuery} $from
* @param {jQuery} $to
*/
function copySpaceAffectingStyles( $from, $to ) {
var stylesToCopy = [
'fontFamily',
'fontSize',
'fontWeight',
'fontStyle',
'letterSpacing',
'lineHeight',
'textTransform',
'wordSpacing',
'textIndent',
'overflowY',
'wordWrap'
];
for ( var i = 0; i < stylesToCopy.length; i++ ) {
$to.css( stylesToCopy[i], $from.css( stylesToCopy[i] ) );
}
// styles not being influenced by copying styles
$to.css( {
overflow: 'hidden',
overflowY: 'hidden'
} );
}
/**
* Escapes HTML entities.
* @ignore
*
* @param {string} text
* @return {string}
*/
function escaped( text ) {
return $( '<div/>' ).text( text ).html();
}
/**
* Makes input or textarea elements automatically expand/contract their size according to their
* input value while typing. Vertical resizing will of course work for textareas only.
* The input/textarea element the plugin is initialized on needs to be in the DOM in order to be
* able to correctly detect the element's native width.
* Compatibility: IE >= 8
*
* Based on:
*
* - autoGrowInput plugin by James Padolsey (http://jsbin.com/ahaxe)
*
* - Autosize plugin by Jack Moore (licence: MIT) (http://www.jacklmoore.com/autosize)
*
* @member jQuery.fn
* @method inputautoexpand
* @uses jQuery.AutoExpandInput
* @license GNU GPL v2+
* @author H. Snater < mediawiki at snater.com >
*
* @param {Object} [options={}]
* @param {boolean} [options.expandWidth=true]
* Whether to horizontally expand/contract the input element.
* @param {boolean} [options.expandHeight=false]
* Whether to vertically expand/contract the input element.
* @param {number} [options.maxWidth=1000]
* Maximum width the input element may stretch.
* @param {number} [options.minWidth]
* Minimum width. If undefined, the space required by the input element's placeholder text
* will be determined automatically (taking placeholder into account).
* @param {number} [options.maxHeight]
* Maximum height the input element may stretch. If undefined, the height is not constrained
* to a maximum.
* @param {number} [options.minHeight]
* Minimum height. If undefined, the height is not constrained to a minimum.
* @param {number} [options.comfortZone]
* White space behind the input text to prevent resize jitters while typing. If undefined, an
* appropriate amount of space will be calculated automatically.
* @param {boolean} [options.suppressNewLine=false]
* Whether to suppress new-line characters.
* @param {string} [options.eventNamespace='inputautoexpand']
* Namespace used for the events the plugin attaches handlers to.
*/
$.fn.inputautoexpand = function( options ) {
if ( !options ) {
options = {};
}
// Inject default options for missing ones:
var fullOptions = $.extend( {
expandWidth: true,
expandHeight: false,
maxWidth: 1000,
minWidth: undefined,
maxHeight: undefined,
minHeight: undefined,
comfortZone: undefined,
suppressNewLine: false,
eventNamespace: 'inputautoexpand'
}, options );
// Expand input fields:
this.filter( 'input:text, textarea' ).each( function() {
var instance = $.data( this, 'inputautoexpand' );
if ( instance ) {
// AutoExpand initialized already, update options only (will also expand):
if ( options ) {
instance.options( options );
}
instance.expand();
} else {
// Initialize new auto expand:
$.data( this, 'inputautoexpand', new $.AutoExpandInput( this, fullOptions ) );
}
} );
return this;
};
/**
* Manages expanding input elements.
* @class jQuery.AutoExpandInput
* @uses jQuery.event.special.eachchange
* @private
* @license GNU GPL v2+
* @author H. Snater < mediawiki at snater.com >
*
* @constructor
*
* @param {HTMLElement} element
* @param {Object} options
*/
$.AutoExpandInput = function( element, options ) {
this.$input = $( element );
this._options = options;
var self = this;
this._nodeName = element.nodeName;
this.$input.on( 'eachchange', function( event, oldValue ) {
if ( self._options.suppressNewLine ) {
self.$input.val( self.$input.val().replace( /\r?\n/g, '' ) );
}
self.expand();
} );
initRulers();
this.expand();
// Do not show any resize handle for manual resizing:
this.$input.css( 'resize', 'none' );
$( window )
.off( '.' + this._options.eventNamespace )
.on( 'resize.' + this._options.eventNamespace, function( event ) {
$( 'input:text, textarea' ).each( function() {
var instance = $.data( this, 'inputautoexpand' );
if ( instance ) {
instance.expand();
}
} );
} );
};
$.extend( $.AutoExpandInput.prototype, {
/**
* The input element the auto-expand mechanism is initialized on.
* @property {jQuery}
* @private
* @readonly
*/
$input: null,
/**
* Options.
* @property {Object}
* @private
*/
_options: null,
/**
* Caching the previous input to simply abort expanding when it did not change.
* @property {string}
* @private
*/
_previousVal: null,
/**
* The input element's node name.
* @property {string}
* @private
*/
_nodeName: null,
/**
* Sets the input box's width to fit the box's content.
*
* @param {boolean} [force] Whether to evaluate height/width regardless of the element's text
* having changed.
*/
expand: function( force ) {
var newVal = this.$input.val();
if ( !force && newVal === this._previousVal ) {
return;
}
if ( this._options.expandWidth ) {
this._expandWidth();
}
if ( this._options.expandHeight && this._nodeName === 'TEXTAREA' ) {
this._expandHeight();
}
this._previousVal = newVal;
},
/**
* Expands/Contracts the input element's width.
* @private
*/
_expandWidth: function() {
copySpaceAffectingStyles( this.$input, $rulerX );
var minWidth = this._getMinWidth(),
maxWidth = this._options.maxWidth - ( this.$input.outerWidth() - this.$input.width() ),
comfortZone = this._getComfortZone();
// Since the minimum width may have been calculated dynamically using the placeholder,
// the minimum width may be greater than the maximum width.
if ( minWidth > maxWidth ) {
minWidth = maxWidth;
}
var valWidth = this._getWidthFor( this.$input.val() ),
newWidth = valWidth + comfortZone;
if ( newWidth < minWidth ) {
newWidth = minWidth;
} else if ( newWidth >= maxWidth ) {
newWidth = maxWidth;
}
this.$input.width( newWidth );
},
/**
* Expands/Contracts the input element's height.
* @private
*/
_expandHeight: function() {
copySpaceAffectingStyles( this.$input, $rulerY );
var newHeight = this._getHeightFor( this.$input.val() ),
input = this.$input.get( 0 ),
minHeight = this._options.minHeight || 0,// keeps at least one single line
maxHeight = this._options.maxHeight;
if ( maxHeight && newHeight > maxHeight ) {
input.style.height = maxHeight + 'px';
input.style.overflow = 'scroll';
} else {
if ( minHeight && newHeight < minHeight ) {
input.style.height = minHeight + 'px';
} else {
input.style.height = ( !isNaN( newHeight ) ? newHeight : 0 ) + 'px';
}
input.style.overflow = 'hidden';
}
},
/**
* Calculates the width which would be required for the input field if the given text was
* inserted. This does not consider the comfort zone given in the options and doesn't check
* for min/max width restraints.
* @private
*
* @param {string} text
* @return {number}
*/
_getWidthFor: function( text ) {
$rulerX.html( escaped( text ) );
return Math.ceil( $rulerX.width() );
},
/**
* Returns the minimum width the input element may have assigned.
* @private
*
* @return {number}
*/
_getMinWidth: function() {
if ( this._options.minWidth ) {
return this._options.minWidth;
}
// If there is no static minimum width, the placeholder is used to detect the minimum width
// Since the placeholder may change, its width is calculated always.
if ( !this.$input.attr( 'placeholder' ) ) {
return 0;
}
// Don't need comfort zone in this case, just some sane space:
return this._getWidthFor( this.$input.attr( 'placeholder' ) + '0' );
},
/**
* Calculates the height the given text would require to not show any scrollbar within the input
* element.
* @private
*
* @param {string} text
* @return {number}
*/
_getHeightFor: function( text ) {
if ( text === '' ) {
text = ' ';
}
var ruler = $rulerY.get( 0 );
ruler.value = text;
// Update the width in case the original textarea width has changed:
var width = this._options.maxWidth;
if ( !this._options.expandWidth || this.$input.width() > this._options.maxWidth ) {
width = Math.ceil( this.$input.width() ) - 1;
}
// Catch miscalculation:
if ( width < 0 ) {
width = 0;
}
ruler.style.width = width + 'px';
// Set a very high value for scrollTop to be sure the mirror is scrolled all the way to the
// bottom.
ruler.scrollTop = 9e4;
return ruler.scrollTop + $rulerY.outerHeight();
},
/**
* Returns the width to add to the input element to prevent jitters when resizing while typing.
* @private
*
* @return {number}
*/
_getComfortZone: function() {
return ( this._options.comfortZone )
? this._options.comfortZone
// IE does not recognize space characters, using 2ch CSS units instead:
: this._getWidthFor( '00' );
},
/**
* Sets the plugin's options or gets the options when no parameter is passed in.
*
* @param {Object} [options]
* @return {*|undefined}
*
* @throws {Error} when trying to set eventNamespace option which should only be set on
* initialization.
*/
options: function( options ) {
if ( !options ) {
return this._options;
}
if ( options.eventNamespace ) {
throw new Error( 'Cannot alter eventNamespace after initialization.' );
}
$.extend( this._options, options );
},
/**
* Destroys the plugin instance.
*/
destroy: function() {
$.removeData( this.$input.get( 0 ), 'inputautoexpand' );
var hasRemainingInstances = false;
$( 'input' ).each( function() {
if ( $.data( this, 'inputautoexpand' ) ) {
hasRemainingInstances = true;
return false;
}
} );
if ( !hasRemainingInstances ) {
$( 'window' ).off( this._options.eventNamespace );
destroyRulers();
}
}
} );
}() );