-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number.ts
450 lines (413 loc) · 14.3 KB
/
number.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
/* eslint-disable max-classes-per-file */
import onScroll from "../helpers/onScroll";
import { mathFixFP, onEvent } from "../indexHelpers";
import localeInfo from "../objects/localeInfo";
import WUPBaseControl, { SetValueReasons } from "./baseControl";
import WUPTextControl from "./text";
const tagName = "wup-num";
declare global {
namespace WUP.Number {
interface Format {
/** Decimal separator; for number 123.4 it's dot
* @see {@link localeInfo.sepDecimal} */
sepDecimal?: string;
/** Thousands separator; for number 1,234.5 it's comma
* @see {@link localeInfo.sep1000} */
sep1000?: string;
/** Maximum displayed fraction digits; for 123.45 it's 2
* @defaultValue 0 */
maxDecimal?: number;
/** Minimun displayed fraction digits; if pointed 2 then 123.4 goes to 123.40
* @defaultValue 0 */
minDecimal?: number;
}
interface EventMap extends WUP.BaseControl.EventMap {}
interface ValidityMap extends WUP.Text.ValidityMap {
/** If $value < pointed shows message 'Min value {x}` */
min: number;
/** If $value < pointed shows message 'Max value {x}` */
max: number;
}
interface NewOptions {
/** String representation of displayed value
* @defaultValue no-decimal and separators from localeInfo */
format: Format | null;
/** Multiply value to store value different from text-value
* @example point 0.01 when need to cast text value `100` to 1 (user sees `100` but stored 1)
* @defaultValue 1 */
scale: number;
/** Shift value to store value different from text-value
* @example point 20 when need to cast text value `100` to 120 (user sees `100` but stored 120)
* @defaultValue 0 */
offset: number;
}
interface TextAnyOptions<T = any, VM = ValidityMap> extends WUP.Text.Options<T, VM> {}
interface Options<T = number, VM extends ValidityMap = ValidityMap> extends TextAnyOptions<T, VM>, NewOptions {}
interface JSXProps<C = WUPNumberControl> extends WUP.Text.JSXProps<C>, WUP.Base.OnlyNames<NewOptions> {
/** String representation of displayed value
* Point Global reference to object @see {@link Format}
* @example
* ```js
* window.format = {};
* <wup-number w-items="window.format"></wup-number>
* ```
* @defaultValue no-decimal and separators from localeInfo */
"w-format"?: string; // NiceToHave: parse from string
"w-scale"?: number;
"w-offset"?: number;
"w-initValue"?: number;
}
}
interface HTMLElementTagNameMap {
[tagName]: WUPNumberControl; // add element to document.createElement
}
}
declare module "react" {
namespace JSX {
interface IntrinsicElements {
/** Form-control with number input
* @see {@link WUPNumberControl} */
[tagName]: WUP.Base.ReactHTML<WUPNumberControl> & WUP.Number.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 number input
* @see {@link WUPNumberControl} */
[tagName]: HTMLAttributes<WUPNumberControl> & WUP.Number.JSXProps; // add element to tsx/jsx intellisense (preact)
}
}
}
abstract class TextAnyControl<
ValueType,
TOptions extends WUP.Number.TextAnyOptions,
EventMap extends WUP.Text.EventMap
> extends WUPTextControl<ValueType, TOptions, EventMap> {}
/** Form-control with number-input
* @see demo {@link https://yegorich555.github.io/web-ui-pack/control/number}
* @example
const el = document.createElement("wup-num");
el.$options.name = "number";
el.$options.validations = {
min: 1,
max: 1000,
};
const form = document.body.appendChild(document.createElement("wup-form"));
form.appendChild(el);
// or HTML
<wup-form>
<wup-num w-name="number" w-validations="myValidations"/>
</wup-form>;
* @see {@link WUPTextControl} */
export default class WUPNumberControl<
ValueType = number,
TOptions extends WUP.Number.Options = WUP.Number.Options,
EventMap extends WUP.Number.EventMap = WUP.Number.EventMap
> extends TextAnyControl<ValueType, TOptions, EventMap> {
#ctr = this.constructor as typeof WUPNumberControl;
/** Default options - applied to every element. Change it to configure default behavior */
static $defaults: WUP.Number.Options = {
...(WUPTextControl.$defaults as WUP.Number.TextAnyOptions<any, any>),
validationRules: {
...WUPBaseControl.$defaults.validationRules,
min: (v, setV, c) =>
(v == null || v < setV) && __wupln(`Min value is ${(c as WUPNumberControl).valueToInput(setV)}`, "validation"),
max: (v, setV, c) =>
(v == null || v > setV) && __wupln(`Max value is ${(c as WUPNumberControl).valueToInput(setV)}`, "validation"),
},
format: null,
scale: 1,
offset: 0,
};
/** Custom number parsing: better Number.parse because ignores wrong chars + depends format */
static $parse(s: string, format: Required<WUP.Number.Format>): number | undefined {
let v: number | undefined = 0;
let ok = false;
let dec: number | null = null;
let decLn = 1;
let decI = 0;
const f = format;
for (let i = 0; i < s.length; ++i) {
const ascii = s.charCodeAt(i);
const num = ascii - 48;
if (num >= 0 && num <= 9) {
ok = true;
if (dec === null) {
v = v * 10 + num;
} else if (f.maxDecimal >= ++decI) {
dec = dec * 10 + num;
decLn *= 10;
}
} else if (ascii === f.sepDecimal.charCodeAt(0)) {
// WARN: expected sepDecimal is single char
dec = 0;
}
}
if (dec) {
v += dec / decLn;
}
if (!ok) {
v = undefined; // case impossible but maybe...
} else if (s.charCodeAt(0) === 45) {
v *= -1; // case: "-123"
}
return v;
}
static $stringify(v: number | undefined | null, format: Required<WUP.Number.Format>): string {
if (v == null) {
return "";
}
// if (this._opts.mask) {
// return (v as any).toString();
// }
// eslint-disable-next-line prefer-const
let [int, dec] = (v as any).toString().split(".");
const f = format;
if (f.sep1000) {
const to = (v as number)! > 0 ? 0 : 1;
for (let i = int.length - 3; i > to; i -= 3) {
int = `${int.substring(0, i)}${f.sep1000}${int.substring(i)}`;
}
}
if (dec || f.minDecimal || f.maxDecimal) {
dec = dec === undefined ? "" : dec.substring(0, Math.min(f.maxDecimal, dec.length));
dec += "0".repeat(Math.max(f.minDecimal - dec.length, 0));
if (dec.length) {
return int + f.sepDecimal + dec;
}
}
return int;
}
/** Returns $options.format joined with defaults */
get $format(): Required<WUP.Number.Format> {
const f = this._opts.format;
return {
sepDecimal: localeInfo.sepDecimal,
sep1000: localeInfo.sep1000,
...f,
maxDecimal: f?.maxDecimal ?? f?.minDecimal ?? 0,
minDecimal: f?.minDecimal ?? 0,
};
}
// WARN usage format #.### impossible because unclear what sepDec/sep100 and what if user wants only limit decimal part
valueToInput(v: ValueType | undefined, skipScaling?: boolean): string {
if (v == null) {
return "";
}
if (!skipScaling) {
const { scale, offset } = this._opts;
(v as number) /= scale || 1;
(v as number) += offset || 0;
(v as number) = mathFixFP(v as number); // WARN: 95 + scale: 0.01 => need avoid 0.9500000000000001
}
if (this._opts.mask) {
return (v as any).toString();
}
return this.#ctr.$stringify(v as number, this.$format);
}
override parse(text: string): ValueType | undefined {
const v = Number(text);
if (!text || Number.isNaN(v)) {
return undefined;
}
return v as any;
}
override canParseInput(text: string): boolean {
const f = this.$format;
if (f.maxDecimal > 0 && text.endsWith(f.sepDecimal)) {
return false; // case "4.|" - use must able to type '.'
}
return true;
}
override parseInput(text: string): ValueType | undefined {
let v = this.#ctr.$parse(text, this.$format);
if (v != null && (v! > Number.MAX_SAFE_INTEGER || v! < Number.MIN_SAFE_INTEGER)) {
this.declineInput(); // decline looks better validation "Out of range"
throw new RangeError("Out of range");
// return v as any;
}
const rawValue = v;
if (v != null) {
const { scale, offset } = this._opts;
v -= offset || 0;
v = mathFixFP(v * (scale || 1)); // WARN: 95 + scale: 0.01 => need avoid 0.9500000000000001
}
if (!this._opts.mask) {
// otherwise it conflicts with mask
const next = this.#ctr.$stringify(rawValue, this.$format);
const hasDeclined = this._canShowDeclined && text.length > next.length;
if (hasDeclined && next === this.#ctr.$stringify(this.$value as number, this.$format)) {
// WARN: don't compare v === this.$value because $value=4.567 but format can be 4.56
this.declineInput();
} else if (text !== next) {
const el = this.$refInput;
// fix cursor position
const pos = el.selectionStart || 0;
let dp = 0;
for (let i = 0, k = 0; k < pos && i < next.length; ++i, ++k) {
const ascii = text.charCodeAt(k);
if (!(ascii >= 48 && ascii <= 57)) {
--i;
--dp;
} else if (next[i] !== text[k]) {
++dp;
--k;
}
}
// el.value = next;
this.setInputValue(v as any, SetValueReasons.userInput); // WARN: it calls valueToInput again
const end = pos + dp;
el.setSelectionRange(end, end);
}
}
return v as any;
}
// @ts-expect-error - because expected string
protected override setInputValue(v: ValueType | undefined, reason: SetValueReasons): void {
const txt = this.valueToInput(v);
super.setInputValue(txt, reason);
}
protected override renderControl(): void {
super.renderControl();
this.$refInput.setAttribute("role", "spinbutton");
}
protected override gotChanges(propsChanged: Array<keyof WUP.Number.Options> | null): void {
super.gotChanges(propsChanged as any);
if ((!propsChanged && this._opts.format) || propsChanged?.includes("format")) {
this.setInputValue(this.$value, SetValueReasons.userInput);
}
}
protected override gotBeforeInput(e: WUP.Text.GotInputEvent): void {
super.gotBeforeInput(e);
if (!this._opts.mask) {
const el = e.target;
let pos = el.selectionStart || 0;
if (pos === el.selectionEnd) {
let isBefore = false;
switch (e!.inputType) {
case "deleteContentBackward":
--pos;
isBefore = true;
// eslint-disable-next-line no-fallthrough
case "deleteContentForward":
if (el.value[pos] === this.$format.sep1000) {
pos += isBefore ? 0 : 1; // case "1|,234" + Delete => 1|34
el.setSelectionRange(pos, pos);
}
break;
default:
break;
}
}
}
}
private _canShowDeclined?: boolean;
protected override gotInput(e: WUP.Text.GotInputEvent): void {
if (!this._opts.mask) {
switch (e!.inputType) {
case "insertText":
case "insertFromPaste":
this._canShowDeclined = true;
break;
default:
delete this._canShowDeclined;
break;
}
}
super.gotInput(e);
}
protected override gotFocus(ev: FocusEvent): Array<() => void> {
const r = super.gotFocus(ev);
this.$refInput.setAttribute("inputmode", "numeric"); // otherwise textControl removes it if mask isn't applied
r.push(
onScroll(
this, //
(v) => this.gotIncrement(-1 * v),
{ skip: () => this.$isReadOnly || this.$isDisabled }
)
); // allow inc/dec via scroll/swipe
this.style.overflow = ""; // disable inline-style from onScroll helper
r.push(
onEvent(
this,
"keyup",
(e) => {
if (!e.altKey) {
delete this._isAltDown;
e.key === "Alt" && this._wasInc && e.preventDefault(); // otherwise focus moves to browser
delete this._wasInc;
}
if (!e.shiftKey) delete this._isShiftDown;
if (!e.ctrlKey) delete this._isCtrlDown;
},
{ passive: false }
)
);
r.push(() => {
delete this._wasInc;
delete this._isAltDown;
delete this._isShiftDown;
delete this._isCtrlDown;
});
return r;
}
/** To prevent focus to browser panel by Alt key */
_wasInc?: boolean;
_isAltDown?: true;
_isShiftDown?: true;
_isCtrlDown?: true;
protected override gotKeyDown(e: KeyboardEvent): void {
super.gotKeyDown(e);
if (e.altKey) this._isAltDown = true;
if (e.shiftKey) this._isShiftDown = true;
if (e.ctrlKey) this._isCtrlDown = true;
let v = 0;
switch (e.key) {
case "ArrowUp":
++v;
break;
case "ArrowDown":
--v;
break;
default:
break;
}
if (v) {
e.preventDefault();
this.gotIncrement(v);
}
}
/** Called when user tries to increment/decrement value (via ArrowKeys/Mouse/Swipe) */
protected gotIncrement(dval: number): void {
this._wasInc = true;
if (this._isAltDown) {
dval *= 0.1;
if (this.$format.maxDecimal < 1) {
return; // don't allow decimal increment
}
} else if (this._isShiftDown) dval *= 10;
else if (this._isCtrlDown) dval *= 100;
const tv = this.$refInput.value;
const v = (tv && this.#ctr.$parse(tv, this.$format)) || 0;
const hasFloat = this._isAltDown || v % 1 !== 0;
const next = hasFloat ? mathFixFP(v + dval) : v + dval;
const el = this.$refInput;
const inputType = dval > 0 ? "_inc" : "_dec";
const data = this.valueToInput(next as any, true);
setTimeout(() => {
const isPrevented = !el.dispatchEvent(
new InputEvent("beforeinput", { inputType, data, bubbles: true, cancelable: true })
);
if (!isPrevented) {
el.value = data;
el.dispatchEvent(new InputEvent("input", { inputType, bubbles: true }));
}
});
}
}
customElements.define(tagName, WUPNumberControl);