diff --git a/cypress/components/Headlines.cy.tsx b/cypress/components/Headlines.cy.tsx index 2fd627b5d..dfa1a450a 100644 --- a/cypress/components/Headlines.cy.tsx +++ b/cypress/components/Headlines.cy.tsx @@ -6,6 +6,7 @@ import { Headline4, } from '~/components/Headlines'; import mockNextRouter, { MockRouter } from '../plugins/mockNextRouterUtils'; +import slugifyMarkdownHeadline from '~/lib/slugifyMarkdownHeadline'; describe('Headlines Component', () => { let mockRouter: MockRouter; @@ -94,11 +95,14 @@ describe('Headlines Component', () => { it('should be active if the URL has the hash', () => { /* Testing the active headline with Headline1 */ - // Set the URL with the hash - mockRouter.asPath = '/#what-is-json-schema'; + const title = 'What is JSON Schema?'; + const slug = slugifyMarkdownHeadline(title); + + // Update the existing mock router's properties + mockRouter.asPath = `/#${slug}`; // Check if Correct headline is active - cy.mount(What is JSON Schema?); + cy.mount({title}); cy.get('span').should( 'have.class', 'text-startBlue dark:text-endBlue inline-block ml-2', diff --git a/lib/slugifyMarkdownHeadline.ts b/lib/slugifyMarkdownHeadline.ts index ae943e138..14b796b2d 100644 --- a/lib/slugifyMarkdownHeadline.ts +++ b/lib/slugifyMarkdownHeadline.ts @@ -4,23 +4,42 @@ export default function slugifyMarkdownHeadline( markdownChildren: string | any[], ): string { const FRAGMENT_REGEX = /\[#(?(\w|-|_)*)\]/g; + if (!markdownChildren) return ''; + if (typeof markdownChildren === 'string') - return slugify(markdownChildren, { lower: true, trim: true }); + return slugify(markdownChildren, { + lower: true, + trim: true, + remove: /[*+~()'"!]/g, + }); + const metaSlug = markdownChildren.reduce((acc, child) => { if (acc) return acc; + if (typeof child !== 'string') return null; + const fragment = FRAGMENT_REGEX.exec(child); + if (!fragment) return null; + const slug = fragment?.groups?.slug; + return slug || null; }, null); + if (metaSlug) return metaSlug; const joinedChildren = markdownChildren .filter((child) => typeof child === 'string') .map((string) => string.replace(FRAGMENT_REGEX, '')) .join(' '); - const slug = slugify(joinedChildren, { lower: true, trim: true }); + + const slug = slugify(joinedChildren, { + lower: true, + trim: true, + remove: /[*+~()'"!]/g, + }); + return slug; }