Skip to content
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

feat(nuxt): head manipulation with islands #27987

Merged
merged 33 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
c524953
wip
huang-julien Jun 30, 2024
577ba96
feat: wip
huang-julien Jun 30, 2024
42d49b4
fix: remove filter and key
huang-julien Jul 4, 2024
f2bdba2
perf: push into head only if array.length
huang-julien Jul 14, 2024
785f8e8
revert: revert debug
huang-julien Jul 14, 2024
491c6cd
Merge branch 'main' into feat/island_head
huang-julien Jul 14, 2024
0b97f7d
chore: lint
huang-julien Jul 14, 2024
d89f241
[autofix.ci] apply automated fixes
autofix-ci[bot] Jul 14, 2024
9474ce3
fix: test and ssr head
huang-julien Jul 14, 2024
fecb33a
Merge branch 'feat/island_head' of https://github.com/nuxt/nuxt into …
huang-julien Jul 14, 2024
e9829ca
Merge branch 'main' into feat/island_head
huang-julien Jul 19, 2024
a8997f2
update test
huang-julien Jul 19, 2024
5e69b79
fix tests
huang-julien Jul 19, 2024
c35a2e6
fix test
huang-julien Jul 19, 2024
5441ba3
Merge branch 'main' into feat/island_head
huang-julien Aug 21, 2024
9542acd
chore: move unhead vue to devdeps
huang-julien Aug 21, 2024
4624811
Merge remote-tracking branch 'origin/main' into feat/island_head
huang-julien Aug 21, 2024
3b83e11
test: update snapshots
huang-julien Aug 21, 2024
83cd9e3
perf: don't push empty inline styles
huang-julien Aug 21, 2024
1d5203a
test: update snapshots
huang-julien Aug 21, 2024
ac4b3a0
Merge remote-tracking branch 'origin/main' into feat/island_head
danielroe Aug 22, 2024
7d3ac1a
chore: bump unhead/vue
danielroe Aug 22, 2024
f6504b4
chore: dedupe lockfile
danielroe Aug 22, 2024
103b98a
test: remove references to `@nuxt+ui-templates` pkg
danielroe Aug 22, 2024
010c9a6
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 22, 2024
0f5b37e
chore: remove todo comment
danielroe Aug 22, 2024
19211a7
test: update filter
danielroe Aug 22, 2024
11a81ca
fix: don't duplicate inline styles
danielroe Aug 22, 2024
4ed877d
test: update snapshot
danielroe Aug 22, 2024
bf9ff58
test: add prop
danielroe Aug 22, 2024
80fc187
test: ignore `PureComponent` (preexisting dev time bug)
danielroe Aug 22, 2024
4b62566
test: one more update
danielroe Aug 22, 2024
b82fcd0
chore: again
danielroe Aug 22, 2024
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
7 changes: 6 additions & 1 deletion packages/nuxt/src/app/components/island-renderer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import type { defineAsyncComponent } from 'vue'
import { createVNode, defineComponent, onErrorCaptured } from 'vue'

import { injectHead } from '@unhead/vue'
import { createError } from '../composables/error'

// @ts-expect-error virtual file
import { islandComponents } from '#build/components.islands.mjs'
import { islandComponents } from '#build/components.islands.mjs'

export default defineComponent({
props: {
Expand All @@ -14,6 +15,10 @@ export default defineComponent({
},
},
setup (props) {
// reset head - we don't want to have any head tags from plugin or anywhere else.
const head = injectHead()
head.headEntries().splice(0, head.headEntries().length)

const component = islandComponents[props.context.name] as ReturnType<typeof defineAsyncComponent>

if (!component) {
Expand Down
19 changes: 12 additions & 7 deletions packages/nuxt/src/app/components/nuxt-island.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Component, PropType, VNode } from 'vue'
import { Fragment, Teleport, computed, createStaticVNode, createVNode, defineComponent, getCurrentInstance, h, nextTick, onMounted, ref, toRaw, watch, withMemo } from 'vue'
import { Fragment, Teleport, computed, createStaticVNode, createVNode, defineComponent, getCurrentInstance, h, nextTick, onMounted, reactive, ref, toRaw, watch, withMemo } from 'vue'
import { debounce } from 'perfect-debounce'
import { hash } from 'ohash'
import { appendResponseHeader } from 'h3'
import { useHead } from '@unhead/vue'
import { injectHead } from '@unhead/vue'
import { randomUUID } from 'uncrypto'
import { joinURL, withQuery } from 'ufo'
import type { FetchResponse } from 'ofetch'
Expand Down Expand Up @@ -96,7 +96,7 @@ export default defineComponent({
if (result.props) { toRevive.props = result.props }
if (result.slots) { toRevive.slots = result.slots }
if (result.components) { toRevive.components = result.components }

if (result.head) { toRevive.head = result.head }
nuxtApp.payload.data[key] = {
__nuxt_island: {
key,
Expand Down Expand Up @@ -158,8 +158,7 @@ export default defineComponent({
return html
})

const cHead = ref<Record<'link' | 'style', Array<Record<string, string>>>>({ link: [], style: [] })
useHead(cHead)
const head = injectHead()

async function _fetchComponent (force = false) {
const key = `${props.name}_${hashId.value}`
Expand Down Expand Up @@ -199,8 +198,7 @@ export default defineComponent({
}
try {
const res: NuxtIslandResponse = await nuxtApp[pKey][uid.value]
cHead.value.link = res.head.link
cHead.value.style = res.head.style

ssrHTML.value = res.html.replaceAll(DATA_ISLAND_UID_RE, `data-island-uid="${uid.value}"`)
key.value++
error.value = null
Expand Down Expand Up @@ -248,6 +246,13 @@ export default defineComponent({
await loadComponents(props.source, payloads.components)
}

if (nuxtApp.isHydrating) {
// re-push head into active head instance
nuxtApp.payload.data[`${props.name}_${hashId.value}`]?.head?.forEach((h) => {
head.push(h)
})
}

return (_ctx: any, _cache: any) => {
if (!html.value || error.value) {
return [slots.fallback?.({ error: error.value }) ?? createVNode('div')]
Expand Down
5 changes: 0 additions & 5 deletions packages/nuxt/src/app/plugins/revive-payload.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ if (componentIslands) {
}
return {
html: '',
state: {},
head: {
link: [],
style: [],
},
...result,
}
}
Expand Down
49 changes: 29 additions & 20 deletions packages/nuxt/src/core/runtime/nitro/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import { getQuery as getURLQuery, joinURL, withoutTrailingSlash } from 'ufo'
import { renderToString as _renderToString } from 'vue/server-renderer'
import { hash } from 'ohash'
import { propsToString, renderSSRHead } from '@unhead/ssr'
import type { HeadEntryOptions } from '@unhead/schema'
import type { Head, HeadEntryOptions, MergeHead } from '@unhead/schema'
import type { Link, Script, Style } from '@unhead/vue'
import { createServerHead } from '@unhead/vue'
import { toValue } from 'vue'

import { defineRenderHandler, getRouteRules, useNitroApp, useRuntimeConfig, useStorage } from 'nitro/runtime'

Expand Down Expand Up @@ -78,10 +79,7 @@ export interface NuxtIslandContext {
export interface NuxtIslandResponse {
id?: string
html: string
head: {
link: (Record<string, string>)[]
style: ({ innerHTML: string, key: string })[]
}
head: Head[]
props?: Record<string, Record<string, any>>
components?: Record<string, NuxtIslandClientResponse>
slots?: Record<string, NuxtIslandSlotResponse>
Expand Down Expand Up @@ -480,21 +478,32 @@ export default defineRenderHandler(async (event): Promise<Partial<RenderResponse

// Response for component islands
if (isRenderingIsland && islandContext) {
const islandHead: NuxtIslandResponse['head'] = {
link: [],
style: [],
}
for (const tag of await head.resolveTags()) {
if (tag.tag === 'link') {
islandHead.link.push({ key: 'island-link-' + hash(tag.props), ...tag.props })
} else if (tag.tag === 'style' && tag.innerHTML) {
islandHead.style.push({ key: 'island-style-' + hash(tag.innerHTML), innerHTML: tag.innerHTML })
}
}
// re-push inlined styles - head is reset by the island renderer
head.push({ style: inlinedStyles })
const islandResponse: NuxtIslandResponse = {
id: islandContext.id,
head: islandHead,
html: getServerComponentHTML(htmlContext.body),
head: head.headEntries().filter((h) => {
huang-julien marked this conversation as resolved.
Show resolved Hide resolved
if (h.resolvedInput) {
const resolvedInput = toValue(h.resolvedInput)
for (const key in resolvedInput) {
const input = resolvedInput[key as keyof MergeHead]
if (Array.isArray(input)) {
if (toValue(input).length === 0) {
delete resolvedInput[key as keyof MergeHead]
} else {
// @ts-expect-error todo fix this
input.forEach((i) => { if (typeof i === 'object') { i.key = 'island-key-' + hash(i) } })
huang-julien marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
if (Object.keys(h.resolvedInput).length) {
return true
}
}

return false
}).map(h => h.resolvedInput) as Head[],
html: getServerComponentHTML(_rendered.html),
components: getClientIslandResponse(ssrContext),
slots: getSlotIslandResponse(ssrContext),
}
Expand Down Expand Up @@ -637,8 +646,8 @@ function splitPayload (ssrContext: NuxtSSRContext) {
/**
* remove the root node from the html body
*/
function getServerComponentHTML (body: string[]): string {
const match = body[0].match(ROOT_NODE_REGEX)
function getServerComponentHTML (body: string): string {
const match = body.match(ROOT_NODE_REGEX)
return match ? match[1] : body[0]
}

Expand Down
102 changes: 69 additions & 33 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1873,6 +1873,12 @@ describe('server components/islands', () => {
await page.close()
})

it('/server-page', async () => {
const html = await $fetch<string>('/server-page')
// test island head
expect(html).toContain('<meta name="author" content="Nuxt">')
})

it.skipIf(isDev)('should allow server-only components to set prerender hints', async () => {
// @ts-expect-error ssssh! untyped secret property
const publicDir = useTestContext().nuxt._nitro.options.output.publicDir
Expand Down Expand Up @@ -2082,15 +2088,20 @@ describe('component islands', () => {

result.html = result.html.replace(/ data-island-uid="[^"]*"/g, '')
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href!.includes('@nuxt+ui-templates') && (l.href!.startsWith('_nuxt/components/islands/') && l.href!.includes('_nuxt/components/islands/RouteComponent')))
result.head = result.head.filter(h => h.tag !== 'link' || ((!h.props.href!.includes('@nuxt+ui-templates') && (h.props.href!.startsWith('_nuxt/components/islands/') && h.props.href!.includes('_nuxt/components/islands/RouteComponent')))))
}

expect(result).toMatchInlineSnapshot(`
{
"head": {
"link": [],
"style": [],
},
"head": [
{
"props": {
"data-capo": "",
"key": "island-tag-TNSM0SxoEb",
},
"tag": "htmlAttrs",
},
],
"html": "<pre data-island-uid> Route: /foo
</pre>",
}
Expand All @@ -2104,15 +2115,20 @@ describe('component islands', () => {
}),
}))
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href!.includes('@nuxt+ui-templates') && (l.href!.startsWith('_nuxt/components/islands/') && l.href!.includes('_nuxt/components/islands/LongAsyncComponent')))
result.head = result.head.filter(h => h.tag !== 'link' || (!h.props.href!.includes('@nuxt+ui-templates') && (h.props.href!.startsWith('_nuxt/components/islands/') && h.props.href!.includes('_nuxt/components/islands/LongAsyncComponent'))))
}
result.html = result.html.replaceAll(/ (data-island-uid|data-island-component)="([^"]*)"/g, '')
expect(result).toMatchInlineSnapshot(`
{
"head": {
"link": [],
"style": [],
},
"head": [
{
"props": {
"data-capo": "",
"key": "island-tag-TNSM0SxoEb",
},
"tag": "htmlAttrs",
},
],
"html": "<div data-island-uid><div> count is above 2 </div><!--[--><div style="display: contents;" data-island-uid data-island-slot="default"><!--teleport start--><!--teleport end--></div><!--]--> that was very long ... <div id="long-async-component-count">3</div> <!--[--><div style="display: contents;" data-island-uid data-island-slot="test"><!--teleport start--><!--teleport end--></div><!--]--><p>hello world !!!</p><!--[--><div style="display: contents;" data-island-uid data-island-slot="hello"><!--teleport start--><!--teleport end--></div><!--teleport start--><!--teleport end--><!--]--><!--[--><div style="display: contents;" data-island-uid data-island-slot="fallback"><!--teleport start--><!--teleport end--></div><!--teleport start--><!--teleport end--><!--]--></div>",
"slots": {
"default": {
Expand Down Expand Up @@ -2162,7 +2178,7 @@ describe('component islands', () => {
}),
}))
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href!.includes('@nuxt+ui-templates') && (l.href!.startsWith('_nuxt/components/islands/') && l.href!.includes('_nuxt/components/islands/AsyncServerComponent')))
result.head = result.head.filter(h => h.tag !== 'link' || (!h.props.href!.includes('@nuxt+ui-templates') && (h.props.href!.startsWith('_nuxt/components/islands/') && h.props.href!.includes('_nuxt/components/islands/AsyncServerComponent'))))
}
result.props = {}
result.components = {}
Expand All @@ -2172,10 +2188,15 @@ describe('component islands', () => {
expect(result).toMatchInlineSnapshot(`
{
"components": {},
"head": {
"link": [],
"style": [],
},
"head": [
{
"props": {
"data-capo": "",
"key": "island-tag-TNSM0SxoEb",
},
"tag": "htmlAttrs",
},
],
"html": "<div data-island-uid> This is a .server (20ms) async component that was very long ... <div id="async-server-component-count">2</div><div class="sugar-counter"> Sugar Counter 12 x 1 = 12 <button> Inc </button></div><!--[--><div style="display: contents;" data-island-uid data-island-slot="default"><!--teleport start--><!--teleport end--></div><!--]--></div>",
"props": {},
"slots": {},
Expand All @@ -2187,7 +2208,7 @@ describe('component islands', () => {
it('render server component with selective client hydration', async () => {
const result = await $fetch<NuxtIslandResponse>('/__nuxt_island/ServerWithClient')
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href!.includes('@nuxt+ui-templates') && (l.href!.startsWith('_nuxt/components/islands/') && l.href!.includes('_nuxt/components/islands/AsyncServerComponent')))
result.head = result.head.filter(h => h.tag !== 'link' || !h.props.href!.includes('@nuxt+ui-templates'))
}
const { components } = result
result.components = {}
Expand All @@ -2199,10 +2220,15 @@ describe('component islands', () => {
expect(result).toMatchInlineSnapshot(`
{
"components": {},
"head": {
"link": [],
"style": [],
},
"head": [
{
"props": {
"data-capo": "",
"key": "island-tag-TNSM0SxoEb",
},
"tag": "htmlAttrs",
},
],
"html": "<div data-island-uid> ServerWithClient.server.vue : <p>count: 0</p> This component should not be preloaded <div><!--[--><div>a</div><div>b</div><div>c</div><!--]--></div> This is not interactive <div class="sugar-counter"> Sugar Counter 12 x 1 = 12 <button> Inc </button></div><div class="interactive-component-wrapper" style="border:solid 1px red;"> The component bellow is not a slot but declared as interactive <!--[--><div style="display: contents;" data-island-uid data-island-component="Counter"></div><!--teleport start--><!--teleport end--><!--]--></div></div>",
"slots": {},
}
Expand Down Expand Up @@ -2231,11 +2257,17 @@ describe('component islands', () => {

if (isDev()) {
const fixtureDir = normalize(fileURLToPath(new URL('./fixtures/basic', import.meta.url)))
for (const link of result.head.link) {
link.href = link.href!.replace(fixtureDir, '/<rootDir>').replaceAll('//', '/')
link.key = link.key!.replace(/-[a-z0-9]+$/i, '')
for (const head of result.head) {
if (head.tag === 'link') {
if (head.props.href) {
head.props.href = head.props.href.replace(fixtureDir, '/<rootDir>').replaceAll('//', '/')
}
if (head.props.key) {
head.props.key = head.props.key!.replace(/-[a-z0-9]+$/i, '')
}
}
}
result.head.link.sort((a, b) => b.href!.localeCompare(a.href!))
result.head.filter(h => h.tag === 'link').sort((a, b) => b.props.href!.localeCompare(a.props.href!))
}

// TODO: fix rendering of styles in webpack
Expand All @@ -2254,7 +2286,7 @@ describe('component islands', () => {
} else if (isDev() && !isWebpack) {
// TODO: resolve dev bug triggered by earlier fetch of /vueuse-head page
// https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/core/runtime/nitro/renderer.ts#L139
result.head.link = result.head.link.filter(h => !h.href!.includes('SharedComponent'))
result.head = result.head.filter(h => h.tag !== 'link' || !h.props.href!.includes('@nuxt+ui-templates'))
expect(result.head).toMatchInlineSnapshot(`
{
"link": [
Expand Down Expand Up @@ -2612,14 +2644,18 @@ describe('Node.js compatibility for client-side', () => {
function normaliseIslandResult (result: NuxtIslandResponse) {
return {
...result,
head: {
...result.head,
style: result.head.style.map(s => ({
...s,
innerHTML: (s.innerHTML || '').replace(/data-v-[a-z0-9]+/, 'data-v-xxxxx').replace(/\.[a-zA-Z0-9]+\.svg/, '.svg'),
key: s.key.replace(/-[a-z0-9]+$/i, ''),
})),
},
head: result.head.map((h) => {
if (h.tag === 'style') {
return {
...h,
props: {
...h.props,
innerHTML: (h.props.innerHTML || '').replace(/data-v-[a-z0-9]+/, 'data-v-xxxxx'),
key: h.props.key!.replace(/-[a-z0-9]+$/i, ''),
},
}
}
}),
}
}

Expand Down
Loading