Skip to content

app/client/nav.ts

41 lines · 1.4 KB · TypeScript
Raw
const appBase = document.documentElement.dataset.appBase ?? ''

export function navigate(path: string) {
	history.pushState(null, '', `${appBase}${path}`)
	dispatchEvent(new PopStateEvent('popstate'))
}

/**
 * Host-root package-app OAuth login. Returns to the current room (or app root)
 * on this origin after `/_kody/auth/callback` sets the package-app session.
 * `app=world-builder` is required on `*.kody.run`; custom app hostnames ignore it.
 */
function currentReturnTo() {
	let path = location.pathname
	if (appBase && path.startsWith(appBase)) path = path.slice(appBase.length)
	const room = /^\/r\/([a-z0-9]{4,24})\/?$/i.exec(path)
	return room ? `${appBase}/r/${room[1]!.toLowerCase()}` : appBase || '/'
}

/**
 * Host-root package-app sign out (`/_kody/auth/logout`, same as package-app-kit
 * `auth.logoutUrl`). Clears the package-app session cookie on this host and
 * returns to the current page, which then shows watch mode.
 */
export function signOutHref() {
	return `/_kody/auth/logout?${new URLSearchParams({ return_to: currentReturnTo() })}`
}

export function signInHref() {
	let path = location.pathname
	if (appBase && path.startsWith(appBase)) path = path.slice(appBase.length)
	const room = /^\/r\/([a-z0-9]{4,24})\/?$/i.exec(path)
	const returnTo = room
		? `${appBase}/r/${room[1]!.toLowerCase()}`
		: appBase || '/'
	const params = new URLSearchParams({
		app: 'world-builder',
		return_to: returnTo,
	})
	return `/_kody/auth/login?${params}`
}