Skip to content

Commit

Permalink
fix(useSeoMeta): support multiple themeColor's with media
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Jun 26, 2023
1 parent a30b48f commit 75fd20d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
22 changes: 20 additions & 2 deletions packages/unhead/src/utils/meta/unpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 2,9 @@ import type { Head, MetaFlatInput } from '@unhead/schema'
import { unpackToArray, unpackToString } from 'packrup'
import { MetaPackingSchema } from './utils'

const ArrayableInputs = ['Image', 'Video', 'Audio']
const OpenGraphInputs = ['Image', 'Video', 'Audio']

const SimpleArrayUnpackMetas: (keyof MetaFlatInput)[] = ['themeColor']

const ColonPrefixKeys = /^(og|twitter|fb)/

Expand Down Expand Up @@ -49,7 51,7 @@ function changeKeyCasingDeep<T extends any>(input: T): T {
export function unpackMeta<T extends MetaFlatInput>(input: T): Required<Head>['meta'] {
const extras: Record<string, any>[] = []

ArrayableInputs.forEach((key) => {
OpenGraphInputs.forEach((key) => {
const ogKey = `og:${key.toLowerCase()}`
const inputKey = `og${key}` as keyof MetaFlatInput
const val = input[inputKey]
Expand All @@ -76,6 78,22 @@ export function unpackMeta<T extends MetaFlatInput>(input: T): Required<Head>['m
delete input[inputKey]
}
})

SimpleArrayUnpackMetas.forEach((meta: keyof T) => {
if (input[meta]) {
// maybe it's an array, convert to array
const val = (Array.isArray(input[meta]) ? input[meta] : [input[meta]]) as (Record<string, string>)[]
// for each array entry
delete input[meta]
val.forEach((entry) => {
extras.push({
name: fixKeyCase(meta as string),
...entry,
})
})
}
})

const meta = unpackToArray((input), {
key({ key }) {
return resolveMetaKeyType(key) as string
Expand Down
27 changes: 27 additions & 0 deletions test/unhead/useSeoMeta.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,27 @@
import { createHead, useSeoMeta } from 'unhead'
import { renderSSRHead } from '@unhead/ssr'
import { describe, it } from 'vitest'

describe('useSeoMeta', () => {
it('themeColor', async () => {
const head = createHead()

useSeoMeta({
themeColor: [
{ content: 'cyan', media: '(prefers-color-scheme: light)' },
{ content: 'black', media: '(prefers-color-scheme: dark)' },
],
})

expect(await renderSSRHead(head)).toMatchInlineSnapshot(`
{
"bodyAttrs": "",
"bodyTags": "",
"bodyTagsOpen": "",
"headTags": "<meta name=\\"theme-color\\" content=\\"cyan\\" media=\\"(prefers-color-scheme: light)\\">
<meta name=\\"theme-color\\" content=\\"black\\" media=\\"(prefers-color-scheme: dark)\\">",
"htmlAttrs": "",
}
`)
})
})

0 comments on commit 75fd20d

Please sign in to comment.