|
1 | 1 | import { MDXLink } from '@/components/MDXComponents';
|
| 2 | +import { View } from '@aws-amplify/ui-react'; |
2 | 3 |
|
3 | 4 | type stringOrJSXArray = (string | JSX.Element)[];
|
4 | 5 |
|
| 6 | +export const parseMarkdown = (input: stringOrJSXArray): stringOrJSXArray => { |
| 7 | + const lineBreaks: stringOrJSXArray = []; |
| 8 | + const result: stringOrJSXArray = []; |
| 9 | + |
| 10 | + // look for line breaks and wrap them in a line-break View |
| 11 | + function parseLineBreak(inputString) { |
| 12 | + if (typeof inputString === 'string' && inputString.indexOf('\n\n') !== -1) { |
| 13 | + const parts = inputString.split('\n\n'); |
| 14 | + parts.forEach((part, idx) => { |
| 15 | + if (idx < parts.length - 1) { |
| 16 | + lineBreaks.push( |
| 17 | + <View className="line-break" marginBottom="1rem"> |
| 18 | + {part} |
| 19 | + </View> |
| 20 | + ); |
| 21 | + } else { |
| 22 | + lineBreaks.push(part); |
| 23 | + } |
| 24 | + }); |
| 25 | + } else { |
| 26 | + lineBreaks.push(inputString); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + // iterate over the array looking at each item for strings that contain \n\n and replace with line breaks |
| 31 | + input.forEach((item) => { |
| 32 | + if (Array.isArray(item)) { |
| 33 | + item.forEach((val) => { |
| 34 | + parseLineBreak(val); |
| 35 | + }); |
| 36 | + } else { |
| 37 | + parseLineBreak(item); |
| 38 | + } |
| 39 | + }); |
| 40 | + |
| 41 | + // look for \n- which indicates a list and create a list starting with the first \n- |
| 42 | + for (let i = 0; i < lineBreaks.length; i++) { |
| 43 | + const current = lineBreaks[i]; |
| 44 | + if (typeof current === 'string' && current.indexOf('\n-') !== -1) { |
| 45 | + const parts = current.split('\n-'); |
| 46 | + result.push(parts[0]); |
| 47 | + const listItems: JSX.Element[] = []; |
| 48 | + for (let x = 1; x < parts.length; x++) { |
| 49 | + if (x < parts.length - 1) { |
| 50 | + // not the last item in the list, add as a list item |
| 51 | + listItems.push(<li>{parts[x]}</li>); |
| 52 | + } else { |
| 53 | + // last item in the parts list need to continue iterating through lineBreaks to look for other list item indicators |
| 54 | + const currentParts: stringOrJSXArray = [parts[x]]; |
| 55 | + for (let y = i + 1; y < lineBreaks.length; y++) { |
| 56 | + currentParts.push(lineBreaks[y]); |
| 57 | + } |
| 58 | + listItems.push(<li>{currentParts}</li>); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + const unorderedList = <ul>{listItems}</ul>; |
| 63 | + result.push(unorderedList); |
| 64 | + break; |
| 65 | + } else { |
| 66 | + result.push(current); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return result; |
| 71 | +}; |
| 72 | + |
5 | 73 | export const parseMarkdownLinks = (inputString: string): stringOrJSXArray => {
|
6 | 74 | const result: stringOrJSXArray = [];
|
7 | 75 | if (!inputString) return result;
|
|
0 commit comments