@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.
@@ -0,0 +1,167 @@
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
+ /* eslint-disable @typescript-eslint/no-explicit-any */
18
+ import { useMemo, useRef, useState } from 'react';
19
+ import { MOBILE_BOUND } from '@/constants';
20
+ /**
21
+ * Get slider position from an event, supports mobile touch events.
22
+ *
23
+ * @param e - The event object of MouseEvent or TouchEvent.
24
+ * @param mobile - Whether the event is from a mobile touch (default: false).
25
+ * @param axis - The axis to get position from, either 'X' or 'Y' (default: 'X').
26
+ * @returns The page X or Y coordinate from the event.
27
+ */
28
+ export function slider(_a) {
29
+ var e = _a.e, mobile = _a.mobile, axis = _a.axis;
30
+ return mobile ? e.changedTouches[0]["page".concat(axis)] : e["page".concat(axis)];
31
+ }
32
+ /**
33
+ * useSlider is a custom hook to manage the logic for the slider component.
34
+ *
35
+ * @param data - An array of data to display in the slider.
36
+ * @param mobileOnly - Boolean indicating whether the slider is showed on mobile only or not.
37
+ * @param infiniteSlide - Boolean indicating whether the slider can be slided infinitely or not.
38
+ * @param isLoading - Boolean indicating whether the data is still loading.
39
+ * @param mobileBound - Number as bound for mobile only mode
40
+ * @param onNext - Emited method to override the next function.
41
+ * @param onBack - Emited method to override the back function.
42
+ * @returns An object containing state values and handlers for slider control and interaction.
43
+ */
44
+ export function useSlider(_a) {
45
+ var data = _a.data, mobileOnly = _a.mobileOnly, infiniteSlide = _a.infiniteSlide, isLoading = _a.isLoading, mobileBound = _a.mobileBound, onBack = _a.onBack, onNext = _a.onNext;
46
+ var _b = __read(useState(0), 2), currentSlide = _b[0], setCurrentSlide = _b[1];
47
+ var _c = __read(useState(0), 2), movement = _c[0], setMovement = _c[1];
48
+ var _d = __read(useState(false), 2), grab = _d[0], setGrab = _d[1];
49
+ var startRef = useRef(0);
50
+ var endRef = useRef(0);
51
+ var throttleRef = useRef(false);
52
+ /**
53
+ * Determines whether the left navigation arrow should be disabled.
54
+ */
55
+ var disableLeftArrow = useMemo(function () {
56
+ return currentSlide === 0 || data.length === 0 || isLoading;
57
+ }, [currentSlide, data, isLoading]);
58
+ /**
59
+ * Determines whether the right navigation arrow should be disabled.
60
+ */
61
+ var disableRightArrow = useMemo(function () {
62
+ return currentSlide === data.length - 1 || data.length === 0 || isLoading;
63
+ }, [currentSlide, data, isLoading]);
64
+ /**
65
+ * Begins drag or swipe interaction for the slider.
66
+ *
67
+ * @param e - Mouse or touch event.
68
+ * @param param - Optional parameter to indicate a mobile event. Defaults to `true`.
69
+ */
70
+ var startSlide = function (param) {
71
+ if (mobileOnly && window.innerWidth >= (mobileBound || MOBILE_BOUND))
72
+ return;
73
+ startRef.current = slider(param);
74
+ setGrab(true);
75
+ };
76
+ /**
77
+ * Handles the ongoing drag/swipe movement of the slider.
78
+ *
79
+ * @param e - Mouse or touch event.
80
+ * @param param - Optional parameter to indicate a mobile event.
81
+ */
82
+ var moveSlide = function (param) {
83
+ if (mobileOnly && window.innerWidth >= (mobileBound || MOBILE_BOUND))
84
+ return;
85
+ var diff = slider(param) - startRef.current;
86
+ var move = param.mobile && Math.abs(diff) <= 24 ? 0 : diff;
87
+ if (!onNext || !onBack) {
88
+ var len = data.length - 1;
89
+ if (currentSlide === 0 && move > 0)
90
+ setCurrentSlide(0);
91
+ if (currentSlide === len && move < 0)
92
+ setCurrentSlide(len);
93
+ }
94
+ setMovement(move);
95
+ };
96
+ /**
97
+ * Throttle call of next and back function.
98
+ */
99
+ var throttle = function (callback, delay) {
100
+ if (delay === void 0) { delay = 100; }
101
+ if (throttleRef.current)
102
+ return;
103
+ throttleRef.current = true;
104
+ callback();
105
+ setTimeout(function () {
106
+ throttleRef.current = false;
107
+ }, delay);
108
+ };
109
+ /**
110
+ * Navigates to the next slide if possible.
111
+ */
112
+ var next = function () {
113
+ if (disableRightArrow && !infiniteSlide)
114
+ return;
115
+ throttle(function () {
116
+ if (disableRightArrow) {
117
+ setCurrentSlide(0);
118
+ return;
119
+ }
120
+ setCurrentSlide(function (prev) { return prev + 1; });
121
+ });
122
+ };
123
+ /**
124
+ * Navigates to the previous slide if possible.
125
+ */
126
+ var back = function () {
127
+ if (disableLeftArrow && !infiniteSlide)
128
+ return;
129
+ throttle(function () {
130
+ if (disableLeftArrow) {
131
+ setCurrentSlide(data.length - 1);
132
+ return;
133
+ }
134
+ setCurrentSlide(function (prev) { return prev - 1; });
135
+ });
136
+ };
137
+ /**
138
+ * Ends the drag or swipe interaction and determines if a slide change should occur.
139
+ *
140
+ * @param e - Mouse or touch event.
141
+ * @param param - Optional parameter to indicate a mobile event.
142
+ */
143
+ var endSlide = function (param) {
144
+ if (mobileOnly && window.innerWidth >= (mobileBound || MOBILE_BOUND))
145
+ return;
146
+ setGrab(false);
147
+ endRef.current = slider(param);
148
+ if (startRef.current > endRef.current && startRef.current - endRef.current > 64)
149
+ onNext ? onNext() : next();
150
+ if (startRef.current < endRef.current && endRef.current - startRef.current > 64)
151
+ onBack ? onBack() : back();
152
+ setMovement(0);
153
+ };
154
+ return {
155
+ currentSlide: currentSlide,
156
+ movement: movement,
157
+ grab: grab,
158
+ disableLeftArrow: disableLeftArrow,
159
+ disableRightArrow: disableRightArrow,
160
+ setCurrentSlide: setCurrentSlide,
161
+ startSlide: startSlide,
162
+ moveSlide: moveSlide,
163
+ endSlide: endSlide,
164
+ next: next,
165
+ back: back,
166
+ };
167
+ }
@@ -0,0 +1,11 @@
1
+ export * from "./constants";
2
+ export * from "./hooks/debounce";
3
+ export * from "./hooks/router";
4
+ export * from "./hooks/slider";
5
+ export * from "./types";
6
+ export { default as http, ApiInstance, ApiMeta } from "./utils/api";
7
+ export * from "./utils/cookie";
8
+ export * from "./utils/file";
9
+ export * from "./utils/general";
10
+ export * from "./utils/local";
11
+ export { default as createApi } from "./utils/useApi";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export * from "./constants";
2
+ export * from "./hooks/debounce";
3
+ export * from "./hooks/router";
4
+ export * from "./hooks/slider";
5
+ export * from "./types";
6
+ export { default as http, ApiInstance, ApiMeta } from "./utils/api";
7
+ export * from "./utils/cookie";
8
+ export * from "./utils/file";
9
+ export * from "./utils/general";
10
+ export * from "./utils/local";
11
+ export { default as createApi } from "./utils/useApi";
@@ -0,0 +1,12 @@
1
+ export declare enum EStatus {
2
+ Error = "error",
3
+ Success = "success",
4
+ Info = "info",
5
+ Warning = "warning"
6
+ }
7
+ export declare enum ERegisterMode {
8
+ Register = "Register",
9
+ Registered = "Registered",
10
+ RegisteredAsOther = "RegisteredAsOther",
11
+ Login = "Login"
12
+ }
@@ -0,0 +1,14 @@
1
+ export var EStatus;
2
+ (function (EStatus) {
3
+ EStatus["Error"] = "error";
4
+ EStatus["Success"] = "success";
5
+ EStatus["Info"] = "info";
6
+ EStatus["Warning"] = "warning";
7
+ })(EStatus || (EStatus = {}));
8
+ export var ERegisterMode;
9
+ (function (ERegisterMode) {
10
+ ERegisterMode["Register"] = "Register";
11
+ ERegisterMode["Registered"] = "Registered";
12
+ ERegisterMode["RegisteredAsOther"] = "RegisteredAsOther";
13
+ ERegisterMode["Login"] = "Login";
14
+ })(ERegisterMode || (ERegisterMode = {}));
@@ -0,0 +1 @@
1
+ export type * from "./meta.d.ts";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,274 @@
1
+ export type TPrimitive = string | number | boolean;
2
+ export type TProgress = {
3
+ loaded: number;
4
+ total: number;
5
+ percentage: number;
6
+ };
7
+ export type TProgressCallback = (progress: TProgress) => void;
8
+ export type THttpConfig = {
9
+ /** Optional request headers */
10
+ headers?: Record<string, string>;
11
+ /** Query parameters for the request */
12
+ params?: Record<string, TPrimitive | TPrimitive[]>;
13
+ /** Optional cache configuration */
14
+ cache?: {
15
+ /** Enable or disable caching for this request */
16
+ enabled?: boolean;
17
+ /** Cache revalidation time in milliseconds */
18
+ revalidate?: number;
19
+ };
20
+ /** Abort signal to cancel the request */
21
+ signal?: AbortSignal;
22
+ /** Upload progress callback */
23
+ onUpload?: TProgressCallback;
24
+ /** Download progress callback */
25
+ onDownload?: TProgressCallback;
26
+ };
27
+ export type TCacheEntry<T> = {
28
+ /** Cached data */
29
+ data: T;
30
+ /** Timestamp when the data was cached */
31
+ timestamp: number;
32
+ /** Optional time-to-live (TTL) in milliseconds */
33
+ ttl?: number;
34
+ };
35
+ export type TApiConfig = {
36
+ /** Base URL of the API */
37
+ baseURL?: string;
38
+ /** Endpoint URL (relative or absolute) */
39
+ url: string;
40
+ /** HTTP method for the request */
41
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
42
+ /** Request body content */
43
+ body?: globalThis.BodyInit;
44
+ /** Request mode (e.g., 'cors', 'same-origin') */
45
+ mode?: globalThis.RequestMode;
46
+ /** Number of retry attempts on failure */
47
+ retry?: number;
48
+ } & THttpConfig;
49
+ export type TApiInstanceOptions = {
50
+ /** Base URL applied to all requests from this instance */
51
+ baseURL?: string;
52
+ /** Default headers applied to all requests */
53
+ headers?: Record<string, string>;
54
+ /** Source identifier used for cache scoping */
55
+ source?: string;
56
+ /** Maximum number of cache entries to store */
57
+ maxCacheSize?: number;
58
+ };
59
+ export type TApiResponse<T> = {
60
+ /** Parsed JSON data from the response */
61
+ data: T;
62
+ /** Unique key identifying this request (for caching) */
63
+ cacheKey?: string;
64
+ /** Indicates whether the data was served from cache */
65
+ fromCache: boolean;
66
+ };
67
+ export interface IApiInterceptor {
68
+ /**
69
+ * Intercept and modify the request configuration before sending.
70
+ * @param config{@link TApiConfig}: The outgoing request configuration
71
+ */
72
+ request?: (config: TApiConfig) => TApiConfig | Promise<TApiConfig>;
73
+ /**
74
+ * Intercept and modify the response before returning.
75
+ * @param response The received Response object
76
+ */
77
+ response?: (response: Response) => Response | Promise<Response>;
78
+ /**
79
+ * Handle errors thrown during the request lifecycle.
80
+ * @param error The thrown error object
81
+ */
82
+ error?: (error: unknown) => Promise<unknown>;
83
+ }
84
+ interface IApiInstance {
85
+ /**
86
+ * Registers custom interceptors for requests and responses.
87
+ *
88
+ * @param interceptors{@link IApiInterceptor}: Object containing optional `request`, `response`, and `error` interceptors.
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * api.setInterceptors({
93
+ * request: config => ({ ...config, headers: { ...config.headers, Authorization: 'Bearer token' } }),
94
+ * response: response => response,
95
+ * error: error => Promise.reject(error),
96
+ * })
97
+ * ```
98
+ */
99
+ setInterceptors(interceptors: IApiInterceptor): void;
100
+ /**
101
+ * Sends a general API request with full configuration control.
102
+ *
103
+ * @template T - The expected response data type.
104
+ * @param config{@link TApiConfig}: Full request configuration including URL, method, params, headers, etc.
105
+ * @returns A promise that resolves to the API response.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * const res = await api.request<{ users: User[] }>({
110
+ * url: '/users',
111
+ * method: 'GET',
112
+ * cache: { enabled: true, revalidate: 5000 },
113
+ * })
114
+ * ```
115
+ */
116
+ request<T>(config: TApiConfig): Promise<TApiResponse<T>>;
117
+ /**
118
+ * Performs a GET request.
119
+ *
120
+ * @template T - The expected response data type.
121
+ * @param url - The request URL.
122
+ * @param config{@link TApiConfig}: Optional request configuration (headers, params, cache, etc).
123
+ * @returns A promise resolving to the API response.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * const res = await api.get<User[]>('/users')
128
+ * ```
129
+ */
130
+ get<T>(url: string, config?: THttpConfig): Promise<TApiResponse<T>>;
131
+ /**
132
+ * Performs a POST request.
133
+ *
134
+ * @template T - The expected response data type.
135
+ * @param url - The request URL.
136
+ * @param body - Optional request body.
137
+ * @param config{@link TApiConfig}: Optional request configuration.
138
+ * @returns A promise resolving to the API response.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const res = await api.post<User>('/users', JSON.stringify({ name: 'John' }))
143
+ * ```
144
+ */
145
+ post<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
146
+ /**
147
+ * Performs a PUT request.
148
+ *
149
+ * @template T - The expected response data type.
150
+ * @param url - The request URL.
151
+ * @param body - Optional request body.
152
+ * @param config{@link TApiConfig}: Optional request configuration.
153
+ * @returns A promise resolving to the API response.
154
+ */
155
+ put<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
156
+ /**
157
+ * Performs a PATCH request.
158
+ *
159
+ * @template T - The expected response data type.
160
+ * @param url - The request URL.
161
+ * @param body - Optional request body.
162
+ * @param config{@link TApiConfig}: Optional request configuration.
163
+ * @returns A promise resolving to the API response.
164
+ */
165
+ patch<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
166
+ /**
167
+ * Performs a DELETE request.
168
+ *
169
+ * @template T - The expected response data type.
170
+ * @param url - The request URL.
171
+ * @param body - Optional request body.
172
+ * @param config{@link TApiConfig}: Optional request configuration.
173
+ * @returns A promise resolving to the API response.
174
+ */
175
+ delete<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
176
+ /**
177
+ * Retrieves a cached response by key.
178
+ *
179
+ * @template T - Type of cached data.
180
+ * @param key - Cache key used during the request.
181
+ * @returns Cached data if available, otherwise `undefined`.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * const cached = api.getCache<User[]>('users:list')
186
+ * ```
187
+ */
188
+ getCache<T>(key: string): T | undefined;
189
+ /**
190
+ * Manually stores data in cache.
191
+ *
192
+ * @template T - Type of data to cache.
193
+ * @param key - Cache key.
194
+ * @param data - Data to store.
195
+ * @param ttl - Optional time-to-live (milliseconds).
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * api.setCache('user:1', { id: 1, name: 'John' }, 5000)
200
+ * ```
201
+ */
202
+ setCache<T>(key: string, data: T, ttl?: number): void;
203
+ /**
204
+ * Removes a specific cache entry by key.
205
+ *
206
+ * @param key - Cache key to remove.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * api.removeCache('user:1')
211
+ * ```
212
+ */
213
+ removeCache(key: string): void;
214
+ /**
215
+ * Clears all cache entries from the instance.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * api.clearCache()
220
+ * ```
221
+ */
222
+ clearCache(): void;
223
+ }
224
+ export declare const buildURL: (url: string, params?: THttpConfig["params"]) => string;
225
+ export declare class ApiMeta extends Error {
226
+ code: number;
227
+ status: string;
228
+ constructor(code: number, message: string, status: string);
229
+ }
230
+ export declare class ApiInstance implements IApiInstance {
231
+ private baseURL;
232
+ private defaultHeaders;
233
+ private interceptors;
234
+ private source;
235
+ private cache;
236
+ private maxCacheSize;
237
+ private cacheAccessOrder;
238
+ constructor(options?: TApiInstanceOptions);
239
+ setInterceptors(interceptors: IApiInterceptor): void;
240
+ private hash;
241
+ private buildcacheKey;
242
+ private fetchWithXHR;
243
+ private fetchWithRetry;
244
+ private handleInterceptors;
245
+ private handleResponse;
246
+ private handleError;
247
+ private getCacheEntry;
248
+ private setCacheEntry;
249
+ private removeCacheEntry;
250
+ request<T>(config: TApiConfig): Promise<TApiResponse<T>>;
251
+ get<T>(url: string, config?: THttpConfig): Promise<TApiResponse<T>>;
252
+ post<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
253
+ put<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
254
+ patch<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
255
+ delete<T, U = unknown>(url: string, body?: U, config?: THttpConfig): Promise<TApiResponse<T>>;
256
+ getCache<T>(key: string): T | undefined;
257
+ setCache<T>(key: string, data: T, ttl?: number): void;
258
+ removeCache(key: string): void;
259
+ clearCache(): void;
260
+ }
261
+ declare const http: {
262
+ get: <T>(url: string, config?: THttpConfig) => Promise<TApiResponse<T>>;
263
+ post: <T, U = unknown>(url: string, body?: U, config?: THttpConfig) => Promise<TApiResponse<T>>;
264
+ put: <T, U = unknown>(url: string, body?: U, config?: THttpConfig) => Promise<TApiResponse<T>>;
265
+ patch: <T, U = unknown>(url: string, body?: U, config?: THttpConfig) => Promise<TApiResponse<T>>;
266
+ delete: <T, U = unknown>(url: string, body?: U, config?: THttpConfig) => Promise<TApiResponse<T>>;
267
+ getCache: <T>(key: string) => T | undefined;
268
+ setCache: <T>(key: string, data: T, ttl?: number) => void;
269
+ removeCache: (key: string) => void;
270
+ clearCache: () => void;
271
+ request: (config: TApiConfig) => Promise<TApiResponse<unknown>>;
272
+ create: (options?: TApiInstanceOptions) => IApiInstance;
273
+ };
274
+ export default http;