@zj-dynamics/hooks 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ZJ Dynamics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Octopusapp Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @zj-dynamics/hooks
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reusable React hooks shared by web and React Native.
4
+
5
+ The first exports are `useBool`, `useCallbackRef`, `useDebounce`, `useIsMounted`, `useOnMount`, `useShowClear` `useStepper` and `useCollectionQuery`. Every hook is available from the root and a matching leaf. These contracts were adapted from the frozen 2.21.1 reference using React and the pinned debounce dependency. The retained MIT notice is included.
6
+
7
+
8
+ ## Paginated collections
9
+
10
+ Use `useCollectionQuery({key, source, live})` with a stable `CollectionSource`. The source supplies `loadPage({key, cursor, reason})`, an item identity function, and an optional subscription with cleanup. Include filters and variables in `key`. Set `live` to false for filtered lists where incoming items should wait for refresh.
11
+
12
+ The hook exposes `data.items`, pagination metadata, initial/refresh/next-page loading flags, errors, and the `refresh()` and `nextPage()` actions. New pages replace duplicate item values without reordering the existing list. Subscription inserts prepend by identity. Results from earlier keys are discarded. An adapter that needs transport cancellation should manage it in the app alongside its client.
13
+
14
+ Apollo setup stays in the consuming app. Map query results to `CollectionPage`, pass the cursor and app variables to your query call, and forward subscription inserts and errors from the client. The package imports React and contains no Apollo runtime or declaration dependency.
15
+
16
+ ## License
17
+
18
+ The MIT license in `LICENSE` applies to Rulnar-owned code. Third-party materials retain their accompanying licenses and notices.
@@ -0,0 +1,13 @@
1
+ export { useBool } from './useBool.js';
2
+ export type { SetFalse, SetTrue, Toggle } from './useBool.js';
3
+ export { useCallbackRef } from './useCallbackRef.js';
4
+ export { useDebounce } from './useDebounce.js';
5
+ export type { DebounceOptions, DebouncedCallback } from './useDebounce.js';
6
+ export { useIsMounted } from './useIsMounted.js';
7
+ export { useOnMount } from './useOnMount.js';
8
+ export { useSafeLayoutEffect } from './useSafeLayoutEffect.js';
9
+ export { useShowClear } from './useShowClear.js';
10
+ export type { Clearable } from './useShowClear.js';
11
+ export { useStepper } from './useStepper.js';
12
+ export { useCollectionQuery } from './useCollectionQuery.js';
13
+ export type { CollectionPage, CollectionQueryOptions, CollectionRequest, CollectionSource } from './useCollectionQuery.js';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { useBool } from './useBool.js';
2
+ export { useCallbackRef } from './useCallbackRef.js';
3
+ export { useDebounce } from './useDebounce.js';
4
+ export { useIsMounted } from './useIsMounted.js';
5
+ export { useOnMount } from './useOnMount.js';
6
+ export { useSafeLayoutEffect } from './useSafeLayoutEffect.js';
7
+ export { useShowClear } from './useShowClear.js';
8
+ export { useStepper } from './useStepper.js';
9
+ export { useCollectionQuery } from './useCollectionQuery.js';
@@ -0,0 +1,9 @@
1
+ declare const callbackKind: unique symbol;
2
+ type BooleanCallback<T extends string> = (() => void) & {
3
+ [callbackKind]: T;
4
+ };
5
+ export type SetTrue = BooleanCallback<'SetTrue'>;
6
+ export type SetFalse = BooleanCallback<'SetFalse'>;
7
+ export type Toggle = BooleanCallback<'Toggle'>;
8
+ export declare function useBool(initialState?: boolean): [boolean, SetTrue, SetFalse, Toggle];
9
+ export {};
@@ -0,0 +1,8 @@
1
+ import { useCallback, useState } from 'react';
2
+ export function useBool(initialState = false) {
3
+ const [value, setValue] = useState(initialState);
4
+ const setTrue = useCallback(() => setValue(true), []);
5
+ const setFalse = useCallback(() => setValue(false), []);
6
+ const toggle = useCallback(() => setValue(current => !current), []);
7
+ return [value, setTrue, setFalse, toggle];
8
+ }
@@ -0,0 +1,3 @@
1
+ type Callback = (...args: never[]) => unknown;
2
+ export declare function useCallbackRef<Fn extends Callback>(callback: Fn | undefined): Fn;
3
+ export {};
@@ -0,0 +1,11 @@
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+ export function useCallbackRef(callback) {
3
+ const current = useRef(callback);
4
+ useEffect(() => {
5
+ current.current = callback;
6
+ }, [callback]);
7
+ return useCallback((...args) => {
8
+ const fn = current.current;
9
+ return fn?.apply(current, args);
10
+ }, []);
11
+ }
@@ -0,0 +1,34 @@
1
+ export interface CollectionPage<Item> {
2
+ readonly items: readonly Item[];
3
+ readonly hasNextPage: boolean;
4
+ readonly endCursor?: string;
5
+ readonly totalCount?: number;
6
+ }
7
+ export interface CollectionRequest {
8
+ readonly key: string;
9
+ readonly cursor?: string;
10
+ readonly reason: 'initial' | 'refresh' | 'next';
11
+ }
12
+ export interface CollectionSource<Item> {
13
+ loadPage(request: CollectionRequest): Promise<CollectionPage<Item>>;
14
+ keyOf(item: Item): string | number;
15
+ subscribe?(key: string, events: {
16
+ insert(item: Item): void;
17
+ error(error: unknown): void;
18
+ }): () => void;
19
+ }
20
+ export interface CollectionQueryOptions<Item> {
21
+ readonly key: string;
22
+ readonly source: CollectionSource<Item>;
23
+ readonly enabled?: boolean;
24
+ readonly live?: boolean;
25
+ }
26
+ export declare function useCollectionQuery<Item>({ key, source, enabled, live }: CollectionQueryOptions<Item>): {
27
+ data: CollectionPage<Item> | undefined;
28
+ error: unknown;
29
+ loadingInitialContent: boolean;
30
+ loadingRefresh: boolean;
31
+ loadingNextPage: boolean;
32
+ refresh: () => Promise<void>;
33
+ nextPage: () => Promise<void>;
34
+ };
@@ -0,0 +1,105 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ function mergeItems(items, incoming, keyOf) {
3
+ const merged = new Map(items.map(item => [keyOf(item), item]));
4
+ for (const item of incoming)
5
+ merged.set(keyOf(item), item);
6
+ return [...merged.values()];
7
+ }
8
+ function prepend(page, items, source) {
9
+ const existing = new Set(page.items.map(item => source.keyOf(item)));
10
+ const inserted = [];
11
+ for (const item of items) {
12
+ const key = source.keyOf(item);
13
+ if (existing.has(key))
14
+ continue;
15
+ existing.add(key);
16
+ inserted.unshift(item);
17
+ }
18
+ return {
19
+ ...page,
20
+ items: [...inserted, ...page.items],
21
+ ...(page.totalCount !== undefined && { totalCount: page.totalCount + inserted.length }),
22
+ };
23
+ }
24
+ export function useCollectionQuery({ key, source, enabled = true, live = true }) {
25
+ const session = useRef(undefined);
26
+ const [snapshot, setSnapshot] = useState();
27
+ const active = snapshot?.key === key && snapshot.source === source && snapshot.enabled === enabled
28
+ ? snapshot.state : undefined;
29
+ const refresh = useCallback(() => session.current?.load('refresh') ?? Promise.resolve(), []);
30
+ const nextPage = useCallback(() => session.current?.load('next') ?? Promise.resolve(), []);
31
+ useEffect(() => {
32
+ let mounted = true;
33
+ const state = { data: undefined, error: undefined, pending: undefined };
34
+ const buffered = [];
35
+ const publish = () => {
36
+ if (mounted)
37
+ setSnapshot({ key, source, enabled, state: { ...state } });
38
+ };
39
+ async function load(reason) {
40
+ if (!enabled || !mounted || state.pending)
41
+ return;
42
+ const previous = state.data;
43
+ const cursor = reason === 'next' ? previous?.endCursor : undefined;
44
+ if (reason === 'next' && (!previous?.hasNextPage || cursor === undefined))
45
+ return;
46
+ state.pending = reason;
47
+ state.error = undefined;
48
+ publish();
49
+ try {
50
+ const page = await source.loadPage({ key, reason, ...(cursor !== undefined && { cursor }) });
51
+ if (!mounted)
52
+ return;
53
+ const items = mergeItems(reason === 'next' && previous ? state.data?.items ?? previous.items : [], page.items, item => source.keyOf(item));
54
+ state.data = prepend({ ...page, items }, buffered, source);
55
+ }
56
+ catch (error) {
57
+ if (mounted)
58
+ state.error = error;
59
+ }
60
+ finally {
61
+ if (mounted) {
62
+ buffered.length = 0;
63
+ state.pending = undefined;
64
+ publish();
65
+ }
66
+ }
67
+ }
68
+ session.current = { load };
69
+ publish();
70
+ if (enabled)
71
+ void load('initial');
72
+ const cleanup = enabled && live ? source.subscribe?.(key, {
73
+ insert(item) {
74
+ if (!mounted)
75
+ return;
76
+ if (state.pending === 'initial' || state.pending === 'refresh')
77
+ buffered.push(item);
78
+ if (state.data) {
79
+ state.data = prepend(state.data, [item], source);
80
+ publish();
81
+ }
82
+ },
83
+ error(error) {
84
+ if (!mounted)
85
+ return;
86
+ state.error = error;
87
+ publish();
88
+ },
89
+ }) : undefined;
90
+ return () => {
91
+ mounted = false;
92
+ session.current = undefined;
93
+ cleanup?.();
94
+ };
95
+ }, [key, source, enabled, live]);
96
+ return {
97
+ data: active?.data,
98
+ error: active?.error,
99
+ loadingInitialContent: enabled && (!active || active.pending === 'initial'),
100
+ loadingRefresh: active?.pending === 'refresh',
101
+ loadingNextPage: active?.pending === 'next',
102
+ refresh,
103
+ nextPage,
104
+ };
105
+ }
@@ -0,0 +1,16 @@
1
+ export interface DebounceOptions {
2
+ signal?: {
3
+ readonly aborted: boolean;
4
+ addEventListener(event: 'abort', listener: () => void, options?: {
5
+ once?: boolean;
6
+ }): void;
7
+ };
8
+ edges?: Array<'leading' | 'trailing'>;
9
+ }
10
+ export interface DebouncedCallback<Args extends unknown[]> {
11
+ (...args: Args): void;
12
+ schedule(): void;
13
+ cancel(): void;
14
+ flush(): void;
15
+ }
16
+ export declare function useDebounce<Args extends unknown[], Result>(callback: (...args: Args) => Result, wait: number, options?: DebounceOptions): DebouncedCallback<Args>;
@@ -0,0 +1,10 @@
1
+ import { useEffect, useMemo } from 'react';
2
+ import { debounce } from 'es-toolkit';
3
+ import { useCallbackRef } from './useCallbackRef.js';
4
+ export function useDebounce(callback, wait, options) {
5
+ const latest = useCallbackRef(callback);
6
+ // Timing and options are selected at mount. Subsequent renders update the callback.
7
+ const debounced = useMemo(() => debounce((...args) => latest(...args), wait, options), [latest]);
8
+ useEffect(() => () => debounced.cancel(), [debounced]);
9
+ return debounced;
10
+ }
@@ -0,0 +1 @@
1
+ export declare function useIsMounted(): import("react").RefObject<boolean>;
@@ -0,0 +1,9 @@
1
+ import { useLayoutEffect, useRef } from 'react';
2
+ export function useIsMounted() {
3
+ const mounted = useRef(false);
4
+ useLayoutEffect(() => {
5
+ mounted.current = true;
6
+ return () => { mounted.current = false; };
7
+ }, []);
8
+ return mounted;
9
+ }
@@ -0,0 +1 @@
1
+ export declare function useOnMount(callback: () => void): void;
@@ -0,0 +1,12 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { useCallbackRef } from './useCallbackRef.js';
3
+ export function useOnMount(callback) {
4
+ const invoked = useRef(false);
5
+ const latest = useCallbackRef(callback);
6
+ useEffect(() => {
7
+ if (invoked.current)
8
+ return;
9
+ invoked.current = true;
10
+ latest();
11
+ }, [latest]);
12
+ }
@@ -0,0 +1,2 @@
1
+ import { useLayoutEffect } from 'react';
2
+ export declare const useSafeLayoutEffect: typeof useLayoutEffect;
@@ -0,0 +1,2 @@
1
+ import { useEffect, useLayoutEffect } from 'react';
2
+ export const useSafeLayoutEffect = Reflect.get(globalThis, 'document') ? useLayoutEffect : useEffect;
@@ -0,0 +1,11 @@
1
+ export type Clearable = 'never' | 'while-editing' | 'always';
2
+ interface ClearState {
3
+ clearable: Clearable;
4
+ multiline: boolean;
5
+ focused: boolean;
6
+ hasValue: boolean;
7
+ disabled?: boolean;
8
+ readonly?: boolean;
9
+ }
10
+ export declare function useShowClear({ clearable, multiline, focused, hasValue, readonly, disabled }: ClearState): boolean | undefined;
11
+ export {};
@@ -0,0 +1,10 @@
1
+ export function useShowClear({ clearable, multiline, focused, hasValue, readonly, disabled = false }) {
2
+ if (multiline && clearable !== 'never')
3
+ throw new Error('Multiline inputs can not be clearable');
4
+ if (!hasValue || clearable === 'never' || disabled || readonly)
5
+ return false;
6
+ if (clearable === 'while-editing')
7
+ return focused;
8
+ if (clearable === 'always')
9
+ return true;
10
+ }
@@ -0,0 +1,12 @@
1
+ interface UseStepOptions<StepName extends string> {
2
+ defaultStep?: StepName;
3
+ }
4
+ export declare function useStepper<StepName extends string>(steps: readonly StepName[], options?: UseStepOptions<StepName>): {
5
+ goToNextStep(): void;
6
+ goToPreviousStep(): void;
7
+ currentStep: StepName;
8
+ isFirst: boolean;
9
+ isLast: boolean;
10
+ goToStep: import("react").Dispatch<import("react").SetStateAction<StepName>>;
11
+ };
12
+ export {};
@@ -0,0 +1,29 @@
1
+ import { useMemo, useState } from 'react';
2
+ export function useStepper(steps, options = {}) {
3
+ const first = options.defaultStep ?? steps[0];
4
+ if (!first)
5
+ throw new Error('Invariant failed: Steps array cannot be empty');
6
+ const [currentStep, goToStep] = useState(first);
7
+ const handlers = useMemo(() => ({
8
+ goToNextStep() {
9
+ goToStep(previous => {
10
+ const index = steps.indexOf(previous) + 1;
11
+ const step = steps[Math.min(index, steps.length - 1)];
12
+ if (!step)
13
+ throw new Error(`Invariant failed: Index out of bounds: ${index}`);
14
+ return step;
15
+ });
16
+ },
17
+ goToPreviousStep() {
18
+ goToStep(previous => {
19
+ const index = steps.indexOf(previous) - 1;
20
+ const step = steps[Math.max(index, 0)];
21
+ if (!step)
22
+ throw new Error(`Invariant failed: Index out of bounds: ${index}`);
23
+ return step;
24
+ });
25
+ },
26
+ }), [steps]);
27
+ return { currentStep, isFirst: currentStep === steps[0], isLast: currentStep === steps[steps.length - 1],
28
+ goToStep, ...handlers };
29
+ }
package/package.json CHANGED
@@ -1,6 +1,86 @@
1
1
  {
2
2
  "name": "@zj-dynamics/hooks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Reusable React hooks shared by web and React Native.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.js"
14
+ },
15
+ "./dist": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js",
18
+ "require": "./dist/index.js"
19
+ },
20
+ "./useBool": {
21
+ "types": "./dist/useBool.d.ts",
22
+ "import": "./dist/useBool.js",
23
+ "require": "./dist/useBool.js"
24
+ },
25
+ "./useCallbackRef": {
26
+ "types": "./dist/useCallbackRef.d.ts",
27
+ "import": "./dist/useCallbackRef.js",
28
+ "require": "./dist/useCallbackRef.js"
29
+ },
30
+ "./useDebounce": {
31
+ "types": "./dist/useDebounce.d.ts",
32
+ "import": "./dist/useDebounce.js",
33
+ "require": "./dist/useDebounce.js"
34
+ },
35
+ "./useIsMounted": {
36
+ "types": "./dist/useIsMounted.d.ts",
37
+ "import": "./dist/useIsMounted.js",
38
+ "require": "./dist/useIsMounted.js"
39
+ },
40
+ "./useOnMount": {
41
+ "types": "./dist/useOnMount.d.ts",
42
+ "import": "./dist/useOnMount.js",
43
+ "require": "./dist/useOnMount.js"
44
+ },
45
+ "./useSafeLayoutEffect": {
46
+ "types": "./dist/useSafeLayoutEffect.d.ts",
47
+ "import": "./dist/useSafeLayoutEffect.js",
48
+ "require": "./dist/useSafeLayoutEffect.js"
49
+ },
50
+ "./useShowClear": {
51
+ "types": "./dist/useShowClear.d.ts",
52
+ "import": "./dist/useShowClear.js",
53
+ "require": "./dist/useShowClear.js"
54
+ },
55
+ "./useStepper": {
56
+ "types": "./dist/useStepper.d.ts",
57
+ "import": "./dist/useStepper.js",
58
+ "require": "./dist/useStepper.js"
59
+ },
60
+ "./useCollectionQuery": {
61
+ "types": "./dist/useCollectionQuery.d.ts",
62
+ "import": "./dist/useCollectionQuery.js",
63
+ "require": "./dist/useCollectionQuery.js"
64
+ }
65
+ },
66
+ "files": [
67
+ "dist",
68
+ "README.md",
69
+ "NOTICE"
70
+ ],
71
+ "publishConfig": {
72
+ "access": "restricted",
73
+ "registry": "https://registry.npmjs.org/"
74
+ },
75
+ "scripts": {
76
+ "build": "tsc --build",
77
+ "typecheck": "tsc --noEmit --incremental false --composite false",
78
+ "prepack": "npm run build"
79
+ },
80
+ "peerDependencies": {
81
+ "react": "^19.0.0"
82
+ },
83
+ "dependencies": {
84
+ "es-toolkit": "1.52.0"
85
+ }
86
+ }