New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
WIP: RSC sub route #1858
Draft
wizardlyhel
wants to merge
23
commits into
v1.x-2022-07
Choose a base branch
from
sub-routes
base: v1.x-2022-07
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
WIP: RSC sub route #1858
Changes from 15 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
971ee9b
prototype sub route
wizardlyhel c650fa0
working sub routes
wizardlyhel 8b965d9
don't rsc render on sub routes
wizardlyhel e1a8678
supply different app wrapper for sub routes
wizardlyhel 61b87d4
simplify sub route wrapper
wizardlyhel ca03334
different way of wrapping rsc sub route client
wizardlyhel 1459acf
fix preload on sub routes
wizardlyhel 4e90f34
add pending state
wizardlyhel a1dadc5
remove used lib
wizardlyhel 4b72e72
log request id in query timing
wizardlyhel a7d83dd
make sure we use oxygen api token
wizardlyhel e209ac7
merge with v1.x-2022-07
wizardlyhel 1fded73
working with defineOutlet
wizardlyhel abb5c2e
prevent outlet from preload
wizardlyhel 0f72002
lint fix
wizardlyhel 14a5981
test demo with global outlets
wizardlyhel 9c06f7a
refactor to sections
wizardlyhel d2a45be
rename to Hydrogen Section
wizardlyhel 7107bf6
add error fallback
wizardlyhel 47ee36f
stuff
wizardlyhel 5080a1c
fix weird jsxDEV issue
wizardlyhel 9da85d8
clean up
wizardlyhel 266a9a7
remove default error fallback
wizardlyhel File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
126 changes: 126 additions & 0 deletions
126
packages/hydrogen/src/foundation/RSCSubRoute/RSCSubRoute.client.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
import React, { | ||
useEffect, | ||
useState, | ||
ReactElement, | ||
useTransition, | ||
Suspense, | ||
} from 'react'; | ||
import {ErrorBoundary} from 'react-error-boundary'; | ||
import { | ||
createFromFetch, | ||
// @ts-ignore | ||
} from '@shopify/hydrogen/vendor/react-server-dom-vite'; | ||
import {RSC_PATHNAME} from '../../constants'; | ||
|
||
type RSCSubRouteClientProps = { | ||
outletName: string; | ||
/** The state of this RSC route */ | ||
state: any; | ||
isRSC: boolean; | ||
children?: ReactElement; | ||
}; | ||
|
||
const DEFAULT_MAX_AGE = 500; | ||
const cache = new Map(); | ||
|
||
export function RSCSubRouteClient({ | ||
outletName, | ||
state, | ||
isRSC, | ||
children, | ||
}: RSCSubRouteClientProps) { | ||
console.log('RSCSubRouteClient', outletName); | ||
const [_, startTransition] = useTransition(); | ||
const [response, setResponse] = useState(<Suspense>{children}</Suspense>); | ||
const [expiry, setExpiry] = useState(Date.now() + DEFAULT_MAX_AGE); | ||
|
||
useEffect(() => { | ||
if (isRSC || expiry < Date.now()) { | ||
console.log('isRsc', isRSC); | ||
startTransition(() => { | ||
const cachedEntry = getSubServerResponse({ | ||
...state, | ||
pathname: window.location.pathname, | ||
search: window.location.search, | ||
outlet: outletName, | ||
}); | ||
if (cachedEntry.expiry > expiry) { | ||
setExpiry(cachedEntry.expiry); | ||
setResponse(cachedEntry.response); | ||
} | ||
}); | ||
} | ||
}, [isRSC, expiry]); | ||
|
||
return ( | ||
<ErrorBoundary | ||
fallbackRender={() => { | ||
return null; | ||
}} | ||
> | ||
{/* @ts-ignore */} | ||
{response && response.readRoot ? response.readRoot() : response} | ||
</ErrorBoundary> | ||
); | ||
} | ||
|
||
function getSubServerResponse(state: any) { | ||
const key = JSON.stringify(state); | ||
|
||
const cacheEntry = cache.get(key); | ||
|
||
console.log('cache', state.outlet, cacheEntry); | ||
|
||
if (cacheEntry && Date.now() < cacheEntry.expiry) { | ||
console.log('cached', cacheEntry); | ||
return cacheEntry.response; | ||
} | ||
|
||
console.log('fetch', key); | ||
|
||
const response = createFromFetch( | ||
fetch(`${RSC_PATHNAME}?state=` + encodeURIComponent(key)).then((res) => { | ||
// let maxAge: number = DEFAULT_MAX_AGE; | ||
// const cacheControl = res.headers.get('cache-control'); | ||
|
||
// if (cacheControl) { | ||
// const maxAgeMatch = cacheControl.match(/max-age=(\d*)/); | ||
// if (maxAgeMatch) { | ||
// try { | ||
// maxAge = parseInt(maxAgeMatch[1]) * 1000; | ||
// } catch { | ||
// maxAge = DEFAULT_MAX_AGE; | ||
// } | ||
// } | ||
// } | ||
|
||
// mergeCacheEntry(key, { | ||
// expiry: | ||
// Math.floor(res.status / 100) === 2 | ||
// ? Date.now() + maxAge | ||
// : Date.now() + DEFAULT_MAX_AGE, | ||
// }); | ||
|
||
return res; | ||
}) | ||
); | ||
|
||
// mergeCacheEntry(key, { | ||
// response, | ||
// }); | ||
|
||
cache.set(key, { | ||
response, | ||
expiry: Date.now() + DEFAULT_MAX_AGE, | ||
}); | ||
|
||
return cache.get(key); | ||
} | ||
|
||
// function mergeCacheEntry(key: string, data: any) { | ||
// const cachedData = cache.get(key); | ||
// cache.set(key, { | ||
// ...cachedData, | ||
// ...data, | ||
// }); | ||
// } |
93 changes: 93 additions & 0 deletions
93
packages/hydrogen/src/foundation/RSCSubRoute/RSCSubRoute.server.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
import React, {ReactElement} from 'react'; | ||
import {CachingStrategy} from '../../types'; | ||
import {CacheShort} from '../Cache/strategies'; | ||
// import {ErrorBoundary} from 'react-error-boundary'; | ||
import {useServerRequest} from '../ServerRequestProvider'; | ||
import {RSCSubRouteClient} from './RSCSubRoute.client'; | ||
|
||
export type RSCSubRouteProps = { | ||
outletName: string; | ||
/** The server props of this RSC route */ | ||
serverProps: any; | ||
/** The state of this RSC route */ | ||
state: any; | ||
cache: CachingStrategy; | ||
/** A reference to a React Server Component that's rendered when the route is active. */ | ||
component: ({...componentProps}: any) => JSX.Element | undefined; | ||
fallback?: ReactElement; | ||
}; | ||
|
||
export function RSCSubRoute({ | ||
outletName, | ||
serverProps, | ||
state, | ||
component, | ||
cache, | ||
fallback, | ||
}: RSCSubRouteProps) { | ||
// console.log('RSCSubRoute', state, component); | ||
const request = useServerRequest(); | ||
const isRSC = request.isRscRequest(); | ||
|
||
if (serverProps.outlet && component) { | ||
console.log('RSCSub', serverProps.outlet, serverProps.response.cache); | ||
serverProps.response.cache(cache); | ||
return component ? component(state) : null; | ||
} else if (isRSC) { | ||
console.log('RSCSub - RSC'); | ||
return ( | ||
<RSCSubRouteClient outletName={outletName} state={state} isRSC={isRSC} /> | ||
); | ||
} else { | ||
console.log('RSCSub - SSR'); | ||
return ( | ||
<RSCSubRouteClient outletName={outletName} state={state} isRSC={isRSC}> | ||
{component(serverProps)} | ||
</RSCSubRouteClient> | ||
); | ||
} | ||
} | ||
|
||
export function defineRSCOutlet({ | ||
outletName, | ||
component, | ||
dependency = [], | ||
cache = CacheShort(), | ||
fallback, | ||
}: { | ||
outletName: string; | ||
component: ({...componentProps}: any) => JSX.Element; | ||
dependency?: string[]; | ||
cache?: CachingStrategy; | ||
fallback?: ReactElement; | ||
}) { | ||
return (serverProps: any) => { | ||
console.log('defineOutlet', component); | ||
|
||
const dependencyState = dependency.reduce(function (obj: any, key) { | ||
if (key in serverProps) obj[key] = serverProps[key]; | ||
return obj; | ||
}, {}); | ||
|
||
serverProps.response?.cache(cache); | ||
|
||
return ( | ||
<> | ||
{/* @ts-ignore */} | ||
<RSCSubRoute | ||
outletName={outletName} | ||
serverProps={serverProps} | ||
state={{ | ||
...dependencyState, | ||
pathname: serverProps.pathname, | ||
search: serverProps.search, | ||
outlet: serverProps.outlet, | ||
}} | ||
cache={cache} | ||
component={component} | ||
fallback={fallback} | ||
/> | ||
</> | ||
); | ||
}; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@frandiox I want to gather on your thoughts on this
So I have been noodling on this pattern for the outlets and I am wondering if it is do-able for the full page SSR as well.
What this code piece is doing ...
Say we have a server component
On SSR pass for
/product/123
, this will render the SSR output ofProduct
and aRSCSubRouteClient
. We don't need a RSC payload to hydrate because the children ofRSCSubRouteClient
is the exact content we need.On RSC pass for
/product/123
, this will just renderRSCSubRouteClient
with the stateThe content of this route
<p>Product title</p>
will be replaced byrscResponse.readRoot()
Do you think it is possible to do the same for the full page SSR render and we can drop the 2nd RSC pass entirely?