-
Notifications
You must be signed in to change notification settings - Fork 246
feat: styled-components & streaming #588
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
Draft
wetteyve
wants to merge
7
commits into
remix-run:main
Choose a base branch
from
wetteyve:styled-components
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
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.
+260
−84
Draft
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4c36906
feat: upgrade to remix v2, react v19, styled-components v6 & switch t…
wetteyve a762768
refactor: move ErrorBoundary into root.tsx file
wetteyve ebd585b
refactor: remove entry.client.ts and unused color highlight
wetteyve c68902a
refactor: remove falsly commited declaration file
wetteyve 4a96bcd
fix: add unnamed route _boundary
wetteyve 34ea2a3
chore: align eslint with example and add comment in root.tsx
wetteyve 8a7e111
refactor: cleanup root.tsx
wetteyve File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,18 @@ | ||
/** | ||
* By default, Remix will handle hydrating your app on the client for you. | ||
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ | ||
* For more information, see https://remix.run/file-conventions/entry.client | ||
*/ | ||
|
||
import { RemixBrowser } from "@remix-run/react"; | ||
import { startTransition, StrictMode } from "react"; | ||
import { hydrateRoot } from "react-dom/client"; | ||
|
||
startTransition(() => { | ||
hydrateRoot( | ||
document, | ||
<StrictMode> | ||
<RemixBrowser /> | ||
</StrictMode> | ||
); | ||
}); |
This file contains hidden or 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 |
---|---|---|
@@ -1,30 +1,99 @@ | ||
import { PassThrough, Transform } from "stream"; | ||
|
||
import type { AppLoadContext, EntryContext } from "@remix-run/node"; | ||
import { createReadableStreamFromReadable } from "@remix-run/node"; | ||
import { RemixServer } from "@remix-run/react"; | ||
import { renderToString } from "react-dom/server"; | ||
import { ServerStyleSheet } from "styled-components"; | ||
import { renderToPipeableStream } from "react-dom/server"; | ||
import { ServerStyleSheet, StyleSheetManager } from "styled-components"; | ||
import { isbot } from "isbot"; | ||
|
||
// Reject/cancel all pending promises after 5 seconds | ||
export const streamTimeout = 15000; | ||
|
||
export default function handleRequest( | ||
request: Request, | ||
responseStatusCode: number, | ||
responseHeaders: Headers, | ||
remixContext: EntryContext, | ||
loadContext: AppLoadContext, | ||
// This is ignored so we can keep it in the template for visibility. Feel | ||
// free to delete this parameter in your app if you're not using it! | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
loadContext: AppLoadContext | ||
) { | ||
const sheet = new ServerStyleSheet(); | ||
const styleSheet = new ServerStyleSheet(); | ||
const decoder = new TextDecoder("utf-8"); | ||
// Stream interceptor in order to inject additional HTML on the fly | ||
const transformer = transformStream({ decoder, styleSheet }); | ||
|
||
const callbackName = isbot(request.headers.get("user-agent")) | ||
? "onAllReady" | ||
: "onShellReady"; | ||
|
||
// eslint-disable-next-line no-async-promise-executor | ||
return new Promise(async (resolve, reject) => { | ||
let didError = false; | ||
|
||
let markup = renderToString( | ||
sheet.collectStyles( | ||
<RemixServer context={remixContext} url={request.url} />, | ||
), | ||
); | ||
const styles = sheet.getStyleTags(); | ||
const { pipe, abort } = renderToPipeableStream( | ||
<StyleSheetManager sheet={styleSheet.instance}> | ||
<RemixServer context={remixContext} url={request.url} /> | ||
</StyleSheetManager>, | ||
{ | ||
[callbackName]: () => { | ||
const body = new PassThrough(); | ||
responseHeaders.set("Content-Type", "text/html"); | ||
|
||
markup = markup.replace("__STYLES__", styles); | ||
pipe(transformer); | ||
transformer.pipe(body); | ||
|
||
responseHeaders.set("Content-Type", "text/html"); | ||
resolve( | ||
new Response(createReadableStreamFromReadable(body), { | ||
status: didError ? 500 : responseStatusCode, | ||
headers: responseHeaders, | ||
}) | ||
); | ||
}, | ||
onShellError: (err: unknown) => { | ||
reject(err); | ||
}, | ||
onError: () => { | ||
didError = true; | ||
}, | ||
} | ||
); | ||
|
||
return new Response("<!DOCTYPE html>" + markup, { | ||
status: responseStatusCode, | ||
headers: responseHeaders, | ||
// Automatically timeout the React renderer after 6 seconds, which ensures | ||
// React has enough time to flush down the rejected boundary contents | ||
setTimeout(abort, streamTimeout + 1000); | ||
}); | ||
} | ||
|
||
/** | ||
* Returns a Transform stream that injects styled-components styles into streamed HTML. | ||
* - Replaces `__STYLES__` with styled-components CSS. | ||
*/ | ||
const transformStream = ({ | ||
decoder, | ||
styleSheet, | ||
}: { | ||
decoder: TextDecoder; | ||
styleSheet: ServerStyleSheet; | ||
}) => | ||
new Transform({ | ||
objectMode: true, | ||
flush(callback) { | ||
callback(); | ||
}, | ||
transform(chunk, encoding, callback) { | ||
let renderedHtml = | ||
chunk instanceof Uint8Array | ||
? decoder.decode(chunk, { stream: true }) | ||
: chunk.toString(encoding || "utf8"); | ||
renderedHtml = renderedHtml.replace( | ||
"__STYLES__", | ||
styleSheet.getStyleTags() | ||
); | ||
this.push(renderedHtml); | ||
|
||
callback(); | ||
}, | ||
}); |
This file contains hidden or 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 hidden or 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 |
---|---|---|
@@ -1,30 +1,33 @@ | ||
import { Outlet, useCatch } from "@remix-run/react"; | ||
import { isRouteErrorResponse, useRouteError } from "@remix-run/react"; | ||
|
||
import { Box } from "~/components/Box"; | ||
|
||
export default function Boundary() { | ||
return <Outlet />; | ||
} | ||
export function ErrorBoundary() { | ||
const error = useRouteError(); | ||
|
||
export function CatchBoundary() { | ||
const caught = useCatch(); | ||
if (isRouteErrorResponse(error)) { | ||
return ( | ||
<Box> | ||
<h1>Catch Boundary</h1> | ||
<p> | ||
{error.status} {error.statusText} | ||
</p> | ||
</Box> | ||
); | ||
} | ||
|
||
return ( | ||
<Box> | ||
<h1>Catch Boundary</h1> | ||
<p> | ||
{caught.status} {caught.statusText} | ||
</p> | ||
</Box> | ||
); | ||
} | ||
let errorMessage = "Unknown error"; | ||
let errorStatus = 500; | ||
if (error instanceof Error) { | ||
errorMessage = error.message; | ||
} | ||
|
||
export function ErrorBoundary({ error }: { error: Error }) { | ||
return ( | ||
<Box> | ||
<h1>Error Boundary</h1> | ||
<p>{error.message}</p> | ||
<pre>{error.stack}</pre> | ||
<h1>Error Boundary</h1> | ||
<p> | ||
{errorStatus} {errorMessage} | ||
</p> | ||
</Box> | ||
); | ||
} | ||
} |
This file contains hidden or 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 |
---|---|---|
@@ -1,4 +1,4 @@ | ||
import * as React from "react"; | ||
const StylesContext = React.createContext<null | React.ReactNode>(null); | ||
export const StylesProvider = StylesContext.Provider; | ||
export const useStyles = () => React.useContext(StylesContext); | ||
export const useStyles = () => React.useContext(StylesContext); |
This file contains hidden or 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 @@ | ||
export declare const Box: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").ClassAttributes<HTMLDivElement> & import("react").HTMLAttributes<HTMLDivElement>, never>> & string; |
This file contains hidden or 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 |
---|---|---|
@@ -1,6 +1,7 @@ | ||
import styled from "styled-components"; | ||
import { styled } from "styled-components"; | ||
|
||
export const Box = styled("div")` | ||
font-family: system-ui, sans-serif; | ||
line-height: 1.8; | ||
background-color: red; | ||
`; |
This file contains hidden or 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 hidden or 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 was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains hidden or 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 |
---|---|---|
@@ -1,22 +1,22 @@ | ||
{ | ||
"include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"], | ||
"include": ["**/*.ts", "**/*.tsx"], | ||
"compilerOptions": { | ||
"lib": ["DOM", "DOM.Iterable", "ES2019"], | ||
"lib": ["DOM", "DOM.Iterable", "ES2022"], | ||
"types": ["@remix-run/node", "vite/client"], | ||
"isolatedModules": true, | ||
"esModuleInterop": true, | ||
"jsx": "react-jsx", | ||
"moduleResolution": "node", | ||
"module": "ESNext", | ||
"moduleResolution": "Bundler", | ||
"resolveJsonModule": true, | ||
"target": "ES2019", | ||
"target": "ES2022", | ||
"strict": true, | ||
"allowJs": true, | ||
"skipLibCheck": true, | ||
"forceConsistentCasingInFileNames": true, | ||
"baseUrl": ".", | ||
"paths": { | ||
"~/*": ["./app/*"] | ||
}, | ||
|
||
// Remix takes care of building everything in `remix build`. | ||
"noEmit": true | ||
} | ||
} | ||
} |
This file contains hidden or 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,24 @@ | ||
import { vitePlugin as remix } from "@remix-run/dev"; | ||
import { defineConfig } from "vite"; | ||
import tsconfigPaths from "vite-tsconfig-paths"; | ||
|
||
declare module "@remix-run/node" { | ||
interface Future { | ||
v3_singleFetch: true; | ||
} | ||
} | ||
|
||
export default defineConfig({ | ||
plugins: [ | ||
remix({ | ||
future: { | ||
v3_fetcherPersist: true, | ||
v3_relativeSplatPath: true, | ||
v3_throwAbortReason: true, | ||
v3_singleFetch: true, | ||
v3_lazyRouteDiscovery: true, | ||
}, | ||
}), | ||
tsconfigPaths(), | ||
], | ||
}); |
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.
Isn't it possible for the
__STYLES__
string to be truncated across two different chunks?In that case, the styles would not get replaced.
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.
in theory this could be true, you're right. unfortunately i don't understand node streaming and how the chunks are cut in depth. however, we have been using this approach in production for 2 weeks (first with remix v2 and now with react-router v7) and have never noticed this side effect.
Uh oh!
There was an error while loading. Please reload this page.
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.
In my own project, I ended up using
Which handles chunk boundaries correctly, but I'd lean against including that additional dependency in this pull request.
I do think the edge case should be handled correctly, but I don't have any alternative suggestions as to how, other than reimplementing similar logic. But that seems like overkill maybe 🤷♂️