|
| 1 | +import React, { forwardRef, Fragment } from 'react'; |
| 2 | +import Markdown from 'markdown-to-jsx'; |
| 3 | +import { |
| 4 | + Heading, |
| 5 | + Paragraph, |
| 6 | + Anchor, |
| 7 | + Image, |
| 8 | + Table, |
| 9 | + TableBody, |
| 10 | + TableCell, |
| 11 | + TableFooter, |
| 12 | + TableHeader, |
| 13 | + TableRow, |
| 14 | +} from 'grommet'; |
| 15 | + |
| 16 | +const isObject = (item) => |
| 17 | + item && typeof item === 'object' && !Array.isArray(item); |
| 18 | + |
| 19 | +const deepMerge = (target, ...sources) => { |
| 20 | + if (!sources.length) { |
| 21 | + return target; |
| 22 | + } |
| 23 | + // making sure to not change target (immutable) |
| 24 | + const output = { ...target }; |
| 25 | + sources.forEach((source) => { |
| 26 | + if (isObject(source)) { |
| 27 | + Object.keys(source).forEach((key) => { |
| 28 | + if (isObject(source[key])) { |
| 29 | + if (!output[key]) { |
| 30 | + output[key] = { ...source[key] }; |
| 31 | + } else { |
| 32 | + output[key] = deepMerge(output[key], source[key]); |
| 33 | + } |
| 34 | + } else { |
| 35 | + output[key] = source[key]; |
| 36 | + } |
| 37 | + }); |
| 38 | + } |
| 39 | + }); |
| 40 | + return output; |
| 41 | +}; |
| 42 | + |
| 43 | +const GrommetMarkdown = forwardRef( |
| 44 | + ({ children, components, options, theme, ...rest }, ref) => { |
| 45 | + const heading = [1, 2, 3, 4].reduce((obj, level) => { |
| 46 | + const result = { ...obj }; |
| 47 | + result[`h${level}`] = { |
| 48 | + component: Heading, |
| 49 | + props: { level }, |
| 50 | + }; |
| 51 | + return result; |
| 52 | + }, {}); |
| 53 | + |
| 54 | + const overrides = deepMerge( |
| 55 | + { |
| 56 | + a: { component: Anchor }, |
| 57 | + img: { component: Image }, |
| 58 | + p: { component: Paragraph }, |
| 59 | + table: { component: Table }, |
| 60 | + td: { component: TableCell, props: { plain: true } }, |
| 61 | + tbody: { component: TableBody }, |
| 62 | + tfoot: { component: TableFooter }, |
| 63 | + th: { component: TableCell }, |
| 64 | + thead: { component: TableHeader }, |
| 65 | + tr: { component: TableRow }, |
| 66 | + }, |
| 67 | + heading, |
| 68 | + components, |
| 69 | + options && options.overrides, |
| 70 | + ); |
| 71 | + |
| 72 | + // we use Fragment as the wrapper so we can assign the ref with the div |
| 73 | + // wrapper can still be overridden with the options. |
| 74 | + return ( |
| 75 | + <div ref={ref} {...rest}> |
| 76 | + <Markdown |
| 77 | + {...{ children }} |
| 78 | + options={{ wrapper: Fragment, ...options, overrides }} |
| 79 | + /> |
| 80 | + </div> |
| 81 | + ); |
| 82 | + }, |
| 83 | +); |
| 84 | + |
| 85 | +export { GrommetMarkdown }; |
0 commit comments