Open History to see the last commit
1import * as React from 'react'
2import { Asset } from './Asset'
3import { useRouter } from './useRouter'
4import { useRouterState } from './useRouterState'
5import type { RouterManagedTag } from '@tanstack/router-core'
6β
7/**
8 * Build the list of head/link/meta/script tags to render for active matches.
9 * Used internally by `HeadContent`.
10 */
11export const useTags = () => {
12 const router = useRouter()
13 const nonce = router.options.ssr?.nonce
14 const routeMeta = useRouterState({
15 select: (state) => {
16 return state.matches.map((match) => match.meta!).filter(Boolean)
17 },
18 })
19β
20 const meta: Array<RouterManagedTag> = React.useMemo(() => {
21 const resultMeta: Array<RouterManagedTag> = []
22 const metaByAttribute: Record<string, true> = {}
23 let title: RouterManagedTag | undefined
24 for (let i = routeMeta.length - 1; i >= 0; i--) {
25 const metas = routeMeta[i]!
26 for (let j = metas.length - 1; j >= 0; j--) {
27 const m = metas[j]
28 if (!m) continue
29β
30 if (m.title) {
31 if (!title) {
32 title = {
33 tag: 'title',
34 children: m.title,
35 }
36 }
37 } else {
38 const attribute = m.name ?? m.property
39 if (attribute) {
40 if (metaByAttribute[attribute]) {
41 continue
42 } else {
43 metaByAttribute[attribute] = true
44 }
45 }
46β
47 resultMeta.push({
48 tag: 'meta',
49 attrs: {
50 ...m,
51 nonce,
52 },
53 })
54 }
55 }
56 }
57β
58 if (title) {
59 resultMeta.push(title)
60 }
61β
62 if (nonce) {
63 resultMeta.push({
64 tag: 'meta',
65 attrs: {
66 property: 'csp-nonce',
67 content: nonce,
68 },
69 })
70 }
71 resultMeta.reverse()
72β
73 return resultMeta
74 }, [routeMeta, nonce])
75β
76 const links = useRouterState({
77 select: (state) => {
78 const constructed = state.matches
79 .map((match) => match.links!)
80 .filter(Boolean)
81 .flat(1)
82 .map((link) => ({
83 tag: 'link',
84 attrs: {
85 ...link,
86 nonce,
87 },
88 })) satisfies Array<RouterManagedTag>
89β
90 const manifest = router.ssr?.manifest
91β
92 // These are the assets extracted from the ViteManifest
93 // using the `startManifestPlugin`
94 const assets = state.matches
95 .map((match) => manifest?.routes[match.routeId]?.assets ?? [])
96 .filter(Boolean)
97 .flat(1)
98 .filter((asset) => asset.tag === 'link')
99 .map(
100 (asset) =>
101 ({
102 tag: 'link',
103 attrs: {
104 ...asset.attrs,
105 suppressHydrationWarning: true,
106 nonce,
107 },
108 }) satisfies RouterManagedTag,
109 )
110β
111 return [...constructed, ...assets]
112 },
113 structuralSharing: true as any,
114 })
115β
116 const preloadMeta = useRouterState({
117 select: (state) => {
118 const preloadMeta: Array<RouterManagedTag> = []
119β
120 state.matches
121 .map((match) => router.looseRoutesById[match.routeId]!)
122 .forEach((route) =>
123 router.ssr?.manifest?.routes[route.id]?.preloads
124 ?.filter(Boolean)
125 .forEach((preload) => {
126 preloadMeta.push({
127 tag: 'link',
128 attrs: {
129 rel: 'modulepreload',
130 href: preload,
131 nonce,
132 },
133 })
134 }),
135 )
136β
137 return preloadMeta
138 },
139 structuralSharing: true as any,
140 })
141β
142 const styles = useRouterState({
143 select: (state) =>
144 (
145 state.matches
146 .map((match) => match.styles!)
147 .flat(1)
148 .filter(Boolean) as Array<RouterManagedTag>
149 ).map(({ children, ...attrs }) => ({
150 tag: 'style',
151 attrs,
152 children,
153 nonce,
154 })),
155 structuralSharing: true as any,
156 })
157β
158 const headScripts = useRouterState({
159 select: (state) =>
160 (
161 state.matches
162 .map((match) => match.headScripts!)
163 .flat(1)
164 .filter(Boolean) as Array<RouterManagedTag>
165 ).map(({ children, ...script }) => ({
166 tag: 'script',
167 attrs: {
168 ...script,
169 nonce,
170 },
171 children,
172 })),
173 structuralSharing: true as any,
174 })
175β
176 return uniqBy(
177 [
178 ...meta,
179 ...preloadMeta,
180 ...links,
181 ...styles,
182 ...headScripts,
183 ] as Array<RouterManagedTag>,
184 (d) => {
185 return JSON.stringify(d)
186 },
187 )
188}
189β
190/**
191 * @description The `HeadContent` component is used to render meta tags, links, and scripts for the current route.
192 * It should be rendered in the `<head>` of your document.
193 */
194/**
195 * Render route-managed head tags (title, meta, links, styles, head scripts).
196 * Place inside the document head of your app shell.
197 * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
198 */
199export function HeadContent() {
200 const tags = useTags()
201 const router = useRouter()
202 const nonce = router.options.ssr?.nonce
203 return tags.map((tag) => (
204 <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} />
205 ))
206}
207β
208function uniqBy<T>(arr: Array<T>, fn: (item: T) => string) {
209 const seen = new Set<string>()
210 return arr.filter((item) => {
211 const key = fn(item)
212 if (seen.has(key)) {
213 return false
214 }
215 seen.add(key)
216 return true
217 })
218}