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