/ src / lib / utils / post-utils.ts
post-utils.ts
 1  export function hashStringToColor(str: string): string {
 2    if (!str) {
 3      return '';
 4    }
 5  
 6    let hash = 0;
 7    for (let i = 0; i < str.length; i++) {
 8      hash = str.charCodeAt(i) + ((hash << 5) - hash);
 9    }
10  
11    const r = (hash >> 24) & 0xff;
12    const g = (hash >> 16) & 0xff;
13    const b = (hash >> 8) & 0xff;
14  
15    return `rgb(${r}, ${g}, ${b})`;
16  }
17  
18  export function getTextColorForBackground(rgb: string): string {
19    const [r, g, b] = rgb.match(/\d+/g)?.map(Number) || [0, 0, 0];
20    const brightness = r * 0.299 + g * 0.587 + b * 0.114;
21    return brightness > 125 ? 'black' : 'white';
22  }
23  
24  export const formatMarkdown = (content: string): string => {
25    let md = content;
26    if (md) {
27      // Check if the content already contains valid Markdown patterns
28      const alreadyFormattedPattern = /\n&nbsp;\n/;
29  
30      // help the user by formatting the content if it's not already formatted
31      if (!alreadyFormattedPattern.test(md)) {
32        // Replace single newline with "/n&nbsp;/n" if followed by a newline
33        md = md.replace(/\n(?=\n)/g, '\n&nbsp;\n');
34        // Replace single newline with double newline if between two characters
35        md = md.replace(/\n(?=\S)/g, '\n\n');
36      }
37    }
38    return md;
39  };
40  
41  export function removeMarkdown(md: string): string {
42    return md
43      .replace(/\[([^\]]*?)][[(].*?[)\]]/g, '$1') // Remove links
44      .replace(/[*_~`]/g, '') // Remove emphasis and code markers
45      .replace(/^#+\s*(.+)$/gm, '$1') // Remove headers
46      .replace(/^\s*[-*+]\s+/gm, '') // Remove list markers
47      .replace(/^\s*>\s+/gm, '') // Remove blockquotes
48      .replace(/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/g, '') // Remove reference-style links
49      .replace(/^(\n)?\s{0,}#{1,6}\s*( (.+))? +#+$|^(\n)?\s{0,}#{1,6}\s*( (.+))?$/gm, '$1$3$4$6') // Remove atx-style headers
50      .replace(/([*]+)(\S)(.*?\S)?\1/g, '$2$3') // Remove * emphasis
51      .replace(/(^|\W)([_]+)(\S)(.*?\S)??\2($|\W)/g, '$1$3$4$5') // Remove _ emphasis
52      .replace(/(`{3,})(.*?)\1/gm, '$2') // Remove code blocks
53      .replace(/`(.+?)`/g, '$1') // Remove inline code
54      .replace(/~(.*?)~/g, '$1') // Remove strike through
55      .trim();
56  }