@supatype/react 0.1.0-alpha.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/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/dist/context.d.ts +31 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +35 -0
- package/dist/context.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -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 +45 -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 +38 -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 +46 -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 +59 -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 +68 -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 +38 -0
- package/dist/useSubscription.js.map +1 -0
- package/package.json +31 -0
- package/src/context.tsx +44 -0
- package/src/index.ts +20 -0
- package/src/useAuth.ts +84 -0
- package/src/useFunction.ts +70 -0
- package/src/useLivePreview.ts +62 -0
- package/src/useMutation.ts +90 -0
- package/src/useQuery.ts +109 -0
- package/src/useSubscription.ts +70 -0
- package/tsconfig.json +14 -0
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useQuery.js","sourceRoot":"","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AAE,EAAE,OAAO,CAAC,eAAe,CAAC,CAAA;QAClF,CAAC;QACD,OAAO,GAAG,EAAE;YACV,IAAI,WAAW,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;gBACjC,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;gBAClC,WAAW,CAAC,OAAO,GAAG,IAAI,CAAA;YAC5B,CAAC;QACH,CAAC,CAAA;QACD,uDAAuD;IACzD,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;IAEb,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,OAAO,EAAE,EAAE,CAAA;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":"AACA,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,38 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
import { useSupatype } from "./context.js";
|
|
3
|
+
/**
|
|
4
|
+
* Subscribe to real-time row changes on a table.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```tsx
|
|
8
|
+
* useSubscription<Post>('posts-channel', {
|
|
9
|
+
* event: 'INSERT',
|
|
10
|
+
* table: 'posts',
|
|
11
|
+
* callback: (payload) => console.log('New post:', payload.new),
|
|
12
|
+
* })
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export function useSubscription(channelName, opts) {
|
|
16
|
+
const client = useSupatype();
|
|
17
|
+
const [status, setStatus] = useState("SUBSCRIBING");
|
|
18
|
+
// Stable ref so the effect doesn't re-run when the callback reference changes
|
|
19
|
+
const callbackRef = useRef(opts.callback);
|
|
20
|
+
callbackRef.current = opts.callback;
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
const channel = client.realtime
|
|
23
|
+
.channel(channelName)
|
|
24
|
+
.on("postgres_changes", {
|
|
25
|
+
event: opts.event ?? "*",
|
|
26
|
+
...(opts.schema !== undefined && { schema: opts.schema }),
|
|
27
|
+
...(opts.table !== undefined && { table: opts.table }),
|
|
28
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
29
|
+
}, (payload) => callbackRef.current(payload))
|
|
30
|
+
.subscribe((s) => setStatus(s));
|
|
31
|
+
return () => {
|
|
32
|
+
channel.unsubscribe();
|
|
33
|
+
};
|
|
34
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
35
|
+
}, [client, channelName, opts.event, opts.schema, opts.table, opts.filter]);
|
|
36
|
+
return { status };
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=useSubscription.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useSubscription.js","sourceRoot":"","sources":["../src/useSubscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEnD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;A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C,CAAC,CAAA;IAE3E,OAAO,EAAE,MAAM,EAAE,CAAA;AACnB,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@supatype/react",
|
|
3
|
+
"version": "0.1.0-alpha.6",
|
|
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.6"
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"react": ">=18"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/react": "^18",
|
|
22
|
+
"react": "^18",
|
|
23
|
+
"typescript": "^5"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsc --project tsconfig.json",
|
|
27
|
+
"dev": "tsc --project tsconfig.json --watch",
|
|
28
|
+
"typecheck": "tsc --project tsconfig.json --noEmit",
|
|
29
|
+
"clean": "rm -rf dist *.tsbuildinfo"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/context.tsx
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import React from "react"
|
|
2
|
+
import type { SupatypeClient, AnyDatabase } from "@supatype/client"
|
|
3
|
+
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5
|
+
export const SupatypeContext = React.createContext<SupatypeClient<any> | null>(null)
|
|
6
|
+
|
|
7
|
+
export interface SupatypeProviderProps {
|
|
8
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
9
|
+
client: SupatypeClient<any>
|
|
10
|
+
children: React.ReactNode
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Wrap your application with SupatypeProvider to make the client available
|
|
15
|
+
* via all Supatype hooks.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* const client = createClient({ url: '...', anonKey: '...' })
|
|
20
|
+
*
|
|
21
|
+
* function App() {
|
|
22
|
+
* return (
|
|
23
|
+
* <SupatypeProvider client={client}>
|
|
24
|
+
* <YourApp />
|
|
25
|
+
* </SupatypeProvider>
|
|
26
|
+
* )
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function SupatypeProvider({ client, children }: SupatypeProviderProps): React.ReactElement {
|
|
31
|
+
return React.createElement(SupatypeContext.Provider, { value: client }, children)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Access the Supatype client directly. Most callers should use the
|
|
36
|
+
* higher-level hooks (useAuth, useQuery, useMutation) instead.
|
|
37
|
+
*/
|
|
38
|
+
export function useSupatype<TDatabase extends AnyDatabase = AnyDatabase>(): SupatypeClient<TDatabase> {
|
|
39
|
+
const client = React.useContext(SupatypeContext) as SupatypeClient<TDatabase> | null
|
|
40
|
+
if (client === null) {
|
|
41
|
+
throw new Error("useSupatype must be used inside a <SupatypeProvider>")
|
|
42
|
+
}
|
|
43
|
+
return client
|
|
44
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
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"
|
package/src/useAuth.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { useState, useEffect } from "react"
|
|
2
|
+
import type { Session, User, AuthChangeEvent, SupatypeError } from "@supatype/client"
|
|
3
|
+
import { useSupatype } from "./context.js"
|
|
4
|
+
|
|
5
|
+
export interface UseAuthReturn {
|
|
6
|
+
/** The currently authenticated user, or null if not signed in. */
|
|
7
|
+
user: User | null
|
|
8
|
+
/** The current session (includes access token), or null. */
|
|
9
|
+
session: Session | null
|
|
10
|
+
/** True while loading the initial auth state. */
|
|
11
|
+
loading: boolean
|
|
12
|
+
/** Sign up with email and password. */
|
|
13
|
+
signUp(credentials: {
|
|
14
|
+
email: string
|
|
15
|
+
password: string
|
|
16
|
+
options?: { data?: Record<string, unknown> } | undefined
|
|
17
|
+
}): Promise<{ data: { session: Session | null; user: User | null }; error: SupatypeError | null }>
|
|
18
|
+
/** Sign in with email and password. */
|
|
19
|
+
signIn(credentials: {
|
|
20
|
+
email: string
|
|
21
|
+
password: string
|
|
22
|
+
}): Promise<{ data: { session: Session | null; user: User | null }; error: SupatypeError | null }>
|
|
23
|
+
/** Sign in via OAuth provider (returns redirect URL). */
|
|
24
|
+
signInWithOAuth(opts: {
|
|
25
|
+
provider: string
|
|
26
|
+
options?: { redirectTo?: string } | undefined
|
|
27
|
+
}): Promise<{ data: { url: string; provider: string }; error: SupatypeError | null }>
|
|
28
|
+
/** Sign in with a magic link (OTP) sent to the email. */
|
|
29
|
+
signInWithOtp(opts: {
|
|
30
|
+
email: string
|
|
31
|
+
options?: { emailRedirectTo?: string } | undefined
|
|
32
|
+
}): Promise<{ data: { messageId?: string | undefined }; error: SupatypeError | null }>
|
|
33
|
+
/** Sign out the current user. */
|
|
34
|
+
signOut(): Promise<{ error: SupatypeError | null }>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Access auth state and methods. Must be used inside a <SupatypeProvider>.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```tsx
|
|
42
|
+
* function LoginButton() {
|
|
43
|
+
* const { user, signIn, signOut } = useAuth()
|
|
44
|
+
* if (user) return <button onClick={signOut}>Sign out</button>
|
|
45
|
+
* return <button onClick={() => signIn({ email, password })}>Sign in</button>
|
|
46
|
+
* }
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export function useAuth(): UseAuthReturn {
|
|
50
|
+
const client = useSupatype()
|
|
51
|
+
const [user, setUser] = useState<User | null>(null)
|
|
52
|
+
const [session, setSession] = useState<Session | null>(null)
|
|
53
|
+
const [loading, setLoading] = useState(true)
|
|
54
|
+
|
|
55
|
+
useEffect(() => {
|
|
56
|
+
// Seed from current session
|
|
57
|
+
void client.auth.getSession().then(({ data }) => {
|
|
58
|
+
setSession(data.session)
|
|
59
|
+
setUser(data.session?.user ?? null)
|
|
60
|
+
setLoading(false)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
// Subscribe to future changes
|
|
64
|
+
const { data: { subscription } } = client.auth.onAuthStateChange(
|
|
65
|
+
(_event: AuthChangeEvent, newSession: Session | null) => {
|
|
66
|
+
setSession(newSession)
|
|
67
|
+
setUser(newSession?.user ?? null)
|
|
68
|
+
},
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return () => subscription.unsubscribe()
|
|
72
|
+
}, [client])
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
user,
|
|
76
|
+
session,
|
|
77
|
+
loading,
|
|
78
|
+
signUp: (creds) => client.auth.signUp(creds),
|
|
79
|
+
signIn: (creds) => client.auth.signInWithPassword(creds),
|
|
80
|
+
signInWithOAuth: (opts) => client.auth.signInWithOAuth(opts),
|
|
81
|
+
signInWithOtp: (opts) => client.auth.signInWithOtp(opts),
|
|
82
|
+
signOut: () => client.auth.signOut(),
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { useState, useCallback } from "react"
|
|
2
|
+
import type { AnyDatabase, SupatypeError } from "@supatype/client"
|
|
3
|
+
import { useSupatype } from "./context.js"
|
|
4
|
+
|
|
5
|
+
export interface FunctionCallOptions {
|
|
6
|
+
/** HTTP method. Default: POST */
|
|
7
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | undefined
|
|
8
|
+
/** Extra request headers */
|
|
9
|
+
headers?: Record<string, string> | undefined
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface UseFunctionResult<TResponse> {
|
|
13
|
+
/** Invoke the function with optional options */
|
|
14
|
+
invoke(body?: unknown, options?: FunctionCallOptions | undefined): Promise<{ data: TResponse | null; error: SupatypeError | null }>
|
|
15
|
+
/** Most recent response data */
|
|
16
|
+
data: TResponse | null
|
|
17
|
+
/** Most recent error */
|
|
18
|
+
error: SupatypeError | null
|
|
19
|
+
/** True while the function is executing */
|
|
20
|
+
loading: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Invoke a Supatype Edge Function.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* const { invoke, data, loading, error } = useFunction<OrderResult>('process-order')
|
|
29
|
+
*
|
|
30
|
+
* const handleSubmit = async () => {
|
|
31
|
+
* const { data, error } = await invoke({ items: cart, address })
|
|
32
|
+
* if (data) router.push(`/orders/${data.orderId}`)
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export function useFunction<
|
|
37
|
+
TResponse = unknown,
|
|
38
|
+
TDatabase extends AnyDatabase = AnyDatabase,
|
|
39
|
+
>(
|
|
40
|
+
functionName: string,
|
|
41
|
+
): UseFunctionResult<TResponse> {
|
|
42
|
+
const client = useSupatype<TDatabase>()
|
|
43
|
+
const [data, setData] = useState<TResponse | null>(null)
|
|
44
|
+
const [error, setError] = useState<SupatypeError | null>(null)
|
|
45
|
+
const [loading, setLoading] = useState(false)
|
|
46
|
+
|
|
47
|
+
const invoke = useCallback(
|
|
48
|
+
async (
|
|
49
|
+
body?: unknown,
|
|
50
|
+
options?: FunctionCallOptions | undefined,
|
|
51
|
+
) => {
|
|
52
|
+
setLoading(true)
|
|
53
|
+
setError(null)
|
|
54
|
+
|
|
55
|
+
const result = await client.functions.invoke<TResponse>(functionName, {
|
|
56
|
+
...options,
|
|
57
|
+
...(body !== undefined ? { body } : {}),
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
setLoading(false)
|
|
61
|
+
setData(result.data)
|
|
62
|
+
if (result.error !== null) setError(result.error)
|
|
63
|
+
return result
|
|
64
|
+
},
|
|
65
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
66
|
+
[client, functionName],
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
return { invoke, data, error, loading }
|
|
70
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { useState, useEffect, useRef } from "react"
|
|
2
|
+
|
|
3
|
+
export interface UseLivePreviewOptions<TData> {
|
|
4
|
+
/** The initial/server data to display when not in preview mode. */
|
|
5
|
+
initialData: TData
|
|
6
|
+
/** Optional model name filter — only accept preview data for this model. */
|
|
7
|
+
model?: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface UseLivePreviewResult<TData> {
|
|
11
|
+
/** The current data — either live preview data or initial data. */
|
|
12
|
+
data: TData
|
|
13
|
+
/** Whether the component is currently receiving live preview updates. */
|
|
14
|
+
isPreview: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Hook for receiving live preview updates from the Supatype admin panel.
|
|
19
|
+
*
|
|
20
|
+
* When the admin panel's edit view is open with Live Preview enabled,
|
|
21
|
+
* it sends `postMessage` events with form data as the editor types.
|
|
22
|
+
* This hook receives those events and returns the live data.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* function BlogPost({ post }: { post: Post }) {
|
|
27
|
+
* const { data, isPreview } = useLivePreview({ initialData: post, model: "post" })
|
|
28
|
+
* return (
|
|
29
|
+
* <article>
|
|
30
|
+
* {isPreview && <div className="preview-badge">Preview</div>}
|
|
31
|
+
* <h1>{data.title}</h1>
|
|
32
|
+
* <div>{data.body}</div>
|
|
33
|
+
* </article>
|
|
34
|
+
* )
|
|
35
|
+
* }
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function useLivePreview<TData>(
|
|
39
|
+
opts: UseLivePreviewOptions<TData>,
|
|
40
|
+
): UseLivePreviewResult<TData> {
|
|
41
|
+
const [previewData, setPreviewData] = useState<TData | null>(null)
|
|
42
|
+
const initialRef = useRef(opts.initialData)
|
|
43
|
+
initialRef.current = opts.initialData
|
|
44
|
+
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
const handler = (event: MessageEvent) => {
|
|
47
|
+
if (typeof event.data !== "object" || event.data === null) return
|
|
48
|
+
const msg = event.data as { type?: string; model?: string; data?: unknown }
|
|
49
|
+
if (msg.type !== "supatype:live-preview") return
|
|
50
|
+
if (opts.model && msg.model !== opts.model) return
|
|
51
|
+
setPreviewData(msg.data as TData)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
window.addEventListener("message", handler)
|
|
55
|
+
return () => { window.removeEventListener("message", handler) }
|
|
56
|
+
}, [opts.model])
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
data: previewData ?? initialRef.current,
|
|
60
|
+
isPreview: previewData !== null,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { useState, useCallback } from "react"
|
|
2
|
+
import type { AnyDatabase, SupatypeError } from "@supatype/client"
|
|
3
|
+
import { useSupatype } from "./context.js"
|
|
4
|
+
|
|
5
|
+
export type MutationOperation = "insert" | "update" | "delete" | "upsert"
|
|
6
|
+
|
|
7
|
+
export interface MutationOptions {
|
|
8
|
+
/** Simple equality filters for update/delete operations */
|
|
9
|
+
filter?: Record<string, unknown> | undefined
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface UseMutationResult<TRow> {
|
|
13
|
+
mutate(
|
|
14
|
+
data?: Record<string, unknown> | Record<string, unknown>[] | undefined,
|
|
15
|
+
options?: MutationOptions | undefined,
|
|
16
|
+
): Promise<{ data: TRow[] | null; error: SupatypeError | null; count: number | null }>
|
|
17
|
+
loading: boolean
|
|
18
|
+
error: SupatypeError | null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Perform insert, update, delete, or upsert on a table.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* const { mutate: createPost, loading } = useMutation('posts', 'insert')
|
|
27
|
+
* await createPost({ title: 'Hello', status: 'draft' })
|
|
28
|
+
*
|
|
29
|
+
* const { mutate: deletePost } = useMutation('posts', 'delete')
|
|
30
|
+
* await deletePost(undefined, { filter: { id: postId } })
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export function useMutation<
|
|
34
|
+
TDatabase extends AnyDatabase = AnyDatabase,
|
|
35
|
+
TTable extends keyof TDatabase["public"]["Tables"] & string = keyof TDatabase["public"]["Tables"] & string,
|
|
36
|
+
TRow = TDatabase["public"]["Tables"][TTable]["Row"],
|
|
37
|
+
>(
|
|
38
|
+
table: TTable,
|
|
39
|
+
operation: MutationOperation,
|
|
40
|
+
): UseMutationResult<TRow> {
|
|
41
|
+
const client = useSupatype<TDatabase>()
|
|
42
|
+
const [loading, setLoading] = useState(false)
|
|
43
|
+
const [error, setError] = useState<SupatypeError | null>(null)
|
|
44
|
+
|
|
45
|
+
const mutate = useCallback(
|
|
46
|
+
async (
|
|
47
|
+
data?: Record<string, unknown> | Record<string, unknown>[] | undefined,
|
|
48
|
+
options?: MutationOptions | undefined,
|
|
49
|
+
) => {
|
|
50
|
+
setLoading(true)
|
|
51
|
+
setError(null)
|
|
52
|
+
|
|
53
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
54
|
+
const tableClient = client.from(table) as any
|
|
55
|
+
|
|
56
|
+
let result: { data: TRow[] | null; error: SupatypeError | null; count: number | null }
|
|
57
|
+
|
|
58
|
+
if (operation === "insert") {
|
|
59
|
+
result = await tableClient.insert(data)
|
|
60
|
+
} else if (operation === "upsert") {
|
|
61
|
+
result = await tableClient.upsert(data)
|
|
62
|
+
} else if (operation === "update") {
|
|
63
|
+
let q = tableClient.update(data)
|
|
64
|
+
if (options?.filter !== undefined) {
|
|
65
|
+
for (const [col, val] of Object.entries(options.filter)) {
|
|
66
|
+
q = q.eq(col, val)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
result = await q
|
|
70
|
+
} else {
|
|
71
|
+
// delete
|
|
72
|
+
let q = tableClient.delete()
|
|
73
|
+
if (options?.filter !== undefined) {
|
|
74
|
+
for (const [col, val] of Object.entries(options.filter)) {
|
|
75
|
+
q = q.eq(col, val)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
result = await q
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
setLoading(false)
|
|
82
|
+
if (result.error !== null) setError(result.error)
|
|
83
|
+
return result
|
|
84
|
+
},
|
|
85
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
86
|
+
[client, table, operation],
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
return { mutate, loading, error }
|
|
90
|
+
}
|
package/src/useQuery.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { useState, useEffect, useCallback, useRef } from "react"
|
|
2
|
+
import type { AnyDatabase, SupatypeError } from "@supatype/client"
|
|
3
|
+
import { useSupatype } from "./context.js"
|
|
4
|
+
|
|
5
|
+
export interface UseQueryOptions {
|
|
6
|
+
/** PostgREST select expression (default: '*') */
|
|
7
|
+
select?: string | undefined
|
|
8
|
+
/** Simple equality filters keyed by column name */
|
|
9
|
+
filter?: Record<string, unknown> | undefined
|
|
10
|
+
/** Column to order by */
|
|
11
|
+
order?: { column: string; ascending?: boolean | undefined } | undefined
|
|
12
|
+
/** Maximum number of rows to return */
|
|
13
|
+
limit?: number | undefined
|
|
14
|
+
/** Row offset (for pagination) */
|
|
15
|
+
offset?: number | undefined
|
|
16
|
+
/** Set to false to skip the query (useful for conditional fetching) */
|
|
17
|
+
enabled?: boolean | undefined
|
|
18
|
+
/** Re-fetch interval in milliseconds */
|
|
19
|
+
refetchInterval?: number | undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface UseQueryResult<TRow> {
|
|
23
|
+
data: TRow[] | null
|
|
24
|
+
error: SupatypeError | null
|
|
25
|
+
count: number | null
|
|
26
|
+
loading: boolean
|
|
27
|
+
refetch(): void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Fetch rows from a table with automatic re-execution when options change.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```tsx
|
|
35
|
+
* const { data: posts, loading } = useQuery('posts', {
|
|
36
|
+
* filter: { status: 'published' },
|
|
37
|
+
* order: { column: 'created_at', ascending: false },
|
|
38
|
+
* limit: 10,
|
|
39
|
+
* })
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function useQuery<
|
|
43
|
+
TDatabase extends AnyDatabase = AnyDatabase,
|
|
44
|
+
TTable extends keyof TDatabase["public"]["Tables"] & string = keyof TDatabase["public"]["Tables"] & string,
|
|
45
|
+
TRow = TDatabase["public"]["Tables"][TTable]["Row"],
|
|
46
|
+
>(
|
|
47
|
+
table: TTable,
|
|
48
|
+
options?: UseQueryOptions | undefined,
|
|
49
|
+
): UseQueryResult<TRow> {
|
|
50
|
+
const client = useSupatype<TDatabase>()
|
|
51
|
+
const [data, setData] = useState<TRow[] | null>(null)
|
|
52
|
+
const [error, setError] = useState<SupatypeError | null>(null)
|
|
53
|
+
const [count, setCount] = useState<number | null>(null)
|
|
54
|
+
const [loading, setLoading] = useState(true)
|
|
55
|
+
|
|
56
|
+
// Stable reference to options for the effect dep
|
|
57
|
+
const optionsJson = JSON.stringify(options)
|
|
58
|
+
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
|
59
|
+
|
|
60
|
+
const execute = useCallback(async () => {
|
|
61
|
+
if (options?.enabled === false) {
|
|
62
|
+
setLoading(false)
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
setLoading(true)
|
|
66
|
+
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
68
|
+
let query: any = (client.from(table) as any).select(options?.select ?? "*")
|
|
69
|
+
|
|
70
|
+
if (options?.filter !== undefined) {
|
|
71
|
+
for (const [col, val] of Object.entries(options.filter)) {
|
|
72
|
+
query = query.eq(col, val)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (options?.order !== undefined) {
|
|
76
|
+
query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
|
|
77
|
+
}
|
|
78
|
+
if (options?.limit !== undefined) {
|
|
79
|
+
query = query.limit(options.limit)
|
|
80
|
+
}
|
|
81
|
+
if (options?.offset !== undefined && options.limit !== undefined) {
|
|
82
|
+
query = query.range(options.offset, options.offset + options.limit - 1)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const result = (await query) as { data: TRow[] | null; error: SupatypeError | null; count: number | null }
|
|
86
|
+
setData(result.data)
|
|
87
|
+
setError(result.error)
|
|
88
|
+
setCount(result.count)
|
|
89
|
+
setLoading(false)
|
|
90
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
91
|
+
}, [client, table, optionsJson])
|
|
92
|
+
|
|
93
|
+
useEffect(() => {
|
|
94
|
+
void execute()
|
|
95
|
+
|
|
96
|
+
if (options?.refetchInterval !== undefined) {
|
|
97
|
+
intervalRef.current = setInterval(() => void execute(), options.refetchInterval)
|
|
98
|
+
}
|
|
99
|
+
return () => {
|
|
100
|
+
if (intervalRef.current !== null) {
|
|
101
|
+
clearInterval(intervalRef.current)
|
|
102
|
+
intervalRef.current = null
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
106
|
+
}, [execute])
|
|
107
|
+
|
|
108
|
+
return { data, error, count, loading, refetch: () => void execute() }
|
|
109
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react"
|
|
2
|
+
import type { RealtimeEvent, RealtimePayload, ChannelStatus } from "@supatype/client"
|
|
3
|
+
import { useSupatype } from "./context.js"
|
|
4
|
+
|
|
5
|
+
export type SubscriptionStatus = ChannelStatus
|
|
6
|
+
|
|
7
|
+
export interface UseSubscriptionOptions<TRow> {
|
|
8
|
+
/** Postgres event to listen for. Defaults to "*" (all events). */
|
|
9
|
+
event?: RealtimeEvent | undefined
|
|
10
|
+
/** Table to listen on. Defaults to the channel name. */
|
|
11
|
+
table?: string | undefined
|
|
12
|
+
/** PostgREST filter expression (e.g. "id=eq.1"). */
|
|
13
|
+
filter?: string | undefined
|
|
14
|
+
/** Schema to listen on. Defaults to "public". */
|
|
15
|
+
schema?: string | undefined
|
|
16
|
+
/** Called on every change event matching the subscription. */
|
|
17
|
+
callback: (payload: RealtimePayload<TRow>) => void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface UseSubscriptionResult {
|
|
21
|
+
/** Current subscription status. */
|
|
22
|
+
status: SubscriptionStatus
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Subscribe to real-time row changes on a table.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* useSubscription<Post>('posts-channel', {
|
|
31
|
+
* event: 'INSERT',
|
|
32
|
+
* table: 'posts',
|
|
33
|
+
* callback: (payload) => console.log('New post:', payload.new),
|
|
34
|
+
* })
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export function useSubscription<TRow = Record<string, unknown>>(
|
|
38
|
+
channelName: string,
|
|
39
|
+
opts: UseSubscriptionOptions<TRow>,
|
|
40
|
+
): UseSubscriptionResult {
|
|
41
|
+
const client = useSupatype()
|
|
42
|
+
const [status, setStatus] = useState<SubscriptionStatus>("SUBSCRIBING")
|
|
43
|
+
|
|
44
|
+
// Stable ref so the effect doesn't re-run when the callback reference changes
|
|
45
|
+
const callbackRef = useRef(opts.callback)
|
|
46
|
+
callbackRef.current = opts.callback
|
|
47
|
+
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
const channel = client.realtime
|
|
50
|
+
.channel<TRow>(channelName)
|
|
51
|
+
.on(
|
|
52
|
+
"postgres_changes",
|
|
53
|
+
{
|
|
54
|
+
event: opts.event ?? "*",
|
|
55
|
+
...(opts.schema !== undefined && { schema: opts.schema }),
|
|
56
|
+
...(opts.table !== undefined && { table: opts.table }),
|
|
57
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
58
|
+
},
|
|
59
|
+
(payload) => callbackRef.current(payload),
|
|
60
|
+
)
|
|
61
|
+
.subscribe((s) => setStatus(s))
|
|
62
|
+
|
|
63
|
+
return () => {
|
|
64
|
+
channel.unsubscribe()
|
|
65
|
+
}
|
|
66
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
67
|
+
}, [client, channelName, opts.event, opts.schema, opts.table, opts.filter])
|
|
68
|
+
|
|
69
|
+
return { status }
|
|
70
|
+
}
|