@flexacms/react 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +53 -2
- package/dist/index.cjs +123 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +48 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +101 -0
- package/dist/index.js.map +1 -0
- package/package.json +63 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ivan Mercedes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @flexacms/react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React provider and hooks for the [Flexa](https://github.com/flexacms) headless CMS.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @flexacms/react
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
import { createClient, FlexaProvider, useEntries } from '@flexacms/react';
|
|
11
|
+
|
|
12
|
+
const flexa = createClient({
|
|
13
|
+
url: import.meta.env.VITE_FLEXA_URL,
|
|
14
|
+
apiKey: import.meta.env.VITE_FLEXA_API_KEY,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export function App() {
|
|
18
|
+
return (
|
|
19
|
+
<FlexaProvider client={flexa}>
|
|
20
|
+
<Posts />
|
|
21
|
+
</FlexaProvider>
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function Posts() {
|
|
26
|
+
const { data, error, isLoading, refetch } = useEntries('posts', {
|
|
27
|
+
status: 'published',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
if (isLoading) return <p>Loading…</p>;
|
|
31
|
+
if (error) return <p>{error.message}</p>;
|
|
32
|
+
|
|
33
|
+
return (
|
|
34
|
+
<ul>
|
|
35
|
+
{data?.data.map((post) => (
|
|
36
|
+
<li key={post.id}>{post.title}</li>
|
|
37
|
+
))}
|
|
38
|
+
</ul>
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`useEntry(entity, idOrSlug)` returns one entry (`null` when it does not exist) and waits while the identifier is `null` or `undefined`. Stale responses are cancelled when the arguments change.
|
|
44
|
+
|
|
45
|
+
> These hooks run in the browser, so the API key is public. Use a **Read**-only key limited to the entities the site shows, or fetch on the server with [`@flexacms/next`](../next).
|
|
46
|
+
|
|
47
|
+
## Typed hooks
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { createFlexaHooks } from '@flexacms/react';
|
|
51
|
+
import type { FlexaSchema } from './flexa'; // npx @flexacms/cli generate
|
|
52
|
+
|
|
53
|
+
export const { useEntries, useEntry } = createFlexaHooks<FlexaSchema>();
|
|
54
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
"use strict";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
|
|
22
|
+
// src/index.ts
|
|
23
|
+
var index_exports = {};
|
|
24
|
+
__export(index_exports, {
|
|
25
|
+
FlexaProvider: () => FlexaProvider,
|
|
26
|
+
createFlexaHooks: () => createFlexaHooks,
|
|
27
|
+
useEntries: () => useEntries,
|
|
28
|
+
useEntry: () => useEntry,
|
|
29
|
+
useFlexa: () => useFlexa
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
var import_react = require("react");
|
|
33
|
+
__reExport(index_exports, require("@flexacms/client"), module.exports);
|
|
34
|
+
var FlexaContext = (0, import_react.createContext)(null);
|
|
35
|
+
function FlexaProvider({
|
|
36
|
+
client,
|
|
37
|
+
children
|
|
38
|
+
}) {
|
|
39
|
+
return (0, import_react.createElement)(FlexaContext.Provider, { value: client }, children);
|
|
40
|
+
}
|
|
41
|
+
function useFlexa() {
|
|
42
|
+
const client = (0, import_react.useContext)(FlexaContext);
|
|
43
|
+
if (!client) {
|
|
44
|
+
throw new Error("useFlexa() must be used inside a <FlexaProvider>.");
|
|
45
|
+
}
|
|
46
|
+
return client;
|
|
47
|
+
}
|
|
48
|
+
function useQuery(key, enabled, run) {
|
|
49
|
+
const [state, setState] = (0, import_react.useState)({
|
|
50
|
+
data: void 0,
|
|
51
|
+
error: void 0,
|
|
52
|
+
isLoading: enabled
|
|
53
|
+
});
|
|
54
|
+
const [version, setVersion] = (0, import_react.useState)(0);
|
|
55
|
+
const runRef = (0, import_react.useRef)(run);
|
|
56
|
+
runRef.current = run;
|
|
57
|
+
(0, import_react.useEffect)(() => {
|
|
58
|
+
if (!enabled) {
|
|
59
|
+
setState((current) => ({ ...current, isLoading: false }));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
setState((current) => ({
|
|
64
|
+
...current,
|
|
65
|
+
error: void 0,
|
|
66
|
+
isLoading: true
|
|
67
|
+
}));
|
|
68
|
+
runRef.current(controller.signal).then(
|
|
69
|
+
(data) => {
|
|
70
|
+
if (!controller.signal.aborted) {
|
|
71
|
+
setState({ data, error: void 0, isLoading: false });
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
(error) => {
|
|
75
|
+
if (!controller.signal.aborted) {
|
|
76
|
+
setState((current) => ({
|
|
77
|
+
...current,
|
|
78
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
79
|
+
isLoading: false
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
);
|
|
84
|
+
return () => controller.abort();
|
|
85
|
+
}, [key, enabled, version]);
|
|
86
|
+
const refetch = (0, import_react.useCallback)(() => setVersion((current) => current + 1), []);
|
|
87
|
+
return { ...state, refetch };
|
|
88
|
+
}
|
|
89
|
+
function createFlexaHooks() {
|
|
90
|
+
return {
|
|
91
|
+
useFlexa: () => useFlexa(),
|
|
92
|
+
useEntries: (entity, params = {}) => {
|
|
93
|
+
const client = useFlexa();
|
|
94
|
+
return useQuery(
|
|
95
|
+
`${entity}:${JSON.stringify(params)}`,
|
|
96
|
+
true,
|
|
97
|
+
(signal) => client.entity(entity).list(params, { signal })
|
|
98
|
+
);
|
|
99
|
+
},
|
|
100
|
+
useEntry: (entity, idOrSlug, params = {}) => {
|
|
101
|
+
const client = useFlexa();
|
|
102
|
+
const enabled = idOrSlug !== null && idOrSlug !== void 0 && idOrSlug !== "";
|
|
103
|
+
return useQuery(
|
|
104
|
+
`${entity}:${String(idOrSlug)}:${JSON.stringify(params)}`,
|
|
105
|
+
enabled,
|
|
106
|
+
(signal) => client.entity(entity).find(idOrSlug, params, { signal })
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
var untypedHooks = createFlexaHooks();
|
|
112
|
+
var useEntries = untypedHooks.useEntries;
|
|
113
|
+
var useEntry = untypedHooks.useEntry;
|
|
114
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
115
|
+
0 && (module.exports = {
|
|
116
|
+
FlexaProvider,
|
|
117
|
+
createFlexaHooks,
|
|
118
|
+
useEntries,
|
|
119
|
+
useEntry,
|
|
120
|
+
useFlexa,
|
|
121
|
+
...require("@flexacms/client")
|
|
122
|
+
});
|
|
123
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n ContentSchema,\n Entry,\n EntryValues,\n FlexaClient,\n GetParams,\n ListParams,\n Paginated,\n} from '@flexacms/client';\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react';\nimport type { ReactNode } from 'react';\n\nexport * from '@flexacms/client';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst FlexaContext = createContext<FlexaClient<any> | null>(null);\n\n/**\n * Makes a Flexa client available to the hooks below.\n *\n * The client runs in the browser, so its API key is public: use a key with only\n * the Read ability, limited to the entities the site shows. Prefer fetching on\n * the server (e.g. `@flexacms/next`) when you can.\n */\nexport function FlexaProvider<TSchema extends object = ContentSchema>({\n client,\n children,\n}: {\n client: FlexaClient<TSchema>;\n children?: ReactNode;\n}) {\n return createElement(FlexaContext.Provider, { value: client }, children);\n}\n\n/** The client given to the nearest `FlexaProvider`. */\nexport function useFlexa<\n TSchema extends object = ContentSchema,\n>(): FlexaClient<TSchema> {\n const client = useContext(FlexaContext);\n\n if (!client) {\n throw new Error('useFlexa() must be used inside a <FlexaProvider>.');\n }\n\n return client as FlexaClient<TSchema>;\n}\n\nexport interface QueryState<T> {\n data: T | undefined;\n error: Error | undefined;\n isLoading: boolean;\n /** Fetch again, keeping the current data until the new response arrives. */\n refetch: () => void;\n}\n\n/**\n * Run an async request on mount and whenever `key` changes, cancelling stale\n * requests so a slow response never overwrites a newer one.\n */\nfunction useQuery<T>(\n key: string,\n enabled: boolean,\n run: (signal: AbortSignal) => Promise<T>,\n): QueryState<T> {\n const [state, setState] = useState<Omit<QueryState<T>, 'refetch'>>({\n data: undefined,\n error: undefined,\n isLoading: enabled,\n });\n const [version, setVersion] = useState(0);\n const runRef = useRef(run);\n\n runRef.current = run;\n\n useEffect(() => {\n if (!enabled) {\n setState((current) => ({ ...current, isLoading: false }));\n\n return;\n }\n\n const controller = new AbortController();\n\n setState((current) => ({\n ...current,\n error: undefined,\n isLoading: true,\n }));\n\n runRef.current(controller.signal).then(\n (data) => {\n if (!controller.signal.aborted) {\n setState({ data, error: undefined, isLoading: false });\n }\n },\n (error: unknown) => {\n if (!controller.signal.aborted) {\n setState((current) => ({\n ...current,\n error:\n error instanceof Error\n ? error\n : new Error(String(error)),\n isLoading: false,\n }));\n }\n },\n );\n\n return () => controller.abort();\n }, [key, enabled, version]);\n\n const refetch = useCallback(() => setVersion((current) => current + 1), []);\n\n return { ...state, refetch };\n}\n\ntype ValuesFor<\n TSchema extends object,\n TEntity extends string,\n> = TEntity extends keyof TSchema\n ? TSchema[TEntity] extends object\n ? TSchema[TEntity]\n : EntryValues\n : EntryValues;\n\nexport interface FlexaHooks<TSchema extends object> {\n useFlexa: () => FlexaClient<TSchema>;\n /** A page of entries of an entity. */\n useEntries: <\n TEntity extends Extract<keyof TSchema, string> | (string & {}),\n >(\n entity: TEntity,\n params?: ListParams,\n ) => QueryState<Paginated<Entry<ValuesFor<TSchema, TEntity>>>>;\n /**\n * One entry by id or slug. `data` is `null` when it does not exist; pass\n * `null`/`undefined` as the identifier to wait (e.g. until a route param is known).\n */\n useEntry: <TEntity extends Extract<keyof TSchema, string> | (string & {})>(\n entity: TEntity,\n idOrSlug: number | string | null | undefined,\n params?: GetParams,\n ) => QueryState<Entry<ValuesFor<TSchema, TEntity>> | null>;\n}\n\n/**\n * Hooks typed with your generated schema:\n *\n * export const { useEntries, useEntry } = createFlexaHooks<FlexaSchema>();\n */\nexport function createFlexaHooks<\n TSchema extends object = ContentSchema,\n>(): FlexaHooks<TSchema> {\n return {\n useFlexa: () => useFlexa<TSchema>(),\n useEntries: (entity, params = {}) => {\n const client = useFlexa<TSchema>();\n\n return useQuery(\n `${entity}:${JSON.stringify(params)}`,\n true,\n (signal) => client.entity(entity).list(params, { signal }),\n ) as never;\n },\n useEntry: (entity, idOrSlug, params = {}) => {\n const client = useFlexa<TSchema>();\n const enabled =\n idOrSlug !== null && idOrSlug !== undefined && idOrSlug !== '';\n\n return useQuery(\n `${entity}:${String(idOrSlug)}:${JSON.stringify(params)}`,\n enabled,\n (signal) =>\n client\n .entity(entity)\n .find(idOrSlug as number | string, params, { signal }),\n ) as never;\n },\n };\n}\n\nconst untypedHooks = createFlexaHooks();\n\n/** A page of entries of an entity. Use `createFlexaHooks<FlexaSchema>()` for typed values. */\nexport const useEntries = untypedHooks.useEntries;\n\n/** One entry by id or slug (`null` when missing). Use `createFlexaHooks<FlexaSchema>()` for typed values. */\nexport const useEntry = untypedHooks.useEntry;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,mBAQO;AAGP,0BAAc,6BApBd;AAuBA,IAAM,mBAAe,4BAAuC,IAAI;AASzD,SAAS,cAAsD;AAAA,EAClE;AAAA,EACA;AACJ,GAGG;AACC,aAAO,4BAAc,aAAa,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;AAC3E;AAGO,SAAS,WAEU;AACtB,QAAM,aAAS,yBAAW,YAAY;AAEtC,MAAI,CAAC,QAAQ;AACT,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACvE;AAEA,SAAO;AACX;AAcA,SAAS,SACL,KACA,SACA,KACa;AACb,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAyC;AAAA,IAC/D,MAAM;AAAA,IACN,OAAO;AAAA,IACP,WAAW;AAAA,EACf,CAAC;AACD,QAAM,CAAC,SAAS,UAAU,QAAI,uBAAS,CAAC;AACxC,QAAM,aAAS,qBAAO,GAAG;AAEzB,SAAO,UAAU;AAEjB,8BAAU,MAAM;AACZ,QAAI,CAAC,SAAS;AACV,eAAS,CAAC,aAAa,EAAE,GAAG,SAAS,WAAW,MAAM,EAAE;AAExD;AAAA,IACJ;AAEA,UAAM,aAAa,IAAI,gBAAgB;AAEvC,aAAS,CAAC,aAAa;AAAA,MACnB,GAAG;AAAA,MACH,OAAO;AAAA,MACP,WAAW;AAAA,IACf,EAAE;AAEF,WAAO,QAAQ,WAAW,MAAM,EAAE;AAAA,MAC9B,CAAC,SAAS;AACN,YAAI,CAAC,WAAW,OAAO,SAAS;AAC5B,mBAAS,EAAE,MAAM,O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,WAAW,aAAa;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { FlexaClient, ListParams, Paginated, Entry, EntryValues, GetParams, ContentSchema } from '@flexacms/client';
|
|
4
|
+
export * from '@flexacms/client';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Makes a Flexa client available to the hooks below.
|
|
8
|
+
*
|
|
9
|
+
* The client runs in the browser, so its API key is public: use a key with only
|
|
10
|
+
* the Read ability, limited to the entities the site shows. Prefer fetching on
|
|
11
|
+
* the server (e.g. `@flexacms/next`) when you can.
|
|
12
|
+
*/
|
|
13
|
+
declare function FlexaProvider<TSchema extends object = ContentSchema>({ client, children, }: {
|
|
14
|
+
client: FlexaClient<TSchema>;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
}): react.FunctionComponentElement<react.ProviderProps<FlexaClient<any> | null>>;
|
|
17
|
+
/** The client given to the nearest `FlexaProvider`. */
|
|
18
|
+
declare function useFlexa<TSchema extends object = ContentSchema>(): FlexaClient<TSchema>;
|
|
19
|
+
interface QueryState<T> {
|
|
20
|
+
data: T | undefined;
|
|
21
|
+
error: Error | undefined;
|
|
22
|
+
isLoading: boolean;
|
|
23
|
+
/** Fetch again, keeping the current data until the new response arrives. */
|
|
24
|
+
refetch: () => void;
|
|
25
|
+
}
|
|
26
|
+
type ValuesFor<TSchema extends object, TEntity extends string> = TEntity extends keyof TSchema ? TSchema[TEntity] extends object ? TSchema[TEntity] : EntryValues : EntryValues;
|
|
27
|
+
interface FlexaHooks<TSchema extends object> {
|
|
28
|
+
useFlexa: () => FlexaClient<TSchema>;
|
|
29
|
+
/** A page of entries of an entity. */
|
|
30
|
+
useEntries: <TEntity extends Extract<keyof TSchema, string> | (string & {})>(entity: TEntity, params?: ListParams) => QueryState<Paginated<Entry<ValuesFor<TSchema, TEntity>>>>;
|
|
31
|
+
/**
|
|
32
|
+
* One entry by id or slug. `data` is `null` when it does not exist; pass
|
|
33
|
+
* `null`/`undefined` as the identifier to wait (e.g. until a route param is known).
|
|
34
|
+
*/
|
|
35
|
+
useEntry: <TEntity extends Extract<keyof TSchema, string> | (string & {})>(entity: TEntity, idOrSlug: number | string | null | undefined, params?: GetParams) => QueryState<Entry<ValuesFor<TSchema, TEntity>> | null>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Hooks typed with your generated schema:
|
|
39
|
+
*
|
|
40
|
+
* export const { useEntries, useEntry } = createFlexaHooks<FlexaSchema>();
|
|
41
|
+
*/
|
|
42
|
+
declare function createFlexaHooks<TSchema extends object = ContentSchema>(): FlexaHooks<TSchema>;
|
|
43
|
+
/** A page of entries of an entity. Use `createFlexaHooks<FlexaSchema>()` for typed values. */
|
|
44
|
+
declare const useEntries: <TEntity extends string | (string & {})>(entity: TEntity, params?: ListParams) => QueryState<Paginated<Entry<ValuesFor<ContentSchema, TEntity>>>>;
|
|
45
|
+
/** One entry by id or slug (`null` when missing). Use `createFlexaHooks<FlexaSchema>()` for typed values. */
|
|
46
|
+
declare const useEntry: <TEntity extends string | (string & {})>(entity: TEntity, idOrSlug: number | string | null | undefined, params?: GetParams) => QueryState<Entry<ValuesFor<ContentSchema, TEntity>> | null>;
|
|
47
|
+
|
|
48
|
+
export { type FlexaHooks, FlexaProvider, type QueryState, createFlexaHooks, useEntries, useEntry, useFlexa };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { FlexaClient, ListParams, Paginated, Entry, EntryValues, GetParams, ContentSchema } from '@flexacms/client';
|
|
4
|
+
export * from '@flexacms/client';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Makes a Flexa client available to the hooks below.
|
|
8
|
+
*
|
|
9
|
+
* The client runs in the browser, so its API key is public: use a key with only
|
|
10
|
+
* the Read ability, limited to the entities the site shows. Prefer fetching on
|
|
11
|
+
* the server (e.g. `@flexacms/next`) when you can.
|
|
12
|
+
*/
|
|
13
|
+
declare function FlexaProvider<TSchema extends object = ContentSchema>({ client, children, }: {
|
|
14
|
+
client: FlexaClient<TSchema>;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
}): react.FunctionComponentElement<react.ProviderProps<FlexaClient<any> | null>>;
|
|
17
|
+
/** The client given to the nearest `FlexaProvider`. */
|
|
18
|
+
declare function useFlexa<TSchema extends object = ContentSchema>(): FlexaClient<TSchema>;
|
|
19
|
+
interface QueryState<T> {
|
|
20
|
+
data: T | undefined;
|
|
21
|
+
error: Error | undefined;
|
|
22
|
+
isLoading: boolean;
|
|
23
|
+
/** Fetch again, keeping the current data until the new response arrives. */
|
|
24
|
+
refetch: () => void;
|
|
25
|
+
}
|
|
26
|
+
type ValuesFor<TSchema extends object, TEntity extends string> = TEntity extends keyof TSchema ? TSchema[TEntity] extends object ? TSchema[TEntity] : EntryValues : EntryValues;
|
|
27
|
+
interface FlexaHooks<TSchema extends object> {
|
|
28
|
+
useFlexa: () => FlexaClient<TSchema>;
|
|
29
|
+
/** A page of entries of an entity. */
|
|
30
|
+
useEntries: <TEntity extends Extract<keyof TSchema, string> | (string & {})>(entity: TEntity, params?: ListParams) => QueryState<Paginated<Entry<ValuesFor<TSchema, TEntity>>>>;
|
|
31
|
+
/**
|
|
32
|
+
* One entry by id or slug. `data` is `null` when it does not exist; pass
|
|
33
|
+
* `null`/`undefined` as the identifier to wait (e.g. until a route param is known).
|
|
34
|
+
*/
|
|
35
|
+
useEntry: <TEntity extends Extract<keyof TSchema, string> | (string & {})>(entity: TEntity, idOrSlug: number | string | null | undefined, params?: GetParams) => QueryState<Entry<ValuesFor<TSchema, TEntity>> | null>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Hooks typed with your generated schema:
|
|
39
|
+
*
|
|
40
|
+
* export const { useEntries, useEntry } = createFlexaHooks<FlexaSchema>();
|
|
41
|
+
*/
|
|
42
|
+
declare function createFlexaHooks<TSchema extends object = ContentSchema>(): FlexaHooks<TSchema>;
|
|
43
|
+
/** A page of entries of an entity. Use `createFlexaHooks<FlexaSchema>()` for typed values. */
|
|
44
|
+
declare const useEntries: <TEntity extends string | (string & {})>(entity: TEntity, params?: ListParams) => QueryState<Paginated<Entry<ValuesFor<ContentSchema, TEntity>>>>;
|
|
45
|
+
/** One entry by id or slug (`null` when missing). Use `createFlexaHooks<FlexaSchema>()` for typed values. */
|
|
46
|
+
declare const useEntry: <TEntity extends string | (string & {})>(entity: TEntity, idOrSlug: number | string | null | undefined, params?: GetParams) => QueryState<Entry<ValuesFor<ContentSchema, TEntity>> | null>;
|
|
47
|
+
|
|
48
|
+
export { type FlexaHooks, FlexaProvider, type QueryState, createFlexaHooks, useEntries, useEntry, useFlexa };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import {
|
|
5
|
+
createContext,
|
|
6
|
+
createElement,
|
|
7
|
+
useCallback,
|
|
8
|
+
useContext,
|
|
9
|
+
useEffect,
|
|
10
|
+
useRef,
|
|
11
|
+
useState
|
|
12
|
+
} from "react";
|
|
13
|
+
export * from "@flexacms/client";
|
|
14
|
+
var FlexaContext = createContext(null);
|
|
15
|
+
function FlexaProvider({
|
|
16
|
+
client,
|
|
17
|
+
children
|
|
18
|
+
}) {
|
|
19
|
+
return createElement(FlexaContext.Provider, { value: client }, children);
|
|
20
|
+
}
|
|
21
|
+
function useFlexa() {
|
|
22
|
+
const client = useContext(FlexaContext);
|
|
23
|
+
if (!client) {
|
|
24
|
+
throw new Error("useFlexa() must be used inside a <FlexaProvider>.");
|
|
25
|
+
}
|
|
26
|
+
return client;
|
|
27
|
+
}
|
|
28
|
+
function useQuery(key, enabled, run) {
|
|
29
|
+
const [state, setState] = useState({
|
|
30
|
+
data: void 0,
|
|
31
|
+
error: void 0,
|
|
32
|
+
isLoading: enabled
|
|
33
|
+
});
|
|
34
|
+
const [version, setVersion] = useState(0);
|
|
35
|
+
const runRef = useRef(run);
|
|
36
|
+
runRef.current = run;
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
if (!enabled) {
|
|
39
|
+
setState((current) => ({ ...current, isLoading: false }));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
setState((current) => ({
|
|
44
|
+
...current,
|
|
45
|
+
error: void 0,
|
|
46
|
+
isLoading: true
|
|
47
|
+
}));
|
|
48
|
+
runRef.current(controller.signal).then(
|
|
49
|
+
(data) => {
|
|
50
|
+
if (!controller.signal.aborted) {
|
|
51
|
+
setState({ data, error: void 0, isLoading: false });
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
(error) => {
|
|
55
|
+
if (!controller.signal.aborted) {
|
|
56
|
+
setState((current) => ({
|
|
57
|
+
...current,
|
|
58
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
59
|
+
isLoading: false
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
);
|
|
64
|
+
return () => controller.abort();
|
|
65
|
+
}, [key, enabled, version]);
|
|
66
|
+
const refetch = useCallback(() => setVersion((current) => current + 1), []);
|
|
67
|
+
return { ...state, refetch };
|
|
68
|
+
}
|
|
69
|
+
function createFlexaHooks() {
|
|
70
|
+
return {
|
|
71
|
+
useFlexa: () => useFlexa(),
|
|
72
|
+
useEntries: (entity, params = {}) => {
|
|
73
|
+
const client = useFlexa();
|
|
74
|
+
return useQuery(
|
|
75
|
+
`${entity}:${JSON.stringify(params)}`,
|
|
76
|
+
true,
|
|
77
|
+
(signal) => client.entity(entity).list(params, { signal })
|
|
78
|
+
);
|
|
79
|
+
},
|
|
80
|
+
useEntry: (entity, idOrSlug, params = {}) => {
|
|
81
|
+
const client = useFlexa();
|
|
82
|
+
const enabled = idOrSlug !== null && idOrSlug !== void 0 && idOrSlug !== "";
|
|
83
|
+
return useQuery(
|
|
84
|
+
`${entity}:${String(idOrSlug)}:${JSON.stringify(params)}`,
|
|
85
|
+
enabled,
|
|
86
|
+
(signal) => client.entity(entity).find(idOrSlug, params, { signal })
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
var untypedHooks = createFlexaHooks();
|
|
92
|
+
var useEntries = untypedHooks.useEntries;
|
|
93
|
+
var useEntry = untypedHooks.useEntry;
|
|
94
|
+
export {
|
|
95
|
+
FlexaProvider,
|
|
96
|
+
createFlexaHooks,
|
|
97
|
+
useEntries,
|
|
98
|
+
useEntry,
|
|
99
|
+
useFlexa
|
|
100
|
+
};
|
|
101
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n ContentSchema,\n Entry,\n EntryValues,\n FlexaClient,\n GetParams,\n ListParams,\n Paginated,\n} from '@flexacms/client';\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react';\nimport type { ReactNode } from 'react';\n\nexport * from '@flexacms/client';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst FlexaContext = createContext<FlexaClient<any> | null>(null);\n\n/**\n * Makes a Flexa client available to the hooks below.\n *\n * The client runs in the browser, so its API key is public: use a key with only\n * the Read ability, limited to the entities the site shows. Prefer fetching on\n * the server (e.g. `@flexacms/next`) when you can.\n */\nexport function FlexaProvider<TSchema extends object = ContentSchema>({\n client,\n children,\n}: {\n client: FlexaClient<TSchema>;\n children?: ReactNode;\n}) {\n return createElement(FlexaContext.Provider, { value: client }, children);\n}\n\n/** The client given to the nearest `FlexaProvider`. */\nexport function useFlexa<\n TSchema extends object = ContentSchema,\n>(): FlexaClient<TSchema> {\n const client = useContext(FlexaContext);\n\n if (!client) {\n throw new Error('useFlexa() must be used inside a <FlexaProvider>.');\n }\n\n return client as FlexaClient<TSchema>;\n}\n\nexport interface QueryState<T> {\n data: T | undefined;\n error: Error | undefined;\n isLoading: boolean;\n /** Fetch again, keeping the current data until the new response arrives. */\n refetch: () => void;\n}\n\n/**\n * Run an async request on mount and whenever `key` changes, cancelling stale\n * requests so a slow response never overwrites a newer one.\n */\nfunction useQuery<T>(\n key: string,\n enabled: boolean,\n run: (signal: AbortSignal) => Promise<T>,\n): QueryState<T> {\n const [state, setState] = useState<Omit<QueryState<T>, 'refetch'>>({\n data: undefined,\n error: undefined,\n isLoading: enabled,\n });\n const [version, setVersion] = useState(0);\n const runRef = useRef(run);\n\n runRef.current = run;\n\n useEffect(() => {\n if (!enabled) {\n setState((current) => ({ ...current, isLoading: false }));\n\n return;\n }\n\n const controller = new AbortController();\n\n setState((current) => ({\n ...current,\n error: undefined,\n isLoading: true,\n }));\n\n runRef.current(controller.signal).then(\n (data) => {\n if (!controller.signal.aborted) {\n setState({ data, error: undefined, isLoading: false });\n }\n },\n (error: unknown) => {\n if (!controller.signal.aborted) {\n setState((current) => ({\n ...current,\n error:\n error instanceof Error\n ? error\n : new Error(String(error)),\n isLoading: false,\n }));\n }\n },\n );\n\n return () => controller.abort();\n }, [key, enabled, version]);\n\n const refetch = useCallback(() => setVersion((current) => current + 1), []);\n\n return { ...state, refetch };\n}\n\ntype ValuesFor<\n TSchema extends object,\n TEntity extends string,\n> = TEntity extends keyof TSchema\n ? TSchema[TEntity] extends object\n ? TSchema[TEntity]\n : EntryValues\n : EntryValues;\n\nexport interface FlexaHooks<TSchema extends object> {\n useFlexa: () => FlexaClient<TSchema>;\n /** A page of entries of an entity. */\n useEntries: <\n TEntity extends Extract<keyof TSchema, string> | (string & {}),\n >(\n entity: TEntity,\n params?: ListParams,\n ) => QueryState<Paginated<Entry<ValuesFor<TSchema, TEntity>>>>;\n /**\n * One entry by id or slug. `data` is `null` when it does not exist; pass\n * `null`/`undefined` as the identifier to wait (e.g. until a route param is known).\n */\n useEntry: <TEntity extends Extract<keyof TSchema, string> | (string & {})>(\n entity: TEntity,\n idOrSlug: number | string | null | undefined,\n params?: GetParams,\n ) => QueryState<Entry<ValuesFor<TSchema, TEntity>> | null>;\n}\n\n/**\n * Hooks typed with your generated schema:\n *\n * export const { useEntries, useEntry } = createFlexaHooks<FlexaSchema>();\n */\nexport function createFlexaHooks<\n TSchema extends object = ContentSchema,\n>(): FlexaHooks<TSchema> {\n return {\n useFlexa: () => useFlexa<TSchema>(),\n useEntries: (entity, params = {}) => {\n const client = useFlexa<TSchema>();\n\n return useQuery(\n `${entity}:${JSON.stringify(params)}`,\n true,\n (signal) => client.entity(entity).list(params, { signal }),\n ) as never;\n },\n useEntry: (entity, idOrSlug, params = {}) => {\n const client = useFlexa<TSchema>();\n const enabled =\n idOrSlug !== null && idOrSlug !== undefined && idOrSlug !== '';\n\n return useQuery(\n `${entity}:${String(idOrSlug)}:${JSON.stringify(params)}`,\n enabled,\n (signal) =>\n client\n .entity(entity)\n .find(idOrSlug as number | string, params, { signal }),\n ) as never;\n },\n };\n}\n\nconst untypedHooks = createFlexaHooks();\n\n/** A page of entries of an entity. Use `createFlexaHooks<FlexaSchema>()` for typed values. */\nexport const useEntries = untypedHooks.useEntries;\n\n/** One entry by id or slug (`null` when missing). Use `createFlexaHooks<FlexaSchema>()` for typed values. */\nexport const useEntry = untypedHooks.useEntry;\n"],"mappings":";;;AASA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAGP,cAAc;AAGd,IAAM,eAAe,cAAuC,IAAI;AASzD,SAAS,cAAsD;AAAA,EAClE;AAAA,EACA;AACJ,GAGG;AACC,SAAO,cAAc,aAAa,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;AAC3E;AAGO,SAAS,WAEU;AACtB,QAAM,SAAS,WAAW,YAAY;AAEtC,MAAI,CAAC,QAAQ;AACT,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACvE;AAEA,SAAO;AACX;AAcA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AAkB;AAEjC,aAAO;AAAA,QACH,GAAG,MAAM,IAAI,KAAK,UAAU,MAAM,CAAC;AAAA,QACnC;AAAA,QACA,CAAC,WAAW,OAAO,OAAO,MAAM,EAAE,KAAK,QAAQ,EAAE,OAAO,CAAC;AAAA,MAC7D;AAAA,IACJ;AAAA,IACA,UAAU,CAAC,QAAQ,UAAU,SAAS,CAAC,MAAM;AACzC,YAAM,SAAS,SAAkB;AACjC,YAAM,UACF,aAAa,QAAQ,aAAa,UAAa,aAAa;AAEhE,aAAO;AAAA,QACH,GAAG,MAAM,IAAI,OAAO,QAAQ,CAAC,IAAI,KAAK,UAAU,MAAM,CAAC;AAAA,QACvD;AAAA,QACA,CAAC,WACG,OACK,OAAO,MAAM,EACb,KAAK,UAA6B,QAAQ,EAAE,OAAO,CAAC;AAAA,MACjE;AAAA,IACJ;AAAA,EACJ;AACJ;AAEA,IAAM,eAAe,iBAAiB;AAG/B,IAAM,aAAa,aAAa;AAGhC,IAAM,WAAW,aAAa;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@flexacms/react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React provider and hooks for the Flexa headless CMS.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cms",
|
|
7
|
+
"flexa",
|
|
8
|
+
"headless",
|
|
9
|
+
"hooks",
|
|
10
|
+
"react"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/flexacms/sdk/tree/main/packages/react#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/flexacms/sdk/issues"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/flexacms/sdk.git",
|
|
20
|
+
"directory": "packages/react"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"main": "./dist/index.cjs",
|
|
30
|
+
"module": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"import": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/index.js"
|
|
37
|
+
},
|
|
38
|
+
"require": {
|
|
39
|
+
"types": "./dist/index.d.cts",
|
|
40
|
+
"default": "./dist/index.cjs"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsup",
|
|
49
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@flexacms/client": "^0.1.0"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@testing-library/react": "^16.3.3",
|
|
56
|
+
"@types/react": "^19.3.0",
|
|
57
|
+
"jsdom": "^30.1.2",
|
|
58
|
+
"react": "^19.3.0",
|
|
59
|
+
"react-dom": "^19.3.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"react": "^18.2.0 || ^19.0.0"
|
|
63
|
+
}
|
|
64
|
+
}
|