Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
10 changes: 7 additions & 3 deletions cypress/components/Headlines.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(<Headline1>What is JSON Schema?</Headline1>);
cy.mount(<Headline1>{title}</Headline1>);
cy.get('span').should(
'have.class',
'text-startBlue dark:text-endBlue inline-block ml-2',
Expand Down
30 changes: 28 additions & 2 deletions lib/slugifyMarkdownHeadline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,49 @@ export default function slugifyMarkdownHeadline(
markdownChildren: string | any[],
): string {
const FRAGMENT_REGEX = /\[#(?<slug>(\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;
}