Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
49 changes: 40 additions & 9 deletions packages/core/src/head.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import debounce from './debounce'

const INERTIA_ATTRIBUTES = ['data-inertia', 'inertia']

const Renderer = {
buildDOMElement(tag: string): ChildNode {
const template = document.createElement('template')
Expand All @@ -20,13 +22,19 @@ const Renderer = {
},

isInertiaManagedElement(element: Element): boolean {
return element.nodeType === Node.ELEMENT_NODE && element.getAttribute('inertia') !== null
return (
element.nodeType === Node.ELEMENT_NODE &&
INERTIA_ATTRIBUTES.some((attribute) => element.getAttribute(attribute) !== null)
)
},

findMatchingElementIndex(element: Element, elements: Array<Element>): number {
const key = element.getAttribute('inertia')
if (key !== null) {
return elements.findIndex((element) => element.getAttribute('inertia') === key)
for (const attr of INERTIA_ATTRIBUTES) {
const key = element.getAttribute(attr)

if (key !== null) {
return elements.findIndex((el) => el.getAttribute(attr) === key)
}
}

return -1
Expand Down Expand Up @@ -64,8 +72,21 @@ export default function createHeadManager(
createProvider: () => {
update: (elements: string[]) => void
disconnect: () => void
preferredAttribute: () => string
}
} {
// Detect which attribute to use based on existing elements
let preferredAttribute = 'inertia'

if (!isServer) {
const hasLegacyAttribute = document.querySelector('[inertia]')
const hasDataAttribute = document.querySelector('[data-inertia]')

if (!hasLegacyAttribute && hasDataAttribute) {
preferredAttribute = 'data-inertia'
}
}

const states: Record<string, Array<string>> = {}
let lastProviderId = 0

Expand Down Expand Up @@ -102,7 +123,7 @@ export default function createHeadManager(
const title = titleCallback('')

const defaults: Record<string, string> = {
...(title ? { title: `<title inertia="">${title}</title>` } : {}),
...(title ? { title: `<title ${preferredAttribute}="">${title}</title>` } : {}),
}

const elements = Object.values(states)
Expand All @@ -118,10 +139,19 @@ export default function createHeadManager(
return carry
}

const match = element.match(/ inertia="[^"]+"/)
if (match) {
carry[match[0]] = element
} else {
let matchFound = false

for (const attr of INERTIA_ATTRIBUTES) {
const match = element.match(new RegExp(` ${attr}="[^"]+"`))

if (match) {
carry[match[0]] = element
matchFound = true
break
}
}

if (!matchFound) {
carry[Object.keys(carry).length] = element
}

Expand All @@ -148,6 +178,7 @@ export default function createHeadManager(
reconnect: () => reconnect(id),
update: (elements) => update(id, elements),
disconnect: () => disconnect(id),
preferredAttribute: () => preferredAttribute,
}
},
}
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/Head.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const Head: InertiaHead = function ({ children, title }) {

function ensureNodeHasInertiaProp(node) {
return React.cloneElement(node, {
inertia: node.props['head-key'] !== undefined ? node.props['head-key'] : '',
[provider.preferredAttribute()]: node.props['head-key'] !== undefined ? node.props['head-key'] : '',
})
}

Expand All @@ -94,7 +94,7 @@ const Head: InertiaHead = function ({ children, title }) {
.filter((node) => node)
.map((node) => renderNode(node))
if (title && !computed.find((tag) => tag.startsWith('<title'))) {
computed.push(`<title inertia>${title}</title>`)
computed.push(`<title ${provider.preferredAttribute()}>${title}</title>`)
}
return computed
}
Expand Down
2 changes: 1 addition & 1 deletion packages/react/test-app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>
<head>
<meta charset="utf-8" />
<title>Inertia React - Testing Environment</title>
<title {{ titleAttribute }}>Inertia React - Testing Environment</title>
<script>
window.initialPage = '{{ placeholder }}'
</script>
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte/test-app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>
<head>
<meta charset="utf-8" />
<title>Inertia Svelte - Testing Environment</title>
<title {{ titleAttribute }}>Inertia Svelte - Testing Environment</title>
<script>
window.initialPage = '{{ placeholder }}'
</script>
Expand Down
4 changes: 2 additions & 2 deletions packages/vue3/src/head.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const Head: InertiaHead = defineComponent({
},
renderTagStart(node) {
node.props = node.props || {}
node.props.inertia = node.props['head-key'] !== undefined ? node.props['head-key'] : ''
node.props[this.provider.preferredAttribute()] = node.props['head-key'] !== undefined ? node.props['head-key'] : ''
const attrs = Object.keys(node.props).reduce((carry, name) => {
const value = String(node.props[name])
if (['key', 'head-key'].includes(name)) {
Expand Down Expand Up @@ -96,7 +96,7 @@ const Head: InertiaHead = defineComponent({
},
addTitleElement(elements) {
if (this.title && !elements.find((tag) => tag.startsWith('<title'))) {
elements.push(`<title inertia>${this.title}</title>`)
elements.push(`<title ${this.provider.preferredAttribute()}>${this.title}</title>`)
}
return elements
},
Expand Down
2 changes: 1 addition & 1 deletion packages/vue3/test-app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>
<head>
<meta charset="utf-8" />
<title>Inertia Vue - Testing Environment</title>
<title {{ titleAttribute }}>Inertia Vue - Testing Environment</title>
<script>
window.initialPage = '{{ placeholder }}'
</script>
Expand Down
5 changes: 3 additions & 2 deletions tests/app/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const package = process.env.PACKAGE || 'vue3'

module.exports = {
package,
render: (req, res, data) => {
render: (req, res, data, titleAttribute = '') => {
data = {
component: req.path
.slice(1)
Expand Down Expand Up @@ -46,7 +46,8 @@ module.exports = {
fs
.readFileSync(path.resolve(__dirname, '../../packages/', package, 'test-app/dist/index.html'))
.toString()
.replace("'{{ placeholder }}'", JSON.stringify(data)),
.replace("'{{ placeholder }}'", JSON.stringify(data))
.replace('{{ titleAttribute }}', titleAttribute),
)
},
location: (res, href) => res.status(409).header('X-Inertia-Location', href).send(''),
Expand Down
2 changes: 2 additions & 0 deletions tests/app/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ app.get('/client-side-visit', (req, res) =>
}),
)

app.get('/head/:attribute', (req, res) => inertia.render(req, res, { component: 'Head' }, req.params.attribute))

app.get('/visits/partial-reloads', (req, res) =>
inertia.render(req, res, {
component: 'Visits/PartialReloads',
Expand Down
36 changes: 23 additions & 13 deletions tests/head.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
import { expect, test } from '@playwright/test'

test('renders the title tag and children', async ({ page }) => {
test.skip(process.env.PACKAGE === 'svelte', 'Svelte adapter has no Head component')
const supportedAttributes = [undefined, 'inertia', 'data-inertia']

await page.goto('/head')
supportedAttributes.forEach((attribute) => {
test(`renders the title tag and children with ${attribute ?? 'no'} attribute`, async ({ page }) => {
test.skip(process.env.PACKAGE === 'svelte', 'Svelte adapter has no Head component')

const inertiaTitle = await page.evaluate(() => document.querySelector('title[inertia]')?.textContent)
await page.goto(attribute ? `/head/${attribute}` : '/head')

await expect(inertiaTitle).toBe('Test Head Component')
await expect(page.locator('meta[name="viewport"]')).toHaveAttribute('content', 'width=device-width, initial-scale=1')
await expect(page.locator('meta[name="description"]')).toHaveAttribute('content', 'This is an "escape" example')
await expect(page.locator('meta[name="number"]')).toHaveAttribute('content', '0')
await expect(page.locator('meta[name="boolean"]')).toHaveAttribute('content', 'true')
await expect(page.locator('meta[name="false"]')).toHaveAttribute('content', 'false')
await expect(page.locator('meta[name="null"]')).toHaveAttribute('content', 'null')
await expect(page.locator('meta[name="undefined"]')).toHaveAttribute('content', 'undefined')
await expect(page.locator('meta[name="float"]')).toHaveAttribute('content', '3.14')
const inertiaTitle = await page.evaluate(
(attribute) => document.querySelector(`title[${attribute}]`)?.textContent,
attribute ?? 'inertia', // it defaults to 'inertia' if no attribute is provided
)

await expect(inertiaTitle).toBe('Test Head Component')
await expect(page.locator('meta[name="viewport"]')).toHaveAttribute(
'content',
'width=device-width, initial-scale=1',
)
await expect(page.locator('meta[name="description"]')).toHaveAttribute('content', 'This is an "escape" example')
await expect(page.locator('meta[name="number"]')).toHaveAttribute('content', '0')
await expect(page.locator('meta[name="boolean"]')).toHaveAttribute('content', 'true')
await expect(page.locator('meta[name="false"]')).toHaveAttribute('content', 'false')
await expect(page.locator('meta[name="null"]')).toHaveAttribute('content', 'null')
await expect(page.locator('meta[name="undefined"]')).toHaveAttribute('content', 'undefined')
await expect(page.locator('meta[name="float"]')).toHaveAttribute('content', '3.14')
})
})