react-app-utilities 0.0.0-stage → 0.0.1

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/src/state.ts ADDED
@@ -0,0 +1,225 @@
1
+ import { ChangeEvent } from "react"
2
+ import { normalizeFax, normalizePhone } from "./core"
3
+ import { setValue } from "./reflect"
4
+
5
+ export function getDecimalSeparator(ele: HTMLInputElement): string {
6
+ let separator = ele.getAttribute("data-decimal-separator")
7
+ if (!separator) {
8
+ const form = ele.form
9
+ if (form) {
10
+ separator = form.getAttribute("data-decimal-separator")
11
+ }
12
+ }
13
+ return separator === "," || separator === "٫" ? separator : "."
14
+ }
15
+ export function normalizeInteger(s?: string | null): string {
16
+ if (!s) {
17
+ return ""
18
+ }
19
+ const len = s.length
20
+ const buf = new Array<string>(len)
21
+ let j = 0
22
+ for (let i = 0; i < len; i++) {
23
+ const c = s.charCodeAt(i)
24
+ if (c >= 48 && c <= 57) {
25
+ buf[j++] = s[i]
26
+ }
27
+ }
28
+ return j === len ? buf.join("") : buf.slice(0, j).join("")
29
+ }
30
+ export function removeSeparators(s?: string | null): string {
31
+ if (!s) {
32
+ return ""
33
+ }
34
+ const len = s.length
35
+ const buffer = new Uint16Array(len) // preallocate max possible
36
+ let write = 0
37
+
38
+ for (let i = 0; i < len; i++) {
39
+ const c = s.charCodeAt(i)
40
+ // '0'–'9' (48–57), '.' (46)
41
+ if ((c >= 48 && c <= 57) || c === 46) {
42
+ buffer[write++] = c
43
+ }
44
+ }
45
+ // Convert only the used portion to string
46
+ return String.fromCharCode.apply(null, buffer.subarray(0, write) as any)
47
+ }
48
+ // Keep digits 0–9 ; Replace , and ٫ (Arabic decimal separator) → . ; Remove everything else
49
+ export function normalizeNumber(s?: string | null): string {
50
+ if (!s) {
51
+ return ""
52
+ }
53
+ const len = s.length
54
+ const buf = new Array<string>(len)
55
+ let j = 0
56
+ for (let i = 0; i < len; i++) {
57
+ const c = s.charCodeAt(i)
58
+
59
+ if (c >= 48 && c <= 57) {
60
+ buf[j++] = s[i]
61
+ } else if (c === 44 || c === 1643) {
62
+ buf[j++] = "."
63
+ }
64
+ }
65
+ return j === len ? buf.join("") : buf.slice(0, j).join("")
66
+ }
67
+ // const r1 = / |,|\$|€|£|¥|'|٬|،| /g
68
+ // const r2 = / |\.|\$|€|£|¥|'|٬|،| /g
69
+ export function updateNumber<T>(
70
+ e: ChangeEvent<HTMLInputElement>,
71
+ o: T,
72
+ setObj: (v: React.SetStateAction<T>) => void,
73
+ decimalSeparator?: string,
74
+ callback?: () => void,
75
+ formatStr?: (s?: string) => string,
76
+ ) {
77
+ const ctrl = e.target
78
+ const v0: string = formatStr ? formatStr(ctrl.value) : ctrl.value
79
+ const dataField = ctrl.getAttribute("data-field")
80
+ const field = dataField ? dataField : ctrl.name
81
+ let v = decimalSeparator === "," || decimalSeparator === "٫" ? normalizeNumber(v0) : removeSeparators(v0)
82
+ if (v === "" || v == null) {
83
+ setValue(o, field, undefined)
84
+ } else {
85
+ const val = isNaN(v as any) ? undefined : parseFloat(v)
86
+ setValue(o, field, val)
87
+ }
88
+ setObj({ ...o })
89
+ if (callback) {
90
+ callback()
91
+ }
92
+ }
93
+ export function formatAndUpdateState<T>(
94
+ e:
95
+ | ChangeEvent<HTMLInputElement>
96
+ | ChangeEvent<HTMLSelectElement>
97
+ | ChangeEvent<HTMLTextAreaElement>
98
+ | ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
99
+ o: T,
100
+ setObj: (v: React.SetStateAction<T>) => void,
101
+ formatStr?: (s?: string) => string,
102
+ decimalSeparator?: string,
103
+ callback?: () => void,
104
+ ) {
105
+ updateState(e, o, setObj, decimalSeparator, formatStr, callback)
106
+ }
107
+ export function updateStateAndCallback<T>(
108
+ e:
109
+ | ChangeEvent<HTMLInputElement>
110
+ | ChangeEvent<HTMLSelectElement>
111
+ | ChangeEvent<HTMLTextAreaElement>
112
+ | ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
113
+ o: T,
114
+ setObj: (v: React.SetStateAction<T>) => void,
115
+ callback?: () => void,
116
+ decimalSeparator?: string,
117
+ formatStr?: (s?: string) => string,
118
+ ) {
119
+ updateState(e, o, setObj, decimalSeparator, formatStr, callback)
120
+ }
121
+ export function updateState<T>(
122
+ e:
123
+ | ChangeEvent<HTMLInputElement>
124
+ | ChangeEvent<HTMLSelectElement>
125
+ | ChangeEvent<HTMLTextAreaElement>
126
+ | ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
127
+ o: T,
128
+ setObj: (v: React.SetStateAction<T>) => void,
129
+ decimalSeparator?: string,
130
+ formatStr?: (s?: string) => string,
131
+ callback?: () => void,
132
+ ) {
133
+ const ctrl = e.target
134
+ const v0: string = formatStr ? formatStr(ctrl.value) : ctrl.value
135
+ const dataField = ctrl.getAttribute("data-field")
136
+ const field = dataField ? dataField : ctrl.name
137
+ if (ctrl.tagName === "SELECT") {
138
+ if (ctrl.tagName === "SELECT") {
139
+ if (v0 === "" || !v0) {
140
+ ctrl.removeAttribute("data-value")
141
+ } else {
142
+ ctrl.setAttribute("data-value", v0)
143
+ }
144
+ }
145
+ setValue(o, field, v0)
146
+ } else {
147
+ let stype = ctrl.getAttribute("type")
148
+ const type: string = stype ? stype.toLowerCase() : "text"
149
+ let model: any = o
150
+ if (type === "checkbox") {
151
+ let value = model[field]
152
+ if (ctrl.id && ctrl.name !== ctrl.id) {
153
+ if (!value || !Array.isArray(value)) {
154
+ value = []
155
+ }
156
+ value.includes(v0) ? (value = value.filter((v: string) => v !== v0)) : value.push(v0)
157
+ model[field] = value
158
+ } else {
159
+ const v = valueOfCheckbox(ctrl as HTMLInputElement)
160
+ model[field] = v
161
+ }
162
+ } else if (type === "radio") {
163
+ if (field.indexOf(".") < 0 && field.indexOf("[") < 0) {
164
+ model[field] = v0
165
+ } else {
166
+ setValue(model, field, v0)
167
+ }
168
+ } else if (type === "date" || type === "datetime-local") {
169
+ const date = new Date(v0)
170
+ const val = !isNaN(date.getTime()) ? date.toISOString() : null
171
+ setValue(model, field, val)
172
+ } else if (type === "time") {
173
+ const date = new Date(v0)
174
+ if (!isNaN(date.getTime())) {
175
+ setValue(model, field, date.getTime())
176
+ } else {
177
+ setValue(model, field, null)
178
+ }
179
+ } else {
180
+ const datatype = ctrl.getAttribute("data-type")
181
+ if (datatype === "phone") {
182
+ const val = normalizePhone(v0)
183
+ setValue(o, field, val)
184
+ } else if (datatype === "fax") {
185
+ const val = normalizeFax(v0)
186
+ setValue(o, field, val)
187
+ } else if (datatype === "integer") {
188
+ let v = normalizeInteger(v0)
189
+ if (v === "" || v == null) {
190
+ setValue(o, field, undefined)
191
+ } else {
192
+ const val = isNaN(v as any) ? undefined : parseFloat(v)
193
+ setValue(o, field, val)
194
+ }
195
+ } else if (datatype === "number") {
196
+ const sep = decimalSeparator ? decimalSeparator : getDecimalSeparator(ctrl as HTMLInputElement)
197
+ let v = sep === "," || sep === "٫" ? normalizeNumber(v0) : removeSeparators(v0)
198
+ if (v === "" || v == null) {
199
+ setValue(o, field, undefined)
200
+ } else {
201
+ const val = isNaN(v as any) ? undefined : parseFloat(v)
202
+ setValue(o, field, val)
203
+ }
204
+ } else {
205
+ setValue(o, field, v0)
206
+ }
207
+ }
208
+ }
209
+ setObj({ ...o })
210
+ if (callback) {
211
+ callback()
212
+ }
213
+ }
214
+
215
+ export function valueOfCheckbox(ctrl: HTMLInputElement): string | number | boolean {
216
+ const ctrlOnValue = ctrl.getAttribute("data-on-value")
217
+ const ctrlOffValue = ctrl.getAttribute("data-off-value")
218
+ if (ctrlOnValue && ctrlOffValue) {
219
+ const onValue = ctrlOnValue ? ctrlOnValue : true
220
+ const offValue = ctrlOffValue ? ctrlOffValue : false
221
+ return ctrl.checked === true ? onValue : offValue
222
+ } else {
223
+ return ctrl.checked === true
224
+ }
225
+ }
@@ -0,0 +1,31 @@
1
+ import * as React from "react"
2
+ import { ErrorMessage } from "./core"
3
+
4
+ export interface MessageState {
5
+ message?: string
6
+ alertClass?: string
7
+ }
8
+
9
+ export const useMessage = (initialState: MessageState) => {
10
+ const [msg, setMessage] = React.useState<MessageState>(initialState)
11
+
12
+ const hideMessage = () => {
13
+ setMessage({ alertClass: "", message: "" })
14
+ }
15
+
16
+ const showMessage = (ms: string) => {
17
+ setMessage({ alertClass: "alert alert-info", message: ms })
18
+ }
19
+
20
+ const showError = (ms: string | ErrorMessage[]) => {
21
+ if (typeof ms === "string") {
22
+ setMessage({ alertClass: "alert alert-error", message: ms })
23
+ } else if (Array.isArray(ms) && ms.length > 0) {
24
+ setMessage({ alertClass: "alert alert-error", message: ms[0].message })
25
+ } else {
26
+ const x = JSON.stringify(ms)
27
+ setMessage({ alertClass: "alert alert-error", message: x })
28
+ }
29
+ }
30
+ return { msg, showError, showMessage, hideMessage }
31
+ }
package/src/util.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { Locale } from "./core"
2
+
3
+ export const enLocale = {
4
+ id: "en-US",
5
+ countryCode: "US",
6
+ dateFormat: "M/d/yyyy",
7
+ firstDayOfWeek: 1,
8
+ decimalSeparator: ".",
9
+ groupSeparator: ",",
10
+ decimalDigits: 2,
11
+ currencyCode: "USD",
12
+ currencySymbol: "$",
13
+ currencyPattern: 0,
14
+ }
15
+
16
+ const r1 = / |,|\$|€|£|¥|'|٬|،| /g
17
+ const r2 = / |\.|\$|€|£|¥|'|٬|،| /g
18
+
19
+ export function valueOf(ctrl: HTMLInputElement, locale?: Locale, eventType?: string): { mustChange: any; value?: any } {
20
+ if (ctrl.type === "checkbox") {
21
+ const ctrlOnValue = ctrl.getAttribute("data-on-value")
22
+ const ctrlOffValue = ctrl.getAttribute("data-off-value")
23
+ if (ctrlOnValue && ctrlOffValue) {
24
+ const onValue = ctrlOnValue ? ctrlOnValue : true
25
+ const offValue = ctrlOffValue ? ctrlOffValue : false
26
+ return ctrl.checked === true ? { mustChange: true, value: onValue } : { mustChange: true, value: offValue }
27
+ } else {
28
+ return ctrl.checked === true ? { mustChange: true, value: true } : { mustChange: true, value: false }
29
+ }
30
+ } else {
31
+ const datatype = ctrl.getAttribute("data-type")
32
+ if (datatype === "number" || datatype === "integer") {
33
+ let v
34
+ if (locale && locale.decimalSeparator !== ".") {
35
+ v = ctrl.value.replace(r2, "")
36
+ if (v.indexOf(locale.decimalSeparator) >= 0) {
37
+ v = v.replace(locale.decimalSeparator, ".")
38
+ }
39
+ } else {
40
+ v = ctrl.value.replace(r1, "")
41
+ }
42
+ return isNaN(v as any) ? { mustChange: false } : { mustChange: true, value: parseFloat(v) }
43
+ } else if (datatype === "currency" || datatype === "string-currency") {
44
+ const ml = ctrl.getAttribute("maxlength")
45
+ const nm = ml != null && !isNaN(ml as any) ? parseInt(ml, 10) : undefined
46
+ const res: any = getStringCurrency(ctrl.value, datatype, locale, nm, eventType === "blur")
47
+ return res
48
+ } else {
49
+ return { mustChange: true, value: ctrl.value }
50
+ }
51
+ }
52
+ }
53
+
54
+ function getStringCurrency(value: string, datatype: string, locale?: Locale, maxLength?: number, isOnBlur?: boolean): { mustChange: any; value?: string } {
55
+ if (locale && locale.decimalSeparator !== ".") {
56
+ value = value.replace(r2, "")
57
+ if (value.indexOf(locale.decimalSeparator) >= 0) {
58
+ value = value.replace(locale.decimalSeparator, ".")
59
+ }
60
+ } else {
61
+ value = value.replace(r1, "")
62
+ }
63
+ if (value === "") {
64
+ return { mustChange: true, value: "" }
65
+ }
66
+ value = extractNumber(value, ".") // value = ReactUtil.extractNumber(value, locale.decimalSeparator);
67
+ if (value.length === 0) {
68
+ return { mustChange: false }
69
+ } else if (value.length > 0 && value.charAt(0) === "0") {
70
+ return { mustChange: true, value: value.substring(1) }
71
+ }
72
+
73
+ if (!locale) {
74
+ locale = enLocale
75
+ }
76
+ const decimalDigits = locale ? locale.decimalDigits : 2
77
+ const groupDigits = 3 // TODO in database locale don't have data
78
+ const decimalSeparator = locale.decimalSeparator // '.'
79
+ const groupSeparator = locale.groupSeparator // ','
80
+
81
+ if (isOnBlur) {
82
+ const number = Number(value.replace(/^0+/, ""))
83
+ if (number === 0) {
84
+ return { mustChange: true, value: "" }
85
+ } else {
86
+ value = number.toFixed(decimalDigits)
87
+ }
88
+ }
89
+
90
+ const dotPosition = value.indexOf(".")
91
+ // Format thousands
92
+ let beforeDot = dotPosition >= 0 ? value.substring(0, dotPosition) : value
93
+ if (datatype === "string-currency" || isOnBlur) {
94
+ beforeDot = beforeDot.replace(new RegExp("\\B(?=(\\d{" + groupDigits + "})+(?!\\d))", "g"), groupSeparator)
95
+ }
96
+
97
+ // Cut after dot
98
+ let afterDot
99
+ if (dotPosition > 0) {
100
+ afterDot = value.substring(dotPosition + 1)
101
+ if (afterDot.length > decimalDigits) {
102
+ afterDot = afterDot.substring(0, decimalDigits)
103
+ }
104
+ }
105
+ if (maxLength && beforeDot.length > maxLength - (decimalDigits + 1)) {
106
+ return { mustChange: false }
107
+ }
108
+
109
+ value = dotPosition >= 0 ? beforeDot + decimalSeparator + afterDot : beforeDot
110
+ return maxLength && value.length > maxLength ? { mustChange: false } : { mustChange: true, value }
111
+ }
112
+
113
+ function extractNumber(str: string, decimalSeparator: string): string {
114
+ const arrs: string[] = []
115
+ let d = false
116
+ for (let i = 0; i < str.length; i++) {
117
+ const ch = str.charAt(i) // get char
118
+ if (ch >= "0" && ch <= "9") {
119
+ arrs.push(ch)
120
+ } else if (ch === decimalSeparator) {
121
+ // else if (ch === '.') {
122
+ if (d) {
123
+ return arrs.join("")
124
+ } else {
125
+ d = true
126
+ arrs.push(ch)
127
+ }
128
+ } else {
129
+ return arrs.join("")
130
+ }
131
+ }
132
+ return arrs.join("")
133
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "compileOnSave": true,
3
+ "compilerOptions": {
4
+ "target": "es5",
5
+ "baseUrl": "./src",
6
+ "outDir": "./lib",
7
+ "module": "commonjs",
8
+ "moduleResolution": "node",
9
+ "strict": true,
10
+ "strictNullChecks": true,
11
+ "pretty": true,
12
+ "sourceMap": false,
13
+ "declaration": false,
14
+ "experimentalDecorators": false,
15
+ "removeComments": true,
16
+ "lib": ["dom", "es6"]
17
+ },
18
+ "include": ["src/**/*.ts"],
19
+ "exclude": ["node_modules"]
20
+ }