-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathTextArea.ts
More file actions
736 lines (627 loc) · 17.8 KB
/
TextArea.ts
File metadata and controls
736 lines (627 loc) · 17.8 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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
import UI5Element from "@ui5/webcomponents-base/dist/UI5Element.js";
import type { Slot } from "@ui5/webcomponents-base/dist/UI5Element.js";
import property from "@ui5/webcomponents-base/dist/decorators/property.js";
import ValueState from "@ui5/webcomponents-base/dist/types/ValueState.js";
import slot from "@ui5/webcomponents-base/dist/decorators/slot-strict.js";
import event from "@ui5/webcomponents-base/dist/decorators/event-strict.js";
import customElement from "@ui5/webcomponents-base/dist/decorators/customElement.js";
import jsxRenderer from "@ui5/webcomponents-base/dist/renderer/JsxRenderer.js";
import ResizeHandler from "@ui5/webcomponents-base/dist/delegate/ResizeHandler.js";
import type { ResizeObserverCallback } from "@ui5/webcomponents-base/dist/delegate/ResizeHandler.js";
import {
getEffectiveAriaLabelText,
getAssociatedLabelForTexts,
getEffectiveAriaDescriptionText,
} from "@ui5/webcomponents-base/dist/util/AccessibilityTextsHelper.js";
import i18n from "@ui5/webcomponents-base/dist/decorators/i18n.js";
import type I18nBundle from "@ui5/webcomponents-base/dist/i18nBundle.js";
import { isEscape } from "@ui5/webcomponents-base/dist/Keys.js";
import type { IFormInputElement } from "@ui5/webcomponents-base/dist/features/InputElementsFormSupport.js";
import type Popover from "./Popover.js";
import type InputComposition from "./features/InputComposition.js";
import TextAreaTemplate from "./TextAreaTemplate.js";
import {
VALUE_STATE_SUCCESS,
VALUE_STATE_INFORMATION,
VALUE_STATE_ERROR,
VALUE_STATE_WARNING,
VALUE_STATE_TYPE_SUCCESS,
VALUE_STATE_TYPE_INFORMATION,
VALUE_STATE_TYPE_ERROR,
VALUE_STATE_TYPE_WARNING,
TEXTAREA_CHARACTERS_LEFT,
TEXTAREA_CHARACTERS_EXCEEDED,
FORM_TEXTFIELD_REQUIRED,
TEXTAREA_EXCEEDS_MAXLENGTH,
} from "./generated/i18n/i18n-defaults.js";
// Styles
import textareaStyles from "./generated/themes/TextArea.css.js";
import valueStateMessageStyles from "./generated/themes/ValueStateMessage.css.js";
type TokenizedText = Array<string>;
type IndexedTokenizedText = Array<{
text: string;
last: boolean;
}>;
type ExceededText = {
exceededText?: string;
leftCharactersCount?: number;
calcedMaxLength?: number;
};
type TextAreaInputEventDetail = {
escapePressed?: boolean;
};
/**
* @class
*
* ### Overview
*
* The `ui5-textarea` component is used to enter multiple rows of text.
*
* When empty, it can hold a placeholder similar to a `ui5-input`.
* You can define the rows of the `ui5-textarea` and also determine specific behavior when handling long texts.
*
* ### ES6 Module Import
*
* `import "@ui5/webcomponents/dist/TextArea.js";`
* @constructor
* @extends UI5Element
* @public
* @csspart textarea - Used to style the native textarea
*/
@customElement({
tag: "ui5-textarea",
formAssociated: true,
languageAware: true,
styles: [
textareaStyles,
valueStateMessageStyles,
],
renderer: jsxRenderer,
template: TextAreaTemplate,
})
/**
* Fired when the text has changed and the focus leaves the component.
* @public
*/
@event("change", {
bubbles: true,
})
/**
* Fired to make Angular two way data binding work properly.
* @private
*/
@event("value-changed", {
bubbles: true,
})
/**
* Fired when the value of the component changes at each keystroke or when
* something is pasted.
* @since 1.0.0-rc.5
* @param {boolean} escapePressed Indicates whether the Escape key was pressed, which triggers a revert to the previous value
* @public
*/
@event("input", {
bubbles: true,
cancelable: true,
})
/**
* Fired when some text has been selected.
*
* @since 1.23.0
* @public
*/
@event("select", {
bubbles: true,
})
/**
* Fired when textarea is scrolled.
*
* @since 1.23.0
* @public
*/
@event("scroll", {
bubbles: true,
})
class TextArea extends UI5Element implements IFormInputElement {
eventDetails!: {
"change": void;
"input": TextAreaInputEventDetail;
"select": void;
"scroll": void;
"value-changed": void;
}
/**
* Defines the value of the component.
* @formEvents change input
* @formProperty
* @default ""
* @public
*/
@property()
value = "";
/**
* Indicates whether the user can interact with the component or not.
*
* **Note:** A disabled component is completely noninteractive.
* @default false
* @public
*/
@property({ type: Boolean })
disabled = false;
/**
* Defines whether the component is read-only.
*
* **Note:** A read-only component is not editable,
* but still provides visual feedback upon user interaction.
* @default false
* @public
*/
@property({ type: Boolean })
readonly = false;
/**
* Defines whether the component is required.
* @default false
* @public
* @since 1.0.0-rc.3
*/
@property({ type: Boolean })
required = false;
/**
* Defines a short hint intended to aid the user with data entry when the component has no value.
* @default undefined
* @public
*/
@property()
placeholder?: string;
/**
* Defines the value state of the component.
*
* **Note:** If `maxlength` property is set,
* the component turns into "Critical" state once the characters exceeds the limit.
* In this case, only the "Negative" state is considered and can be applied.
* @default "None"
* @since 1.0.0-rc.7
* @public
*/
@property()
valueState: `${ValueState}` = "None";
/**
* Defines the number of visible text rows for the component.
*
* **Notes:**
*
* - If the `growing` property is enabled, this property defines the minimum rows to be displayed
* in the textarea.
* - The CSS `height` property wins over the `rows` property, if both are set.
* @default 0
* @public
*/
@property({ type: Number })
rows = 0;
/**
* Defines the maximum number of characters that the `value` can have.
* @default undefined
* @public
*/
@property({ type: Number })
maxlength?: number
/**
* Determines whether the characters exceeding the maximum allowed character count are visible
* in the component.
*
* If set to `false`, the user is not allowed to enter more characters than what is set in the
* `maxlength` property.
* If set to `true` the characters exceeding the `maxlength` value are selected on
* paste and the counter below the component displays their number.
* @default false
* @public
*/
@property({ type: Boolean })
showExceededText = false;
/**
* Enables the component to automatically grow and shrink dynamically with its content.
* @default false
* @public
*/
@property({ type: Boolean })
growing = false;
/**
* Defines the maximum number of rows that the component can grow.
* @default 0
* @public
*/
@property({ type: Number })
growingMaxRows = 0;
/**
* Determines the name by which the component will be identified upon submission in an HTML form.
*
* **Note:** This property is only applicable within the context of an HTML Form element.
* @default undefined
* @public
*/
@property()
name?: string;
/**
* Defines the accessible ARIA name of the component.
* @default undefined
* @public
* @since 1.0.0-rc.15
*/
@property()
accessibleName?: string;
/**
* Receives id(or many ids) of the elements that label the textarea.
* @default undefined
* @public
* @since 1.0.0-rc.15
*/
@property()
accessibleNameRef?: string;
/**
* Defines the accessible description of the component.
* @default undefined
* @public
* @since 2.16.0
*/
@property()
accessibleDescription?: string;
/**
* Receives id(or many ids) of the elements that describe the textarea.
* @default undefined
* @public
* @since 2.16.0
*/
@property()
accessibleDescriptionRef?: string;
/**
* @private
*/
@property({ type: Boolean })
focused = false;
/**
* @private
*/
@property({ type: Boolean })
exceeding = false;
/**
* @private
*/
@property({ type: Array, noAttribute: true })
_mirrorText: IndexedTokenizedText = [];
/**
* @private
*/
@property({ noAttribute: true })
_maxHeight?: string;
/**
* @private
*/
@property({ type: Number })
_width?: number;
/**
* Indicates whether IME composition is currently active
* @default false
* @private
*/
@property({ type: Boolean, noAttribute: true })
_isComposing = false;
/**
* Defines the value state message that will be displayed as pop up under the component.
* The value state message slot should contain only one root element.
*
* **Note:** If not specified, a default text (in the respective language) will be displayed.
*
* **Note:** The `valueStateMessage` would be displayed if the component has
* `valueState` of type `Information`, `Critical` or `Negative`.
* @since 1.0.0-rc.7
* @public
*/
@slot()
valueStateMessage!: Slot<HTMLElement>;
_fnOnResize: ResizeObserverCallback;
_firstRendering: boolean;
_openValueStateMsgPopover: boolean;
_exceededTextProps!: ExceededText;
_keyDown?: boolean;
previousValue: string;
valueStatePopover?: Popover;
_composition?: InputComposition;
@i18n("@ui5/webcomponents")
static i18nBundle: I18nBundle;
static composition: typeof InputComposition;
get formValidityMessage() {
if (this.formValidity.valueMissing) {
return TextArea.i18nBundle.getText(FORM_TEXTFIELD_REQUIRED);
}
if (this.formValidity.tooLong) {
return TextArea.i18nBundle.getText(TEXTAREA_EXCEEDS_MAXLENGTH, this.value.length - (this.maxlength ?? 0));
}
}
get formValidity(): ValidityStateFlags {
return {
valueMissing: this.required && !this.value,
tooLong: this.showExceededText && (this.value.length > (this.maxlength ?? 0)),
};
}
async formElementAnchor() {
return this.getFocusDomRefAsync();
}
get formFormattedValue(): FormData | string | null {
return this.value;
}
constructor() {
super();
this._firstRendering = true;
this._openValueStateMsgPopover = false;
this._fnOnResize = this._onResize.bind(this);
this.previousValue = "";
}
onEnterDOM() {
ResizeHandler.register(this, this._fnOnResize);
this._enableComposition();
}
onExitDOM() {
ResizeHandler.deregister(this, this._fnOnResize);
this._composition?.removeEventListeners();
}
onBeforeRendering() {
if (!this.value) {
// fallback to default value
this.value = "";
}
this._exceededTextProps = this._calcExceededText();
this._mirrorText = this._tokenizeText(this.value);
this.exceeding = !!this._exceededTextProps.leftCharactersCount && this._exceededTextProps.leftCharactersCount < 0;
this._setCSSParams();
}
onAfterRendering() {
const nativeTextArea = this.getInputDomRef();
if (this.rows === 1) {
nativeTextArea.setAttribute("rows", "1");
} else {
nativeTextArea.removeAttribute("rows");
}
this.toggleValueStateMessage(this.openValueStateMsgPopover);
this._firstRendering = false;
}
getInputDomRef() {
return this.getDomRef()!.querySelector<HTMLTextAreaElement>("textarea")!;
}
_onkeydown(e: KeyboardEvent) {
this._keyDown = true;
if (this._isComposing) {
return;
}
if (isEscape(e)) {
const nativeTextArea = this.getInputDomRef();
const prevented = !this.fireDecoratorEvent("input", {
escapePressed: true,
});
if (!prevented) {
this.value = this.previousValue;
nativeTextArea.value = this.value;
}
}
}
_onkeyup() {
this._keyDown = false;
}
_onfocusin() {
this.focused = true;
this._openValueStateMsgPopover = true;
this.previousValue = this.getInputDomRef().value;
}
_onfocusout(e: FocusEvent) {
const eTarget = e.relatedTarget as HTMLElement;
const focusedOutToValueStateMessage = eTarget && this.contains(eTarget);
this.focused = false;
if (!focusedOutToValueStateMessage) {
this._openValueStateMsgPopover = false;
}
}
_onchange() {
this.fireDecoratorEvent("change");
}
_onselect() {
this.fireDecoratorEvent("select");
}
_onscroll() {
this.fireDecoratorEvent("scroll");
}
_oninput(e: InputEvent) {
const nativeTextArea = this.getInputDomRef();
if (e.target === nativeTextArea) {
// stop the native event, as the semantic "input" would be fired.
e.stopImmediatePropagation();
}
this.value = nativeTextArea.value;
const valueLength = this.value.length;
if (e.inputType === "insertFromPaste" && this.maxlength && valueLength > this.maxlength) {
nativeTextArea.setSelectionRange(this.maxlength, valueLength);
}
this.fireDecoratorEvent("input");
// Angular two way data binding
this.fireDecoratorEvent("value-changed");
}
_onResize() {
if (this.displayValueStateMessagePopover) {
this._width = this.offsetWidth;
}
}
_setCSSParams() {
this.style.setProperty("--_textarea_rows", this.rows ? String(this.rows) : "2");
this.style.setProperty("--_textarea_growing_max_rows", String(this.growingMaxRows));
}
toggleValueStateMessage(toggle: boolean) {
if (toggle) {
this.openPopover();
} else {
this.closePopover();
}
}
openPopover() {
this.valueStatePopover = this._getPopover();
if (this.valueStatePopover) {
this.valueStatePopover.opener = this.shadowRoot!.querySelector<HTMLElement>(".ui5-textarea-root .ui5-textarea-wrapper")!;
this.valueStatePopover.open = true;
}
}
closePopover() {
this.valueStatePopover = this._getPopover();
if (this.valueStatePopover) {
this.valueStatePopover.open = false;
}
}
_getPopover() {
return this.shadowRoot!.querySelector<Popover>("[ui5-popover]")!;
}
_tokenizeText(value: string) {
const tokenizedText = value.replace(/</gm, "<")
.replace(/>/gm, ">")
.split("\n");
return this._mapTokenizedTextToObject(tokenizedText);
}
_mapTokenizedTextToObject(tokenizedText: TokenizedText) {
return tokenizedText.map((token, index) => {
return {
text: token,
last: index === (tokenizedText.length - 1),
};
});
}
_calcExceededText() {
let calcedMaxLength,
exceededText,
leftCharactersCount;
if (this.showExceededText) {
const maxLength = this.maxlength;
if (maxLength !== null && maxLength !== undefined) {
leftCharactersCount = maxLength - this.value.length;
if (leftCharactersCount >= 0) {
exceededText = TextArea.i18nBundle.getText(TEXTAREA_CHARACTERS_LEFT, leftCharactersCount);
} else {
exceededText = TextArea.i18nBundle.getText(TEXTAREA_CHARACTERS_EXCEEDED, Math.abs(leftCharactersCount));
}
}
} else {
calcedMaxLength = this.maxlength;
}
return {
exceededText, leftCharactersCount, calcedMaxLength,
};
}
_enableComposition() {
if (this._composition) {
return;
}
const setup = (FeatureClass: typeof InputComposition) => {
this._composition = new FeatureClass({
getInputEl: () => this.getInputDomRef(),
updateCompositionState: (isComposing: boolean) => {
this._isComposing = isComposing;
},
});
this._composition.addEventListeners();
};
if (TextArea.composition) {
setup(TextArea.composition);
} else {
import("./features/InputComposition.js").then(CompositionModule => {
TextArea.composition = CompositionModule.default;
setup(CompositionModule.default);
});
}
}
get classes() {
return {
root: {
"ui5-textarea-root": true,
},
valueStateMsg: {
"ui5-valuestatemessage-header": true,
"ui5-valuestatemessage--error": this.valueState === ValueState.Negative,
"ui5-valuestatemessage--warning": this.valueState === ValueState.Critical,
"ui5-valuestatemessage--information": this.valueState === ValueState.Information,
},
};
}
get tabIndex() {
return this.disabled ? -1 : 0;
}
get ariaLabelText() {
const effectiveAriaLabelText = getEffectiveAriaLabelText(this) || getAssociatedLabelForTexts(this);
if (this.showExceededText) {
if (effectiveAriaLabelText) {
return effectiveAriaLabelText.concat(" ", this._exceededTextProps.exceededText!);
}
return this._exceededTextProps.exceededText;
}
return effectiveAriaLabelText;
}
get ariaDescriptionText() {
return getEffectiveAriaDescriptionText(this);
}
get ariaDescriptionTextId() {
return this.ariaDescriptionText ? "accessibleDescription" : "";
}
get ariaDescribedBy() {
const ids = [
this.hasValueState ? `${this._id}-valueStateDesc` : "",
this.ariaDescriptionTextId,
].filter(Boolean).join(" ");
return ids || undefined;
}
get ariaValueStateHiddenText() {
if (!this.hasValueState) {
return;
}
if (this.valueState === ValueState.None) {
return;
}
if (this.hasCustomValueState) {
return `${this.valueStateTypeMappings[this.valueState]}`.concat(" ", this.valueStateMessage.map(el => el.textContent).join(" "));
}
return `${this.valueStateTypeMappings[this.valueState]} ${this.valueStateDefaultText}`;
}
get valueStateDefaultText() {
if (this.valueState !== ValueState.None) {
return this.valueStateTextMappings[this.valueState];
}
return "";
}
get _ariaInvalid() {
return this.valueState === ValueState.Negative ? "true" : undefined;
}
get openValueStateMsgPopover() {
return !this._firstRendering && this._openValueStateMsgPopover && this.displayValueStateMessagePopover;
}
get displayValueStateMessagePopover() {
return !this.readonly && (this.hasCustomValueState || this.hasValueState);
}
get hasCustomValueState() {
return !!this.valueStateMessage.length && this.hasValueState;
}
get hasValueState() {
return this.valueState === ValueState.Negative || this.valueState === ValueState.Critical || this.valueState === ValueState.Information;
}
get valueStateTextMappings() {
return {
"Positive": TextArea.i18nBundle.getText(VALUE_STATE_SUCCESS),
"Information": TextArea.i18nBundle.getText(VALUE_STATE_INFORMATION),
"Negative": TextArea.i18nBundle.getText(VALUE_STATE_ERROR),
"Critical": TextArea.i18nBundle.getText(VALUE_STATE_WARNING),
};
}
get valueStateTypeMappings() {
return {
"Positive": TextArea.i18nBundle.getText(VALUE_STATE_TYPE_SUCCESS),
"Information": TextArea.i18nBundle.getText(VALUE_STATE_TYPE_INFORMATION),
"Negative": TextArea.i18nBundle.getText(VALUE_STATE_TYPE_ERROR),
"Critical": TextArea.i18nBundle.getText(VALUE_STATE_TYPE_WARNING),
};
}
}
TextArea.define();
export default TextArea;
export { TextArea as BaseTextArea };
export type { TextAreaInputEventDetail };