Skip to content

Adds unhead types and head tag sorting #4082

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

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions packages/react-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"combinate": "^1.1.11",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"unhead": "^2.0.8",
"zod": "^3.24.2"
},
"peerDependencies": {
Expand Down
85 changes: 82 additions & 3 deletions packages/react-router/src/HeadContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,33 @@ import { useRouter } from './useRouter'
import { useRouterState } from './useRouterState'
import type { RouterManagedTag } from '@tanstack/router-core'

const isTruthy = (val?: string | boolean) => val === '' || val === true
const WEIGHT_MAP = {
meta: {
'content-security-policy': -30,
charset: -20,
viewport: -15,
},
link: {
preconnect: 20,
stylesheet: 60,
preload: 70,
modulepreload: 70,
prefetch: 90,
'dns-prefetch': 90,
prerender: 90,
},
script: {
async: 30,
defer: 80,
sync: 50,
},
style: {
imported: 40,
sync: 60,
},
} as const

export const useTags = () => {
const router = useRouter()

Expand Down Expand Up @@ -133,9 +160,61 @@ export const useTags = () => {
*/
export function HeadContent() {
const tags = useTags()
return tags.map((tag) => (
<Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} />
))
return tags
.map(weightTags)
.sort((a, b) => a.weight - b.weight)
.map((tag) => <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} />)
}

function weightTags(tag: RouterManagedTag) {
let weight = 100

if (tag.tag === 'title') {
weight = 10
} else if (tag.tag === 'meta') {
const metaType =
tag.attrs?.httpEquiv === 'content-security-policy'
? 'content-security-policy'
: tag.attrs?.charSet
? 'charset'
: tag.attrs?.name === 'viewport'
? 'viewport'
: null

if (metaType) {
weight = WEIGHT_MAP.meta[metaType]
}
} else if (tag.tag === 'link' && tag.attrs?.rel) {
weight =
tag.attrs.rel in WEIGHT_MAP.link
? WEIGHT_MAP.link[tag.attrs.rel as keyof typeof WEIGHT_MAP.link]
: weight
} else if (tag.tag === 'script') {
if (isTruthy(tag.attrs?.async)) {
weight = WEIGHT_MAP.script.async
} else if (
tag.attrs?.src &&
!isTruthy(tag.attrs.defer) &&
!isTruthy(tag.attrs.async) &&
tag.attrs.type !== 'module' &&
!tag.attrs.type?.endsWith('json')
) {
weight = WEIGHT_MAP.script.sync
} else if (
isTruthy(tag.attrs?.defer) &&
tag.attrs.src &&
!isTruthy(tag.attrs.async)
) {
weight = WEIGHT_MAP.script.defer
}
} else if (tag.tag === 'style') {
weight = tag.children ? WEIGHT_MAP.style.imported : WEIGHT_MAP.style.sync
}

return {
...tag,
weight,
}
}

function uniqBy<T>(arr: Array<T>, fn: (item: T) => string) {
Expand Down
16 changes: 14 additions & 2 deletions packages/react-router/src/Matches.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Transitioner } from './Transitioner'
import { matchContext } from './matchContext'
import { Match } from './Match'
import { SafeFragment } from './SafeFragment'
import type { LinkWithoutEvents, Meta } from 'unhead/types'
import type {
StructuralSharingOption,
ValidateSelected,
Expand All @@ -31,8 +32,19 @@ import type {

declare module '@tanstack/router-core' {
export interface RouteMatchExtensions {
meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>
links?: Array<React.JSX.IntrinsicElements['link'] | undefined>
meta?: Array<
| (React.JSX.IntrinsicElements['meta'] &
Omit<Meta, 'http-equiv' | 'charset'> & {
charSet?: Meta['charset']
httpEquiv?: Meta['http-equiv']
})
| undefined
>
links?: Array<
| (React.JSX.IntrinsicElements['link'] &
Omit<LinkWithoutEvents, 'referrerpolicy'>)
| undefined
>
scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>
headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>
}
Expand Down
3 changes: 3 additions & 0 deletions packages/router-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,8 @@
"@tanstack/history": "workspace:*",
"@tanstack/store": "^0.7.0",
"tiny-invariant": "^1.3.3"
},
"devDependencies": {
"unhead": "^2.0.8"
}
}
17 changes: 15 additions & 2 deletions packages/router-core/src/manifest.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { LinkWithoutEvents, Meta } from 'unhead/types'

export type Manifest = {
routes: Record<
string,
Expand All @@ -16,8 +18,19 @@ export type RouterManagedTag =
children: string
}
| {
tag: 'meta' | 'link'
attrs?: Record<string, any>
tag: 'meta'
attrs?:
| (Record<string, any> &
Omit<Meta, 'http-equiv' | 'charset' | 'content'> & {
charSet?: Meta['charset']
httpEquiv?: Meta['http-equiv']
})
| undefined
children?: never
}
| {
tag: 'link'
attrs?: Record<string, any> & Omit<LinkWithoutEvents, 'referrerpolicy'>
children?: never
}
| {
Expand Down
1 change: 1 addition & 0 deletions packages/solid-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"combinate": "^1.1.11",
"eslint-plugin-solid": "^0.14.5",
"solid-js": "^1.9.5",
"unhead": "^2.0.8",
"vite-plugin-solid": "^2.11.2",
"zod": "^3.23.8"
},
Expand Down
88 changes: 85 additions & 3 deletions packages/solid-router/src/HeadContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,33 @@ import { useRouter } from './useRouter'
import { useRouterState } from './useRouterState'
import type { RouterManagedTag } from '@tanstack/router-core'

const isTruthy = (val?: string | boolean) => val === '' || val === true
Copy link
Contributor

Choose a reason for hiding this comment

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

we should move the whole sorting logic into router-core
also add a comment please where that is originating from

Copy link
Contributor

Choose a reason for hiding this comment

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

thinking about this more, maybe we should just expose an API that a user could hook into to apply sorting using existing libraries instead of copying the stuff into router.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

also add a comment please where that is originating from

Can you clarify what you mean?

const WEIGHT_MAP = {
meta: {
'content-security-policy': -30,
charset: -20,
viewport: -15,
},
link: {
preconnect: 20,
stylesheet: 60,
preload: 70,
modulepreload: 70,
prefetch: 90,
'dns-prefetch': 90,
prerender: 90,
},
script: {
async: 30,
defer: 80,
sync: 50,
},
style: {
imported: 40,
sync: 60,
},
} as const

export const useTags = () => {
const router = useRouter()

Expand Down Expand Up @@ -132,15 +159,70 @@ export const useTags = () => {
*/
export function HeadContent() {
const tags = useTags()

return (
<MetaProvider>
{tags().map((tag) => (
<Asset {...tag} />
))}
{tags()
.map(weightTags)
.sort((a, b) => a.weight - b.weight)
.map((tag) => (
<Asset {...tag} />
))}
</MetaProvider>
)
}

function weightTags(tag: RouterManagedTag) {
let weight = 100

if (tag.tag === 'title') {
weight = 10
} else if (tag.tag === 'meta') {
const metaType =
tag.attrs?.httpEquiv === 'content-security-policy'
? 'content-security-policy'
: tag.attrs?.charSet
? 'charset'
: tag.attrs?.name === 'viewport'
? 'viewport'
: null

if (metaType) {
weight = WEIGHT_MAP.meta[metaType]
}
} else if (tag.tag === 'link' && tag.attrs?.rel) {
weight =
tag.attrs.rel in WEIGHT_MAP.link
? WEIGHT_MAP.link[tag.attrs.rel as keyof typeof WEIGHT_MAP.link]
: weight
} else if (tag.tag === 'script') {
if (isTruthy(tag.attrs?.async)) {
weight = WEIGHT_MAP.script.async
} else if (
tag.attrs?.src &&
!isTruthy(tag.attrs.defer) &&
!isTruthy(tag.attrs.async) &&
tag.attrs.type !== 'module' &&
!tag.attrs.type?.endsWith('json')
) {
weight = WEIGHT_MAP.script.sync
} else if (
isTruthy(tag.attrs?.defer) &&
tag.attrs.src &&
!isTruthy(tag.attrs.async)
) {
weight = WEIGHT_MAP.script.defer
}
} else if (tag.tag === 'style') {
weight = tag.children ? WEIGHT_MAP.style.imported : WEIGHT_MAP.style.sync
}

return {
...tag,
weight,
}
}

function uniqBy<T>(arr: Array<T>, fn: (item: T) => string) {
const seen = new Set<string>()
return arr.filter((item) => {
Expand Down
16 changes: 14 additions & 2 deletions packages/solid-router/src/Matches.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Transitioner } from './Transitioner'
import { matchContext } from './matchContext'
import { Match } from './Match'
import { SafeFragment } from './SafeFragment'
import type { LinkWithoutEvents, Meta } from 'unhead/types'
import type {
AnyRouter,
DeepPartial,
Expand All @@ -26,8 +27,19 @@ import type {

declare module '@tanstack/router-core' {
export interface RouteMatchExtensions {
meta?: Array<Solid.JSX.IntrinsicElements['meta'] | undefined>
links?: Array<Solid.JSX.IntrinsicElements['link'] | undefined>
meta?: Array<
| (Solid.JSX.IntrinsicElements['meta'] &
Omit<Meta, 'http-equiv' | 'charset'> & {
charSet?: Meta['charset']
httpEquiv?: Meta['http-equiv']
})
| undefined
>
links?: Array<
| (Solid.JSX.IntrinsicElements['link'] &
Omit<LinkWithoutEvents, 'referrerpolicy'>)
| undefined
>
scripts?: Array<Solid.JSX.IntrinsicElements['script'] | undefined>
headScripts?: Array<Solid.JSX.IntrinsicElements['script'] | undefined>
}
Expand Down
Loading
Loading