-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselectMany.ts
789 lines (724 loc) · 27.2 KB
/
selectMany.ts
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
import animate, { isAnimEnabled } from "../helpers/animate";
import isOverlap from "../helpers/isOverlap";
import { parseMsTime } from "../helpers/styleHelpers";
import { onEvent } from "../indexHelpers";
import WUPPopupElement from "../popup/popupElement";
import { WUPcssIcon, WUPcssScrollSmall } from "../styles";
import { MenuOpenCases } from "./baseCombo";
import { SetValueReasons } from "./baseControl";
import WUPSelectControl from "./select";
const tagName = "wup-selectmany";
declare global {
namespace WUP.SelectMany {
interface EventMap extends WUP.BaseCombo.EventMap {}
interface ValidityMap extends WUP.BaseCombo.ValidityMap {}
interface NewOptions {
/** Hide items in menu that selected
* @defaultValue false */
hideSelected: boolean;
/** Allow user to change ordering of items; Use drag&drop or keyboard Shift/Ctrl/Meta + arrows to change item position
* @defaultValue false */
sortable: boolean;
}
interface Options<T = any, VM = ValidityMap> extends WUP.Select.Options<T, VM>, NewOptions {
/** @readonly Constant value that impossible to change */
multiple: true;
}
interface JSXProps<C = WUPSelectManyControl> extends WUP.Select.JSXProps<C>, WUP.Base.OnlyNames<NewOptions> {
"w-hideSelected"?: boolean | "";
"w-sortable"?: boolean | "";
}
}
interface HTMLElementTagNameMap {
[tagName]: WUPSelectManyControl; // add element to document.createElement
}
}
declare module "react" {
namespace JSX {
interface IntrinsicElements {
/** Form-control with dropdown/combobox behavior
* @see {@link WUPSelectManyControl} */
[tagName]: WUP.Base.ReactHTML<WUPSelectManyControl> & WUP.SelectMany.JSXProps; // add element to tsx/jsx intellisense (react)
}
}
}
// @ts-ignore - because Preact & React can't work together
declare module "preact/jsx-runtime" {
namespace JSX {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface HTMLAttributes<RefType> {}
interface IntrinsicElements {
/** Form-control with dropdown/combobox behavior
* @see {@link WUPSelectManyControl} */
[tagName]: HTMLAttributes<WUPSelectManyControl> & WUP.SelectMany.JSXProps; // add element to tsx/jsx intellisense (preact)
}
}
}
/** Form-control with dropdown/combobox behavior
* @see demo {@link https://yegorich555.github.io/web-ui-pack/control/selectMany}
* @example
const el = document.createElement("wup-selectmany");
el.$options.name = "gender";
el.$options.items = [
{ value: 1, text: "Male" },
{ value: 2, text: "Female" },
{ value: 3, text: "Other/Skip" },
];
el.$initValue = [3];
el.$options.validations = { required: true };
const form = document.body.appendChild(document.createElement("wup-form"));
form.appendChild(el);
// or HTML
<wup-form>
<wup-selectmany w-name="gender" w-initvalue="window.myInitValue" w-validations="myValidations" w-items="window.myDropdownItems" />
</wup-form>;
@tutorial Troubleshooting
* * Accessibility. Screen readers announce 'blank' when focus on not-empty control.
Solution not found (using contenteditable fixes this but provides more other bugs)
* @tutorial innerHTML @example
* <label>
* <span> // extra span requires to use with icons via label:before, label:after without adjustments
* <span [item]>Item 1</span>
* <span [item]>Item 2</span>
* // etc/
* <input/>
* <strong>{$options.label}</strong>
* </span>
* <button clear/>
* <wup-popup menu>
* <ul>
* <li>Item 1</li>
* <li>Item 2</li>
* // etc/
* </ul>
* </wup-popup>
* </label>
*/
export default class WUPSelectManyControl<
ValueType = any,
TOptions extends WUP.SelectMany.Options = WUP.SelectMany.Options,
EventMap extends WUP.SelectMany.EventMap = WUP.SelectMany.EventMap
> extends WUPSelectControl<ValueType[], ValueType, TOptions, EventMap> {
#ctr = this.constructor as typeof WUPSelectManyControl;
static get $styleRoot(): string {
return `:root {
--ctrl-select-item-text: inherit;
--ctrl-select-item-bg: rgba(0,0,0,0.04);
--ctrl-select-item-del-display: none;
--ctrl-select-item-del: var(--ctrl-icon);
--ctrl-select-item-del-img: var(--wup-icon-cross);
--ctrl-select-item-del-size: 0.8em;
--ctrl-select-gap: 0.5em;
}
[wupdark] {
--ctrl-select-item-bg: #fff2;
--ctrl-select-item-del: var(--ctrl-icon);
}`;
}
static get $style(): string {
return `${super.$style}
:host label {
position: relative;
}
${WUPcssScrollSmall(":host label>span")}
:host label > span {
position: initial;
overflow: auto;
gap: var(--ctrl-select-gap);
flex-wrap: wrap;
flex-direction: row;
margin: var(--ctrl-padding);
padding: 0;
margin-left: 0;
margin-right: 0;
max-height: 5em;
}
:host strong {
top: 1.6em;
margin: var(--ctrl-padding);
margin-top: 0;
margin-bottom: 0;
}
:host[filled] strong {
transform: var(--ctrl-label-active-pos);
}
:host [item],
:host input {
padding: var(--ctrl-select-gap);
}
:host input {
flex: 1 1 auto;
width: 0;
min-width: 1em;
padding-left: 0; padding-right: 0;
}
:host[filled] input:placeholder-shown,
:host[filled] input:not(:focus) {
min-width: 0;
padding-left: calc(var(--ctrl-select-gap));
margin-right: 0;
margin-left: calc(-1 * var(--ctrl-select-gap));
}
:host [item] {
--ctrl-icon: var(--ctrl-select-item-del);
--ctrl-icon-size: var(--ctrl-select-item-del-size);
--ctrl-icon-img: var(--ctrl-select-item-del-img);
color: var(--ctrl-select-item-text);
background-color: var(--ctrl-select-item-bg);
border-radius: var(--ctrl-border-radius);
cursor: pointer;
box-sizing: border-box;
white-space: nowrap;
overflow: hidden;
flex: 0 0 auto;
}
:host [item]:after {
${WUPcssIcon}
display: var(--ctrl-select-item-del-display);
content: "";
padding: 0;
margin-left: 0.5em;
}
:host [item][focused],
:host [item][drag],
:host [item][drop] {
color: var(--ctrl-focus-label);
box-shadow: inset 0 0 3px 0 var(--ctrl-focus);
}
:host [item][removed],
:host [item][drag][remove] {
--ctrl-icon: var(--ctrl-err);
text-decoration: line-through;
color: var(--ctrl-err);
background-color: var(--ctrl-err-bg);
}
:host[readonly] [item] {
pointer-events: none;
touch-action: none;
}
:host button[clear] {
display: inline-block;
opacity: 0;
}
@media (hover: hover) and (pointer: fine) {
:host [item]:hover {
--ctrl-icon: var(--ctrl-err);
text-decoration: line-through;
color: var(--ctrl-err);
background-color: var(--ctrl-err-bg);
}
}
@media not all and (pointer: fine) {
:host [item] {
-webkit-user-select: none;
user-select: none;
}${/* don't allow select text on blocks to allow custom touch-logic */ ""}
}
@media not all and (prefers-reduced-motion) {
:host [item][removed] {
transition: all var(--anim-t) ease-in-out;
transition-property: margin, padding, width, opacity;
padding-left: 0; padding-right: 0;
margin-left: 0; margin-right: 0;
width: 0;
opacity: 0;
}
}
:host [item][drag] {
z-index: 9999;
position: fixed;
left:0; top:0;
cursor: grabbing;
text-decoration: none;
--ctrl-icon: var(--ctrl-select-item-del);
color: var(--ctrl-select-item-text);
background-color: var(--ctrl-select-item-bg);
}
:host [item][drop] {
opacity: 0.7;
}`;
}
static override $isEmpty(v: unknown[] | undefined): boolean {
return !v || v.length === 0;
}
static override $filterMenuItem(
this: WUPSelectManyControl,
menuItemText: string,
menuItemValue: any,
inputValue: string,
inputRawValue: string
): boolean {
if (this._opts.hideSelected && this.$value?.includes(menuItemValue)) {
return false;
}
return super.$filterMenuItem.call(this, menuItemText, menuItemValue, inputValue, inputRawValue);
}
static $defaults: WUP.SelectMany.Options = {
...WUPSelectControl.$defaults,
multiple: true,
sortable: false,
hideSelected: false,
};
/** Items selected & rendered on control */
$refItems?: Array<HTMLElement & { _wupValue: ValueType }>;
protected override renderControl(): void {
super.renderControl();
// Move ctrl-label outside scrollable part
this.$refLabel.prepend(this.$refTitle); // WARN: expected browser won't autofill this type of control - otherwise it doesn't work
}
protected override canHandleUndo(): boolean {
return false; // custom history not required for this control
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
override canParseInput(_text: string): boolean {
return false; // disable behavior from select[multiple]
}
override parseInput(text: string): ValueType[] | undefined {
// WARN must be called only on allowNewValue
// @ts-expect-error: because declared as constant true
this._opts.multiple = false;
const vi = super.parseInput(text) as ValueType | undefined;
this._opts.multiple = true;
if (vi === undefined || this.$value?.some((v) => this.#ctr.$isEqual(v, vi, this))) {
return this.$value; // no-changes, no-duplicates
}
return this.$value ? [...this.$value, vi] : [vi];
}
protected override gotChanges(propsChanged: Array<keyof WUP.Select.Options> | null): void {
this._opts.multiple = true;
this.removeAttribute("w-multiple");
super.gotChanges(propsChanged);
this._opts.sortable ??= false;
if (this._opts.sortable) {
!this._disposeDragdrop && this.applyDragdrop();
} else {
this._disposeDragdrop?.call(this);
this._disposeDragdrop = undefined;
}
}
/** It prevents menu opening if user tries sorting and focus got after mouseUp */
_wasSortAfterClick?: boolean;
/** Call it to remove dragdrop logic */
_disposeDragdrop?: () => void;
/** Called to apply dragdrop logic */
protected applyDragdrop(): void {
this._disposeDragdrop = onEvent(this, "pointerdown", (e) => {
this._wasSortAfterClick = false;
if (this.$isReadOnly || this.$isDisabled) {
return;
}
const t = e.target;
let eli = (this.$refItems && this.$refItems.findIndex((item) => t === item || this.includes.call(item, t)))!;
if (eli === -1 || eli === undefined) {
return;
}
const el = this.$refItems![eli];
let dr: HTMLElement;
let isWaitTouch = false; // wait for touch to detect if possible to prevent scrollByTouch (browser can cancel pointer events if swipe)
let r0 = onEvent(
document,
"touchstart",
() => {
isWaitTouch = true;
r0 = onEvent(
document,
"touchmove",
(ev) => {
if (ev.cancelable) {
ev.preventDefault(); // prevent scrolling by touch if possible
isWaitTouch = false;
}
},
{ passive: false, capture: true }
);
},
{ capture: true }
);
let isInside = true;
let isThrottle = false;
const r1 = onEvent(document, "pointermove", (ev) => {
if (isWaitTouch) {
return;
}
// init
if (!dr) {
this._wasSortAfterClick = true;
// clone draggable element
dr = el.cloneNode(true) as HTMLElement;
dr.setAttribute("drag", "");
dr.style.width = `${el.offsetWidth}px`;
dr.style.height = `${el.offsetHeight}px`;
el.parentElement!.prepend(dr);
el.setAttribute("drop", ""); // mark current element
this.setAttribute("hovered", ""); // if pick item and move cursor fast control-focus-frame is blinking because because cursor much faster than js events
}
// set position
const x = ev.clientX - el.offsetWidth / 2;
const y = ev.clientY - el.offsetHeight / 2;
dr.style.transform = `translate(${x}px, ${y}px)`;
// define if element inside control (if outside - remove logic)
isInside = isOverlap(this.getBoundingClientRect(), dr.getBoundingClientRect());
this.setAttr.call(dr, "remove", !isInside, true);
if (!isInside) {
return; // skip new place detection when item outside control
}
if (isThrottle) {
return;
}
// find nearest line
let nearest = eli; // index of nearest item
let nearestEnd = eli; // index of last item in the nearest line
let dist = Number.MAX_SAFE_INTEGER; // distance between centers
const rects = this.$refItems!.map((item) => item.getBoundingClientRect());
let lineY = 0;
rects.some((r, i) => {
const nextLineY = r.y + r.height / 2;
if (Math.abs(nextLineY - lineY) > 3) {
// compare with 3px because centers can be not aligned properly
lineY = nextLineY; // it's next line
const c = Math.abs(ev.clientY - lineY);
if (c < dist) {
dist = c;
nearest = i; // index of 1st item in the nearest line
nearestEnd = i;
} else {
return true; // break search because next line is further then previous
}
} else {
nearestEnd += 1;
}
return false;
});
// find nearest item in the nearest line
dist = Number.MAX_SAFE_INTEGER;
// console.warn(nearest, nearestEnd, lineY);
const nearestStart = nearest;
for (let i = nearest; i <= nearestEnd; ++i) {
const r = rects[i];
const dx = ev.clientX - (r.x + r.width / 2);
const dy = ev.clientY - (r.y + r.height / 2);
const c = Math.sqrt(dx * dx + dy * dy);
if (c < dist) {
dist = c;
nearest = i;
}
}
// define left/right side
if (eli !== nearest) {
const trg = this.$refItems![nearest];
const r = rects[nearest];
const isYChangeByEdges = nearestStart === nearest || nearestEnd === nearest;
const isLeftOrTop = isYChangeByEdges
? eli > nearest
: Math.abs(r.x - ev.clientX) < Math.abs(r.x + r.width - ev.clientX);
let nextEli = eli;
if (nearest < eli) {
nextEli = isLeftOrTop ? nearest : nearest + 1; // shift from right to left
} else {
// if (nearest >= eli) {
nextEli = /* isLeftOrTop ? nearest - 1 : */ nearest; // shift from left to right
}
if (nextEli !== eli) {
if (isLeftOrTop) {
trg.parentElement!.insertBefore(el, trg);
} else {
trg.parentElement!.insertBefore(el, trg.nextElementSibling);
}
this.$refItems!.splice(nextEli, 0, this.$refItems!.splice(eli, 1)[0]);
eli = nextEli;
isThrottle = true;
setTimeout(() => (isThrottle = false), 100); // to prevent fast changing position
}
}
});
const cancel = (): void => {
if (dr) {
setTimeout(() => (this._wasSortAfterClick = false), 1);
this.removeAttribute("hovered");
if (!isInside) {
el.removeAttribute("drop");
dr.remove();
this.removeValue(eli);
} else {
const animTime = parseMsTime(window.getComputedStyle(el).getPropertyValue("--anim-t"));
const from = dr.getBoundingClientRect();
const to = el.getBoundingClientRect();
const diff = { x: to.x - from.x, y: to.y - from.y };
// return element back
animate(0, 1, animTime, (v) => {
dr.style.transform = `translate(${from.x + diff.x * v}px, ${from.y + diff.y * v}px)`;
}).finally(() => {
el.removeAttribute("drop");
dr.remove();
});
// change value
this.setValue(
this.$refItems!.map((a) => a._wupValue),
SetValueReasons.userInput
);
}
}
r0();
r1();
r2();
r3();
};
const r2 = onEvent(document, "pointerup", cancel, { capture: true });
const r3 = onEvent(document, "pointercancel", cancel, { capture: true }); // pointerup not called if touchmove can't be cancelled and browser scrolls
});
}
override canOpenMenu(openCase: MenuOpenCases, e?: MouseEvent | FocusEvent | KeyboardEvent | null): boolean {
return !this._wasSortAfterClick && super.canOpenMenu(openCase, e);
}
protected override renderMenu(popup: WUPPopupElement, menuId: string): HTMLElement {
const r = super.renderMenu(popup, menuId);
this.filterMenuItems();
return r;
}
/** Called to update/remove selected items on control */
protected renderItems(v: ValueType[], all: WUP.Select.MenuItem<any>[]): void {
const refs = this.$refItems ?? [];
v.forEach((vi, i) => {
let r = refs[i];
if (!r) {
r = this.$refInput.parentNode!.insertBefore(document.createElement("span"), this.$refInput) as HTMLElement & {
_wupValue: ValueType;
};
r.setAttribute("item", "");
r.setAttribute("aria-hidden", true);
refs.push(r);
}
if (r._wupValue !== vi) {
r.textContent = this.valueToText(vi, all);
r._wupValue = vi;
}
});
const toRemove = refs.length - v.length;
toRemove > 0 && refs.splice(v.length, toRemove).forEach((el) => !el.hasAttribute("removed") && el.remove()); // remove previous items
this.$refPopup && this.filterMenuItems(); // NiceToHave it can be optimized because on Remove/Select we can hide/show specific item
this.$refItems = refs;
this.ariaSpeakValue();
}
/** Announce items as single value on change if element is focused */
protected ariaSpeakValue(): void {
this.$isFocused &&
this.$refItems?.length &&
this.$ariaSpeak(this.$refItems.map((el) => el.textContent).join(","), 0);
}
protected resetInputValue(): void {
this.$refInput.value = this.valueToInput(this.$value as ValueType[], true);
}
protected override valueToInput(v: ValueType[] | undefined, isReset?: boolean): string {
// todo issue when items is promise and called .$value =
!isReset && setTimeout(() => this.renderItems(v ?? [], this.getItems())); // timeout required otherwise filter is reset by empty input
return this.$isFocused || !v?.length ? "" : " "; // otherwise broken css:placeholder-shown
}
// @ts-expect-error - because expected v: ValueType[]
protected override selectValue(v: ValueType, canCloseMenu = true): void {
super.selectValue(v as any, canCloseMenu);
this._opts.hideSelected && this.focusMenuItem(null);
}
/** Index of focused value-item */
_focusIndex?: number;
/** Focus value-item by index (related to this.$refItems) */
protected focusItemByIndex(i: number | null): void {
const el = i == null ? null : this.$refItems![i];
this.focusMenuItem(el);
if (el) {
el.setAttribute("role", "option"); // otherwise NVDA doesn't allow to use Arrow to goto
el.removeAttribute("aria-hidden");
el.removeAttribute("aria-selected"); // attribute appended by selectControl
}
this._focusIndex = i ?? undefined;
}
protected override focusMenuItem(next: HTMLElement | null): void {
if (this._focusIndex != null) {
const prev = this.$refItems![this._focusIndex];
if (prev) {
prev.setAttribute("aria-hidden", true);
prev.removeAttribute("role");
}
this._focusIndex = undefined;
}
super.focusMenuItem(next);
}
protected selectMenuItemByValue(v: ValueType[] | undefined): void {
!this._opts.hideSelected && super.selectMenuItemByValue(v);
}
protected override selectMenuItem(next: HTMLElement | null): void {
!this._opts.hideSelected && super.selectMenuItem(next);
}
protected override clearFilterMenuItems(): void {
!this._opts.hideSelected && super.clearFilterMenuItems(); // skip this because default filtering doesn't reset after re-opening menu
}
/** Called to remove item with animation */
protected removeValue(index: number): void {
const item = this.$refItems!.splice(index, 1)[0]; // otherwise item is replaced
this._focusIndex === index && this.focusItemByIndex(null);
let ms = 0;
const isAnim = isAnimEnabled();
if (isAnim) {
item.style.width = `${item.offsetWidth}px`;
item.setAttribute("removed", "");
setTimeout(() => (item.style.width = ""));
ms = parseMsTime(window.getComputedStyle(item).getPropertyValue("--anim-t"));
}
setTimeout(() => item.remove(), ms);
const v = [...this.$value!];
v.splice(index, 1);
this.setValue(v.length ? v : undefined, SetValueReasons.userInput);
}
protected override setValue(v: ValueType[] | undefined, reason: SetValueReasons, skipInput = false): boolean | null {
const isChanged = super.setValue(v, reason, skipInput);
isChanged !== false && this.setAttr("filled", !this.$isEmpty, true);
return isChanged;
}
protected override gotFocus(ev: FocusEvent): Array<() => void> {
const r = super.gotFocus(ev);
this.ariaSpeakValue();
this.$refInput.value = "";
// https://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
const isTouchScreen = !window.matchMedia("(hover: hover) and (pointer: fine)").matches; // WARN: 'window.matchMedia("(pointer: coarse)").matches' but it's correlated with css-hover styles
let preventClickAfterFocus = isTouchScreen; // allow focus by touch-click instead of focus+removeItem (otherwise difficult to focus control without removing item when no space)
isTouchScreen && setTimeout(() => (preventClickAfterFocus = false));
const dsps = onEvent(
this.$refInput.parentElement!,
"click",
(e) => {
if (e.button || this.$isDisabled || this.$isReadOnly || preventClickAfterFocus) {
return;
}
const t = e.target;
const eli = this.$refItems?.findIndex((li) => li === t || this.includes.call(li, t));
if (eli != null && eli > -1) {
e.preventDefault(); // to prevent open/hide popup
this.removeValue(eli);
}
},
{ passive: false }
);
r.push(dsps);
const dsps2 = onEvent(this.$refInput, "blur", () => {
this.$refInput.value = " "; // fix label position trigerring: testcase focus>long mouseDown outside>blur - label must save position
onEvent(this.$refInput, "focus", () => (this.$refInput.value = ""), { once: true }); // case: user click on browser console and click again on control: in this case gotFocus isn't fired
});
r.push(dsps2);
return r;
}
protected override gotFocusLost(): void {
super.gotFocusLost();
this.focusItemByIndex(null);
}
protected override gotKeyDown(e: KeyboardEvent): void {
super.gotKeyDown(e);
if (!(this.$refInput.selectionEnd === 0 && this.$refItems?.length)) {
return;
}
let handled = true;
if (e.shiftKey) {
if (!this._opts.sortable || this._focusIndex == null) {
return;
}
const prev = this._focusIndex;
const trg = this.$refItems[prev];
let isR = false;
const lastInd = this.$refItems.length - 1;
switch (e.key) {
case "ArrowLeft":
this._focusIndex = this._focusIndex > 0 ? this._focusIndex - 1 : lastInd;
break;
case "ArrowRight":
this._focusIndex = this._focusIndex < lastInd ? this._focusIndex + 1 : 0;
isR = true;
break;
default:
handled = false;
break;
}
if (handled) {
e.preventDefault();
// if (prev !== this._focusIndex) {
trg.parentElement!.insertBefore(
trg,
this._focusIndex === lastInd
? this.$refInput
: this.$refItems[isR && this._focusIndex !== 0 ? this._focusIndex + 1 : this._focusIndex]
);
this.$refItems.splice(this._focusIndex, 0, this.$refItems.splice(prev, 1)[0]);
this.setValue(
this.$refItems.map((a) => a._wupValue),
SetValueReasons.userInput
);
// }
}
return;
}
let next = this._focusIndex ?? null;
const len = this.$refItems.length;
switch (e.key) {
case "Enter":
if (next != null) {
this._focusIndex = undefined; // WARN Enter fired click after empty timout but need to reset index immediately to focus next
next = Math.max(0, next - 1);
} else {
handled = false; // it must be skipped if handled above otherwise auto-focus on select menu item by Enter
}
break;
case "Backspace":
if (next != null) {
this.removeValue(next);
next = !this.$refItems.length ? null : Math.max(0, next - 1);
break;
}
// eslint-disable-next-line no-fallthrough
case "ArrowLeft":
next = Math.max(0, (next ?? this.$refItems.length) - 1);
break;
case "Delete":
if (next != null) {
this.removeValue(next);
next = !this.$refItems.length ? null : Math.min(next, this.$refItems.length - 1);
break;
}
// eslint-disable-next-line no-fallthrough
case "ArrowRight":
if (next != null) {
next = Math.min(this.$refItems.length - 1, next + 1);
if (next === this._focusIndex) {
next = null; // move focus to input if was selected last
}
} else {
handled = false;
}
break;
default:
handled = false;
break;
}
if (handled && (this._focusIndex !== next || len !== this.$refItems.length)) {
e.preventDefault();
this.focusItemByIndex(next);
}
}
}
customElements.define(tagName, WUPSelectManyControl);
/**
* known issues when 'contenteditable':
*
* <span contenteditalbe='true'>
* <span></span>
* <span contenteditalbe='false'>Item 1</span>
* <span></span>
* <span contenteditalbe='false'>Item 2</span>
* <span>Input text here</span>
* </span>
* 01. NVDA. Reads only first line (the same issue for textarea)
* 02. NVDA. Reads only first item in Firefox (when :after exists)
* 1. Firefox. Caret position is wrong/missed between Items is use try to use ArrowKeys
* 2. Firefox. Caret position is missed if no empty spans between items
* 3. Without contenteditalbe='false' browser moves cursor into item, but it should be outside
*/
/* todo popup can change position during the hiding by focuslost when input is goes invisible and control size is reduced - need somehow block changing position-priority
when popup is opened => don't change bottom...top if menu or control height changed. Change bottom to top only during the scrolling
*/
// NiceToHave: Ctrl+Z must should work for the whole control. Not only for `input`