Open History to see the last commit
1import { afterEach, describe, expect, test, vi } from 'vitest'
2import {
3 cleanup,
4 fireEvent,
5 render,
6 screen,
7 waitFor,
8} from '@solidjs/testing-library'
9import { hydrate } from '@tanstack/router-core/ssr/client'
10import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id'
11β
12import {
13 HeadContent,
14 Link,
15 Outlet,
16 RouterContextProvider,
17 RouterProvider,
18 createBrowserHistory,
19 createMemoryHistory,
20 createRootRoute,
21 createRoute,
22 createRouter,
23} from '../src'
24import { Scripts } from '../src/Scripts'
25import type { Manifest } from '@tanstack/router-core'
26β
27const createTestManifest = (
28 routeId: string,
29 options?: { scriptFormat?: Manifest['scriptFormat'] },
30) =>
31 ({
32 ...(options?.scriptFormat ? { scriptFormat: options.scriptFormat } : {}),
33 routes: {
34 [routeId]: {
35 preloads: ['/main.js'],
36 css: ['/main.css'],
37 },
38 },
39 }) satisfies Manifest
40β
41const browserHistories: Array<ReturnType<typeof createBrowserHistory>> = []
42β
43const createTestBrowserHistory = () => {
44 const history = createBrowserHistory()
45 browserHistories.push(history)
46 return history
47}
48β
49afterEach(() => {
50 cleanup()
51 browserHistories.splice(0).forEach((history) => history.destroy())
52 window.history.replaceState(null, 'root', '/')
53 delete window.$_TSR
54})
55β
56describe('ssr scripts', () => {
57 test.each([undefined, '', 'window.inlineRan = true'])(
58 'mounts one external script with children %j and removes it on unmount',
59 async (children) => {
60 const rootRoute = createRootRoute({
61 scripts: () => [{ src: '/external-script.js', children }],
62 component: Scripts,
63 })
64 const router = createRouter({
65 routeTree: rootRoute,
66 history: createMemoryHistory(),
67 })
68 await router.load()
69β
70 const initialScriptCount = document.querySelectorAll('script').length
71 const { unmount } = render(() => <RouterProvider router={router} />)
72 const scripts = document.querySelectorAll(
73 'script[src="/external-script.js"]',
74 )
75 expect(scripts).toHaveLength(1)
76 expect(scripts[0]?.textContent).toBe('')
77 expect(document.querySelectorAll('script')).toHaveLength(
78 initialScriptCount + 1,
79 )
80β
81 unmount()
82 expect(document.querySelectorAll('script')).toHaveLength(
83 initialScriptCount,
84 )
85 expect(
86 document.querySelectorAll('script[src="/external-script.js"]'),
87 ).toHaveLength(0)
88 },
89 )
90β
91 test('updates route data scripts after client navigation', async () => {
92 const rootRoute = createRootRoute({
93 component: () => (
94 <>
95 <Outlet />
96 <Scripts />
97 </>
98 ),
99 })
100 const firstRoute = createRoute({
101 getParentRoute: () => rootRoute,
102 path: '/first',
103 scripts: () => [
104 {
105 id: 'first-route-data',
106 type: 'application/json',
107 children: 'first',
108 },
109 ],
110 component: () => <Link to="/second">Second</Link>,
111 })
112 const secondRoute = createRoute({
113 getParentRoute: () => rootRoute,
114 path: '/second',
115 scripts: () => [
116 {
117 id: 'second-route-data',
118 type: 'application/json',
119 children: 'second',
120 },
121 ],
122 component: () => <div>Second route</div>,
123 })
124 const router = createRouter({
125 routeTree: rootRoute.addChildren([firstRoute, secondRoute]),
126 history: createMemoryHistory({ initialEntries: ['/first'] }),
127 })
128β
129 const { container } = render(() => <RouterProvider router={router} />)
130 await screen.findByRole('link', { name: 'Second' })
131 expect(container.querySelector('#first-route-data')?.textContent).toBe(
132 'first',
133 )
134β
135 fireEvent.click(screen.getByRole('link', { name: 'Second' }))
136 expect(await screen.findByText('Second route')).toBeInTheDocument()
137 await waitFor(() => {
138 expect(container.querySelector('#first-route-data')).toBeNull()
139 expect(container.querySelector('#second-route-data')?.textContent).toBe(
140 'second',
141 )
142 })
143 })
144β
145 test('it works', async () => {
146 const rootRoute = createRootRoute({
147 // loader: () => new Promise((r) => setTimeout(r, 1)),
148 head: () => {
149 return {
150 scripts: [
151 {
152 src: 'script.js',
153 },
154 {
155 src: 'script2.js',
156 },
157 ],
158 }
159 },
160 component: () => {
161 return <Scripts />
162 },
163 })
164β
165 const indexRoute = createRoute({
166 path: '/',
167 getParentRoute: () => rootRoute,
168 // loader: () => new Promise((r) => setTimeout(r, 2)),
169 head: () => {
170 return {
171 scripts: [
172 {
173 src: 'script3.js',
174 },
175 ],
176 }
177 },
178 })
179β
180 const router = createRouter({
181 history: createMemoryHistory({
182 initialEntries: ['/'],
183 }),
184 routeTree: rootRoute.addChildren([indexRoute]),
185 isServer: true,
186 })
187β
188 await router.load()
189β
190 expect(router.state.matches.map((d) => d.headScripts).flat(1)).toEqual([
191 { src: 'script.js' },
192 { src: 'script2.js' },
193 { src: 'script3.js' },
194 ])
195 })
196β
197 test('excludes `undefined` script values', async () => {
198 const rootRoute = createRootRoute({
199 scripts: () => [
200 { src: 'script.js' },
201 undefined, // 'script2.js' opted out by certain conditions, such as `NODE_ENV=production`.
202 ],
203 component: () => {
204 return <Scripts />
205 },
206 })
207β
208 const indexRoute = createRoute({
209 path: '/',
210 getParentRoute: () => rootRoute,
211 scripts: () => [{ src: 'script3.js' }],
212 })
213β
214 const router = createRouter({
215 history: createMemoryHistory({
216 initialEntries: ['/'],
217 }),
218 routeTree: rootRoute.addChildren([indexRoute]),
219 isServer: true,
220 })
221β
222 await router.load()
223β
224 expect(router.state.matches.map((d) => d.scripts).flat(1)).toEqual([
225 { src: 'script.js' },
226 undefined,
227 { src: 'script3.js' },
228 ])
229β
230 const { container } = render(() => <RouterProvider router={router} />)
231β
232 expect(container.innerHTML).toEqual(
233 '<script src="script.js"></script><script src="script3.js"></script>',
234 )
235 })
236β
237 test('keeps manifest stylesheet links mounted across repeated Link navigations', async () => {
238 const history = createTestBrowserHistory()
239β
240 const rootRoute = createRootRoute({
241 component: () => {
242 return (
243 <>
244 <HeadContent />
245 <Outlet />
246 </>
247 )
248 },
249 })
250β
251 const indexRoute = createRoute({
252 path: '/',
253 getParentRoute: () => rootRoute,
254 component: () => <Link to="/about">Go to about page</Link>,
255 })
256β
257 const aboutRoute = createRoute({
258 path: '/about',
259 getParentRoute: () => rootRoute,
260 component: () => <Link to="/">Back to home</Link>,
261 })
262β
263 const router = createRouter({
264 history,
265 routeTree: rootRoute.addChildren([indexRoute, aboutRoute]),
266 })
267β
268 router.ssr = {
269 manifest: createTestManifest(rootRoute.id),
270 }
271β
272 await router.load()
273β
274 render(() => <RouterProvider router={router} />)
275β
276 const getStylesheetLink = () =>
277 Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find(
278 (link) => link.getAttribute('href') === '/main.css',
279 )
280β
281 await waitFor(() => {
282 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
283 })
284β
285 const initialLink = getStylesheetLink()
286 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
287β
288 for (let i = 0; i < 5; i++) {
289 fireEvent.click(screen.getByRole('link', { name: 'Go to about page' }))
290β
291 await waitFor(() => {
292 expect(router.state.location.pathname).toBe('/about')
293 })
294β
295 await screen.findByRole('link', { name: 'Back to home' })
296β
297 fireEvent.click(screen.getByRole('link', { name: 'Back to home' }))
298β
299 await waitFor(() => {
300 expect(router.state.location.pathname).toBe('/')
301 })
302β
303 await screen.findByRole('link', { name: 'Go to about page' })
304 }
305β
306 expect(getStylesheetLink()).toBe(initialLink)
307 expect(
308 Array.from(
309 document.head.querySelectorAll('link[rel="stylesheet"]'),
310 ).filter((link) => link.getAttribute('href') === '/main.css'),
311 ).toHaveLength(1)
312 })
313β
314 test('keeps manifest stylesheet links mounted when preload counts change', async () => {
315 const history = createTestBrowserHistory()
316β
317 const rootRoute = createRootRoute({
318 component: () => {
319 return (
320 <>
321 <HeadContent />
322 <Outlet />
323 </>
324 )
325 },
326 })
327β
328 const aRoute = createRoute({
329 path: '/a',
330 getParentRoute: () => rootRoute,
331 component: () => <Link to="/b">Go to B</Link>,
332 })
333β
334 const bRoute = createRoute({
335 path: '/b',
336 getParentRoute: () => rootRoute,
337 component: () => <Link to="/a">Go to A</Link>,
338 })
339β
340 const router = createRouter({
341 history,
342 routeTree: rootRoute.addChildren([aRoute, bRoute]),
343 })
344β
345 router.ssr = {
346 manifest: {
347 routes: {
348 [rootRoute.id]: {
349 preloads: ['/root.js'],
350 css: ['/main.css'],
351 },
352 [aRoute.id]: {
353 preloads: ['/a.js'],
354 },
355 [bRoute.id]: {
356 preloads: ['/b.js', '/b-child.js'],
357 },
358 },
359 },
360 }
361β
362 await router.navigate({ to: '/a' })
363 await router.load()
364β
365 render(() => <RouterProvider router={router} />)
366β
367 const getStylesheetLink = () =>
368 Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find(
369 (link) => link.getAttribute('href') === '/main.css',
370 )
371β
372 await waitFor(() => {
373 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
374 })
375β
376 const initialLink = getStylesheetLink()
377 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
378β
379 fireEvent.click(screen.getByRole('link', { name: 'Go to B' }))
380β
381 await waitFor(() => {
382 expect(router.state.location.pathname).toBe('/b')
383 })
384β
385 await screen.findByRole('link', { name: 'Go to A' })
386β
387 expect(getStylesheetLink()).toBe(initialLink)
388 expect(
389 Array.from(
390 document.head.querySelectorAll('link[rel="stylesheet"]'),
391 ).filter((link) => link.getAttribute('href') === '/main.css'),
392 ).toHaveLength(1)
393 })
394β
395 test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => {
396 const history = createTestBrowserHistory()
397β
398 const rootRoute = createRootRoute({
399 component: () => {
400 return (
401 <>
402 <HeadContent
403 assetCrossOrigin={{
404 script: 'anonymous',
405 stylesheet: 'use-credentials',
406 }}
407 />
408 <Outlet />
409 </>
410 )
411 },
412 })
413β
414 const indexRoute = createRoute({
415 path: '/',
416 getParentRoute: () => rootRoute,
417 component: () => <div>Index</div>,
418 })
419β
420 const router = createRouter({
421 history,
422 routeTree: rootRoute.addChildren([indexRoute]),
423 })
424β
425 router.ssr = {
426 manifest: createTestManifest(rootRoute.id),
427 }
428β
429 await router.load()
430β
431 render(() => <RouterProvider router={router} />)
432β
433 await waitFor(() => {
434 expect(document.head.querySelector('link[rel="stylesheet"]')).toBeTruthy()
435 expect(
436 document.head.querySelector('link[rel="modulepreload"]'),
437 ).toBeTruthy()
438 })
439β
440 expect(
441 document.head
442 .querySelector('link[rel="stylesheet"]')
443 ?.getAttribute('crossorigin'),
444 ).toBe('use-credentials')
445 expect(
446 document.head
447 .querySelector('link[rel="modulepreload"]')
448 ?.getAttribute('crossorigin'),
449 ).toBe('anonymous')
450 expect(
451 document.head
452 .querySelector('link[rel="modulepreload"]')
453 ?.getAttribute('fetchpriority'),
454 ).toBe('low')
455 })
456β
457 test('renders runtime manifest inlineStyle', async () => {
458 const history = createTestBrowserHistory()
459β
460 const rootRoute = createRootRoute({
461 component: () => {
462 return (
463 <>
464 <HeadContent />
465 <Outlet />
466 </>
467 )
468 },
469 })
470β
471 const indexRoute = createRoute({
472 path: '/',
473 getParentRoute: () => rootRoute,
474 component: () => <div>Index</div>,
475 })
476β
477 const router = createRouter({
478 history,
479 routeTree: rootRoute.addChildren([indexRoute]),
480 })
481β
482 router.ssr = {
483 manifest: {
484 inlineStyle: {
485 attrs: { id: 'runtime-inline-style' },
486 children: '.runtime{color:red}',
487 },
488 routes: {
489 [rootRoute.id]: {},
490 },
491 },
492 }
493β
494 await router.load()
495β
496 render(() => <RouterProvider router={router} />)
497β
498 await waitFor(() => {
499 expect(
500 document.head.querySelector('style#runtime-inline-style'),
501 ).toBeTruthy()
502 })
503β
504 expect(
505 document.head.querySelector('style#runtime-inline-style')?.textContent,
506 ).toBe('.runtime{color:red}')
507 })
508β
509 test('renders iife manifest preloads as low priority script links', async () => {
510 const history = createTestBrowserHistory()
511β
512 const rootRoute = createRootRoute({
513 component: () => {
514 return (
515 <>
516 <HeadContent />
517 <Outlet />
518 </>
519 )
520 },
521 })
522β
523 const indexRoute = createRoute({
524 path: '/',
525 getParentRoute: () => rootRoute,
526 component: () => <div>Index</div>,
527 })
528β
529 const router = createRouter({
530 history,
531 routeTree: rootRoute.addChildren([indexRoute]),
532 })
533β
534 router.ssr = {
535 manifest: createTestManifest(rootRoute.id, { scriptFormat: 'iife' }),
536 }
537β
538 await router.load()
539β
540 render(() => <RouterProvider router={router} />)
541β
542 await waitFor(() => {
543 expect(
544 document.head.querySelector('link[rel="preload"][as="script"]'),
545 ).toBeTruthy()
546 })
547β
548 expect(document.head.querySelector('link[rel="modulepreload"]')).toBeFalsy()
549 expect(
550 document.head
551 .querySelector('link[rel="preload"][as="script"]')
552 ?.getAttribute('fetchpriority'),
553 ).toBe('low')
554 })
555})
556β
557describe('ssr HeadContent', () => {
558 test('renders descendant assets during a data-only hydration handoff', async () => {
559 const rootRoute = createRootRoute({})
560 const dataOnlyRoute = createRoute({
561 getParentRoute: () => rootRoute,
562 path: '/report',
563 ssr: 'data-only',
564 loader: () => 'report',
565 })
566 const childRoute = createRoute({
567 getParentRoute: () => dataOnlyRoute,
568 path: '/details',
569 loader: () => 'details',
570 head: () => ({
571 meta: [{ name: 'solid-data-only-child', content: 'visible' }],
572 }),
573 scripts: () => [
574 {
575 id: 'solid-data-only-body-script',
576 type: 'application/json',
577 children: '{"source":"body"}',
578 },
579 ],
580 })
581 const router = createRouter({
582 history: createMemoryHistory({
583 initialEntries: ['/report/details'],
584 }),
585 routeTree: rootRoute.addChildren([
586 dataOnlyRoute.addChildren([childRoute]),
587 ]),
588 })
589 const matches = router.matchRoutes(router.latestLocation)
590 window.$_TSR = {
591 router: {
592 dehydratedData: {},
593 manifest: {
594 routes: {
595 [childRoute.id]: {
596 preloads: ['/solid-data-only-manifest.js'],
597 scripts: [
598 {
599 attrs: {
600 id: 'solid-data-only-manifest-script',
601 type: 'application/json',
602 },
603 children: '{"source":"manifest"}',
604 },
605 ],
606 },
607 },
608 },
609 matches: matches.map((match, index) => ({
610 i: dehydrateSsrMatchId(match.id),
611 s: 'success',
612 ssr: index === 1 ? 'data-only' : true,
613 l: index ? (index === 1 ? 'report' : 'details') : undefined,
614 u: Date.now(),
615 })),
616 },
617 h: vi.fn(),
618 e: vi.fn(),
619 c: vi.fn(),
620 p: vi.fn(),
621 buffer: [],
622 }
623β
624 await hydrate(router)
625β
626 expect(router.state.matches.map((match) => match.status)).toEqual([
627 'success',
628 'pending',
629 'success',
630 ])
631 render(() => (
632 <RouterContextProvider router={router}>
633 {() => (
634 <>
635 <HeadContent />
636 <Scripts />
637 </>
638 )}
639 </RouterContextProvider>
640 ))
641β
642 expect(
643 document.querySelector('meta[name="solid-data-only-child"]'),
644 ).not.toBeNull()
645 expect(
646 document.querySelector('link[href="/solid-data-only-manifest.js"]'),
647 ).not.toBeNull()
648 expect(
649 document.querySelector('#solid-data-only-body-script'),
650 ).not.toBeNull()
651 expect(
652 document.querySelector('#solid-data-only-manifest-script'),
653 ).not.toBeNull()
654 })
655β
656 test('derives title, dedupes meta, and allows non-loader HeadContent', async () => {
657 const rootRoute = createRootRoute({
658 loader: () =>
659 new Promise((r) => setTimeout(r, 1)).then(() => ({
660 description: 'Root',
661 })),
662 head: ({ loaderData }) => {
663 return {
664 meta: [
665 {
666 title: 'Root',
667 },
668 {
669 name: 'description',
670 content: loaderData?.description,
671 },
672 {
673 name: 'image',
674 content: 'image.jpg',
675 },
676 {
677 property: 'og:image',
678 content: 'root-image.jpg',
679 },
680 {
681 property: 'og:description',
682 content: 'Root description',
683 },
684 ],
685 }
686 },
687 component: () => {
688 return <HeadContent />
689 },
690 })
691β
692 const indexRoute = createRoute({
693 path: '/',
694 getParentRoute: () => rootRoute,
695 loader: () =>
696 new Promise((r) => setTimeout(r, 2)).then(() => ({
697 description: 'Index',
698 })),
699 head: ({ loaderData }) => {
700 return {
701 meta: [
702 {
703 title: 'Index',
704 },
705 {
706 name: 'description',
707 content: loaderData?.description,
708 },
709 {
710 name: 'last-modified',
711 content: '2021-10-10',
712 },
713 {
714 property: 'og:image',
715 content: 'index-image.jpg',
716 },
717 ],
718 }
719 },
720 })
721β
722 const router = createRouter({
723 history: createMemoryHistory({
724 initialEntries: ['/'],
725 }),
726 routeTree: rootRoute.addChildren([indexRoute]),
727 isServer: true,
728 })
729β
730 await router.load()
731β
732 expect(router.state.matches.map((d) => d.meta).flat(1)).toEqual([
733 { title: 'Root' },
734 { name: 'description', content: 'Root' },
735 { name: 'image', content: 'image.jpg' },
736 { property: 'og:image', content: 'root-image.jpg' },
737 { property: 'og:description', content: 'Root description' },
738 { title: 'Index' },
739 { name: 'description', content: 'Index' },
740 { name: 'last-modified', content: '2021-10-10' },
741 { property: 'og:image', content: 'index-image.jpg' },
742 ])
743 })
744β
745 test('keeps manifest stylesheet links mounted when history state changes', async () => {
746 const history = createTestBrowserHistory()
747β
748 const rootRoute = createRootRoute({
749 component: () => {
750 return (
751 <>
752 <HeadContent />
753 <button
754 onClick={() => {
755 window.history.replaceState(
756 { slideId: 'slide-2' },
757 '',
758 window.location.href,
759 )
760 }}
761 >
762 Replace state
763 </button>
764 <Outlet />
765 </>
766 )
767 },
768 })
769β
770 const indexRoute = createRoute({
771 path: '/',
772 getParentRoute: () => rootRoute,
773 component: () => <div>Index</div>,
774 })
775β
776 const router = createRouter({
777 history,
778 routeTree: rootRoute.addChildren([indexRoute]),
779 })
780β
781 router.ssr = {
782 manifest: createTestManifest(rootRoute.id),
783 }
784β
785 await router.load()
786β
787 render(() => <RouterProvider router={router} />)
788β
789 const getStylesheetLink = () =>
790 Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find(
791 (link) => link.getAttribute('href') === '/main.css',
792 )
793β
794 await waitFor(() => {
795 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
796 })
797β
798 const initialLink = getStylesheetLink()
799 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
800β
801 fireEvent.click(screen.getByRole('button', { name: 'Replace state' }))
802β
803 await waitFor(() => {
804 expect(router.state.location.state).toMatchObject({
805 slideId: 'slide-2',
806 })
807 })
808β
809 expect(getStylesheetLink()).toBe(initialLink)
810 expect(
811 Array.from(
812 document.head.querySelectorAll('link[rel="stylesheet"]'),
813 ).filter((link) => link.getAttribute('href') === '/main.css'),
814 ).toHaveLength(1)
815 })
816})