Last active
May 12, 2024 08:43
-
-
Save PatrickJS/d59d3481ad892e98b1677372e5e4d661 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { HTMLAttributes, JSXOutput, Signal } from '@builder.io/qwik'; | |
import { | |
Slot, | |
component$ | |
} from '@builder.io/qwik'; | |
import { | |
Link as QwikLink | |
} from '@builder.io/qwik-city'; | |
export function getBaseUrl(base?: string) { | |
const baseEnv = import.meta.env.VITE_BASE_URL; | |
const baseUrl = base | |
? `${base.startsWith('/') ? '' : '/'}${base}${ | |
base.endsWith('/') ? '' : '/' | |
}` | |
: baseEnv && // default false | |
`${baseEnv.startsWith('/') ? '' : '/'}${baseEnv}${ | |
baseEnv.endsWith('/') ? '' : '/' | |
}`; | |
return baseUrl; | |
} | |
type LinkProps = { | |
ref?: Signal<HTMLAnchorElement | undefined>; | |
class?: string; | |
href?: string; | |
server?: boolean; // set the default value for your app (or useContext for app settings) | |
base?: string; | |
target?: '_blank' | '_self' | '_parent' | '_top'; | |
} & HTMLAttributes<HTMLAnchorElement>; | |
export const Link = component$<LinkProps>( | |
({ base, ref, server = false, ...props }) => { | |
// TODO: better ways to get baseUrl | |
const baseUrl = getBaseUrl(base); | |
const Tag = server ? 'a' : QwikLink; | |
// TODO: better way to do this for server-only | |
if (props.href === undefined || props.href === '/') { | |
// href = '' will link to root | |
props.href = ''; | |
} else { | |
if (server && baseUrl && baseUrl !== '/') { | |
if (props.href.startsWith('/')) { | |
props.href = props.href.replace(/^\//, baseUrl); | |
} else { | |
props.href = baseUrl + props.href; | |
} | |
} | |
// fallthrough no baseUrl | |
} | |
return ( | |
<Tag {...(ref ? { ref } : {})} {...props}> | |
<Slot /> | |
</Tag> | |
); | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
VITE_BASE_URL should always be an absolute path starting and ending with /.
Anything else is a configuration error.
We should add a check to the qwik-city plugin.
The qwik base should also be absolute and ending with / but can be a url.