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

Bypass router on hydration #563

Merged
merged 5 commits into from
Mar 17, 2021
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
5 changes: 5 additions & 0 deletions .changeset/neat-worms-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Bypass router on hydration
10 changes: 9 additions & 1 deletion packages/kit/src/core/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@ async function build_server(
/** @type {Record<string, string>} */
const amp_css_lookup = {};

/** @type {Record<string, string>} */
const client_component_lookup = {};

[client_entry_file, ...manifest.components].forEach((file) => {
client_component_lookup[file] = client_manifest[file].file;

const js_deps = new Set();
const css_deps = new Set();

Expand Down Expand Up @@ -286,6 +291,8 @@ async function build_server(
${config.kit.amp ? `
const amp_css_lookup = ${s(amp_css_lookup)};` : ''}

const client_component_lookup = ${s(client_component_lookup)};

const manifest = {
assets: ${s(manifest.assets)},
layout: ${stringify_component(manifest.layout)},
Expand All @@ -294,7 +301,7 @@ async function build_server(
${manifest.pages
.map((data) => {
const params = get_params(data.params);
const parts = data.parts.map(c => `components[${component_indexes.get(c)}]`);
const parts = data.parts.map(id => `{ id: ${s(id)}, load: components[${component_indexes.get(id)}] }`);

const js_deps = new Set(common_js_deps);
const css_deps = new Set(common_css_deps);
Expand Down Expand Up @@ -352,6 +359,7 @@ async function build_server(
app_dir: ${s(config.kit.appDir)},
host: ${s(config.kit.host)},
host_header: ${s(config.kit.hostHeader)},
get_component_path: id => ${s(`${config.kit.paths.assets}/${config.kit.appDir}/`)} + client_component_lookup[id],
get_stack: error => error.stack,
get_static_file,
get_amp_css: dep => amp_css_lookup[dep]
Expand Down
30 changes: 21 additions & 9 deletions packages/kit/src/core/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { copy_assets } from '../utils.js';
import svelte from '@svitejs/vite-plugin-svelte';

/** @typedef {{ cwd?: string, port: number, config: import('../../../types.internal').ValidatedConfig }} Options */
/** @typedef {import('../../../types.internal').SSRComponent} SSRComponent */

/** @param {Options} opts */
export function dev(opts) {
Expand Down Expand Up @@ -195,6 +196,7 @@ class Watcher extends EventEmitter {
only_prerender: false,
host: this.config.kit.host,
host_header: this.config.kit.hostHeader,
get_component_path: (id) => `/${id}?import`,
get_stack: (error) => {
this.viteDevServer.ssrFixStacktrace(error);
return error.stack;
Expand Down Expand Up @@ -239,11 +241,15 @@ class Watcher extends EventEmitter {

/**
* @param {string} file
* @returns {Promise<{
* mod: SSRComponent;
* css: Set<string>;
* }>}
*/
const load = async (file) => {
const url = path.resolve(this.cwd, file);

const mod = await this.viteDevServer.ssrLoadModule(url);
const mod = /** @type {SSRComponent} */ (await this.viteDevServer.ssrLoadModule(url));
const node = await this.viteDevServer.moduleGraph.getModuleByUrl(url);

const deps = new Set();
Expand Down Expand Up @@ -280,6 +286,7 @@ class Watcher extends EventEmitter {
}
};

/** @type {import('../../../types.internal').SSRManifest} */
this.manifest = {
assets: manifest_data.assets,
layout: async () => {
Expand All @@ -304,14 +311,19 @@ class Watcher extends EventEmitter {
return {
pattern: data.pattern,
params: get_params(data.params),
parts: data.parts.map((file) => async () => {
const { mod, css } = await load(file);

css.forEach((mod) => {
css_deps.add(mod);
});

return mod;
parts: data.parts.map((id) => {
return {
id,
async load() {
const { mod, css } = await load(id);

css.forEach((mod) => {
css_deps.add(mod);
});

return mod;
}
};
}),
get style() {
// TODO is it possible to inject <link> elements with
Expand Down
46 changes: 22 additions & 24 deletions packages/kit/src/runtime/client/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,19 @@ export class Renderer {
* Root: import('../../../types.internal').CSRComponent;
* layout: import('../../../types.internal').CSRComponent;
* target: Node;
* error: Error;
* status: number;
* session: any;
* }} opts */
constructor({ Root, layout, target, error, status, session }) {
constructor({ Root, layout, target, session }) {
this.Root = Root;
this.layout = layout;
this.layout_loader = () => layout;

/** @type {import('./router').Router} */
this.router = null;

// TODO ideally we wouldn't need to store these...
this.target = target;

this.initial = {
error,
status
};
this.started = false;

this.current = {
page: null,
Expand Down Expand Up @@ -117,17 +111,21 @@ export class Renderer {
ready = true;
}

/** @param {import('./types').NavigationTarget} selected */
async start(selected) {
/**
* @param {import('./types').NavigationTarget} selected
* @param {number} status
* @param {Error} error
*/
async start(selected, status, error) {
/** @type {Record<string, any>} */
const props = {
stores: this.stores,
error: this.initial.error,
status: this.initial.status,
error,
status,
page: selected.page
};

if (this.initial.error) {
if (error) {
props.components = [this.layout.default];
} else {
const hydrated = await this.hydrate(selected);
Expand Down Expand Up @@ -155,16 +153,16 @@ export class Renderer {
hydrate: true
});

this.initial = null;
this.started = true;
}

/** @param {import('./types').NavigationTarget} selected */
notify(selected) {
/** @param {import('../../../types.internal').Page} page */
notify(page) {
dispatchEvent(new CustomEvent('sveltekit:navigation-start'));

this.stores.navigating.set({
from: this.current.page,
to: selected.page
to: page
});
}

Expand Down Expand Up @@ -203,7 +201,7 @@ export class Renderer {
}

/** @param {import('./types').NavigationTarget} selected */
async hydrate({ route, page }) {
async hydrate({ nodes, page }) {
/** @type {Record<string, any>} */
const props = {
status: 200,
Expand All @@ -220,7 +218,7 @@ export class Renderer {
* @param {RequestInit} opts
*/
const fetcher = (url, opts) => {
if (this.initial) {
if (!this.started) {
const script = document.querySelector(`script[type="svelte-data"][url="${url}"]`);
if (script) {
const { body, ...init } = JSON.parse(script.textContent);
Expand Down Expand Up @@ -254,7 +252,7 @@ export class Renderer {
contexts: []
};

const component_promises = [this.layout_loader(), ...route.parts.map((loader) => loader())];
const component_promises = [this.layout, ...nodes];
const props_promises = [];

/** @type {Record<string, any>} */
Expand Down Expand Up @@ -302,7 +300,7 @@ export class Renderer {
/** @type {Branch} */
let node;

/** @type {import('../../../types.internal').LoadResult} */
/** @type {import('../../../types.internal').LoadOutput} */
let loaded;

if (cached && (!changed.context || !cached.node.uses.context)) {
Expand Down Expand Up @@ -444,11 +442,11 @@ export class Renderer {

/** @param {URL} url */
async prefetch(url) {
const page = this.router.select(url);
const selected = this.router.select(url);

if (page) {
if (selected) {
if (url.href !== this.prefetching.href) {
this.prefetching = { href: url.href, promise: this.hydrate(page) };
this.prefetching = { href: url.href, promise: this.hydrate(selected) };
}

return this.prefetching.promise;
Expand Down
18 changes: 8 additions & 10 deletions packages/kit/src/runtime/client/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class Router {
/** @param {{
* base: string;
* host: string;
* pages: import('../../../types.internal').Page[];
* pages: import('../../../types.internal').CSRPage[];
* ignore: RegExp[];
* }} opts */
constructor({ base, host, pages, ignore }) {
Expand Down Expand Up @@ -112,7 +112,7 @@ export class Router {
const selected = this.select(url);
if (selected) {
const noscroll = a.hasAttribute('sveltekit:noscroll');
this.renderer.notify(selected);
this.renderer.notify(selected.page);
this.history.pushState({}, '', url.href);
this.navigate(selected, noscroll ? scroll_state() : null, [], url.hash);
event.preventDefault();
Expand All @@ -134,12 +134,6 @@ export class Router {

// make it possible to reset focus
document.body.setAttribute('tabindex', '-1');

// load current page
this.history.replaceState({}, '', location.href);

const selected = this.select(new URL(location.href));
if (selected) return this.renderer.start(selected);
}

/**
Expand All @@ -166,9 +160,13 @@ export class Router {
const query = new URLSearchParams(url.search);
const params = route.params(match);

/** @type {import('../../../types.internal').Page} */
const page = { host: this.host, path, query, params };

return { href: url.href, route, match, page };
return {
nodes: route.parts.map((loader) => loader()),
page
};
}
}
}
Expand All @@ -183,7 +181,7 @@ export class Router {
const selected = this.select(url);

if (selected) {
this.renderer.notify(selected);
this.renderer.notify(selected.page);

// TODO shouldn't need to pass the hash here
this.history[replaceState ? 'replaceState' : 'pushState']({}, '', href);
Expand Down
12 changes: 6 additions & 6 deletions packages/kit/src/runtime/client/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@ import { set_paths } from '../paths.js';
* base: string;
* },
* target: Node;
* host: string;
* session: any;
* error: Error;
* status: number;
* nodes: import('./types').NavigationTarget["nodes"];
* page: import('./types').NavigationTarget["page"];
* }} opts */
export async function start({ paths, target, host, session, error, status }) {
export async function start({ paths, target, session, error, status, nodes, page }) {
const router = new Router({
base: paths.base,
host,
host: page.host,
pages,
ignore
});
Expand All @@ -30,15 +31,14 @@ export async function start({ paths, target, host, session, error, status }) {
Root,
layout,
target,
error,
status,
session
});

init({ router, renderer });
set_paths(paths);

await router.init(renderer);
router.init(renderer);
await renderer.start({ nodes, page }, status, error);

dispatchEvent(new CustomEvent('sveltekit:start'));
}
Expand Down
13 changes: 4 additions & 9 deletions packages/kit/src/runtime/client/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import { CSRComponent, Page } from '../../../types.internal';

export type NavigationTarget = {
href: string;
route: import('../../../types.internal').Page;
match: RegExpExecArray;
page: {
host: string;
path: string;
query: URLSearchParams;
params: Record<string, string | string[]>;
};
nodes: Array<Promise<CSRComponent>>;
page: Page;
};
4 changes: 2 additions & 2 deletions packages/kit/src/runtime/load.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @param {import('../../types.internal').LoadResult} loaded
* @returns {import('../../types.internal').LoadResult}
* @param {import('../../types.internal').LoadOutput} loaded
* @returns {import('../../types.internal').LoadOutput}
*/
export function normalize(loaded) {
// TODO should this behaviour be dev-only?
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/endpoint.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* @param {import('../../../types.internal').Request} request
* @param {*} context // TODO
* @param {import('../../../types.internal').RenderOptions} options
* @param {import('../../../types.internal').SSRRenderOptions} options
* @returns {Promise<import('../../../types.internal').Response>}
*/
export default function render_route(request, context, options) {
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function md5(body) {

/**
* @param {import('../../../types.internal').Request} request
* @param {import('../../../types.internal').RenderOptions} options
* @param {import('../../../types.internal').SSRRenderOptions} options
*/
export async function ssr(request, options) {
if (request.path.endsWith('/') && request.path !== '/') {
Expand Down
Loading