@fajarmaulana/komerce-lp-helper 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 fajarmaulana-dev
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 ADDED
@@ -0,0 +1,159 @@
1
+ # komerce-lp-helper
2
+
3
+ A collection of useful React hooks, utilities, and helper functions designed for Komerce Landing Page projects.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install komerce-lp-helper
9
+ ```
10
+
11
+ ## Features
12
+
13
+ ### HTTP Client & API Hooks
14
+
15
+ #### `http`
16
+
17
+ A wrapper around `fetch` with support for interceptors, caching, and retries.
18
+
19
+ ```typescript
20
+ import { http } from "komerce-lp-helper";
21
+
22
+ // GET request
23
+ const users = await http.get("/users");
24
+
25
+ // POST request with body
26
+ await http.post("/users", { name: "John Doe" });
27
+
28
+ // Using cache
29
+ const cachedData = http.getCache("my-key");
30
+ ```
31
+
32
+ #### `createApi`
33
+
34
+ Creates a new API instance with built-in React hooks (`fetch`, `mutation`, `infinite`) for performing typed data fetching and mutations with progress tracking.
35
+
36
+ ```tsx
37
+ import { createApi } from "komerce-lp-helper";
38
+
39
+ const api = createApi({ baseURL: "/api" });
40
+
41
+ // Fetch
42
+ const { data, isLoading, refetch } = api.fetch<User[]>("/users");
43
+
44
+ // Mutation (POST, PUT, DELETE)
45
+ const { mutate, isLoading, progress } = api.mutation<User, FormData>("/users", { method: "POST" });
46
+
47
+ // Infinite Fetch
48
+ const { data, fetchNextPage } = api.infinite<User[]>("/users", {
49
+ initialOffset: 0,
50
+ setOffset: (lastItems, allItems, lastOffset) => (lastItems.length ? lastOffset + 1 : null),
51
+ });
52
+ ```
53
+
54
+ ### Hooks
55
+
56
+ #### `useDebounce`
57
+
58
+ Returns a debounced version of a value. Useful for delaying expensive operations.
59
+
60
+ ```typescript
61
+ import { useDebounce } from "komerce-lp-helper";
62
+ const debouncedSearchTerm = useDebounce(searchTerm, 500);
63
+ ```
64
+
65
+ #### `useDebounceFunc`
66
+
67
+ Returns a debounced version of a callback function.
68
+
69
+ ```typescript
70
+ import { useDebounceFunc } from "komerce-lp-helper";
71
+ const debouncedSearch = useDebounceFunc((q) => fetchResults(q), 300);
72
+ ```
73
+
74
+ #### `useConditionalDebounce`
75
+
76
+ Conditionally executes a callback function after a specified debounce delay.
77
+
78
+ #### `useRouter`
79
+
80
+ A custom router API built on top of React Router DOM that provides easier navigation methods and state management.
81
+
82
+ ```typescript
83
+ import { useRouter } from "komerce-lp-helper";
84
+
85
+ const { push, replace, back, query, params } = useRouter();
86
+
87
+ // Navigate with query params
88
+ push({ pathname: "/dashboard", query: { tab: "settings" } });
89
+ ```
90
+
91
+ #### `useQueryParams`
92
+
93
+ A hook for reading and updating query parameters in the URL locally.
94
+
95
+ ```typescript
96
+ import { useQueryParams } from "komerce-lp-helper";
97
+ const [queryObj, updateQuery] = useQueryParams<{ page: string }>();
98
+ ```
99
+
100
+ #### `useSlider`
101
+
102
+ Manages logic for custom slider components, including touch/drag support and navigation.
103
+
104
+ ```typescript
105
+ import { useSlider } from "komerce-lp-helper";
106
+ const slider = useSlider({ data: items });
107
+ ```
108
+
109
+ ### Utilities
110
+
111
+ #### Cookie
112
+
113
+ Managed wrappers for `document.cookie`.
114
+
115
+ - `setCookie({ key, value, maxAge })`: Sets a cookie.
116
+ - `setCookies([ ... ])`: Sets multiple cookies.
117
+ - `getCookie(key)`: Gets and parses a cookie value.
118
+ - `getCookies([keys])`: Retrieves multiple cookies.
119
+ - `removeCookie(key)`: Removes a cookie.
120
+ - `removeCookies([keys])`: Removes multiple cookies.
121
+ - `clearCookies()`: Clears all cookies.
122
+
123
+ #### Local Storage
124
+
125
+ Type-safe wrappers for `localStorage`.
126
+
127
+ - `setLocal(key, value)`: Stores a value (JSON stringified).
128
+ - `setLocals([ ... ])`: Stores multiple values.
129
+ - `getLocal(key)`: Retrieves and parses a value.
130
+ - `getLocals([keys])`: Retrieves multiple values.
131
+ - `removeLocal(key)`: Removes an item.
132
+ - `clearLocals()`: Clears local storage.
133
+
134
+ #### File
135
+
136
+ Helpers for file and blob manipulation.
137
+
138
+ - `checkImage(url)`: Checks if an image URL is valid.
139
+ - `convertBlob(blob)`: Converts a Blob to a Base64 string.
140
+ - `extension(mimeType)`: Gets file extension from MIME type.
141
+ - `filenameWithExtension(blob, prefix)`: Generates a filename.
142
+ - `createDownloadAnchor(blob, options)`: Creates an anchor for downloading.
143
+ - `downloadBlob(blob, filename)`: Triggers a file download.
144
+
145
+ #### General
146
+
147
+ Common DOM and string utilities.
148
+
149
+ - `getById(id)`: Type-safe `document.getElementById`.
150
+ - `getByAny(selector)`: Type-safe `document.querySelector`.
151
+ - `clickById(id)`: Triggers a click on an element by ID.
152
+ - `focusById(id)`: Focuses an element by ID.
153
+ - `handleHashLink(hash, currentHash)`: Smooth scrolling for hash links.
154
+ - `acronym(name)`: Generates a 2-letter acronym from a name.
155
+ - `isNotPrimitive(value)`: Checks if a value is an object/array.
156
+
157
+ ## License
158
+
159
+ MIT
@@ -0,0 +1 @@
1
+ export declare const MOBILE_BOUND = 640;
@@ -0,0 +1 @@
1
+ export var MOBILE_BOUND = 640;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * useDebounce is a React hook that returns a debounced version of a value.
3
+ * It updates the returned value only after a specified delay has passed
4
+ * without any changes to the input value.
5
+ *
6
+ * Useful for delaying expensive operations such as API calls,
7
+ * especially while the user is typing.
8
+ *
9
+ * @param value - The input value to debounce.
10
+ * @param delay - The debounce delay in milliseconds.
11
+ * @returns The debounced value.
12
+ *
13
+ * @example
14
+ * const debouncedSearchTerm = useDebounce(searchTerm, 500);
15
+ */
16
+ export declare function useDebounce<T>(value: T, delay?: number): T;
17
+ /**
18
+ * useDebounceFunc returns a debounced version of a callback function.
19
+ * The function will only be executed after the specified delay has passed
20
+ * without being called again. This is helpful for limiting function execution
21
+ * in response to frequent user actions like typing or resizing.
22
+ *
23
+ * @param callback - The original function to debounce.
24
+ * @param delay - Delay in milliseconds before the callback is executed.
25
+ * @returns A debounced function that delays execution of the callback.
26
+ *
27
+ * @example
28
+ * const debouncedSearch = useDebounceFunc((q) => fetchResults(q), 300);
29
+ * debouncedSearch('hello'); // Will wait 300ms before calling fetchResults
30
+ */
31
+ export declare function useDebounceFunc<T extends (...args: any[]) => void>(callback: T, delay: number): (...args: Parameters<T>) => void;
32
+ /**
33
+ * A React hook that conditionally executes a callback function after a specified debounce delay.
34
+ *
35
+ * Unlike a standard debounce, `useConditionalDebounce` only triggers the callback if a given condition is `true`.
36
+ * It automatically clears any pending timeouts when the component unmounts or when the condition changes before the delay expires.
37
+ *
38
+ * @param {number} [delay=500] - The debounce delay in milliseconds before executing the callback.
39
+ */
40
+ export declare function useConditionalDebounce(delay?: number): (condition: boolean, callback: () => void) => void;
@@ -0,0 +1,118 @@
1
+ var __read = (this && this.__read) || function (o, n) {
2
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
3
+ if (!m) return o;
4
+ var i = m.call(o), r, ar = [], e;
5
+ try {
6
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
7
+ }
8
+ catch (error) { e = { error: error }; }
9
+ finally {
10
+ try {
11
+ if (r && !r.done && (m = i["return"])) m.call(i);
12
+ }
13
+ finally { if (e) throw e.error; }
14
+ }
15
+ return ar;
16
+ };
17
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
18
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
19
+ if (ar || !(i in from)) {
20
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
21
+ ar[i] = from[i];
22
+ }
23
+ }
24
+ return to.concat(ar || Array.prototype.slice.call(from));
25
+ };
26
+ /* eslint-disable @typescript-eslint/no-explicit-any */
27
+ import { useCallback, useEffect, useRef, useState } from 'react';
28
+ /**
29
+ * useDebounce is a React hook that returns a debounced version of a value.
30
+ * It updates the returned value only after a specified delay has passed
31
+ * without any changes to the input value.
32
+ *
33
+ * Useful for delaying expensive operations such as API calls,
34
+ * especially while the user is typing.
35
+ *
36
+ * @param value - The input value to debounce.
37
+ * @param delay - The debounce delay in milliseconds.
38
+ * @returns The debounced value.
39
+ *
40
+ * @example
41
+ * const debouncedSearchTerm = useDebounce(searchTerm, 500);
42
+ */
43
+ export function useDebounce(value, delay) {
44
+ if (delay === void 0) { delay = 500; }
45
+ var _a = __read(useState(value), 2), debouncedValue = _a[0], setDebouncedValue = _a[1];
46
+ useEffect(function () {
47
+ var handler = setTimeout(function () {
48
+ setDebouncedValue(value);
49
+ }, delay);
50
+ return function () {
51
+ clearTimeout(handler);
52
+ };
53
+ }, [value, delay]);
54
+ return debouncedValue;
55
+ }
56
+ /**
57
+ * useDebounceFunc returns a debounced version of a callback function.
58
+ * The function will only be executed after the specified delay has passed
59
+ * without being called again. This is helpful for limiting function execution
60
+ * in response to frequent user actions like typing or resizing.
61
+ *
62
+ * @param callback - The original function to debounce.
63
+ * @param delay - Delay in milliseconds before the callback is executed.
64
+ * @returns A debounced function that delays execution of the callback.
65
+ *
66
+ * @example
67
+ * const debouncedSearch = useDebounceFunc((q) => fetchResults(q), 300);
68
+ * debouncedSearch('hello'); // Will wait 300ms before calling fetchResults
69
+ */
70
+ export function useDebounceFunc(callback, delay) {
71
+ var timerRef = useRef(null);
72
+ var debouncedFunction = function () {
73
+ var args = [];
74
+ for (var _i = 0; _i < arguments.length; _i++) {
75
+ args[_i] = arguments[_i];
76
+ }
77
+ if (timerRef.current) {
78
+ clearTimeout(timerRef.current);
79
+ }
80
+ timerRef.current = setTimeout(function () {
81
+ callback.apply(void 0, __spreadArray([], __read(args), false));
82
+ }, delay);
83
+ };
84
+ useEffect(function () {
85
+ return function () {
86
+ if (timerRef.current) {
87
+ clearTimeout(timerRef.current);
88
+ }
89
+ };
90
+ }, []);
91
+ return debouncedFunction;
92
+ }
93
+ /**
94
+ * A React hook that conditionally executes a callback function after a specified debounce delay.
95
+ *
96
+ * Unlike a standard debounce, `useConditionalDebounce` only triggers the callback if a given condition is `true`.
97
+ * It automatically clears any pending timeouts when the component unmounts or when the condition changes before the delay expires.
98
+ *
99
+ * @param {number} [delay=500] - The debounce delay in milliseconds before executing the callback.
100
+ */
101
+ export function useConditionalDebounce(delay) {
102
+ if (delay === void 0) { delay = 500; }
103
+ var timeoutRef = useRef(null);
104
+ var run = useCallback(function (condition, callback) {
105
+ if (timeoutRef.current)
106
+ clearTimeout(timeoutRef.current);
107
+ if (!condition)
108
+ return;
109
+ timeoutRef.current = window.setTimeout(callback, delay);
110
+ }, [delay]);
111
+ useEffect(function () {
112
+ return function () {
113
+ if (timeoutRef.current)
114
+ clearTimeout(timeoutRef.current);
115
+ };
116
+ }, []);
117
+ return run;
118
+ }
@@ -0,0 +1,111 @@
1
+ import { type NavigateOptions } from 'react-router-dom';
2
+ /**
3
+ * Represents the query string parameters of a URL.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * { page: "1", tags: ["react", "typescript"] }
8
+ * ```
9
+ */
10
+ export type TRouterQuery = {
11
+ [key: string]: string | string[];
12
+ };
13
+ /**
14
+ * Represents the state of the router navigation.
15
+ */
16
+ export type TRouterState = {
17
+ /** The target URL for navigation. */
18
+ url?: string;
19
+ /** The path shown in the browser as the navigation result. */
20
+ as?: string;
21
+ /** Navigation options passed to the router method (`replace`, `state`, etc.) */
22
+ options?: NavigateOptions;
23
+ /** Additional metadata that may be attached to the router state. */
24
+ [key: string]: unknown;
25
+ };
26
+ /**
27
+ * Type definition for a navigation function.
28
+ * It can accept either a string path directly, or
29
+ * an object containing `pathname`, `query`, and `hash`.
30
+ */
31
+ export interface IRouterPush {
32
+ /**
33
+ * Navigate using a string path.
34
+ *
35
+ * @param url - Destination path, e.g. "/dashboard"
36
+ * @param options - Additional navigation options (`replace`, `state`, etc.)
37
+ */
38
+ (url: string | {
39
+ pathname: string;
40
+ query?: TRouterQuery;
41
+ hash?: string;
42
+ }, options?: NavigateOptions): void;
43
+ /**
44
+ * Navigate using an object with query parameters and hash.
45
+ *
46
+ * @param pathObj - Object containing `pathname`, `query`, and `hash`
47
+ * @param options - Additional navigation options
48
+ */
49
+ (pathObj: {
50
+ pathname: string;
51
+ query?: TRouterQuery;
52
+ hash?: string;
53
+ }, options?: NavigateOptions): void;
54
+ }
55
+ /**
56
+ * Custom router API built on top of React Router DOM.
57
+ */
58
+ export type TUseRouter = {
59
+ /** Navigate to a new page */
60
+ push: IRouterPush;
61
+ /** Navigate to a new page with query parameters */
62
+ route: (pathname: string, query?: TRouterQuery, options?: NavigateOptions) => void;
63
+ /** Replace the current history entry with a new one */
64
+ replace: IRouterPush;
65
+ /** Go back to the previous page (history -1) */
66
+ back: () => void;
67
+ /** Go forward to the next page (history +1) */
68
+ next: () => void;
69
+ /** Jump to a specific history index */
70
+ go: (num: number) => void;
71
+ /** Reload the current page */
72
+ refresh: () => void;
73
+ /** The current pathname without query/hash */
74
+ path: string;
75
+ /** The hash portion of the current URL (e.g. "#section1") */
76
+ hash: string;
77
+ /** Full path including pathname, query, and hash */
78
+ fullpath: string;
79
+ /** The base URL */
80
+ origin: string;
81
+ /** Full URL including base URL, pathname, query, and hash */
82
+ href: string;
83
+ /** Parsed query parameters as an object */
84
+ query: TRouterQuery;
85
+ /** Current route parameters (from `useParams`) */
86
+ params: Record<string, string | undefined>;
87
+ /**
88
+ * Registers a callback to be executed before navigating back/forward.
89
+ * The callback can cancel navigation if it returns `false`.
90
+ *
91
+ * @param cb - Function to handle popstate events
92
+ */
93
+ beforePopState: (cb: (state: TRouterState) => boolean) => void;
94
+ };
95
+ /**
96
+ * Custom router API built on top of React Router DOM.
97
+ *
98
+ * @returns An object implementing the {@link TUseRouter} interface
99
+ */
100
+ export declare function useRouter(): TUseRouter;
101
+ /**
102
+ * A hook for reading and updating query parameters in the URL.
103
+ *
104
+ * @template T - Shape of the query parameters
105
+ * @param defaultValues - Optional default values for query parameters
106
+ *
107
+ * @returns A tuple:
108
+ * - `queryObj`: The parsed query parameters as an object
109
+ * - `updateQuery`: A function to update query parameters
110
+ */
111
+ export declare function useQueryParams<T extends Record<string, string | string[]>>(defaultValues?: Partial<T>): [T, (updates: Partial<T>) => void];
@@ -0,0 +1,182 @@
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ var __read = (this && this.__read) || function (o, n) {
13
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
14
+ if (!m) return o;
15
+ var i = m.call(o), r, ar = [], e;
16
+ try {
17
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
18
+ }
19
+ catch (error) { e = { error: error }; }
20
+ finally {
21
+ try {
22
+ if (r && !r.done && (m = i["return"])) m.call(i);
23
+ }
24
+ finally { if (e) throw e.error; }
25
+ }
26
+ return ar;
27
+ };
28
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
29
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
30
+ if (ar || !(i in from)) {
31
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
32
+ ar[i] = from[i];
33
+ }
34
+ }
35
+ return to.concat(ar || Array.prototype.slice.call(from));
36
+ };
37
+ import { useCallback, useMemo } from 'react';
38
+ import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
39
+ /**
40
+ * Custom router API built on top of React Router DOM.
41
+ *
42
+ * @returns An object implementing the {@link TUseRouter} interface
43
+ */
44
+ export function useRouter() {
45
+ var navigate = useNavigate();
46
+ var location = useLocation();
47
+ var params = useParams();
48
+ var _a = __read(useSearchParams(), 1), searchParams = _a[0];
49
+ var query = useMemo(function () {
50
+ var queryObj = {};
51
+ searchParams.forEach(function (value, key) {
52
+ if (queryObj[key]) {
53
+ queryObj[key] = Array.isArray(queryObj[key])
54
+ ? __spreadArray(__spreadArray([], __read(queryObj[key]), false), [value], false) : [queryObj[key], value];
55
+ }
56
+ else {
57
+ queryObj[key] = value;
58
+ }
59
+ });
60
+ return queryObj;
61
+ }, [searchParams]);
62
+ var push = useCallback(function (url, options) {
63
+ if (typeof url === 'string') {
64
+ navigate(url, options);
65
+ }
66
+ else {
67
+ var queryString = url.query
68
+ ? '?' +
69
+ new URLSearchParams(Object.entries(url.query).map(function (_a) {
70
+ var _b = __read(_a, 2), k = _b[0], v = _b[1];
71
+ return [k, Array.isArray(v) ? v.join(',') : v];
72
+ })).toString()
73
+ : '';
74
+ var hash = url.hash ? (url.hash.startsWith('#') ? url.hash : "#".concat(url.hash)) : '';
75
+ navigate("".concat(url.pathname).concat(queryString).concat(hash), options);
76
+ }
77
+ }, [navigate]);
78
+ var route = useCallback(function (pathname, query, options) {
79
+ var searchParams = new URLSearchParams();
80
+ if (query) {
81
+ Object.entries(query).forEach(function (_a) {
82
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
83
+ if (Array.isArray(value)) {
84
+ value.forEach(function (v) { return searchParams.append(key, v); });
85
+ }
86
+ else {
87
+ searchParams.set(key, value);
88
+ }
89
+ });
90
+ }
91
+ var search = searchParams.toString();
92
+ var fullPath = search ? "".concat(pathname, "?").concat(search) : pathname;
93
+ navigate(fullPath, options);
94
+ }, [navigate]);
95
+ var replace = useCallback(function (url, options) {
96
+ var replaceOptions = __assign(__assign({}, options), { replace: true });
97
+ push(url, replaceOptions);
98
+ }, [push]);
99
+ var back = useCallback(function () {
100
+ navigate(-1);
101
+ }, [navigate]);
102
+ var next = useCallback(function () {
103
+ navigate(1);
104
+ }, [navigate]);
105
+ var go = useCallback(function (num) {
106
+ navigate(num);
107
+ }, [navigate]);
108
+ var refresh = useCallback(function () {
109
+ window.location.reload();
110
+ }, []);
111
+ var beforePopState = useCallback(function (cb) {
112
+ var handlePopState = function (event) {
113
+ if (!cb(event.state)) {
114
+ event.preventDefault();
115
+ window.history.pushState(location.state, '', location.pathname + location.search);
116
+ }
117
+ };
118
+ window.addEventListener('popstate', handlePopState);
119
+ return function () { return window.removeEventListener('popstate', handlePopState); };
120
+ }, [location]);
121
+ return {
122
+ push: push,
123
+ route: route,
124
+ replace: replace,
125
+ back: back,
126
+ next: next,
127
+ go: go,
128
+ refresh: refresh,
129
+ path: location.pathname,
130
+ hash: location.hash,
131
+ fullpath: "".concat(location.pathname).concat(location.search).concat(location.hash),
132
+ origin: window.location.origin,
133
+ href: window.location.href,
134
+ query: query,
135
+ params: params,
136
+ beforePopState: beforePopState,
137
+ };
138
+ }
139
+ /**
140
+ * A hook for reading and updating query parameters in the URL.
141
+ *
142
+ * @template T - Shape of the query parameters
143
+ * @param defaultValues - Optional default values for query parameters
144
+ *
145
+ * @returns A tuple:
146
+ * - `queryObj`: The parsed query parameters as an object
147
+ * - `updateQuery`: A function to update query parameters
148
+ */
149
+ export function useQueryParams(defaultValues) {
150
+ var _a = __read(useSearchParams(), 2), searchParams = _a[0], setSearchParams = _a[1];
151
+ var queryObj = useMemo(function () {
152
+ var result = __assign({}, defaultValues);
153
+ searchParams.forEach(function (value, key) {
154
+ var allValues = searchParams.getAll(key);
155
+ if (allValues.length > 1) {
156
+ result[key] = allValues;
157
+ }
158
+ else {
159
+ result[key] = value;
160
+ }
161
+ });
162
+ return result;
163
+ }, [searchParams, defaultValues]);
164
+ var updateQuery = useCallback(function (updates) {
165
+ var newParams = new URLSearchParams(searchParams);
166
+ Object.entries(updates).forEach(function (_a) {
167
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
168
+ if (value === undefined || value === null) {
169
+ newParams.delete(key);
170
+ }
171
+ else if (Array.isArray(value)) {
172
+ newParams.delete(key);
173
+ value.forEach(function (v) { return newParams.append(key, v); });
174
+ }
175
+ else {
176
+ newParams.set(key, value);
177
+ }
178
+ });
179
+ setSearchParams(newParams);
180
+ }, [searchParams, setSearchParams]);
181
+ return [queryObj, updateQuery];
182
+ }
@@ -0,0 +1,50 @@
1
+ import { type MouseEvent, type TouchEvent } from 'react';
2
+ type TSlider = {
3
+ e: MouseEvent | TouchEvent;
4
+ mobile?: boolean;
5
+ axis: 'X' | 'Y';
6
+ };
7
+ type TSlide = {
8
+ data: any[];
9
+ mobileOnly?: boolean;
10
+ infiniteSlide?: boolean;
11
+ isLoading?: boolean;
12
+ mobileBound?: number;
13
+ onNext?: () => void;
14
+ onBack?: () => void;
15
+ };
16
+ /**
17
+ * Get slider position from an event, supports mobile touch events.
18
+ *
19
+ * @param e - The event object of MouseEvent or TouchEvent.
20
+ * @param mobile - Whether the event is from a mobile touch (default: false).
21
+ * @param axis - The axis to get position from, either 'X' or 'Y' (default: 'X').
22
+ * @returns The page X or Y coordinate from the event.
23
+ */
24
+ export declare function slider({ e, mobile, axis }: TSlider): number;
25
+ /**
26
+ * useSlider is a custom hook to manage the logic for the slider component.
27
+ *
28
+ * @param data - An array of data to display in the slider.
29
+ * @param mobileOnly - Boolean indicating whether the slider is showed on mobile only or not.
30
+ * @param infiniteSlide - Boolean indicating whether the slider can be slided infinitely or not.
31
+ * @param isLoading - Boolean indicating whether the data is still loading.
32
+ * @param mobileBound - Number as bound for mobile only mode
33
+ * @param onNext - Emited method to override the next function.
34
+ * @param onBack - Emited method to override the back function.
35
+ * @returns An object containing state values and handlers for slider control and interaction.
36
+ */
37
+ export declare function useSlider({ data, mobileOnly, infiniteSlide, isLoading, mobileBound, onBack, onNext }: TSlide): {
38
+ currentSlide: number;
39
+ movement: number;
40
+ grab: boolean;
41
+ disableLeftArrow: boolean | undefined;
42
+ disableRightArrow: boolean | undefined;
43
+ setCurrentSlide: import("react").Dispatch<import("react").SetStateAction<number>>;
44
+ startSlide: (param: TSlider) => void;
45
+ moveSlide: (param: TSlider) => void;
46
+ endSlide: (param: TSlider) => void;
47
+ next: () => void;
48
+ back: () => void;
49
+ };
50
+ export {};