@tide-design/components 0.21.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NumberFormatInput/NumberFormatInput.d.ts +7 -3
- package/dist/NumberFormatInput/NumberFormatInput.js +53 -51
- package/dist/NumberFormatInput/hooks/useNumberText.js +79 -0
- package/dist/NumberFormatInput/libs/fieldEdit.js +44 -0
- package/dist/NumberFormatInput/libs/inputGuard.js +140 -0
- package/dist/NumberFormatInput/libs/maskFormatter.js +69 -0
- package/dist/NumberFormatInput/libs/numericFormatter.js +89 -0
- package/dist/NumberFormatInput/types.d.ts +5 -3
- package/package.json +6 -3
- package/dist/NumberFormatInput/components/MaskModeInput.js +0 -22
- package/dist/NumberFormatInput/components/NumericModeInput.js +0 -16
- package/dist/NumberFormatInput/hooks/useNumberCompositionGuard.js +0 -21
|
@@ -11,10 +11,14 @@ export interface NumberFormatInputOwnProps extends NumericFormatOptions {
|
|
|
11
11
|
/** 처음 값(비제어). `value`와 같은 형태다. */
|
|
12
12
|
defaultValue?: number | string | null;
|
|
13
13
|
/**
|
|
14
|
-
* 사용자가 값을 바꾸면 부른다. `value`는 숫자(빈 칸 `null`), `formattedValue`는 화면 글자,
|
|
14
|
+
* 사용자가 값을 바꾸면 객체 하나로 부른다. `value`는 숫자(빈 칸 `null`), `formattedValue`는 화면 글자,
|
|
15
15
|
* `digits`는 숫자만 남긴 문자열이다. 앞자리 0·큰 자릿수(전화·카드번호)는 `digits`를 쓴다.
|
|
16
16
|
*/
|
|
17
|
-
onValueChange?: (
|
|
17
|
+
onValueChange?: (values: {
|
|
18
|
+
value: number | null;
|
|
19
|
+
formattedValue: string;
|
|
20
|
+
digits: string;
|
|
21
|
+
}) => void;
|
|
18
22
|
/** 높이 `sm` 32px, `md` 40px, `lg` 48px. 같은 size의 Input과 같다. 기본값은 `md`다. */
|
|
19
23
|
size?: InputSize;
|
|
20
24
|
/** 오류 상태. `aria-invalid="true"`와 `data-invalid`가 붙는다. Field 값보다 여기 준 값이 이긴다. */
|
|
@@ -31,5 +35,5 @@ export type NumberFormatInputProps = NumberFormatInputModeProps & NumberFormatIn
|
|
|
31
35
|
* `mask` 틀(패턴 모드)을 다룬다. `<input type="text">`이고 Field 안에서 label·설명·오류가 연결된다.
|
|
32
36
|
* Tide props: `mask`, `value`, `defaultValue`, `onValueChange`, `size`, `invalid`, `prefix`, `suffix`, `decimalPlaces`, `fixedDecimalPlaces`, `allowNegative`, `groupStyle`, `groupSeparator`, `decimalSeparator`, `locale` ({@link NumberFormatInputOwnProps}). 나머지는 `<input>` 속성.
|
|
33
37
|
*/
|
|
34
|
-
export declare function NumberFormatInput({ mask, value, defaultValue, onValueChange, prefix, suffix, decimalPlaces, fixedDecimalPlaces, allowNegative, groupStyle, groupSeparator, decimalSeparator, locale, inputMode, ref,
|
|
38
|
+
export declare function NumberFormatInput({ mask, value, defaultValue, onValueChange, prefix, suffix, decimalPlaces, fixedDecimalPlaces, allowNegative, groupStyle, groupSeparator, decimalSeparator, locale, inputMode, ref, onInput, onChange, ...props }: NumberFormatInputProps): ReactElement;
|
|
35
39
|
export {};
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
3
|
import { Input } from "../Input/Input.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { toNumericString } from "./libs/numericFormat.js";
|
|
4
|
+
import { useNumberText } from "./hooks/useNumberText.js";
|
|
5
|
+
import { createInputGuard } from "./libs/inputGuard.js";
|
|
6
|
+
import { createMaskFormatter } from "./libs/maskFormatter.js";
|
|
7
|
+
import { createNumericFormatter } from "./libs/numericFormatter.js";
|
|
9
8
|
import { jsx } from "react/jsx-runtime";
|
|
10
|
-
import {
|
|
9
|
+
import { useMemo } from "react";
|
|
10
|
+
import { useMaskito } from "@maskito/react";
|
|
11
|
+
import { mergeRefs } from "react-aria";
|
|
11
12
|
|
|
12
13
|
// src/NumberFormatInput/NumberFormatInput.tsx
|
|
13
14
|
/**
|
|
@@ -15,56 +16,57 @@ import { useRef } from "react";
|
|
|
15
16
|
* `mask` 틀(패턴 모드)을 다룬다. `<input type="text">`이고 Field 안에서 label·설명·오류가 연결된다.
|
|
16
17
|
* Tide props: `mask`, `value`, `defaultValue`, `onValueChange`, `size`, `invalid`, `prefix`, `suffix`, `decimalPlaces`, `fixedDecimalPlaces`, `allowNegative`, `groupStyle`, `groupSeparator`, `decimalSeparator`, `locale` ({@link NumberFormatInputOwnProps}). 나머지는 `<input>` 속성.
|
|
17
18
|
*/
|
|
18
|
-
function NumberFormatInput({ mask, value, defaultValue, onValueChange, prefix, suffix, decimalPlaces, fixedDecimalPlaces, allowNegative, groupStyle, groupSeparator, decimalSeparator, locale, inputMode, ref,
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
function NumberFormatInput({ mask, value, defaultValue, onValueChange, prefix, suffix, decimalPlaces, fixedDecimalPlaces, allowNegative, groupStyle, groupSeparator, decimalSeparator, locale, inputMode, ref, onInput, onChange, ...props }) {
|
|
20
|
+
const formatterKey = JSON.stringify(mask === void 0 ? {
|
|
21
|
+
prefix,
|
|
22
|
+
suffix,
|
|
23
|
+
decimalPlaces,
|
|
24
|
+
fixedDecimalPlaces,
|
|
25
|
+
allowNegative,
|
|
26
|
+
groupStyle,
|
|
27
|
+
groupSeparator,
|
|
28
|
+
decimalSeparator,
|
|
29
|
+
locale
|
|
30
|
+
} : { mask });
|
|
31
|
+
const formatter = useMemo(() => {
|
|
32
|
+
const options = JSON.parse(formatterKey);
|
|
33
|
+
return options.mask === void 0 ? createNumericFormatter(options) : createMaskFormatter(options.mask);
|
|
34
|
+
}, [formatterKey]);
|
|
35
|
+
const text = useNumberText({
|
|
36
|
+
formatter,
|
|
37
|
+
formatterKey,
|
|
38
|
+
value,
|
|
39
|
+
defaultValue,
|
|
40
|
+
onValueChange
|
|
22
41
|
});
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
42
|
+
const { committedText, onCompositionChange } = text;
|
|
43
|
+
const maskitoOptions = useMemo(() => ({
|
|
44
|
+
...formatter.maskOptions,
|
|
45
|
+
plugins: [createInputGuard({
|
|
46
|
+
accepts: formatter.accepts,
|
|
47
|
+
getCommittedText: () => committedText.current,
|
|
48
|
+
onCompositionChange
|
|
49
|
+
}), ...formatter.maskOptions.plugins ?? []]
|
|
50
|
+
}), [
|
|
51
|
+
formatter,
|
|
52
|
+
committedText,
|
|
53
|
+
onCompositionChange
|
|
54
|
+
]);
|
|
55
|
+
const maskitoRef = useMaskito({ options: maskitoOptions });
|
|
56
|
+
const mergedRef = useMemo(() => mergeRefs(ref, maskitoRef), [ref, maskitoRef]);
|
|
57
|
+
return /* @__PURE__ */ jsx(Input, {
|
|
39
58
|
...props,
|
|
40
|
-
|
|
59
|
+
ref: mergedRef,
|
|
41
60
|
type: "text",
|
|
42
61
|
inputMode: inputMode ?? (mask !== void 0 || decimalPlaces === 0 ? "numeric" : allowNegative ? void 0 : "decimal"),
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
};
|
|
50
|
-
if (mask !== void 0) return /* @__PURE__ */ jsx(MaskModeInput, {
|
|
51
|
-
...shared,
|
|
52
|
-
mask
|
|
53
|
-
});
|
|
54
|
-
return /* @__PURE__ */ jsx(NumericModeInput, {
|
|
55
|
-
...shared,
|
|
56
|
-
options: {
|
|
57
|
-
prefix,
|
|
58
|
-
suffix,
|
|
59
|
-
decimalPlaces,
|
|
60
|
-
fixedDecimalPlaces,
|
|
61
|
-
allowNegative,
|
|
62
|
-
groupStyle,
|
|
63
|
-
groupSeparator,
|
|
64
|
-
decimalSeparator,
|
|
65
|
-
locale
|
|
66
|
-
}
|
|
62
|
+
value: text.text,
|
|
63
|
+
onInput: (event) => {
|
|
64
|
+
text.onInput(event);
|
|
65
|
+
onInput?.(event);
|
|
66
|
+
},
|
|
67
|
+
onChange: onChange ?? noop
|
|
67
68
|
});
|
|
68
69
|
}
|
|
70
|
+
function noop() {}
|
|
69
71
|
|
|
70
72
|
export { NumberFormatInput };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useCallback, useLayoutEffect, useRef, useState } from "react";
|
|
4
|
+
|
|
5
|
+
// src/NumberFormatInput/hooks/useNumberText.ts
|
|
6
|
+
/** 화면 글자와 바깥 `value`를 맞추고 사용자가 바꾼 값만 알린다. 조합 중에는 알리지 않는다. */
|
|
7
|
+
function useNumberText({ formatter, formatterKey, value, defaultValue, onValueChange }) {
|
|
8
|
+
const fromOutside = (next) => {
|
|
9
|
+
const text = next === null || next === void 0 ? "" : formatter.format(formatter.fromValue(next));
|
|
10
|
+
return {
|
|
11
|
+
text,
|
|
12
|
+
digits: formatter.parse(text),
|
|
13
|
+
pending: [],
|
|
14
|
+
outside: value,
|
|
15
|
+
formatterKey
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
const [stored, setStored] = useState(() => fromOutside(value ?? defaultValue));
|
|
19
|
+
let state = stored;
|
|
20
|
+
if (state.formatterKey !== formatterKey) {
|
|
21
|
+
const text = formatter.format(state.digits);
|
|
22
|
+
state = {
|
|
23
|
+
...state,
|
|
24
|
+
text,
|
|
25
|
+
digits: formatter.parse(text),
|
|
26
|
+
formatterKey
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
if (value !== void 0 && !Object.is(value, state.outside)) {
|
|
30
|
+
const returned = state.pending.findIndex((change) => Object.is(change.value, value) || Object.is(change.digits, value));
|
|
31
|
+
state = returned === -1 ? fromOutside(value) : {
|
|
32
|
+
...state,
|
|
33
|
+
outside: value,
|
|
34
|
+
pending: state.pending.slice(returned + 1)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
if (state !== stored) setStored(state);
|
|
38
|
+
const [draft, setDraft] = useState(null);
|
|
39
|
+
const composing = useRef(false);
|
|
40
|
+
const committedText = useRef(state.text);
|
|
41
|
+
const onCompositionChange = useCallback((next) => {
|
|
42
|
+
composing.current = next;
|
|
43
|
+
}, []);
|
|
44
|
+
useLayoutEffect(() => {
|
|
45
|
+
committedText.current = state.text;
|
|
46
|
+
}, [state.text]);
|
|
47
|
+
const commit = (text) => {
|
|
48
|
+
setDraft(null);
|
|
49
|
+
if (text === committedText.current) return;
|
|
50
|
+
committedText.current = text;
|
|
51
|
+
const digits = formatter.parse(text);
|
|
52
|
+
const next = formatter.toValue(digits);
|
|
53
|
+
setStored((previous) => ({
|
|
54
|
+
...previous,
|
|
55
|
+
text,
|
|
56
|
+
digits,
|
|
57
|
+
pending: [...previous.pending.slice(-50), {
|
|
58
|
+
value: next,
|
|
59
|
+
digits
|
|
60
|
+
}]
|
|
61
|
+
}));
|
|
62
|
+
onValueChange?.({
|
|
63
|
+
value: next,
|
|
64
|
+
formattedValue: text,
|
|
65
|
+
digits
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
text: draft ?? state.text,
|
|
70
|
+
committedText,
|
|
71
|
+
onCompositionChange,
|
|
72
|
+
onInput: (event) => {
|
|
73
|
+
if (composing.current) setDraft(event.currentTarget.value);
|
|
74
|
+
else commit(event.currentTarget.value);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export { useNumberText };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// src/NumberFormatInput/libs/fieldEdit.ts
|
|
2
|
+
/** `before`가 `after`로 바뀔 때 고친 범위와 새로 들어간 글자. 같은 숫자가 이어져도 맞도록 바뀐 뒤의 커서로 끝을 정한다. */
|
|
3
|
+
function findEdit(before, after) {
|
|
4
|
+
const tail = after.value.slice(after.selection[1]);
|
|
5
|
+
let tailLength = tail.length;
|
|
6
|
+
if (!before.value.endsWith(tail)) {
|
|
7
|
+
tailLength = 0;
|
|
8
|
+
while (tailLength < Math.min(before.value.length, after.value.length) && before.value.at(-1 - tailLength) === after.value.at(-1 - tailLength)) tailLength += 1;
|
|
9
|
+
}
|
|
10
|
+
const to = before.value.length - tailLength;
|
|
11
|
+
const afterEnd = after.value.length - tailLength;
|
|
12
|
+
const limit = Math.min(before.selection[0], to, afterEnd);
|
|
13
|
+
let from = 0;
|
|
14
|
+
while (from < limit && before.value.charAt(from) === after.value.charAt(from)) from += 1;
|
|
15
|
+
return {
|
|
16
|
+
from,
|
|
17
|
+
to,
|
|
18
|
+
text: after.value.slice(from, afterEnd)
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** `beforeinput`이 알려 준 변경. 선택이 없으면 Backspace는 앞 글자, Delete는 뒤 글자를 지운다. */
|
|
22
|
+
function intendedEdit(inputType, data, { value, selection: [from, to] }) {
|
|
23
|
+
if (inputType.startsWith("insert")) return {
|
|
24
|
+
from,
|
|
25
|
+
to,
|
|
26
|
+
text: data ?? ""
|
|
27
|
+
};
|
|
28
|
+
if (from !== to) return {
|
|
29
|
+
from,
|
|
30
|
+
to,
|
|
31
|
+
text: ""
|
|
32
|
+
};
|
|
33
|
+
return inputType === "deleteContentForward" ? {
|
|
34
|
+
from,
|
|
35
|
+
to: Math.min(to + 1, value.length),
|
|
36
|
+
text: ""
|
|
37
|
+
} : {
|
|
38
|
+
from: Math.max(from - 1, 0),
|
|
39
|
+
to,
|
|
40
|
+
text: ""
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { findEdit, intendedEdit };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { findEdit, intendedEdit } from "./fieldEdit.js";
|
|
2
|
+
|
|
3
|
+
// src/NumberFormatInput/libs/inputGuard.ts
|
|
4
|
+
const replayableTypes = /* @__PURE__ */ new Set([
|
|
5
|
+
"insertText",
|
|
6
|
+
"insertCompositionText",
|
|
7
|
+
"insertFromComposition",
|
|
8
|
+
"deleteContentBackward",
|
|
9
|
+
"deleteContentForward",
|
|
10
|
+
"deleteCompositionText"
|
|
11
|
+
]);
|
|
12
|
+
function readState(element) {
|
|
13
|
+
const { value, selectionStart, selectionEnd } = element;
|
|
14
|
+
return {
|
|
15
|
+
value,
|
|
16
|
+
selection: [selectionStart ?? value.length, selectionEnd ?? value.length]
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function writeState(element, { value, selection }) {
|
|
20
|
+
if (element.value !== value) element.value = value;
|
|
21
|
+
if (element.matches(":focus")) element.setSelectionRange(selection[0], selection[1]);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Maskito가 `beforeinput`에서 막거나 계산하지 못한 변경(취소할 수 없는 입력, `beforeinput` 없는 입력, 조합)을
|
|
25
|
+
* 입력 전 상태로 되돌린 뒤 같은 변경을 Maskito의 `beforeinput` 처리에 다시 넘긴다. 타이머는 쓰지 않는다.
|
|
26
|
+
* Maskito보다 먼저 이벤트를 받아야 하므로 plugins의 맨 앞에 둔다(ADR 0043).
|
|
27
|
+
*/
|
|
28
|
+
function createInputGuard(handlers) {
|
|
29
|
+
return (element) => {
|
|
30
|
+
const abort = new AbortController();
|
|
31
|
+
const { signal } = abort;
|
|
32
|
+
let known = readState(element);
|
|
33
|
+
let pending = null;
|
|
34
|
+
let composition = null;
|
|
35
|
+
let replaying = false;
|
|
36
|
+
const replay = (before, inputType, edit) => {
|
|
37
|
+
const isDeletion = edit.text === "";
|
|
38
|
+
replaying = true;
|
|
39
|
+
element.dispatchEvent(new InputEvent("input", { inputType: "insertCompositionText" }));
|
|
40
|
+
writeState(element, {
|
|
41
|
+
value: before.value,
|
|
42
|
+
selection: [edit.from, edit.to]
|
|
43
|
+
});
|
|
44
|
+
const event = new InputEvent("beforeinput", {
|
|
45
|
+
cancelable: true,
|
|
46
|
+
inputType: !isDeletion ? "insertText" : inputType === "deleteContentForward" ? inputType : "deleteContentBackward",
|
|
47
|
+
data: isDeletion ? null : edit.text
|
|
48
|
+
});
|
|
49
|
+
const accepted = !(isDeletion && edit.from === edit.to) && element.dispatchEvent(event);
|
|
50
|
+
replaying = false;
|
|
51
|
+
if (!accepted && !isDeletion) writeState(element, before);
|
|
52
|
+
};
|
|
53
|
+
const startComposition = () => {
|
|
54
|
+
composition = {
|
|
55
|
+
state: readState(element),
|
|
56
|
+
committed: handlers.getCommittedText()
|
|
57
|
+
};
|
|
58
|
+
handlers.onCompositionChange(true);
|
|
59
|
+
};
|
|
60
|
+
const endComposition = () => {
|
|
61
|
+
composition = null;
|
|
62
|
+
known = readState(element);
|
|
63
|
+
handlers.onCompositionChange(false);
|
|
64
|
+
};
|
|
65
|
+
const finishComposition = () => {
|
|
66
|
+
if (!composition) return;
|
|
67
|
+
const { state, committed } = composition;
|
|
68
|
+
pending = null;
|
|
69
|
+
const external = handlers.getCommittedText();
|
|
70
|
+
if (external !== committed) writeState(element, {
|
|
71
|
+
value: external,
|
|
72
|
+
selection: [external.length, external.length]
|
|
73
|
+
});
|
|
74
|
+
else if (element.value !== state.value) {
|
|
75
|
+
const edit = findEdit(state, readState(element));
|
|
76
|
+
if (edit.text === "" && state.selection[0] !== state.selection[1]) writeState(element, state);
|
|
77
|
+
else replay(state, "insertText", edit);
|
|
78
|
+
}
|
|
79
|
+
endComposition();
|
|
80
|
+
element.dispatchEvent(new InputEvent("input", {
|
|
81
|
+
bubbles: true,
|
|
82
|
+
inputType: "insertText"
|
|
83
|
+
}));
|
|
84
|
+
known = readState(element);
|
|
85
|
+
};
|
|
86
|
+
element.addEventListener("beforeinput", (event) => {
|
|
87
|
+
if (replaying || !event.isTrusted) return;
|
|
88
|
+
const { isComposing } = event;
|
|
89
|
+
if (composition && !isComposing) finishComposition();
|
|
90
|
+
else if (!composition && isComposing) startComposition();
|
|
91
|
+
if (composition) return;
|
|
92
|
+
pending = {
|
|
93
|
+
event,
|
|
94
|
+
state: readState(element)
|
|
95
|
+
};
|
|
96
|
+
}, { signal });
|
|
97
|
+
element.addEventListener("input", (event) => {
|
|
98
|
+
if (replaying || !event.isTrusted) return;
|
|
99
|
+
if (composition) {
|
|
100
|
+
const { text } = findEdit(composition.state, readState(element));
|
|
101
|
+
if (text !== "" && !handlers.accepts(text)) {
|
|
102
|
+
writeState(element, composition.state);
|
|
103
|
+
endComposition();
|
|
104
|
+
}
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const { inputType } = event;
|
|
108
|
+
const seen = pending;
|
|
109
|
+
pending = null;
|
|
110
|
+
if (!replayableTypes.has(inputType)) return;
|
|
111
|
+
const handled = seen?.event.inputType === inputType && seen.event.cancelable && !seen.event.defaultPrevented;
|
|
112
|
+
const before = seen?.state ?? known;
|
|
113
|
+
if (handled || element.value === before.value) return;
|
|
114
|
+
const edit = seen ? intendedEdit(seen.event.inputType, seen.event.data, before) : findEdit(before, readState(element));
|
|
115
|
+
replay(before, inputType, edit);
|
|
116
|
+
}, {
|
|
117
|
+
capture: true,
|
|
118
|
+
signal
|
|
119
|
+
});
|
|
120
|
+
element.addEventListener("input", () => {
|
|
121
|
+
if (!replaying && !composition) known = readState(element);
|
|
122
|
+
}, { signal });
|
|
123
|
+
element.addEventListener("compositionstart", startComposition, { signal });
|
|
124
|
+
element.addEventListener("compositionend", finishComposition, { signal });
|
|
125
|
+
element.addEventListener("blur", finishComposition, {
|
|
126
|
+
capture: true,
|
|
127
|
+
signal
|
|
128
|
+
});
|
|
129
|
+
element.addEventListener("focus", () => known = readState(element), { signal });
|
|
130
|
+
element.ownerDocument.addEventListener("selectionchange", () => {
|
|
131
|
+
if (!composition && element.matches(":focus")) known = readState(element);
|
|
132
|
+
}, { signal });
|
|
133
|
+
return () => {
|
|
134
|
+
if (composition) handlers.onCompositionChange(false);
|
|
135
|
+
abort.abort();
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export { createInputGuard };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { applyMask, maskDigits, maxMaskDigits, sortMasks } from "./maskFormat.js";
|
|
2
|
+
|
|
3
|
+
// src/NumberFormatInput/libs/maskFormatter.ts
|
|
4
|
+
const slotCount = (mask) => mask.split("#").length - 1;
|
|
5
|
+
/** 앞에서부터 숫자 `count`개를 지난 위치 */
|
|
6
|
+
function indexAfterDigits(text, count) {
|
|
7
|
+
let seen = 0;
|
|
8
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
9
|
+
if (seen === count) return index;
|
|
10
|
+
if (/\d/.test(text.charAt(index))) seen += 1;
|
|
11
|
+
}
|
|
12
|
+
return text.length;
|
|
13
|
+
}
|
|
14
|
+
/** 패턴 모드 포맷 규칙. 틀은 `applyMask`로 채워 `formatNumber`와 같은 글자를 만든다. */
|
|
15
|
+
function createMaskFormatter(mask) {
|
|
16
|
+
const masks = sortMasks(mask);
|
|
17
|
+
const maxDigits = maxMaskDigits(masks);
|
|
18
|
+
const format = (digits) => applyMask(digits.slice(0, maxDigits), masks);
|
|
19
|
+
const digitsOnly = ({ elementState, data }, actionType) => {
|
|
20
|
+
if (actionType !== "insert") return {
|
|
21
|
+
elementState,
|
|
22
|
+
data
|
|
23
|
+
};
|
|
24
|
+
const { value, selection } = elementState;
|
|
25
|
+
const [from, to] = selection;
|
|
26
|
+
const digits = maskDigits(data);
|
|
27
|
+
const total = maskDigits(value.slice(0, from) + value.slice(to)).length + digits.length;
|
|
28
|
+
return digits === "" || total > maxDigits ? {
|
|
29
|
+
elementState: {
|
|
30
|
+
value,
|
|
31
|
+
selection: [to, to]
|
|
32
|
+
},
|
|
33
|
+
data: ""
|
|
34
|
+
} : {
|
|
35
|
+
elementState,
|
|
36
|
+
data: digits
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const fillMask = ({ value, selection }) => {
|
|
40
|
+
const text = format(maskDigits(value));
|
|
41
|
+
if (text === value) return {
|
|
42
|
+
value,
|
|
43
|
+
selection
|
|
44
|
+
};
|
|
45
|
+
const move = (index) => indexAfterDigits(text, maskDigits(value.slice(0, index)).length);
|
|
46
|
+
return {
|
|
47
|
+
value: text,
|
|
48
|
+
selection: [move(selection[0]), move(selection[1])]
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
maskOptions: {
|
|
53
|
+
mask: ({ value }) => {
|
|
54
|
+
const count = maskDigits(value).length;
|
|
55
|
+
const current = masks.find((item) => slotCount(item) >= count) ?? masks.at(-1) ?? "";
|
|
56
|
+
return Array.from(current, (char) => char === "#" ? /\d/ : char);
|
|
57
|
+
},
|
|
58
|
+
preprocessors: [digitsOnly],
|
|
59
|
+
postprocessors: [fillMask]
|
|
60
|
+
},
|
|
61
|
+
format,
|
|
62
|
+
parse: maskDigits,
|
|
63
|
+
toValue: (digits) => digits === "" ? null : Number(digits),
|
|
64
|
+
fromValue: (value) => maskDigits(String(value)),
|
|
65
|
+
accepts: (text) => maskDigits(text) !== ""
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export { createMaskFormatter };
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { toLibraryNumericOptions, toNumericString } from "./numericFormat.js";
|
|
2
|
+
import { maskitoTransform } from "@maskito/core";
|
|
3
|
+
import { maskitoNumber } from "@maskito/kit";
|
|
4
|
+
|
|
5
|
+
// src/NumberFormatInput/libs/numericFormatter.ts
|
|
6
|
+
/** 만 단위로 묶는다(`1234567` → `123`, `4567`). */
|
|
7
|
+
const wanGroups = (digits) => digits.match(/\d{1,4}(?=(?:\d{4})*$)/g) ?? [];
|
|
8
|
+
/** 숫자 모드 포맷 규칙. 구분자는 `formatNumber`와 같은 방법으로 고른다. */
|
|
9
|
+
function createNumericFormatter(options) {
|
|
10
|
+
const separators = toLibraryNumericOptions(options);
|
|
11
|
+
const decimal = separators.decimalSeparator ?? ".";
|
|
12
|
+
const group = typeof separators.thousandSeparator === "string" ? separators.thousandSeparator : "";
|
|
13
|
+
const decimalKeys = separators.allowedDecimalSeparators ?? [decimal];
|
|
14
|
+
const prefix = options.prefix ?? "";
|
|
15
|
+
const suffix = options.suffix ?? "";
|
|
16
|
+
const allowNegative = options.allowNegative ?? false;
|
|
17
|
+
const { decimalPlaces } = options;
|
|
18
|
+
const params = {
|
|
19
|
+
prefix,
|
|
20
|
+
postfix: suffix,
|
|
21
|
+
thousandSeparator: group,
|
|
22
|
+
decimalSeparator: decimal,
|
|
23
|
+
decimalPseudoSeparators: decimalKeys.filter((key) => key !== decimal),
|
|
24
|
+
maximumFractionDigits: decimalPlaces ?? Infinity,
|
|
25
|
+
minimumFractionDigits: options.fixedDecimalPlaces ? decimalPlaces ?? 0 : 0,
|
|
26
|
+
minusSign: "-",
|
|
27
|
+
negativePattern: "minusFirst",
|
|
28
|
+
...allowNegative ? {} : { min: 0 },
|
|
29
|
+
...options.groupStyle === "wan" ? { thousandSeparatorPattern: wanGroups } : {}
|
|
30
|
+
};
|
|
31
|
+
/** prefix·suffix를 뺀 숫자 부분. prefix·suffix 안의 점을 소수점으로 보지 않으려고 쓴다. */
|
|
32
|
+
const numberRange = (text) => {
|
|
33
|
+
let start = text.startsWith("-") ? 1 : 0;
|
|
34
|
+
if (prefix !== "" && text.startsWith(prefix, start)) start += prefix.length;
|
|
35
|
+
const end = suffix !== "" && text.endsWith(suffix) && text.length - suffix.length >= start ? text.length - suffix.length : text.length;
|
|
36
|
+
return [start, end];
|
|
37
|
+
};
|
|
38
|
+
const decimalIndex = (text) => {
|
|
39
|
+
const [start, end] = numberRange(text);
|
|
40
|
+
const index = text.slice(start, end).indexOf(decimal);
|
|
41
|
+
return index === -1 ? -1 : start + index;
|
|
42
|
+
};
|
|
43
|
+
const parse = (text) => {
|
|
44
|
+
const [start, end] = numberRange(text);
|
|
45
|
+
const body = Array.from(text.slice(start, end)).filter((char) => char >= "0" && char <= "9" || char === decimal).map((char) => char === decimal ? "." : char).join("");
|
|
46
|
+
return text.startsWith("-") ? `-${body}` : body;
|
|
47
|
+
};
|
|
48
|
+
/** 점이 이미 있으면 새 점은 무시한다. 바로 앞의 점을 넘거나 선택한 점을 바꾸는 것은 Maskito가 처리한다. */
|
|
49
|
+
const singleDecimal = ({ elementState, data }, actionType) => {
|
|
50
|
+
const index = decimalIndex(elementState.value);
|
|
51
|
+
const [from, to] = elementState.selection;
|
|
52
|
+
const passes = from === to ? from === index : from <= index && index < to;
|
|
53
|
+
if (actionType !== "insert" || !decimalKeys.includes(data) || index === -1 || passes) return {
|
|
54
|
+
elementState,
|
|
55
|
+
data
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
elementState: {
|
|
59
|
+
value: elementState.value,
|
|
60
|
+
selection: [to, to]
|
|
61
|
+
},
|
|
62
|
+
data: ""
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
const base = maskitoNumber(params);
|
|
66
|
+
return {
|
|
67
|
+
maskOptions: {
|
|
68
|
+
...base,
|
|
69
|
+
preprocessors: [singleDecimal, ...base.preprocessors ?? []],
|
|
70
|
+
postprocessors: [...base.postprocessors ?? [], (state) => parse(state.value) === "" ? {
|
|
71
|
+
value: "",
|
|
72
|
+
selection: [0, 0]
|
|
73
|
+
} : state]
|
|
74
|
+
},
|
|
75
|
+
parse,
|
|
76
|
+
format: (digits) => {
|
|
77
|
+
const signed = allowNegative ? digits : digits.replace("-", "");
|
|
78
|
+
return signed === "" ? "" : maskitoTransform(signed.replace(".", decimal), maskitoNumber(params));
|
|
79
|
+
},
|
|
80
|
+
toValue: (digits) => {
|
|
81
|
+
const value = Number.parseFloat(digits);
|
|
82
|
+
return Number.isNaN(value) ? null : value;
|
|
83
|
+
},
|
|
84
|
+
fromValue: (value) => typeof value === "number" ? toNumericString(value, decimalPlaces) : value,
|
|
85
|
+
accepts: (text) => /[0-90-9]/.test(text) || decimalKeys.some((key) => text.includes(key)) || allowNegative && text.includes("-")
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export { createNumericFormatter };
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import "
|
|
2
|
-
import "react-number-format";
|
|
1
|
+
import "@maskito/core";
|
|
3
2
|
/** 숫자를 몇 자리씩 묶는지. `thousand` 1,234,567 · `wan` 123,4567(만 단위) · `none` 묶지 않음. */
|
|
4
3
|
export type NumberGroupStyle = "thousand" | "wan" | "none";
|
|
5
4
|
/** 숫자 모드 포맷 옵션. `NumberFormatInput`과 `formatNumber`가 같은 옵션으로 같은 글자를 만든다. */
|
|
@@ -10,7 +9,10 @@ export interface NumericFormatOptions {
|
|
|
10
9
|
suffix?: string;
|
|
11
10
|
/** 소수 최대 자릿수. `0`이면 소수점을 받지 않는다. 기본값은 제한 없음. */
|
|
12
11
|
decimalPlaces?: number;
|
|
13
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* `decimalPlaces`만큼 소수 자리를 늘 채운다(`1` → `1.00`). 입력 칸은 치는 중에도 채우고,
|
|
14
|
+
* 채운 소수 자리에 치면 그 자리를 덮어쓴다. 기본값 `false`.
|
|
15
|
+
*/
|
|
14
16
|
fixedDecimalPlaces?: boolean;
|
|
15
17
|
/** 음수(`-`)를 받는다. 기본값 `false`. */
|
|
16
18
|
allowNegative?: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tide-design/components",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0",
|
|
4
4
|
"description": "Tide 디자인 시스템의 React Component",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"accessibility",
|
|
@@ -34,8 +34,11 @@
|
|
|
34
34
|
"./styles.css": "./dist/styles.css"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@
|
|
38
|
-
"@
|
|
37
|
+
"@maskito/core": "5.6.1",
|
|
38
|
+
"@maskito/kit": "5.6.1",
|
|
39
|
+
"@maskito/react": "5.6.1",
|
|
40
|
+
"@tide-design/foundation": "0.23.0",
|
|
41
|
+
"@tide-design/icons": "0.23.0",
|
|
39
42
|
"clsx": "^2.1.1",
|
|
40
43
|
"react-aria": "^3.53.1",
|
|
41
44
|
"react-number-format": "^5.4.5",
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
|
|
3
|
-
import { applyMask, maskDigits, maxMaskDigits, sortMasks } from "../libs/maskFormat.js";
|
|
4
|
-
import { jsx } from "react/jsx-runtime";
|
|
5
|
-
import { NumberFormatBase } from "react-number-format";
|
|
6
|
-
|
|
7
|
-
// src/NumberFormatInput/components/MaskModeInput.tsx
|
|
8
|
-
function MaskModeInput({ mask, ...props }) {
|
|
9
|
-
const masks = sortMasks(mask);
|
|
10
|
-
const maxDigits = maxMaskDigits(masks);
|
|
11
|
-
return /* @__PURE__ */ jsx(NumberFormatBase, {
|
|
12
|
-
...props,
|
|
13
|
-
format: (digits) => applyMask(digits, masks),
|
|
14
|
-
removeFormatting: (text, change) => {
|
|
15
|
-
const digits = maskDigits(text);
|
|
16
|
-
if (digits.length > maxDigits && change) return maskDigits(change.lastValue);
|
|
17
|
-
return digits.slice(0, maxDigits);
|
|
18
|
-
}
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export { MaskModeInput };
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
|
|
3
|
-
import { toLibraryNumericOptions } from "../libs/numericFormat.js";
|
|
4
|
-
import { jsx } from "react/jsx-runtime";
|
|
5
|
-
import { NumberFormatBase, useNumericFormat } from "react-number-format";
|
|
6
|
-
|
|
7
|
-
// src/NumberFormatInput/components/NumericModeInput.tsx
|
|
8
|
-
function NumericModeInput({ options, ...props }) {
|
|
9
|
-
const baseProps = useNumericFormat({
|
|
10
|
-
...props,
|
|
11
|
-
...toLibraryNumericOptions(options)
|
|
12
|
-
});
|
|
13
|
-
return /* @__PURE__ */ jsx(NumberFormatBase, { ...baseProps });
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export { NumericModeInput };
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
|
|
3
|
-
import { useRef } from "react";
|
|
4
|
-
|
|
5
|
-
// src/NumberFormatInput/hooks/useNumberCompositionGuard.ts
|
|
6
|
-
/** IME 조합 중인 글자를 지워 조합 직전 값으로 되돌린다. 넘긴 처리기는 되돌린 뒤 부른다. */
|
|
7
|
-
function useNumberCompositionGuard({ onCompositionStart, onInput }) {
|
|
8
|
-
const valueBeforeComposition = useRef("");
|
|
9
|
-
return {
|
|
10
|
-
onCompositionStart: (event) => {
|
|
11
|
-
valueBeforeComposition.current = event.currentTarget.value;
|
|
12
|
-
onCompositionStart?.(event);
|
|
13
|
-
},
|
|
14
|
-
onInput: (event) => {
|
|
15
|
-
if (event.nativeEvent.isComposing) event.currentTarget.value = valueBeforeComposition.current;
|
|
16
|
-
onInput?.(event);
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export { useNumberCompositionGuard };
|