@supatype/react 0.3.5 → 0.7.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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +19 -0
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/RichText.d.ts +9 -6
- package/dist/RichText.d.ts.map +1 -1
- package/dist/RichText.js +27 -10
- package/dist/RichText.js.map +1 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +2 -1
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/live-preview-message.d.ts +19 -0
- package/dist/live-preview-message.d.ts.map +1 -0
- package/dist/live-preview-message.js +45 -0
- package/dist/live-preview-message.js.map +1 -0
- package/dist/useAuth.d.ts +7 -2
- package/dist/useAuth.d.ts.map +1 -1
- package/dist/useAuth.js +15 -10
- package/dist/useAuth.js.map +1 -1
- package/dist/useFunction.d.ts.map +1 -1
- package/dist/useFunction.js +15 -9
- package/dist/useFunction.js.map +1 -1
- package/dist/useLivePreview.d.ts +12 -1
- package/dist/useLivePreview.d.ts.map +1 -1
- package/dist/useLivePreview.js +18 -12
- package/dist/useLivePreview.js.map +1 -1
- package/dist/useMutation.d.ts +11 -6
- package/dist/useMutation.d.ts.map +1 -1
- package/dist/useMutation.js +14 -30
- package/dist/useMutation.js.map +1 -1
- package/dist/useQuery.d.ts.map +1 -1
- package/dist/useQuery.js +5 -6
- package/dist/useQuery.js.map +1 -1
- package/package.json +10 -5
- package/src/RichText.tsx +32 -19
- package/src/context.tsx +3 -2
- package/src/index.ts +1 -0
- package/src/live-preview-message.ts +52 -0
- package/src/useAuth.ts +21 -12
- package/src/useFunction.ts +13 -9
- package/src/useLivePreview.ts +26 -13
- package/src/useMutation.ts +21 -34
- package/src/useQuery.ts +8 -9
- package/tests/RichText.test.tsx +77 -0
- package/tests/tsconfig.json +9 -0
- package/tests/useAuth-redirect.test.tsx +89 -0
- package/tests/useAuth-signup.test.tsx +61 -0
- package/tests/useLivePreview-origin.test.tsx +108 -0
- package/tests/useMutation-requests.test.tsx +188 -0
- package/tests/useSubscription-status.test.tsx +48 -0
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
package/dist/useMutation.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMutation.js","sourceRoot":"","sources":["../src/useMutation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAA;AAEZ,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAE7C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"useMutation.js","sourceRoot":"","sources":["../src/useMutation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAA;AAEZ,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAE7C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAAE,WAAW,EAAgD,MAAM,2BAA2B,CAAA;AAuBrG;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,WAAW,CAKzB,KAAa,EACb,SAA4B;IAE5B,MAAM,MAAM,GAAG,WAAW,EAAa,CAAA;IACvC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAA;IAC7C,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,QAAQ,CAAuB,IAAI,CAAC,CAAA;IAE9D,MAAM,MAAM,GAAG,WAAW,CACxB,KAAK,EACH,IAAsE,EACtE,OAAqC,EACrC,EAAE;QACF,UAAU,CAAC,IAAI,CAAC,CAAA;QAChB,QAAQ,CAAC,IAAI,CAAC,CAAA;QACd,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO,CAAA;YAChC,MAAM,MAAM,GAAG,MAAM,WAAW,CAAO,MAAmB,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE;gBACnG,GAAG,CAAC,OAAO,KAAK,SAAS,IAAI,EAAE,OAAO,EAAE,CAAC;aAC1C,CAAC,CAAA;YACF,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI;gBAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACjD,OAAO,MAAM,CAAA;QACf,CAAC;gBAAS,CAAC;YACT,UAAU,CAAC,KAAK,CAAC,CAAA;QACnB,CAAC;IACH,CAAC;IACD,uDAAuD;IACvD,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,CAC3B,CAAA;IAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAA;AACnC,CAAC"}
|
package/dist/useQuery.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAa,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AAKnH,MAAM,WAAW,eAAe;IAC9B,iDAAiD;IACjD,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAA;IAC5C,yBAAyB;IACzB,KAAK,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;KAAE,GAAG,SAAS,CAAA;IACvE,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,kCAAkC;IAClC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,uEAAuE;IACvE,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC7B,wCAAwC;IACxC,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACpC,kFAAkF;IAClF,KAAK,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAA;IACrC;;;;;;;;;;;;;OAaG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;CAC5B;AAED,MAAM,WAAW,cAAc,CAAC,IAAI;IAClC,IAAI,EAAE,IAAI,EAAE,GAAG,IAAI,CAAA;IACnB,KAAK,EAAE,aAAa,GAAG,IAAI,CAAA;IAC3B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,IAAI,IAAI,CAAA;CAChB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CACtB,SAAS,SAAS,WAAW,GAAG,iBAAiB,EACjD,MAAM,SAAS,MAAM,SAAS,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,GAAG,MAAM,GAAG,MAAM,SAAS,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,GAAG,MAAM,EAC1G,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,EAEnD,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,GACpC,cAAc,CAAC,IAAI,CAAC,CA+EtB"}
|
package/dist/useQuery.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { useState, useEffect, useCallback, useRef } from "react";
|
|
3
3
|
import { onIdentityChange } from "@supatype/client";
|
|
4
4
|
import { useSupatype } from "./context.js";
|
|
5
|
+
import { isRowsOf } from "@supatype/client/bindings";
|
|
5
6
|
/**
|
|
6
7
|
* Fetch rows from a table with automatic re-execution when options change.
|
|
7
8
|
*
|
|
@@ -29,13 +30,11 @@ export function useQuery(table, options) {
|
|
|
29
30
|
return;
|
|
30
31
|
}
|
|
31
32
|
setLoading(true);
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
33
|
+
// Through the untyped client: the generated row types do not survive a table name known only
|
|
34
|
+
// at run time, so the rows are typed as `TRow` once they arrive.
|
|
35
35
|
const source = client.from(table);
|
|
36
36
|
// A draft read is the same request against a different schema, so it branches here rather than
|
|
37
37
|
// duplicating every filter below.
|
|
38
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
39
38
|
let query = (options?.draft === true ? source.draft() : source).select(options?.select ?? "*");
|
|
40
39
|
if (options?.filter !== undefined) {
|
|
41
40
|
for (const [col, val] of Object.entries(options.filter)) {
|
|
@@ -54,8 +53,8 @@ export function useQuery(table, options) {
|
|
|
54
53
|
if (options?.cache !== undefined) {
|
|
55
54
|
query = query.cache(options.cache);
|
|
56
55
|
}
|
|
57
|
-
const result =
|
|
58
|
-
setData(result.data);
|
|
56
|
+
const result = await query;
|
|
57
|
+
setData(isRowsOf(result.data) ? result.data : null);
|
|
59
58
|
setError(result.error);
|
|
60
59
|
setCount(result.count);
|
|
61
60
|
setLoading(false);
|
package/dist/useQuery.js.map
CHANGED
|
@@ -1 +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,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"useQuery.js","sourceRoot":"","sources":["../src/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AAO,EAAE,GAAG,EAAE,CAAC,KAAK,OAAO,EAAE,EAAE,CAAA;AACvE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supatype/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Supatype React hooks: useAuth, useQuery, useMutation, SupatypeProvider",
|
|
6
6
|
"type": "module",
|
|
@@ -13,21 +13,26 @@
|
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
|
-
"@supatype/
|
|
17
|
-
"@supatype/
|
|
16
|
+
"@supatype/client": "0.7.0",
|
|
17
|
+
"@supatype/common": "0.7.0"
|
|
18
18
|
},
|
|
19
19
|
"peerDependencies": {
|
|
20
20
|
"react": ">=18"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
+
"@types/node": "^22",
|
|
23
24
|
"@types/react": "^18",
|
|
25
|
+
"@types/react-test-renderer": "^18",
|
|
24
26
|
"react": "^18",
|
|
25
|
-
"
|
|
27
|
+
"react-test-renderer": "^18",
|
|
28
|
+
"typescript": "^5",
|
|
29
|
+
"vitest": "^4.0.18"
|
|
26
30
|
},
|
|
27
31
|
"scripts": {
|
|
28
32
|
"build": "tsc --project tsconfig.json",
|
|
29
33
|
"dev": "tsc --project tsconfig.json --watch",
|
|
30
|
-
"typecheck": "tsc --project tsconfig.json --noEmit",
|
|
34
|
+
"typecheck": "tsc --project tests/tsconfig.json --noEmit",
|
|
35
|
+
"test": "vitest run",
|
|
31
36
|
"clean": "rm -rf dist *.tsbuildinfo"
|
|
32
37
|
}
|
|
33
38
|
}
|
package/src/RichText.tsx
CHANGED
|
@@ -1,31 +1,44 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createElement, type ReactElement, type ReactNode } from "react"
|
|
2
|
+
import {
|
|
3
|
+
richTextTree,
|
|
4
|
+
type RichTextAttributes,
|
|
5
|
+
type RichTextChild,
|
|
6
|
+
type RichTextContent,
|
|
7
|
+
} from "@supatype/common/richtext"
|
|
2
8
|
|
|
3
9
|
export interface RichTextProps {
|
|
4
|
-
/** Lexical
|
|
5
|
-
content:
|
|
10
|
+
/** A saved Lexical document: the editor state (`{ root }`), its root node, a list of nodes, or null. */
|
|
11
|
+
content: RichTextContent
|
|
6
12
|
/** Optional CSS class applied to the wrapper element. */
|
|
7
13
|
className?: string
|
|
8
14
|
/** Wrapper element tag. Defaults to `"div"`. */
|
|
9
15
|
as?: "div" | "article" | "section" | "aside" | "main"
|
|
10
16
|
}
|
|
11
17
|
|
|
18
|
+
/** React's names for the two attributes that differ from HTML, in the order the walker set them. */
|
|
19
|
+
function reactProps(attributes: RichTextAttributes, key: number): Record<string, unknown> {
|
|
20
|
+
const props: Record<string, unknown> = { key }
|
|
21
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
22
|
+
if (name === "class") props["className"] = value
|
|
23
|
+
else if (name === "checked") props["defaultChecked"] = value
|
|
24
|
+
else props[name] = value
|
|
25
|
+
}
|
|
26
|
+
return props
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function toReactNode(child: RichTextChild, index: number): ReactNode {
|
|
30
|
+
if (typeof child === "string") return child
|
|
31
|
+
return createElement(child.tag, reactProps(child.attributes, index), ...child.children.map(toReactNode))
|
|
32
|
+
}
|
|
33
|
+
|
|
12
34
|
/**
|
|
13
|
-
* Renders a Lexical rich
|
|
35
|
+
* Renders a saved Lexical rich text document as React elements.
|
|
14
36
|
*
|
|
15
|
-
*
|
|
37
|
+
* The document is walked by `richTextTree` from @supatype/common, the same walker the HTML string
|
|
38
|
+
* renderer uses, so both print the same thing. Text becomes React text children, never HTML, and
|
|
39
|
+
* links only keep a safe href. Works in both Server Components and Client Components.
|
|
16
40
|
*/
|
|
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 }} />
|
|
41
|
+
export function RichText({ content, className, as: Tag = "div" }: RichTextProps): ReactElement | null {
|
|
42
|
+
if (content === null || content === undefined) return null
|
|
43
|
+
return <Tag {...(className !== undefined && { className })}>{richTextTree(content).map(toReactNode)}</Tag>
|
|
31
44
|
}
|
package/src/context.tsx
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import React from "react"
|
|
4
4
|
import type { AnyClient, SupatypeClient, AnyDatabase, AugmentedDatabase } from "@supatype/client"
|
|
5
|
+
import { isClientFor } from "@supatype/client/bindings"
|
|
5
6
|
|
|
6
7
|
/** Typed at `AnyClient`, narrowed on read. See `AnyClient` for why it is neither generic nor `any`. */
|
|
7
8
|
export const SupatypeContext = React.createContext<AnyClient | null>(null)
|
|
@@ -37,8 +38,8 @@ export function SupatypeProvider({ client, children }: SupatypeProviderProps): R
|
|
|
37
38
|
* higher-level hooks (useAuth, useQuery, useMutation) instead.
|
|
38
39
|
*/
|
|
39
40
|
export function useSupatype<TDatabase extends AnyDatabase = AugmentedDatabase>(): SupatypeClient<TDatabase> {
|
|
40
|
-
const client = React.useContext(SupatypeContext)
|
|
41
|
-
if (client === null) {
|
|
41
|
+
const client = React.useContext(SupatypeContext)
|
|
42
|
+
if (client === null || !isClientFor<TDatabase>(client)) {
|
|
42
43
|
throw new Error("useSupatype must be used inside a <SupatypeProvider>")
|
|
43
44
|
}
|
|
44
45
|
return client
|
package/src/index.ts
CHANGED
|
@@ -15,6 +15,7 @@ export type { UseSubscriptionOptions, UseSubscriptionResult, SubscriptionStatus
|
|
|
15
15
|
|
|
16
16
|
export { useLivePreview } from "./useLivePreview.js"
|
|
17
17
|
export type { UseLivePreviewOptions, UseLivePreviewResult } from "./useLivePreview.js"
|
|
18
|
+
export type { StudioOrigins } from "./live-preview-message.js"
|
|
18
19
|
|
|
19
20
|
export { useFunction } from "./useFunction.js"
|
|
20
21
|
export type { UseFunctionResult } from "./useFunction.js"
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which `message` events `useLivePreview` believes.
|
|
3
|
+
*
|
|
4
|
+
* A preview message repaints the page with whatever it carries, so it is only applied when Studio
|
|
5
|
+
* sent it. Two checks, taken from the two editors that solved this first:
|
|
6
|
+
*
|
|
7
|
+
* - The sender's origin is compared exactly with the origins Studio is served from, as Payload's
|
|
8
|
+
* live preview compares `event.origin` with its `serverURL`.
|
|
9
|
+
* - The sending window must be the one this page is framed by, as Sanity's comlink pins the one
|
|
10
|
+
* window it handshook with. Studio's pane is that parent; any other window is not Studio.
|
|
11
|
+
*
|
|
12
|
+
* Studio is served at `/studio/` on the project's API URL, so the client's URL names its origin
|
|
13
|
+
* unless the app says otherwise. With neither, nothing is trusted: an unknown sender is never one.
|
|
14
|
+
*/
|
|
15
|
+
import { originOf } from "@supatype/client/bindings"
|
|
16
|
+
|
|
17
|
+
/** One URL or origin, or several, that Studio may post previews from. */
|
|
18
|
+
export type StudioOrigins = string | readonly string[]
|
|
19
|
+
|
|
20
|
+
/** A space cannot appear in a URL, so it cannot split one. */
|
|
21
|
+
const URL_SEPARATOR = " "
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The URLs Studio may post from, as one string: the ones `configured` names, else the client URL.
|
|
25
|
+
*
|
|
26
|
+
* A string so a hook can depend on it: a caller's inline array is a new array every render, and the
|
|
27
|
+
* listener should be replaced only when the URLs themselves change.
|
|
28
|
+
*/
|
|
29
|
+
export function studioUrlsKey(configured: StudioOrigins | undefined, clientUrl: string | undefined): string {
|
|
30
|
+
const urls = configured ?? clientUrl ?? []
|
|
31
|
+
return typeof urls === "string" ? urls : urls.join(URL_SEPARATOR)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The exact origins a `studioUrlsKey` names; an entry that is not an absolute URL names none. */
|
|
35
|
+
export function trustedStudioOrigins(urlsKey: string): ReadonlySet<string> {
|
|
36
|
+
return new Set(urlsKey.split(URL_SEPARATOR).map((url) => originOf(url)).filter((origin) => origin !== null))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Say, once per origin, that a preview from `origin` was refused.
|
|
41
|
+
*
|
|
42
|
+
* A Studio served somewhere other than the client's URL is a configuration a developer has to make,
|
|
43
|
+
* and without this the only symptom is a preview that never updates.
|
|
44
|
+
*/
|
|
45
|
+
export function warnRefusedOrigin(origin: string, warned: Set<string>): void {
|
|
46
|
+
if (warned.has(origin)) return
|
|
47
|
+
warned.add(origin)
|
|
48
|
+
console.warn(
|
|
49
|
+
`[supatype] useLivePreview ignored a live preview message from ${origin}, which is not a trusted ` +
|
|
50
|
+
"Studio origin. If Studio is served from there, pass it as `studioOrigin`.",
|
|
51
|
+
)
|
|
52
|
+
}
|
package/src/useAuth.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import { useState, useEffect } from "react"
|
|
4
|
-
import type { Session, User, AuthChangeEvent, SupatypeError } from "@supatype/client"
|
|
4
|
+
import type { Session, User, AuthChangeEvent, AuthRedirectError, SupatypeError } from "@supatype/client"
|
|
5
5
|
import { useSupatype } from "./context.js"
|
|
6
6
|
|
|
7
7
|
export interface UseAuthReturn {
|
|
@@ -9,8 +9,13 @@ export interface UseAuthReturn {
|
|
|
9
9
|
user: User | null
|
|
10
10
|
/** The current session (includes access token), or null. */
|
|
11
11
|
session: Session | null
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* True while loading the initial auth state, which includes finishing a sign-in the page's URL
|
|
14
|
+
* carries (an OAuth or email-link redirect).
|
|
15
|
+
*/
|
|
13
16
|
loading: boolean
|
|
17
|
+
/** The sign-in the auth server refused and reported in the page's URL, or null. */
|
|
18
|
+
error: AuthRedirectError | null
|
|
14
19
|
/** Sign up with email and password. */
|
|
15
20
|
signUp(credentials: {
|
|
16
21
|
email: string
|
|
@@ -50,33 +55,37 @@ export interface UseAuthReturn {
|
|
|
50
55
|
*/
|
|
51
56
|
export function useAuth(): UseAuthReturn {
|
|
52
57
|
const client = useSupatype()
|
|
53
|
-
const [user, setUser] = useState<User | null>(null)
|
|
54
58
|
const [session, setSession] = useState<Session | null>(null)
|
|
55
59
|
const [loading, setLoading] = useState(true)
|
|
60
|
+
const [error, setError] = useState<AuthRedirectError | null>(null)
|
|
56
61
|
|
|
57
62
|
useEffect(() => {
|
|
58
|
-
|
|
59
|
-
|
|
63
|
+
let active = true
|
|
64
|
+
// Seed once the client has started: the stored session, or the one the page's URL carried.
|
|
65
|
+
void client.auth.initialize().then(async ({ error: redirectError }) => {
|
|
66
|
+
const { data } = await client.auth.getSession()
|
|
67
|
+
if (!active) return
|
|
60
68
|
setSession(data.session)
|
|
61
|
-
|
|
69
|
+
setError(redirectError)
|
|
62
70
|
setLoading(false)
|
|
63
71
|
})
|
|
64
72
|
|
|
65
73
|
// Subscribe to future changes
|
|
66
74
|
const { data: { subscription } } = client.auth.onAuthStateChange(
|
|
67
|
-
(_event: AuthChangeEvent, newSession: Session | null) =>
|
|
68
|
-
setSession(newSession)
|
|
69
|
-
setUser(newSession?.user ?? null)
|
|
70
|
-
},
|
|
75
|
+
(_event: AuthChangeEvent, newSession: Session | null) => setSession(newSession),
|
|
71
76
|
)
|
|
72
77
|
|
|
73
|
-
return () =>
|
|
78
|
+
return () => {
|
|
79
|
+
active = false
|
|
80
|
+
subscription.unsubscribe()
|
|
81
|
+
}
|
|
74
82
|
}, [client])
|
|
75
83
|
|
|
76
84
|
return {
|
|
77
|
-
user,
|
|
85
|
+
user: session?.user ?? null,
|
|
78
86
|
session,
|
|
79
87
|
loading,
|
|
88
|
+
error,
|
|
80
89
|
signUp: (creds) => client.auth.signUp(creds),
|
|
81
90
|
signIn: (creds) => client.auth.signInWithPassword(creds),
|
|
82
91
|
signInWithOAuth: (opts) => client.auth.signInWithOAuth(opts),
|
package/src/useFunction.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { useState, useCallback } from "react"
|
|
4
4
|
import type { AnyDatabase, AugmentedDatabase, SupatypeError } from "@supatype/client"
|
|
5
5
|
import { useSupatype } from "./context.js"
|
|
6
|
+
import { isCallerValue } from "@supatype/client/bindings"
|
|
6
7
|
|
|
7
8
|
export interface FunctionCallOptions {
|
|
8
9
|
/** HTTP method. Default: POST */
|
|
@@ -54,15 +55,18 @@ export function useFunction<
|
|
|
54
55
|
setLoading(true)
|
|
55
56
|
setError(null)
|
|
56
57
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
58
|
+
try {
|
|
59
|
+
const result = await client.functions.invoke(functionName, {
|
|
60
|
+
...options,
|
|
61
|
+
...(body !== undefined ? { body } : {}),
|
|
62
|
+
})
|
|
63
|
+
const answer = { data: isCallerValue<TResponse>(result.data) ? result.data : null, error: result.error }
|
|
64
|
+
setData(answer.data)
|
|
65
|
+
if (answer.error !== null) setError(answer.error)
|
|
66
|
+
return answer
|
|
67
|
+
} finally {
|
|
68
|
+
setLoading(false)
|
|
69
|
+
}
|
|
66
70
|
},
|
|
67
71
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
68
72
|
[client, functionName],
|
package/src/useLivePreview.ts
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
|
-
import { useState, useEffect, useRef } from "react"
|
|
3
|
+
import { useState, useEffect, useRef, useContext } from "react"
|
|
4
|
+
import { isCallerValue, previewMessageOf } from "@supatype/client/bindings"
|
|
5
|
+
import { SupatypeContext } from "./context.js"
|
|
6
|
+
import { studioUrlsKey, trustedStudioOrigins, warnRefusedOrigin, type StudioOrigins } from "./live-preview-message.js"
|
|
4
7
|
|
|
5
8
|
export interface UseLivePreviewOptions<TData> {
|
|
6
9
|
/** The initial/server data to display when not in preview mode. */
|
|
7
10
|
initialData: TData
|
|
8
11
|
/** Optional model name filter, only accept preview data for this model. */
|
|
9
12
|
model?: string
|
|
13
|
+
/**
|
|
14
|
+
* Where Studio is served, as a URL or origin, or a list of them. Only messages from these origins
|
|
15
|
+
* are applied.
|
|
16
|
+
*
|
|
17
|
+
* Defaults to the origin of the `<SupatypeProvider>` client's URL, since Studio is served at
|
|
18
|
+
* `/studio/` on the project's API URL. Set it when Studio lives elsewhere, or when this page has
|
|
19
|
+
* no provider: with neither, every preview message is ignored.
|
|
20
|
+
*/
|
|
21
|
+
studioOrigin?: StudioOrigins
|
|
10
22
|
}
|
|
11
23
|
|
|
12
24
|
export interface UseLivePreviewResult<TData> {
|
|
@@ -21,7 +33,8 @@ export interface UseLivePreviewResult<TData> {
|
|
|
21
33
|
*
|
|
22
34
|
* When the admin panel's edit view is open with Live Preview enabled,
|
|
23
35
|
* it sends `postMessage` events with form data as the editor types.
|
|
24
|
-
* This hook receives those events and returns the live data.
|
|
36
|
+
* This hook receives those events and returns the live data. A message is applied only when it
|
|
37
|
+
* comes from the window framing this page, at a Studio origin (see `studioOrigin`).
|
|
25
38
|
*
|
|
26
39
|
* @example
|
|
27
40
|
* ```tsx
|
|
@@ -43,22 +56,22 @@ export function useLivePreview<TData>(
|
|
|
43
56
|
const [previewData, setPreviewData] = useState<TData | null>(null)
|
|
44
57
|
const initialRef = useRef(opts.initialData)
|
|
45
58
|
initialRef.current = opts.initialData
|
|
59
|
+
const urlsKey = studioUrlsKey(opts.studioOrigin, useContext(SupatypeContext)?.url)
|
|
60
|
+
const warned = useRef(new Set<string>())
|
|
46
61
|
|
|
47
62
|
useEffect(() => {
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
63
|
+
const trusted = trustedStudioOrigins(urlsKey)
|
|
64
|
+
// Applied only when the framing window sent it, from an origin Studio is served at.
|
|
65
|
+
const handler = (event: MessageEvent): void => {
|
|
66
|
+
const msg = previewMessageOf(event.data)
|
|
67
|
+
if (msg === null || event.source !== window.parent) return
|
|
68
|
+
if (!trusted.has(event.origin)) return warnRefusedOrigin(event.origin, warned.current)
|
|
52
69
|
if (opts.model && msg.model !== opts.model) return
|
|
53
|
-
setPreviewData(msg.data
|
|
70
|
+
if (isCallerValue<TData>(msg.data)) setPreviewData(msg.data)
|
|
54
71
|
}
|
|
55
|
-
|
|
56
72
|
window.addEventListener("message", handler)
|
|
57
73
|
return () => { window.removeEventListener("message", handler) }
|
|
58
|
-
}, [opts.model])
|
|
74
|
+
}, [opts.model, urlsKey])
|
|
59
75
|
|
|
60
|
-
return {
|
|
61
|
-
data: previewData ?? initialRef.current,
|
|
62
|
-
isPreview: previewData !== null,
|
|
63
|
-
}
|
|
76
|
+
return { data: previewData ?? initialRef.current, isPreview: previewData !== null }
|
|
64
77
|
}
|
package/src/useMutation.ts
CHANGED
|
@@ -1,21 +1,27 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import { useState, useCallback } from "react"
|
|
4
|
-
import type { AnyDatabase, AugmentedDatabase, SupatypeError } from "@supatype/client"
|
|
4
|
+
import type { AnyClient, AnyDatabase, AugmentedDatabase, SupatypeError } from "@supatype/client"
|
|
5
5
|
import { useSupatype } from "./context.js"
|
|
6
|
+
import { runMutation, type MutationOperation, type MutationOutcome } from "@supatype/client/bindings"
|
|
6
7
|
|
|
7
|
-
export type MutationOperation
|
|
8
|
+
export type { MutationOperation }
|
|
8
9
|
|
|
9
10
|
export interface MutationOptions {
|
|
10
11
|
/** Simple equality filters for update/delete operations */
|
|
11
12
|
filter?: Record<string, unknown> | undefined
|
|
13
|
+
/**
|
|
14
|
+
* For an update on a model that keeps drafts: publish the drafts it saves in the same call. Without
|
|
15
|
+
* it the update saves a new draft of each record and the live rows stay as they are.
|
|
16
|
+
*/
|
|
17
|
+
publish?: boolean | undefined
|
|
12
18
|
}
|
|
13
19
|
|
|
14
20
|
export interface UseMutationResult<TRow> {
|
|
15
21
|
mutate(
|
|
16
22
|
data?: Record<string, unknown> | Record<string, unknown>[] | undefined,
|
|
17
23
|
options?: MutationOptions | undefined,
|
|
18
|
-
): Promise<
|
|
24
|
+
): Promise<MutationOutcome<TRow>>
|
|
19
25
|
loading: boolean
|
|
20
26
|
error: SupatypeError | null
|
|
21
27
|
}
|
|
@@ -28,6 +34,9 @@ export interface UseMutationResult<TRow> {
|
|
|
28
34
|
* const { mutate: createPost, loading } = useMutation('posts', 'insert')
|
|
29
35
|
* await createPost({ title: 'Hello', status: 'draft' })
|
|
30
36
|
*
|
|
37
|
+
* const { mutate: editPost } = useMutation('posts', 'update')
|
|
38
|
+
* await editPost({ title: 'Hello again' }, { filter: { id: postId }, publish: true })
|
|
39
|
+
*
|
|
31
40
|
* const { mutate: deletePost } = useMutation('posts', 'delete')
|
|
32
41
|
* await deletePost(undefined, { filter: { id: postId } })
|
|
33
42
|
* ```
|
|
@@ -51,38 +60,16 @@ export function useMutation<
|
|
|
51
60
|
) => {
|
|
52
61
|
setLoading(true)
|
|
53
62
|
setError(null)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
63
|
+
try {
|
|
64
|
+
const publish = options?.publish
|
|
65
|
+
const result = await runMutation<TRow>(client as AnyClient, table, operation, data, options?.filter, {
|
|
66
|
+
...(publish !== undefined && { publish }),
|
|
67
|
+
})
|
|
68
|
+
if (result.error !== null) setError(result.error)
|
|
69
|
+
return result
|
|
70
|
+
} finally {
|
|
71
|
+
setLoading(false)
|
|
81
72
|
}
|
|
82
|
-
|
|
83
|
-
setLoading(false)
|
|
84
|
-
if (result.error !== null) setError(result.error)
|
|
85
|
-
return result
|
|
86
73
|
},
|
|
87
74
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
88
75
|
[client, table, operation],
|
package/src/useQuery.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import { useState, useEffect, useCallback, useRef } from "react"
|
|
4
|
-
import type { AnyDatabase, AugmentedDatabase, SupatypeError, QueryCacheOptions } from "@supatype/client"
|
|
4
|
+
import type { AnyClient, AnyDatabase, AugmentedDatabase, SupatypeError, QueryCacheOptions } from "@supatype/client"
|
|
5
5
|
import { onIdentityChange } from "@supatype/client"
|
|
6
6
|
import { useSupatype } from "./context.js"
|
|
7
|
+
import { isRowsOf } from "@supatype/client/bindings"
|
|
7
8
|
|
|
8
9
|
export interface UseQueryOptions {
|
|
9
10
|
/** PostgREST select expression (default: '*') */
|
|
@@ -84,14 +85,12 @@ export function useQuery<
|
|
|
84
85
|
}
|
|
85
86
|
setLoading(true)
|
|
86
87
|
|
|
87
|
-
//
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
const source: any = client.from(table)
|
|
88
|
+
// Through the untyped client: the generated row types do not survive a table name known only
|
|
89
|
+
// at run time, so the rows are typed as `TRow` once they arrive.
|
|
90
|
+
const source = (client as AnyClient).from(table)
|
|
91
91
|
// A draft read is the same request against a different schema, so it branches here rather than
|
|
92
92
|
// duplicating every filter below.
|
|
93
|
-
|
|
94
|
-
let query: any = (options?.draft === true ? source.draft() : source).select(
|
|
93
|
+
let query = (options?.draft === true ? source.draft() : source).select(
|
|
95
94
|
options?.select ?? "*",
|
|
96
95
|
)
|
|
97
96
|
|
|
@@ -113,8 +112,8 @@ export function useQuery<
|
|
|
113
112
|
query = query.cache(options.cache)
|
|
114
113
|
}
|
|
115
114
|
|
|
116
|
-
const result =
|
|
117
|
-
setData(result.data)
|
|
115
|
+
const result = await query
|
|
116
|
+
setData(isRowsOf<TRow>(result.data) ? result.data : null)
|
|
118
117
|
setError(result.error)
|
|
119
118
|
setCount(result.count)
|
|
120
119
|
setLoading(false)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `RichText` must render a saved Lexical document exactly as the HTML string renderer does, since
|
|
3
|
+
* both print the same tree from @supatype/common. These run the shared cases through React and
|
|
4
|
+
* print what React built back to HTML, so a difference in either renderer fails here.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import React from "react"
|
|
8
|
+
import { describe, expect, it } from "vitest"
|
|
9
|
+
import { create, type ReactTestRendererJSON } from "react-test-renderer"
|
|
10
|
+
import { RichText } from "../src/RichText.js"
|
|
11
|
+
import { RENDER_CASES } from "../../common/tests/richtext-cases.js"
|
|
12
|
+
|
|
13
|
+
type Rendered = ReactTestRendererJSON | string
|
|
14
|
+
|
|
15
|
+
const ESCAPES: Readonly<Record<string, string>> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }
|
|
16
|
+
const VOID_TAGS: ReadonlySet<string> = new Set(["br", "hr", "input"])
|
|
17
|
+
const PROP_NAMES: Readonly<Record<string, string>> = { className: "class", defaultChecked: "checked" }
|
|
18
|
+
|
|
19
|
+
function escapeHtml(text: string): string {
|
|
20
|
+
return text.replace(/[&<>"']/g, (char) => ESCAPES[char] ?? char)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function cssText(style: object): string {
|
|
24
|
+
return Object.entries(style)
|
|
25
|
+
.map(([property, value]) => `${property.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${String(value)}`)
|
|
26
|
+
.join(";")
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function propText(name: string, value: unknown): string {
|
|
30
|
+
const attribute = PROP_NAMES[name] ?? name
|
|
31
|
+
if (value === true) return ` ${attribute}`
|
|
32
|
+
if (value === false || value === undefined) return ""
|
|
33
|
+
const printed = typeof value === "object" && value !== null ? cssText(value) : String(value)
|
|
34
|
+
return ` ${attribute}="${escapeHtml(printed)}"`
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function toHtml(node: Rendered): string {
|
|
38
|
+
if (typeof node === "string") return escapeHtml(node)
|
|
39
|
+
const attributes = Object.entries(node.props).map(([name, value]) => propText(name, value)).join("")
|
|
40
|
+
if (VOID_TAGS.has(node.type)) return `<${node.type}${attributes} />`
|
|
41
|
+
return `<${node.type}${attributes}>${(node.children ?? []).map(toHtml).join("")}</${node.type}>`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function wrapper(element: React.ReactElement): ReactTestRendererJSON {
|
|
45
|
+
const json = create(element).toJSON()
|
|
46
|
+
if (json === null || Array.isArray(json)) throw new Error("RichText should render one wrapper element")
|
|
47
|
+
return json
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe("RichText renders what Lexical saves", () => {
|
|
51
|
+
it.each(RENDER_CASES)("$name", ({ content, html }) => {
|
|
52
|
+
const rendered = wrapper(<RichText content={content} />)
|
|
53
|
+
expect((rendered.children ?? []).map(toHtml).join("")).toBe(html)
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
describe("RichText element", () => {
|
|
58
|
+
const xss = RENDER_CASES.find((c) => c.name.startsWith("script"))
|
|
59
|
+
|
|
60
|
+
it("builds elements rather than injecting an HTML string", () => {
|
|
61
|
+
if (xss === undefined) throw new Error("xss case missing")
|
|
62
|
+
const rendered = wrapper(<RichText content={xss.content} />)
|
|
63
|
+
expect(rendered.props).not.toHaveProperty("dangerouslySetInnerHTML")
|
|
64
|
+
const first = rendered.children?.[0]
|
|
65
|
+
expect(typeof first === "object" && first.children).toEqual(["<script>alert(\"x\")</script> & 'quotes'"])
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it("keeps the wrapper props: className and the element tag", () => {
|
|
69
|
+
const rendered = wrapper(<RichText content={[]} className="prose" as="article" />)
|
|
70
|
+
expect(rendered.type).toBe("article")
|
|
71
|
+
expect(rendered.props).toEqual({ className: "prose" })
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it("renders nothing for null content", () => {
|
|
75
|
+
expect(create(<RichText content={null} />).toJSON()).toBeNull()
|
|
76
|
+
})
|
|
77
|
+
})
|