-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.ts
775 lines (714 loc) · 26.8 KB
/
text.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
// eslint-disable-next-line max-classes-per-file
import MaskTextInput from "./text.mask";
import { onEvent } from "../indexHelpers";
import { WUPcssIcon } from "../styles";
import WUPBaseControl, { SetValueReasons, ValidateFromCases } from "./baseControl";
import TextHistory from "./text.history";
const emailReg =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const tagName = "wup-text";
declare global {
namespace WUP.Text {
interface EventMap extends WUP.BaseControl.EventMap {}
interface ValidityMap extends WUP.BaseControl.ValidityMap {
/** If textLength < pointed shows message 'Min length is {x} characters` */
min: number;
/** If textLength > pointed shows message 'Max length is {x} characters` */
max: number;
/** If $value doesn't match email-pattern shows message 'Invalid email address` */
email: boolean;
}
interface NewOptions {
/** Debounce time to wait for user finishes typing to start validate and provide $change event
* @defaultValue 0; */
debounceMs: number;
/** Select whole text when input got focus (when input is not readonly and not disabled);
* @defaultValue false */
selectOnFocus: boolean;
/** Show/hide clear button
* @see {@link ClearActions} from `web-ui-pack/baseControl`
* @defaultValue true */
clearButton: boolean;
/** Make input masked
* @rules when mask is pointed and contains only numeric vars
* * inputmode='numeric' so mobile device show numeric-keyboard
* * enables validation 'mask' with error message 'Incomplete value'
* @example
* "0000-00-00" // for date in format yyyy-mm-dd
* "##0.##0.##0.##0" // IPaddress
* "+1(000) 000-0000" // phoneNumber
* "00:00 /[AP]/M" // time hh:mm AM/PM
* '0' // required digit
* '#' // optional digit
* '*' // any char
* '*{1,5}' // - any 1..5 chars
* '//[a-zA-Z]//' // regex: 1 letter (WARN: regex must be pointed for check-in only 1 char at once)
* '//[a-zA-Z]//{1,5}' // regex: 1..5 letters
* '|0' // or '\x00' - static char '0'
* '|#' // or '\x01' - static char '#'
* '|*' // or '\x02' - static char '*'
* '|/' // or '\x03' - static char '/' */
mask?: string | null | undefined;
/** Placeholder for mask. By default it inherits from mask. To disabled it set `false`;
* for date maskholder can be 'yyyy-mm-dd' */
maskholder?: string | false | null | undefined;
/** Part before input; for example for value "$ 123 USD" prefix is "$ " */
prefix?: string | null | undefined;
/** Part after input; for example for value "$ 123 USD" postfix is " USD" */
postfix?: string | null | undefined;
}
interface Options<T = string, VM = ValidityMap> extends WUP.BaseControl.Options<T, VM>, NewOptions {}
interface JSXProps<C = WUPTextControl> extends WUP.BaseControl.JSXProps<C>, WUP.Base.OnlyNames<NewOptions> {
"w-debounceMs"?: number;
"w-selectOnFocus"?: boolean | "";
"w-clearButton"?: boolean | "";
"w-mask"?: string;
"w-maskholder"?: string | false;
"w-prefix"?: string;
"w-postfix"?: string;
}
interface GotInputEvent extends InputEvent {
target: HTMLInputElement;
// /** Call it to prevent calling setValue by input event */
// preventSetValue: () => void;
// /** Returns a boolean value indicating whether or not the call to InputEvent.preventSetValue() */
// setValuePrevented: boolean;
}
}
interface HTMLElementTagNameMap {
[tagName]: WUPTextControl; // add element to document.createElement
}
}
declare module "react" {
namespace JSX {
interface IntrinsicElements {
/** Form-control with text input
* @see {@link WUPTextControl} */
[tagName]: WUP.Base.ReactHTML<WUPTextControl> & WUP.Text.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 text input
* @see {@link WUPTextControl} */
[tagName]: HTMLAttributes<WUPTextControl> & WUP.Text.JSXProps; // add element to tsx/jsx intellisense (preact)
}
}
}
/** Form-control with text-input
* @see demo {@link https://yegorich555.github.io/web-ui-pack/control/text}
* @example
const el = document.createElement("wup-text");
el.$options.name = "email";
el.$options.validations = { required: true, max: 100, email: true };
const form = document.body.appendChild(document.createElement("wup-form"));
form.appendChild(el);
// or HTML
<wup-form>
<wup-text w-name="firstName" w-initvalue="Donny" w-validations="myValidations"/>
</wup-form>;
* @tutorial innerHTML @example
* <label>
* <span> // extra span requires to use with icons via label:before, label:after without adjustments
* <input/>
* <strong>{$options.label}</strong>
* </span>
* <button clear/>
* </label>
* @tutorial Troubleshooting @see {@link https://yegorich555.github.io/web-ui-pack/control/text#troubleshooting} */
export default class WUPTextControl<
ValueType = string,
TOptions extends WUP.Text.Options = WUP.Text.Options,
EventMap extends WUP.Text.EventMap = WUP.Text.EventMap
> extends WUPBaseControl<ValueType, TOptions, EventMap> {
/** Returns this.constructor // watch-fix: https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146 */
#ctr = this.constructor as typeof WUPTextControl;
static get $styleRoot(): string {
return `:root {
--ctrl-autofill: #00869e;
--ctrl-clear: red;
--ctrl-clear-hover: rgba(255,0,0,0.1);
--ctrl-label-active-pos: translateY(calc(-100% - 0.2em)) scale(0.9);
}
[wupdark] {
--ctrl-clear-hover: rgba(255,0,0,0.2);
--ctrl-autofill: #89bc55;
--ctrl-autofill-caret: #fff;
}`;
}
static get $style(): string {
return `${super.$style}
:host {
cursor: text;
text-align: start;
}
:host label > span {
width: 100%;
position: relative;${/* to position <strong /> relative to input */ ""}
display: flex;
flex-direction: row-reverse;${/* WA: required for reading <strong /> 1st */ ""}
}
:host input,
:host textarea,
:host [maskholder],
:host [prefix],
:host [postfix] {
padding: var(--ctrl-padding);
padding-left: 0;
padding-right: 0;
font: inherit;
text-align: inherit;
color: inherit;
margin: 0;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
:host input,
:host textarea,
:host [contenteditable=true],
:host [maskholder],
:host [postfix] {
width: 100%;
box-sizing: border-box;
border: none;
background: none;
outline: none;
}
:host [prefix],
:host [postfix] {
color: inherit;
flex-shrink: 0;
}
:host [maskholder],
:host [prefix],
:host [postfix] {
display: none;
opacity: 0;
pointer-events: none;
text-overflow: initial;
white-space: pre;
}
:host [postfix] {
position: absolute;
}
:host [maskholder] {
position: absolute;
opacity: 0.65;
}
:host [maskholder]>i,
:host [postfix]>i {
visibility: hidden;
font: inherit;
white-space: pre;
}
:host input:-webkit-autofill,
:host textarea:-webkit-autofill,
:host [contenteditable=true]:-webkit-autofill {
font: inherit;
-webkit-background-clip: text;
-webkit-text-fill-color: var(--ctrl-autofill);
caret-color: var(--ctrl-autofill-caret, auto);
}
:host input:autofill,
:host textarea:autofill,
:host [contenteditable=true]:autofill {
font: inherit;
background-clip: text;
text-fill-color: var(--ctrl-autofill);
caret-color: var(--ctrl-autofill-caret, auto);
}
:host strong {
display: block;
position: absolute;
top: 50%;
left: 0;
padding: 0;
margin: 0;
box-sizing: border-box;
max-width: 100%;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
transform-origin: top left;
transform: translateY(-50%);
font-weight: normal;
text-decoration: none;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; ${/* to fix sometimes blink during the animation */ ""}
}
@media not all and (prefers-reduced-motion) {
:host strong {
transition: top var(--anim), transform var(--anim), color var(--anim);
}
}
:host input:not(:focus):placeholder,
:host textarea:not(:focus):placeholder {
color: transparent;
}
:host:focus-within strong,
:host input:not(:placeholder-shown) + strong,
:host textarea:not(:placeholder-shown) + strong,
:host [contenteditable=true]:not(:empty) + strong,
:host legend {
transform: var(--ctrl-label-active-pos);
}
:host input:-webkit-autofill + strong
:host textarea:-webkit-autofill + strong
:host [contenteditable=true]:-webkit-autofill + strong {
transform: var(--ctrl-label-active-pos);
}
:host input:autofill + strong,
:host textarea:autofill + strong,
:host [contenteditable=true]:autofill + strong {
transform: var(--ctrl-label-active-pos);
}
:host:focus-within [maskholder],
:host:focus-within [prefix],
:host:focus-within [postfix],
:host input:not(:placeholder-shown) ~ [prefix],
:host input:not(:placeholder-shown) ~ [postfix],
:host textarea:not(:placeholder-shown) ~ [prefix],
:host textarea:not(:placeholder-shown) ~ [postfix] {
display: inline-block;
opacity: 1;
}
/* style for icons */
:host label:after,
:host label:before {
${WUPcssIcon}
cursor: pointer;
-webkit-mask-image: none;
mask-image: none;
}
:host label:after {
margin-right: calc(var(--ctrl-icon-size) / -2);
}
:host label:before {
margin-left: calc(var(--ctrl-icon-size) / -2);
}
:host label>button {
z-index: 1;
contain: strict;
font-size: inherit;
flex: 0 0 auto;
align-self: center;
}
:host button[clear] {
--icon-size: var(--ctrl-icon-size);
--icon-hover-r: 24px;
--icon-img: var(--wup-icon-cross);
--icon: var(--ctrl-label);
--icon-hover: var(--ctrl-clear);
--icon-hover-bg: var(--ctrl-clear-hover);
display: none;
opacity: 0;
margin-right: -0.5em;
}
:host button[clear=back] {
--icon-img: var(--wup-icon-back);
}
:host:focus-within button[clear] {
display: inline-block;
opacity: 1;
}
@media (hover: hover) and (pointer: fine) {
:host:hover button[clear] {
display: inline-block;
opacity: 1;
}
}
:host[disabled] button[clear],
:host[readonly] button[clear] {
display: none;
pointer-events: none;
}`;
}
static $errorParse = __wupln("Invalid value", "validation");
static $errorMask = __wupln("Incomplete value", "validation");
static $defaults: WUP.Text.Options = {
...WUPBaseControl.$defaults,
selectOnFocus: false,
clearButton: true,
validationRules: {
...WUPBaseControl.$defaults.validationRules,
min: (v, setV) =>
(v === undefined || v.length < setV) && __wupln(`Min length is ${setV} characters`, "validation"),
max: (v, setV) =>
(v === undefined || v.length > setV) && __wupln(`Max length is ${setV} characters`, "validation"),
email: (v, setV) => setV && (!v || !emailReg.test(v)) && __wupln("Invalid email address", "validation"),
},
debounceMs: 0,
mask: "",
maskholder: "",
prefix: "",
postfix: "",
};
$refBtnClear?: HTMLButtonElement;
$refMaskholder?: HTMLSpanElement;
$refPrefix?: HTMLSpanElement;
$refPostfix?: HTMLSpanElement;
constructor() {
super();
this.$refInput.placeholder = " "; // Without this css related styles don't work with browser autofill
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
override parse(text: string): ValueType | undefined {
return (text || undefined) as any;
}
/** Called before parseInput on gotInput event */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
canParseInput(_text: string): boolean {
return true;
}
/** Called to parse/prettify input text to value (related to locale or pointed format)
* @throws {RangeError} if value out of possible range (for DateControl value.month > 12 for example) */
parseInput(text: string): ValueType | undefined {
return this.parse(text.trim());
}
/** Returns true if need to use custom undo/redo (required when input somehow formatted/masked) */
protected canHandleUndo(): boolean {
return true;
}
protected get validations(): WUP.Text.Options["validations"] {
const vls = (super.validations as { [k: string]: WUP.BaseControl.ValidityFunction<any> }) || {};
vls._invalidInput = (_v, c) => (c as WUPTextControl)._inputError || false;
return vls;
}
protected override renderControl(): void {
(this.$refInput as HTMLInputElement).type = "text";
this.$refInput.id = this.#ctr.$uniqueId;
this.$refLabel.setAttribute("for", this.$refInput.id);
const s = this.$refLabel.appendChild(document.createElement("span"));
s.appendChild(this.$refInput); // input appended to span to allow user user :after,:before without padding adjust
s.appendChild(this.$refTitle);
this.appendChild(this.$refLabel);
// WARN: browser autofill can fire input without focus: need listen for input event every time
this.$refInput.addEventListener("beforeinput", (e) => this.gotBeforeInput(e as WUP.Text.GotInputEvent)); // WARN: method `onbeforeinput` poor supported
this.$refInput.addEventListener("input", (e) => this.gotInput(e as WUP.Text.GotInputEvent), { passive: true });
}
/** Create & append element to control */
protected renderBtnClear(): HTMLButtonElement {
const bc = document.createElement("button");
const span = this.$refLabel.querySelector("span");
if (span!.nextElementSibling) {
this.$refLabel.insertBefore(bc, span!.nextElementSibling);
} else {
this.$refLabel.appendChild(bc);
}
bc.setAttribute(this.#ctr.classNameBtnIcon, "");
bc.setAttribute("clear", "");
bc.setAttribute("tabindex", -1);
bc.setAttribute("aria-hidden", true);
bc.setAttribute("type", "button");
onEvent(
bc,
"click",
(e) => {
e.preventDefault(); // prevent from submit
this.clearValue();
},
{ passive: false }
);
return bc;
}
/** Add/update/remove prefix part */
protected renderPrefix(text: string | undefined | null): void {
let el = this.$refPrefix;
if (!text) {
if (el) {
el.remove();
delete this.$refPrefix;
}
} else {
if (!el) {
el = document.createElement("span");
el.setAttribute("prefix", "");
this.$refLabel.firstElementChild!.append(el);
this.$refPrefix = el;
}
el.textContent = text;
}
// because postfix depends on prefix
this.renderPostfix(this._opts.postfix);
}
/** Add/update or remove prefix part */
protected renderPostfix(text: string | undefined | null): void {
let el = this.$refPostfix;
if (!text) {
if (el) {
el.remove();
delete this.$refPostfix;
}
} else {
if (!el) {
el = document.createElement("span");
el.setAttribute("postfix", "");
el.appendChild(document.createElement("i"));
el.append("");
this.$refLabel.firstElementChild!.append(el);
this.$refPostfix = el;
}
el.firstChild!.textContent =
(this.$isFocused && this.$refMaskholder?.textContent) ||
(this.$refPrefix?.textContent || "") + this.$refInput.value;
el.lastChild!.textContent = text;
}
}
/** Custom history undo/redo */
_refHistory?: TextHistory;
protected override gotFocus(ev: FocusEvent): Array<() => void> {
const arr = super.gotFocus(ev);
if (this.canHandleUndo()) {
this._refHistory ??= new TextHistory(this.$refInput);
}
if (!this.$refInput.readOnly) {
let canSelectAll = this._opts.selectOnFocus;
if (this._opts.mask) {
this.maskInputProcess(null); // to apply prefix + maskholder
canSelectAll &&= this.refMask!.isCompleted;
this.renderPostfix(this._opts.postfix);
if (!canSelectAll) {
const end = this.$refInput.value.length;
this.$refInput.setSelectionRange(end, end); // move cursor to the end
}
}
canSelectAll && this.$refInput.select();
}
const hasOnlyNums = this.refMask?.chunks.every((c) => !c.isVar || c.pattern[0] !== "*");
this.setAttr.call(this.$refInput, "inputmode", hasOnlyNums ? "numeric" : "");
return arr;
}
protected override gotFocusLost(): void {
this.#declineInputEnd?.call(this);
if (this.refMask) {
if (this.refMask.prefix && this.refMask.value === this.refMask.prefix) {
this.$refInput.value = ""; // rollback prefix/postfix if user types nothing
delete (this.$refInput as WUP.Text.Mask.HandledInput)._maskPrev;
}
this.renderPostfix(this._opts.postfix); // postfix depends on maskholder
}
super.gotFocusLost();
}
protected override gotChanges(propsChanged: Array<keyof WUP.Text.Options> | null): void {
// apply mask options
if (!this._opts.mask || this._opts.mask !== this.refMask?.pattern) {
delete this.refMask; // delete if mask is removed or changed (it's recovered again on event)
}
if (this._opts.mask && !this._opts.maskholder && this._opts.maskholder !== false) {
this.refMask ??= new MaskTextInput(this._opts.mask, "");
this._opts.maskholder = this.refMask.chunks.map((c) => c.pattern).join("");
}
if ((!this._opts.maskholder || !this._opts.mask) && this.$refMaskholder) {
this.$refMaskholder.remove();
delete this.$refMaskholder;
}
super.gotChanges(propsChanged as any);
if (this._opts.clearButton) {
this.$refBtnClear = this.$refBtnClear || this.renderBtnClear();
} else if (this.$refBtnClear) {
this.$refBtnClear.remove();
this.$refBtnClear = undefined;
}
if (!propsChanged || propsChanged.includes("prefix")) {
this.renderPrefix(this._opts.prefix);
}
if (!propsChanged || propsChanged.includes("postfix")) {
this.renderPostfix(this._opts.postfix);
}
}
protected override gotKeyDown(e: KeyboardEvent): void {
super.gotKeyDown(e);
this._refHistory?.handleKeyDown(e);
}
/** Value-text before input changed - used with declineInput */
_beforeSnap?: string;
/** Handler of 'beforeinput' event */
protected gotBeforeInput(e: WUP.Text.GotInputEvent): void {
const isUndoRedo = this._refHistory?.handleBeforeInput(e);
this.#declineInputEnd?.call(this);
this._beforeSnap = TextHistory.historyToSnapshot(this.$refInput.value, this.$refInput.selectionStart || 0);
setTimeout(() => delete this._beforeSnap);
if (!isUndoRedo && this._opts.mask) {
this.refMask = this.refMask ?? new MaskTextInput(this._opts.mask, e.target.value);
this.refMask.handleBeforeInput(e);
}
}
_inputError?: string;
#inputTimer?: ReturnType<typeof setTimeout>;
/** Called when user types text OR when need to apply/reset mask (on focusGot, focusLost) */
protected gotInput(e: WUP.Text.GotInputEvent): void {
const isBrowserAutofill = e.isTrusted && e.inputType == null;
if (isBrowserAutofill && !this._refHistory && this.canHandleUndo()) {
this._refHistory = new TextHistory(this.$refInput);
}
this._refHistory?.handleInput(e);
const el = e.target as WUP.Text.Mask.HandledInput;
let txt = el.value;
let errMsg: string | undefined;
if (this._opts.mask) {
const prev = el._maskPrev?.value;
txt = this.maskInputProcess(e); // returns true value
if (txt === prev) {
// this.renderPostfix(this._opts.postfix);
return; // skip because no changes from previous action
}
const m = this.refMask!;
if (m.value !== m.prefix && !m.isCompleted) {
errMsg = this.#ctr.$errorMask;
}
}
let v = this.$value;
let isParsedOrEmpty = false;
if (txt) {
if (this.canParseInput(txt)) {
try {
v = this.parseInput(txt);
isParsedOrEmpty = true;
} catch (err) {
v = this.$value;
errMsg ||= this.#ctr.$errorParse;
}
}
} else {
isParsedOrEmpty = true;
v = undefined;
}
this.renderPostfix(this._opts.postfix);
const wasErr = !errMsg && !!this._inputError;
this._inputError = errMsg;
const act = (): void => {
if (this._inputError || wasErr) {
this.goValidate(ValidateFromCases.onChange);
}
isParsedOrEmpty && this.setValue(v, SetValueReasons.userInput, true);
};
this._validTimer && clearTimeout(this._validTimer);
this.#inputTimer && clearTimeout(this.#inputTimer);
if (this._opts.debounceMs) {
this.#inputTimer = setTimeout(act, this._opts.debounceMs);
} else {
act();
}
}
/** Mask object to proccess mask on input */
refMask?: MaskTextInput;
/** Called to apply mask-behavior (on "input" event) */
protected maskInputProcess(e: WUP.Text.GotInputEvent | null): string {
const el = this.$refInput;
const v = el.value;
const { mask } = this._opts;
this.refMask = this.refMask ?? new MaskTextInput(mask!, "");
const mi = this.refMask;
const isFocused = this.$isFocused;
if (!v && !isFocused) {
el.value = v;
mi.parse(v);
return v; // ignore mask prefix/postfix if user isn't touched input; it appends only by focusGot
}
let declinedAdd = 0;
let pos = el.selectionStart || 0;
if (!e) {
mi.parse(v);
pos = mi.value.length; // fix case: mask with prefix + call .clearValue()
} else {
const r = mi.handleInput(e);
declinedAdd = r.declinedAdd;
pos = r.position;
}
if (declinedAdd) {
this.declineInput(pos, mi.value); // fix when ###: "12|" + "3b" => 123|
} else if (el.value !== mi.value) {
el.value = mi.value;
document.activeElement === el && el.setSelectionRange(pos, pos); // without checking on focus setSelectionRange sets focus on Safari
}
isFocused && this.renderMaskHolder(this._opts.maskholder, mi.leftLength - declinedAdd);
return mi.value;
}
/** Add/update maskholder or skip if it's not defined */
private renderMaskHolder(text: string | false | undefined | null, leftLength: number): void {
if (!text) {
return;
}
if (!this.$refMaskholder) {
const m = document.createElement("span");
m.setAttribute("aria-hidden", "true");
m.setAttribute("maskholder", "");
m.appendChild(document.createElement("i"));
m.append("");
this.$refInput.parentElement!.prepend(m);
this.$refMaskholder = m;
}
this.$refMaskholder.firstChild!.textContent = (this._opts.prefix || "") + this.$refInput.value;
this.$refMaskholder.lastChild!.textContent = text.substring(text.length - leftLength);
}
#declineInputEnd?: () => void;
/** Make undo for input after 100ms when user types not allowed chars
* point nextCaret for custom undo value
* @tutorial Troubleshooting
* * declineInput doesn't trigger beforeinput & input events (do it manually if required) */
protected declineInput(nextCaret?: number, nextValue?: string): void {
if (!this._beforeSnap) {
return;
}
const { v, pos } = TextHistory.historyFromSnapshot(this._beforeSnap);
nextCaret ??= pos;
nextValue ??= v;
delete this._beforeSnap;
const isChanged = v !== nextValue;
isChanged && nextValue != null && this._refHistory?.save(v, nextValue); // update history if last value is different
this.#declineInputEnd = (): void => {
this.#declineInputEnd = undefined;
clearTimeout(t);
this.$refInput.value = nextValue!;
this.$refInput.setSelectionRange(nextCaret!, nextCaret!);
this.refMask && this.renderMaskHolder(this._opts.maskholder, this.refMask.leftLength);
this.renderPostfix(this._opts.postfix);
v === nextValue && this._refHistory?.removeLast();
};
const t = setTimeout(this.#declineInputEnd, 100);
}
protected override setValue(v: ValueType | undefined, reason: SetValueReasons, skipInput = false): boolean | null {
!skipInput && this.setInputValue(v as string, reason);
const isChanged = super.setValue(v, reason);
this._isValid !== false && this.goHideError();
return isChanged;
}
/** Called to update/reset value for <input/> */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected setInputValue(v: string, reason: SetValueReasons): void {
this._inputError && this.goHideError(); // after focusLost value resets to prev valid but message left: combobox controls
delete this._inputError;
const prev = this.$refInput.value;
const str = v != null ? ((v as any).toString() as string) : "";
this.$refInput.value = str;
// possible when element $initValue changed but element isn't rendered yet
if (this.$isReady) {
this._opts.mask && this.maskInputProcess(null);
str !== prev && this._refHistory?.save(prev, this.$refInput.value);
this.renderPostfix(this._opts.postfix);
}
}
protected override setClearState(): ValueType | undefined {
const next = super.setClearState();
if (this.$refBtnClear) {
this.$refBtnClear.setAttribute("clear", this.#ctr.$isEmpty(next) ? "" : "back");
}
return next;
}
override focus(): boolean {
if (this.$isDisabled) {
return false;
}
this.$refInput.focus();
return document.activeElement === this.$refInput;
}
}
customElements.define(tagName, WUPTextControl);
// todo example how to create built-in dropdown before the main input (like phone-number with ability to select countryCode)
// gotInput > setMask > parseValue >... setValue ....> toString > setInput > setMask