Skip to content
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

feat: prevent FOUC with SSR in dev #5

Merged
merged 8 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions factories/inertia_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* file that was distributed with this source code.
*/

import type { ViteDevServer } from 'vite'
import type { ViteRuntime } from 'vite/runtime'
import { HttpContext } from '@adonisjs/core/http'
import { AppFactory } from '@adonisjs/core/factories/app'
Expand All @@ -30,7 +31,7 @@ export class InertiaFactory {
#parameters: FactoryParameters = {
ctx: new HttpContextFactory().create(),
}
#viteRuntime?: ViteRuntime
#vite?: { runtime: ViteRuntime; devServer: ViteDevServer }

#getApp() {
return new AppFactory().create(new URL('./', import.meta.url), () => {}) as ApplicationService
Expand All @@ -52,8 +53,8 @@ export class InertiaFactory {
return this
}

withViteRuntime(runtime: { executeEntrypoint: (path: string) => Promise<any> }) {
this.#viteRuntime = runtime as any
withVite(options: { runtime: ViteRuntime; devServer: ViteDevServer }) {
this.#vite = options
return this
}

Expand All @@ -69,6 +70,6 @@ export class InertiaFactory {

async create() {
const config = await defineConfig(this.#parameters.config || {}).resolver(this.#getApp())
return new Inertia(this.#parameters.ctx, config, this.#viteRuntime)
return new Inertia(this.#parameters.ctx, config, this.#vite?.runtime, this.#vite?.devServer)
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"crc-32": "^1.2.2",
"edge-error": "^4.0.1",
"html-entities": "^2.4.0",
"locate-path": "^7.2.0",
"qs": "^6.11.2"
},
"peerDependencies": {
Expand Down
8 changes: 7 additions & 1 deletion providers/inertia_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
/// <reference types="@adonisjs/vite/vite_provider" />

import { configProvider } from '@adonisjs/core'
import { BriskRoute } from '@adonisjs/core/http'
import { RuntimeException } from '@poppinss/utils'
import type { ApplicationService } from '@adonisjs/core/types'

import InertiaMiddleware from '../src/inertia_middleware.js'
import type { InertiaConfig, ResolvedConfig } from '../src/types.js'
import { BriskRoute } from '@adonisjs/core/http'

declare module '@adonisjs/core/http' {
interface BriskRoute {
Expand Down Expand Up @@ -48,6 +48,9 @@ export default class InertiaProvider {
edgeExports.default.use(edgePluginInertia())
}

/**
* Register inertia middleware
*/
async register() {
this.app.container.singleton(InertiaMiddleware, async () => {
const inertiaConfigProvider = this.app.config.get<InertiaConfig>('inertia')
Expand All @@ -64,6 +67,9 @@ export default class InertiaProvider {
})
}

/**
* Register edge plugin and brisk route macro
*/
async boot() {
await this.registerEdgePlugin()

Expand Down
12 changes: 9 additions & 3 deletions src/define_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,31 @@ import { configProvider } from '@adonisjs/core'
import type { ConfigProvider } from '@adonisjs/core/types'

import { VersionCache } from './version_cache.js'
import { FilesDetector } from './files_detector.js'
import type { InertiaConfig, ResolvedConfig } from './types.js'
import { slash } from '@poppinss/utils'

/**
* Define the Inertia configuration
*/
export function defineConfig(config: InertiaConfig): ConfigProvider<ResolvedConfig> {
return configProvider.create(async (app) => {
const detector = new FilesDetector(app)
const versionCache = new VersionCache(app.appRoot, config.assetsVersion)
await versionCache.computeVersion()

return {
versionCache,
rootView: config.rootView ?? 'root',
sharedData: config.sharedData || {},
versionCache,
entrypoint: slash(config.entrypoint ?? (await detector.detectEntrypoint('resources/app.ts'))),
ssr: {
enabled: config.ssr?.enabled ?? false,
pages: config.ssr?.pages,
entrypoint: config.ssr?.entrypoint ?? app.makePath('resources/ssr.ts'),
bundle: config.ssr?.bundle ?? app.makePath('ssr/ssr.js'),
entrypoint:
config.ssr?.entrypoint ?? (await detector.detectSsrEntrypoint('resources/ssr.ts')),

bundle: config.ssr?.bundle ?? (await detector.detectSsrBundle('ssr/ssr.js')),
},
}
})
Expand Down
66 changes: 66 additions & 0 deletions src/files_detector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* @adonisjs/inertia
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import { locatePath } from 'locate-path'
import { Application } from '@adonisjs/core/app'

export class FilesDetector {
constructor(protected app: Application<any>) {}

/**
* Try to locate the entrypoint file based
* on the conventional locations
*/
async detectEntrypoint(defaultPath: string) {
const possiblesLocations = [
'./resources/app.ts',
'./resources/app.tsx',
'./resources/application/app.ts',
'./resources/application/app.tsx',
'./resources/app.jsx',
'./resources/app.js',
'./resources/application/app.jsx',
'./resources/application/app.js',
]

const path = await locatePath(possiblesLocations, { cwd: this.app.appRoot })
return this.app.makePath(path || defaultPath)
}

/**
* Try to locate the SSR entrypoint file based
* on the conventional locations
*/
async detectSsrEntrypoint(defaultPath: string) {
const possiblesLocations = [
'./resources/ssr.ts',
'./resources/ssr.tsx',
'./resources/application/ssr.ts',
'./resources/application/ssr.tsx',
'./resources/ssr.jsx',
'./resources/ssr.js',
'./resources/application/ssr.jsx',
'./resources/application/ssr.js',
]

const path = await locatePath(possiblesLocations, { cwd: this.app.appRoot })
return this.app.makePath(path || defaultPath)
}

/**
* Try to locate the SSR bundle file based
* on the conventional locations
*/
async detectSsrBundle(defaultPath: string) {
const possiblesLocations = ['./ssr/ssr.js', './ssr/ssr.mjs']

const path = await locatePath(possiblesLocations, { cwd: this.app.appRoot })
return this.app.makePath(path || defaultPath)
}
}
22 changes: 8 additions & 14 deletions src/inertia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@

/// <reference types="@adonisjs/core/providers/edge_provider" />

import type { ViteDevServer } from 'vite'
import type { ViteRuntime } from 'vite/runtime'
import type { HttpContext } from '@adonisjs/core/http'

import { ServerRenderer } from './server_renderer.js'
import type {
Data,
MaybePromise,
Expand All @@ -31,13 +33,16 @@ const kLazySymbol = Symbol('lazy')
*/
export class Inertia {
#sharedData: SharedData = {}
#serverRenderer: ServerRenderer

constructor(
protected ctx: HttpContext,
protected config: ResolvedConfig,
protected viteRuntime?: ViteRuntime
protected viteRuntime?: ViteRuntime,
protected viteDevServer?: ViteDevServer
) {
this.#sharedData = config.sharedData
this.#serverRenderer = new ServerRenderer(config, viteRuntime, viteDevServer)
}

/**
Expand Down Expand Up @@ -121,24 +126,13 @@ export class Inertia {

/**
* Render the page on the server
*
* On development, we use the Vite Runtime API
* On production, we just import and use the SSR bundle generated by Vite
*/
async #renderOnServer(pageObject: PageObject, viewProps?: Record<string, any>) {
let render: { default: (page: any) => Promise<{ head: string; body: string }> }

if (this.viteRuntime) {
render = await this.viteRuntime.executeEntrypoint(this.config.ssr.entrypoint!)
} else {
render = await import(this.config.ssr.bundle!)
}

const result = await render.default(pageObject)
const { head, body } = await this.#serverRenderer.render(pageObject)

return this.ctx.view.render(this.config.rootView, {
...viewProps,
page: { ssrHead: result.head, ssrBody: result.body, ...pageObject },
page: { ssrHead: head, ssrBody: body, ...pageObject },
})
}

Expand Down
10 changes: 7 additions & 3 deletions src/inertia_middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
* file that was distributed with this source code.
*/

import type { ViteDevServer } from 'vite'
import type { Vite } from '@adonisjs/vite'
import type { ViteRuntime } from 'vite/runtime'
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'

Expand All @@ -28,19 +30,21 @@ declare module '@adonisjs/core/http' {
* set appropriate headers/status
*/
export default class InertiaMiddleware {
#runtime: ReturnType<Vite['getRuntime']> | undefined
#runtime?: ViteRuntime
#viteDevServer?: ViteDevServer

constructor(
protected config: ResolvedConfig,
vite?: Vite
protected vite?: Vite
) {
this.#runtime = vite?.getRuntime()
this.#viteDevServer = vite?.getDevServer()
}

async handle(ctx: HttpContext, next: NextFn) {
const { response, request } = ctx

ctx.inertia = new Inertia(ctx, this.config, this.#runtime)
ctx.inertia = new Inertia(ctx, this.config, this.#runtime, this.#viteDevServer)

await next()

Expand Down
Loading
Loading