@isik-kaplan/core 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 Işık Kaplan
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,22 @@
1
+ # @isik-kaplan/core
2
+
3
+ Everyday TypeScript utilities - the small stuff every project ends up rewriting: object/string
4
+ helpers, date formatting, browser file handling, a couple of React hooks, and some Next.js glue.
5
+ Framework-specific pieces are split into their own entry points so you never pay for peer
6
+ dependencies you don't use.
7
+
8
+ ```typescript
9
+ import { formattedDate, slugify } from '@isik-kaplan/core'
10
+
11
+ slugify('Café Münster') // 'cafe-munster'
12
+ formattedDate('yyyy-MM-dd', new Date(2026, 0, 5)) // '2026-01-05'
13
+ ```
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @isik-kaplan/core
19
+ ```
20
+
21
+ See [docs/INDEX.md](docs/INDEX.md) for everything else - every exported utility, its entry point,
22
+ and a usage example.
@@ -0,0 +1,341 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/hooks/index.ts
21
+ var hooks_exports = {};
22
+ __export(hooks_exports, {
23
+ useEffectAfterMount: () => useEffectAfterMount,
24
+ useElementAttributes: () => useElementAttributes,
25
+ useFileDragDrop: () => useFileDragDrop,
26
+ useFilePaste: () => useFilePaste,
27
+ useFormState: () => useFormState
28
+ });
29
+ module.exports = __toCommonJS(hooks_exports);
30
+ var import_react = require("react");
31
+ function useElementAttributes(attributeKeys) {
32
+ const ref = (0, import_react.useRef)(null);
33
+ const [attributeValues, setAttributeValue] = (0, import_react.useState)({});
34
+ const updateAttribute = (0, import_react.useCallback)(() => {
35
+ if (ref.current) {
36
+ const values = {};
37
+ for (const key of attributeKeys) {
38
+ Object.defineProperty(values, key, {
39
+ value: ref.current[key],
40
+ writable: true,
41
+ configurable: true,
42
+ enumerable: true
43
+ });
44
+ }
45
+ setAttributeValue((prevValues) => {
46
+ const hasChanged = attributeKeys.some((key) => prevValues[key] !== values[key]);
47
+ return hasChanged ? values : prevValues;
48
+ });
49
+ }
50
+ }, [attributeKeys]);
51
+ (0, import_react.useEffect)(() => {
52
+ updateAttribute();
53
+ window.addEventListener("resize", updateAttribute);
54
+ if (ref.current) {
55
+ const observer = new MutationObserver(updateAttribute);
56
+ observer.observe(ref.current, { attributes: true });
57
+ return () => {
58
+ window.removeEventListener("resize", updateAttribute);
59
+ observer.disconnect();
60
+ };
61
+ }
62
+ return () => {
63
+ window.removeEventListener("resize", updateAttribute);
64
+ };
65
+ }, [updateAttribute]);
66
+ return { ref, attributeValues };
67
+ }
68
+ function useFormState(initialState) {
69
+ const [formState, setFormState] = (0, import_react.useState)(initialState);
70
+ const [formErrors, setFormErrors] = (0, import_react.useState)();
71
+ function resetFormState() {
72
+ setFormState(initialState);
73
+ }
74
+ function handleFormState({
75
+ key,
76
+ inputType
77
+ }) {
78
+ return (event) => {
79
+ let value;
80
+ if (inputType === "event") {
81
+ const target = event.target;
82
+ if (target.type === "checkbox") {
83
+ value = target.checked;
84
+ } else if (target.type === "number" || target.type === "range") {
85
+ value = target.valueAsNumber;
86
+ } else {
87
+ value = target.value;
88
+ }
89
+ } else {
90
+ value = event;
91
+ }
92
+ setFormState((prev) => ({ ...prev, [key]: value }));
93
+ };
94
+ }
95
+ const handleFormStateValue = (key) => handleFormState({ key, inputType: "value" });
96
+ const handleFormStateEvent = (key) => handleFormState({ key, inputType: "event" });
97
+ const handleFormStateOnClick = (key, value) => () => {
98
+ setFormState((prev) => ({ ...prev, [key]: value }));
99
+ };
100
+ return {
101
+ formState,
102
+ setFormState,
103
+ formErrors,
104
+ setFormErrors,
105
+ handleFormStateValue,
106
+ handleFormStateEvent,
107
+ handleFormStateOnClick,
108
+ resetFormState
109
+ };
110
+ }
111
+ function useEffectAfterMount(effect, deps) {
112
+ const isFirstRender = (0, import_react.useRef)(true);
113
+ (0, import_react.useEffect)(() => {
114
+ if (isFirstRender.current) {
115
+ isFirstRender.current = false;
116
+ return;
117
+ }
118
+ return effect();
119
+ }, deps);
120
+ }
121
+ function useFilePaste({
122
+ acceptedTypes,
123
+ maxSize,
124
+ targetElement,
125
+ enabled = true
126
+ } = {}) {
127
+ const [files, setFiles] = (0, import_react.useState)([]);
128
+ const [isLoading, setIsLoading] = (0, import_react.useState)(false);
129
+ const [error, setError] = (0, import_react.useState)(null);
130
+ const clearFiles = (0, import_react.useCallback)(() => {
131
+ setFiles([]);
132
+ setError(null);
133
+ }, []);
134
+ const validateFiles = (0, import_react.useCallback)(
135
+ (pastedFiles) => {
136
+ if (acceptedTypes && acceptedTypes.length > 0) {
137
+ const wildcardAcceptedTypes = acceptedTypes.filter((type) => type.endsWith("/*")).map((type) => type.slice(0, -1));
138
+ const normalizedAcceptedTypes = acceptedTypes.map((type) => type.endsWith("/*") ? type.slice(0, -2) : type);
139
+ const invalidFiles = pastedFiles.filter((file) => {
140
+ const fileType = file.type;
141
+ return !normalizedAcceptedTypes.includes(fileType) && !wildcardAcceptedTypes.some((wildcardType) => fileType.startsWith(wildcardType));
142
+ });
143
+ if (invalidFiles.length > 0) {
144
+ const invalidFileNames = invalidFiles.map((file) => file.name).join(", ");
145
+ return {
146
+ valid: false,
147
+ error: `Invalid file types: ${invalidFileNames}. Accepted types: ${acceptedTypes.join(", ")}`
148
+ };
149
+ }
150
+ }
151
+ if (maxSize) {
152
+ const oversizedFile = pastedFiles.find((file) => file.size > maxSize);
153
+ if (oversizedFile) {
154
+ const fileSizeMB = (oversizedFile.size / (1024 * 1024)).toFixed(2);
155
+ const maxSizeMB = (maxSize / (1024 * 1024)).toFixed(2);
156
+ return {
157
+ valid: false,
158
+ error: `File "${oversizedFile.name}" (${fileSizeMB} MB) exceeds the maximum size of ${maxSizeMB} MB`
159
+ };
160
+ }
161
+ }
162
+ return { valid: true };
163
+ },
164
+ [acceptedTypes, maxSize]
165
+ );
166
+ const handlePaste = (0, import_react.useCallback)(
167
+ (event) => {
168
+ const { clipboardData } = event;
169
+ if (!clipboardData) return;
170
+ const hasFiles = clipboardData.files && clipboardData.files.length > 0;
171
+ if (!hasFiles) return;
172
+ event.preventDefault();
173
+ setIsLoading(true);
174
+ setError(null);
175
+ try {
176
+ const pastedFiles = Array.from(clipboardData.files);
177
+ const validation = validateFiles(pastedFiles);
178
+ if (!validation.valid) {
179
+ setError(validation.error);
180
+ setFiles([]);
181
+ } else {
182
+ setFiles(pastedFiles);
183
+ }
184
+ } catch (err) {
185
+ setError(err instanceof Error ? err.message : "Failed to process pasted files");
186
+ setFiles([]);
187
+ } finally {
188
+ setIsLoading(false);
189
+ }
190
+ },
191
+ [validateFiles]
192
+ );
193
+ (0, import_react.useEffect)(() => {
194
+ if (!enabled) return;
195
+ const target = targetElement || document;
196
+ target.addEventListener("paste", handlePaste);
197
+ return () => {
198
+ target.removeEventListener("paste", handlePaste);
199
+ };
200
+ }, [enabled, handlePaste, targetElement]);
201
+ return { files, isLoading, error, clearFiles };
202
+ }
203
+ function useFileDragDrop(options = {}) {
204
+ const { onDrop, onDragOver, onDragLeave, acceptedFileTypes, maxFileSize, multiple = true } = options;
205
+ const [state, setState] = (0, import_react.useState)({
206
+ isDragging: false,
207
+ files: null
208
+ });
209
+ const ref = (0, import_react.useRef)(null);
210
+ const dragCounter = (0, import_react.useRef)(0);
211
+ const handleDragOver = (0, import_react.useCallback)(
212
+ (e) => {
213
+ e.preventDefault();
214
+ e.stopPropagation();
215
+ onDragOver?.(e);
216
+ },
217
+ [onDragOver]
218
+ );
219
+ const handleDragEnter = (0, import_react.useCallback)(
220
+ (e) => {
221
+ e.preventDefault();
222
+ e.stopPropagation();
223
+ dragCounter.current += 1;
224
+ if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
225
+ const hasValidItems = Array.from(e.dataTransfer.items).some((item) => {
226
+ if (item.kind !== "file") {
227
+ return false;
228
+ }
229
+ if (acceptedFileTypes && acceptedFileTypes.length > 0) {
230
+ return acceptedFileTypes.some((type) => {
231
+ if (type.endsWith("/*")) {
232
+ const category = type.split("/")[0];
233
+ return item.type.startsWith(`${category}/`);
234
+ }
235
+ return item.type === type;
236
+ });
237
+ }
238
+ return true;
239
+ });
240
+ if (hasValidItems) {
241
+ setState((prevState) => ({
242
+ ...prevState,
243
+ isDragging: true
244
+ }));
245
+ }
246
+ }
247
+ },
248
+ [acceptedFileTypes]
249
+ );
250
+ const handleDragLeave = (0, import_react.useCallback)(
251
+ (e) => {
252
+ e.preventDefault();
253
+ e.stopPropagation();
254
+ dragCounter.current -= 1;
255
+ if (dragCounter.current === 0) {
256
+ setState((prevState) => ({
257
+ ...prevState,
258
+ isDragging: false
259
+ }));
260
+ }
261
+ onDragLeave?.(e);
262
+ },
263
+ [onDragLeave]
264
+ );
265
+ const handleDrop = (0, import_react.useCallback)(
266
+ (e) => {
267
+ e.preventDefault();
268
+ e.stopPropagation();
269
+ dragCounter.current = 0;
270
+ setState((prevState) => ({
271
+ ...prevState,
272
+ isDragging: false
273
+ }));
274
+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
275
+ let validFiles = Array.from(e.dataTransfer.files);
276
+ if (acceptedFileTypes && acceptedFileTypes.length > 0) {
277
+ validFiles = validFiles.filter(
278
+ (file) => acceptedFileTypes.some((type) => {
279
+ if (type.endsWith("/*")) {
280
+ const category = type.split("/")[0];
281
+ return file.type.startsWith(`${category}/`);
282
+ }
283
+ return file.type === type;
284
+ })
285
+ );
286
+ }
287
+ if (maxFileSize) {
288
+ validFiles = validFiles.filter((file) => file.size <= maxFileSize);
289
+ }
290
+ if (!multiple && validFiles.length > 0) {
291
+ validFiles = [validFiles[0]];
292
+ }
293
+ if (validFiles.length > 0) {
294
+ setState((prevState) => ({
295
+ ...prevState,
296
+ files: validFiles
297
+ }));
298
+ onDrop?.(validFiles);
299
+ }
300
+ }
301
+ },
302
+ [onDrop, acceptedFileTypes, maxFileSize, multiple]
303
+ );
304
+ (0, import_react.useEffect)(() => {
305
+ const currentRef = ref.current;
306
+ if (currentRef) {
307
+ currentRef.addEventListener("dragover", handleDragOver);
308
+ currentRef.addEventListener("dragenter", handleDragEnter);
309
+ currentRef.addEventListener("dragleave", handleDragLeave);
310
+ currentRef.addEventListener("drop", handleDrop);
311
+ return () => {
312
+ currentRef.removeEventListener("dragover", handleDragOver);
313
+ currentRef.removeEventListener("dragenter", handleDragEnter);
314
+ currentRef.removeEventListener("dragleave", handleDragLeave);
315
+ currentRef.removeEventListener("drop", handleDrop);
316
+ };
317
+ }
318
+ return void 0;
319
+ }, [handleDragOver, handleDragEnter, handleDragLeave, handleDrop]);
320
+ const reset = (0, import_react.useCallback)(() => {
321
+ setState({
322
+ isDragging: false,
323
+ files: null
324
+ });
325
+ }, []);
326
+ return {
327
+ ref,
328
+ isDragging: state.isDragging,
329
+ files: state.files,
330
+ reset
331
+ };
332
+ }
333
+ // Annotate the CommonJS export names for ESM import in node:
334
+ 0 && (module.exports = {
335
+ useEffectAfterMount,
336
+ useElementAttributes,
337
+ useFileDragDrop,
338
+ useFilePaste,
339
+ useFormState
340
+ });
341
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hooks/index.ts"],"sourcesContent":["import type { ChangeEvent, DependencyList, DragEvent, EffectCallback } from 'react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nexport function useElementAttributes<T extends HTMLElement, K extends keyof T>(attributeKeys: K[]) {\n const ref = useRef<T | null>(null)\n const [attributeValues, setAttributeValue] = useState<Partial<Pick<T, K>>>({})\n\n const updateAttribute = useCallback(() => {\n if (ref.current) {\n const values = {} as Partial<Pick<T, K>>\n for (const key of attributeKeys) {\n // Object.defineProperty (unlike a plain `values[key] = value` assignment) always creates/\n // overwrites an own property, even if a consumer's T somehow has a key like \"__proto__\" -\n // matches the same defensive pattern used everywhere else in this package that writes a\n // non-literal key onto an object.\n Object.defineProperty(values, key, {\n value: ref.current[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n\n setAttributeValue((prevValues) => {\n const hasChanged = attributeKeys.some((key) => prevValues[key] !== values[key])\n return hasChanged ? values : prevValues\n })\n }\n }, [attributeKeys])\n\n useEffect(() => {\n updateAttribute()\n window.addEventListener('resize', updateAttribute)\n\n if (ref.current) {\n const observer = new MutationObserver(updateAttribute)\n observer.observe(ref.current, { attributes: true })\n\n return () => {\n window.removeEventListener('resize', updateAttribute)\n observer.disconnect()\n }\n }\n\n return () => {\n window.removeEventListener('resize', updateAttribute)\n }\n }, [updateAttribute])\n\n return { ref, attributeValues }\n}\n\ntype InputEventType = ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>\n\nexport function useFormState<T>(initialState: T) {\n const [formState, setFormState] = useState<T>(initialState)\n const [formErrors, setFormErrors] = useState<Partial<Record<keyof T, string[]>> & { non_field_errors?: string[] }>()\n\n function resetFormState() {\n setFormState(initialState)\n }\n\n function handleFormState<K extends keyof T, HandlerInputType>({\n key,\n inputType,\n }: {\n key: K\n inputType: 'event' | 'value'\n }) {\n return (event: HandlerInputType) => {\n let value: T[K]\n if (inputType === 'event') {\n const target = (event as InputEventType).target\n if (target.type === 'checkbox') {\n value = (target as HTMLInputElement).checked as T[K]\n } else if (target.type === 'number' || target.type === 'range') {\n value = (target as HTMLInputElement).valueAsNumber as T[K]\n } else {\n value = target.value as T[K]\n }\n } else {\n value = event as T[K]\n }\n setFormState((prev) => ({ ...prev, [key]: value }))\n }\n }\n\n const handleFormStateValue = <K extends keyof T>(key: K) => handleFormState<K, T[K]>({ key, inputType: 'value' })\n const handleFormStateEvent = <K extends keyof T>(key: K) =>\n handleFormState<K, InputEventType>({ key, inputType: 'event' })\n const handleFormStateOnClick =\n <K extends keyof T>(key: K, value: T[K]) =>\n () => {\n setFormState((prev) => ({ ...prev, [key]: value }))\n }\n\n return {\n formState,\n setFormState,\n formErrors,\n setFormErrors,\n handleFormStateValue,\n handleFormStateEvent,\n handleFormStateOnClick,\n resetFormState,\n }\n}\n\nexport function useEffectAfterMount(effect: EffectCallback, deps: DependencyList) {\n const isFirstRender = useRef(true)\n\n // No manual \"did deps actually change\" recheck needed here: React's own useEffect already\n // only re-invokes this callback when a dependency's value changed (shallow-compared against\n // the last time *this exact effect* ran) - which is exactly the same comparison a hand-rolled\n // check against a \"previous deps\" ref would be making, just duplicated.\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false\n return\n }\n return effect()\n }, deps)\n}\n\nexport function useFilePaste({\n acceptedTypes,\n maxSize,\n targetElement,\n enabled = true,\n}: {\n acceptedTypes?: string[]\n maxSize?: number\n targetElement?: HTMLElement | null\n enabled?: boolean\n} = {}): {\n files: File[]\n isLoading: boolean\n error: string | null\n clearFiles: () => void\n} {\n const [files, setFiles] = useState<File[]>([])\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n const clearFiles = useCallback(() => {\n setFiles([])\n setError(null)\n }, [])\n\n const validateFiles = useCallback(\n (pastedFiles: File[]): { valid: true } | { valid: false; error: string } => {\n if (acceptedTypes && acceptedTypes.length > 0) {\n const wildcardAcceptedTypes = acceptedTypes\n .filter((type) => type.endsWith('/*'))\n .map((type) => type.slice(0, -1))\n const normalizedAcceptedTypes = acceptedTypes.map((type) => (type.endsWith('/*') ? type.slice(0, -2) : type))\n\n const invalidFiles = pastedFiles.filter((file) => {\n const fileType = file.type\n return (\n !normalizedAcceptedTypes.includes(fileType) &&\n !wildcardAcceptedTypes.some((wildcardType) => fileType.startsWith(wildcardType))\n )\n })\n if (invalidFiles.length > 0) {\n const invalidFileNames = invalidFiles.map((file) => file.name).join(', ')\n return {\n valid: false,\n error: `Invalid file types: ${invalidFileNames}. Accepted types: ${acceptedTypes.join(', ')}`,\n }\n }\n }\n\n if (maxSize) {\n const oversizedFile = pastedFiles.find((file) => file.size > maxSize)\n if (oversizedFile) {\n const fileSizeMB = (oversizedFile.size / (1024 * 1024)).toFixed(2)\n const maxSizeMB = (maxSize / (1024 * 1024)).toFixed(2)\n return {\n valid: false,\n error: `File \"${oversizedFile.name}\" (${fileSizeMB} MB) exceeds the maximum size of ${maxSizeMB} MB`,\n }\n }\n }\n\n return { valid: true }\n },\n [acceptedTypes, maxSize]\n )\n\n const handlePaste = useCallback(\n (event: ClipboardEvent) => {\n const { clipboardData } = event\n if (!clipboardData) return\n\n const hasFiles = clipboardData.files && clipboardData.files.length > 0\n if (!hasFiles) return\n\n event.preventDefault()\n setIsLoading(true)\n setError(null)\n\n try {\n const pastedFiles = Array.from(clipboardData.files)\n const validation = validateFiles(pastedFiles)\n\n if (!validation.valid) {\n setError(validation.error)\n setFiles([])\n } else {\n setFiles(pastedFiles)\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Failed to process pasted files')\n setFiles([])\n } finally {\n setIsLoading(false)\n }\n },\n [validateFiles]\n )\n\n useEffect(() => {\n if (!enabled) return\n\n const target = targetElement || document\n\n target.addEventListener('paste', handlePaste as EventListener)\n return () => {\n target.removeEventListener('paste', handlePaste as EventListener)\n }\n }, [enabled, handlePaste, targetElement])\n\n return { files, isLoading, error, clearFiles }\n}\n\ntype FileDragDropState = {\n isDragging: boolean\n files: File[] | null\n}\n\ntype FileDragDropOptions = {\n onDrop?: (files: File[]) => void\n onDragOver?: (e: DragEvent<HTMLElement>) => void\n onDragLeave?: (e: DragEvent<HTMLElement>) => void\n acceptedFileTypes?: string[]\n maxFileSize?: number\n multiple?: boolean\n}\n\nexport function useFileDragDrop<T extends HTMLElement = HTMLDivElement>(options: FileDragDropOptions = {}) {\n const { onDrop, onDragOver, onDragLeave, acceptedFileTypes, maxFileSize, multiple = true } = options\n\n const [state, setState] = useState<FileDragDropState>({\n isDragging: false,\n files: null,\n })\n\n const ref = useRef<T | null>(null)\n const dragCounter = useRef(0)\n\n const handleDragOver = useCallback(\n (e: DragEvent<T>) => {\n e.preventDefault()\n e.stopPropagation()\n\n onDragOver?.(e)\n },\n [onDragOver]\n )\n\n const handleDragEnter = useCallback(\n (e: DragEvent<T>) => {\n e.preventDefault()\n e.stopPropagation()\n\n dragCounter.current += 1\n\n if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {\n const hasValidItems = Array.from(e.dataTransfer.items).some((item) => {\n if (item.kind !== 'file') {\n return false\n }\n\n if (acceptedFileTypes && acceptedFileTypes.length > 0) {\n return acceptedFileTypes.some((type) => {\n if (type.endsWith('/*')) {\n const category = type.split('/')[0]\n return item.type.startsWith(`${category}/`)\n }\n return item.type === type\n })\n }\n\n return true\n })\n\n if (hasValidItems) {\n setState((prevState) => ({\n ...prevState,\n isDragging: true,\n }))\n }\n }\n },\n [acceptedFileTypes]\n )\n\n const handleDragLeave = useCallback(\n (e: DragEvent<T>) => {\n e.preventDefault()\n e.stopPropagation()\n\n dragCounter.current -= 1\n\n if (dragCounter.current === 0) {\n setState((prevState) => ({\n ...prevState,\n isDragging: false,\n }))\n }\n\n onDragLeave?.(e)\n },\n [onDragLeave]\n )\n\n const handleDrop = useCallback(\n (e: DragEvent<T>) => {\n e.preventDefault()\n e.stopPropagation()\n\n dragCounter.current = 0\n setState((prevState) => ({\n ...prevState,\n isDragging: false,\n }))\n\n if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {\n let validFiles = Array.from(e.dataTransfer.files)\n\n if (acceptedFileTypes && acceptedFileTypes.length > 0) {\n validFiles = validFiles.filter((file) =>\n acceptedFileTypes.some((type) => {\n if (type.endsWith('/*')) {\n const category = type.split('/')[0]\n return file.type.startsWith(`${category}/`)\n }\n return file.type === type\n })\n )\n }\n\n if (maxFileSize) {\n validFiles = validFiles.filter((file) => file.size <= maxFileSize)\n }\n\n if (!multiple && validFiles.length > 0) {\n validFiles = [validFiles[0]]\n }\n\n if (validFiles.length > 0) {\n setState((prevState) => ({\n ...prevState,\n files: validFiles,\n }))\n\n onDrop?.(validFiles)\n }\n }\n },\n [onDrop, acceptedFileTypes, maxFileSize, multiple]\n )\n\n useEffect(() => {\n const currentRef = ref.current\n if (currentRef) {\n currentRef.addEventListener('dragover', handleDragOver as unknown as EventListener)\n currentRef.addEventListener('dragenter', handleDragEnter as unknown as EventListener)\n currentRef.addEventListener('dragleave', handleDragLeave as unknown as EventListener)\n currentRef.addEventListener('drop', handleDrop as unknown as EventListener)\n\n return () => {\n currentRef.removeEventListener('dragover', handleDragOver as unknown as EventListener)\n currentRef.removeEventListener('dragenter', handleDragEnter as unknown as EventListener)\n currentRef.removeEventListener('dragleave', handleDragLeave as unknown as EventListener)\n currentRef.removeEventListener('drop', handleDrop as unknown as EventListener)\n }\n }\n return undefined\n }, [handleDragOver, handleDragEnter, handleDragLeave, handleDrop])\n\n const reset = useCallback(() => {\n setState({\n isDragging: false,\n files: null,\n })\n }, [])\n\n return {\n ref,\n isDragging: state.isDragging,\n files: state.files,\n reset,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAyD;AAElD,SAAS,qBAA+D,eAAoB;AACjG,QAAM,UAAM,qBAAiB,IAAI;AACjC,QAAM,CAAC,iBAAiB,iBAAiB,QAAI,uBAA8B,CAAC,CAAC;AAE7E,QAAM,sBAAkB,0BAAY,MAAM;AACxC,QAAI,IAAI,SAAS;AACf,YAAM,SAAS,CAAC;AAChB,iBAAW,OAAO,eAAe;AAK/B,eAAO,eAAe,QAAQ,KAAK;AAAA,UACjC,OAAO,IAAI,QAAQ,GAAG;AAAA,UACtB,UAAU;AAAA,UACV,cAAc;AAAA,UACd,YAAY;AAAA,QACd,CAAC;AAAA,MACH;AAEA,wBAAkB,CAAC,eAAe;AAChC,cAAM,aAAa,cAAc,KAAK,CAAC,QAAQ,WAAW,GAAG,MAAM,OAAO,GAAG,CAAC;AAC9E,eAAO,aAAa,SAAS;AAAA,MAC/B,CAAC;AAAA,IACH;AAAA,EACF,GAAG,CAAC,aAAa,CAAC;AAElB,8BAAU,MAAM;AACd,oBAAgB;AAChB,WAAO,iBAAiB,UAAU,eAAe;AAEjD,QAAI,IAAI,SAAS;AACf,YAAM,WAAW,IAAI,iBAAiB,eAAe;AACrD,eAAS,QAAQ,IAAI,SAAS,EAAE,YAAY,KAAK,CAAC;AAElD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AAS,GAAG;AACzB,mBAAS,CAAC,eAAe;AAAA,YACvB,GAAG;AAAA,YACH,OAAO;AAAA,UACT,EAAE;AAEF,mBAAS,UAAU;AAAA,QACrB;AAAA,MACF;AAAA,IACF;AAAA,IACA,CAAC,QAAQ,mBAAmB,aAAa,QAAQ;AAAA,EACnD;AAEA,8BAAU,MAAM;AACd,UAAM,aAAa,IAAI;AACvB,QAAI,YAAY;AACd,iBAAW,iBAAiB,YAAY,cAA0C;AAClF,iBAAW,iBAAiB,aAAa,eAA2C;AACpF,iBAAW,iBAAiB,aAAa,eAA2C;AACpF,iBAAW,iBAAiB,QAAQ,UAAsC;AAE1E,aAAO,MAAM;AACX,mBAAW,oBAAoB,YAAY,cAA0C;AACrF,mBAAW,oBAAoB,aAAa,eAA2C;AACvF,mBAAW,oBAAoB,aAAa,eAA2C;AACvF,mBAAW,oBAAoB,QAAQ,UAAsC;AAAA,MAC/E;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,gBAAgB,iBAAiB,iBAAiB,UAAU,CAAC;AAEjE,QAAM,YAAQ,0BAAY,MAAM;AAC9B,aAAS;AAAA,MACP,YAAY;AAAA,MACZ,OAAO;AAAA,IACT,CAAC;AAAA,EACH,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA,YAAY,MAAM;AAAA,IAClB,OAAO,MAAM;AAAA,IACb;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,50 @@
1
+ import * as react from 'react';
2
+ import { EffectCallback, DependencyList, DragEvent, ChangeEvent } from 'react';
3
+
4
+ declare function useElementAttributes<T extends HTMLElement, K extends keyof T>(attributeKeys: K[]): {
5
+ ref: react.RefObject<T | null>;
6
+ attributeValues: Partial<Pick<T, K>>;
7
+ };
8
+ type InputEventType = ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>;
9
+ declare function useFormState<T>(initialState: T): {
10
+ formState: T;
11
+ setFormState: react.Dispatch<react.SetStateAction<T>>;
12
+ formErrors: (Partial<Record<keyof T, string[]>> & {
13
+ non_field_errors?: string[];
14
+ }) | undefined;
15
+ setFormErrors: react.Dispatch<react.SetStateAction<(Partial<Record<keyof T, string[]>> & {
16
+ non_field_errors?: string[];
17
+ }) | undefined>>;
18
+ handleFormStateValue: <K extends keyof T>(key: K) => (event: T[K]) => void;
19
+ handleFormStateEvent: <K extends keyof T>(key: K) => (event: InputEventType) => void;
20
+ handleFormStateOnClick: <K extends keyof T>(key: K, value: T[K]) => () => void;
21
+ resetFormState: () => void;
22
+ };
23
+ declare function useEffectAfterMount(effect: EffectCallback, deps: DependencyList): void;
24
+ declare function useFilePaste({ acceptedTypes, maxSize, targetElement, enabled, }?: {
25
+ acceptedTypes?: string[];
26
+ maxSize?: number;
27
+ targetElement?: HTMLElement | null;
28
+ enabled?: boolean;
29
+ }): {
30
+ files: File[];
31
+ isLoading: boolean;
32
+ error: string | null;
33
+ clearFiles: () => void;
34
+ };
35
+ type FileDragDropOptions = {
36
+ onDrop?: (files: File[]) => void;
37
+ onDragOver?: (e: DragEvent<HTMLElement>) => void;
38
+ onDragLeave?: (e: DragEvent<HTMLElement>) => void;
39
+ acceptedFileTypes?: string[];
40
+ maxFileSize?: number;
41
+ multiple?: boolean;
42
+ };
43
+ declare function useFileDragDrop<T extends HTMLElement = HTMLDivElement>(options?: FileDragDropOptions): {
44
+ ref: react.RefObject<T | null>;
45
+ isDragging: boolean;
46
+ files: File[] | null;
47
+ reset: () => void;
48
+ };
49
+
50
+ export { useEffectAfterMount, useElementAttributes, useFileDragDrop, useFilePaste, useFormState };
@@ -0,0 +1,50 @@
1
+ import * as react from 'react';
2
+ import { EffectCallback, DependencyList, DragEvent, ChangeEvent } from 'react';
3
+
4
+ declare function useElementAttributes<T extends HTMLElement, K extends keyof T>(attributeKeys: K[]): {
5
+ ref: react.RefObject<T | null>;
6
+ attributeValues: Partial<Pick<T, K>>;
7
+ };
8
+ type InputEventType = ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>;
9
+ declare function useFormState<T>(initialState: T): {
10
+ formState: T;
11
+ setFormState: react.Dispatch<react.SetStateAction<T>>;
12
+ formErrors: (Partial<Record<keyof T, string[]>> & {
13
+ non_field_errors?: string[];
14
+ }) | undefined;
15
+ setFormErrors: react.Dispatch<react.SetStateAction<(Partial<Record<keyof T, string[]>> & {
16
+ non_field_errors?: string[];
17
+ }) | undefined>>;
18
+ handleFormStateValue: <K extends keyof T>(key: K) => (event: T[K]) => void;
19
+ handleFormStateEvent: <K extends keyof T>(key: K) => (event: InputEventType) => void;
20
+ handleFormStateOnClick: <K extends keyof T>(key: K, value: T[K]) => () => void;
21
+ resetFormState: () => void;
22
+ };
23
+ declare function useEffectAfterMount(effect: EffectCallback, deps: DependencyList): void;
24
+ declare function useFilePaste({ acceptedTypes, maxSize, targetElement, enabled, }?: {
25
+ acceptedTypes?: string[];
26
+ maxSize?: number;
27
+ targetElement?: HTMLElement | null;
28
+ enabled?: boolean;
29
+ }): {
30
+ files: File[];
31
+ isLoading: boolean;
32
+ error: string | null;
33
+ clearFiles: () => void;
34
+ };
35
+ type FileDragDropOptions = {
36
+ onDrop?: (files: File[]) => void;
37
+ onDragOver?: (e: DragEvent<HTMLElement>) => void;
38
+ onDragLeave?: (e: DragEvent<HTMLElement>) => void;
39
+ acceptedFileTypes?: string[];
40
+ maxFileSize?: number;
41
+ multiple?: boolean;
42
+ };
43
+ declare function useFileDragDrop<T extends HTMLElement = HTMLDivElement>(options?: FileDragDropOptions): {
44
+ ref: react.RefObject<T | null>;
45
+ isDragging: boolean;
46
+ files: File[] | null;
47
+ reset: () => void;
48
+ };
49
+
50
+ export { useEffectAfterMount, useElementAttributes, useFileDragDrop, useFilePaste, useFormState };