Adds reusably utility for fetching parsing yml and md

This commit is contained in:
Alicia Sykes 2024-02-17 16:44:02 +00:00
parent 5def0fe53f
commit c57efee823
2 changed files with 56 additions and 0 deletions

View file

@ -0,0 +1,15 @@
import yaml from 'js-yaml';
import type { AwesomePrivacy, Section, Service } from '../types/Service';
export const fetchData = async (): Promise<AwesomePrivacy> => {
return await fetch('http://localhost:4321/awesome-privacy.yml')
.then((res) => res.text())
.then((data) => yaml.load(data))
.catch((err) => console.error(err)) as AwesomePrivacy;
}
export const slugify = (title: string) => {
return title.toLowerCase().replace(/\s/g, '-');
};

View file

@ -0,0 +1,41 @@
import { marked } from 'marked';
export const parseMarkdown = (text: string | undefined): string => {
if (!text) return '';
// Custom renderer
const renderer = new marked.Renderer();
// Override function to handle headings
renderer.heading = (text, level) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
return `<h${level} id="${escapedText}">${text}</h${level}>`;
};
// Override function to handle links
renderer.link = (href, title, text) => {
if (href.startsWith('/')) {
href = `https://github.com/Lissy93/personal-security-checklist/blob/old-version/${href}`;
}
title = title ? `title="${title}"` : '';
return `<a href="${href}" ${title} target="_blank" rel="noopener noreferrer">${text}</a>`;
};
// Sanitize the input to remove <script> tags
const sanitizeHtml = (html: string): string => {
return html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
};
// Configure marked with the custom renderer
marked.use({ renderer });
// Parse the markdown, then sanitize the HTML to remove <script> tags
const rawHtml = marked.parse(text, { async: false}) as string;
const sanitizedHtml = sanitizeHtml(rawHtml);
return sanitizedHtml;
};
export const formatLink = (link: string) => {
return (link || '').replace(/^(https?:\/\/)?(www\.)?/, '').replace(/\/+$/, '');
};