Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

headContentUtils.tsx

216 lines5.5 KB

1import * as React from 'react'
2import { useSelector } from '@tanstack/react-store'
3import {
4 _getAssetMatches,
5 appendUniqueUserTags,
6 deepEqual,
7 escapeHtml,
8 getAssetCrossOrigin,
9 getScriptPreloadAttrs,
10 resolveManifestCssLink,
11} from '@tanstack/router-core'
12import { isServer } from '@tanstack/router-core/isServer'
13import { useRouter } from './useRouter'
14import type {
15 AnyRouteMatch,
16 AssetCrossOriginConfig,
17 RouterManagedTag,
18} from '@tanstack/router-core'
19​
20function buildTagsFromMatches(
21 router: ReturnType<typeof useRouter>,
22 nonce: string | undefined,
23 matches: Array<AnyRouteMatch>,
24 assetCrossOrigin?: AssetCrossOriginConfig,
25): Array<RouterManagedTag> {
26 matches = _getAssetMatches(matches)
27 const routeMeta = matches
28 .map((match) => match.meta)
29 .filter((meta) => meta !== undefined)
30​
31 const resultMeta: Array<RouterManagedTag> = []
32 const metaByAttribute: Record<string, true> = {}
33 let title: RouterManagedTag | undefined
34 for (let i = routeMeta.length - 1; i >= 0; i--) {
35 const metas = routeMeta[i]!
36 for (let j = metas.length - 1; j >= 0; j--) {
37 const m = metas[j]
38 if (!m) continue
39​
40 if (m.title) {
41 if (!title) {
42 title = {
43 tag: 'title',
44 children: m.title,
45 }
46 }
47 } else if ('script:ld+json' in m) {
48 try {
49 const json = JSON.stringify(m['script:ld+json'])
50 resultMeta.push({
51 tag: 'script',
52 attrs: {
53 type: 'application/ld+json',
54 },
55 children: escapeHtml(json),
56 })
57 } catch {
58 // Skip invalid JSON-LD objects
59 }
60 } else {
61 const attribute = m.name ?? m.property
62 if (attribute) {
63 if (metaByAttribute[attribute]) {
64 continue
65 } else {
66 metaByAttribute[attribute] = true
67 }
68 }
69​
70 resultMeta.push({
71 tag: 'meta',
72 attrs: {
73 ...m,
74 nonce,
75 },
76 })
77 }
78 }
79 }
80​
81 if (title) {
82 resultMeta.push(title)
83 }
84​
85 if (nonce) {
86 resultMeta.push({
87 tag: 'meta',
88 attrs: {
89 property: 'csp-nonce',
90 content: nonce,
91 },
92 })
93 }
94 resultMeta.reverse()
95​
96 const constructedLinks = matches
97 .flatMap((match) => match.links ?? [])
98 .filter((link) => link !== undefined)
99 .map((link) => ({
100 tag: 'link',
101 attrs: {
102 ...link,
103 nonce,
104 },
105 })) satisfies Array<RouterManagedTag>
106​
107 const manifest = router.ssr?.manifest
108 const manifestCssTags: Array<RouterManagedTag> = []
109 if (manifest) {
110 matches.forEach((match) => {
111 const css = manifest.routes[match.routeId]?.css
112 css?.forEach((link) => {
113 const resolvedLink = resolveManifestCssLink(link)
114 manifestCssTags.push({
115 tag: 'link',
116 attrs: {
117 rel: 'stylesheet',
118 ...resolvedLink,
119 crossOrigin:
120 getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ??
121 resolvedLink.crossOrigin,
122 suppressHydrationWarning: true,
123 nonce,
124 },
125 })
126 })
127 })
128​
129 if (manifest.inlineStyle) {
130 manifestCssTags.push({
131 tag: 'style',
132 attrs: {
133 ...manifest.inlineStyle.attrs,
134 nonce,
135 },
136 children: manifest.inlineStyle.children,
137 inlineCss: true,
138 })
139 }
140 }
141​
142 const preloadLinks: Array<RouterManagedTag> = []
143 if (manifest) {
144 matches.forEach((match) => {
145 manifest.routes[match.routeId]?.preloads?.forEach((preload) => {
146 preloadLinks.push({
147 tag: 'link',
148 attrs: {
149 ...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin),
150 nonce,
151 },
152 })
153 })
154 })
155 }
156​
157 const styles = matches
158 .flatMap((match) => match.styles ?? [])
159 .filter((style) => style !== undefined)
160 .map(({ children, ...attrs }) => ({
161 tag: 'style',
162 attrs: {
163 ...attrs,
164 nonce,
165 },
166 children: children as string | undefined,
167 })) satisfies Array<RouterManagedTag>
168​
169 const headScripts = matches
170 .flatMap((match) => match.headScripts ?? [])
171 .filter((script) => script !== undefined)
172 .map(({ children, ...script }) => ({
173 tag: 'script',
174 attrs: {
175 ...script,
176 nonce,
177 },
178 children: children as string | undefined,
179 })) satisfies Array<RouterManagedTag>
180​
181 const tags: Array<RouterManagedTag> = []
182 appendUniqueUserTags(tags, resultMeta)
183 tags.push(...preloadLinks)
184 appendUniqueUserTags(tags, constructedLinks)
185 tags.push(...manifestCssTags)
186 appendUniqueUserTags(tags, styles)
187 appendUniqueUserTags(tags, headScripts)
188 return tags
190​
191/**
192 * Build the head/link/meta/script tags from the renderable presented prefix.
193 * Used internally by `HeadContent`.
194 */
195export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => {
196 const router = useRouter()
197 const nonce = router.options.ssr?.nonce
198​
199 if (isServer ?? router.isServer) {
200 return buildTagsFromMatches(
201 router,
202 nonce,
203 router.stores.matches.get(),
204 assetCrossOrigin,
205 )
206 }
207​
208 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
209 const selectTags = React.useCallback(
210 (matches: Array<AnyRouteMatch>) =>
211 buildTagsFromMatches(router, nonce, matches, assetCrossOrigin),
212 [assetCrossOrigin, nonce, router],
213 )
214 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
215 return useSelector(router.stores.matches, selectTags, { compare: deepEqual })