Skip to content

feat: allow tags insertion before </body> #67

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

Merged
merged 6 commits into from
Jul 29, 2022
Merged
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
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ import { renderHeadToString } from '@vueuse/head'
const appHTML = await renderToString(yourVueApp)

// `head` is created from `createHead()`
const { headTags, htmlAttrs, bodyAttrs } = renderHeadToString(head)
const { headTags, htmlAttrs, bodyAttrs, bodyTags } = renderHeadToString(head)

const finalHTML = `
<html${htmlAttrs}>
Expand All @@ -81,6 +81,7 @@ const finalHTML = `

<body${bodyAttrs}>
<div id="app">${appHTML}</div>
${bodyTags}
</body>

</html>
Expand Down Expand Up @@ -131,6 +132,19 @@ useHead({
})
```

To render tags at the end of the `<body>`, set `body: true` in a HeadAttrs Object.

```ts
useHead({
script: [
{
children: `console.log('Hello world!')`,
body: true
},
],
})
```

To set the `textContent` of an element, use the `children` attribute:

```ts
Expand Down Expand Up @@ -180,13 +194,15 @@ Note that you need to use `<html>` and `<body>` to set `htmlAttrs` and `bodyAttr
- Returns: `HTMLResult`

```ts
interface HTMLResult {
export interface HTMLResult {
// Tags in `<head>`
readonly headTags: string
// Attributes for `<html>`
readonly htmlAttrs: string
// Attributes for `<body>`
readonly bodyAttrs: string
// Tags in `<body>`
readonly bodyTags: string
}
```

Expand Down
6 changes: 6 additions & 0 deletions example/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ export const createApp = () => {
key: 'zh',
},
],
script: [
{
children: `console.log('hi')`,
body: true
},
],
})
return () => (
<div>
Expand Down
2 changes: 2 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export const HEAD_COUNT_KEY = `head:count`
export const HEAD_ATTRS_KEY = `data-head-attrs`

export const SELF_CLOSING_TAGS = ['meta', 'link', 'base']

export const BODY_TAG_ATTR_NAME = `data-meta-body`
23 changes: 15 additions & 8 deletions src/create-element.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { BODY_TAG_ATTR_NAME } from "./constants"

export const createElement = (
tag: string,
attrs: { [k: string]: any },
Expand All @@ -6,16 +8,21 @@ export const createElement = (
const el = document.createElement(tag)

for (const key of Object.keys(attrs)) {
let value = attrs[key]
if (key === 'body' && attrs.body === true) {
// set meta-body attribute to add the tag before </body>
el.setAttribute(BODY_TAG_ATTR_NAME, 'true')
} else {
let value = attrs[key]

if (key === 'key' || value === false) {
continue
}
if (key === 'key' || value === false) {
continue
}

if (key === 'children') {
el.textContent = value
} else {
el.setAttribute(key, value)
if (key === 'children') {
el.textContent = value
} else {
el.setAttribute(key, value)
}
}
}

Expand Down
61 changes: 46 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
HEAD_COUNT_KEY,
HEAD_ATTRS_KEY,
SELF_CLOSING_TAGS,
BODY_TAG_ATTR_NAME,
} from './constants'
import { createElement } from './create-element'
import { stringifyAttrs } from './stringify-attrs'
Expand All @@ -39,6 +40,7 @@ export type HeadObjectPlain = UnwrapRef<HeadObject>
export type HeadTag = {
tag: string
props: {
body?: boolean
[k: string]: any
}
}
Expand All @@ -62,6 +64,8 @@ export interface HTMLResult {
readonly htmlAttrs: string
// Attributes for `<body>`
readonly bodyAttrs: string
// Tags in `<body>`
readonly bodyTags: string
}

const getTagKey = (
Expand Down Expand Up @@ -170,20 +174,30 @@ const updateElements = (
tags: HeadTag[],
) => {
const head = document.head
const body = document.body
let headCountEl = head.querySelector(`meta[name="${HEAD_COUNT_KEY}"]`)
let bodyMetaElements = body.querySelectorAll(`[${BODY_TAG_ATTR_NAME}]`);
const headCount = headCountEl
? Number(headCountEl.getAttribute('content'))
: 0
const oldElements: Element[] = []
const oldHeadElements: Element[] = []
const oldBodyElements: Element[] = []

if (bodyMetaElements) {
for (let i = 0; i < bodyMetaElements.length; i++) {
if (bodyMetaElements[i] && bodyMetaElements[i].tagName?.toLowerCase() === type) {
oldBodyElements.push(bodyMetaElements[i])
}
}
}
if (headCountEl) {
for (
let i = 0, j = headCountEl.previousElementSibling;
i < headCount;
i++, j = j?.previousElementSibling || null
) {
if (j?.tagName?.toLowerCase() === type) {
oldElements.push(j)
oldHeadElements.push(j)
}
}
} else {
Expand All @@ -192,28 +206,34 @@ const updateElements = (
headCountEl.setAttribute('content', '0')
head.append(headCountEl)
}
let newElements = tags.map((tag) =>
createElement(tag.tag, tag.props, document),
)
let newElements = tags.map((tag) => ({
element: createElement(tag.tag, tag.props, document),
body: tag.props.body ?? false
}))

newElements = newElements.filter((newEl) => {
for (let i = 0; i < oldElements.length; i++) {
const oldEl = oldElements[i]
if (isEqualNode(oldEl, newEl)) {
oldElements.splice(i, 1)
for (let i = 0; i < oldHeadElements.length; i++) {
const oldEl = oldHeadElements[i]
if (isEqualNode(oldEl, newEl.element)) {
oldHeadElements.splice(i, 1)
return false
}
}
return true
})

oldElements.forEach((t) => t.parentNode?.removeChild(t))
oldBodyElements.forEach((t) => t.parentNode?.removeChild(t))
oldHeadElements.forEach((t) => t.parentNode?.removeChild(t))
newElements.forEach((t) => {
head.insertBefore(t, headCountEl)
if (t.body === true) {
body.insertAdjacentElement('beforeend', t.element)
} else {
head.insertBefore(t.element, headCountEl)
}
})
headCountEl.setAttribute(
'content',
'' + (headCount - oldElements.length + newElements.length),
'' + (headCount - oldHeadElements.length + newElements.filter(t => !t.body).length),
)
}

Expand Down Expand Up @@ -339,27 +359,35 @@ export const useHead = (obj: MaybeRef<HeadObject>) => {
}

const tagToString = (tag: HeadTag) => {
let isBodyTag = false
if (tag.props.body) {
isBodyTag = true
// avoid rendering body attr
delete tag.props.body
}
let attrs = stringifyAttrs(tag.props)

if (SELF_CLOSING_TAGS.includes(tag.tag)) {
return `<${tag.tag}${attrs}>`
return `<${tag.tag}${attrs}${isBodyTag ? ' ' + BODY_TAG_ATTR_NAME : ''}>`
}

return `<${tag.tag}${attrs}>${tag.props.children || ''}</${tag.tag}>`
return `<${tag.tag}${attrs}${isBodyTag ? ' ' + BODY_TAG_ATTR_NAME : ''}>${tag.props.children || ''}</${tag.tag}>`
}

export const renderHeadToString = (head: HeadClient): HTMLResult => {
const tags: string[] = []
let titleTag = ''
let htmlAttrs: HeadAttrs = {}
let bodyAttrs: HeadAttrs = {}
let bodyTags: string[] = []
for (const tag of head.headTags) {
if (tag.tag === 'title') {
titleTag = tagToString(tag)
} else if (tag.tag === 'htmlAttrs') {
Object.assign(htmlAttrs, tag.props)
} else if (tag.tag === 'bodyAttrs') {
Object.assign(bodyAttrs, tag.props)
} else if (tag.props.body) {
bodyTags.push(tagToString(tag))
} else {
tags.push(tagToString(tag))
}
Expand All @@ -382,6 +410,9 @@ export const renderHeadToString = (head: HeadClient): HTMLResult => {
[HEAD_ATTRS_KEY]: Object.keys(bodyAttrs).join(','),
})
},
get bodyTags() {
return bodyTags.join('')
}
}
}

Expand Down
9 changes: 9 additions & 0 deletions tests/test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,12 @@ test('script key', async (t) => {
`<script>console.log('B')</script><meta name="head:count" content="1">`,
)
})

test('body script', async (t) => {
const page = await t.context.browser.newPage()
await page.goto(`http://localhost:3000`)

const script = await page.$('[data-meta-body]')
const scriptHtml = await script.innerHTML()
t.is(scriptHtml, `console.log('hi')`)
})