react-hook-core 0.5.16 → 0.5.18

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/README.md CHANGED
@@ -1 +1,397 @@
1
- # react-hook-core
1
+ # react-hook-core
2
+
3
+ A TypeScript utility library for React applications. It provides reusable building blocks for common data-entry and administration screens: form-state updates, search filters, pagination, sorting, URL query handling, edit/save workflows, object comparison, locale-aware numeric input, and a small set of shared React components.
4
+
5
+ The library is used by the `react-admin` frontend, but its exported helpers are not tied to a particular admin application or backend API.
6
+
7
+ ## What it provides
8
+
9
+ | Area | Main capabilities |
10
+ |---|---|
11
+ | Form state | Update a model from input, select, textarea, checkbox, and radio events; support nested field paths and typed values. |
12
+ | Search and lists | Filter models, page-size and page changes, sort state, result messages, and URL synchronization. |
13
+ | Routing | Read URL query parameters into typed models and navigate back with an unsaved-change confirmation. |
14
+ | Edit workflows | Create an initial model from attribute metadata and handle common create/update results. |
15
+ | Object utilities | Clone objects, compare values, calculate changed fields, create partial updates, and set nested values. |
16
+ | Locale and numbers | Normalize phone/fax and numeric strings; parse and format currency-like input using locale settings. |
17
+ | React helpers | A message hook and small reusable components for loading, error, select, page-size, and search UI. |
18
+ | Keyboard input | Allow valid digit, integer, and decimal keystrokes while preserving common editing shortcuts. |
19
+
20
+ This package is a collection of helpers, not a data-fetching framework or a global state-management solution. For example, search functions call a callback supplied by the application; they do not make HTTP requests themselves.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install react-hook-core
26
+ ```
27
+
28
+ ### Runtime dependency note
29
+
30
+ The current `package.json` lists `react` and `query-string` under `devDependencies`, not `dependencies` or `peerDependencies`. The source imports React at runtime, and `route.ts` imports `query-string` at runtime. Make sure the consuming application provides compatible versions of these packages. The navigation helper types also reference `NavigateFunction` from `react-router`.
31
+
32
+ The package manifest should be reviewed before publishing or consuming this package in an environment that installs production dependencies only. In particular, `query-string` should be declared as a runtime dependency (or otherwise guaranteed by the application), and React should normally be declared as a peer dependency for a React library.
33
+
34
+ ## Quick start
35
+
36
+ ### 1. Keep a form model in React state
37
+
38
+ `updateState` reads the changed control and updates the corresponding model property. It uses the control's `data-field` attribute when present; otherwise it uses `name`. Nested paths such as `address.city` are supported by the underlying `setValue` helper.
39
+
40
+ ```tsx
41
+ import { useState } from "react"
42
+ import { updateState } from "react-hook-core"
43
+
44
+ interface User {
45
+ username: string
46
+ displayName: string
47
+ active: boolean
48
+ }
49
+
50
+ export function UserForm() {
51
+ const [user, setUser] = useState<User>({
52
+ username: "",
53
+ displayName: "",
54
+ active: true,
55
+ })
56
+
57
+ return (
58
+ <form>
59
+ <input
60
+ name="username"
61
+ value={user.username}
62
+ onChange={(e) => updateState(e, user, setUser)}
63
+ />
64
+
65
+ <input
66
+ name="displayName"
67
+ value={user.displayName}
68
+ onChange={(e) => updateState(e, user, setUser)}
69
+ />
70
+
71
+ <input
72
+ type="checkbox"
73
+ name="active"
74
+ checked={user.active}
75
+ onChange={(e) => updateState(e, user, setUser)}
76
+ />
77
+ </form>
78
+ )
79
+ }
80
+ ```
81
+
82
+ `updateState` mutates the supplied model and then calls the setter with a shallow copy (`{ ...model }`) to trigger a React render. Call it with the current model and its corresponding state setter. For numeric and locale-aware fields, see [Form state and value conversion](#form-state-and-value-conversion).
83
+
84
+ ### 2. Build a searchable list
85
+
86
+ The library defines the filter and result contracts, plus helpers for pagination, sorting, and URL state. The application still owns the API call and the React state.
87
+
88
+ ```tsx
89
+ import { useState } from "react"
90
+ import {
91
+ Filter,
92
+ SearchResult,
93
+ getOffset,
94
+ onPageChanged,
95
+ resources,
96
+ } from "react-hook-core"
97
+
98
+ interface User {
99
+ userId: string
100
+ username: string
101
+ }
102
+
103
+ interface UserFilter extends Filter {
104
+ status?: string
105
+ }
106
+
107
+ async function loadUsers(filter: UserFilter): Promise<SearchResult<User>> {
108
+ // Call the application's API client here.
109
+ // The service can use getOffset(filter.limit, filter.page, filter.firstLimit)
110
+ // to calculate the requested offset.
111
+ return { list: [], total: 0 }
112
+ }
113
+
114
+ export function UserList() {
115
+ const [filter, setFilter] = useState<UserFilter>({
116
+ limit: resources.defaultLimit,
117
+ })
118
+ const [users, setUsers] = useState<User[]>([])
119
+
120
+ const search = async (nextFilter: UserFilter) => {
121
+ const result = await loadUsers(nextFilter)
122
+ setUsers(result.list)
123
+ }
124
+
125
+ const changePage = (page: number, size: number) => {
126
+ onPageChanged({ page, size }, search, filter)
127
+ setFilter({ ...filter, page, limit: size })
128
+ }
129
+
130
+ return (
131
+ <div>
132
+ {/* Render users and connect your pager to changePage. */}
133
+ <span>{users.length} loaded</span>
134
+ </div>
135
+ )
136
+ }
137
+ ```
138
+
139
+ The example illustrates the callback-oriented API. In a real screen, keep filter updates and the search callback coordinated so that the API request, displayed rows, and URL all represent the same filter. The helpers generally mutate the filter passed to them; see [Search, pagination, sorting, and URL state](#search-pagination-sorting-and-url-state).
140
+
141
+ ### 3. Show message and validation feedback
142
+
143
+ `useMessage` stores a message and a CSS class for the caller to render.
144
+
145
+ ```tsx
146
+ import { useMessage } from "react-hook-core"
147
+
148
+ export function MessageExample() {
149
+ const { msg, showMessage, showError, hideMessage } = useMessage({})
150
+
151
+ return (
152
+ <section>
153
+ <div className={msg.alertClass}>{msg.message}</div>
154
+ <button type="button" onClick={() => showMessage("Saved")}>Show</button>
155
+ <button type="button" onClick={() => showError("Unable to save")}>Error</button>
156
+ <button type="button" onClick={hideMessage}>Hide</button>
157
+ </section>
158
+ )
159
+ }
160
+ ```
161
+
162
+ The hook does not render an alert itself. The consuming application supplies the markup and CSS for the `alert alert-info` and `alert alert-error` class names.
163
+
164
+ ## API guide
165
+
166
+ All modules are re-exported from the package entry point (`src/index.ts`). Consumers can import from `react-hook-core` rather than importing individual source files.
167
+
168
+ ### Form state and value conversion
169
+
170
+ The main functions are in `state.ts`:
171
+
172
+ | API | Purpose |
173
+ |---|---|
174
+ | `updateState(event, model, setModel, decimalSeparator?, formatStr?, callback?)` | Read a form control and update its model field. |
175
+ | `formatAndUpdateState(event, model, setModel, formatStr?, decimalSeparator?, callback?)` | Convenience wrapper that places `formatStr` before `decimalSeparator`. |
176
+ | `updateStateAndCallback(event, model, setModel, callback?, decimalSeparator?, formatStr?)` | Convenience wrapper that places the callback before locale/format arguments. |
177
+ | `updateNumber(event, model, setModel, decimalSeparator?, callback?, formatStr?)` | Update a numeric field using numeric normalization. |
178
+ | `getDecimalSeparator(input)` | Read `data-decimal-separator` from the input or its form; defaults to `.`. |
179
+ | `normalizeInteger(value)` | Keep digits `0`–`9`. |
180
+ | `normalizeNumber(value)` | Keep digits and convert comma / Arabic decimal separator to `.`. |
181
+ | `removeSeparators(value)` | Keep digits and `.`. |
182
+ | `valueOfCheckbox(input)` | Return the checked value, optionally using `data-on-value` and `data-off-value`. |
183
+
184
+ `updateState` uses these conventions:
185
+
186
+ - The model field is taken from `data-field`, falling back to the control's `name`.
187
+ - A `SELECT` stores its selected value as a string and updates its `data-value` attribute.
188
+ - A checkbox whose `name` and `id` differ is treated as part of a string-value array. Other checkboxes are treated as booleans or use `data-on-value` / `data-off-value`.
189
+ - Radio buttons store their selected string value.
190
+ - `date` and `datetime-local` inputs are converted to ISO strings; `time` inputs are converted to epoch milliseconds.
191
+ - `data-type="phone"`, `"fax"`, `"integer"`, and `"number"` trigger their corresponding normalization.
192
+ - Dotted field paths are handled by `reflect.setValue`. The setter also recognizes bracket notation for arrays, but its indexed-array behavior should be tested before relying on arbitrary array positions.
193
+
194
+ For example, a locale-aware number input can use `data-type="number"` and the locale's decimal separator:
195
+
196
+ ```tsx
197
+ <input
198
+ name="amount"
199
+ data-type="number"
200
+ value={String(model.amount ?? "")}
201
+ onChange={(e) => updateState(e, model, setModel, locale.decimalSeparator)}
202
+ />
203
+ ```
204
+
205
+ `updateState` is intended for browser form events. It directly reads and sometimes changes DOM attributes such as `data-value`; it is not a general-purpose immutable object reducer.
206
+
207
+ ### Search, pagination, sorting, and URL state
208
+
209
+ The main contracts in `search.ts` are:
210
+
211
+ - `Filter`: `q`, `page`, required `limit`, optional `firstLimit`, `fields`, and `sort`.
212
+ - `SearchResult<T>`: `list` plus optional `total`, `next`, and `last`.
213
+ - `SearchService<T, S>`: an application-provided `search(filter, limit?, offset?, fields?)` method returning a `Promise<SearchResult<T>>`.
214
+ - `PageChange`, `Pagination`, and `Sortable`: page and sort state shapes used by the helpers.
215
+
216
+ Important helper groups:
217
+
218
+ | Group | APIs |
219
+ |---|---|
220
+ | Filter initialization | `mergeFilter`, `isArray`, `initFilter` |
221
+ | Visible fields / result display | `getFields`, `getPageTotal`, `formatText`, `buildMessage` |
222
+ | Query-string synchronization | `addParametersIntoUrl`, `updateUrl` |
223
+ | Sort model | `buildSort`, `setSort`, `buildSortFilter`, `getSortId`, `setSortFilter`, `sort`, `handleSort`, `getSortElement`, `toggleSortStyle`, `removeSortStatus`, `onSort`, `sortOnChange` |
224
+ | Search and paging events | `getNumber`, `handleToggle`, `onToggleSearch`, `resetSearch`, `onClearQ`, `onPageSizeChanged`, `onPageChanged`, `onSearch` |
225
+ | Offset calculation | `getOffset` |
226
+
227
+ A common list-screen sequence is:
228
+
229
+ 1. Create a filter with at least `limit`.
230
+ 2. Use `buildFromUrl` / `buildParameters` or `initFilter` to restore filter and paging state.
231
+ 3. Call the application's search service with the filter and an offset from `getOffset`.
232
+ 4. Use `onPageChanged`, `onPageSizeChanged`, `onSearch`, and sorting helpers to update the filter and invoke the application's search callback.
233
+ 5. Use `updateUrl` or `addParametersIntoUrl` when the screen should reflect filter state in the browser URL.
234
+
235
+ `resources.defaultLimit` is `24`; `resources.limits` defaults to `[12, 24, 60, 100, 120, 180, 300, 600]`. `getOffset(limit, page, firstLimit)` supports a different first-page size. The helpers do not make requests or own list state.
236
+
237
+ Some helpers mutate their arguments. In particular, `mergeFilter`, `initFilter`, `buildSortFilter`, `setSortFilter`, and the event handlers may update the supplied filter or sort state. When using React state, account for this mutation and pass a new object to the state setter when needed.
238
+
239
+ `addParametersIntoUrl` uses `window.location` and `window.history.replaceState`; it is browser-only. It serializes supported primitive, date, array, and one-level nested filter values into the current URL. It intentionally omits the configured fields parameter.
240
+
241
+ ### Route and navigation helpers
242
+
243
+ `route.ts` exports:
244
+
245
+ | API | Purpose |
246
+ |---|---|
247
+ | `buildFromUrl(model?)` | Parse `window.location.search` into an object or a model-shaped object. |
248
+ | `buildParameters(url, model?)` | Parse a URL/query string into an object. |
249
+ | `convertToObject(input, model?)` | Convert a parsed key/value map into nested properties, or map it using a model as a type template. |
250
+ | `onBack(event, navigate, confirm, resource, current, original?, keys?, version?)` | Prevent the default event and run the back-navigation check. |
251
+ | `goBack(navigate, confirm, resource, current, original?, keys?, version?)` | Navigate back immediately when there are no tracked changes; otherwise ask for confirmation. |
252
+
253
+ When a model is supplied to `buildParameters` / `convertToObject`, the model's values determine the conversion type for each property. Date, number, boolean, string, array, and nested-object fields receive corresponding conversions. Without a model, dotted query keys become nested objects and string values that look numeric or boolean are converted.
254
+
255
+ `onBack` and `goBack` expect the application to supply its router's `navigate` function and a confirmation callback. The confirmation UI is not included in this package.
256
+
257
+ ### Create and update workflows
258
+
259
+ `edit.ts` exports:
260
+
261
+ - `createModel<T>(attributes?)`: create an initial object using an `Attributes` map.
262
+ - `isSuccessful(result)`: interpret a numeric/object/error-array result.
263
+ - `afterSaved(...)`: show form validation errors, a save-success alert, not-found, or conflict feedback; after success it navigates back when a `navigate` function is supplied.
264
+ - `afterCreated(...)`: similar handling for create operations, using caller-provided success and duplicate messages.
265
+
266
+ `createModel` uses each attribute's `name` as the resulting object property and initializes by `type`:
267
+
268
+ | Attribute type | Initial value |
269
+ |---|---|
270
+ | `string`, `text` | `""` |
271
+ | `integer`, `number` | `0` |
272
+ | `array` | `[]` |
273
+ | `boolean` | `false` |
274
+ | `date` | `new Date()` |
275
+ | `object` | A recursively created object when `typeof` is supplied; otherwise `{}` |
276
+ | `ObjectId` | `null` |
277
+ | Other / unspecified type | `""` |
278
+
279
+ The result handlers use the following convention: an array is treated as a list of `ErrorMessage` validation errors; a positive number or object is treated as success; `afterSaved` treats `0` as not found and other non-success values as conflict. `afterCreated` treats a non-success, non-error-array result as a duplicate/failure and displays the supplied duplicate message.
280
+
281
+ ### Object reflection and comparison
282
+
283
+ `reflect.ts` contains general object helpers:
284
+
285
+ | API | Purpose |
286
+ |---|---|
287
+ | `clone(value)` | Recursively clone arrays and plain objects; clone `Date` values by timestamp. |
288
+ | `diff(a, b)` | Return field names whose values differ, comparing keys in both objects. |
289
+ | `makeDiff(current, original?, keys?, version?)` | Build a partial object containing changed values, plus explicitly included keys/version when supplied. |
290
+ | `hasDiff(current, original?, keys?, version?)` | Check whether `makeDiff` produces a non-empty result. |
291
+ | `equal(a, b)`, `equalArrays(a, b)` | Compare values, arrays, dates, and nested objects. |
292
+ | `isEmpty(object)` | Check whether an object has own enumerable properties. |
293
+ | `notIn(a, b)` | Return values from the second string array that are not in the first. |
294
+ | `getArray(list, name, value)` | Filter objects whose named property equals a value. |
295
+ | `getDiffArray(list, name, value)` | Filter objects whose named property does not equal a value. |
296
+ | `getDirectValue(object, key)` | Read an own direct property, or return `null`. |
297
+ | `setValue(object, path, value)` | Assign a value through a dotted / bracketed property path. |
298
+
299
+ `diff` and `makeDiff` are intended for model comparison and partial-update construction, not as a general JSON Patch implementation. `clone` handles ordinary objects, arrays, and dates; it does not preserve prototypes or special object types. `setValue` parses bracket notation, but array assignment may append rather than replace a requested index, so verify the behavior for the exact paths used by a form.
300
+
301
+ ### Approval / comparison models
302
+
303
+ `diff.ts` exports the types `DiffModel<T, ID>`, `ApprService<ID>`, `DiffService<T, ID>`, `DiffApprService<T, ID>`, and `DiffState<T>`, plus:
304
+
305
+ - `formatDiffModel(model, formatFields?)`: clone a diff model, normalize `origin` and `value` from JSON strings when needed, default missing sides to empty objects, and optionally format object fields.
306
+ - `getDataFields(form?)`: recursively find DOM elements carrying a non-empty `data-field` attribute.
307
+
308
+ The service interfaces describe contracts only; they do not implement an approval API.
309
+
310
+ ### Shared React components
311
+
312
+ `com.ts` exports small components that render basic HTML elements and expect the application to provide matching styles:
313
+
314
+ | Component | Purpose |
315
+ |---|---|
316
+ | `Error` | Render an error heading/message and an optional back button. |
317
+ | `PageSizeSelect` | Render a page-size select; defaults to `pageSizes`. |
318
+ | `Select` | Render a select from `{ value, text? }` items. |
319
+ | `Search` | Render a search input and optional page-size, clear, toggle, and search buttons. |
320
+
321
+ `index.ts` additionally exports:
322
+
323
+ - `Loading`: loading markup, or `Error Load Module!` when its `error` prop is truthy.
324
+ - `CurrencyInput`: an input wrapper with locale-aware blur formatting through the supplied `currencyOnBlur` callback and optional numeric change callback. If an `onChange` prop is supplied, it replaces the component's internal change handler; in that case its internal state update and `onChangeNumber` callback are not run by the component.
325
+
326
+ These components use class names such as `loader-wrapper`, `loader-sign`, `loader`, `error-header`, `error-body`, `btn-search`, and `btn-filter`. Their visual appearance depends on CSS provided by the consuming application; the package does not include a theme or stylesheet.
327
+
328
+ ### Locale, currency, date, and keyboard utilities
329
+
330
+ `core.ts` exports:
331
+
332
+ - `Locale`, describing country/date/number/currency settings.
333
+ - `ErrorMessage`, with `field`, `code`, and optional `param` / `message`.
334
+ - `Type`, `Attribute`, and `Attributes`, used by `createModel`.
335
+ - `StringMap`, `LoadingService`, `pageSizes`, `sizes`, `resources`, `normalizePhone`, and `normalizeFax`.
336
+
337
+ `util.ts` exports `enLocale` and `valueOf(input, locale?, eventType?)`. `valueOf` reads a checkbox or a regular input; numeric and currency behavior is selected through the input's `data-type` attribute.
338
+
339
+ The package entry point also exports:
340
+
341
+ - `formatDate`, `dateToString`, `datetimeToString`, and `numberToString`.
342
+ - `getParam`, `checked`, `includes`, and `value`.
343
+ - `scrollToFocus` for the library's expected form DOM layout.
344
+ - `digitKeyDown`, `integerKeyDown`, and `numberKeyDown`, plus React event wrappers `digitOnKeyDown`, `integerOnKeyDown`, and `numberOnKeyDown`.
345
+
346
+ The keyboard helpers allow common control keys and Ctrl/Cmd shortcuts. `integerKeyDown` and `numberKeyDown` allow a leading minus sign only when the input's `min` attribute represents a negative number. `numberKeyDown` accepts one configured decimal separator (`.`, `,`, or `٫`). These are key filters, not complete validation; pasted values and programmatic changes still need validation.
347
+
348
+ ## Project structure
349
+
350
+ ```text
351
+ react-hook-core/
352
+ ├── src/
353
+ │ ├── index.ts # Package entry point and general React/input helpers
354
+ │ ├── core.ts # Shared types, resources, locale, page-size defaults
355
+ │ ├── state.ts # Form event -> model state conversion
356
+ │ ├── search.ts # Filters, pagination, sorting, URL synchronization
357
+ │ ├── route.ts # Query parsing and back-navigation helpers
358
+ │ ├── edit.ts # Model creation and save/create result handling
359
+ │ ├── reflect.ts # Clone, equality, diff, and nested property assignment
360
+ │ ├── diff.ts # Approval/diff model contracts and DOM data-field lookup
361
+ │ ├── com.ts # Small shared React components
362
+ │ ├── useMessage.ts # useMessage hook
363
+ │ └── util.ts # Locale-aware input value conversion
364
+ ├── lib/ # Compiled CommonJS JavaScript
365
+ ├── package.json
366
+ └── tsconfig.json
367
+ ```
368
+
369
+ ## Build
370
+
371
+ The package compiles TypeScript from `src/` into `lib/` using the root `tsconfig.json`.
372
+
373
+ ```bash
374
+ npm run build:lib
375
+ ```
376
+
377
+ To remove the compiled output:
378
+
379
+ ```bash
380
+ npm run clean:lib
381
+ ```
382
+
383
+ The current `package.json` does not define a test or lint script. The provided source archive also does not include a test suite.
384
+
385
+ ## Implementation notes and limitations
386
+
387
+ - **Browser-oriented helpers:** URL synchronization, focus scrolling, DOM field discovery, and form-state conversion access `window`, `document`, `navigator`, or DOM nodes. Do not call these helpers during server-side rendering.
388
+ - **Application-owned services:** `SearchService`, `DiffService`, `ApprService`, loading, alerts, and confirmation are interfaces/callback contracts. The library does not implement HTTP clients, modals, notifications, or backend behavior.
389
+ - **Mutable model helpers:** several search, edit, and state functions mutate supplied objects before or while updating state. Review the specific function's behavior when using immutable-state conventions.
390
+ - **CSS is external:** components emit markup and class names but do not ship styles.
391
+ - **Currency formatting is delegated:** `CurrencyInput` calls the supplied `currencyOnBlur`; it does not provide a complete built-in currency formatter. `valueOf` implements its own input normalization rules.
392
+ - **Date behavior:** `dateToString` and `datetimeToString` use the local time zone through `Date` getters. `formatDate` formats a date through an `en-US` locale string and token replacement; it is not a general date-formatting engine.
393
+ - **Package metadata should be checked:** `package-lock.json` records a different root version and an older dependency set than `package.json`. The TypeScript configuration also targets ES5, uses CommonJS, and does not emit declaration files (`declaration: false`); the package manifest points `types` to `src/index.ts`.
394
+
395
+ ## License
396
+
397
+ MIT
package/lib/index.js CHANGED
@@ -192,3 +192,105 @@ exports.scrollToFocus = function (e, isUseTimeOut) {
192
192
  console.log(e)
193
193
  }
194
194
  }
195
+ var SHORTCUT_KEYS = new Set(["a", "c", "v", "x", "z", "y"])
196
+ var CONTROL_KEYS = new Set([
197
+ "Backspace",
198
+ "Delete",
199
+ "Tab",
200
+ "Enter",
201
+ "Escape",
202
+ "ArrowLeft",
203
+ "ArrowRight",
204
+ "ArrowUp",
205
+ "ArrowDown",
206
+ "Home",
207
+ "End",
208
+ "PageUp",
209
+ "PageDown",
210
+ "Insert",
211
+ ])
212
+ function detectShortcut(e) {
213
+ return (e.ctrlKey || e.metaKey) && SHORTCUT_KEYS.has(e.key.toLowerCase())
214
+ }
215
+ exports.detectShortcut = detectShortcut
216
+ function isDigit(key) {
217
+ return key.length === 1 && key >= "0" && key <= "9"
218
+ }
219
+ function isControlKey(key) {
220
+ return CONTROL_KEYS.has(key)
221
+ }
222
+ function digitKeyDown(e) {
223
+ if (detectShortcut(e)) {
224
+ return true
225
+ }
226
+ var key = e.key
227
+ if (isControlKey(key)) {
228
+ return true
229
+ }
230
+ return isDigit(key)
231
+ }
232
+ exports.digitKeyDown = digitKeyDown
233
+ function integerKeyDown(e) {
234
+ if (detectShortcut(e)) {
235
+ return true
236
+ }
237
+ var key = e.key
238
+ if (isControlKey(key)) {
239
+ return true
240
+ }
241
+ var input = e.target
242
+ if (key === "-") {
243
+ if (!input.min) {
244
+ return true
245
+ } else {
246
+ var min = Number(input.min)
247
+ return !Number.isNaN(min) && min < 0 && !input.value.includes("-")
248
+ }
249
+ }
250
+ return isDigit(key)
251
+ }
252
+ exports.integerKeyDown = integerKeyDown
253
+ function numberKeyDown(e, decimalSeparator) {
254
+ if (detectShortcut(e)) {
255
+ return true
256
+ }
257
+ var key = e.key
258
+ if (isControlKey(key)) {
259
+ return true
260
+ }
261
+ var input = e.target
262
+ if (key === "-") {
263
+ if (!input.min) {
264
+ return true
265
+ } else {
266
+ var min = Number(input.min)
267
+ return !Number.isNaN(min) && min < 0 && !input.value.includes("-")
268
+ }
269
+ }
270
+ if (key === "." || key === "," || key === "٫") {
271
+ if (!decimalSeparator) {
272
+ decimalSeparator = "."
273
+ }
274
+ return key === decimalSeparator && !input.value.includes(decimalSeparator)
275
+ }
276
+ return isDigit(key)
277
+ }
278
+ exports.numberKeyDown = numberKeyDown
279
+ function digitOnKeyDown(e) {
280
+ if (!digitKeyDown(e.nativeEvent)) {
281
+ e.preventDefault()
282
+ }
283
+ }
284
+ exports.digitOnKeyDown = digitOnKeyDown
285
+ function integerOnKeyDown(e) {
286
+ if (!integerKeyDown(e.nativeEvent)) {
287
+ e.preventDefault()
288
+ }
289
+ }
290
+ exports.integerOnKeyDown = integerOnKeyDown
291
+ function numberOnKeyDown(e, decimalSeparator) {
292
+ if (!numberKeyDown(e.nativeEvent, decimalSeparator)) {
293
+ e.preventDefault()
294
+ }
295
+ }
296
+ exports.numberOnKeyDown = numberOnKeyDown
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-hook-core",
3
- "version": "0.5.16",
3
+ "version": "0.5.18",
4
4
  "description": "react",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./src/index.ts",
package/src/index.ts CHANGED
@@ -243,3 +243,138 @@ export const scrollToFocus = (e: any, isUseTimeOut?: boolean) => {
243
243
  console.log(e)
244
244
  }
245
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
+ }