Skip to content

[chore] Router refactor #2655

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

Closed
wants to merge 6 commits into from
Closed
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 packages/kit/src/runtime/app/navigation.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { router as router_ } from '../client/singletons.js';
import { get_base_uri } from '../client/utils.js';
import { router as router_, prefetcher as prefetcher_, renderer } from '../client/singletons.js';
import { get_base_uri } from '../client/router.js';

const router = /** @type {import('../client/router').Router} */ (router_);
const prefetcher = /** @type {import('../client/prefetcher').Prefetcher} */ (prefetcher_);

/**
* @param {string} name
Expand Down Expand Up @@ -29,14 +30,14 @@ async function goto_(href, opts) {
*/
async function invalidate_(resource) {
const { href } = new URL(resource, location.href);
return router.renderer.invalidate(href);
return renderer.invalidate(href);
}

/**
* @type {import('$app/navigation').prefetch}
*/
function prefetch_(href) {
return router.prefetch(new URL(href, get_base_uri(document)));
return prefetcher.prefetch(new URL(href, get_base_uri(document)));
}

/**
Expand Down
52 changes: 52 additions & 0 deletions packages/kit/src/runtime/client/prefetcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { get_anchor, get_href } from './router';

export class Prefetcher {
/**
* @param {{
* router: import('./router').Router
* handle_prefetch: import('./types').PrefetchHandler
* }} opts
*/
constructor({ router, handle_prefetch }) {
this.router = router;
this.handle_prefetch = handle_prefetch;
}

init_listeners() {
/** @param {MouseEvent|TouchEvent} event */
const trigger_prefetch = (event) => {
const a = get_anchor(/** @type {Node} */ (event.target));
if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
this.prefetch(get_href(a));
}
};

/** @type {NodeJS.Timeout} */
let mousemove_timeout;

/** @param {MouseEvent|TouchEvent} event */
const handle_mousemove = (event) => {
clearTimeout(mousemove_timeout);
mousemove_timeout = setTimeout(() => {
trigger_prefetch(event);
}, 20);
};

addEventListener('touchstart', trigger_prefetch);
addEventListener('mousemove', handle_mousemove);
}

/**
* @param {URL} url
* @returns {Promise<import('./types').NavigationResult>}
*/
async prefetch(url) {
const info = this.router.parse(url);

if (!info) {
throw new Error('Attempted to prefetch a URL that does not belong to this app');
}

return this.handle_prefetch(info);
}
}
71 changes: 24 additions & 47 deletions packages/kit/src/runtime/client/router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { get_base_uri } from './utils';

function scroll_state() {
return {
x: pageXOffset,
Expand All @@ -8,19 +6,36 @@ function scroll_state() {
}

/**
* Returns the base URI of the document.
* @param {Document} doc
*/
export function get_base_uri(doc) {
let baseURI = doc.baseURI;

if (!baseURI) {
const baseTags = doc.getElementsByTagName('base');
baseURI = baseTags.length ? baseTags[0].href : doc.URL;
}

return baseURI;
}

/**
* Returns the first parent node that is an anchor element (i.e. "a" html tag).
* @param {Node | null} node
* @returns {HTMLAnchorElement | SVGAElement | null}
*/
function find_anchor(node) {
export function get_anchor(node) {
while (node && node.nodeName.toUpperCase() !== 'A') node = node.parentNode; // SVG <a> elements have a lowercase name
return /** @type {HTMLAnchorElement | SVGAElement} */ (node);
}

/**
* Returns the location the given element is linking to.
* @param {HTMLAnchorElement | SVGAElement} node
* @returns {URL}
*/
function get_href(node) {
export function get_href(node) {
return node instanceof SVGAElement
? new URL(node.href.baseVal, document.baseURI)
: new URL(node.href);
Expand All @@ -32,19 +47,17 @@ export class Router {
* base: string;
* routes: import('types/internal').CSRRoute[];
* trailing_slash: import('types/internal').TrailingSlash;
* renderer: import('./renderer').Renderer
* handle_nav: import('./types').NavigationHandler
* }} opts
*/
constructor({ base, routes, trailing_slash, renderer }) {
constructor({ base, routes, trailing_slash, handle_nav }) {
this.base = base;
this.routes = routes;
this.trailing_slash = trailing_slash;
/** Keeps tracks of multiple navigations caused by redirects during rendering */
this.navigating = 0;

/** @type {import('./renderer').Renderer} */
this.renderer = renderer;
renderer.router = this;
this.handle_nav = handle_nav;

this.enabled = true;

Expand Down Expand Up @@ -91,28 +104,6 @@ export class Router {
}, 50);
});

/** @param {MouseEvent|TouchEvent} event */
const trigger_prefetch = (event) => {
const a = find_anchor(/** @type {Node} */ (event.target));
if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
this.prefetch(get_href(a));
}
};

/** @type {NodeJS.Timeout} */
let mousemove_timeout;

/** @param {MouseEvent|TouchEvent} event */
const handle_mousemove = (event) => {
clearTimeout(mousemove_timeout);
mousemove_timeout = setTimeout(() => {
trigger_prefetch(event);
}, 20);
};

addEventListener('touchstart', trigger_prefetch);
addEventListener('mousemove', handle_mousemove);

/** @param {MouseEvent} event */
addEventListener('click', (event) => {
if (!this.enabled) return;
Expand All @@ -123,7 +114,7 @@ export class Router {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
if (event.defaultPrevented) return;

const a = find_anchor(/** @type {Node} */ (event.target));
const a = get_anchor(/** @type {Node} */ (event.target));
if (!a) return;

if (!a.href) return;
Expand Down Expand Up @@ -227,20 +218,6 @@ export class Router {
this.enabled = false;
}

/**
* @param {URL} url
* @returns {Promise<import('./types').NavigationResult>}
*/
async prefetch(url) {
const info = this.parse(url);

if (!info) {
throw new Error('Attempted to prefetch a URL that does not belong to this app');
}

return this.renderer.load(info);
}

/**
* @param {URL} url
* @param {{ x: number, y: number }?} scroll
Expand Down Expand Up @@ -276,7 +253,7 @@ export class Router {
}
}

await this.renderer.handle_navigation(info, chain, false, { hash, scroll, keepfocus });
await this.handle_nav(info, chain, false, { hash, scroll, keepfocus });

this.navigating--;
if (!this.navigating) {
Expand Down
18 changes: 15 additions & 3 deletions packages/kit/src/runtime/client/singletons.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
/** @type {import('./renderer').Renderer} */
export let renderer;

/** @type {import('./router').Router?} */
export let router;

/** @param {import('./router').Router?} _ */
export function init(_) {
router = _;
/** @type {import('./prefetcher').Prefetcher?} */
export let prefetcher;

/**
* @param {import('./renderer').Renderer} render
* @param {import('./router').Router?} route
* @param {import('./prefetcher').Prefetcher?} prefetch
*/
export function init(render, route, prefetch) {
renderer = render;
router = route;
prefetcher = prefetch;
}
31 changes: 22 additions & 9 deletions packages/kit/src/runtime/client/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Router } from './router.js';
import { Renderer } from './renderer.js';
import { init } from './singletons.js';
import { set_paths } from '../paths.js';
import { Prefetcher } from './prefetcher.js';

/**
* @param {{
Expand Down Expand Up @@ -40,22 +41,34 @@ export async function start({ paths, target, session, host, route, spa, trailing
host
});

const router = route
? new Router({
base: paths.base,
routes,
trailing_slash,
renderer
})
: null;
let router = null;
let prefetcher = null;

init(router);
// I don't love having a cycle between renderer and router and I wonder if we couldn't clean it up over time
// The router no longer directly has a reference to the renderer, but takes a callback which invokes the renderer
// The renderer needs the router for:
// reacting to changes in the stores and invalidations (which perhaps don't need to live in the renderer)
// handling redirects (perhaps rather than redirecting in the renderer it could return a redirect result)
// handling "export const router" turning the router on and off on individual pages (maybe could be replaced by route guards?)
if (route) {
router = new Router({
base: paths.base,
routes,
trailing_slash,
handle_nav: renderer.handle_navigation.bind(renderer)
});
renderer.router = router;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible later on to resolve this somewhat cyclic dependency? I read this as "renderer depends on router, which depends on renderer"

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, it's a good question. I'm not quite sure and don't have any ideas on how it would be done

the cycle isn't a new one. In master, the router takes the render as a constructor arg and then did this inside the constructor. I just moved where it's occurring. I agree with you that I don't love it, but am not sure how to change it. I'd be all ears if you have suggestions

Copy link
Member Author

@benmccann benmccann Oct 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dug into this a bit and added a comment explaining options for cleaning it up. It'd be too big of a change to try to tackle in this PR, but might make a nice follow up if I get some time 😄

prefetcher = new Prefetcher({ router, handle_prefetch: renderer.load.bind(renderer) });
}

init(renderer, router, prefetcher);
set_paths(paths);

if (hydrate) await renderer.start(hydrate);
if (router) {
if (spa) router.goto(location.href, { replaceState: true }, []);
router.init_listeners();
prefetcher?.init_listeners();
}

dispatchEvent(new CustomEvent('sveltekit:start'));
Expand Down
44 changes: 32 additions & 12 deletions packages/kit/src/runtime/client/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,47 @@
import { CSRComponent, CSRPage, CSRRoute, NormalizedLoadOutput } from 'types/internal';
import { Page } from 'types/page';

export type NavigationInfo = {
// Router types

export interface NavigationInfo {
/** an ID to uniquely identify the request */
id: string;
routes: CSRRoute[];
path: string;
decoded_path: string;
query: URLSearchParams;
};
}

export type NavigationCandidate = {
route: CSRPage;
info: NavigationInfo;
};
export interface NavigationHandler {
(
info: NavigationInfo,
chain: string[],
no_cache: boolean,
opts?: { hash?: string; scroll: { x: number; y: number } | null; keepfocus: boolean }
): Promise<void>;
}

export type NavigationResult = {
// Prefetcher types

export interface NavigationResult {
reload?: boolean;
redirect?: string;
state: NavigationState;
props: Record<string, any>;
};
}

export interface PrefetchHandler {
(info: NavigationInfo): Promise<NavigationResult>;
}

// Renderer types

export interface NavigationCandidate {
route: CSRPage;
info: NavigationInfo;
}

export type BranchNode = {
export interface BranchNode {
module: CSRComponent;
loaded: NormalizedLoadOutput | null;
uses: {
Expand All @@ -33,10 +53,10 @@ export type BranchNode = {
dependencies: string[];
};
stuff: Record<string, any>;
};
}

export type NavigationState = {
export interface NavigationState {
page: Page;
branch: Array<BranchNode | undefined>;
session_id: number;
};
}
11 changes: 0 additions & 11 deletions packages/kit/src/runtime/client/utils.js

This file was deleted.