houdini-react 2.0.0-go.4 → 2.0.0-go.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.
@@ -0,0 +1,62 @@
1
+ import type {
2
+ DocumentArtifact,
3
+ GraphQLVariables,
4
+ QueryResult,
5
+ GraphQLObject,
6
+ } from 'houdini/runtime'
7
+ import type { DocumentStore, SendParams } from 'houdini/runtime/client'
8
+
9
+ import { useSession } from '../routing/Router'
10
+ import useDeepCompareEffect from './useDeepCompareEffect'
11
+ import { useDocumentStore, type UseDocumentStoreParams } from './useDocumentStore'
12
+
13
+ export function useDocumentSubscription<
14
+ _Artifact extends DocumentArtifact = DocumentArtifact,
15
+ _Data extends GraphQLObject = GraphQLObject,
16
+ _Input extends GraphQLVariables = GraphQLVariables
17
+ >({
18
+ artifact,
19
+ variables,
20
+ send,
21
+ disabled,
22
+ ...observeParams
23
+ }: UseDocumentStoreParams<_Artifact, _Data, _Input> & {
24
+ variables: _Input
25
+ disabled?: boolean
26
+ send?: Partial<SendParams>
27
+ }): [QueryResult<_Data, _Input> & { parent?: string | null }, DocumentStore<_Data, _Input>] {
28
+ const [storeValue, observer] = useDocumentStore<_Data, _Input>({
29
+ artifact,
30
+ ...observeParams,
31
+ })
32
+
33
+ // grab the current session value
34
+ const [session] = useSession()
35
+
36
+ // whenever the variables change, we need to retrigger the query
37
+ useDeepCompareEffect(() => {
38
+ if (!disabled) {
39
+ observer.send({
40
+ variables,
41
+ session,
42
+ // TODO: metadata
43
+ metadata: {},
44
+ ...send,
45
+ })
46
+ }
47
+
48
+ return () => {
49
+ if (!disabled) {
50
+ observer.cleanup()
51
+ }
52
+ }
53
+ }, [disabled, session, observer, variables ?? {}, send ?? {}])
54
+
55
+ return [
56
+ {
57
+ parent: send?.stuff?.parentID,
58
+ ...storeValue,
59
+ },
60
+ observer,
61
+ ]
62
+ }
@@ -0,0 +1,102 @@
1
+ import { deepEquals } from 'houdini/runtime'
2
+ import { fragmentKey } from 'houdini/runtime'
3
+ import type { GraphQLObject, GraphQLVariables, FragmentArtifact } from 'houdini/runtime'
4
+ import * as React from 'react'
5
+
6
+ import { useRouterContext } from '../routing'
7
+ import { useDeepCompareMemoize } from './useDeepCompareEffect'
8
+ import { useDocumentSubscription } from './useDocumentSubscription'
9
+
10
+ export function useFragment<
11
+ _Data extends GraphQLObject,
12
+ _ReferenceType extends {},
13
+ _Input extends GraphQLVariables = GraphQLVariables
14
+ >(
15
+ reference: _Data | { [fragmentKey]: _ReferenceType } | null,
16
+ document: { artifact: FragmentArtifact }
17
+ ) {
18
+ const { cache } = useRouterContext()
19
+
20
+ // get the fragment reference info
21
+ const { parent, variables, loading } = fragmentReference<_Data, _Input, _ReferenceType>(
22
+ reference,
23
+ document
24
+ )
25
+
26
+ // if we got this far then we are safe to use the fields on the object
27
+ let cachedValue = reference as _Data | null
28
+
29
+ // on the client, we want to ensure that we apply masking to the initial value by
30
+ // loading the value from cache
31
+ if (reference && parent) {
32
+ cachedValue = cache.read({
33
+ selection: document.artifact.selection,
34
+ parent,
35
+ variables,
36
+ loading,
37
+ }).data as _Data
38
+ }
39
+
40
+ // we're ready to setup the live document
41
+ const [storeValue] = useDocumentSubscription<FragmentArtifact, _Data, _Input>({
42
+ artifact: document.artifact,
43
+ variables,
44
+ initialValue: cachedValue,
45
+ // dont subscribe to anything if we are loading
46
+ disabled: loading,
47
+ send: {
48
+ stuff: {
49
+ parentID: parent,
50
+ },
51
+ setup: true,
52
+ },
53
+ })
54
+
55
+ // the parent has changed, we need to use initialValue for this render
56
+ // if we don't, then there is a very brief flash where we will show the old data
57
+ // before the store has had a chance to update
58
+ const lastReference = React.useRef<{ parent: string; variables: _Input } | null>(null)
59
+ return React.useMemo(() => {
60
+ // if the parent reference has changed we need to always prefer the cached value
61
+ const parentChange =
62
+ storeValue.parent !== parent ||
63
+ !deepEquals({ parent, variables }, lastReference.current)
64
+ if (parentChange) {
65
+ // make sure we keep track of the last reference we used
66
+ lastReference.current = { parent, variables: { ...variables } }
67
+
68
+ // and use the cached value
69
+ return cachedValue
70
+ }
71
+
72
+ return storeValue.data
73
+ }, [
74
+ useDeepCompareMemoize({
75
+ parent,
76
+ variables,
77
+ cachedValue,
78
+ storeValue: storeValue.data,
79
+ storeParent: storeValue.parent,
80
+ }),
81
+ ])
82
+ }
83
+
84
+ export function fragmentReference<_Data extends GraphQLObject, _Input, _ReferenceType extends {}>(
85
+ reference: _Data | { [fragmentKey]: _ReferenceType } | null,
86
+ document: { artifact: FragmentArtifact }
87
+ ): { variables: _Input; parent: string; loading: boolean } {
88
+ // @ts-expect-error: typescript can't guarantee that the fragment key is defined
89
+ // but if its not, then the fragment wasn't mixed into the right thing
90
+ // the variables for the fragment live on the initial value's $fragment key
91
+ const { variables, parent } = reference?.[fragmentKey]?.values?.[document.artifact.name] ?? {}
92
+ if (reference && fragmentKey in reference && (!variables || !parent)) {
93
+ console.warn(
94
+ `⚠️ Parent does not contain the information for this fragment. Something is wrong.
95
+ Please ensure that you have passed a record that has ${document.artifact.name} mixed into it.`
96
+ )
97
+ }
98
+ // @ts-expect-error
99
+ const loading = Boolean(reference?.[fragmentKey]?.loading)
100
+
101
+ return { variables, parent, loading }
102
+ }
@@ -0,0 +1,47 @@
1
+ import type {
2
+ GraphQLObject,
3
+ FragmentArtifact,
4
+ QueryArtifact,
5
+ fragmentKey,
6
+ GraphQLVariables,
7
+ } from 'houdini/runtime'
8
+
9
+ import { useDocumentHandle, type DocumentHandle } from './useDocumentHandle'
10
+ import { useDocumentStore } from './useDocumentStore'
11
+ import { fragmentReference, useFragment } from './useFragment'
12
+
13
+ // useFragmentHandle is just like useFragment except it also returns an imperative handle
14
+ // that users can use to interact with the fragment
15
+ export function useFragmentHandle<
16
+ _Artifact extends FragmentArtifact,
17
+ _Data extends GraphQLObject,
18
+ _ReferenceType extends {},
19
+ _PaginationArtifact extends QueryArtifact,
20
+ _Input extends GraphQLVariables = GraphQLVariables
21
+ >(
22
+ reference: _Data | { [fragmentKey]: _ReferenceType } | null,
23
+ document: { artifact: FragmentArtifact; refetchArtifact?: QueryArtifact }
24
+ ): DocumentHandle<_PaginationArtifact, _Data, _Input> {
25
+ // get the fragment values
26
+ const data = useFragment<_Data, _ReferenceType, _Input>(reference, document)
27
+
28
+ // look at the fragment reference to get the variables
29
+ const { variables } = fragmentReference<_Data, _Input, _ReferenceType>(reference, document)
30
+
31
+ // use the pagination fragment for meta data if it exists.
32
+ // if we pass this a fragment artifact, it won't add any data
33
+ const [handleValue, handleObserver] = useDocumentStore<_Data, _Input>({
34
+ artifact: document.refetchArtifact ?? document.artifact,
35
+ })
36
+ const handle = useDocumentHandle<_PaginationArtifact, _Data, _Input>({
37
+ observer: handleObserver,
38
+ storeValue: handleValue,
39
+ artifact: document.refetchArtifact ?? document.artifact,
40
+ })
41
+
42
+ return {
43
+ ...handle,
44
+ variables,
45
+ data,
46
+ }
47
+ }
@@ -0,0 +1,14 @@
1
+ import { useRef, useEffect } from 'react'
2
+
3
+ export function useIsMountedRef(): { current: boolean } {
4
+ const isMountedRef = useRef(true)
5
+
6
+ useEffect(() => {
7
+ isMountedRef.current = true
8
+ return () => {
9
+ isMountedRef.current = false
10
+ }
11
+ }, [])
12
+
13
+ return isMountedRef
14
+ }
@@ -0,0 +1,54 @@
1
+ import type {
2
+ MutationArtifact,
3
+ GraphQLObject,
4
+ QueryResult,
5
+ GraphQLVariables,
6
+ } from 'houdini/runtime'
7
+
8
+ import { useSession } from '../routing/Router'
9
+ import { useDocumentStore } from './useDocumentStore'
10
+
11
+ export type MutationHandler<_Result, _Input, _Optimistic extends GraphQLObject> = (args: {
12
+ variables: _Input
13
+
14
+ metadata?: App.Metadata
15
+ fetch?: typeof globalThis.fetch
16
+ optimisticResponse?: _Optimistic
17
+ }) => Promise<QueryResult<_Result, _Input>>
18
+
19
+ export function useMutation<
20
+ _Result extends GraphQLObject,
21
+ _Input extends GraphQLVariables,
22
+ _Optimistic extends GraphQLObject
23
+ >({
24
+ artifact,
25
+ }: {
26
+ artifact: MutationArtifact
27
+ }): [boolean, MutationHandler<_Result, _Input, _Optimistic>] {
28
+ // build the live document we'll use to send values
29
+ const [storeValue, observer] = useDocumentStore<_Result, _Input>({ artifact })
30
+
31
+ // grab the pending state from the document store
32
+ const pending = storeValue.fetching
33
+
34
+ // grab the current session value
35
+ const [session] = useSession()
36
+
37
+ // sending the mutation just means invoking the observer's send method
38
+ const mutate: MutationHandler<_Result, _Input, _Optimistic> = ({
39
+ metadata,
40
+ fetch,
41
+ variables,
42
+ ...mutationConfig
43
+ }) =>
44
+ observer.send({
45
+ variables,
46
+ metadata,
47
+ session,
48
+ stuff: {
49
+ ...mutationConfig,
50
+ },
51
+ })
52
+
53
+ return [pending, mutate]
54
+ }
@@ -0,0 +1,17 @@
1
+ import type { GraphQLVariables, GraphQLObject, QueryArtifact } from 'houdini/runtime'
2
+
3
+ import type { UseQueryConfig } from './useQueryHandle'
4
+ import { useQueryHandle } from './useQueryHandle'
5
+
6
+ export function useQuery<
7
+ _Artifact extends QueryArtifact,
8
+ _Data extends GraphQLObject = GraphQLObject,
9
+ _Input extends GraphQLVariables = GraphQLVariables
10
+ >(
11
+ document: { artifact: QueryArtifact },
12
+ variables: any = null,
13
+ config: UseQueryConfig = {}
14
+ ): _Data {
15
+ const { data } = useQueryHandle<_Artifact, _Data, _Input>(document, variables, config)
16
+ return data
17
+ }
@@ -0,0 +1,184 @@
1
+ import { createLRUCache } from 'houdini/runtime'
2
+ import type { GraphQLObject, CachePolicies, QueryArtifact, GraphQLVariables } from 'houdini/runtime'
3
+ import React from 'react'
4
+
5
+ import { useClient } from '../routing'
6
+ import type { DocumentHandle } from './useDocumentHandle'
7
+ import { useDocumentHandle } from './useDocumentHandle'
8
+ import { useIsMountedRef } from './useIsMounted'
9
+
10
+ // Suspense requires a way to throw a promise that resolves to a place
11
+ // we can put when we go back on a susequent render. This means that we have to have
12
+ // a stable way to identify _this_ useQueryHandle called.
13
+ // For now, we're going to compute an identifier based on the name of the artifact
14
+ // and the variables that we were given.
15
+ //
16
+ // - If we have a cached promise that's pending, we should just throw that promise
17
+ // - If we have a cached promise that's been resolved, we should return that value
18
+ //
19
+ // When the Component unmounts, we need to remove the entry from the cache (so we can load again)
20
+
21
+ const promiseCache = createLRUCache<QuerySuspenseUnit>()
22
+ type QuerySuspenseUnit = {
23
+ resolve: () => void
24
+ resolved?: DocumentHandle<QueryArtifact, GraphQLObject, {}>
25
+ then: (val: any) => any
26
+ }
27
+
28
+ export function useQueryHandle<
29
+ _Artifact extends QueryArtifact,
30
+ _Data extends GraphQLObject = GraphQLObject,
31
+ _Input extends GraphQLVariables = GraphQLVariables
32
+ >(
33
+ { artifact }: { artifact: QueryArtifact },
34
+ variables: any = null,
35
+ config: UseQueryConfig = {}
36
+ ): DocumentHandle<_Artifact, _Data, _Input> {
37
+ // figure out the identifier so we know what to look for
38
+ const identifier = queryIdentifier({ artifact, variables, config })
39
+
40
+ // see if we have an entry in the cache for the identifier
41
+ const suspenseValue = promiseCache.get(identifier)
42
+
43
+ const client = useClient()
44
+
45
+ const isMountedRef = useIsMountedRef()
46
+
47
+ // hold onto an observer we'll use
48
+ let [observer] = React.useState(
49
+ client.observe<_Data, _Input>({
50
+ artifact,
51
+ initialValue: (suspenseValue?.resolved?.data ?? {}) as _Data,
52
+ })
53
+ )
54
+
55
+ // a ref flag we'll enable before throwing so that we don't update while suspend
56
+ const suspenseTracker = React.useRef(false)
57
+
58
+ // a stable box to put the store's value
59
+ const box = React.useRef(observer.state)
60
+
61
+ // a stable subscribe function for the document store
62
+ const subscribe: any = React.useCallback(
63
+ (fn: () => void) => {
64
+ return observer.subscribe((val) => {
65
+ box.current = val
66
+ if (isMountedRef.current && !suspenseTracker.current) {
67
+ fn()
68
+ }
69
+ })
70
+ },
71
+ [observer]
72
+ )
73
+
74
+ // get a safe reference to the cache
75
+ const storeValue = React.useSyncExternalStore(subscribe, () => box.current)
76
+
77
+ // compute the imperative handle for this artifact
78
+ const handle = useDocumentHandle<_Artifact, _Data, _Input>({
79
+ artifact,
80
+ observer,
81
+ storeValue,
82
+ })
83
+
84
+ // if the identifier changes, we need to remove the old identifier from the
85
+ // suspense cache
86
+ React.useEffect(() => {
87
+ return () => {
88
+ promiseCache.delete(identifier)
89
+ }
90
+ }, [identifier])
91
+
92
+ // when we unmount, we need to clean up
93
+ React.useEffect(() => {
94
+ return () => {
95
+ observer.cleanup()
96
+ }
97
+ }, [observer])
98
+
99
+ // if the promise has resolved, let's use that for our first render
100
+ let result = storeValue.data
101
+
102
+ if (!suspenseValue) {
103
+ // we are going to cache the promise and then throw it
104
+ // when it resolves the cached value will be updated
105
+ // and it will be picked up in the next render
106
+ let resolve: () => void = () => {}
107
+ const loadPromise = new Promise<void>((r) => (resolve = r))
108
+
109
+ const suspenseUnit: QuerySuspenseUnit = {
110
+ then: loadPromise.then.bind(loadPromise),
111
+ resolve,
112
+ // @ts-ignore
113
+ variables,
114
+ }
115
+
116
+ // @ts-ignore
117
+ promiseCache.set(identifier, suspenseUnit)
118
+
119
+ // the suspense unit gives react something to hold onto
120
+ // and it acts as a place for us to register a callback on
121
+ // send to update the cache before resolving the suspense
122
+ handle
123
+ .fetch({
124
+ variables,
125
+ // @ts-ignore: this is actually allowed... 🤫
126
+ stuff: {
127
+ silenceLoading: true,
128
+ },
129
+ })
130
+ .then((value) => {
131
+ // @ts-expect-error
132
+ // the final value
133
+ suspenseUnit.resolved = {
134
+ ...handle,
135
+ data: value.data,
136
+ partia: value.partial,
137
+ artifact,
138
+ }
139
+
140
+ suspenseUnit.resolve()
141
+ })
142
+ suspenseTracker.current = true
143
+ throw suspenseUnit
144
+ }
145
+
146
+ // if the promise is still pending, we're still waiting
147
+ if (!result && suspenseValue && !suspenseValue.resolved) {
148
+ suspenseTracker.current = true
149
+ throw suspenseValue
150
+ }
151
+
152
+ // make sure we prefer the latest store value instead of the initial version we loaded on mount
153
+ if (!result && suspenseValue?.resolved) {
154
+ return suspenseValue.resolved as unknown as DocumentHandle<_Artifact, _Data, _Input>
155
+ }
156
+
157
+ return {
158
+ ...handle,
159
+ variables: storeValue.variables,
160
+ data: result,
161
+ }
162
+ }
163
+
164
+ export type UseQueryConfig = {
165
+ policy?: CachePolicies
166
+ metadata?: App.Metadata
167
+ fetchKey?: any
168
+ }
169
+
170
+ function queryIdentifier(args: {
171
+ artifact: QueryArtifact
172
+ fetchKey?: number
173
+ variables: {}
174
+ config: UseQueryConfig
175
+ }): string {
176
+ // make sure there is always a fetchKey
177
+ args.fetchKey ??= 0
178
+
179
+ // pull the common stuff out
180
+ const { artifact, variables, fetchKey } = args
181
+
182
+ // a query identifier is a mix of its name, arguments, and the fetch key
183
+ return [artifact.name, JSON.stringify(variables), fetchKey].join('@@')
184
+ }
@@ -0,0 +1,12 @@
1
+ import type { SubscriptionArtifact, GraphQLObject, GraphQLVariables } from 'houdini/runtime'
2
+
3
+ import { useSubscriptionHandle } from './useSubscriptionHandle'
4
+
5
+ // a hook to subscribe to a subscription artifact
6
+ export function useSubscription<_Result extends GraphQLObject, _Input extends GraphQLVariables>(
7
+ document: { artifact: SubscriptionArtifact },
8
+ variables: _Input
9
+ ) {
10
+ const { data } = useSubscriptionHandle(document, variables)
11
+ return data
12
+ }
@@ -0,0 +1,33 @@
1
+ import type { SubscriptionArtifact, GraphQLObject, GraphQLVariables } from 'houdini/runtime'
2
+
3
+ import { useDocumentSubscription } from './useDocumentSubscription'
4
+
5
+ export type SubscriptionHandle<_Result extends GraphQLObject, _Input extends GraphQLVariables> = {
6
+ data: _Result | null
7
+ errors: { message: string }[] | null
8
+ variables: _Input
9
+ listen: (args: { variables?: _Input }) => void
10
+ unlisten: () => void
11
+ fetching: boolean
12
+ }
13
+
14
+ // a hook to subscribe to a subscription artifact
15
+ export function useSubscriptionHandle<
16
+ _Result extends GraphQLObject,
17
+ _Input extends GraphQLVariables
18
+ >({ artifact }: { artifact: SubscriptionArtifact }, variables: _Input) {
19
+ // a subscription is basically just a live document
20
+ const [storeValue, observer] = useDocumentSubscription({
21
+ artifact,
22
+ variables,
23
+ })
24
+
25
+ return {
26
+ data: storeValue.data,
27
+ errors: storeValue.errors,
28
+ fetching: storeValue.fetching,
29
+ variables,
30
+ unlisten: observer.cleanup,
31
+ listen: observer.send,
32
+ }
33
+ }
@@ -0,0 +1,49 @@
1
+ import type { GraphQLObject } from 'houdini/runtime'
2
+ import type { Cache } from 'houdini/runtime/cache'
3
+
4
+ import client from './client'
5
+ import manifest from './manifest'
6
+ import { Router as RouterImpl, RouterCache, RouterContextProvider } from './routing'
7
+
8
+ export * from './hooks'
9
+ export { router_cache, useSession, useLocation, useRoute } from './routing'
10
+
11
+ export function Router({
12
+ cache,
13
+ initialURL,
14
+ artifact_cache,
15
+ component_cache,
16
+ data_cache,
17
+ ssr_signals,
18
+ last_variables,
19
+ session,
20
+ assetPrefix,
21
+ injectToStream,
22
+ }: {
23
+ initialURL: string
24
+ initialVariables: GraphQLObject
25
+ cache: Cache
26
+ session?: App.Session
27
+ assetPrefix: string
28
+ injectToStream?: (chunk: string) => void
29
+ } & RouterCache) {
30
+ return (
31
+ <RouterContextProvider
32
+ client={client()}
33
+ cache={cache}
34
+ artifact_cache={artifact_cache}
35
+ component_cache={component_cache}
36
+ data_cache={data_cache}
37
+ ssr_signals={ssr_signals}
38
+ last_variables={last_variables}
39
+ session={session}
40
+ >
41
+ <RouterImpl
42
+ initialURL={initialURL}
43
+ manifest={manifest}
44
+ assetPrefix={assetPrefix}
45
+ injectToStream={injectToStream}
46
+ />
47
+ </RouterContextProvider>
48
+ )
49
+ }
@@ -0,0 +1,6 @@
1
+ import type { RouterManifest } from 'houdini/runtime'
2
+
3
+ // @ts-ignore: this file will get replaced by the build system
4
+ const manifest: RouterManifest = {}
5
+
6
+ export default manifest
@@ -0,0 +1 @@
1
+ {"type":"module"}