From 108082397c51b1815884d2b08133953703b428a3 Mon Sep 17 00:00:00 2001 From: harlan Date: Sun, 14 Jul 2024 21:53:52 +1000 Subject: [PATCH] fix(addons): honour titleTemplate `tagPriority` Fixes https://github.com/harlan-zw/nuxt-seo/issues/137 --- .../addons/src/plugins/inferSeoMetaPlugin.ts | 6 ++- test/unhead/hooks/infer-seo-meta.test.ts | 44 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/packages/addons/src/plugins/inferSeoMetaPlugin.ts b/packages/addons/src/plugins/inferSeoMetaPlugin.ts index e6c34070..a4997c87 100644 --- a/packages/addons/src/plugins/inferSeoMetaPlugin.ts +++ b/packages/addons/src/plugins/inferSeoMetaPlugin.ts @@ -29,11 +29,15 @@ export interface InferSeoMetaPluginOptions { resolve({ entries }) { // need to find the last titleTemplate entry let titleTemplate = null + let lastWeight = 999 for (const entry of entries) { const inputKey = entry.resolvedInput ? 'resolvedInput' : 'input' const input = entry[inputKey] - if (typeof input.titleTemplate !== 'undefined') + const weight = (typeof input.titleTemplate === 'object' ? input.titleTemplate?.tagPriority : false) || entry.tagPriority || 100 + if (typeof input.titleTemplate !== 'undefined' && weight <= lastWeight) { titleTemplate = input.titleTemplate + lastWeight = weight + } } for (const entry of entries) { diff --git a/test/unhead/hooks/infer-seo-meta.test.ts b/test/unhead/hooks/infer-seo-meta.test.ts index bcf3e853..13da5a70 100644 --- a/test/unhead/hooks/infer-seo-meta.test.ts +++ b/test/unhead/hooks/infer-seo-meta.test.ts @@ -32,4 +32,48 @@ describe('hooks', () => { " `) }) + + it('infer-seo-meta multiple titleTemplates', async () => { + const head = useDOMHead({ + plugins: [ + InferSeoMetaPlugin(), + ], + }) + + head.push({ + titleTemplate: { + textContent: '%s | 1', + tagPriority: 50, + }, + title: 'Hello World', + meta: [ + { name: 'description', content: 'description' }, + ], + }) + + head.push({ + titleTemplate: '%s | 2', + title: 'Hello World', + meta: [ + { name: 'description', content: 'description' }, + ], + }, { + tagPriority: -5, + }) + + head.push({ + titleTemplate: '%s | 3', + title: 'Hello World', + meta: [ + { name: 'description', content: 'description' }, + ], + }, { + tagPriority: 103, + }) + const dom = await useDelayedSerializedDom() + const title = dom.match(/Hello World \| (\d)<\/title>/)?.[1] + const ogTitle = dom.match(/<meta property="og:title" content="Hello World \| (\d)">/)?.[1] + expect(title).toEqual(ogTitle) + expect(title).toEqual(`2`) + }) })