feat(web): open every external link in a new tab, derived from the URL (MITHOME-124)
General rule: links to another host open in a new tab with rel="noopener noreferrer"; internal paths, mailto: and tel: stay in the same tab. Behaviour was inconsistent before — the home Webmail button opened in the same tab while the other webmail links did not, and the CTA and header relied on a manual "external" switch. src/lib/external-link.ts decides from the URL (externalLinkProps for JSX, openExternalLinksInNewTab for CMS-provided HTML in About paragraphs, legal pages and the GDPR label). All link sites use it; the manual "external" CTA checkbox and NavigationItem flag are removed so the rule cannot be bypassed. Rule documented in architecture.md and CLAUDE.md; staging smoke SMOKE-07 checks every external homepage link. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
183b304687
commit
ca4d447d73
@@ -35,7 +35,8 @@ A projekt egy **Next.js 15 alapú marketing weboldal** a mozdIT Bt. számára, A
|
||||
2. **Stateless API**: A backend API teljesen stateless — session-t a kliens kezel.
|
||||
3. **Observability**: Minden szerveroldali hiba legyen logolva strukturált Winston-bejegyzésként stdout/stderr-re; az alkalmazás ne küldjön közvetlenül távoli logszolgáltatásnak. API-válaszok egységes formátuma: `{ success, data, error }`.
|
||||
4. **Security-by-design**: Input validáció minden API route-on, secrets csak env változókból.
|
||||
5. **Component-first**: Komponensek Server Component-ek alapértelmezetten — csak indokolt esetben adj `"use client"` direktívát.
|
||||
5. **Külső linkek mindig új lapon** (MITHOME-124, általános szabály): minden más hostra mutató http(s) link `target="_blank"` + `rel="noopener noreferrer"` attribútumot kap. Belső útvonal, `mailto:` és `tel:` ugyanazon a lapon marad. A döntés **a címből** születik, sosem kézi kapcsolóból: JSX-ben `<a href={href} {...externalLinkProps(href)}>`, CMS-ből érkező HTML-nél `openExternalLinksInNewTab(html)` (`proto/src/lib/external-link.ts`). Kézzel írt `target="_blank"` vagy „external” mező ne kerüljön a kódba.
|
||||
6. **Component-first**: Komponensek Server Component-ek alapértelmezetten — csak indokolt esetben adj `"use client"` direktívát.
|
||||
|
||||
## Adatfolyam (Request Lifecycle)
|
||||
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
4. **Commit**: Conventional Commits (`feat:`, `fix:`, `docs:`, `chore:`)
|
||||
5. **Fájlméret**: soft limit 300 sor, hard limit 400 sor
|
||||
6. **Language**: kód+commit = English, kommunikáció+docs = Magyar
|
||||
7. **OpenSpec**: nagyobb feature/API/adatmodell/architektúra változáshoz `/opsx-propose`, majd jóváhagyott specifikációra `/opsx-apply`; a Plane MITHOME és `TODO.md` marad a feladat- és státuszkezelés
|
||||
7. **Külső link = új lap**: minden külső link új lapon nyílik; mindig a `proto/src/lib/external-link.ts` helperrel (`externalLinkProps`, `openExternalLinksInNewTab`), nincs kézi kapcsoló (MITHOME-124)
|
||||
8. **OpenSpec**: nagyobb feature/API/adatmodell/architektúra változáshoz `/opsx-propose`, majd jóváhagyott specifikációra `/opsx-apply`; a Plane MITHOME és `TODO.md` marad a feladat- és státuszkezelés
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -63,6 +63,18 @@ for (const [locale, contactPath] of [['hu', '/hu/kapcsolat'], ['en', '/en/contac
|
||||
})
|
||||
}
|
||||
|
||||
// MITHOME-124: external links always open in a new tab (the home Webmail
|
||||
// button used to open in the same tab while other webmail links did not).
|
||||
test('SMOKE-07: external links on the homepage open in a new tab', async ({ page }) => {
|
||||
await page.goto('/hu')
|
||||
const external = page.locator('a[href^="http"]:not([href^="' + new URL(page.url()).origin + '"])')
|
||||
expect(await external.count()).toBeGreaterThan(0)
|
||||
for (const link of await external.all()) {
|
||||
await expect(link).toHaveAttribute('target', '_blank')
|
||||
await expect(link).toHaveAttribute('rel', /noopener/)
|
||||
}
|
||||
})
|
||||
|
||||
test('SMOKE-05: empty contact form is blocked client-side without API submission', async ({ page }) => {
|
||||
let contactPostCount = 0
|
||||
page.on('request', request => {
|
||||
|
||||
@@ -52,14 +52,16 @@ function toStringArray(items: readonly string[]): { value: string }[] {
|
||||
return items.map((value) => ({ value }))
|
||||
}
|
||||
|
||||
type CtaJson = { text: string; href: string; external?: boolean }
|
||||
// `external` in the legacy JSON is ignored: new-tab behaviour is derived
|
||||
// from the URL itself (MITHOME-124).
|
||||
type CtaJson = { text: string; href: string }
|
||||
|
||||
/** MITHOME-123: internal JSON paths become page links, the rest stay URLs. */
|
||||
function toCtaLink({ text, href, external }: CtaJson) {
|
||||
function toCtaLink({ text, href }: CtaJson) {
|
||||
const page = internalPathToPageKey(href)
|
||||
return page
|
||||
? { text, linkType: 'page' as const, page, external }
|
||||
: { text, linkType: 'url' as const, href, external }
|
||||
? { text, linkType: 'page' as const, page }
|
||||
: { text, linkType: 'url' as const, href }
|
||||
}
|
||||
|
||||
function buildHomeData(json: typeof homeJson) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { siteConfig } from '@/config/site'
|
||||
import Link from 'next/link'
|
||||
import type { NavigationItem } from '@/types/site'
|
||||
import type { Locale } from '@/lib/i18n'
|
||||
import { externalLinkProps } from '@/lib/external-link'
|
||||
|
||||
type FooterServiceItem = { id: string; title: string; icon: string }
|
||||
|
||||
@@ -97,6 +98,7 @@ export default function Footer({ nav, legalLinks, homeHref, description, contact
|
||||
<li key={item.href}>
|
||||
<a
|
||||
href={item.href}
|
||||
{...externalLinkProps(item.href)}
|
||||
className="group flex items-center gap-2 text-sm transition-all duration-200"
|
||||
style={{ color: 'var(--color-foreground-muted)' }}
|
||||
onMouseEnter={(e) => {
|
||||
@@ -165,6 +167,7 @@ export default function Footer({ nav, legalLinks, homeHref, description, contact
|
||||
<a
|
||||
key={link.href}
|
||||
href={link.href}
|
||||
{...externalLinkProps(link.href)}
|
||||
className="text-sm transition-all duration-200 link-underline relative"
|
||||
style={{ color: 'var(--color-foreground-muted)' }}
|
||||
onMouseEnter={(e) => {
|
||||
|
||||
@@ -168,4 +168,18 @@ describe('Header', () => {
|
||||
const mobileMenu = container.querySelector('.md\\:hidden.overflow-hidden')
|
||||
expect(mobileMenu).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// MITHOME-124: every external link opens in a new tab, derived from the URL.
|
||||
it('should open external nav links in a new tab and keep internal ones in place', () => {
|
||||
const nav = [...getMainNavigation('hu'), { label: 'Webmail', href: 'https://mail.mozdit.hu' }]
|
||||
render(<Header {...headerProps} nav={nav} />)
|
||||
|
||||
for (const link of screen.getAllByRole('link', { name: /Webmail/ })) {
|
||||
expect(link).toHaveAttribute('target', '_blank')
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
}
|
||||
for (const link of screen.getAllByRole('link', { name: 'Rólunk' })) {
|
||||
expect(link).not.toHaveAttribute('target')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import { ThemeToggle } from './ThemeProvider'
|
||||
import Link from 'next/link'
|
||||
import Image from 'next/image'
|
||||
import type { NavigationItem } from '@/types/site'
|
||||
import { externalLinkProps, isExternalHref } from '@/lib/external-link'
|
||||
|
||||
type HeaderProps = {
|
||||
nav: NavigationItem[]
|
||||
@@ -74,8 +75,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
|
||||
<a
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.external ? '_blank' : undefined}
|
||||
rel={item.external ? 'noopener noreferrer' : undefined}
|
||||
{...externalLinkProps(item.href)}
|
||||
className={`relative px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
|
||||
item.primary
|
||||
? 'btn btn-primary text-white'
|
||||
@@ -93,7 +93,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
|
||||
)}
|
||||
<span className="relative z-10">
|
||||
{item.label}
|
||||
{item.external && (
|
||||
{isExternalHref(item.href) && (
|
||||
<svg className="inline-block w-3 h-3 ml-1 -mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
@@ -161,8 +161,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
|
||||
<a
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.external ? '_blank' : undefined}
|
||||
rel={item.external ? 'noopener noreferrer' : undefined}
|
||||
{...externalLinkProps(item.href)}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
className={`block px-4 py-3 rounded-lg text-base font-medium transition-all duration-200 ${
|
||||
item.primary ? 'btn btn-primary text-white mt-2' : ''
|
||||
@@ -189,7 +188,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
|
||||
>
|
||||
<span className="flex items-center justify-between">
|
||||
{item.label}
|
||||
{item.external && (
|
||||
{isExternalHref(item.href) && (
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { localePath, type Locale } from '@/lib/i18n'
|
||||
import type { getAboutContent } from '@/lib/payload-content'
|
||||
import { openExternalLinksInNewTab } from '@/lib/external-link'
|
||||
|
||||
type AboutViewProps = {
|
||||
content: Awaited<ReturnType<typeof getAboutContent>>
|
||||
@@ -55,7 +56,7 @@ export default function AboutView({ content: pageContent, locale }: AboutViewPro
|
||||
{pageContent.story.paragraphs.map((paragraph, index) => (
|
||||
<p
|
||||
key={index}
|
||||
dangerouslySetInnerHTML={{ __html: paragraph }}
|
||||
dangerouslySetInnerHTML={{ __html: openExternalLinksInNewTab(paragraph) }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState } from 'react'
|
||||
import { siteConfig } from '@/config/site'
|
||||
import { localePath, type Locale } from '@/lib/i18n'
|
||||
import type { getContactContent } from '@/lib/payload-content'
|
||||
import { externalLinkProps, openExternalLinksInNewTab } from '@/lib/external-link'
|
||||
|
||||
type ContactViewProps = {
|
||||
content: Awaited<ReturnType<typeof getContactContent>>
|
||||
@@ -237,7 +238,7 @@ export default function ContactView({ content: pageContent, contactEmail, footer
|
||||
/>
|
||||
<span
|
||||
className="text-sm text-gray-700"
|
||||
dangerouslySetInnerHTML={{ __html: gdprLabel + ' *' }}
|
||||
dangerouslySetInnerHTML={{ __html: openExternalLinksInNewTab(gdprLabel) + ' *' }}
|
||||
/>
|
||||
</label>
|
||||
{errors.gdprConsent && <p className="mt-1 text-sm text-red-600">{errors.gdprConsent}</p>}
|
||||
@@ -303,8 +304,7 @@ export default function ContactView({ content: pageContent, contactEmail, footer
|
||||
// Szolgáltatások oldalon) — javítva a tényleges webmail
|
||||
// URL-re.
|
||||
href={webmailHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
{...externalLinkProps(webmailHref)}
|
||||
className="text-blue-600 hover:text-blue-700"
|
||||
>
|
||||
{pageContent.info.webmail.linkText}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Image from 'next/image'
|
||||
import { localePath, type Locale } from '@/lib/i18n'
|
||||
import type { getHomeContent, PartnerView } from '@/lib/payload-content'
|
||||
import { externalLinkProps } from '@/lib/external-link'
|
||||
|
||||
type HomeViewProps = {
|
||||
content: Awaited<ReturnType<typeof getHomeContent>>
|
||||
@@ -69,8 +70,7 @@ export default function HomeView({ content: pageContent, partners, locale }: Hom
|
||||
>
|
||||
<a
|
||||
href={pageContent.hero.cta.primary.href}
|
||||
target={pageContent.hero.cta.primary.external ? '_blank' : undefined}
|
||||
rel={pageContent.hero.cta.primary.external ? 'noopener noreferrer' : undefined}
|
||||
{...externalLinkProps(pageContent.hero.cta.primary.href)}
|
||||
className="btn btn-primary text-lg px-8 py-4 group"
|
||||
>
|
||||
<svg
|
||||
@@ -86,6 +86,7 @@ export default function HomeView({ content: pageContent, partners, locale }: Hom
|
||||
{pageContent.hero.cta.secondary && (
|
||||
<a
|
||||
href={pageContent.hero.cta.secondary.href}
|
||||
{...externalLinkProps(pageContent.hero.cta.secondary.href)}
|
||||
className="btn btn-secondary text-lg px-8 py-4"
|
||||
>
|
||||
{pageContent.hero.cta.secondary.text}
|
||||
@@ -248,8 +249,7 @@ export default function HomeView({ content: pageContent, partners, locale }: Hom
|
||||
<a
|
||||
key={partner.name}
|
||||
href={partner.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
{...externalLinkProps(partner.url)}
|
||||
className="group flex flex-col items-center gap-3 opacity-80 hover:opacity-100 transition-opacity duration-200"
|
||||
title={partner.name}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Locale } from '@/lib/i18n'
|
||||
import type { getLegalPage } from '@/lib/payload-content'
|
||||
import { openExternalLinksInNewTab } from '@/lib/external-link'
|
||||
|
||||
type LegalPageViewProps = {
|
||||
page: NonNullable<Awaited<ReturnType<typeof getLegalPage>>>
|
||||
@@ -45,11 +46,13 @@ export default function LegalPageView({ page, locale }: LegalPageViewProps) {
|
||||
style={{ color: 'var(--color-foreground-muted)' }}
|
||||
dangerouslySetInnerHTML={{
|
||||
// Ehelyett a valódi alkalmazásban javasolt egy Markdown parser, de az egyszerűség kedvéért a sima sortöréseket lekezeljük
|
||||
__html: section.content
|
||||
__html: openExternalLinksInNewTab(
|
||||
section.content
|
||||
.replace(/\n\n/g, '</p><p class="mb-4">')
|
||||
.replace(/• \*\*(.*?)\*\*/g, '<br/>• <strong>$1</strong>')
|
||||
.replace(/^/, '<p class="mb-4">')
|
||||
.replace(/$/, '</p>')
|
||||
.replace(/$/, '</p>'),
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { localePath, type Locale } from '@/lib/i18n'
|
||||
import type { getHomeContent, getServicesContent } from '@/lib/payload-content'
|
||||
import { externalLinkProps } from '@/lib/external-link'
|
||||
|
||||
type ServicesViewProps = {
|
||||
content: Awaited<ReturnType<typeof getServicesContent>>
|
||||
@@ -143,8 +144,7 @@ export default function ServicesView({ content: pageContent, homeServices, featu
|
||||
// target="_blank"-kal a "Webmail belépés" gombhoz — javítva a
|
||||
// tényleges webmail URL-re.
|
||||
href={webmailHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
{...externalLinkProps(webmailHref)}
|
||||
className="inline-block border-2 border-white text-white hover:bg-white hover:text-gray-900 font-medium px-8 py-3 rounded-md transition-colors"
|
||||
>
|
||||
{pageContent.cta.secondaryButton}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { globalVersions } from '../lib/payload-versions'
|
||||
* kihagyjuk, nehogy két, egymásnak ellentmondó forrás legyen.
|
||||
*
|
||||
* MITHOME-111 lokalizáció: minden fordítható szöveg `localized: true`; az
|
||||
* `icon`, a sor-`id` és az `external` közös. WHY a `cta.*.href` is
|
||||
* `icon` és a sor-`id` közös. WHY a `cta.*.href` is
|
||||
* lokalizált: egy külső cél nyelvenként eltérhet. Belső oldalra a CTA
|
||||
* oldalválasztóval mutat (MITHOME-123, fields/ctaLink.ts) — a nyelvhelyes
|
||||
* útvonalat a frontend számolja (/hu/kapcsolat vs /en/contact). A
|
||||
|
||||
@@ -21,6 +21,8 @@ const isPageLink = (sibling: Sibling) => (sibling?.linkType ?? 'page') === 'page
|
||||
*
|
||||
* WHY custom `validate` instead of `required`: `page` and `href` are only
|
||||
* required for their own link type; the other one is hidden and empty.
|
||||
* WHY no "open in new tab" switch: external links always open in a new
|
||||
* tab, decided from the URL (MITHOME-124, src/lib/external-link.ts).
|
||||
* DECISION: `href` stays localized (MITHOME-111) — an external target may
|
||||
* differ per language; `linkType`/`page` are shared across locales.
|
||||
*/
|
||||
@@ -57,7 +59,6 @@ export function ctaLinkGroup(name: string): GroupField {
|
||||
validate: (value: unknown, { siblingData }: { siblingData: Sibling }) =>
|
||||
isPageLink(siblingData) || Boolean(value) || 'Add meg az URL-t.',
|
||||
},
|
||||
{ name: 'external', type: 'checkbox', defaultValue: false },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { externalLinkProps, isExternalHref, openExternalLinksInNewTab } from './external-link'
|
||||
|
||||
const SITE = 'https://stage.mozdit.hu'
|
||||
|
||||
describe('isExternalHref (MITHOME-124)', () => {
|
||||
it.each([
|
||||
'https://mail.mozdit.hu',
|
||||
'http://example.com/path',
|
||||
'//cdn.example.com/x.png',
|
||||
'HTTPS://PARTNER.EXAMPLE',
|
||||
])('should treat %s as external', (href) => {
|
||||
expect(isExternalHref(href, SITE)).toBe(true)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'/hu/kapcsolat',
|
||||
'#top',
|
||||
'?q=1',
|
||||
'relative/path',
|
||||
'mailto:info@mozdit.hu',
|
||||
'tel:+3612345678',
|
||||
'https://stage.mozdit.hu/hu/rolunk',
|
||||
'',
|
||||
])('should treat %s as internal (same tab)', (href) => {
|
||||
expect(isExternalHref(href, SITE)).toBe(false)
|
||||
})
|
||||
|
||||
it('should not throw on malformed absolute URLs', () => {
|
||||
expect(isExternalHref('https://', SITE)).toBe(false)
|
||||
})
|
||||
|
||||
it('should fall back to treating every absolute http(s) URL as external without a valid site URL', () => {
|
||||
expect(isExternalHref('https://stage.mozdit.hu', 'not a url')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('externalLinkProps', () => {
|
||||
it('should open external links in a new tab without leaking the opener', () => {
|
||||
expect(externalLinkProps('https://mail.mozdit.hu', SITE)).toEqual({
|
||||
target: '_blank',
|
||||
rel: 'noopener noreferrer',
|
||||
})
|
||||
})
|
||||
|
||||
it('should return no props for internal links', () => {
|
||||
expect(externalLinkProps('/en/contact', SITE)).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('openExternalLinksInNewTab', () => {
|
||||
it('should add target and rel to external anchors in CMS HTML', () => {
|
||||
expect(openExternalLinksInNewTab('Lásd <a href="https://naih.hu">NAIH</a>.', SITE)).toBe(
|
||||
'Lásd <a href="https://naih.hu" target="_blank" rel="noopener noreferrer">NAIH</a>.',
|
||||
)
|
||||
})
|
||||
|
||||
it('should replace an existing target/rel on external anchors', () => {
|
||||
expect(
|
||||
openExternalLinksInNewTab(`<a class="x" target='_self' rel="nofollow" href='https://naih.hu'>N</a>`, SITE),
|
||||
).toBe(`<a class="x" href='https://naih.hu' target="_blank" rel="noopener noreferrer">N</a>`)
|
||||
})
|
||||
|
||||
it('should leave internal anchors, mailto links and other tags untouched', () => {
|
||||
const html =
|
||||
'<p>Az <a href="/hu/adatvedelem" class="underline">adatkezelési tájékoztatót</a>, <a href="mailto:info@mozdit.hu">írjon</a>, <abbr title="x">GDPR</abbr>.</p>'
|
||||
expect(openExternalLinksInNewTab(html, SITE)).toBe(html)
|
||||
})
|
||||
|
||||
it('should handle several anchors in one string', () => {
|
||||
const out = openExternalLinksInNewTab('<a href="https://a.example">A</a> <a href="/hu">B</a> <a href="https://b.example">C</a>', SITE)
|
||||
expect(out.match(/target="_blank"/g)).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* MITHOME-124 — general rule: every external link opens in a new tab.
|
||||
*
|
||||
* "External" = an absolute http(s) or protocol-relative URL whose host is
|
||||
* not the site's own host. Internal paths, anchors, `mailto:` and `tel:`
|
||||
* stay in the same tab.
|
||||
*
|
||||
* DECISION: decided from the URL itself, never from a manual flag — a
|
||||
* per-link "external" switch would allow exceptions to the rule (the old
|
||||
* CTA checkbox and the webmail button drifted apart exactly that way).
|
||||
*/
|
||||
import { siteConfig } from '@/config/site'
|
||||
|
||||
const NEW_TAB_PROPS = { target: '_blank', rel: 'noopener noreferrer' } as const
|
||||
|
||||
type NewTabProps = typeof NEW_TAB_PROPS | Record<string, never>
|
||||
|
||||
function hostOf(url: string): string | undefined {
|
||||
try {
|
||||
return new URL(url).host.toLowerCase()
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function isExternalHref(href: string, siteUrl: string = siteConfig.general.url): boolean {
|
||||
const normalized = href.trim()
|
||||
if (!/^(https?:)?\/\//i.test(normalized)) return false
|
||||
const host = hostOf(normalized.startsWith('//') ? `https:${normalized}` : normalized)
|
||||
if (!host) return false
|
||||
return host !== hostOf(siteUrl)
|
||||
}
|
||||
|
||||
/** Spread onto an `<a>`: `<a href={href} {...externalLinkProps(href)}>`. */
|
||||
export function externalLinkProps(href: string, siteUrl?: string): NewTabProps {
|
||||
return isExternalHref(href, siteUrl) ? NEW_TAB_PROPS : {}
|
||||
}
|
||||
|
||||
const ANCHOR_OPEN_TAG = /<a\b([^>]*)>/gi
|
||||
const HREF_ATTR = /\bhref\s*=\s*(["'])(.*?)\1/i
|
||||
const TARGET_OR_REL_ATTR = /\s+(?:target|rel)\s*=\s*(["']).*?\1/gi
|
||||
|
||||
/**
|
||||
* Applies the rule to CMS-provided HTML (rendered with
|
||||
* dangerouslySetInnerHTML), where JSX props cannot be spread.
|
||||
* TRADEOFF: regex over a full HTML parser — the input is short, admin-
|
||||
* authored markup; an unparseable anchor is left as is (same tab).
|
||||
*/
|
||||
export function openExternalLinksInNewTab(html: string, siteUrl?: string): string {
|
||||
return html.replace(ANCHOR_OPEN_TAG, (tag: string, attrs: string) => {
|
||||
const href = HREF_ATTR.exec(attrs)?.[2]
|
||||
if (href === undefined || !isExternalHref(href, siteUrl)) return tag
|
||||
const cleaned = attrs.replace(TARGET_OR_REL_ATTR, '')
|
||||
return `<a${cleaned} target="${NEW_TAB_PROPS.target}" rel="${NEW_TAB_PROPS.rel}">`
|
||||
})
|
||||
}
|
||||
@@ -172,7 +172,7 @@ describe('Payload globals', () => {
|
||||
function expected(finding: Finding): boolean {
|
||||
if (finding.path.endsWith('(container)')) return false
|
||||
if (finding.path.endsWith('[]')) return true
|
||||
// Checkbox/radio/select (external, linkType, page) are structural.
|
||||
// Checkbox/radio/select (linkType, page) are structural.
|
||||
if (finding.type !== 'text' && finding.type !== 'textarea') return false
|
||||
return !SHARED_TEXT_FIELDS.has(finding.path.split('.').pop()!)
|
||||
}
|
||||
@@ -186,13 +186,14 @@ describe('Payload globals', () => {
|
||||
},
|
||||
)
|
||||
|
||||
it('should localize the CTA URL but share the link type, page and external flag', () => {
|
||||
it('should localize the CTA URL but share the link type and page', () => {
|
||||
const findings = walk(Home.fields as Node[], '', [])
|
||||
const byPath = Object.fromEntries(findings.map((f) => [f.path, f.localized]))
|
||||
expect(byPath['hero.cta.primary.href']).toBe(true)
|
||||
expect(byPath['hero.cta.primary.linkType']).toBe(false)
|
||||
expect(byPath['hero.cta.primary.page']).toBe(false)
|
||||
expect(byPath['hero.cta.primary.external']).toBe(false)
|
||||
// MITHOME-124: no manual new-tab switch — derived from the URL.
|
||||
expect(byPath).not.toHaveProperty('hero.cta.primary.external')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ export interface GeneralConfig {
|
||||
export interface NavigationItem {
|
||||
label: string
|
||||
href: string
|
||||
external?: boolean
|
||||
primary?: boolean
|
||||
}
|
||||
|
||||
@@ -36,7 +35,6 @@ export interface HeroSectionConfig {
|
||||
primary: {
|
||||
text: string
|
||||
href: string
|
||||
external?: boolean
|
||||
}
|
||||
secondary?: {
|
||||
text: string
|
||||
|
||||
Reference in New Issue
Block a user