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/edit.ts ADDED
@@ -0,0 +1,108 @@
1
+ import { NavigateFunction } from "react-router"
2
+ import { Attributes, ErrorMessage, StringMap } from "./core"
3
+
4
+ export function isSuccessful<T>(x: number | T | ErrorMessage[]): boolean {
5
+ if (Array.isArray(x)) {
6
+ return false
7
+ } else if (typeof x === "object") {
8
+ return true
9
+ } else if (typeof x === "number" && x > 0) {
10
+ return true
11
+ }
12
+ return false
13
+ }
14
+
15
+ type Result<T> = number | T | ErrorMessage[]
16
+ export function afterSaved<T>(
17
+ res: Result<T>,
18
+ form: HTMLFormElement | undefined | null,
19
+ resource: StringMap,
20
+ showFormError: (form?: HTMLFormElement | null, errors?: ErrorMessage[]) => ErrorMessage[],
21
+ alertSuccess: (msg: string, callback?: () => void) => void,
22
+ alertError: (msg: string) => void,
23
+ navigate?: NavigateFunction,
24
+ ) {
25
+ if (Array.isArray(res)) {
26
+ showFormError(form, res)
27
+ } else if (isSuccessful(res)) {
28
+ alertSuccess(resource.msg_save_success, () => {
29
+ if (navigate) {
30
+ navigate(-1)
31
+ }
32
+ })
33
+ } else if (res === 0) {
34
+ alertError(resource.error_not_found)
35
+ } else {
36
+ alertError(resource.error_conflict)
37
+ }
38
+ }
39
+ export function afterCreated<T>(
40
+ res: Result<T>,
41
+ form: HTMLFormElement | undefined | null,
42
+ successMessage: string,
43
+ duplicateMessage: string,
44
+ showFormError: (form?: HTMLFormElement | null, errors?: ErrorMessage[]) => ErrorMessage[],
45
+ alertSuccess: (msg: string, callback?: () => void) => void,
46
+ alertError: (msg: string) => void,
47
+ navigate?: NavigateFunction,
48
+ ) {
49
+ if (Array.isArray(res)) {
50
+ showFormError(form, res)
51
+ } else if (isSuccessful(res)) {
52
+ alertSuccess(successMessage, () => {
53
+ if (navigate) {
54
+ navigate(-1)
55
+ }
56
+ })
57
+ } else {
58
+ alertError(duplicateMessage)
59
+ }
60
+ }
61
+
62
+ export function createModel<T>(attributes?: Attributes): T {
63
+ const obj: any = {}
64
+ if (!attributes) {
65
+ return obj
66
+ }
67
+ const attrs = Object.keys(attributes)
68
+ for (const k of attrs) {
69
+ const attr = attributes[k]
70
+ if (attr.name) {
71
+ switch (attr.type) {
72
+ case "string":
73
+ case "text":
74
+ obj[attr.name] = ""
75
+ break
76
+ case "integer":
77
+ case "number":
78
+ obj[attr.name] = 0
79
+ break
80
+ case "array":
81
+ obj[attr.name] = []
82
+ break
83
+ case "boolean":
84
+ obj[attr.name] = false
85
+ break
86
+ case "date":
87
+ obj[attr.name] = new Date()
88
+ break
89
+ case "object":
90
+ if (attr.typeof) {
91
+ const object = createModel(attr.typeof)
92
+ obj[attr.name] = object
93
+ break
94
+ } else {
95
+ obj[attr.name] = {}
96
+ break
97
+ }
98
+ case "ObjectId":
99
+ obj[attr.name] = null
100
+ break
101
+ default:
102
+ obj[attr.name] = ""
103
+ break
104
+ }
105
+ }
106
+ }
107
+ return obj
108
+ }
package/src/index.ts ADDED
@@ -0,0 +1,380 @@
1
+ import * as React from "react"
2
+ import { ChangeEvent, ChangeEventHandler, FocusEvent, useEffect, useState } from "react"
3
+ export * from "./com"
4
+ export * from "./core"
5
+ export * from "./diff"
6
+ export * from "./edit"
7
+ export * from "./reflect"
8
+ export * from "./route"
9
+ export * from "./search"
10
+ export * from "./state"
11
+ export * from "./useMessage"
12
+ export * from "./util"
13
+
14
+ export type ButtonMouseEvent = React.MouseEvent<HTMLButtonElement, MouseEvent>
15
+ export type SelectChangeEvent = ChangeEvent<HTMLSelectElement>
16
+ export type InputChangeEvent = ChangeEvent<HTMLInputElement>
17
+ /*
18
+ type CallBackType<T> = (updatedValue: T) => void;
19
+ type SetStateType<T> = T | ((prev: T) => T);
20
+ type RetType = <T>(initialValue: T | (() => T)) => [T, (newValue: SetStateType<T>, callback?: CallBackType<T>) => void];
21
+
22
+ export const useCallbackState: RetType = <T>(initialValue: T | (() => T)) => {
23
+ const [state, _setState] = useState<T>(initialValue);
24
+ const callbackQueue = useRef<CallBackType<T>[]>([]);
25
+
26
+ useEffect(() => {
27
+ callbackQueue.current.forEach((cb) => cb(state));
28
+ callbackQueue.current = [];
29
+ }, [state]);
30
+
31
+ const setState = (newValue: SetStateType<T>, callback?: CallBackType<T>) => {
32
+ _setState(newValue);
33
+ if (callback && typeof callback === "function") {
34
+ callbackQueue.current.push(callback);
35
+ }
36
+ };
37
+ return [state, setState];
38
+ };
39
+ */
40
+ export function checked(s: string[] | string | undefined, v: string): boolean | undefined {
41
+ if (s) {
42
+ if (Array.isArray(s)) {
43
+ return includes(s, v)
44
+ } else {
45
+ return s === v
46
+ }
47
+ }
48
+ return false
49
+ }
50
+ export function includes(s: string[], v: string): boolean {
51
+ const l = s.length
52
+ for (let i = 0; i < l; i++) {
53
+ if (s[i] === v) {
54
+ return true
55
+ }
56
+ }
57
+ return false
58
+ }
59
+ export function value<T>(obj?: T): T {
60
+ return obj ? obj : ({} as any)
61
+ }
62
+ export interface LoadingProps {
63
+ error?: any
64
+ }
65
+ export const Loading = (props: LoadingProps) => {
66
+ const loadingStyle = {
67
+ top: "30%",
68
+ backgroundColor: "white",
69
+ border: "none",
70
+ WebkitBoxShadow: "none",
71
+ boxShadow: "none",
72
+ }
73
+ if (props.error) {
74
+ return React.createElement("div", null, "Error Load Module!") // return (<div>Error Load Module!</div>);
75
+ } else {
76
+ return React.createElement(
77
+ "div",
78
+ { className: "loader-wrapper" },
79
+ React.createElement("div", { className: "loader-sign", style: loadingStyle }, React.createElement("div", { className: "loader" })),
80
+ )
81
+ /*
82
+ return (
83
+ <div className='loader-wrapper'>
84
+ <div className='loader-sign' style={loadingStyle}>
85
+ <div className='loader' />
86
+ </div>
87
+ </div>
88
+ );*/
89
+ }
90
+ }
91
+ interface Locale {
92
+ decimalSeparator: string
93
+ groupSeparator: string
94
+ currencyCode: string
95
+ currencySymbol: string
96
+ currencyPattern: number
97
+ }
98
+ interface InputProps {
99
+ name?: string
100
+ className?: string
101
+ value?: string
102
+ ["data-field"]?: string
103
+ defaultValue?: string
104
+ onChangeNumber?: (value: number) => void
105
+ onChange?: ChangeEventHandler<HTMLInputElement>
106
+ currencyOnBlur?: (e: Event | any, locale: Locale, currencyCode?: string, includingCurrencySymbol?: boolean) => void
107
+ currencyCode?: string
108
+ symbol?: boolean
109
+ readOnly?: boolean
110
+ locale?: Locale
111
+ type?: string
112
+ disabled?: boolean
113
+ required?: boolean
114
+ typeOutput?: string
115
+ min?: string | number
116
+ max?: string | number
117
+ allowZero?: boolean
118
+ }
119
+ export const CurrencyInput = (props: InputProps) => {
120
+ const [state, setState] = useState<string | undefined>(undefined)
121
+ useEffect(() => {
122
+ setState(props.value)
123
+ }, [props.value])
124
+ const onChange = (e: ChangeEvent<HTMLInputElement>) => {
125
+ const v1 = e.target.value
126
+ setState(v1)
127
+ if (props.onChange) {
128
+ props.onChange(e)
129
+ }
130
+ if (props.onChangeNumber) {
131
+ props.onChangeNumber(parseFloat(v1))
132
+ }
133
+ }
134
+ const onBlur = (e: FocusEvent<HTMLInputElement>) => {
135
+ if (props.allowZero && e.target.value === "0") {
136
+ setState("0")
137
+ return
138
+ }
139
+ if (props.locale && props.currencyOnBlur) {
140
+ props.currencyOnBlur(e, props.locale, props.currencyCode, props.symbol)
141
+ }
142
+ setTimeout(() => {
143
+ const v2 = e.target.value
144
+ setState(v2)
145
+ }, 50)
146
+ }
147
+ // return <input className={props.className} onBlur={onBlur} type={props.type} name={props.name} onChange={props.onChange ? props.onChange : onChange} disabled={props.disabled} data-field={props['data-field']} min={props.min} max={props.max} value={state} />;
148
+ return React.createElement("input", {
149
+ className: props.className,
150
+ onBlur: onBlur,
151
+ type: props.type,
152
+ name: props.name,
153
+ onChange: props.onChange ? props.onChange : onChange,
154
+ disabled: props.disabled,
155
+ "data-field": props["data-field"],
156
+ min: props.min,
157
+ max: props.max,
158
+ value: state,
159
+ })
160
+ }
161
+ export type OnClick = React.MouseEvent<HTMLElement, MouseEvent>
162
+ export function getParam(url: string, i?: number): string {
163
+ const ps = url.split("/")
164
+ if (!i || i < 0) {
165
+ i = 0
166
+ }
167
+ return ps[ps.length - 1 - i]
168
+ }
169
+ export function formatDate(date: Date | null | undefined, format: string): string {
170
+ if (!date) {
171
+ return ""
172
+ }
173
+ const opts: any = {
174
+ year: "numeric",
175
+ month: "2-digit",
176
+ day: "2-digit",
177
+ hour: "numeric",
178
+ minute: "numeric",
179
+ second: "numeric",
180
+ hour12: false,
181
+ }
182
+ const d2 = new Date(date).toLocaleString("en-US", opts)
183
+ let od = format.replace("YYYY", d2.slice(6, 10))
184
+ od = od.replace("MM", d2.slice(0, 2))
185
+ od = od.replace("DD", d2.slice(3, 5))
186
+ od = od.replace("HH", d2.slice(12, 14))
187
+ od = od.replace("mm", d2.slice(15, 17))
188
+ od = od.replace("ss", d2.slice(18, 20))
189
+ return od
190
+ }
191
+ export function dateToString(date: Date | string): string {
192
+ const d2 = typeof date !== "string" ? date : new Date(date)
193
+ const year = d2.getFullYear()
194
+ const month = pad(d2.getMonth() + 1)
195
+ const day = pad(d2.getDate())
196
+ return `${year}-${month}-${day}`
197
+ }
198
+ export function datetimeToString(date?: Date | string): string | undefined {
199
+ if (!date || date === "") {
200
+ return undefined
201
+ }
202
+ const d2 = typeof date !== "string" ? date : new Date(date)
203
+ const year = d2.getFullYear()
204
+ const month = pad(d2.getMonth() + 1)
205
+ const day = pad(d2.getDate())
206
+ const hours = pad(d2.getHours())
207
+ const minutes = pad(d2.getMinutes())
208
+ const seconds = pad(d2.getSeconds())
209
+ return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
210
+ }
211
+ function pad(n: number): string {
212
+ return n < 10 ? "0" + n : n.toString()
213
+ }
214
+ export function numberToString(n?: number | null) {
215
+ if (n == null || isNaN(n)) {
216
+ return ""
217
+ }
218
+ return n.toString()
219
+ }
220
+
221
+ export const scrollToFocus = (e: any, isUseTimeOut?: boolean) => {
222
+ try {
223
+ const element = e.target as HTMLInputElement
224
+ const form = element.form
225
+ if (form) {
226
+ const container = form.childNodes[1] as HTMLElement
227
+ const elementRect = element.getBoundingClientRect()
228
+ const absoluteElementTop = elementRect.top + window.pageYOffset
229
+ const middle = absoluteElementTop - window.innerHeight / 2
230
+ const scrollTop = container.scrollTop
231
+ const timeOut = isUseTimeOut ? 300 : 0
232
+ const isChrome = navigator.userAgent.search("Chrome") > 0
233
+ setTimeout(() => {
234
+ if (isChrome) {
235
+ const scrollPosition = scrollTop === 0 ? elementRect.top + 64 : scrollTop + middle
236
+ container.scrollTo(0, Math.abs(scrollPosition))
237
+ } else {
238
+ container.scrollTo(0, Math.abs(scrollTop + middle))
239
+ }
240
+ }, timeOut)
241
+ }
242
+ } catch (e) {
243
+ console.log(e)
244
+ }
245
+ }
246
+
247
+ // Keyboard shortcuts that should always be allowed
248
+ const SHORTCUT_KEYS = new Set(["a", "c", "v", "x", "z", "y"])
249
+
250
+ // Non-printable keys that should always be allowed
251
+ const CONTROL_KEYS = new Set([
252
+ "Backspace",
253
+ "Delete",
254
+ "Tab",
255
+ "Enter",
256
+ "Escape",
257
+
258
+ "ArrowLeft",
259
+ "ArrowRight",
260
+ "ArrowUp",
261
+ "ArrowDown",
262
+
263
+ "Home",
264
+ "End",
265
+
266
+ "PageUp",
267
+ "PageDown",
268
+
269
+ "Insert",
270
+ ])
271
+
272
+ export function detectShortcut(e: KeyboardEvent): boolean {
273
+ return (e.ctrlKey || e.metaKey) && SHORTCUT_KEYS.has(e.key.toLowerCase())
274
+ }
275
+
276
+ function isDigit(key: string): boolean {
277
+ return key.length === 1 && key >= "0" && key <= "9"
278
+ }
279
+
280
+ function isControlKey(key: string): boolean {
281
+ return CONTROL_KEYS.has(key)
282
+ }
283
+
284
+ /**
285
+ * Digits only
286
+ * Allow:
287
+ * 0-9
288
+ */
289
+ export function digitKeyDown(e: KeyboardEvent): boolean {
290
+ if (detectShortcut(e)) {
291
+ return true
292
+ }
293
+ const key = e.key
294
+ if (isControlKey(key)) {
295
+ return true
296
+ }
297
+ return isDigit(key)
298
+ }
299
+
300
+ /**
301
+ * Integer input
302
+ * Allow:
303
+ * -123
304
+ * 123
305
+ */
306
+ export function integerKeyDown(e: KeyboardEvent): boolean {
307
+ if (detectShortcut(e)) {
308
+ return true
309
+ }
310
+ const key = e.key
311
+ if (isControlKey(key)) {
312
+ return true
313
+ }
314
+ const input = e.target as HTMLInputElement
315
+
316
+ if (key === "-") {
317
+ if (!input.min) {
318
+ return true
319
+ } else {
320
+ const min = Number(input.min)
321
+ return !Number.isNaN(min) && min < 0 && !input.value.includes("-")
322
+ }
323
+ }
324
+
325
+ return isDigit(key)
326
+ }
327
+
328
+ /**
329
+ * Decimal numbers
330
+ * Allow:
331
+ * -123.45
332
+ * -123,45
333
+ * -123٫45 (Arabic decimal separator)
334
+ * depending on decimalSeparator
335
+ */
336
+ export function numberKeyDown(e: KeyboardEvent, decimalSeparator?: "." | "," | "٫"): boolean {
337
+ if (detectShortcut(e)) {
338
+ return true
339
+ }
340
+
341
+ const key = e.key
342
+
343
+ if (isControlKey(key)) {
344
+ return true
345
+ }
346
+
347
+ const input = e.target as HTMLInputElement
348
+ if (key === "-") {
349
+ if (!input.min) {
350
+ return true
351
+ } else {
352
+ const min = Number(input.min)
353
+ return !Number.isNaN(min) && min < 0 && !input.value.includes("-")
354
+ }
355
+ }
356
+
357
+ if (key === "." || key === "," || key === "٫") {
358
+ if (!decimalSeparator) {
359
+ decimalSeparator = "."
360
+ }
361
+ return key === decimalSeparator && !input.value.includes(decimalSeparator)
362
+ }
363
+
364
+ return isDigit(key)
365
+ }
366
+ export function digitOnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
367
+ if (!digitKeyDown(e.nativeEvent)) {
368
+ e.preventDefault()
369
+ }
370
+ }
371
+ export function integerOnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
372
+ if (!integerKeyDown(e.nativeEvent)) {
373
+ e.preventDefault()
374
+ }
375
+ }
376
+ export function numberOnKeyDown(e: React.KeyboardEvent<HTMLInputElement>, decimalSeparator?: "." | "," | "٫") {
377
+ if (!numberKeyDown(e.nativeEvent, decimalSeparator)) {
378
+ e.preventDefault()
379
+ }
380
+ }