Skip to content

Commit

Permalink
DRY out
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Dec 9, 2023
1 parent 830f0e2 commit 87dc49f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
23 changes: 9 additions & 14 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { parse } from './parse.js';
import * as storage from './session-storage.js';
import {
find_anchor,
get_base_uri,
resolve_url,
get_link_info,
get_router_options,
is_external_url,
Expand Down Expand Up @@ -235,12 +235,8 @@ export function create_client(app, target) {
redirect_count,
nav_token
) {
if (typeof url === 'string') {
url = new URL(url, get_base_uri(document));
}

return navigate({
url,
url: resolve_url(url),
scroll: noScroll ? scroll_state() : null,
keepfocus: keepFocus,
redirect_count,
Expand Down Expand Up @@ -1375,21 +1371,20 @@ export function create_client(app, target) {
}
},

goto: (href, opts = {}) => {
if (typeof href === 'string') {
href = new URL(href, get_base_uri(document));
}
if (href.origin !== origin) {
goto: (url, opts = {}) => {
url = resolve_url(url);

if (url.origin !== origin) {
return Promise.reject(
new Error(
DEV
? `Cannot use \`goto\` with an external URL. Use \`window.location = "${href}"\` instead`
? `Cannot use \`goto\` with an external URL. Use \`window.location = "${url}"\` instead`
: 'goto: invalid URL'
)
);
}

return goto(href, opts, 0);
return goto(url, opts, 0);
},

invalidate: (resource) => {
Expand All @@ -1409,7 +1404,7 @@ export function create_client(app, target) {
},

preload_data: async (href) => {
const url = new URL(href, get_base_uri(document));
const url = resolve_url(href);
const intent = get_navigation_intent(url, false);

if (!intent) {
Expand Down
14 changes: 8 additions & 6 deletions packages/kit/src/runtime/client/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ import { PRELOAD_PRIORITIES } from './constants.js';

export const origin = BROWSER ? location.origin : '';

/** @param {HTMLDocument} doc */
export function get_base_uri(doc) {
let baseURI = doc.baseURI;
/** @param {string | URL} url */
export function resolve_url(url) {
if (url instanceof URL) return url;

let baseURI = document.baseURI;

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

return baseURI;
return new URL(url, baseURI);
}

export function scroll_state() {
Expand Down

0 comments on commit 87dc49f

Please sign in to comment.