forked from JanMiksovsky/quetzal-auto-size-text-box
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic-autosize-textarea.html
More file actions
374 lines (322 loc) · 12.7 KB
/
basic-autosize-textarea.html
File metadata and controls
374 lines (322 loc) · 12.7 KB
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
<!--
A text area that makes itself big enough to show its content.
This works by copying the text to an invisible element which will automatically
grow in size; the expanding copy will expand the container, which in turn
stretch the text area.
@element basic-autosize-textarea
@demo http://basic-web-components.github.io/basic-web-components/src/basic-autosize-textarea/?dom=shadow
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../basic-shared/basic-shared.html">
<dom-module id="basic-autosize-textarea">
<template>
<style>
:host {
display: block;
}
#autoSizeContainer {
position: relative;
}
/*
* Ensure both the text area and copy end up with the element's own font
* metrics, so that text will lay out the same in both of them.
*/
#textBox,
#copyContainer {
-moz-box-sizing: border-box;
box-sizing: border-box;
font-family: inherit;
font-size: inherit;
font-style: inherit;
font-weight: inherit;
line-height: inherit;
margin: 0;
}
#textBox {
height: 100%;
overflow: hidden;
position: absolute;
resize: none;
top: 0;
width: 100%;
@apply(--textarea);
}
#copyContainer {
visibility: hidden;
white-space: pre-wrap; /* So lines wrap */
word-wrap: break-word; /* So we break at word boundaries when possible */
}
#contentContainer {
display: none;
}
</style>
<!--
The invisible copyContainer contains an extraSpace element that ensures that,
even if the last line of the textarea is blank, there will be something in the
line that forces the text copy to grow by a line. This extra space is a thin
space, to reduce the amount by which the text copy will prematurely grow.
The copyContainer also contains an extraLine element exists to deal with the
fact that, if the user presses the Enter key down, the textarea's content will
move before the complete text is available. See notes at _keypress.
Lastly, we put the HTML content element into a separate container so we can
hide it. We need to have a content element somewhere in the template to
convince Polymer that we care about the content in the Shady DOM case --
without that content element, Shady DOM will conclude the element doesn't
need its light DOM content, and will throw it away.
-->
<div id="autoSizeContainer">
<textarea id="textBox" on-keypress="_keypress" placeholder="{{placeholder}}" value="{{value::input}}"></textarea>
<div id="copyContainer"><span id="textCopy"></span><span id="extraSpace"> </span><div id="extraLine"> </div></div>
</div>
<div id="contentContainer">
<content></content>
</div>
</template>
</dom-module>
<script>
/**
* Fires when the user types in the textarea.
*
* @event change
*/
Polymer({
is: 'basic-autosize-textarea',
properties: {
ariaLabel: {
type: String,
reflectToAttribute: true,
observer: 'ariaLabelChanged'
},
/**
* Determines the minimum number of rows shown. This is similar to the rows
* attribute on a standard textarea, but because this element can grow, is
* expressed as a minimum rather than a fixed number.
*
* @attribute minimumRows
* @type number
* @default 1
*/
minimumRows: {
type: Number,
reflectToAttribute: true,
value: 1,
observer: 'minimumRowsChanged'
},
/**
* A prompt shown when the field is empty to indicate what the user should enter.
*
* @attribute placeholder
* @type string
*/
placeholder: {
type: String,
reflectToAttribute: true,
value: ""
},
/**
* The text shown in the textarea.
*
* @attribute value
* @type string
*/
value: {
type: String,
notify: true,
observer: 'valueChanged'
}
},
/* Propagate the ARIA label to the inner textarea. */
ariaLabelChanged: function() {
// Not sure why, but using Polymer to bind the aria-label attribute of the
// inner input to the components ariaLabel property is insufficient. So we
// manually propagate label changes to the input.
this.$.textBox.setAttribute('aria-label', this.ariaLabel);
},
/**
* Resize the element such that the textarea can exactly contain its content.
* By default, this method is invoked whenever the text content changes.
*
* @method autoSize
*/
autoSize: function() {
// If we had speculatively added an extra line because of an Enter keypress,
// we can now hide the extra line.
this.$.extraLine.style.display = 'none';
// We resize by copying the textarea contents to the element itself; the
// text will then appear (via <content>) inside the invisible div. If
// we've set things up correctly, this new content should take up the same
// amount of room as the same text in the textarea. Updating the element's
// content adjusts the element's size, which in turn will make the textarea
// the correct height.
this.$.textCopy.textContent = this.value;
},
// Normally the value of the element is set and read through its value
// attribute. As a convenience, and to mirror standard textarea behavior,
// it is possible to set the content of the textarea by including text between
// the opening and closing tag. This works only in one direction: setting
// the tag content updates the textarea, but user edits in the textarea are
// not reflected in the tag content. We capture the value of the initial text content
// in order to set the value property during the create event.
// TODO: Normalize indentation in the text content. Users will often want to
// indent the markup so that it looks pretty. We should detect the indentation
// level and remove any indentation whitespace
// TODO: Consider using content innerHTML rather than plain text. The native
// textarea element will include HTML, not just the stripped text, as initial
// value property text.
attached: function() {
var text = this._getTextContent();
// If a value is provided as part of initialization, we will not overwrite
// it with content. The value property takes precedence. Do not set the value
// here unless necessary as it will establish a lineheight of zero if set
// to the empty string.
if (!this.value && text.length) {
this.value = this._unescapeHtml(text);
}
this._initializeWhenRendered();
},
behaviors: [
Basic.ContentChanged,
Basic.Generic
],
contentChanged: function() {
this.value = this._getTextContent();
},
valueChanged: function() {
this.autoSize();
this.dispatchEvent(new CustomEvent('value-changed'));
},
minimumRowsChanged: function() {
if (this._lineHeight) {
this._setMinimumHeight();
}
},
ready: function() {
this.$.textBox.addEventListener('change', function() {
// Raise our own change event (since change events aren't automatically
// retargetted).
this.dispatchEvent(new CustomEvent('change'));
}.bind(this));
},
get selectionEnd() {
return this.$.textBox.selectionEnd;
},
set selectionEnd(value) {
this.$.textBox.selectionEnd = value;
},
get selectionStart() {
return this.$.textBox.selectionStart;
},
set selectionStart(value) {
this.$.textBox.selectionStart = value;
},
_getTextContent: function() {
var text = this.flattenTextContent;
// Trim the text.
// This is non-standard textarea behavior. A standard textarea will trim the
// first character if it's a newline, but that's it. However, authors will
// want to be able to place the opening and closing tags on their own lines.
// So it seems more helpful to trim whitespace on either side.
text = text.trim();
return text;
},
// Set up once this component has been rendered.
//
// On Chrome (as of 10/23/14) at least, if an instance if this component is
// added dynamically, its attached handler may trigger before its been
// rendered. That would cause our layout calculations to be incorrect.
//
_initializeWhenRendered: function() {
// If the component has been rendered, our height should be nonzero.
if (this.clientHeight === 0) {
// Not rendered yet: wait a bit before trying again.
setTimeout(function() {
this._initializeWhenRendered();
}.bind(this), 10);
return;
}
// If we reach this point, the component's elements should by styled.
// For auto-sizing to work, we need the text copy to have the same border,
// padding, and other relevant characteristics as the original text area.
// Since those aspects are affected by CSS, we have to wait until the
// element is in the document before we can update the text copy.
var textBoxStyle = getComputedStyle(this.$.textBox);
var copyContainerStyle = this.$.copyContainer.style;
copyContainerStyle.borderBottomStyle = textBoxStyle.borderBottomStyle;
copyContainerStyle.borderBottomWidth = textBoxStyle.borderBottomWidth;
copyContainerStyle.borderLeftStyle = textBoxStyle.borderLeftStyle;
copyContainerStyle.borderLeftWidth = textBoxStyle.borderLeftWidth;
copyContainerStyle.borderRightStyle = textBoxStyle.borderRightStyle;
copyContainerStyle.borderRightWidth = textBoxStyle.borderRightWidth;
copyContainerStyle.borderTopStyle = textBoxStyle.borderTopStyle;
copyContainerStyle.borderTopWidth = textBoxStyle.borderTopWidth;
copyContainerStyle.paddingBottom = textBoxStyle.paddingBottom;
copyContainerStyle.paddingLeft = textBoxStyle.paddingLeft;
copyContainerStyle.paddingRight = textBoxStyle.paddingRight;
copyContainerStyle.paddingTop = textBoxStyle.paddingTop;
// Use the extraLine member to gauge the expected height of a single line of
// text. We can't use lineHeight, because that can be reported as "normal",
// and we want to know the actual pixel height.
this.$.extraLine.style.display = 'inherit';
this._lineHeight = this.$.extraLine.clientHeight;
// Now that we know the line height, we can hide the extra line.
this.$.extraLine.style.display = 'none';
// Use the line height in conjunction with minimumRows to establish the
// overall minimum height of the component.
this._setMinimumHeight();
},
// Speculatively add a line to our copy of the text. We're not sure what the
// exact effect of typing this character will be, and at this point it's not
// reflected yet in the textarea's content. We speculate that it will add a
// line to the text and size accordingly. (One other possibility is that the
// user's replacing a selected chunk of text with a newline.) In any event,
// once we get the keyup or change event, we'll make any final adjustments.
//
// TODO: If the user holds down the Enter key, we can get a bunch of keypress
// events before we get keyup. This causes flicker. Instead of supporting only
// a single extra speculative line, we should grow the speculative element to
// contain the number of Enter keypresses we've received.
_keypress: function(event) {
if (event.keyCode === 13 /* Enter */) {
this.$.extraLine.style.display = 'inherit';
}
},
// Setting the minimumRows attribute translates into setting the minimum
// height on the text copy container.
_setMinimumHeight: function() {
var copyContainer = this.$.copyContainer;
var outerHeight = copyContainer.getBoundingClientRect().height;
var style = getComputedStyle(copyContainer);
var paddingTop = parseFloat(style.paddingTop);
var paddingBottom = parseFloat(style.paddingBottom);
var innerHeight = copyContainer.clientHeight - paddingTop - paddingBottom;
var bordersPlusPadding = outerHeight - innerHeight;
var minHeight = (this.minimumRows * this._lineHeight) + bordersPlusPadding;
minHeight = Math.ceil(minHeight);
copyContainer.style.minHeight = minHeight + 'px';
},
_unescapeHtml: function(html) {
return html
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, ">")
.replace(/"/g, '\"')
.replace(/'/g, '\'');
}
});
/*
* The following comments document API members provided by mixins. Ideally these
* docs will eventually be pulled from the mixin source files, but for now are
* copied here by hand.
*/
/**
* True if the component would like to receive generic styling.
*
* This property is true by default — set it to false to turn off all
* generic styles. This makes it easier to apply custom styling; you won't
* have to explicitly override styling you don't want.
*
* @property generic
* @type Boolean
* @default true
*/
</script>