-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathMultiInput.ts
More file actions
489 lines (405 loc) · 12.6 KB
/
MultiInput.ts
File metadata and controls
489 lines (405 loc) · 12.6 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
import type UI5Element from "@ui5/webcomponents-base/dist/UI5Element.js";
import property from "@ui5/webcomponents-base/dist/decorators/property.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 {
isShow,
isBackSpace,
isLeft,
isRight,
isRightCtrl,
isHome,
isEnd,
isDown,
} from "@ui5/webcomponents-base/dist/Keys.js";
import { isPhone } from "@ui5/webcomponents-base/dist/Device.js";
import type { ITabbable } from "@ui5/webcomponents-base/dist/delegate/ItemNavigation.js";
import type { IFormInputElement } from "@ui5/webcomponents-base/dist/features/InputElementsFormSupport.js";
import {
MULTIINPUT_ROLEDESCRIPTION_TEXT,
MULTIINPUT_VALUE_HELP_LABEL,
MULTIINPUT_VALUE_HELP,
FORM_MIXED_TEXTFIELD_REQUIRED,
MULTIINPUT_FILTER_BUTTON_LABEL,
} from "./generated/i18n/i18n-defaults.js";
import Input from "./Input.js";
import MultiInputTemplate from "./MultiInputTemplate.js";
import styles from "./generated/themes/MultiInput.css.js";
import type Token from "./Token.js";
import type Tokenizer from "./Tokenizer.js";
import { getTokensCountText } from "./Tokenizer.js";
import type { TokenizerTokenDeleteEventDetail } from "./Tokenizer.js";
import type {
InputSelectionChangeEventDetail as MultiInputSelectionChangeEventDetail,
} from "./Input.js";
import type { Slot } from "@ui5/webcomponents-base/dist/UI5Element.js";
interface IToken extends UI5Element, ITabbable {
text?: string;
readonly: boolean,
selected: boolean,
isTruncatable: boolean,
}
type MultiInputTokenDeleteEventDetail = {
tokens: Token[];
}
/**
* @class
* ### Overview
* A `ui5-multi-input` field allows the user to enter multiple values, which are displayed as `ui5-token`.
*
* User can choose interaction for creating tokens.
* Fiori Guidelines say that user should create tokens when:
*
* - Type a value in the input and press enter or focus out the input field (`change` event is fired)
* - Move between suggestion items (`selection-change` event is fired)
* - Clicking on a suggestion item (`selection-change` event is fired if the clicked item is different than the current value. Also `change` event is fired )
*
* ### ES6 Module Import
*
* `import "@ui5/webcomponents/dist/MultiInput.js";`
* @constructor
* @extends Input
* @since 1.0.0-rc.9
* @public
*/
@customElement({
tag: "ui5-multi-input",
renderer: jsxRenderer,
formAssociated: true,
template: MultiInputTemplate,
styles: [Input.styles, styles],
})
/**
* Fired when the value help icon is pressed
* and F4 or ALT/OPTION + ARROW_UP/ARROW_DOWN keyboard keys are used.
* @public
*/
@event("value-help-trigger", {
bubbles: true,
})
/**
* Fired when tokens are being deleted.
* @param {Array} tokens An array containing the deleted tokens.
* @public
*/
@event("token-delete", {
bubbles: true,
})
class MultiInput extends Input implements IFormInputElement {
eventDetails!: Input["eventDetails"] & {
"value-help-trigger": void,
"token-delete": MultiInputTokenDeleteEventDetail,
}
/**
* Determines whether a value help icon will be visualized in the end of the input.
* Pressing the icon will fire `value-help-trigger` event.
* @default false
* @public
*/
@property({ type: Boolean })
showValueHelpIcon = false;
/**
* Indicates whether the tokenizer has tokens
* @default false
* @private
*/
@property({ type: Boolean })
tokenizerAvailable = false;
/**
* 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.
* **Note:** When the component is used inside a form element,
* the value is sent as the first element in the form data, even if it's empty.
* @default undefined
* @public
*/
@property()
declare name?: string;
/**
* Indicates whether to show tokens in suggestions popover
* @default false
* @private
*/
@property({ type: Boolean })
_showTokensInSuggestions = false;
/**
* Tracks whether user has explicitly toggled the show tokens state
* @default false
* @private
*/
@property({ type: Boolean })
_userToggledShowTokens = false;
/**
* Defines the component tokens.
* @public
*/
@slot({ type: HTMLElement, individualSlots: true })
tokens!: Slot<IToken>;
_skipOpenSuggestions: boolean;
_valueHelpIconPressed: boolean;
get formValidityMessage() {
return MultiInput.i18nBundle.getText(FORM_MIXED_TEXTFIELD_REQUIRED);
}
get formValidity(): ValidityStateFlags {
const tokens = (this.tokens || []);
return { valueMissing: this.required && !this.value && !tokens.length };
}
get formFormattedValue(): FormData | string | null {
const tokens = (this.tokens || []);
if (tokens.length && this.name) {
const formData = new FormData();
formData.append(this.name, this.value);
for (let i = 0; i < tokens.length; i++) {
formData.append(this.name, (tokens[i].text || ""));
}
return formData;
}
return this.value;
}
constructor() {
super();
// Prevent suggestions' opening.
this._skipOpenSuggestions = false;
this._valueHelpIconPressed = false;
}
valueHelpPress() {
this.closeValueStatePopover();
this.fireDecoratorEvent("value-help-trigger");
}
tokenDelete(e: CustomEvent<TokenizerTokenDeleteEventDetail>) {
const deletedTokens = e.detail.tokens;
const selectedTokens = this.tokens.filter(token => token.selected);
const shouldFocusInput = this.tokens.length - 1 === 0 || this.tokens.length === selectedTokens.length;
if (this._readonly) {
return;
}
if (deletedTokens) {
this.fireDecoratorEvent("token-delete", { tokens: deletedTokens });
if (shouldFocusInput) {
this.focus();
}
}
}
valueHelpMouseDown(e: MouseEvent) {
e.preventDefault();
this.focus();
this.closeValueStatePopover();
this.tokenizer.open = false;
this._valueHelpIconPressed = true;
}
_tokenizerFocusOut(e: FocusEvent) {
if (!this.contains(e.relatedTarget as HTMLElement) && !this.shadowRoot!.contains(e.relatedTarget as HTMLElement)) {
this.tokenizer._tokens.forEach(token => { token.selected = false; });
}
}
valueHelpMouseUp() {
setTimeout(() => {
this._valueHelpIconPressed = false;
}, 0);
}
innerFocusIn() {
this.focused = true;
this.tokenizer._scrollToEndOnExpand = true;
this.tokenizer.expanded = true;
this.tokens.forEach(token => {
token.selected = false;
});
}
_showMoreItemsPress() {
this.tokenizer._scrollToEndOnExpand = true;
}
_onkeydown(e: KeyboardEvent) {
!this._isComposing && super._onkeydown(e);
const target = e.target as HTMLInputElement;
const isHomeInBeginning = isHome(e) && target.selectionStart === 0;
if (isHomeInBeginning) {
this._skipOpenSuggestions = true; // Prevent input focus when navigating through the tokens
return this._focusFirstToken(e);
}
if (isLeft(e)) {
this._skipOpenSuggestions = true;
return this._handleLeft(e);
}
if (isBackSpace(e)) {
this._skipOpenSuggestions = true;
return this._handleBackspace(e);
}
this._skipOpenSuggestions = false;
if (isShow(e)) {
this.valueHelpPress();
}
}
_onTokenizerKeydown(e: KeyboardEvent) {
const rightCtrl = isRightCtrl(e);
if (isRight(e) || isDown(e) || isEnd(e) || rightCtrl) {
e.preventDefault();
const lastTokenIndex = this.tokens.length - 1;
if (e.target === this.tokens[lastTokenIndex] && this.tokens[lastTokenIndex] === document.activeElement) {
setTimeout(() => {
this.focus();
}, 0);
}
}
}
_handleLeft(e: KeyboardEvent) {
const cursorPosition = this.getDomRef()!.querySelector(`input`)!.selectionStart;
const tokens = this.tokens;
const lastToken = tokens.length && tokens[tokens.length - 1];
// selectionStart property applies only to inputs of types text, search, URL, tel, and password
if (((cursorPosition === null && !this.value) || cursorPosition === 0) && lastToken) {
e.preventDefault();
lastToken.focus();
this.tokenizer._itemNav.setCurrentItem(lastToken);
}
}
_handleBackspace(e: KeyboardEvent) {
const tokens = this.tokens;
const lastToken = tokens.length && tokens[tokens.length - 1];
// Only move focus to the last token if the input is empty
if (!this.value && lastToken) {
e.preventDefault();
lastToken.focus();
this.tokenizer._itemNav.setCurrentItem(lastToken);
}
}
_focusFirstToken(e: KeyboardEvent) {
const tokens = this.tokens;
const firstToken = tokens.length && tokens[0];
if (firstToken) {
e.preventDefault();
firstToken.focus();
this.tokenizer._itemNav.setCurrentItem(firstToken);
}
}
_onfocusout(e: FocusEvent) {
super._onfocusout(e);
const relatedTarget = e.relatedTarget as HTMLElement;
const insideDOM = this.contains(relatedTarget);
const insideShadowDom = this.shadowRoot!.contains(relatedTarget);
if (!insideDOM && !insideShadowDom) {
this.tokenizer.expanded = false;
}
if (this.contains(relatedTarget) && relatedTarget.hasAttribute("ui5-token")) {
this.focused = false;
}
}
/**
* @override
*/
_onfocusin(e: FocusEvent) {
const inputDomRef = this.getInputDOMRef();
if (e.target === inputDomRef) {
super._onfocusin(e);
}
}
onBeforeRendering() {
super.onBeforeRendering();
this.style.setProperty("--_ui5-input-icons-count", `${this.iconsCount}`);
this.tokenizerAvailable = this.tokens && this.tokens.length > 0;
if (this.tokenizer) {
this.tokenizer.readonly = this.readonly;
// Set the CSS variable on the tokenizer element so it's available in the shadow DOM
this.tokenizer.style.setProperty("--_ui5-input-icons-count", `${this.iconsCount}`);
}
}
/**
* Override the _handlePickerAfterOpen method to handle token display based on device type
*/
_handlePickerAfterOpen() {
if (this.tokens.length > 0) {
// On mobile: show tokens by default (for filter dialog feature)
// On desktop: keep showing suggestions (default behavior)
if (isPhone()) {
this._showTokensInSuggestions = true;
}
this._userToggledShowTokens = false;
// Expand tokenizer to show all tokens and prevent cut-off
this.tokenizer._scrollToEndOnExpand = true;
this.tokenizer.expanded = true;
}
super._handlePickerAfterOpen();
}
onAfterRendering() {
super.onAfterRendering();
this.tokenizer.preventInitialFocus = true;
}
get iconsCount() {
return super.iconsCount + (this.showValueHelpIcon ? 1 : 0);
}
get tokenizer() {
return this.shadowRoot!.querySelector<Tokenizer>("[ui5-tokenizer]")!;
}
get tokenizerExpanded() {
return this.tokenizer && this.tokenizer.expanded;
}
get _tokensCountText() {
return getTokensCountText(this.tokens.length);
}
get _valueHelpText() {
return MultiInput.i18nBundle.getText(MULTIINPUT_VALUE_HELP);
}
get _filterButtonAccessibleName() {
return MultiInput.i18nBundle.getText(MULTIINPUT_FILTER_BUTTON_LABEL);
}
get _tokensCountTextId() {
return `hiddenText-nMore`;
}
get _valueHelpTextId() {
return this.showValueHelpIcon ? `hiddenText-value-help` : "";
}
/**
* Returns the placeholder value when there are no tokens.
* @protected
*/
get _placeholder() {
if (this.tokens.length) {
return "";
}
return this.placeholder;
}
get accInfo() {
const ariaDescribedBy = `${this._tokensCountTextId} ${this.suggestionsTextId} ${this.valueStateTextId} ${this._valueStateLinksShortcutsTextAccId} ${this._valueHelpTextId}`.trim();
return {
...super.accInfo,
"ariaRoledescription": this.ariaRoleDescription,
"ariaDescribedBy": ariaDescribedBy,
};
}
get valueHelpLabel() {
return MultiInput.i18nBundle.getText(MULTIINPUT_VALUE_HELP_LABEL);
}
get ariaRoleDescription() {
return MultiInput.i18nBundle.getText(MULTIINPUT_ROLEDESCRIPTION_TEXT);
}
get morePopoverOpener(): HTMLElement {
if (this.tokens.length === 1 && this.tokens[0].isTruncatable) {
return this.tokens[0];
}
return this;
}
get shouldDisplayOnlyValueStateMessage() {
return this.hasValueStateMessage && !this.readonly && !this.open && this.focused && !this.tokenizer.open;
}
/**
* Computes the effective state for showing tokens in suggestions.
* Returns false (show suggestions) by default, true only when explicitly set.
*/
get _effectiveShowTokensInSuggestions() {
// If no tokens exist, always show suggestions
if (this.tokens.length === 0) {
return false;
}
// Return the current state (will be true on mobile after picker opens, false otherwise)
return this._showTokensInSuggestions;
}
}
MultiInput.define();
export default MultiInput;
export type {
IToken,
MultiInputTokenDeleteEventDetail,
MultiInputSelectionChangeEventDetail,
};