@kirill.konshin/react 0.0.4 → 0.0.6

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/dist/apiCall.js CHANGED
@@ -1,23 +1,21 @@
1
- const jsonContentType = "application/json";
1
+ //#region src/apiCall.ts
2
+ var jsonContentType = "application/json";
2
3
  async function apiCall(url, init) {
3
- const useBodyAsIs = !init?.body || init?.body instanceof FormData || typeof init?.body === "string";
4
- const res = await fetch(url, {
5
- method: "POST",
6
- ...init,
7
- body: useBodyAsIs ? init?.body : JSON.stringify(init.body),
8
- headers: {
9
- ...init?.headers,
10
- ...useBodyAsIs ? {} : { "Content-Type": jsonContentType }
11
- }
12
- });
13
- if (res.headers.get("Content-Type")?.includes(jsonContentType)) {
14
- res.data = await res.json();
15
- }
16
- if (!res.ok) throw new Error(res.statusText, { cause: res });
17
- return res;
4
+ const useBodyAsIs = !init?.body || init?.body instanceof FormData || typeof init?.body === "string";
5
+ const res = await fetch(url, {
6
+ method: "POST",
7
+ ...init,
8
+ body: useBodyAsIs ? init?.body : JSON.stringify(init.body),
9
+ headers: {
10
+ ...init?.headers,
11
+ ...useBodyAsIs ? {} : { "Content-Type": jsonContentType }
12
+ }
13
+ });
14
+ if (res.headers.get("Content-Type")?.includes("application/json")) res.data = await res.json();
15
+ if (!res.ok) throw new Error(res.statusText, { cause: res });
16
+ return res;
18
17
  }
19
- export {
20
- apiCall,
21
- jsonContentType
22
- };
23
- //# sourceMappingURL=apiCall.js.map
18
+ //#endregion
19
+ export { apiCall, jsonContentType };
20
+
21
+ //# sourceMappingURL=apiCall.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"apiCall.js","sources":["../src/apiCall.ts"],"sourcesContent":["export const jsonContentType = 'application/json';\n\nexport type DataResponse<R> = Response & { data?: R };\n\nexport async function apiCall<R>(url: string, init?: RequestInit): Promise<DataResponse<R>> {\n const useBodyAsIs = !init?.body || init?.body instanceof FormData || typeof init?.body === 'string';\n\n const res: DataResponse<R> = await fetch(url, {\n method: 'POST',\n ...init,\n body: useBodyAsIs ? init?.body : JSON.stringify(init.body),\n headers: {\n ...init?.headers,\n ...(useBodyAsIs ? {} : { 'Content-Type': jsonContentType }),\n },\n });\n\n if (res.headers.get('Content-Type')?.includes(jsonContentType)) {\n res.data = await res.json();\n }\n\n if (!res.ok) throw new Error(res.statusText, { cause: res });\n\n return res;\n}\n"],"names":[],"mappings":"AAAO,MAAM,kBAAkB;AAI/B,eAAsB,QAAW,KAAa,MAA8C;AACxF,QAAM,cAAc,CAAC,MAAM,QAAQ,MAAM,gBAAgB,YAAY,OAAO,MAAM,SAAS;AAE3F,QAAM,MAAuB,MAAM,MAAM,KAAK;AAAA,IAC1C,QAAQ;AAAA,IACR,GAAG;AAAA,IACH,MAAM,cAAc,MAAM,OAAO,KAAK,UAAU,KAAK,IAAI;AAAA,IACzD,SAAS;AAAA,MACL,GAAG,MAAM;AAAA,MACT,GAAI,cAAc,CAAA,IAAK,EAAE,gBAAgB,gBAAA;AAAA,IAAgB;AAAA,EAC7D,CACH;AAED,MAAI,IAAI,QAAQ,IAAI,cAAc,GAAG,SAAS,eAAe,GAAG;AAC5D,QAAI,OAAO,MAAM,IAAI,KAAA;AAAA,EACzB;AAEA,MAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,IAAI,YAAY,EAAE,OAAO,KAAK;AAE3D,SAAO;AACX;"}
1
+ {"version":3,"file":"apiCall.js","names":[],"sources":["../src/apiCall.ts"],"sourcesContent":["export const jsonContentType = 'application/json';\n\nexport type DataResponse<R> = Response & { data?: R };\n\nexport async function apiCall<R>(url: string, init?: RequestInit): Promise<DataResponse<R>> {\n const useBodyAsIs = !init?.body || init?.body instanceof FormData || typeof init?.body === 'string';\n\n const res: DataResponse<R> = await fetch(url, {\n method: 'POST',\n ...init,\n body: useBodyAsIs ? init?.body : JSON.stringify(init.body),\n headers: {\n ...init?.headers,\n ...(useBodyAsIs ? {} : { 'Content-Type': jsonContentType }),\n },\n });\n\n if (res.headers.get('Content-Type')?.includes(jsonContentType)) {\n res.data = await res.json();\n }\n\n if (!res.ok) throw new Error(res.statusText, { cause: res });\n\n return res;\n}\n"],"mappings":";AAAA,IAAa,kBAAkB;AAI/B,eAAsB,QAAW,KAAa,MAA8C;CACxF,MAAM,cAAc,CAAC,MAAM,QAAQ,MAAM,gBAAgB,YAAY,OAAO,MAAM,SAAS;CAE3F,MAAM,MAAuB,MAAM,MAAM,KAAK;EAC1C,QAAQ;EACR,GAAG;EACH,MAAM,cAAc,MAAM,OAAO,KAAK,UAAU,KAAK,IAAI;EACzD,SAAS;GACL,GAAG,MAAM;GACT,GAAI,cAAc,CAAC,IAAI,EAAE,gBAAgB,gBAAgB;EAC7D;CACJ,CAAC;CAED,IAAI,IAAI,QAAQ,IAAI,cAAc,CAAC,EAAE,SAAA,kBAAwB,GACzD,IAAI,OAAO,MAAM,IAAI,KAAK;CAG9B,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,IAAI,YAAY,EAAE,OAAO,IAAI,CAAC;CAE3D,OAAO;AACX"}
@@ -1,4 +1,4 @@
1
- import { MaybeTypeOf, Validation } from './form';
1
+ import { MaybeTypeOf, Validation } from './form.js';
2
2
  import { z } from 'zod';
3
3
  export declare function createClient<S extends z.ZodObject<any>>(schema: S): {
4
4
  useValidation: (actionFn: (data: FormData) => Promise<Validation<S>>, initialData?: MaybeTypeOf<S>) => [state: Validation<S>, dispatch: (payload: FormData) => void, isPending: boolean];
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/form/client.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAU,WAAW,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,wBAAgB,YAAY,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,EACnD,MAAM,EAAE,CAAC,GACV;IACC,aAAa,EA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AAQ,EAAE,CAAC,IAAI,EAAE,QAAQ,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EACpD,WAAW,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,KAC3B,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;CACjF,CAqDA"}
@@ -1,46 +1,50 @@
1
1
  "use client";
2
- import { useTransition, useState, useCallback, useActionState } from "react";
3
2
  import { create } from "./form.js";
4
- const FORM_DEBUG = process.env.NEXT_PUBLIC_FORM_DEBUG === "true";
3
+ import { useActionState, useCallback, useState, useTransition } from "react";
4
+ //#region src/form/client.tsx
5
+ var FORM_DEBUG = process.env.NEXT_PUBLIC_FORM_DEBUG === "true";
5
6
  function createClient(schema) {
6
- const { validate } = create(schema);
7
- function useValidationCallback(actionFn) {
8
- return useCallback(
9
- async (formData) => {
10
- const clientRes = validate(formData);
11
- console.log("Client validation", FORM_DEBUG ? "ignored" : "active", clientRes);
12
- if (!clientRes.success && !FORM_DEBUG) return clientRes;
13
- const serverRes = await actionFn(formData);
14
- console.log("Server validation", serverRes);
15
- return serverRes;
16
- },
17
- [actionFn]
18
- );
19
- }
20
- function useValidation(actionFn, initialData = {}) {
21
- const cb = useValidationCallback(actionFn);
22
- return useActionState(async (_, data) => cb(data), {
23
- success: false,
24
- data: initialData
25
- });
26
- }
27
- function useValidationTransition(actionFn, initialData = {}) {
28
- const [isPending, startTransition] = useTransition();
29
- const [state, setState] = useState({ success: false, data: initialData });
30
- const cb = useValidationCallback(actionFn);
31
- const wrappedCb = useCallback(
32
- (formData) => {
33
- const promise = cb(formData);
34
- startTransition(() => promise.then(setState));
35
- return promise;
36
- },
37
- [cb, startTransition]
38
- );
39
- return [state, wrappedCb, isPending];
40
- }
41
- return { useValidation, useValidationTransition };
7
+ const { validate } = create(schema);
8
+ function useValidationCallback(actionFn) {
9
+ return useCallback(async (formData) => {
10
+ const clientRes = validate(formData);
11
+ console.log("Client validation", FORM_DEBUG ? "ignored" : "active", clientRes);
12
+ if (!clientRes.success && !FORM_DEBUG) return clientRes;
13
+ const serverRes = await actionFn(formData);
14
+ console.log("Server validation", serverRes);
15
+ return serverRes;
16
+ }, [actionFn]);
17
+ }
18
+ function useValidation(actionFn, initialData = {}) {
19
+ const cb = useValidationCallback(actionFn);
20
+ return useActionState(async (_, data) => cb(data), {
21
+ success: false,
22
+ data: initialData
23
+ });
24
+ }
25
+ function useValidationTransition(actionFn, initialData = {}) {
26
+ const [isPending, startTransition] = useTransition();
27
+ const [state, setState] = useState({
28
+ success: false,
29
+ data: initialData
30
+ });
31
+ const cb = useValidationCallback(actionFn);
32
+ return [
33
+ state,
34
+ useCallback((formData) => {
35
+ const promise = cb(formData);
36
+ startTransition(() => promise.then(setState));
37
+ return promise;
38
+ }, [cb, startTransition]),
39
+ isPending
40
+ ];
41
+ }
42
+ return {
43
+ useValidation,
44
+ useValidationTransition
45
+ };
42
46
  }
43
- export {
44
- createClient
45
- };
46
- //# sourceMappingURL=client.js.map
47
+ //#endregion
48
+ export { createClient };
49
+
50
+ //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../src/form/client.tsx"],"sourcesContent":["'use client';\n\nimport { useActionState, useCallback, useState, useTransition } from 'react';\nimport { create, MaybeTypeOf, Validation } from './form';\nimport { z } from 'zod';\n\nconst FORM_DEBUG = process.env.NEXT_PUBLIC_FORM_DEBUG === 'true';\n\nexport function createClient<S extends z.ZodObject<any>>(\n schema: S,\n): {\n useValidation: (\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData?: MaybeTypeOf<S>,\n ) => [state: Validation<S>, dispatch: (payload: FormData) => void, isPending: boolean];\n useValidationTransition: (\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData?: MaybeTypeOf<S>,\n ) => [Validation<S>, (formData: FormData) => Promise<Validation<S>>, boolean];\n} {\n const { validate } = create(schema);\n\n function useValidationCallback(\n actionFn: (data: FormData) => Promise<Validation<S>>,\n ): (formData: FormData) => Promise<Validation<S>> {\n return useCallback(\n async (formData: FormData) => {\n const clientRes = validate(formData);\n console.log('Client validation', FORM_DEBUG ? 'ignored' : 'active', clientRes);\n if (!clientRes.success && !FORM_DEBUG) return clientRes;\n\n const serverRes = await actionFn(formData);\n console.log('Server validation', serverRes);\n return serverRes;\n },\n [actionFn],\n );\n }\n\n function useValidation(\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData: MaybeTypeOf<S> = {} as MaybeTypeOf<S>,\n ): [state: Validation<S>, dispatch: (payload: FormData) => void, isPending: boolean] {\n const cb = useValidationCallback(actionFn);\n\n return useActionState<Validation<S>, FormData>(async (_, data) => cb(data), {\n success: false,\n data: initialData,\n });\n }\n\n function useValidationTransition(\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData: MaybeTypeOf<S> = {} as MaybeTypeOf<S>,\n ): [Validation<S>, (formData: FormData) => Promise<Validation<S>>, boolean] {\n const [isPending, startTransition] = useTransition();\n const [state, setState] = useState<Validation<S>>({ success: false, data: initialData });\n const cb = useValidationCallback(actionFn);\n\n const wrappedCb = useCallback(\n (formData: FormData) => {\n const promise = cb(formData);\n startTransition(() => promise.then(setState));\n return promise;\n },\n [cb, startTransition],\n );\n\n return [state, wrappedCb, isPending];\n }\n\n return { useValidation, useValidationTransition };\n}\n"],"names":[],"mappings":";;;AAMA,MAAM,aAAa,QAAQ,IAAI,2BAA2B;AAEnD,SAAS,aACZ,QAUF;AACE,QAAM,EAAE,SAAA,IAAa,OAAO,MAAM;AAElC,WAAS,sBACL,UAC8C;AAC9C,WAAO;AAAA,MACH,OAAO,aAAuB;AAC1B,cAAM,YAAY,SAAS,QAAQ;AACnC,gBAAQ,IAAI,qBAAqB,aAAa,YAAY,UAAU,SAAS;AAC7E,YAAI,CAAC,UAAU,WAAW,CAAC,WAAY,QAAO;AAE9C,cAAM,YAAY,MAAM,SAAS,QAAQ;AACzC,gBAAQ,IAAI,qBAAqB,SAAS;AAC1C,eAAO;AAAA,MACX;AAAA,MACA,CAAC,QAAQ;AAAA,IAAA;AAAA,EAEjB;AAEA,WAAS,cACL,UACA,cAA8B,IACmD;AACjF,UAAM,KAAK,sBAAsB,QAAQ;AAEzC,WAAO,eAAwC,OAAO,GAAG,SAAS,GAAG,IAAI,GAAG;AAAA,MACxE,SAAS;AAAA,MACT,MAAM;AAAA,IAAA,CACT;AAAA,EACL;AAEA,WAAS,wBACL,UACA,cAA8B,IAC0C;AACxE,UAAM,CAAC,WAAW,eAAe,IAAI,cAAA;AACrC,UAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,EAAE,SAAS,OAAO,MAAM,aAAa;AACvF,UAAM,KAAK,sBAAsB,QAAQ;AAEzC,UAAM,YAAY;AAAA,MACd,CAAC,aAAuB;AACpB,cAAM,UAAU,GAAG,QAAQ;AAC3B,wBAAgB,MAAM,QAAQ,KAAK,QAAQ,CAAC;AAC5C,eAAO;AAAA,MACX;AAAA,MACA,CAAC,IAAI,eAAe;AAAA,IAAA;AAGxB,WAAO,CAAC,OAAO,WAAW,SAAS;AAAA,EACvC;AAEA,SAAO,EAAE,eAAe,wBAAA;AAC5B;"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/form/client.tsx"],"sourcesContent":["'use client';\n\nimport { useActionState, useCallback, useState, useTransition } from 'react';\nimport { create, type MaybeTypeOf, type Validation } from './form';\nimport { type z } from 'zod';\n\nconst FORM_DEBUG = process.env.NEXT_PUBLIC_FORM_DEBUG === 'true';\n\nexport function createClient<S extends z.ZodObject<any>>(\n schema: S,\n): {\n useValidation: (\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData?: MaybeTypeOf<S>,\n ) => [state: Validation<S>, dispatch: (payload: FormData) => void, isPending: boolean];\n useValidationTransition: (\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData?: MaybeTypeOf<S>,\n ) => [Validation<S>, (formData: FormData) => Promise<Validation<S>>, boolean];\n} {\n const { validate } = create(schema);\n\n function useValidationCallback(\n actionFn: (data: FormData) => Promise<Validation<S>>,\n ): (formData: FormData) => Promise<Validation<S>> {\n return useCallback(\n async (formData: FormData) => {\n const clientRes = validate(formData);\n console.log('Client validation', FORM_DEBUG ? 'ignored' : 'active', clientRes);\n if (!clientRes.success && !FORM_DEBUG) return clientRes;\n\n const serverRes = await actionFn(formData);\n console.log('Server validation', serverRes);\n return serverRes;\n },\n [actionFn],\n );\n }\n\n function useValidation(\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData: MaybeTypeOf<S> = {} as MaybeTypeOf<S>,\n ): [state: Validation<S>, dispatch: (payload: FormData) => void, isPending: boolean] {\n const cb = useValidationCallback(actionFn);\n\n return useActionState<Validation<S>, FormData>(async (_, data) => cb(data), {\n success: false,\n data: initialData,\n });\n }\n\n function useValidationTransition(\n actionFn: (data: FormData) => Promise<Validation<S>>,\n initialData: MaybeTypeOf<S> = {} as MaybeTypeOf<S>,\n ): [Validation<S>, (formData: FormData) => Promise<Validation<S>>, boolean] {\n const [isPending, startTransition] = useTransition();\n const [state, setState] = useState<Validation<S>>({ success: false, data: initialData });\n const cb = useValidationCallback(actionFn);\n\n const wrappedCb = useCallback(\n (formData: FormData) => {\n const promise = cb(formData);\n startTransition(() => promise.then(setState));\n return promise;\n },\n [cb, startTransition],\n );\n\n return [state, wrappedCb, isPending];\n }\n\n return { useValidation, useValidationTransition };\n}\n"],"mappings":";;;;AAMA,IAAM,aAAa,QAAQ,IAAI,2BAA2B;AAE1D,SAAgB,aACZ,QAUF;CACE,MAAM,EAAE,aAAa,OAAO,MAAM;CAElC,SAAS,sBACL,UAC8C;EAC9C,OAAO,YACH,OAAO,aAAuB;GAC1B,MAAM,YAAY,SAAS,QAAQ;GACnC,QAAQ,IAAI,qBAAqB,aAAa,YAAY,UAAU,SAAS;GAC7E,IAAI,CAAC,UAAU,WAAW,CAAC,YAAY,OAAO;GAE9C,MAAM,YAAY,MAAM,SAAS,QAAQ;GACzC,QAAQ,IAAI,qBAAqB,SAAS;GAC1C,OAAO;EACX,GACA,CAAC,QAAQ,CACb;CACJ;CAEA,SAAS,cACL,UACA,cAA8B,CAAC,GACkD;EACjF,MAAM,KAAK,sBAAsB,QAAQ;EAEzC,OAAO,eAAwC,OAAO,GAAG,SAAS,GAAG,IAAI,GAAG;GACxE,SAAS;GACT,MAAM;EACV,CAAC;CACL;CAEA,SAAS,wBACL,UACA,cAA8B,CAAC,GACyC;EACxE,MAAM,CAAC,WAAW,mBAAmB,cAAc;EACnD,MAAM,CAAC,OAAO,YAAY,SAAwB;GAAE,SAAS;GAAO,MAAM;EAAY,CAAC;EACvF,MAAM,KAAK,sBAAsB,QAAQ;EAWzC,OAAO;GAAC;GATU,aACb,aAAuB;IACpB,MAAM,UAAU,GAAG,QAAQ;IAC3B,sBAAsB,QAAQ,KAAK,QAAQ,CAAC;IAC5C,OAAO;GACX,GACA,CAAC,IAAI,eAAe,CAGT;GAAW;EAAS;CACvC;CAEA,OAAO;EAAE;EAAe;CAAwB;AACpD"}
@@ -20,10 +20,10 @@ export type Validation<S extends ZodObject> = {
20
20
  export declare const FormContext: Context<{
21
21
  schema: ZodObject;
22
22
  }>;
23
- export interface FormProps<S extends ZodObject> {
23
+ export type FormProps<S extends ZodObject> = {
24
24
  schema: S;
25
25
  children: any;
26
- }
26
+ };
27
27
  export declare const Form: FC<FormProps<any>>;
28
28
  export declare function create<S extends ZodObject>(schema: S): {
29
29
  register: (name: keyof z.output<S>, data?: MaybeTypeOf<S>, errors?: Errors<S>, mui?: boolean) => {
@@ -40,7 +40,7 @@ export declare function create<S extends ZodObject>(schema: S): {
40
40
  validate: (formData: FormData) => Validation<S>;
41
41
  validationError: (data: MaybeTypeOf<S>, errors: Errors<S>) => Validation<S>;
42
42
  };
43
- interface FieldProps<S extends ZodObject> {
43
+ type FieldProps<S extends ZodObject> = {
44
44
  children?: any;
45
45
  name: keyof z.output<S>;
46
46
  errors?: Validation<S>['errors'];
@@ -48,12 +48,12 @@ interface FieldProps<S extends ZodObject> {
48
48
  className?: string;
49
49
  labelProps?: any;
50
50
  [key: string]: any;
51
- }
51
+ };
52
52
  export declare const Field: FC<FieldProps<any>>;
53
- export interface HintProps {
53
+ export type HintProps = {
54
54
  children: any;
55
55
  error?: boolean;
56
- }
56
+ };
57
57
  export declare const Hint: FC<HintProps>;
58
58
  export {};
59
59
  //# sourceMappingURL=form.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../../src/form/form.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAA2C,EAAE,EAAQ,MAAM,OAAO,CAAC;AAKnF,eAAO,MAAM,cAAc,QAAO,CAAC,CAAC,SAAsE,CAAC;AAC3G,eAAO,MAAM,SAAS,GAAI,QAAQ,CAAC,CAAC,SAAS,KAAG,MAA+B,CAAC;AAChF,eAAO,MAAM,SAAS,GAAI,QAAQ,CAAC,CAAC,SAAS,KAAG,MAA+B,CAAC;AAChF,eAAO,MAAM,UAAU,GAAI,QAAQ,CAAC,CAAC,SAAS,KAAG,OAAgC,CAAC;AAElF,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC/D,MAAM,MAAM,WAAW,CAAC,CAAC,SAAS,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AACpE,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,SAAS,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC/F,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,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,MAAM,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,CAAC;CAC/E,CAiEA;AAED,KAAK,UAAU,CAAC,CAAC,SAAS,SAAS,IAAI;IACnC,QAAQ,CAAC,EAAE,GAAG,CAAC;IACf,IAAI,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACxB,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,GAAG,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CA4BpC,CAAC;AAEH,MAAM,MAAM,SAAS,GAAG;IACpB,QAAQ,EAAE,GAAG,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,eAAO,MAAM,IAAI,EAAE,EAAE,CAAC,SAAS,CAE7B,CAAC"}
package/dist/form/form.js CHANGED
@@ -1,87 +1,90 @@
1
+ import { createContext, memo, useContext, useMemo } from "react";
1
2
  import { jsx, jsxs } from "react/jsx-runtime";
2
3
  import { z } from "zod";
3
- import { createContext, memo, useMemo, useContext } from "react";
4
4
  import clsx from "clsx";
5
- const nonEmpty = "This field cannot be empty";
6
- const stringRequired = () => z.string({ error: nonEmpty }).min(1, { error: nonEmpty });
7
- const maxLength = (schema) => schema.maxLength || 0;
8
- const minLength = (schema) => schema.minLength || 0;
9
- const isRequired = (schema) => minLength(schema) > 0;
10
- const FormContext = createContext(null);
11
- const Form = memo(function Form2({ schema, children }) {
12
- const value = useMemo(() => ({ schema }), [schema]);
13
- return /* @__PURE__ */ jsx(FormContext.Provider, { value, children });
5
+ //#region src/form/form.tsx
6
+ var nonEmpty = "This field cannot be empty";
7
+ var stringRequired = () => z.string({ error: nonEmpty }).min(1, { error: nonEmpty });
8
+ var maxLength = (schema) => schema.maxLength || 0;
9
+ var minLength = (schema) => schema.minLength || 0;
10
+ var isRequired = (schema) => minLength(schema) > 0;
11
+ var FormContext = createContext(null);
12
+ var Form = memo(function Form({ schema, children }) {
13
+ const value = useMemo(() => ({ schema }), [schema]);
14
+ return /* @__PURE__ */ jsx(FormContext.Provider, {
15
+ value,
16
+ children
17
+ });
14
18
  });
15
- const getShape = (schema) => schema.shape || schema.in.shape;
19
+ var getShape = (schema) => schema.shape || schema.in.shape;
16
20
  function create(schema) {
17
- if (!getShape(schema)) {
18
- throw new Error("Invalid schema: only z.object() or z.object().refine() are supported");
19
- }
20
- function register(name, data, errors, mui = false) {
21
- const field = getShape(schema)[name];
22
- return {
23
- name,
24
- id: name,
25
- required: isRequired(field),
26
- maxLength: maxLength(field),
27
- type: field.isEmail ? "email" : name.includes("password") ? "password" : "text",
28
- defaultValue: data?.[name],
29
- ...mui ? {
30
- label: field.description,
31
- helperText: errors?.[name]?.join(", "),
32
- error: !!errors?.[name]?.length
33
- } : {}
34
- };
35
- }
36
- function validationError(data, errors) {
37
- return {
38
- success: false,
39
- data,
40
- // data is undefined if there are errors
41
- errors
42
- // Next.js will butcher error object, so we provide something more primitive
43
- };
44
- }
45
- function validate(formData) {
46
- const rawData = Object.fromEntries(formData);
47
- const result = schema.safeParse(rawData);
48
- if (!result.success) {
49
- return validationError(rawData, z.flattenError(result.error).fieldErrors);
50
- }
51
- return { success: true, data: result.data };
52
- }
53
- return { register, validate, validationError };
21
+ if (!getShape(schema)) throw new Error("Invalid schema: only z.object() or z.object().refine() are supported");
22
+ function register(name, data, errors, mui = false) {
23
+ const field = getShape(schema)[name];
24
+ return {
25
+ name,
26
+ id: name,
27
+ required: isRequired(field),
28
+ maxLength: maxLength(field),
29
+ type: field.isEmail ? "email" : name.includes("password") ? "password" : "text",
30
+ defaultValue: data?.[name],
31
+ ...mui ? {
32
+ label: field.description,
33
+ helperText: errors?.[name]?.join(", "),
34
+ error: !!errors?.[name]?.length
35
+ } : {}
36
+ };
37
+ }
38
+ function validationError(data, errors) {
39
+ return {
40
+ success: false,
41
+ data,
42
+ errors
43
+ };
44
+ }
45
+ function validate(formData) {
46
+ const rawData = Object.fromEntries(formData);
47
+ const result = schema.safeParse(rawData);
48
+ if (!result.success) return validationError(rawData, z.flattenError(result.error).fieldErrors);
49
+ return {
50
+ success: true,
51
+ data: result.data
52
+ };
53
+ }
54
+ return {
55
+ register,
56
+ validate,
57
+ validationError
58
+ };
54
59
  }
55
- const Field = memo(function Field2({
56
- children,
57
- name,
58
- errors,
59
- hint,
60
- className,
61
- labelProps,
62
- ...props
63
- }) {
64
- const { schema } = useContext(FormContext);
65
- const { description } = getShape(schema)[name];
66
- return /* @__PURE__ */ jsxs("div", { ...props, className: clsx("form-row", className), children: [
67
- description && /* @__PURE__ */ jsx("label", { ...labelProps, htmlFor: name, children: description }),
68
- children,
69
- hint && /* @__PURE__ */ jsx(Hint, { children: hint }),
70
- errors?.[name]?.map((e) => /* @__PURE__ */ jsx(Hint, { error: true, children: e }, e))
71
- ] });
60
+ var Field = memo(function Field({ children, name, errors, hint, className, labelProps, ...props }) {
61
+ const { schema } = useContext(FormContext);
62
+ const { description } = getShape(schema)[name];
63
+ return /* @__PURE__ */ jsxs("div", {
64
+ ...props,
65
+ className: clsx("form-row", className),
66
+ children: [
67
+ description && /* @__PURE__ */ jsx("label", {
68
+ ...labelProps,
69
+ htmlFor: name,
70
+ children: description
71
+ }),
72
+ children,
73
+ hint && /* @__PURE__ */ jsx(Hint, { children: hint }),
74
+ errors?.[name]?.map((e) => /* @__PURE__ */ jsx(Hint, {
75
+ error: true,
76
+ children: e
77
+ }, e))
78
+ ]
79
+ });
72
80
  });
73
- const Hint = memo(function Hint2({ children, error }) {
74
- return /* @__PURE__ */ jsx("div", { className: `hint ${error ? "hint-error" : ""}`, children });
81
+ var Hint = memo(function Hint({ children, error }) {
82
+ return /* @__PURE__ */ jsx("div", {
83
+ className: `hint ${error ? "hint-error" : ""}`,
84
+ children
85
+ });
75
86
  });
76
- export {
77
- Field,
78
- Form,
79
- FormContext,
80
- Hint,
81
- create,
82
- isRequired,
83
- maxLength,
84
- minLength,
85
- stringRequired
86
- };
87
- //# sourceMappingURL=form.js.map
87
+ //#endregion
88
+ export { Field, Form, FormContext, Hint, create, isRequired, maxLength, minLength, stringRequired };
89
+
90
+ //# sourceMappingURL=form.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"form.js","sources":["../../src/form/form.tsx"],"sourcesContent":["import { z } from 'zod';\nimport { Context, createContext, useContext, useMemo, JSX, FC, memo } from 'react';\nimport clsx from 'clsx';\n\nconst nonEmpty = 'This field cannot be empty';\n\nexport const stringRequired = (): z.ZodString => z.string({ error: nonEmpty }).min(1, { error: nonEmpty });\nexport const maxLength = (schema: z.ZodString): number => schema.maxLength || 0;\nexport const minLength = (schema: z.ZodString): number => schema.minLength || 0;\nexport const isRequired = (schema: z.ZodString): boolean => minLength(schema) > 0;\n\nexport type ZodObject = z.ZodObject<any> | z.ZodPipe<any, any>; // z.ZodType<any, any, any>\nexport type MaybeTypeOf<S extends ZodObject> = Partial<z.output<S>>;\nexport type SafeTypeOf<S extends ZodObject> = z.core.util.SafeParseResult<z.output<S>>['data'];\nexport type Errors<S extends ZodObject> = z.core.$ZodFlattenedError<z.output<S>>['fieldErrors'];\nexport type Validation<S extends ZodObject> =\n | {\n success: true; // this is true only if form was validated successfully\n data: SafeTypeOf<S>;\n errors?: never;\n }\n | {\n success: false;\n data?: MaybeTypeOf<S>;\n errors?: Errors<S>;\n };\n\nexport const FormContext: Context<{\n schema: ZodObject;\n}> = createContext(null as never);\n\nexport interface FormProps<S extends ZodObject> {\n schema: S;\n children: any;\n}\n\nexport const Form: FC<FormProps<any>> = memo(function Form({ schema, children }) {\n const value = useMemo(() => ({ schema }), [schema]);\n return <FormContext.Provider value={value}>{children}</FormContext.Provider>;\n});\n\nconst getShape = <S extends ZodObject>(schema: S) =>\n (schema as z.ZodObject<any>).shape || (schema as z.ZodPipe<any, any>).in.shape;\n\nexport function create<S extends ZodObject>(\n schema: S,\n): {\n register: (\n name: keyof z.output<S>,\n data?: MaybeTypeOf<S>,\n errors?: Errors<S>,\n mui?: boolean,\n ) => {\n label?: any;\n helperText?: string;\n error?: boolean;\n name: keyof z.output<S>;\n id: keyof z.output<S>;\n required: boolean;\n maxLength: number;\n type: string;\n defaultValue?: Partial<z.output<S>>[keyof z.output<S>];\n };\n validate: (formData: FormData) => Validation<S>;\n validationError: (data: MaybeTypeOf<S>, errors: Errors<S>) => Validation<S>;\n} {\n if (!getShape(schema)) {\n throw new Error('Invalid schema: only z.object() or z.object().refine() are supported');\n }\n\n function register(\n name: keyof z.output<S>,\n data?: MaybeTypeOf<S>,\n errors?: Errors<S>,\n mui: boolean = false,\n ): {\n label?: any;\n helperText?: string;\n error?: boolean;\n name: keyof z.output<S>;\n id: keyof z.output<S>;\n required: boolean;\n maxLength: number;\n type: string;\n defaultValue?: Partial<z.output<S>>[keyof z.output<S>];\n } {\n const field = getShape(schema)[name];\n return {\n name,\n id: name,\n required: isRequired(field),\n maxLength: maxLength(field),\n type: field.isEmail ? 'email' : (name as string).includes('password') ? 'password' : 'text',\n defaultValue: data?.[name],\n ...(mui\n ? {\n label: field.description,\n helperText: errors?.[name]?.join(', '),\n error: !!errors?.[name]?.length,\n }\n : {}),\n };\n }\n\n function validationError(data: MaybeTypeOf<S>, errors: Errors<S>): Validation<S> {\n return {\n success: false,\n data, // data is undefined if there are errors\n errors, // Next.js will butcher error object, so we provide something more primitive\n };\n }\n\n function validate(formData: FormData): Validation<S> {\n const rawData = Object.fromEntries(formData) as z.output<S>;\n const result = schema.safeParse(rawData);\n\n // console.log('Validate result', { error, data, rawData });\n\n if (!result.success) {\n // data is undefined if there are errors\n // Next.js will butcher error object, so we provide something more primitive\n return validationError(rawData, z.flattenError(result.error).fieldErrors as any);\n }\n\n return { success: true, data: result.data };\n }\n\n return { register, validate, validationError };\n}\n\ninterface FieldProps<S extends ZodObject> {\n children?: any;\n name: keyof z.output<S>;\n errors?: Validation<S>['errors'];\n hint?: string;\n className?: string;\n labelProps?: any;\n [key: string]: any;\n}\n\nexport const Field: FC<FieldProps<any>> = memo(function Field({\n children,\n name,\n errors,\n hint,\n className,\n labelProps,\n ...props\n}) {\n const { schema } = useContext(FormContext);\n const { description } = getShape(schema)[name];\n\n return (\n <div {...props} className={clsx('form-row', className)}>\n {description && (\n <label {...labelProps} htmlFor={name}>\n {description}\n </label>\n )}\n {children}\n {hint && <Hint>{hint}</Hint>}\n {errors?.[name as any]?.map((e: string) => (\n <Hint error key={e}>\n {e}\n </Hint>\n ))}\n </div>\n );\n});\n\nexport interface HintProps {\n children: any;\n error?: boolean;\n}\n\nexport const Hint: FC<HintProps> = memo(function Hint({ children, error }) {\n return <div className={`hint ${error ? 'hint-error' : ''}`}>{children}</div>;\n});\n"],"names":["Form","Field","Hint"],"mappings":";;;;AAIA,MAAM,WAAW;AAEV,MAAM,iBAAiB,MAAmB,EAAE,OAAO,EAAE,OAAO,UAAU,EAAE,IAAI,GAAG,EAAE,OAAO,UAAU;AAClG,MAAM,YAAY,CAAC,WAAgC,OAAO,aAAa;AACvE,MAAM,YAAY,CAAC,WAAgC,OAAO,aAAa;AACvE,MAAM,aAAa,CAAC,WAAiC,UAAU,MAAM,IAAI;AAkBzE,MAAM,cAER,cAAc,IAAa;AAOzB,MAAM,OAA2B,KAAK,SAASA,MAAK,EAAE,QAAQ,YAAY;AAC7E,QAAM,QAAQ,QAAQ,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC;AAClD,SAAO,oBAAC,YAAY,UAAZ,EAAqB,OAAe,SAAA,CAAS;AACzD,CAAC;AAED,MAAM,WAAW,CAAsB,WAClC,OAA4B,SAAU,OAA+B,GAAG;AAEtE,SAAS,OACZ,QAoBF;AACE,MAAI,CAAC,SAAS,MAAM,GAAG;AACnB,UAAM,IAAI,MAAM,sEAAsE;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AAA,mCACI,SAAA,EAAO,GAAG,YAAY,SAAS,MAC3B,UAAA,aACL;AAAA,IAEH;AAAA,IACA,QAAQ,oBAAC,MAAA,EAAM,UAAA,KAAA,CAAK;AAAA,IACpB,SAAS,IAAW,GAAG,IAAI,CAAC,MACzB,oBAAC,MAAA,EAAK,OAAK,MACN,UAAA,EAAA,GADY,CAEjB,CACH;AAAA,EAAA,GACL;AAER,CAAC;AAOM,MAAM,OAAsB,KAAK,SAASC,MAAK,EAAE,UAAU,SAAS;AACvE,SAAO,oBAAC,SAAI,WAAW,QAAQ,QAAQ,eAAe,EAAE,IAAK,SAAA,CAAS;AAC1E,CAAC;"}
1
+ {"version":3,"file":"form.js","names":[],"sources":["../../src/form/form.tsx"],"sourcesContent":["import { z } from 'zod';\nimport { type Context, createContext, useContext, useMemo, type FC, memo } from 'react';\nimport clsx from 'clsx';\n\nconst nonEmpty = 'This field cannot be empty';\n\nexport const stringRequired = (): z.ZodString => z.string({ error: nonEmpty }).min(1, { error: nonEmpty });\nexport const maxLength = (schema: z.ZodString): number => schema.maxLength || 0;\nexport const minLength = (schema: z.ZodString): number => schema.minLength || 0;\nexport const isRequired = (schema: z.ZodString): boolean => minLength(schema) > 0;\n\nexport type ZodObject = z.ZodObject<any> | z.ZodPipe<any, any>; // z.ZodType<any, any, any>\nexport type MaybeTypeOf<S extends ZodObject> = Partial<z.output<S>>;\nexport type SafeTypeOf<S extends ZodObject> = z.core.util.SafeParseResult<z.output<S>>['data'];\nexport type Errors<S extends ZodObject> = z.core.$ZodFlattenedError<z.output<S>>['fieldErrors'];\nexport type Validation<S extends ZodObject> =\n | {\n success: true; // this is true only if form was validated successfully\n data: SafeTypeOf<S>;\n errors?: never;\n }\n | {\n success: false;\n data?: MaybeTypeOf<S>;\n errors?: Errors<S>;\n };\n\nexport const FormContext: Context<{\n schema: ZodObject;\n}> = createContext(null as never);\n\nexport type FormProps<S extends ZodObject> = {\n schema: S;\n children: any;\n};\n\nexport const Form: FC<FormProps<any>> = memo(function Form({ schema, children }) {\n const value = useMemo(() => ({ schema }), [schema]);\n return <FormContext.Provider value={value}>{children}</FormContext.Provider>;\n});\n\nconst getShape = <S extends ZodObject>(schema: S) =>\n (schema as z.ZodObject<any>).shape || (schema as z.ZodPipe<any, any>).in.shape;\n\nexport function create<S extends ZodObject>(\n schema: S,\n): {\n register: (\n name: keyof z.output<S>,\n data?: MaybeTypeOf<S>,\n errors?: Errors<S>,\n mui?: boolean,\n ) => {\n label?: any;\n helperText?: string;\n error?: boolean;\n name: keyof z.output<S>;\n id: keyof z.output<S>;\n required: boolean;\n maxLength: number;\n type: string;\n defaultValue?: Partial<z.output<S>>[keyof z.output<S>];\n };\n validate: (formData: FormData) => Validation<S>;\n validationError: (data: MaybeTypeOf<S>, errors: Errors<S>) => Validation<S>;\n} {\n if (!getShape(schema)) {\n throw new Error('Invalid schema: only z.object() or z.object().refine() are supported');\n }\n\n function register(\n name: keyof z.output<S>,\n data?: MaybeTypeOf<S>,\n errors?: Errors<S>,\n mui: boolean = false,\n ): {\n label?: any;\n helperText?: string;\n error?: boolean;\n name: keyof z.output<S>;\n id: keyof z.output<S>;\n required: boolean;\n maxLength: number;\n type: string;\n defaultValue?: Partial<z.output<S>>[keyof z.output<S>];\n } {\n const field = getShape(schema)[name];\n return {\n name,\n id: name,\n required: isRequired(field),\n maxLength: maxLength(field),\n type: field.isEmail ? 'email' : (name as string).includes('password') ? 'password' : 'text',\n defaultValue: data?.[name],\n ...(mui\n ? {\n label: field.description,\n helperText: errors?.[name]?.join(', '),\n error: !!errors?.[name]?.length,\n }\n : {}),\n };\n }\n\n function validationError(data: MaybeTypeOf<S>, errors: Errors<S>): Validation<S> {\n return {\n success: false,\n data, // data is undefined if there are errors\n errors, // Next.js will butcher error object, so we provide something more primitive\n };\n }\n\n function validate(formData: FormData): Validation<S> {\n const rawData = Object.fromEntries(formData) as z.output<S>;\n const result = schema.safeParse(rawData);\n\n // console.log('Validate result', { error, data, rawData });\n\n if (!result.success) {\n /*\n * data is undefined if there are errors\n * Next.js will butcher error object, so we provide something more primitive\n */\n return validationError(rawData, z.flattenError(result.error).fieldErrors as any);\n }\n\n return { success: true, data: result.data };\n }\n\n return { register, validate, validationError };\n}\n\ntype FieldProps<S extends ZodObject> = {\n children?: any;\n name: keyof z.output<S>;\n errors?: Validation<S>['errors'];\n hint?: string;\n className?: string;\n labelProps?: any;\n [key: string]: any;\n};\n\nexport const Field: FC<FieldProps<any>> = memo(function Field({\n children,\n name,\n errors,\n hint,\n className,\n labelProps,\n ...props\n}) {\n const { schema } = useContext(FormContext);\n const { description } = getShape(schema)[name];\n\n return (\n <div {...props} className={clsx('form-row', className)}>\n {description && (\n <label {...labelProps} htmlFor={name}>\n {description}\n </label>\n )}\n {children}\n {hint && <Hint>{hint}</Hint>}\n {errors?.[name as any]?.map((e: string) => (\n <Hint error key={e}>\n {e}\n </Hint>\n ))}\n </div>\n );\n});\n\nexport type HintProps = {\n children: any;\n error?: boolean;\n};\n\nexport const Hint: FC<HintProps> = memo(function Hint({ children, error }) {\n return <div className={`hint ${error ? 'hint-error' : ''}`}>{children}</div>;\n});\n"],"mappings":";;;;;AAIA,IAAM,WAAW;AAEjB,IAAa,uBAAoC,EAAE,OAAO,EAAE,OAAO,SAAS,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,OAAO,SAAS,CAAC;AACzG,IAAa,aAAa,WAAgC,OAAO,aAAa;AAC9E,IAAa,aAAa,WAAgC,OAAO,aAAa;AAC9E,IAAa,cAAc,WAAiC,UAAU,MAAM,IAAI;AAkBhF,IAAa,cAER,cAAc,IAAa;AAOhC,IAAa,OAA2B,KAAK,SAAS,KAAK,EAAE,QAAQ,YAAY;CAC7E,MAAM,QAAQ,eAAe,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC;CAClD,OAAO,oBAAC,YAAY,UAAb;EAA6B;EAAQ;CAA+B,CAAA;AAC/E,CAAC;AAED,IAAM,YAAiC,WAClC,OAA4B,SAAU,OAA+B,GAAG;AAE7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AY,EAAE,KAAK,MACzB,oBAAC,MAAD;IAAM,OAAA;cACD;GACC,GAFW,CAEX,CACT;EACA;;AAEb,CAAC;AAOD,IAAa,OAAsB,KAAK,SAAS,KAAK,EAAE,UAAU,SAAS;CACvE,OAAO,oBAAC,OAAD;EAAK,WAAW,QAAQ,QAAQ,eAAe;EAAO;CAAc,CAAA;AAC/E,CAAC"}
@@ -1,3 +1,3 @@
1
- export * from './client';
2
- export * from './form';
1
+ export * from './client.js';
2
+ export * from './form.js';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ import { Field, Form, FormContext, Hint, create, isRequired, maxLength, minLength, stringRequired } from "./form.js";
2
+ import { createClient } from "./client.js";
3
+ export { Field, Form, FormContext, Hint, create, createClient, isRequired, maxLength, minLength, stringRequired };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export * from './apiCall';
2
- export * from './keyboard';
3
- export * from './useFetch';
4
- export * from './useFetcher';
5
- export * from './form';
1
+ export * from './apiCall.js';
2
+ export * from './keyboard.js';
3
+ export * from './useFetch.js';
4
+ export * from './useFetchAction.js';
5
+ export * from './form/index.js';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,QAAQ,CAAC"}
package/dist/index.js CHANGED
@@ -2,25 +2,7 @@ import { apiCall, jsonContentType } from "./apiCall.js";
2
2
  import { HotkeysContext, HotkeysProvider, useHotkeys } from "./keyboard.js";
3
3
  import { useFetch } from "./useFetch.js";
4
4
  import { useFetchAction } from "./useFetchAction.js";
5
- import { createClient } from "./form/client.js";
6
5
  import { Field, Form, FormContext, Hint, create, isRequired, maxLength, minLength, stringRequired } from "./form/form.js";
7
- export {
8
- Field,
9
- Form,
10
- FormContext,
11
- Hint,
12
- HotkeysContext,
13
- HotkeysProvider,
14
- apiCall,
15
- create,
16
- createClient,
17
- isRequired,
18
- jsonContentType,
19
- maxLength,
20
- minLength,
21
- stringRequired,
22
- useFetch,
23
- useFetchAction,
24
- useHotkeys
25
- };
26
- //# sourceMappingURL=index.js.map
6
+ import { createClient } from "./form/client.js";
7
+ import "./form/index.js";
8
+ export { Field, Form, FormContext, Hint, HotkeysContext, HotkeysProvider, apiCall, create, createClient, isRequired, jsonContentType, maxLength, minLength, stringRequired, useFetch, useFetchAction, useHotkeys };
@@ -1 +1 @@
1
- {"version":3,"file":"keyboard.d.ts","sourceRoot":"","sources":["../src/keyboard.tsx"],"names":[],"mappings":"AAEA,OAAO,EAKH,QAAQ,EACR,cAAc,EAEd,EAAE,EAEF,OAAO,EACV,MAAM,OAAO,CAAC;AAMf,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,aAAa,KAAK,IAAI,CAAC,CAAC;AAEhF,MAAM,MAAM,iBAAiB,GAAG;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;CACjD,CAAC;AAEF,eAAO,MAAM,cAAc,EAAE,OAAO,CAAC,iBAAiB,CAGrC,CAAC;AAElB,MAAM,MAAM,oBAAoB,GAAG;IAC/B,QAAQ,EAAE,GAAG,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,eAAe,EAAE,EAAE,CAAC,oBAAoB,CAMnD,CAAC;AAEH,eAAO,MAAM,UAAU,GAAI,SAAS,OAAO,KAAG,IA6B7C,CAAC"}
1
+ {"version":3,"file":"keyboard.d.ts","sourceRoot":"","sources":["../src/keyboard.tsx"],"names":[],"mappings":"AAEA,OAAO,EAKH,KAAK,QAAQ,EACb,KAAK,cAAc,EAEnB,KAAK,EAAE,EAEP,KAAK,OAAO,EACf,MAAM,OAAO,CAAC;AAMf,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,aAAa,KAAK,IAAI,CAAC,CAAC;AAEhF,MAAM,MAAM,iBAAiB,GAAG;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;CACjD,CAAC;AAEF,eAAO,MAAM,cAAc,EAAE,OAAO,CAAC,iBAAiB,CAGrC,CAAC;AAElB,MAAM,MAAM,oBAAoB,GAAG;IAC/B,QAAQ,EAAE,GAAG,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,eAAe,EAAE,EAAE,CAAC,oBAAoB,CAMnD,CAAC;AAEH,eAAO,MAAM,UAAU,GAAI,SAAS,OAAO,KAAG,IA6B7C,CAAC"}
package/dist/keyboard.js CHANGED
@@ -1,42 +1,42 @@
1
1
  "use client";
2
+ import { createContext, memo, useContext, useEffect, useMemo, useState } from "react";
2
3
  import { jsx } from "react/jsx-runtime";
3
- import { createContext, memo, useState, useMemo, useContext, useEffect } from "react";
4
- const isCtrlOrMeta = (e) => e.metaKey || e.ctrlKey;
5
- const EVENT = "keydown";
6
- const HotkeysContext = createContext(null);
7
- const HotkeysProvider = memo(function HotkeysProvider2({ children }) {
8
- const [enabled, setEnabled] = useState(true);
9
- const control = useMemo(() => ({ enabled, setEnabled }), [enabled, setEnabled]);
10
- return /* @__PURE__ */ jsx(HotkeysContext.Provider, { value: control, children });
4
+ //#region src/keyboard.tsx
5
+ var isCtrlOrMeta = (e) => e.metaKey || e.ctrlKey;
6
+ var EVENT = "keydown";
7
+ var HotkeysContext = createContext(null);
8
+ var HotkeysProvider = memo(function HotkeysProvider({ children }) {
9
+ const [enabled, setEnabled] = useState(true);
10
+ const control = useMemo(() => ({
11
+ enabled,
12
+ setEnabled
13
+ }), [enabled, setEnabled]);
14
+ return /* @__PURE__ */ jsx(HotkeysContext.Provider, {
15
+ value: control,
16
+ children
17
+ });
11
18
  });
12
- const useHotkeys = (hotkeys) => {
13
- const { enabled } = useContext(HotkeysContext);
14
- useEffect(() => {
15
- if (typeof document === "undefined" || !enabled) {
16
- return;
17
- }
18
- const ctrl = new AbortController();
19
- window.addEventListener(
20
- EVENT,
21
- (e) => {
22
- if (!isCtrlOrMeta(e)) return;
23
- for (const [code, callback] of Object.entries(hotkeys)) {
24
- if (e.code === code) {
25
- callback(e);
26
- return;
27
- }
28
- }
29
- },
30
- { signal: ctrl.signal, capture: true }
31
- );
32
- return () => {
33
- ctrl.abort();
34
- };
35
- }, [hotkeys, enabled]);
19
+ var useHotkeys = (hotkeys) => {
20
+ const { enabled } = useContext(HotkeysContext);
21
+ useEffect(() => {
22
+ if (typeof document === "undefined" || !enabled) return;
23
+ const ctrl = new AbortController();
24
+ window.addEventListener(EVENT, (e) => {
25
+ if (!isCtrlOrMeta(e)) return;
26
+ for (const [code, callback] of Object.entries(hotkeys)) if (e.code === code) {
27
+ callback(e);
28
+ return;
29
+ }
30
+ }, {
31
+ signal: ctrl.signal,
32
+ capture: true
33
+ });
34
+ return () => {
35
+ ctrl.abort();
36
+ };
37
+ }, [hotkeys, enabled]);
36
38
  };
37
- export {
38
- HotkeysContext,
39
- HotkeysProvider,
40
- useHotkeys
41
- };
42
- //# sourceMappingURL=keyboard.js.map
39
+ //#endregion
40
+ export { HotkeysContext, HotkeysProvider, useHotkeys };
41
+
42
+ //# sourceMappingURL=keyboard.js.map