HTMLInputElement-impl.js
36.2 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
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
"use strict";
const DOMException = require("domexception/webidl2js-wrapper");
const FileList = require("../generated/FileList");
const Decimal = require("decimal.js");
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const idlUtils = require("../generated/utils");
const DefaultConstraintValidationImpl =
require("../constraint-validation/DefaultConstraintValidation-impl").implementation;
const ValidityState = require("../generated/ValidityState");
const { mixin } = require("../../utils");
const { domSymbolTree, cloningSteps } = require("../helpers/internal-constants");
const { getLabelsForLabelable, formOwner } = require("../helpers/form-controls");
const { fireAnEvent } = require("../helpers/events");
const {
isDisabled,
isValidEmailAddress,
isValidAbsoluteURL,
sanitizeValueByType
} = require("../helpers/form-controls");
const {
asciiCaseInsensitiveMatch,
asciiLowercase,
parseFloatingPointNumber,
splitOnCommas
} = require("../helpers/strings");
const { isDate } = require("../helpers/dates-and-times");
const {
convertStringToNumberByType,
convertStringToDateByType,
serializeDateByType,
convertNumberToStringByType
} = require("../helpers/number-and-date-inputs");
const filesSymbol = Symbol("files");
// https://html.spec.whatwg.org/multipage/input.html#attr-input-type
const inputAllowedTypes = new Set([
"hidden", "text", "search", "tel", "url", "email", "password", "date",
"month", "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
"file", "submit", "image", "reset", "button"
]);
// https://html.spec.whatwg.org/multipage/input.html#concept-input-apply
const variableLengthSelectionAllowedTypes = new Set(["text", "search", "url", "tel", "password"]);
const numericTypes = new Set(["date", "month", "week", "time", "datetime-local", "number", "range"]);
const applicableTypesForIDLMember = {
valueAsDate: new Set(["date", "month", "week", "time"]),
valueAsNumber: numericTypes,
select: new Set([
"text", "search", "url", "tel", "email", "password", "date", "month", "week",
"time", "datetime-local", "number", "color", "file"
]),
selectionStart: variableLengthSelectionAllowedTypes,
selectionEnd: variableLengthSelectionAllowedTypes,
selectionDirection: variableLengthSelectionAllowedTypes,
setRangeText: variableLengthSelectionAllowedTypes,
setSelectionRange: variableLengthSelectionAllowedTypes,
stepDown: numericTypes,
stepUp: numericTypes
};
const lengthPatternSizeTypes = new Set(["text", "search", "url", "tel", "email", "password"]);
const readonlyTypes =
new Set([...lengthPatternSizeTypes, "date", "month", "week", "time", "datetime-local", "number"]);
const applicableTypesForContentAttribute = {
list: new Set(["text", "search", "url", "tel", "email", ...numericTypes, "color"]),
max: numericTypes,
maxlength: lengthPatternSizeTypes,
min: numericTypes,
minlength: lengthPatternSizeTypes,
multiple: new Set(["email", "file"]),
pattern: lengthPatternSizeTypes,
readonly: readonlyTypes,
required: new Set([...readonlyTypes, "checkbox", "radio", "file"]),
step: numericTypes
};
const valueAttributeDefaultMode = new Set(["hidden", "submit", "image", "reset", "button"]);
const valueAttributeDefaultOnMode = new Set(["checkbox", "radio"]);
function valueAttributeMode(type) {
if (valueAttributeDefaultMode.has(type)) {
return "default";
}
if (valueAttributeDefaultOnMode.has(type)) {
return "default/on";
}
if (type === "file") {
return "filename";
}
return "value";
}
function getTypeFromAttribute(typeAttribute) {
if (typeof typeAttribute !== "string") {
return "text";
}
const type = asciiLowercase(typeAttribute);
return inputAllowedTypes.has(type) ? type : "text";
}
class HTMLInputElementImpl extends HTMLElementImpl {
constructor(globalObject, args, privateData) {
super(globalObject, args, privateData);
this._selectionStart = this._selectionEnd = 0;
this._selectionDirection = "none";
this._value = "";
this._dirtyValue = false;
this._checkedness = false;
this._dirtyCheckedness = false;
this._preCheckedRadioState = null;
this.indeterminate = false;
this._customValidityErrorMessage = "";
this._labels = null;
this._hasActivationBehavior = true;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
get _convertStringToNumber() {
return convertStringToNumberByType[this.type];
}
get _convertNumberToString() {
return convertNumberToStringByType[this.type];
}
get _convertDateToString() {
return serializeDateByType[this.type];
}
get _convertStringToDate() {
return convertStringToDateByType[this.type];
}
_isStepAligned(v) {
return new Decimal(v).minus(this._stepBase)
.modulo(this._allowedValueStep)
.isZero();
}
// Returns a Decimal.
_stepAlign(v, roundUp) {
const allowedValueStep = this._allowedValueStep;
const stepBase = this._stepBase;
return new Decimal(v).minus(stepBase)
.toNearest(allowedValueStep, roundUp ? Decimal.ROUND_UP : Decimal.ROUND_DOWN)
.add(stepBase);
}
// For <input>, https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fe-value
// is a simple value that is gotten and set, not computed.
_getValue() {
return this._value;
}
_legacyPreActivationBehavior() {
// The spec says we should check this._mutable here, but browsers don't seem to implement this behavior. See
// https://github.com/whatwg/html/issues/3239.
if (this.type === "checkbox") {
this.checked = !this.checked;
} else if (this.type === "radio") {
this._preCheckedRadioState = this.checked;
this.checked = true;
}
}
_legacyCanceledActivationBehavior() {
// The spec says we should check this._mutable here, but browsers don't seem to implement this behavior. See
// https://github.com/whatwg/html/issues/3239.
if (this.type === "checkbox") {
this.checked = !this.checked;
} else if (this.type === "radio") {
if (this._preCheckedRadioState !== null) {
this.checked = this._preCheckedRadioState;
this._preCheckedRadioState = null;
}
}
}
_activationBehavior() {
if (!this._mutable) {
return;
}
const { form } = this;
if (this.type === "checkbox" || (this.type === "radio" && !this._preCheckedRadioState)) {
fireAnEvent("input", this, undefined, { bubbles: true });
fireAnEvent("change", this, undefined, { bubbles: true });
} else if (form && this.type === "submit") {
form._doSubmit();
} else if (form && this.type === "reset") {
form._doReset();
}
}
_attrModified(name, value, oldVal) {
const wrapper = idlUtils.wrapperForImpl(this);
if (!this._dirtyValue && name === "value") {
this._value = sanitizeValueByType(this, wrapper.defaultValue);
}
if (!this._dirtyCheckedness && name === "checked") {
this._checkedness = wrapper.defaultChecked;
if (this._checkedness) {
this._removeOtherRadioCheckedness();
}
}
if (name === "name" || name === "type") {
if (this._checkedness) {
this._removeOtherRadioCheckedness();
}
}
if (name === "type") {
const prevType = getTypeFromAttribute(oldVal);
const curType = getTypeFromAttribute(value);
// When an input element's type attribute changes state…
if (prevType !== curType) {
const prevValueMode = valueAttributeMode(prevType);
const curValueMode = valueAttributeMode(curType);
if (prevValueMode === "value" && this._value !== "" &&
(curValueMode === "default" || curValueMode === "default/on")) {
this.setAttributeNS(null, "value", this._value);
} else if (prevValueMode !== "value" && curValueMode === "value") {
this._value = this.getAttributeNS(null, "value") || "";
this._dirtyValue = false;
} else if (prevValueMode !== "filename" && curValueMode === "filename") {
this._value = "";
}
this._signalATypeChange();
this._value = sanitizeValueByType(this, this._value);
const previouslySelectable = this._idlMemberApplies("setRangeText", prevType);
const nowSelectable = this._idlMemberApplies("setRangeText", curType);
if (!previouslySelectable && nowSelectable) {
this._selectionStart = 0;
this._selectionEnd = 0;
this._selectionDirection = "none";
}
}
}
super._attrModified.apply(this, arguments);
}
// https://html.spec.whatwg.org/multipage/input.html#signal-a-type-change
_signalATypeChange() {
if (this._checkedness) {
this._removeOtherRadioCheckedness();
}
}
_formReset() {
const wrapper = idlUtils.wrapperForImpl(this);
this._value = sanitizeValueByType(this, wrapper.defaultValue);
this._dirtyValue = false;
this._checkedness = wrapper.defaultChecked;
this._dirtyCheckedness = false;
if (this._checkedness) {
this._removeOtherRadioCheckedness();
}
}
_changedFormOwner() {
if (this._checkedness) {
this._removeOtherRadioCheckedness();
}
}
get _otherRadioGroupElements() {
const wrapper = idlUtils.wrapperForImpl(this);
const root = this._radioButtonGroupRoot;
if (!root) {
return [];
}
const result = [];
const descendants = domSymbolTree.treeIterator(root);
for (const candidate of descendants) {
if (candidate._radioButtonGroupRoot !== root) {
continue;
}
const candidateWrapper = idlUtils.wrapperForImpl(candidate);
if (!candidateWrapper.name || candidateWrapper.name !== wrapper.name) {
continue;
}
if (candidate !== this) {
result.push(candidate);
}
}
return result;
}
_removeOtherRadioCheckedness() {
for (const radioGroupElement of this._otherRadioGroupElements) {
radioGroupElement._checkedness = false;
}
}
get _radioButtonGroupRoot() {
const wrapper = idlUtils.wrapperForImpl(this);
if (this.type !== "radio" || !wrapper.name) {
return null;
}
let e = domSymbolTree.parent(this);
while (e) {
// root node of this home sub tree
// or the form element we belong to
if (!domSymbolTree.parent(e) || e.nodeName.toUpperCase() === "FORM") {
return e;
}
e = domSymbolTree.parent(e);
}
return null;
}
_someInRadioGroup(name) {
if (this[name]) {
return true;
}
return this._otherRadioGroupElements.some(radioGroupElement => radioGroupElement[name]);
}
get _mutable() {
return !isDisabled(this) && !this._hasAttributeAndApplies("readonly");
}
get labels() {
return getLabelsForLabelable(this);
}
get form() {
return formOwner(this);
}
get checked() {
return this._checkedness;
}
set checked(checked) {
this._checkedness = Boolean(checked);
this._dirtyCheckedness = true;
if (this._checkedness) {
this._removeOtherRadioCheckedness();
}
}
get value() {
switch (valueAttributeMode(this.type)) {
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
case "value":
return this._getValue();
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
case "default": {
const attr = this.getAttributeNS(null, "value");
return attr !== null ? attr : "";
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
case "default/on": {
const attr = this.getAttributeNS(null, "value");
return attr !== null ? attr : "on";
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
case "filename":
return this.files.length ? "C:\\fakepath\\" + this.files[0].name : "";
default:
throw new Error("jsdom internal error: unknown value attribute mode");
}
}
set value(val) {
switch (valueAttributeMode(this.type)) {
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
case "value": {
const oldValue = this._value;
this._value = sanitizeValueByType(this, val);
this._dirtyValue = true;
if (oldValue !== this._value) {
this._selectionStart = this._selectionEnd = this._getValueLength();
this._selectionDirection = "none";
}
break;
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
case "default":
case "default/on":
this.setAttributeNS(null, "value", val);
break;
// https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
case "filename":
if (val === "") {
this.files.length = 0;
} else {
throw DOMException.create(this._globalObject, [
"This input element accepts a filename, which may only be programmatically set to the empty string.",
"InvalidStateError"
]);
}
break;
default:
throw new Error("jsdom internal error: unknown value attribute mode");
}
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
get valueAsDate() {
if (!this._idlMemberApplies("valueAsDate")) {
return null;
}
const window = this._ownerDocument._defaultView;
const convertedValue = this._convertStringToDate(this._value);
if (convertedValue instanceof Date) {
return new window.Date(convertedValue.getTime());
}
return null;
}
set valueAsDate(v) {
if (!this._idlMemberApplies("valueAsDate")) {
throw DOMException.create(this._globalObject, [
"Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date " +
"values.",
"InvalidStateError"
]);
}
if (v !== null && !isDate(v)) {
throw new TypeError("Failed to set the 'valueAsDate' property on 'HTMLInputElement': The provided value is " +
"not a Date.");
}
if (v === null || isNaN(v)) {
this._value = "";
}
this._value = this._convertDateToString(v);
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
get valueAsNumber() {
if (!this._idlMemberApplies("valueAsNumber")) {
return NaN;
}
const parsedValue = this._convertStringToNumber(this._value);
return parsedValue !== null ? parsedValue : NaN;
}
set valueAsNumber(v) {
if (!isFinite(v)) {
throw new TypeError("Failed to set infinite value as Number");
}
if (!this._idlMemberApplies("valueAsNumber")) {
throw DOMException.create(this._globalObject, [
"Failed to set the 'valueAsNumber' property on 'HTMLInputElement': This input element does not support " +
"Number values.",
"InvalidStateError"
]);
}
this._value = this._convertNumberToString(v);
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
_stepUpdate(n, isUp) {
const methodName = isUp ? "stepUp" : "stepDown";
if (!this._idlMemberApplies(methodName)) {
throw DOMException.create(this._globalObject, [
`Failed to invoke '${methodName}' method on 'HTMLInputElement': ` +
"This input element does not support Number values.",
"InvalidStateError"
]);
}
const allowedValueStep = this._allowedValueStep;
if (allowedValueStep === null) {
throw DOMException.create(this._globalObject, [
`Failed to invoke '${methodName}' method on 'HTMLInputElement': ` +
"This input element does not support value step.",
"InvalidStateError"
]);
}
const min = this._minimum;
const max = this._maximum;
if (min !== null && max !== null) {
if (min > max) {
return;
}
const candidateStepValue = this._stepAlign(Decimal.add(min, allowedValueStep), /* roundUp = */ false);
if (candidateStepValue.lt(min) || candidateStepValue.gt(max)) {
return;
}
}
let value = 0;
try {
value = this.valueAsNumber;
if (isNaN(value)) { // Empty value is parsed as NaN.
value = 0;
}
} catch (error) {
// Step 5. Default value is 0.
}
value = new Decimal(value);
const valueBeforeStepping = value;
if (!this._isStepAligned(value)) {
value = this._stepAlign(value, /* roundUp = */ isUp);
} else {
let delta = Decimal.mul(n, allowedValueStep);
if (!isUp) {
delta = delta.neg();
}
value = value.add(delta);
}
if (min !== null && value.lt(min)) {
value = this._stepAlign(min, /* roundUp = */ true);
}
if (max !== null && value.gt(max)) {
value = this._stepAlign(max, /* roundUp = */ false);
}
if (isUp ? value.lt(valueBeforeStepping) : value.gt(valueBeforeStepping)) {
return;
}
this._value = this._convertNumberToString(value.toNumber());
}
stepDown(n = 1) {
return this._stepUpdate(n, false);
}
stepUp(n = 1) {
return this._stepUpdate(n, true);
}
get files() {
if (this.type === "file") {
this[filesSymbol] = this[filesSymbol] || FileList.createImpl(this._globalObject);
} else {
this[filesSymbol] = null;
}
return this[filesSymbol];
}
set files(value) {
if (this.type === "file" && value !== null) {
this[filesSymbol] = value;
}
}
get type() {
const typeAttribute = this.getAttributeNS(null, "type");
return getTypeFromAttribute(typeAttribute);
}
set type(type) {
this.setAttributeNS(null, "type", type);
}
_dispatchSelectEvent() {
fireAnEvent("select", this, undefined, { bubbles: true, cancelable: true });
}
_getValueLength() {
return typeof this.value === "string" ? this.value.length : 0;
}
select() {
if (!this._idlMemberApplies("select")) {
return;
}
this._selectionStart = 0;
this._selectionEnd = this._getValueLength();
this._selectionDirection = "none";
this._dispatchSelectEvent();
}
get selectionStart() {
if (!this._idlMemberApplies("selectionStart")) {
return null;
}
return this._selectionStart;
}
set selectionStart(start) {
if (!this._idlMemberApplies("selectionStart")) {
throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]);
}
this.setSelectionRange(start, Math.max(start, this._selectionEnd), this._selectionDirection);
}
get selectionEnd() {
if (!this._idlMemberApplies("selectionEnd")) {
return null;
}
return this._selectionEnd;
}
set selectionEnd(end) {
if (!this._idlMemberApplies("selectionEnd")) {
throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]);
}
this.setSelectionRange(this._selectionStart, end, this._selectionDirection);
}
get selectionDirection() {
if (!this._idlMemberApplies("selectionDirection")) {
return null;
}
return this._selectionDirection;
}
set selectionDirection(dir) {
if (!this._idlMemberApplies("selectionDirection")) {
throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]);
}
this.setSelectionRange(this._selectionStart, this._selectionEnd, dir);
}
setSelectionRange(start, end, dir) {
if (!this._idlMemberApplies("setSelectionRange")) {
throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]);
}
this._selectionEnd = Math.min(end, this._getValueLength());
this._selectionStart = Math.min(start, this._selectionEnd);
this._selectionDirection = dir === "forward" || dir === "backward" ? dir : "none";
this._dispatchSelectEvent();
}
setRangeText(repl, start, end, selectionMode = "preserve") {
if (!this._idlMemberApplies("setRangeText")) {
throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]);
}
if (arguments.length < 2) {
start = this._selectionStart;
end = this._selectionEnd;
} else if (start > end) {
throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]);
}
start = Math.min(start, this._getValueLength());
end = Math.min(end, this._getValueLength());
const val = this.value;
let selStart = this._selectionStart;
let selEnd = this._selectionEnd;
this.value = val.slice(0, start) + repl + val.slice(end);
const newEnd = start + this.value.length;
if (selectionMode === "select") {
this.setSelectionRange(start, newEnd);
} else if (selectionMode === "start") {
this.setSelectionRange(start, start);
} else if (selectionMode === "end") {
this.setSelectionRange(newEnd, newEnd);
} else { // preserve
const delta = repl.length - (end - start);
if (selStart > end) {
selStart += delta;
} else if (selStart > start) {
selStart = start;
}
if (selEnd > end) {
selEnd += delta;
} else if (selEnd > start) {
selEnd = newEnd;
}
this.setSelectionRange(selStart, selEnd);
}
}
// https://html.spec.whatwg.org/multipage/input.html#the-list-attribute
get list() {
const id = this._getAttributeIfApplies("list");
if (!id) {
return null;
}
const el = this.getRootNode({}).getElementById(id);
if (el && el.localName === "datalist") {
return el;
}
return null;
}
set maxLength(value) {
if (value < 0) {
throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]);
}
this.setAttributeNS(null, "maxlength", String(value));
}
// Reflected IDL attribute does not care about whether the content attribute applies.
get maxLength() {
if (!this.hasAttributeNS(null, "maxlength")) {
return 524288; // stole this from chrome
}
return parseInt(this.getAttributeNS(null, "maxlength"));
}
set minLength(value) {
if (value < 0) {
throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]);
}
this.setAttributeNS(null, "minlength", String(value));
}
get minLength() {
if (!this.hasAttributeNS(null, "minlength")) {
return 0;
}
return parseInt(this.getAttributeNS(null, "minlength"));
}
get size() {
if (!this.hasAttributeNS(null, "size")) {
return 20;
}
return parseInt(this.getAttributeNS(null, "size"));
}
set size(value) {
if (value <= 0) {
throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]);
}
this.setAttributeNS(null, "size", String(value));
}
// https://html.spec.whatwg.org/multipage/input.html#the-min-and-max-attributes
get _minimum() {
let min = this._defaultMinimum;
const attr = this._getAttributeIfApplies("min");
if (attr !== null && this._convertStringToNumber !== undefined) {
const parsed = this._convertStringToNumber(attr);
if (parsed !== null) {
min = parsed;
}
}
return min;
}
get _maximum() {
let max = this._defaultMaximum;
const attr = this._getAttributeIfApplies("max");
if (attr !== null && this._convertStringToNumber !== undefined) {
const parsed = this._convertStringToNumber(attr);
if (parsed !== null) {
max = parsed;
}
}
return max;
}
get _defaultMinimum() {
if (this.type === "range") {
return 0;
}
return null;
}
get _defaultMaximum() {
if (this.type === "range") {
return 100;
}
return null;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-step
get _allowedValueStep() {
if (!this._contentAttributeApplies("step")) {
return null;
}
const attr = this.getAttributeNS(null, "step");
if (attr === null) {
return this._defaultStep * this._stepScaleFactor;
}
if (asciiCaseInsensitiveMatch(attr, "any")) {
return null;
}
const parsedStep = parseFloatingPointNumber(attr);
if (parsedStep === null || parsedStep <= 0) {
return this._defaultStep * this._stepScaleFactor;
}
return parsedStep * this._stepScaleFactor;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-step-scale
get _stepScaleFactor() {
const dayInMilliseconds = 24 * 60 * 60 * 1000;
switch (this.type) {
case "week":
return 7 * dayInMilliseconds;
case "date":
return dayInMilliseconds;
case "datetime-local":
case "datetime":
case "time":
return 1000;
}
return 1;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-step-default
get _defaultStep() {
if (this.type === "datetime-local" || this.type === "datetime" || this.type === "time") {
return 60;
}
return 1;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-min-zero
get _stepBase() {
if (this._hasAttributeAndApplies("min")) {
const min = this._convertStringToNumber(this.getAttributeNS(null, "min"));
if (min !== null) {
return min;
}
}
if (this.hasAttributeNS(null, "value")) {
const value = this._convertStringToNumber(this.getAttributeNS(null, "value"));
if (value !== null) {
return value;
}
}
if (this._defaultStepBase !== null) {
return this._defaultStepBase;
}
return 0;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-step-default-base
get _defaultStepBase() {
if (this.type === "week") {
// The start of week 1970-W01
return -259200000;
}
return null;
}
// https://html.spec.whatwg.org/multipage/input.html#common-input-element-attributes
// When an attribute doesn't apply to an input element, user agents must ignore the attribute.
_contentAttributeApplies(attribute) {
return applicableTypesForContentAttribute[attribute].has(this.type);
}
_hasAttributeAndApplies(attribute) {
return this._contentAttributeApplies(attribute) && this.hasAttributeNS(null, attribute);
}
_getAttributeIfApplies(attribute) {
if (this._contentAttributeApplies(attribute)) {
return this.getAttributeNS(null, attribute);
}
return null;
}
_idlMemberApplies(member, type = this.type) {
return applicableTypesForIDLMember[member].has(type);
}
_barredFromConstraintValidationSpecialization() {
// https://html.spec.whatwg.org/multipage/input.html#hidden-state-(type=hidden)
// https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset)
// https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button)
const willNotValidateTypes = new Set(["hidden", "reset", "button"]);
// https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
const readOnly = this._hasAttributeAndApplies("readonly");
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled
return willNotValidateTypes.has(this.type) || readOnly;
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-required
get _required() {
return this._hasAttributeAndApplies("required");
}
// https://html.spec.whatwg.org/multipage/input.html#has-a-periodic-domain
get _hasAPeriodicDomain() {
return this.type === "time";
}
// https://html.spec.whatwg.org/multipage/input.html#has-a-reversed-range
get _hasAReversedRange() {
return this._hasAPeriodicDomain && this._maximum < this._minimum;
}
get validity() {
if (!this._validity) {
// Constraint validation: When an element has a reversed range, and the result of applying
// the algorithm to convert a string to a number to the string given by the element's value
// is a number, and the number obtained from that algorithm is more than the maximum and less
// than the minimum, the element is simultaneously suffering from an underflow and suffering
// from an overflow.
const reversedRangeSufferingOverUnderflow = () => {
const parsedValue = this._convertStringToNumber(this._value);
return parsedValue !== null && parsedValue > this._maximum && parsedValue < this._minimum;
};
const state = {
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-being-missing
valueMissing: () => {
// https://html.spec.whatwg.org/multipage/input.html#the-required-attribute
// Constraint validation: If the element is required, and its value IDL attribute applies
// and is in the mode value, and the element is mutable, and the element's value is the
// empty string, then the element is suffering from being missing.
//
// Note: As of today, the value IDL attribute always applies.
if (this._required && valueAttributeMode(this.type) === "value" && this._mutable && this._value === "") {
return true;
}
switch (this.type) {
// https://html.spec.whatwg.org/multipage/input.html#checkbox-state-(type=checkbox)
// Constraint validation: If the element is required and its checkedness is
// false, then the element is suffering from being missing.
case "checkbox":
if (this._required && !this._checkedness) {
return true;
}
break;
// https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
// Constraint validation: If an element in the radio button group is required,
// and all of the input elements in the radio button group have a checkedness
// that is false, then the element is suffering from being missing.
case "radio":
if (this._someInRadioGroup("_required") && !this._someInRadioGroup("checked")) {
return true;
}
break;
// https://html.spec.whatwg.org/multipage/input.html#file-upload-state-(type=file)
// Constraint validation: If the element is required and the list of selected files is
// empty, then the element is suffering from being missing.
case "file":
if (this._required && this.files.length === 0) {
return true;
}
break;
}
return false;
},
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-being-too-long
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-maxlength
// jsdom has no way at the moment to emulate a user interaction, so tooLong/tooShort have
// to be set to false.
tooLong: () => false,
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-being-too-short
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-minlength
tooShort: () => false,
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-an-overflow
rangeOverflow: () => {
// https://html.spec.whatwg.org/multipage/input.html#the-min-and-max-attributes
if (this._hasAReversedRange) {
return reversedRangeSufferingOverUnderflow();
}
// Constraint validation: When the element has a maximum and does not have a reversed
// range, and the result of applying the algorithm to convert a string to a number to the
// string given by the element's value is a number, and the number obtained from that
// algorithm is more than the maximum, the element is suffering from an overflow.
if (this._maximum !== null) {
const parsedValue = this._convertStringToNumber(this._value);
if (parsedValue !== null && parsedValue > this._maximum) {
return true;
}
}
return false;
},
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-an-underflow
rangeUnderflow: () => {
// https://html.spec.whatwg.org/multipage/input.html#the-min-and-max-attributes
if (this._hasAReversedRange) {
return reversedRangeSufferingOverUnderflow();
}
// Constraint validation: When the element has a minimum and does not have a reversed
// range, and the result of applying the algorithm to convert a string to a number to the
// string given by the element's value is a number, and the number obtained from that
// algorithm is less than the minimum, the element is suffering from an underflow.
if (this._minimum !== null) {
const parsedValue = this._convertStringToNumber(this._value);
if (parsedValue !== null && parsedValue < this._minimum) {
return true;
}
}
return false;
},
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-a-pattern-mismatch
patternMismatch: () => {
// https://html.spec.whatwg.org/multipage/input.html#the-pattern-attribute
if (this._value === "" || !this._hasAttributeAndApplies("pattern")) {
return false;
}
let regExp;
try {
const pattern = this.getAttributeNS(null, "pattern");
// The pattern attribute should be matched against the entire value, not just any
// subset, so add ^ and $ anchors. But also check the validity of the regex itself
// first.
new RegExp(pattern, "u"); // eslint-disable-line no-new
regExp = new RegExp("^(?:" + pattern + ")$", "u");
} catch (e) {
return false;
}
if (this._hasAttributeAndApplies("multiple")) {
return !splitOnCommas(this._value).every(value => regExp.test(value));
}
return !regExp.test(this._value);
},
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-a-step-mismatch
// https://html.spec.whatwg.org/multipage/input.html#attr-input-step
stepMismatch: () => {
const allowedValueStep = this._allowedValueStep;
if (allowedValueStep === null) {
return false;
}
const number = this._convertStringToNumber(this._value);
return number !== null && !this._isStepAligned(number);
},
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-a-type-mismatch
typeMismatch: () => {
switch (this.type) {
// https://html.spec.whatwg.org/multipage/input.html#url-state-(type=url)
// Constraint validation: While the value of the element is neither the empty string
// nor a valid absolute URL, the element is suffering from a type mismatch.
case "url":
if (this._value !== "" && !isValidAbsoluteURL(this._value)) {
return true;
}
break;
// https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type=email)
// Constraint validation [multiple=false]: While the value of the element is neither the empty
// string nor a single valid e - mail address, the element is suffering from a type mismatch.
// Constraint validation [multiple=true]: While the value of the element is not a valid e-mail address list,
// the element is suffering from a type mismatch.
case "email":
if (this._value !== "" && !isValidEmailAddress(this._getValue(), this.hasAttributeNS(null, "multiple"))) {
return true;
}
break;
}
return false;
}
};
this._validity = ValidityState.createImpl(this._globalObject, [], {
element: this,
state
});
}
return this._validity;
}
[cloningSteps](copy, node) {
copy._value = node._value;
copy._checkedness = node._checkedness;
copy._dirtyValue = node._dirtyValue;
copy._dirtyCheckedness = node._dirtyCheckedness;
}
}
mixin(HTMLInputElementImpl.prototype, DefaultConstraintValidationImpl.prototype);
module.exports = {
implementation: HTMLInputElementImpl
};