Skip to content

Commit

Permalink
chore: add custom sw logic + example
Browse files Browse the repository at this point in the history
  • Loading branch information
userquin committed Mar 23, 2024
1 parent c9a21c2 commit 77e6bf0
Show file tree
Hide file tree
Showing 37 changed files with 817 additions and 92 deletions.
5 changes: 3 additions & 2 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default defineBuildConfig([{
}, {
entries: [
{ input: 'src/components/index' },
{ input: 'src/sw/offline' },
{ input: 'src/sw/index' },
],
clean: false,
declaration: true,
Expand All @@ -31,7 +31,8 @@ export default defineBuildConfig([{
'react-dom',
'virtual:pwa-info',
'virtual:pwa-assets/head',
'virtual:vite-pwa/remix/routes',
'virtual:vite-pwa/remix/sw',
'workbox-core',
'workbox-precaching',
'workbox-routing',
],
Expand Down
2 changes: 1 addition & 1 deletion examples/pwa-assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"typescript": "^5.4.3",
"vite": "^5.2.3",
"vite": "^5.2.4",
"vite-tsconfig-paths": "^4.2.1"
},
"engines": {
Expand Down
1 change: 0 additions & 1 deletion examples/pwa-assets/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export default defineConfig({
tsconfigPaths(),
RemixVitePWAPlugin({
mode: 'development',
srcDir: 'app',
base: '/',
registerType: 'autoUpdate',
manifest: {
Expand Down
22 changes: 22 additions & 0 deletions examples/pwa-simple-sw/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* 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 { StrictMode, startTransition } from 'react'
import { hydrateRoot } from 'react-dom/client'

// something weird with import.meta.env with remix
if (import.meta.env.VITE_PUBLIC_VIRTUAL_PWA_MODULE === 'true')
import('./pwa')

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>,
)
})
137 changes: 137 additions & 0 deletions examples/pwa-simple-sw/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/**
* By default, Remix will handle generating the HTTP Response 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.server
*/

import { PassThrough } from 'node:stream'

import type { AppLoadContext, EntryContext } from '@remix-run/node'
import { createReadableStreamFromReadable } from '@remix-run/node'
import { RemixServer } from '@remix-run/react'
import { isbot } from 'isbot'
import { renderToPipeableStream } from 'react-dom/server'

const ABORT_DELAY = 5_000

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// 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!
_loadContext: AppLoadContext,
) {
return isbot(request.headers.get('user-agent') || '')
? handleBotRequest(
request,
responseStatusCode,
responseHeaders,
remixContext,
)
: handleBrowserRequest(
request,
responseStatusCode,
responseHeaders,
remixContext,
)
}

function handleBotRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
return new Promise((resolve, reject) => {
let shellRendered = false
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onAllReady() {
shellRendered = true
const body = new PassThrough()
const stream = createReadableStreamFromReadable(body)

responseHeaders.set('Content-Type', 'text/html')

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
}),
)

pipe(body)
},
onShellError(error: unknown) {
reject(error)
},
onError(error: unknown) {
responseStatusCode = 500
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered)
console.error(error)
},
},
)

setTimeout(abort, ABORT_DELAY)
})
}

function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
return new Promise((resolve, reject) => {
let shellRendered = false
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onShellReady() {
shellRendered = true
const body = new PassThrough()
const stream = createReadableStreamFromReadable(body)

responseHeaders.set('Content-Type', 'text/html')

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
}),
)

pipe(body)
},
onShellError(error: unknown) {
reject(error)
},
onError(error: unknown) {
responseStatusCode = 500
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered)
console.error(error)
},
},
)

setTimeout(abort, ABORT_DELAY)
})
}
27 changes: 27 additions & 0 deletions examples/pwa-simple-sw/app/plain-sw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/// <reference types="vite/client" />
/// <reference lib="webworker" />
import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching'
import { clientsClaim } from 'workbox-core'
import { NavigationRoute, registerRoute } from 'workbox-routing'

declare let self: ServiceWorkerGlobalScope

// self.__WB_MANIFEST is default injection point
precacheAndRoute(self.__WB_MANIFEST)

// clean old assets
cleanupOutdatedCaches()

let allowlist: undefined | RegExp[]

if (import.meta.env.DEV)
allowlist = [/^\/$/]

// to allow work offline
registerRoute(new NavigationRoute(
createHandlerBoundToURL('/'),
{ allowlist },
))

self.skipWaiting()
clientsClaim()
13 changes: 13 additions & 0 deletions examples/pwa-simple-sw/app/pwa.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { registerSW } from 'virtual:pwa-register'

// if (window.ENV.VITE_VIRTUAL_PWA_MODULE) {
registerSW({
immediate: true,
onRegisteredSW(swScriptUrl) {
console.log('SW registered: ', swScriptUrl)
},
onOfflineReady() {
console.log('PWA application ready to work offline')
},
})
// }
51 changes: 51 additions & 0 deletions examples/pwa-simple-sw/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from '@remix-run/react'
import { PWAManifest } from '@vite-pwa/remix/components'

// export async function loader() {
// return json({
// ENV: {
// VITE_VIRTUAL_PWA_MODULE: process.env.VITE_VIRTUAL_PWA_MODULE,
// },
// })
// }
//
export function Layout({ children }: { children: React.ReactNode }) {
// const data = useLoaderData<typeof loader>()
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#ffffff" />
<link href="/favicon.ico" rel="icon" sizes="48x48" />
<link href="/favicon.svg" rel="icon" sizes="any" type="image/svg+xml" />
<link href="/apple-touch-icon-180x180.png" rel="apple-touch-icon" />
<Meta />
<PWAManifest />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
{/* <script
dangerouslySetInnerHTML={{
__html: `window.ENV = ${JSON.stringify(
data.ENV,
)}`,
}}
/> */}
<Scripts />
</body>
</html>
)
}

export default function App() {
return <Outlet />
}
17 changes: 17 additions & 0 deletions examples/pwa-simple-sw/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { MetaFunction } from '@remix-run/node'

export const meta: MetaFunction = () => {
return [
{ title: 'Remix PWA App' },
{ name: 'description', content: 'Welcome to Remix PWA!' },
]
}

export default function Index() {
return (
<div style={{ fontFamily: 'system-ui, sans-serif', lineHeight: '1.8' }}>
<h1>Welcome to Remix</h1>
<pre>{import.meta.env.VITE_BUILD_DATE}</pre>
</div>
)
}
10 changes: 10 additions & 0 deletions examples/pwa-simple-sw/app/sw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { setupPwa } from '@vite-pwa/remix/sw'

declare const self: ServiceWorkerGlobalScope

setupPwa({
manifest: self.__WB_MANIFEST,
configureRoutes(routes, ssr) {
console.log('PWA routes:', { 'SSR:': ssr, routes })
},
})
13 changes: 13 additions & 0 deletions examples/pwa-simple-sw/app/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/// <reference types="vite/client" />

// FOR TESTING PURPOSES ONLY IN THIS REPO
interface ImportMetaEnv {
readonly VITE_PUBLIC_VIRTUAL_PWA_MODULE: string
readonly VITE_VIRTUAL_PWA_MODULE: boolean
readonly VITE_BUILD_DATE: string
// more env variables...
}

interface ImportMeta {
readonly env: ImportMetaEnv
}
52 changes: 52 additions & 0 deletions examples/pwa-simple-sw/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "pwa-simple-sw",
"private": true,
"sideEffects": false,
"type": "module",
"scripts": {
"dev": "VIRTUAL_PWA_MODULE=true remix vite:dev",
"dev:spa": "VIRTUAL_PWA_MODULE=true SPA=true remix vite:dev",
"dev:auto": "remix vite:dev",
"dev:auto:spa": "SPA=true remix vite:dev",
"dev:plain": "PLAIN_SW=true remix vite:dev",
"dev:plain:spa": "PLAIN_SW=true SPA=true remix vite:dev",
"build": "VIRTUAL_PWA_MODULE=true remix vite:build",
"build:spa": "VIRTUAL_PWA_MODULE=true SPA=true remix vite:build",
"build:auto": "remix vite:build",
"build:auto:spa": "SPA=true remix vite:build",
"build:plain": "PLAIN_SW=true remix vite:build",
"build:plain:spa": "PLAIN_SW=true SPA=true remix vite:build",
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "remix-serve ./build/server/index.js",
"start:spa": "npx serve build/client",
"typecheck": "tsc"
},
"dependencies": {
"@remix-run/node": "^2.8.1",
"@remix-run/react": "^2.8.1",
"@remix-run/serve": "^2.8.1",
"isbot": "^4.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@remix-run/dev": "^2.8.1",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"@vite-pwa/remix": "workspace:*",
"eslint": "^8.57.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"typescript": "^5.4.3",
"vite": "^5.2.4",
"vite-tsconfig-paths": "^4.2.1"
},
"engines": {
"node": ">=18.0.0"
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/pwa-simple-sw/public/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions examples/pwa-simple-sw/public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/pwa-simple-sw/public/pwa-192x192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/pwa-simple-sw/public/pwa-512x512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/pwa-simple-sw/public/pwa-64x64.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions examples/pwa-simple-sw/public/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
User-agent: *
Allow: /
Loading

0 comments on commit 77e6bf0

Please sign in to comment.