react-hook-core 0.4.6 → 0.4.8

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/core.ts CHANGED
@@ -1,504 +1,216 @@
1
- import { Params } from 'react-router';
2
- import { focusFirstElement } from './formutil';
1
+ import { focusFirstElement } from "./formutil"
3
2
 
4
- export const pageSizes = [12, 24, 60, 100, 120, 180, 300, 600];
3
+ export interface LoadingService {
4
+ showLoading(firstTime?: boolean): void
5
+ hideLoading(): void
6
+ }
7
+ export const pageSizes = [12, 24, 60, 100, 120, 180, 300, 600]
8
+ export const sizes = pageSizes
5
9
  // tslint:disable-next-line:class-name
6
10
  export class resources {
7
- static phone = / |-|\.|\(|\)/g;
8
- static _cache: any = {};
9
- static cache = true;
10
- static fields = "fields";
11
- static page = "page";
12
- static limit = "limit";
13
- static defaultLimit = 24;
14
- static limits = pageSizes;
15
- static pageMaxSize = 7;
16
- }
17
- export const size = pageSizes;
18
- export interface ModelMap {
19
- [key: string]: any;
20
- }
21
- export interface PageChange {
22
- page: number; // currentPage
23
- size: number; // itemsPerPage
24
- }
25
- export interface ModelProps {
26
- setGlobalState?: (m: ModelMap) => void;
27
- shouldBeCustomized?: boolean;
28
- }
29
- export interface EditPermission {
30
- addable?: boolean;
31
- readOnly?: boolean;
32
- deletable?: boolean;
33
- }
34
- export interface SearchPermission {
35
- viewable?: boolean;
36
- addable?: boolean;
37
- editable?: boolean;
38
- deletable?: boolean;
39
- approvable?: boolean;
40
- }
41
- export interface SearchParameter {
42
- resource: ResourceService;
43
- showMessage: (msg: string, option?: string) => void;
44
- showError: (m: string, callback?: () => void, h?: string) => void;
45
- ui?: UIService;
46
- getLocale?: (profile?: string) => Locale;
47
- loading?: LoadingService;
48
- auto?: boolean;
49
- }
50
- /*
51
- export interface EditStatusConfig {
52
- duplicate_key: number | string;
53
- not_found: number | string;
54
- success: number | string;
55
- version_error: number | string;
56
- error?: number | string;
57
- data_corrupt?: number | string;
58
- }
59
- export function createEditStatus(status?: EditStatusConfig): EditStatusConfig {
60
- if (status) {
61
- return status;
62
- }
63
- const s: EditStatusConfig = {
64
- duplicate_key: 0,
65
- not_found: 0,
66
- success: 1,
67
- version_error: -1,
68
- error: 2,
69
- data_corrupt: 4
70
- };
71
- return s;
72
- }
73
- export interface DiffStatusConfig {
74
- not_found: number | string;
75
- success: number | string;
76
- version_error: number | string;
77
- error?: number | string;
78
- }
79
- export function createDiffStatus(status?: DiffStatusConfig): DiffStatusConfig {
80
- if (status) {
81
- return status;
82
- }
83
- const s: DiffStatusConfig = {
84
- not_found: 0,
85
- success: 1,
86
- version_error: 2,
87
- error: 4
88
- };
89
- return s;
90
- }
91
- */
92
- export interface Filter {
93
- q?: string;
94
- page?: number;
95
- limit: number;
96
- firstLimit?: number;
97
- fields?: string[];
98
- sort?: string;
99
- }
100
- export interface SearchResult<T> {
101
- total?: number;
102
- list: T[];
103
- next?: string;
104
- last?: boolean;
105
- }
106
- export interface SearchState<T, S extends Filter> {
107
- model?: S;
108
- q?: string;
109
- list?: T[];
110
- }
111
- export interface SearchService<T, S extends Filter> {
112
- keys?(): string[];
113
- search(s: S, limit?: number, offset?: number | string, fields?: string[]): Promise<SearchResult<T>>;
114
- }
115
- export interface ViewParameter {
116
- resource: ResourceService;
117
- showError: (m: string, header?: string, detail?: string, callback?: () => void) => void;
118
- getLocale?: (profile?: string) => Locale;
119
- loading?: LoadingService;
120
- }
121
- export interface ViewService<T, ID> {
122
- metadata?(): Attributes | undefined;
123
- keys?(): string[];
124
- load(id: ID, ctx?: any): Promise<T | null>;
11
+ static phone = / |-|\.|\(|\)/g
12
+ static _cache: any = {}
13
+ static cache = true
14
+ static fields = "fields"
15
+ static page = "page"
16
+ static limit = "limit"
17
+ static defaultLimit = 24
18
+ static limits = pageSizes
19
+ static pageMaxSize = 7
125
20
  }
126
21
 
127
- export interface DiffParameter {
128
- resource: ResourceService;
129
- showMessage: (msg: string, option?: string) => void;
130
- showError: (m: string, header?: string, detail?: string, callback?: () => void) => void;
131
- loading?: LoadingService;
132
- // status?: DiffStatusConfig;
133
- }
134
- export interface BaseDiffState {
135
- disabled: boolean;
136
- }
137
- export interface DiffModel<T, ID> {
138
- id?: ID;
139
- origin?: T;
140
- value: T;
141
- }
142
- export interface DiffModel<T, ID> {
143
- id?: ID;
144
- origin?: T;
145
- value: T;
146
- }
147
- export interface ApprService<ID> {
148
- approve(id: ID, ctx?: any): Promise<number | string>;
149
- reject(id: ID, ctx?: any): Promise<number | string>;
150
- }
151
- export interface DiffService<T, ID> {
152
- keys(): string[];
153
- diff(id: ID, ctx?: any): Promise<DiffModel<T, ID>>;
154
- }
155
- export interface DiffApprService<T, ID> extends DiffService<T, ID>, ApprService<ID> {
156
- }
157
- export interface DiffState<T> {
158
- origin: T;
159
- value: T;
160
- disabled: boolean;
161
- }
162
-
163
- export function getCurrencyCode(form?: HTMLFormElement | null): string | undefined {
164
- if (form) {
165
- const x = form.getAttribute('currency-code');
166
- if (x) {
167
- return x;
168
- }
169
- }
170
- return undefined;
171
- }
172
22
  export function removePhoneFormat(phone: string): string {
173
23
  if (phone) {
174
- return phone.replace(resources.phone, '');
24
+ return phone.replace(resources.phone, "")
175
25
  } else {
176
- return phone;
26
+ return phone
177
27
  }
178
28
  }
179
29
  export interface StringMap {
180
- [key: string]: string;
30
+ [key: string]: string
181
31
  }
182
32
  export interface ResourceService {
183
- resource(): StringMap;
184
- value(key: string, param?: any): string;
185
- format(f: string, ...args: any[]): string;
186
- }
187
- export interface Message {
188
- message: string;
189
- title: string;
190
- yes?: string;
191
- no?: string;
192
- }
193
- export function getString(key: string, gv: StringMap | ((key: string) => string)): string {
194
- if (typeof gv === 'function') {
195
- return gv(key);
196
- } else {
197
- return gv[key];
198
- }
199
- }
200
- export function message(gv: StringMap | ((key: string) => string), msg: string, title?: string, yes?: string, no?: string): Message {
201
- const m2 = (msg && msg.length > 0 ? getString(msg, gv) : '');
202
- const m: Message = { message: m2, title: '' };
203
- if (title && title.length > 0) {
204
- m.title = getString(title, gv);
205
- }
206
- if (yes && yes.length > 0) {
207
- m.yes = getString(yes, gv);
208
- }
209
- if (no && no.length > 0) {
210
- m.no = getString(no, gv);
211
- }
212
- return m;
213
- }
214
- export function messageByHttpStatus(status: number, gv: StringMap | ((key: string) => string)): string {
215
- const k = 'error_' + status;
216
- let msg = getString(k, gv);
217
- if (!msg || msg.length === 0) {
218
- msg = getString('error_500', gv);
219
- }
220
- return msg;
33
+ resource(): StringMap
34
+ value(key: string, param?: any): string
221
35
  }
222
36
 
223
37
  export interface Locale {
224
- id?: string;
225
- countryCode: string;
226
- dateFormat: string;
227
- firstDayOfWeek: number;
228
- decimalSeparator: string;
229
- groupSeparator: string;
230
- decimalDigits: number;
231
- currencyCode: string;
232
- currencySymbol: string;
233
- currencyPattern: number;
234
- currencySample?: string;
235
- }
236
- export interface LoadingService {
237
- showLoading(firstTime?: boolean): void;
238
- hideLoading(): void;
38
+ id?: string
39
+ countryCode: string
40
+ dateFormat: string
41
+ firstDayOfWeek: number
42
+ decimalSeparator: string
43
+ groupSeparator: string
44
+ decimalDigits: number
45
+ currencyCode: string
46
+ currencySymbol: string
47
+ currencyPattern: number
48
+ currencySample?: string
239
49
  }
240
50
  export interface ErrorMessage {
241
- field: string;
242
- code: string;
243
- param?: string | number | Date;
244
- message?: string;
51
+ field: string
52
+ code: string
53
+ param?: string | number | Date
54
+ message?: string
245
55
  }
246
56
  export interface UIService {
247
- getValue(el: HTMLInputElement, locale?: Locale, currencyCode?: string): string | number | boolean | null | undefined;
57
+ getValue(el: HTMLInputElement, locale?: Locale, currencyCode?: string): string | number | boolean | null | undefined
248
58
  // decodeFromForm(form: HTMLFormElement, locale?: Locale, currencyCode?: string | null): any;
249
59
 
250
- validateForm(form?: HTMLFormElement, locale?: Locale, focusFirst?: boolean, scroll?: boolean): boolean;
251
- removeFormError(form: HTMLFormElement): void;
252
- removeError(el: HTMLInputElement): void;
253
- showFormError(form?: HTMLFormElement, errors?: ErrorMessage[], focusFirst?: boolean): ErrorMessage[];
254
- buildErrorMessage(errors: ErrorMessage[]): string;
60
+ validateForm(form?: HTMLFormElement, locale?: Locale, focusFirst?: boolean, scroll?: boolean): boolean
61
+ removeFormError(form: HTMLFormElement): void
62
+ removeError(el: HTMLInputElement): void
63
+ showFormError(form?: HTMLFormElement, errors?: ErrorMessage[], focusFirst?: boolean): ErrorMessage[]
64
+ buildErrorMessage(errors: ErrorMessage[]): string
255
65
 
256
- registerEvents?(form: HTMLFormElement): void;
66
+ registerEvents?(form: HTMLFormElement): void
257
67
  }
258
68
 
259
- export type DataType = 'ObjectId' | 'date' | 'datetime' | 'time'
260
- | 'boolean' | 'number' | 'integer' | 'string' | 'text'
261
- | 'object' | 'array' | 'binary'
262
- | 'primitives' | 'booleans' | 'numbers' | 'integers' | 'strings' | 'dates' | 'datetimes' | 'times';
263
- /*
264
- export interface Metadata {
265
- name?: string;
266
- attributes: Attributes;
267
- source?: string;
268
- }
269
- */
69
+ export type DataType =
70
+ | "ObjectId"
71
+ | "date"
72
+ | "datetime"
73
+ | "time"
74
+ | "boolean"
75
+ | "number"
76
+ | "integer"
77
+ | "string"
78
+ | "text"
79
+ | "object"
80
+ | "array"
81
+ | "binary"
82
+ | "primitives"
83
+ | "booleans"
84
+ | "numbers"
85
+ | "integers"
86
+ | "strings"
87
+ | "dates"
88
+ | "datetimes"
89
+ | "times"
90
+
270
91
  export interface Attribute {
271
- name?: string;
272
- type?: DataType;
273
- key?: boolean;
274
- version?: boolean;
275
- typeof?: Attributes;
92
+ name?: string
93
+ type?: DataType
94
+ key?: boolean
95
+ version?: boolean
96
+ typeof?: Attributes
276
97
  }
277
98
  export interface Attributes {
278
- [key: string]: Attribute;
99
+ [key: string]: Attribute
279
100
  }
280
101
 
281
- export function buildKeys(attributes: Attributes): string[] {
282
- if (!attributes) {
283
- return [];
284
- }
285
- const ks = Object.keys(attributes);
286
- const ps = [];
287
- for (const k of ks) {
288
- const attr: Attribute = attributes[k];
289
- if (attr.key === true) {
290
- ps.push(k);
291
- }
292
- }
293
- return ps;
294
- }
295
- type Readonly<T> = {
296
- readonly [P in keyof T]: T[P];
297
- };
298
- export function buildId<ID>(p: Readonly<Params<string>>, keys?: string[]): ID | null {
299
- if (!keys || keys.length === 0 || keys.length === 1) {
300
- if (keys && keys.length === 1) {
301
- if (p[keys[0]]) {
302
- return p[keys[0]] as any;
303
- }
304
- }
305
- return p['id'] as any;
306
- }
307
- const id: any = {};
308
- for (const key of keys) {
309
- let v = p[key];
310
- if (!v) {
311
- v = p[key];
312
- if (!v) {
313
- return null;
314
- }
315
- }
316
- id[key] = v;
317
- }
318
- return id;
319
- }
320
102
  export const datetimeToString = (inputDate: Date) => {
321
- const date = new Date(inputDate);
322
- const year = date.getFullYear();
323
- const month = String(date.getMonth() + 1).padStart(2, '0');
324
- const day = String(date.getDate()).padStart(2, '0');
325
- const hours = String(date.getHours()).padStart(2, '0');
326
- const minutes = String(date.getMinutes()).padStart(2, '0');
327
- const seconds = String(date.getSeconds()).padStart(2, '0');
328
- return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
329
- };
330
-
331
- export const dateToString = (inputDate: Date) => {
332
- const year = inputDate.getFullYear();
333
- const month = String(inputDate.getMonth() + 1).padStart(2, '0');
334
- const day = String(inputDate.getDate()).padStart(2, '0');
335
- return `${year}-${month}-${day}`;
336
- };
337
- /*
338
- export function formatFax(value: string) {
339
- return formatter.formatFax(value);
103
+ const date = new Date(inputDate)
104
+ const year = date.getFullYear()
105
+ const month = String(date.getMonth() + 1).padStart(2, "0")
106
+ const day = String(date.getDate()).padStart(2, "0")
107
+ const hours = String(date.getHours()).padStart(2, "0")
108
+ const minutes = String(date.getMinutes()).padStart(2, "0")
109
+ const seconds = String(date.getSeconds()).padStart(2, "0")
110
+ return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
340
111
  }
341
112
 
342
- export function formatPhone(value: string) {
343
- return formatter.formatPhone(value);
344
- }
345
- export function formatNumber(num: string|number, scale?: number, locale?: Locale): string {
346
- if (!scale) {
347
- scale = 2;
348
- }
349
- if (!locale) {
350
- locale = storage.getLocale();
351
- }
352
- let c: number;
353
- if (!num) {
354
- return '';
355
- } else if (typeof num === 'number') {
356
- c = num;
357
- } else {
358
- const x: any = num;
359
- if (isNaN(x)) {
360
- return '';
361
- } else {
362
- c = parseFloat(x);
363
- }
364
- }
365
- return storage.locale().formatNumber(c, scale, locale);
366
- }
367
-
368
- export function formatCurrency(currency: string|number, locale?: Locale, currencyCode?: string) {
369
- if (!currencyCode) {
370
- currencyCode = 'USD';
371
- }
372
- if (!locale) {
373
- locale = storage.getLocale();
374
- }
375
- let c: number;
376
- if (!currency) {
377
- return '';
378
- } else if (typeof currency === 'number') {
379
- c = currency;
380
- } else {
381
- let x: any = currency;
382
- x = x.replace(locale.decimalSeparator, '.');
383
- if (isNaN(x)) {
384
- return '';
385
- } else {
386
- c = parseFloat(x);
387
- }
388
- }
389
- return storage.locale().formatCurrency(c, currencyCode, locale);
113
+ export const dateToString = (inputDate: Date) => {
114
+ const year = inputDate.getFullYear()
115
+ const month = String(inputDate.getMonth() + 1).padStart(2, "0")
116
+ const day = String(inputDate.getDate()).padStart(2, "0")
117
+ return `${year}-${month}-${day}`
390
118
  }
391
- */
392
119
 
393
120
  export function initForm(form?: HTMLFormElement, initMat?: (f: HTMLFormElement) => void): HTMLFormElement | undefined {
394
121
  if (form) {
395
122
  setTimeout(() => {
396
123
  if (initMat) {
397
- initMat(form);
124
+ initMat(form)
398
125
  }
399
- focusFirstElement(form);
400
- }, 100);
401
- }
402
- return form;
403
- }
404
- export function error(err: any, gv: StringMap | ((key: string) => string), ae: (msg: string, callback?: () => void, header?: string) => void) {
405
- const title = getString('error', gv);
406
- let msg = getString('error_internal', gv);
407
- if (!err) {
408
- ae(msg, undefined, title);
409
- return;
410
- }
411
- const data = err && err.response ? err.response : err;
412
- if (data) {
413
- const status = data.status;
414
- if (status && !isNaN(status)) {
415
- msg = messageByHttpStatus(status, gv);
416
- }
417
- ae(msg, undefined, title);
418
- } else {
419
- ae(msg, undefined, title);
126
+ focusFirstElement(form)
127
+ }, 100)
420
128
  }
129
+ return form
421
130
  }
422
131
  export function getName(d: string, n?: string): string {
423
- return (n && n.length > 0 ? n : d);
132
+ return n && n.length > 0 ? n : d
424
133
  }
425
134
  export function getModelName(form?: HTMLFormElement | null, name?: string): string {
426
135
  if (form) {
427
- const a = form.getAttribute('model-name');
136
+ const a = form.getAttribute("model-name")
428
137
  if (a && a.length > 0) {
429
- return a;
138
+ return a
430
139
  }
431
- const b = form.name;
140
+ const b = form.name
432
141
  if (b) {
433
- if (b.endsWith('Form')) {
434
- return b.substr(0, b.length - 4);
142
+ if (b.endsWith("Form")) {
143
+ return b.substring(0, b.length - 4)
435
144
  }
436
- return b;
145
+ return b
437
146
  }
438
147
  }
439
148
  if (name && name.length > 0) {
440
- return name;
149
+ return name
441
150
  }
442
- return '';
151
+ return ""
443
152
  }
444
153
 
445
154
  export const scrollToFocus = (e: any, isUseTimeOut?: boolean) => {
446
155
  try {
447
- const element = e.target as HTMLInputElement;
448
- const form = element.form;
156
+ const element = e.target as HTMLInputElement
157
+ const form = element.form
449
158
  if (form) {
450
- const container = form.childNodes[1] as HTMLElement;
451
- const elementRect = element.getBoundingClientRect();
452
- const absoluteElementTop = elementRect.top + window.pageYOffset;
453
- const middle = absoluteElementTop - (window.innerHeight / 2);
454
- const scrollTop = container.scrollTop;
455
- const timeOut = isUseTimeOut ? 300 : 0;
456
- const isChrome = navigator.userAgent.search('Chrome') > 0;
159
+ const container = form.childNodes[1] as HTMLElement
160
+ const elementRect = element.getBoundingClientRect()
161
+ const absoluteElementTop = elementRect.top + window.pageYOffset
162
+ const middle = absoluteElementTop - window.innerHeight / 2
163
+ const scrollTop = container.scrollTop
164
+ const timeOut = isUseTimeOut ? 300 : 0
165
+ const isChrome = navigator.userAgent.search("Chrome") > 0
457
166
  setTimeout(() => {
458
167
  if (isChrome) {
459
- const scrollPosition = scrollTop === 0 ? (elementRect.top + 64) : (scrollTop + middle);
460
- container.scrollTo(0, Math.abs(scrollPosition));
168
+ const scrollPosition = scrollTop === 0 ? elementRect.top + 64 : scrollTop + middle
169
+ container.scrollTo(0, Math.abs(scrollPosition))
461
170
  } else {
462
- container.scrollTo(0, Math.abs(scrollTop + middle));
171
+ container.scrollTo(0, Math.abs(scrollTop + middle))
463
172
  }
464
- }, timeOut);
173
+ }, timeOut)
465
174
  }
466
175
  } catch (e) {
467
- console.log(e);
176
+ console.log(e)
468
177
  }
469
- };
178
+ }
470
179
  export interface LoadingParameter {
471
- loading?: LoadingService;
180
+ loading?: LoadingService
472
181
  }
473
182
  export function showLoading(s?: LoadingService): void {
474
183
  if (s) {
475
- s.showLoading();
184
+ s.showLoading()
476
185
  }
477
186
  }
478
187
  export function hideLoading(s?: LoadingService): void {
479
188
  if (s) {
480
- s.hideLoading();
189
+ s.hideLoading()
481
190
  }
482
191
  }
483
192
  export interface UIParameter {
484
- ui?: UIService;
193
+ ui?: UIService
485
194
  }
486
195
  export function getRemoveError(u?: UIParameter, rmErr?: (el: HTMLInputElement) => void): ((el: HTMLInputElement) => void) | undefined {
487
196
  if (rmErr) {
488
- return rmErr;
197
+ return rmErr
489
198
  }
490
- return (u && u.ui ? u.ui.removeError : undefined);
199
+ return u && u.ui ? u.ui.removeError : undefined
491
200
  }
492
201
  export function removeFormError(u?: UIParameter, f?: HTMLFormElement): void {
493
202
  if (f && u && u.ui) {
494
- u.ui.removeFormError(f);
203
+ u.ui.removeFormError(f)
495
204
  }
496
205
  }
497
- export function getValidateForm(u?: UIParameter, vf?: (form: HTMLFormElement, locale?: Locale, focusFirst?: boolean, scroll?: boolean) => boolean): ((form: HTMLFormElement, locale?: Locale, focusFirst?: boolean, scroll?: boolean) => boolean) | undefined {
206
+ export function getValidateForm(
207
+ u?: UIParameter,
208
+ vf?: (form: HTMLFormElement, locale?: Locale, focusFirst?: boolean, scroll?: boolean) => boolean,
209
+ ): ((form: HTMLFormElement, locale?: Locale, focusFirst?: boolean, scroll?: boolean) => boolean) | undefined {
498
210
  if (vf) {
499
- return vf;
211
+ return vf
500
212
  }
501
- return (u && u.ui ? u.ui.validateForm : undefined);
213
+ return u && u.ui ? u.ui.validateForm : undefined
502
214
  }
503
215
  /*
504
216
  export function getDecodeFromForm(u?: UIParameter, d?: (form: HTMLFormElement, locale?: Locale, currencyCode?: string) => any): ((form: HTMLFormElement, locale?: Locale, currencyCode?: string) => any) | undefined {