@supatype/react 0.1.0-alpha.10
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/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/dist/RichText.d.ts +16 -0
- package/dist/RichText.d.ts.map +1 -0
- package/dist/RichText.js +17 -0
- package/dist/RichText.js.map +1 -0
- package/dist/context.d.ts +31 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +36 -0
- package/dist/context.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/useAuth.d.ts +77 -0
- package/dist/useAuth.d.ts.map +1 -0
- package/dist/useAuth.js +46 -0
- package/dist/useAuth.js.map +1 -0
- package/dist/useFunction.d.ts +35 -0
- package/dist/useFunction.d.ts.map +1 -0
- package/dist/useFunction.js +39 -0
- package/dist/useFunction.js.map +1 -0
- package/dist/useLivePreview.d.ts +35 -0
- package/dist/useLivePreview.d.ts.map +1 -0
- package/dist/useLivePreview.js +47 -0
- package/dist/useLivePreview.js.map +1 -0
- package/dist/useMutation.d.ts +29 -0
- package/dist/useMutation.d.ts.map +1 -0
- package/dist/useMutation.js +60 -0
- package/dist/useMutation.js.map +1 -0
- package/dist/useQuery.d.ts +41 -0
- package/dist/useQuery.d.ts.map +1 -0
- package/dist/useQuery.js +69 -0
- package/dist/useQuery.js.map +1 -0
- package/dist/useSubscription.d.ts +32 -0
- package/dist/useSubscription.d.ts.map +1 -0
- package/dist/useSubscription.js +39 -0
- package/dist/useSubscription.js.map +1 -0
- package/package.json +32 -0
- package/src/RichText.tsx +31 -0
- package/src/context.tsx +46 -0
- package/src/index.ts +23 -0
- package/src/useAuth.ts +86 -0
- package/src/useFunction.ts +72 -0
- package/src/useLivePreview.ts +64 -0
- package/src/useMutation.ts +92 -0
- package/src/useQuery.ts +111 -0
- package/src/useSubscription.ts +72 -0
- package/tsconfig.json +15 -0
- package/tsconfig.tsbuildinfo +1 -0
package/dist/useQuery.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useState, useEffect, useCallback, useRef } from "react";
|
|
3
|
+
import { useSupatype } from "./context.js";
|
|
4
|
+
/**
|
|
5
|
+
* Fetch rows from a table with automatic re-execution when options change.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```tsx
|
|
9
|
+
* const { data: posts, loading } = useQuery('posts', {
|
|
10
|
+
* filter: { status: 'published' },
|
|
11
|
+
* order: { column: 'created_at', ascending: false },
|
|
12
|
+
* limit: 10,
|
|
13
|
+
* })
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export function useQuery(table, options) {
|
|
17
|
+
const client = useSupatype();
|
|
18
|
+
const [data, setData] = useState(null);
|
|
19
|
+
const [error, setError] = useState(null);
|
|
20
|
+
const [count, setCount] = useState(null);
|
|
21
|
+
const [loading, setLoading] = useState(true);
|
|
22
|
+
// Stable reference to options for the effect dep
|
|
23
|
+
const optionsJson = JSON.stringify(options);
|
|
24
|
+
const intervalRef = useRef(null);
|
|
25
|
+
const execute = useCallback(async () => {
|
|
26
|
+
if (options?.enabled === false) {
|
|
27
|
+
setLoading(false);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
setLoading(true);
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
32
|
+
let query = client.from(table).select(options?.select ?? "*");
|
|
33
|
+
if (options?.filter !== undefined) {
|
|
34
|
+
for (const [col, val] of Object.entries(options.filter)) {
|
|
35
|
+
query = query.eq(col, val);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (options?.order !== undefined) {
|
|
39
|
+
query = query.order(options.order.column, { ascending: options.order.ascending ?? true });
|
|
40
|
+
}
|
|
41
|
+
if (options?.limit !== undefined) {
|
|
42
|
+
query = query.limit(options.limit);
|
|
43
|
+
}
|
|
44
|
+
if (options?.offset !== undefined && options.limit !== undefined) {
|
|
45
|
+
query = query.range(options.offset, options.offset + options.limit - 1);
|
|
46
|
+
}
|
|
47
|
+
const result = (await query);
|
|
48
|
+
setData(result.data);
|
|
49
|
+
setError(result.error);
|
|
50
|
+
setCount(result.count);
|
|
51
|
+
setLoading(false);
|
|
52
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
53
|
+
}, [client, table, optionsJson]);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
void execute();
|
|
56
|
+
if (options?.refetchInterval !== undefined) {
|
|
57
|
+
intervalRef.current = setInterval(() => void execute(), options.refetchInterval);
|
|
58
|
+
}
|
|
59
|
+
return () => {
|
|
60
|
+
if (intervalRef.current !== null) {
|
|
61
|
+
clearInterval(intervalRef.current);
|
|
62
|
+
intervalRef.current = null;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
66
|
+
}, [execute]);
|
|
67
|
+
return { data, error, count, loading, refetch: () => void execute() };
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=useQuery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useQuery.js","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA,YAAY,CAAA;AAEZ,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,OAAO,CAAA;AAEhE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AA2B1C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,QAAQ,CAKtB,KAAa,EACb,OAAqC;IAErC,MAAM,MAAM,GAAG,WAAW,EAAa,CAAA;IACvC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAgB,IAAI,CAAC,CAAA;IACrD,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,QAAQ,CAAuB,IAAI,CAA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AACvE,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { RealtimeEvent, RealtimePayload, ChannelStatus } from "@supatype/client";
|
|
2
|
+
export type SubscriptionStatus = ChannelStatus;
|
|
3
|
+
export interface UseSubscriptionOptions<TRow> {
|
|
4
|
+
/** Postgres event to listen for. Defaults to "*" (all events). */
|
|
5
|
+
event?: RealtimeEvent | undefined;
|
|
6
|
+
/** Table to listen on. Defaults to the channel name. */
|
|
7
|
+
table?: string | undefined;
|
|
8
|
+
/** PostgREST filter expression (e.g. "id=eq.1"). */
|
|
9
|
+
filter?: string | undefined;
|
|
10
|
+
/** Schema to listen on. Defaults to "public". */
|
|
11
|
+
schema?: string | undefined;
|
|
12
|
+
/** Called on every change event matching the subscription. */
|
|
13
|
+
callback: (payload: RealtimePayload<TRow>) => void;
|
|
14
|
+
}
|
|
15
|
+
export interface UseSubscriptionResult {
|
|
16
|
+
/** Current subscription status. */
|
|
17
|
+
status: SubscriptionStatus;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Subscribe to real-time row changes on a table.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```tsx
|
|
24
|
+
* useSubscription<Post>('posts-channel', {
|
|
25
|
+
* event: 'INSERT',
|
|
26
|
+
* table: 'posts',
|
|
27
|
+
* callback: (payload) => console.log('New post:', payload.new),
|
|
28
|
+
* })
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function useSubscription<TRow = Record<string, unknown>>(channelName: string, opts: UseSubscriptionOptions<TRow>): UseSubscriptionResult;
|
|
32
|
+
//# sourceMappingURL=useSubscription.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useSubscription.d.ts","sourceRoot":"","sources":["../src/useSubscription.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAGrF,MAAM,MAAM,kBAAkB,GAAG,aAAa,CAAA;AAE9C,MAAM,WAAW,sBAAsB,CAAC,IAAI;IAC1C,kEAAkE;IAClE,KAAK,CAAC,EAAE,aAAa,GAAG,SAAS,CAAA;IACjC,wDAAwD;IACxD,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,oDAAoD;IACpD,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,iDAAiD;IACjD,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,8DAA8D;IAC9D,QAAQ,EAAE,CAAC,OAAO,EAAE,eAAe,CAAC,IAAI,CAAC,KAAK,IAAI,CAAA;CACnD;AAED,MAAM,WAAW,qBAAqB;IACpC,mCAAmC;IACnC,MAAM,EAAE,kBAAkB,CAAA;CAC3B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5D,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE,sBAAsB,CAAC,IAAI,CAAC,GACjC,qBAAqB,CA8BvB"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef, useState } from "react";
|
|
3
|
+
import { useSupatype } from "./context.js";
|
|
4
|
+
/**
|
|
5
|
+
* Subscribe to real-time row changes on a table.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```tsx
|
|
9
|
+
* useSubscription<Post>('posts-channel', {
|
|
10
|
+
* event: 'INSERT',
|
|
11
|
+
* table: 'posts',
|
|
12
|
+
* callback: (payload) => console.log('New post:', payload.new),
|
|
13
|
+
* })
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export function useSubscription(channelName, opts) {
|
|
17
|
+
const client = useSupatype();
|
|
18
|
+
const [status, setStatus] = useState("SUBSCRIBING");
|
|
19
|
+
// Stable ref so the effect doesn't re-run when the callback reference changes
|
|
20
|
+
const callbackRef = useRef(opts.callback);
|
|
21
|
+
callbackRef.current = opts.callback;
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
const channel = client.realtime
|
|
24
|
+
.channel(channelName)
|
|
25
|
+
.on("postgres_changes", {
|
|
26
|
+
event: opts.event ?? "*",
|
|
27
|
+
...(opts.schema !== undefined && { schema: opts.schema }),
|
|
28
|
+
...(opts.table !== undefined && { table: opts.table }),
|
|
29
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
30
|
+
}, (payload) => callbackRef.current(payload))
|
|
31
|
+
.subscribe((s) => setStatus(s));
|
|
32
|
+
return () => {
|
|
33
|
+
channel.unsubscribe();
|
|
34
|
+
};
|
|
35
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
36
|
+
}, [client, channelName, opts.event, opts.schema, opts.table, opts.filter]);
|
|
37
|
+
return { status };
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=useSubscription.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useSubscription.js","sourceRoot":"","sources":["../src/useSubscription.ts"],"names":[],"mappings":"AAAA,YAAY,CAAA;AAEZ,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEnD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAsB1C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,eAAe,CAC7B,WAAmB,EACnB,IAAkC;IAElC,MAAM,MAAM,GAAG,WAAW,EAAE,CAAA;IAC5B,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAqB,aAAa,CAAC,CAAA;IAEvE,8EAA8E;IAC9E,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IACzC,WAAW,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAA;IAEnC,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ;aAC5B,OAAO,CAAO,WAAW,CAAC;aAC1B,EAAE,CACD,kBAAkB,EAClB;YACE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,GAAG;YACxB,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;YACzD,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;YACtD,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;SAC1D,EACD,CAAC,OAAO,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAC1C;aACA,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAA;QAEjC,OAAO,GAAG,EAAE;YACV,OAAO,CAAC,WAAW,EAAE,CAAA;QACvB,CAAC,CAAA;QACD,uDAAuD;IACzD,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAA;IAE3E,OAAO,EAAE,MAAM,EAAE,CAAA;AACnB,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@supatype/react",
|
|
3
|
+
"version": "0.1.0-alpha.10",
|
|
4
|
+
"description": "Supatype React hooks — useAuth, useQuery, useMutation, SupatypeProvider",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@supatype/client": "0.1.0-alpha.10",
|
|
16
|
+
"@supatype/common": "0.1.0-alpha.10"
|
|
17
|
+
},
|
|
18
|
+
"peerDependencies": {
|
|
19
|
+
"react": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/react": "^18",
|
|
23
|
+
"react": "^18",
|
|
24
|
+
"typescript": "^5"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsc --project tsconfig.json",
|
|
28
|
+
"dev": "tsc --project tsconfig.json --watch",
|
|
29
|
+
"typecheck": "tsc --project tsconfig.json --noEmit",
|
|
30
|
+
"clean": "rm -rf dist *.tsbuildinfo"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/RichText.tsx
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { renderRichText, type RichTextNode } from "@supatype/common/richtext"
|
|
2
|
+
|
|
3
|
+
export interface RichTextProps {
|
|
4
|
+
/** Lexical JSON content — a root node, an array of child nodes, or null. */
|
|
5
|
+
content: RichTextNode | RichTextNode[] | null | undefined
|
|
6
|
+
/** Optional CSS class applied to the wrapper element. */
|
|
7
|
+
className?: string
|
|
8
|
+
/** Wrapper element tag. Defaults to `"div"`. */
|
|
9
|
+
as?: "div" | "article" | "section" | "aside" | "main"
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Renders a Lexical rich-text JSON tree as HTML.
|
|
14
|
+
*
|
|
15
|
+
* Works in both Server Components and Client Components.
|
|
16
|
+
*/
|
|
17
|
+
export function RichText({
|
|
18
|
+
content,
|
|
19
|
+
className,
|
|
20
|
+
as: Tag = "div",
|
|
21
|
+
}: RichTextProps): React.ReactElement | null {
|
|
22
|
+
if (content == null) return null
|
|
23
|
+
|
|
24
|
+
const node: RichTextNode = Array.isArray(content)
|
|
25
|
+
? { type: "root", children: content }
|
|
26
|
+
: content
|
|
27
|
+
|
|
28
|
+
const html = renderRichText(node)
|
|
29
|
+
|
|
30
|
+
return <Tag className={className} dangerouslySetInnerHTML={{ __html: html }} />
|
|
31
|
+
}
|
package/src/context.tsx
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import React from "react"
|
|
4
|
+
import type { SupatypeClient, AnyDatabase } from "@supatype/client"
|
|
5
|
+
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
7
|
+
export const SupatypeContext = React.createContext<SupatypeClient<any> | null>(null)
|
|
8
|
+
|
|
9
|
+
export interface SupatypeProviderProps {
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
11
|
+
client: SupatypeClient<any>
|
|
12
|
+
children: React.ReactNode
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Wrap your application with SupatypeProvider to make the client available
|
|
17
|
+
* via all Supatype hooks.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```tsx
|
|
21
|
+
* const client = createClient({ url: '...', anonKey: '...' })
|
|
22
|
+
*
|
|
23
|
+
* function App() {
|
|
24
|
+
* return (
|
|
25
|
+
* <SupatypeProvider client={client}>
|
|
26
|
+
* <YourApp />
|
|
27
|
+
* </SupatypeProvider>
|
|
28
|
+
* )
|
|
29
|
+
* }
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export function SupatypeProvider({ client, children }: SupatypeProviderProps): React.ReactElement {
|
|
33
|
+
return React.createElement(SupatypeContext.Provider, { value: client }, children)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Access the Supatype client directly. Most callers should use the
|
|
38
|
+
* higher-level hooks (useAuth, useQuery, useMutation) instead.
|
|
39
|
+
*/
|
|
40
|
+
export function useSupatype<TDatabase extends AnyDatabase = AnyDatabase>(): SupatypeClient<TDatabase> {
|
|
41
|
+
const client = React.useContext(SupatypeContext) as SupatypeClient<TDatabase> | null
|
|
42
|
+
if (client === null) {
|
|
43
|
+
throw new Error("useSupatype must be used inside a <SupatypeProvider>")
|
|
44
|
+
}
|
|
45
|
+
return client
|
|
46
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export { SupatypeProvider, SupatypeContext, useSupatype } from "./context.js"
|
|
2
|
+
export type { SupatypeProviderProps } from "./context.js"
|
|
3
|
+
|
|
4
|
+
export { useAuth } from "./useAuth.js"
|
|
5
|
+
export type { UseAuthReturn } from "./useAuth.js"
|
|
6
|
+
|
|
7
|
+
export { useQuery } from "./useQuery.js"
|
|
8
|
+
export type { UseQueryOptions, UseQueryResult } from "./useQuery.js"
|
|
9
|
+
|
|
10
|
+
export { useMutation } from "./useMutation.js"
|
|
11
|
+
export type { UseMutationResult, MutationOperation, MutationOptions } from "./useMutation.js"
|
|
12
|
+
|
|
13
|
+
export { useSubscription } from "./useSubscription.js"
|
|
14
|
+
export type { UseSubscriptionOptions, UseSubscriptionResult, SubscriptionStatus } from "./useSubscription.js"
|
|
15
|
+
|
|
16
|
+
export { useLivePreview } from "./useLivePreview.js"
|
|
17
|
+
export type { UseLivePreviewOptions, UseLivePreviewResult } from "./useLivePreview.js"
|
|
18
|
+
|
|
19
|
+
export { useFunction } from "./useFunction.js"
|
|
20
|
+
export type { UseFunctionResult } from "./useFunction.js"
|
|
21
|
+
|
|
22
|
+
export { RichText } from "./RichText.js"
|
|
23
|
+
export type { RichTextProps } from "./RichText.js"
|
package/src/useAuth.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { useState, useEffect } from "react"
|
|
4
|
+
import type { Session, User, AuthChangeEvent, SupatypeError } from "@supatype/client"
|
|
5
|
+
import { useSupatype } from "./context.js"
|
|
6
|
+
|
|
7
|
+
export interface UseAuthReturn {
|
|
8
|
+
/** The currently authenticated user, or null if not signed in. */
|
|
9
|
+
user: User | null
|
|
10
|
+
/** The current session (includes access token), or null. */
|
|
11
|
+
session: Session | null
|
|
12
|
+
/** True while loading the initial auth state. */
|
|
13
|
+
loading: boolean
|
|
14
|
+
/** Sign up with email and password. */
|
|
15
|
+
signUp(credentials: {
|
|
16
|
+
email: string
|
|
17
|
+
password: string
|
|
18
|
+
options?: { data?: Record<string, unknown> } | undefined
|
|
19
|
+
}): Promise<{ data: { session: Session | null; user: User | null }; error: SupatypeError | null }>
|
|
20
|
+
/** Sign in with email and password. */
|
|
21
|
+
signIn(credentials: {
|
|
22
|
+
email: string
|
|
23
|
+
password: string
|
|
24
|
+
}): Promise<{ data: { session: Session | null; user: User | null }; error: SupatypeError | null }>
|
|
25
|
+
/** Sign in via OAuth provider (returns redirect URL). */
|
|
26
|
+
signInWithOAuth(opts: {
|
|
27
|
+
provider: string
|
|
28
|
+
options?: { redirectTo?: string } | undefined
|
|
29
|
+
}): Promise<{ data: { url: string; provider: string }; error: SupatypeError | null }>
|
|
30
|
+
/** Sign in with a magic link (OTP) sent to the email. */
|
|
31
|
+
signInWithOtp(opts: {
|
|
32
|
+
email: string
|
|
33
|
+
options?: { emailRedirectTo?: string } | undefined
|
|
34
|
+
}): Promise<{ data: { messageId?: string | undefined }; error: SupatypeError | null }>
|
|
35
|
+
/** Sign out the current user. */
|
|
36
|
+
signOut(): Promise<{ error: SupatypeError | null }>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Access auth state and methods. Must be used inside a <SupatypeProvider>.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```tsx
|
|
44
|
+
* function LoginButton() {
|
|
45
|
+
* const { user, signIn, signOut } = useAuth()
|
|
46
|
+
* if (user) return <button onClick={signOut}>Sign out</button>
|
|
47
|
+
* return <button onClick={() => signIn({ email, password })}>Sign in</button>
|
|
48
|
+
* }
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export function useAuth(): UseAuthReturn {
|
|
52
|
+
const client = useSupatype()
|
|
53
|
+
const [user, setUser] = useState<User | null>(null)
|
|
54
|
+
const [session, setSession] = useState<Session | null>(null)
|
|
55
|
+
const [loading, setLoading] = useState(true)
|
|
56
|
+
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
// Seed from current session
|
|
59
|
+
void client.auth.getSession().then(({ data }) => {
|
|
60
|
+
setSession(data.session)
|
|
61
|
+
setUser(data.session?.user ?? null)
|
|
62
|
+
setLoading(false)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
// Subscribe to future changes
|
|
66
|
+
const { data: { subscription } } = client.auth.onAuthStateChange(
|
|
67
|
+
(_event: AuthChangeEvent, newSession: Session | null) => {
|
|
68
|
+
setSession(newSession)
|
|
69
|
+
setUser(newSession?.user ?? null)
|
|
70
|
+
},
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
return () => subscription.unsubscribe()
|
|
74
|
+
}, [client])
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
user,
|
|
78
|
+
session,
|
|
79
|
+
loading,
|
|
80
|
+
signUp: (creds) => client.auth.signUp(creds),
|
|
81
|
+
signIn: (creds) => client.auth.signInWithPassword(creds),
|
|
82
|
+
signInWithOAuth: (opts) => client.auth.signInWithOAuth(opts),
|
|
83
|
+
signInWithOtp: (opts) => client.auth.signInWithOtp(opts),
|
|
84
|
+
signOut: () => client.auth.signOut(),
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { useState, useCallback } from "react"
|
|
4
|
+
import type { AnyDatabase, SupatypeError } from "@supatype/client"
|
|
5
|
+
import { useSupatype } from "./context.js"
|
|
6
|
+
|
|
7
|
+
export interface FunctionCallOptions {
|
|
8
|
+
/** HTTP method. Default: POST */
|
|
9
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | undefined
|
|
10
|
+
/** Extra request headers */
|
|
11
|
+
headers?: Record<string, string> | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface UseFunctionResult<TResponse> {
|
|
15
|
+
/** Invoke the function with optional options */
|
|
16
|
+
invoke(body?: unknown, options?: FunctionCallOptions | undefined): Promise<{ data: TResponse | null; error: SupatypeError | null }>
|
|
17
|
+
/** Most recent response data */
|
|
18
|
+
data: TResponse | null
|
|
19
|
+
/** Most recent error */
|
|
20
|
+
error: SupatypeError | null
|
|
21
|
+
/** True while the function is executing */
|
|
22
|
+
loading: boolean
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Invoke a Supatype Edge Function.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* const { invoke, data, loading, error } = useFunction<OrderResult>('process-order')
|
|
31
|
+
*
|
|
32
|
+
* const handleSubmit = async () => {
|
|
33
|
+
* const { data, error } = await invoke({ items: cart, address })
|
|
34
|
+
* if (data) router.push(`/orders/${data.orderId}`)
|
|
35
|
+
* }
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function useFunction<
|
|
39
|
+
TResponse = unknown,
|
|
40
|
+
TDatabase extends AnyDatabase = AnyDatabase,
|
|
41
|
+
>(
|
|
42
|
+
functionName: string,
|
|
43
|
+
): UseFunctionResult<TResponse> {
|
|
44
|
+
const client = useSupatype<TDatabase>()
|
|
45
|
+
const [data, setData] = useState<TResponse | null>(null)
|
|
46
|
+
const [error, setError] = useState<SupatypeError | null>(null)
|
|
47
|
+
const [loading, setLoading] = useState(false)
|
|
48
|
+
|
|
49
|
+
const invoke = useCallback(
|
|
50
|
+
async (
|
|
51
|
+
body?: unknown,
|
|
52
|
+
options?: FunctionCallOptions | undefined,
|
|
53
|
+
) => {
|
|
54
|
+
setLoading(true)
|
|
55
|
+
setError(null)
|
|
56
|
+
|
|
57
|
+
const result = await client.functions.invoke(functionName, {
|
|
58
|
+
...options,
|
|
59
|
+
...(body !== undefined ? { body } : {}),
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
setLoading(false)
|
|
63
|
+
setData(result.data as TResponse | null)
|
|
64
|
+
if (result.error !== null) setError(result.error)
|
|
65
|
+
return result as { data: TResponse | null; error: SupatypeError | null }
|
|
66
|
+
},
|
|
67
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
68
|
+
[client, functionName],
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return { invoke, data, error, loading }
|
|
72
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { useState, useEffect, useRef } from "react"
|
|
4
|
+
|
|
5
|
+
export interface UseLivePreviewOptions<TData> {
|
|
6
|
+
/** The initial/server data to display when not in preview mode. */
|
|
7
|
+
initialData: TData
|
|
8
|
+
/** Optional model name filter — only accept preview data for this model. */
|
|
9
|
+
model?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface UseLivePreviewResult<TData> {
|
|
13
|
+
/** The current data — either live preview data or initial data. */
|
|
14
|
+
data: TData
|
|
15
|
+
/** Whether the component is currently receiving live preview updates. */
|
|
16
|
+
isPreview: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Hook for receiving live preview updates from the Supatype admin panel.
|
|
21
|
+
*
|
|
22
|
+
* When the admin panel's edit view is open with Live Preview enabled,
|
|
23
|
+
* it sends `postMessage` events with form data as the editor types.
|
|
24
|
+
* This hook receives those events and returns the live data.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* function BlogPost({ post }: { post: Post }) {
|
|
29
|
+
* const { data, isPreview } = useLivePreview({ initialData: post, model: "post" })
|
|
30
|
+
* return (
|
|
31
|
+
* <article>
|
|
32
|
+
* {isPreview && <div className="preview-badge">Preview</div>}
|
|
33
|
+
* <h1>{data.title}</h1>
|
|
34
|
+
* <div>{data.body}</div>
|
|
35
|
+
* </article>
|
|
36
|
+
* )
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export function useLivePreview<TData>(
|
|
41
|
+
opts: UseLivePreviewOptions<TData>,
|
|
42
|
+
): UseLivePreviewResult<TData> {
|
|
43
|
+
const [previewData, setPreviewData] = useState<TData | null>(null)
|
|
44
|
+
const initialRef = useRef(opts.initialData)
|
|
45
|
+
initialRef.current = opts.initialData
|
|
46
|
+
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
const handler = (event: MessageEvent) => {
|
|
49
|
+
if (typeof event.data !== "object" || event.data === null) return
|
|
50
|
+
const msg = event.data as { type?: string; model?: string; data?: unknown }
|
|
51
|
+
if (msg.type !== "supatype:live-preview") return
|
|
52
|
+
if (opts.model && msg.model !== opts.model) return
|
|
53
|
+
setPreviewData(msg.data as TData)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
window.addEventListener("message", handler)
|
|
57
|
+
return () => { window.removeEventListener("message", handler) }
|
|
58
|
+
}, [opts.model])
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
data: previewData ?? initialRef.current,
|
|
62
|
+
isPreview: previewData !== null,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { useState, useCallback } from "react"
|
|
4
|
+
import type { AnyDatabase, SupatypeError } from "@supatype/client"
|
|
5
|
+
import { useSupatype } from "./context.js"
|
|
6
|
+
|
|
7
|
+
export type MutationOperation = "insert" | "update" | "delete" | "upsert"
|
|
8
|
+
|
|
9
|
+
export interface MutationOptions {
|
|
10
|
+
/** Simple equality filters for update/delete operations */
|
|
11
|
+
filter?: Record<string, unknown> | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface UseMutationResult<TRow> {
|
|
15
|
+
mutate(
|
|
16
|
+
data?: Record<string, unknown> | Record<string, unknown>[] | undefined,
|
|
17
|
+
options?: MutationOptions | undefined,
|
|
18
|
+
): Promise<{ data: TRow[] | null; error: SupatypeError | null; count: number | null }>
|
|
19
|
+
loading: boolean
|
|
20
|
+
error: SupatypeError | null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Perform insert, update, delete, or upsert on a table.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* const { mutate: createPost, loading } = useMutation('posts', 'insert')
|
|
29
|
+
* await createPost({ title: 'Hello', status: 'draft' })
|
|
30
|
+
*
|
|
31
|
+
* const { mutate: deletePost } = useMutation('posts', 'delete')
|
|
32
|
+
* await deletePost(undefined, { filter: { id: postId } })
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export function useMutation<
|
|
36
|
+
TDatabase extends AnyDatabase = AnyDatabase,
|
|
37
|
+
TTable extends keyof TDatabase["public"]["Tables"] & string = keyof TDatabase["public"]["Tables"] & string,
|
|
38
|
+
TRow = TDatabase["public"]["Tables"][TTable]["Row"],
|
|
39
|
+
>(
|
|
40
|
+
table: TTable,
|
|
41
|
+
operation: MutationOperation,
|
|
42
|
+
): UseMutationResult<TRow> {
|
|
43
|
+
const client = useSupatype<TDatabase>()
|
|
44
|
+
const [loading, setLoading] = useState(false)
|
|
45
|
+
const [error, setError] = useState<SupatypeError | null>(null)
|
|
46
|
+
|
|
47
|
+
const mutate = useCallback(
|
|
48
|
+
async (
|
|
49
|
+
data?: Record<string, unknown> | Record<string, unknown>[] | undefined,
|
|
50
|
+
options?: MutationOptions | undefined,
|
|
51
|
+
) => {
|
|
52
|
+
setLoading(true)
|
|
53
|
+
setError(null)
|
|
54
|
+
|
|
55
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
56
|
+
const tableClient = client.from(table) as any
|
|
57
|
+
|
|
58
|
+
let result: { data: TRow[] | null; error: SupatypeError | null; count: number | null }
|
|
59
|
+
|
|
60
|
+
if (operation === "insert") {
|
|
61
|
+
result = await tableClient.insert(data)
|
|
62
|
+
} else if (operation === "upsert") {
|
|
63
|
+
result = await tableClient.upsert(data)
|
|
64
|
+
} else if (operation === "update") {
|
|
65
|
+
let q = tableClient.update(data)
|
|
66
|
+
if (options?.filter !== undefined) {
|
|
67
|
+
for (const [col, val] of Object.entries(options.filter)) {
|
|
68
|
+
q = q.eq(col, val)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
result = await q
|
|
72
|
+
} else {
|
|
73
|
+
// delete
|
|
74
|
+
let q = tableClient.delete()
|
|
75
|
+
if (options?.filter !== undefined) {
|
|
76
|
+
for (const [col, val] of Object.entries(options.filter)) {
|
|
77
|
+
q = q.eq(col, val)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
result = await q
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
setLoading(false)
|
|
84
|
+
if (result.error !== null) setError(result.error)
|
|
85
|
+
return result
|
|
86
|
+
},
|
|
87
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
88
|
+
[client, table, operation],
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
return { mutate, loading, error }
|
|
92
|
+
}
|