Forráskód Böngészése

+toReact, +react from CDN, +test render

Ivan Asmer 4 éve
szülő
commit
811cdaf0cb
1 módosított fájl, 53 hozzáadás és 0 törlés
  1. 53 0
      index.js

+ 53 - 0
index.js

@@ -521,6 +521,59 @@ function buildAST(md, mdTags=syntax, offset=0, tree={tag: 'root'}, stack=[]){
     return currentNode
 }
 
+const Heading = ({react:React, children, title, node: {tag}}) => {
+    const level = +tag.slice(-1)
+    const _ = React.createElement.bind(React)
+    if (isNaN(level)) throw new SyntaxError('wrong heading name')
+    return _(React.Fragment, null, 
+                _(`h${level}`, null, ...title),
+                _(`div`, null, ...children)
+            )
+}
+
+const defaultMapMDToComponents = {
+    heading1: Heading,
+    heading2: Heading,
+    heading3: Heading,
+    heading4: Heading,
+    heading5: Heading,
+    heading6: Heading,
+    bold1: "strong",
+    bold2: "strong",
+    italic1: "i",
+    italic2: "i",
+    unOrderedList: 'ul',
+    orderedList: 'ol',
+    unOrderedListItem: 'li',
+    orderedListItem: 'li',
+    code: 'code',
+    codeMultiLine: 'pre',
+    codeLanguage: 'pre',
+    root: ""
+}
+
+function toReact(ast, React, mapMDToComponents=defaultMapMDToComponents){
+    const gC = (tag, c) => (c = mapMDToComponents[tag]) ? c : (c === "" ? React.Fragment : "span")
+    const RenderComponent = gC(ast.tag)
+    const _ = React.createElement.bind(React)
+    const childToReact = child => typeof child === 'string' ?  child  : 
+                                                               toReact(child, React, mapMDToComponents)
+    return _(RenderComponent, {node: ast, 
+                                key: Math.random(),
+                               children: ast.children.map(childToReact),
+                               title: ast.title && ast.title.map(childToReact),
+                               react: React})
+}
+
+window.module && (module.exports = {
+    buildAST,
+    toReact
+})
+
+console.log(Object.keys(syntax))
+
+
+
 //const md = 
 //`
 //# heading1