-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathinput-textarea.js
358 lines (323 loc) · 10.5 KB
/
input-textarea.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
import '../tooltip/tooltip.js';
import { css, html, LitElement } from 'lit';
import { classMap } from 'lit/directives/class-map.js';
import { FocusMixin } from '../../mixins/focus/focus-mixin.js';
import { formatNumber } from '@brightspace-ui/intl/lib/number.js';
import { FormElementMixin } from '../form/form-element-mixin.js';
import { getUniqueId } from '../../helpers/uniqueId.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { InputInlineHelpMixin } from './input-inline-help.js';
import { inputLabelStyles } from './input-label-styles.js';
import { inputStyles } from './input-styles.js';
import { LabelledMixin } from '../../mixins/labelled/labelled-mixin.js';
import { offscreenStyles } from '../offscreen/offscreen.js';
import { RtlMixin } from '../../mixins/rtl/rtl-mixin.js';
import { SkeletonMixin } from '../skeleton/skeleton-mixin.js';
import { styleMap } from 'lit/directives/style-map.js';
/**
* A wrapper around the native `<textarea>` element that provides auto-grow and validation behaviours intended for inputting unformatted multi-line text.
* @slot inline-help - Help text that will appear below the input. Use this only when other helpful cues are not sufficient, such as a carefully-worded label.
* @fires change - Dispatched when an alteration to the value is committed (typically after focus is lost) by the user
* @fires input - Dispatched immediately after changes by the user
*/
class InputTextArea extends InputInlineHelpMixin(FocusMixin(LabelledMixin(FormElementMixin(SkeletonMixin(RtlMixin(LitElement)))))) {
static get properties() {
return {
/**
* ADVANCED: Indicates that the input value is invalid
* @type {string}
*/
ariaInvalid: { type: String, attribute: 'aria-invalid' },
/**
* Additional information communicated in the aria-describedby on the input
* @type {string}
*/
description: { type: String, reflect: true },
/**
* Disables the input
* @type {boolean}
*/
disabled: { type: Boolean, reflect: true },
/**
* Hides the label visually (moves it to the input's "aria-label" attribute)
* @type {boolean}
*/
labelHidden: { type: Boolean, attribute: 'label-hidden' },
/**
* Imposes an upper character limit
* @type {number}
*/
maxlength: { type: Number },
/**
* Maximum number of rows before scrolling
* @type {number}
*/
maxRows: { type: Number, attribute: 'max-rows' },
/**
* Imposes a lower character limit
* @type {number}
*/
minlength: { type: Number },
/**
* Hides the border
* @type {boolean}
*/
noBorder: { type: Boolean, attribute: 'no-border' },
/**
* Removes default left/right padding
* @type {boolean}
*/
noPadding: { type: Boolean, attribute: 'no-padding' },
/**
* @ignore
*/
placeholder: { type: String },
/**
* Indicates that a value is required
* @type {boolean}
*/
required: { type: Boolean, reflect: true },
/**
* Minimum number of rows
* @type {number}
*/
rows: { type: Number },
/**
* Value of the input
* @type {string}
*/
value: { type: String },
_hovered: { state: true }
};
}
static get styles() {
return [ super.styles, inputStyles, inputLabelStyles, offscreenStyles, css`
:host {
display: block;
}
:host([hidden]) {
display: none;
}
.d2l-input-label {
display: inline-block;
vertical-align: bottom;
}
.d2l-input-textarea-container {
height: 100%;
max-width: 100%;
position: relative;
}
textarea.d2l-input {
height: 100%;
left: 0;
line-height: 1rem;
position: absolute;
resize: none;
top: 0;
}
:host([no-border]) textarea.d2l-input {
border-color: transparent;
box-shadow: none;
}
/* mirror dimensions must match textarea - match border + padding */
.d2l-input-textarea-mirror {
line-height: 1rem;
overflow: hidden;
overflow-wrap: anywhere; /* prevent width from growing */
padding-bottom: 0.5rem;
padding-top: 0.5rem;
visibility: hidden;
}
:host([no-padding]) .d2l-input {
padding-left: 0;
padding-right: 0;
}
:host([no-border][no-padding]) textarea.d2l-input:hover,
:host([no-border][no-padding]) textarea.d2l-input:focus {
border-left-width: 1px;
border-right-width: 1px;
}
.d2l-input-textarea-mirror[aria-invalid="true"] {
padding-right: calc(18px + 0.8rem);
}
:host([dir="rtl"]) .d2l-input-textarea-mirror[aria-invalid="true"] {
padding-left: calc(18px + 0.8rem);
padding-right: 0.75rem;
}
`];
}
constructor() {
super();
this.disabled = false;
this.labelHidden = false;
this.maxRows = 11;
this.rows = 5;
this.required = false;
this.value = '';
this._descriptionId = getUniqueId();
this._hovered = false;
this._inlineHelpId = getUniqueId();
this._textareaId = getUniqueId();
}
static get focusElementSelector() {
return 'textarea';
}
/** @ignore */
get textarea() {
// temporary until consumers are updated
return this.shadowRoot && this.shadowRoot.querySelector('textarea');
}
/** @ignore */
get validationMessage() {
if (this.validity.tooShort) {
return this.localize('components.form-element.input.text.tooShort', { label: this.label, minlength: formatNumber(this.minlength) });
}
return super.validationMessage;
}
/** @ignore */
get validity() {
const elem = this.shadowRoot && this.shadowRoot.querySelector('textarea');
if (elem && !elem.validity.valid) {
return elem.validity;
}
return super.validity;
}
connectedCallback() {
super.connectedCallback();
if (this.hasAttribute('aria-label')) {
this.labelRequired = false;
}
this.addEventListener('mouseover', this._handleMouseEnter);
this.addEventListener('mouseout', this._handleMouseLeave);
this.addEventListener('click', this._handleClick);
}
disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener('mouseover', this._handleMouseEnter);
this.removeEventListener('mouseout', this._handleMouseLeave);
this.removeEventListener('click', this._handleClick);
}
render() {
// convert \n to <br> for html mirror
const lines = ((this.value && this.value !== '') ? this.value.split('\n')
: (this.placeholder ? this.placeholder.split('\n') : []));
const ariaRequired = this.required ? 'true' : undefined;
const ariaInvalid = this.invalid ? 'true' : this.ariaInvalid;
const offscreenContainer = this.description ? html`<div class="d2l-offscreen" id="${this._descriptionId}">${this.description}</div>` : null;
const disabled = this.disabled || this.skeleton;
const ariaDescribedByIds = `${this.description ? this._descriptionId : ''} ${this._hasInlineHelp ? this._inlineHelpId : ''}`.trim();
const mirrorStyles = {};
// lines + padding + border; if < 1 it will fallback to min single and/or max infinite
if (this.rows > 0) mirrorStyles.minHeight = `calc(${this.rows + 1}rem + 2px)`;
if (this.maxRows > 0) mirrorStyles.maxHeight = `calc(${this.maxRows + 1}rem + 2px)`;
const inputClasses = {
'd2l-input': true,
'd2l-input-focus': !this.disabled && this._hovered
};
const textarea = html`
<div class="d2l-input-textarea-container d2l-skeletize">
<div class="d2l-input d2l-input-textarea-mirror" style="${styleMap(mirrorStyles)}" aria-invalid="${ifDefined(ariaInvalid)}">
${lines.map(line => html`${line}<br />`)}
</div>
<textarea
aria-describedby="${ifDefined(ariaDescribedByIds.length > 0 ? ariaDescribedByIds : undefined)}"
aria-invalid="${ifDefined(ariaInvalid)}"
aria-label="${ifDefined(this._getAriaLabel())}"
aria-required="${ifDefined(ariaRequired)}"
@blur="${this._handleBlur}"
@change="${this._handleChange}"
class=${classMap(inputClasses)}
?disabled="${disabled}"
id="${this._textareaId}"
@input="${this._handleInput}"
@invalid="${this._handleInvalid}"
maxlength="${ifDefined(this.maxlength)}"
minlength="${ifDefined(this.minlength)}"
placeholder="${ifDefined(this.placeholder)}"
?required="${this.required}"
.value="${this.value}">${this.value}</textarea>
${this.validationError ? html`<d2l-tooltip for=${this._textareaId} state="error" align="start">${this.validationError}</d2l-tooltip>` : null}
</div>
${this._renderInlineHelp(this._inlineHelpId)}
${offscreenContainer}
`;
if (this.label && !this.labelHidden && !this.labelledBy) {
return html`
<label class="d2l-input-label d2l-skeletize" for="${this._textareaId}">${this.label}</label>
${textarea}`;
}
return textarea;
}
updated(changedProperties) {
super.updated(changedProperties);
changedProperties.forEach((oldVal, prop) => {
if (prop === 'value') {
this.setValidity({ tooShort: this.minlength && this.value.length > 0 && this.value.length < this.minlength });
this.requestValidate(false);
this.setFormValue(this.value);
this._prevValue = (oldVal === undefined) ? '' : oldVal;
} else if (prop === 'validationError') {
if (oldVal && this.validationError) {
const tooltip = this.shadowRoot.querySelector('d2l-tooltip');
tooltip.updatePosition();
}
}
});
}
async select() {
const elem = this.shadowRoot && this.shadowRoot.querySelector('textarea');
if (elem) {
elem.select();
} else {
await this.updateComplete;
this.select();
}
}
_getAriaLabel() {
if (this.label && (this.labelHidden || this.labelledBy)) {
return this.label;
}
// check aria-label for backwards compatibility in order to replace old Polymer impl
if (this.hasAttribute('aria-label')) {
return this.getAttribute('aria-label');
}
return undefined;
}
async _handleBlur(e) {
this.requestValidate(true);
/**
* This is needed only for Legacy-Edge since the _handleChange function is NOT
* triggered, therefore we have to detect the blur and handle it ourselves.
*/
const browserType = window.navigator.userAgent;
if (this._prevValue !== e.target.value && (browserType.indexOf('Edge') > -1)) {
this._handleChange();
}
}
_handleChange() {
// change events aren't composed, so we need to re-dispatch
this.dispatchEvent(new CustomEvent(
'change',
{ bubbles: true, composed: false }
));
}
_handleClick(e) {
const input = this.shadowRoot && this.shadowRoot.querySelector('textarea');
if (!input || e.composedPath()[0] !== this) return;
input.focus();
}
_handleInput(e) {
this.value = e.target.value;
return true;
}
_handleInvalid(e) {
e.preventDefault();
}
_handleMouseEnter() {
this._hovered = true;
}
_handleMouseLeave() {
this._hovered = false;
}
}
customElements.define('d2l-input-textarea', InputTextArea);